Debian Codegraph @

pkg/networkmanager/interfaces.js

raw
1 /*
2 * Copyright (C) 2013 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5 import React from "react";
6 import cockpit from 'cockpit';
7
8 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
9
10 import { fmt_to_fragments } from 'utils.jsx';
11 import * as utils from './utils.js';
12 import { v4 as uuidv4 } from 'uuid';
13
14 import "./networking.scss";
15
16 import { show_modal_dialog } from "cockpit-components-dialog.jsx";
17
18 const _ = cockpit.gettext;
19
20 export function show_error_dialog(title, message) {
21 const props = {
22 id: "error-popup",
23 title,
24 body: <p>{message}</p>
25 };
26
27 const footer = {
28 actions: [],
29 cancel_button: { text: _("Close"), variant: "secondary" }
30 };
31
32 show_modal_dialog(props, footer);
33 }
34
35 export function show_unexpected_error(error) {
36 show_error_dialog(_("Unexpected error"), error.message || error);
37 }
38
39 function show_breaking_change_dialog({ fail_text, anyway_text, action }) {
40 const props = {
41 titleIconVariant: "warning",
42 id: "confirm-breaking-change-popup",
43 title: _("Connection will be lost"),
44 body: <p>{fail_text}</p>
45 };
46
47 const footer = {
48 actions: [
49 {
50 caption: anyway_text,
51 clicked: action,
52 style: "danger",
53 }
54 ],
55 cancel_button: { text: _("Keep connection"), variant: "secondary" }
56 };
57
58 show_modal_dialog(props, footer);
59 }
60
61 export function connection_settings(c) {
62 if (c && c.Settings && c.Settings.connection) {
63 return c.Settings.connection;
64 } else {
65 // It is a programming error if we ever access a Connection
66 // object that doesn't have it's settings yet, and we expect
67 // each Connection object to have "connection" settings.
68 console.warn("Incomplete 'Connection' object accessed", c);
69 return { };
70 }
71 }
72
73 /* NetworkManagerModel
74 *
75 * The NetworkManager model maintains a mostly-read-only data
76 * structure that represents the state of the NetworkManager service
77 * on a given machine.
78 *
79 * The data structure consists of JavaScript values such as objects,
80 * arrays, and strings that point at each other. It might have
81 * cycles. In general, it follows the NetworkManager D-Bus API but
82 * tries to hide annoyances such as endian issues.
83 *
84 * For example,
85 *
86 * const manager = model.get_manager();
87 * manager.Devices[0].ActiveConnection.Ipv4Config.Addresses[0][0]
88 *
89 * is the first IPv4 address of the first device as a string.
90 *
91 * The model initializes itself asynchronously and emits the 'changed'
92 * event whenever anything changes. If you only access the data
93 * structure from within the 'changed' event handler, you should
94 * always see it in a complete state.
95 *
96 * In other words, any change in the data structure from one 'changed'
97 * event to the next represents a real change in the state of
98 * NetworkManager.
99 *
100 * When a new model is created, its main 'manager' object starts out
101 * as 'null'. The first 'changed' event signals that initialization
102 * is complete and that the whole data structure is now stable and
103 * reachable from the 'manager' object.
104 *
105 * Methods are invoked directly on the objects in the data structure.
106 * For example,
107 *
108 * manager.Devices[0].disconnect();
109 * manager.Devices[0].ActiveConnection.deactivate();
110 *
111 * TODO - document the details of the data structure.
112 */
113
114 /* HACK
115 *
116 * NetworkManager used to not implement the standard o.fd.DBus.Properties
117 * interface and our code still operates under the assumptions stated below.
118 *
119 * 1) NM does not emit the PropertiesChanged signal on the
120 * o.fd.DBus.Properties interface but rather on its own interfaces
121 * like o.fd.NetworkManager.Device.Wired.
122 *
123 * 2) NM does not always emit the PropertiesChanged signal on the
124 * interface whose properties have changed. For example, when a
125 * property on o.fd.NM.Device changes, this might be notified by a
126 * PropertiesChanged signal on the o.fd.NM.Device.Wired interface
127 * for the same object path.
128 *
129 * https://bugzilla.gnome.org/show_bug.cgi?id=729826
130 *
131 * We cope with this here by merging all properties of all interfaces
132 * for a given object path. This is appropriate and nice for
133 * NetworkManager, and we should probably keep it that way even if
134 * NetworkManager would use a standard o.fd.DBus.Properties API.
135 * In the future this could be rewritten to use DBusProxies.
136 */
137
138 export function NetworkManagerModel() {
139 /*
140 * The NetworkManager model doesn't need proxies in its DBus client.
141 * It uses the 'raw' dbus events and methods and constructs its own data
142 * structure. This has the advantage of avoiding wasting
143 * resources for maintaining the unused proxies, avoids some code
144 * complexity, and allows to do the right thing with the
145 * peculiarities of the NetworkManager API.
146 */
147
148 const self = this;
149 cockpit.event_target(self);
150
151 const client = cockpit.dbus("org.freedesktop.NetworkManager", { superuser: "try" });
152 self.client = client;
153
154 // set to false by default as newer API is backwards compatible
155 // and supports both "dns" and "dns-data" properties
156 // dns-data property was added in version 1.42.0
157 self.supports_dns_data = false;
158
159 function check_version_dns_data_support(version) {
160 if (version.length < 2) {
161 return false;
162 }
163
164 if (version[0] > 1) {
165 return true;
166 } else if (version[0] === 1 && version[1] >= 42) {
167 return true;
168 }
169
170 return false;
171 }
172
173 /* resolved once first stage of initialization is done */
174 self.preinit = new Promise((resolve, reject) => {
175 client.call("/org/freedesktop/NetworkManager",
176 "org.freedesktop.DBus.Properties", "Get",
177 ["org.freedesktop.NetworkManager", "Version"], { flags: "" })
178 .then((reply, options) => {
179 const nm_version = reply[0].v.split(".").map(n => Number.parseInt(n));
180 self.supports_dns_data = check_version_dns_data_support(nm_version);
181
182 if (options.flags) {
183 if (options.flags.indexOf(">") !== -1)
184 utils.set_byteorder("be");
185 else if (options.flags.indexOf("<") !== -1)
186 utils.set_byteorder("le");
187 resolve();
188 }
189 })
190 .catch(complain);
191 });
192
193 /* Mostly generic D-Bus stuff. */
194
195 const objects = { };
196
197 self.set_curtain = (state) => {
198 self.curtain = state;
199 self.dispatchEvent("changed");
200 };
201
202 /* This is a test helper so that we wait for operations to finish before moving forward with the test */
203 self.set_operation_in_progress = (value) => {
204 self.operationInProgress = value;
205 self.dispatchEvent("changed");
206 };
207
208 function complain() {
209 self.ready = false;
210 console.warn.apply(console, arguments);
211 }
212
213 function conv_Object(type) {
214 return function (path) {
215 return get_object(path, type);
216 };
217 }
218
219 function conv_Array(conv) {
220 return function (elts) {
221 return elts.map(conv);
222 };
223 }
224
225 function priv(obj) {
226 return obj[' priv'];
227 }
228
229 let outstanding_refreshes = 0;
230
231 function push_refresh() {
232 outstanding_refreshes += 1;
233 }
234
235 function pop_refresh() {
236 outstanding_refreshes -= 1;
237 if (outstanding_refreshes === 0)
238 export_model();
239 }
240
241 function get_object(path, type) {
242 if (path == "/")
243 return null;
244 function Constructor() {
245 this[' priv'] = { };
246 priv(this).type = type;
247 priv(this).path = path;
248 for (const p in type.props)
249 this[p] = type.props[p].def;
250 }
251 if (!objects[path]) {
252 Constructor.prototype = type.prototype;
253 objects[path] = new Constructor();
254 if (type.refresh)
255 type.refresh(objects[path]);
256 if (type.exporters && type.exporters[0])
257 type.exporters[0](objects[path]);
258 }
259 return objects[path];
260 }
261
262 function peek_object(path) {
263 return objects[path] || null;
264 }
265
266 function drop_object(path) {
267 const obj = objects[path];
268 if (obj) {
269 if (priv(obj).type.drop)
270 priv(obj).type.drop(obj);
271 delete objects[path];
272 export_model();
273 }
274 }
275
276 function set_object_properties(obj, props) {
277 const decl = priv(obj).type.props;
278 for (const p in decl) {
279 let val = props[decl[p].prop || p];
280 if (val !== undefined) {
281 if (decl[p].conv)
282 val = decl[p].conv(val);
283 if (val !== obj[p]) {
284 obj[p] = val;
285 if (decl[p].trigger)
286 decl[p].trigger(obj);
287 }
288 }
289 }
290 }
291
292 function remove_signatures(props_with_sigs) {
293 const props = { };
294 for (const p in props_with_sigs) {
295 if (props_with_sigs[p]) {
296 props[p] = props_with_sigs[p].v;
297 }
298 }
299 return props;
300 }
301
302 function objpath(obj) {
303 if (obj && priv(obj).path)
304 return priv(obj).path;
305 else
306 return "/";
307 }
308
309 function call_object_method(obj, iface, method) {
310 return client.call(objpath(obj), iface, method, Array.prototype.slice.call(arguments, 3));
311 }
312
313 const interface_types = { };
314 let max_export_phases = 0;
315 let export_pending;
316
317 function set_object_types(all_types) {
318 all_types.forEach(function (type) {
319 if (type.exporters && type.exporters.length > max_export_phases)
320 max_export_phases = type.exporters.length;
321 type.interfaces.forEach(function (iface) {
322 interface_types[iface] = type;
323 });
324 });
325 }
326
327 function signal_emitted(path, iface, signal, args) {
328 const obj = peek_object(path);
329
330 if (obj) {
331 const type = priv(obj).type;
332
333 if (signal == "PropertiesChanged") {
334 push_refresh();
335 const props = remove_signatures(args[0]);
336 set_object_properties(obj, props);
337 pop_refresh();
338 } else if (type.signals && type.signals[signal])
339 type.signals[signal](obj, args);
340 }
341 }
342
343 function interface_properties(path, iface, props) {
344 const type = interface_types[iface];
345 if (type)
346 set_object_properties(get_object(path, type), props);
347 }
348
349 function interface_removed(path, iface) {
350 /* For NetworkManager we can make this assumption */
351 drop_object(path);
352 }
353
354 let export_model_promise = null;
355 let export_model_promise_resolve = null;
356
357 function export_model() {
358 function doit() {
359 for (let phase = 0; phase < max_export_phases; phase++) {
360 for (const path in objects) {
361 const obj = objects[path];
362 const exp = priv(obj).type.exporters;
363 if (exp && exp[phase])
364 exp[phase](obj);
365 }
366 }
367
368 self.ready = true;
369 self.dispatchEvent('changed');
370 if (export_model_promise) {
371 export_model_promise_resolve();
372 export_model_promise = null;
373 export_model_promise_resolve = null;
374 }
375 }
376
377 if (!export_pending) {
378 export_pending = true;
379 window.setTimeout(function () { export_pending = false; doit() }, 300);
380 }
381 }
382
383 self.synchronize = function synchronize() {
384 if (outstanding_refreshes === 0) {
385 return Promise.resolve();
386 } else {
387 if (!export_model_promise)
388 export_model_promise = new Promise(resolve => { export_model_promise_resolve = resolve });
389 return export_model_promise;
390 }
391 };
392
393 let subscription;
394 let watch;
395
396 function onNotifyEventHandler(event, data) {
397 Object.keys(data).forEach(path => {
398 const interfaces = data[path];
399
400 Object.keys(interfaces).forEach(iface => {
401 const props = interfaces[iface];
402
403 /* Capture connection failure reasons for devices
404 NM transitions through PREPARE → CONFIG → NEED_AUTH → FAILED → DISCONNECTED very
405 quickly, and React batches these updates, so the UI often misses the FAILED state.
406 Store the failure reason here at the D-Bus event level so we can retrieve it later. */
407 if (path.includes("/Devices/") && props?.StateReason) {
408 const obj = peek_object(path);
409 if (obj) {
410 const [state, reason] = props.StateReason;
411 if (state === 120 && reason !== 0) {
412 utils.debug("Captured", obj.Interface, "failure, reason:", reason);
413 priv(obj).lastFailureReason = reason;
414 }
415 }
416 }
417
418 if (props)
419 interface_properties(path, iface, props);
420 else
421 interface_removed(path, iface);
422 });
423 });
424 }
425
426 self.preinit.then(() => {
427 subscription = client.subscribe({ }, signal_emitted);
428 client.addEventListener("notify", onNotifyEventHandler);
429 watch = client.watch({ path_namespace: "/org/freedesktop" });
430 client.addEventListener("owner", (event, owner) => {
431 if (owner) {
432 watch.remove();
433 watch = client.watch({ path_namespace: "/org/freedesktop" });
434 }
435 });
436 });
437
438 self.close = function close() {
439 subscription.remove();
440 watch.remove();
441 client.removeEventListener("notify", onNotifyEventHandler);
442 client.close("unused");
443 };
444
445 /* NetworkManager specific data conversions and utility functions.
446 */
447
448 function ip_address_from_nm(addr) {
449 return {
450 address: addr.address.v,
451 prefix: utils.ip_prefix_to_text(addr.prefix.v)
452 };
453 }
454
455 function ip_address_to_nm(addr, ipv) {
456 const prefix = ipv === "ipv4" ? utils.ip4_prefix_from_text(addr.prefix) : utils.ip_prefix_from_text(addr.prefix);
457
458 if (!utils.validate_ip(addr.address)) {
459 throw cockpit.format(_("Invalid IP address: $0"), addr.address);
460 }
461
462 return {
463 address: { t: "s", v: addr.address },
464 prefix: { t: "u", v: prefix },
465 };
466 }
467
468 function route_from_nm(route) {
469 const metric = route.metric ? utils.ip_metric_to_text(route.metric.v) : "";
470 return {
471 dest: route.dest.v,
472 prefix: utils.ip_prefix_to_text(route.prefix.v),
473 next_hop: route["next-hop"]?.v ?? "",
474 metric,
475 };
476 }
477
478 function route_to_nm(route, ipv) {
479 const prefix = ipv === "ipv4" ? utils.ip4_prefix_from_text(route.prefix) : utils.ip_prefix_from_text(route.prefix);
480
481 if (!utils.validate_ip(route.dest)) {
482 throw cockpit.format(_("Invalid destination address: $0"), route.dest);
483 }
484
485 const route_nm = {
486 dest: { t: "s", v: route.dest },
487 prefix: { t: "u", v: prefix },
488 };
489
490 // next-hop is an optional property
491 if (route.next_hop !== "") {
492 if (!utils.validate_ip(route.next_hop)) {
493 throw cockpit.format(_("Invalid gateway address: $0"), route.next_hop);
494 }
495
496 route_nm["next-hop"] = { t: "s", v: route.next_hop };
497 }
498
499 // metric is an optional property
500 if (route.metric !== "") {
501 route_nm.metric = { t: "u", v: utils.ip_metric_from_text(route.metric) };
502 }
503
504 return route_nm;
505 }
506
507 function settings_from_nm(settings) {
508 function get(first, second, def) {
509 if (settings[first] && settings[first][second])
510 return settings[first][second].v;
511 else
512 return def;
513 }
514
515 function get_ip(first, ip_to_text) {
516 const dns_data = self.supports_dns_data
517 ? get(first, "dns-data", [])
518 : get(first, "dns", []).map(ip_to_text);
519
520 return {
521 method: get(first, "method", "auto"),
522 ignore_auto_dns: get(first, "ignore-auto-dns", false),
523 ignore_auto_routes: get(first, "ignore-auto-routes", false),
524 address_data: get(first, "address-data", []).map(ip_address_from_nm),
525 gateway: get(first, "gateway", ""),
526 dns_data,
527 dns_search: get(first, "dns-search", []),
528 route_data: get(first, "route-data", []).map(route_from_nm),
529 };
530 }
531
532 const result = {
533 connection: {
534 type: get("connection", "type"),
535 uuid: get("connection", "uuid"),
536 interface_name: get("connection", "interface-name"),
537 timestamp: get("connection", "timestamp", 0),
538 id: get("connection", "id", _("Unknown")),
539 autoconnect: get("connection", "autoconnect", true),
540 autoconnect_priority: get("connection", "autoconnect-priority", 0),
541 autoconnect_members:
542 get("connection", "autoconnect-slaves", -1),
543 member_type: get("connection", "slave-type"),
544 group: get("connection", "master"),
545 multi_connect: get("connection", "multi-connect"),
546 }
547 };
548
549 if (!settings.connection.master) {
550 result.ipv4 = get_ip("ipv4", utils.ip4_to_text);
551 result.ipv6 = get_ip("ipv6", utils.ip6_to_text);
552 }
553
554 if (settings["802-3-ethernet"]) {
555 result.ethernet = {
556 mtu: get("802-3-ethernet", "mtu"),
557 assigned_mac_address: get("802-3-ethernet", "assigned-mac-address")
558 };
559 }
560
561 if (settings.bond) {
562 /* Options are documented as part of the Linux bonding driver.
563 https://www.kernel.org/doc/Documentation/networking/bonding.txt
564 */
565 result.bond = {
566 options: { ...get("bond", "options", { }) },
567 interface_name: get("bond", "interface-name")
568 };
569 }
570
571 function JSON_parse_carefully(str) {
572 try {
573 return JSON.parse(str);
574 } catch (e) {
575 return null;
576 }
577 }
578
579 if (settings.team) {
580 result.team = {
581 config: JSON_parse_carefully(get("team", "config", "{}")),
582 interface_name: get("team", "interface-name")
583 };
584 }
585
586 if (settings["team-port"] || result.connection.member_type == "team") {
587 result.team_port = { config: JSON_parse_carefully(get("team-port", "config", "{}")), };
588 }
589
590 if (settings.bridge) {
591 result.bridge = {
592 interface_name: get("bridge", "interface-name"),
593 stp: get("bridge", "stp", true),
594 priority: get("bridge", "priority", 32768),
595 forward_delay: get("bridge", "forward-delay", 15),
596 hello_time: get("bridge", "hello-time", 2),
597 max_age: get("bridge", "max-age", 20),
598 ageing_time: get("bridge", "ageing-time", 300)
599 };
600 }
601
602 if (settings["bridge-port"] || result.connection.member_type == "bridge") {
603 result.bridge_port = {
604 priority: get("bridge-port", "priority", 32),
605 path_cost: get("bridge-port", "path-cost", 100),
606 hairpin_mode: get("bridge-port", "hairpin-mode", false)
607 };
608 }
609
610 if (settings.vlan) {
611 result.vlan = {
612 parent: get("vlan", "parent"),
613 id: get("vlan", "id"),
614 interface_name: get("vlan", "interface-name")
615 };
616 }
617
618 if (settings.wireguard) {
619 result.wireguard = {
620 listen_port: get("wireguard", "listen-port", 0),
621 peers: get("wireguard", "peers", []).map(peer => ({
622 publicKey: peer['public-key'].v,
623 endpoint: peer.endpoint?.v, // endpoint of a peer is optional
624 allowedIps: peer['allowed-ips']?.v
625 })),
626 };
627 }
628
629 if (settings["802-11-wireless"]) {
630 result["802-11-wireless"] = {
631 ssid: get("802-11-wireless", "ssid"),
632 mode: get("802-11-wireless", "mode"),
633 };
634 }
635
636 return result;
637 }
638
639 function settings_to_nm(settings, orig) {
640 const result = JSON.parse(JSON.stringify(orig || { }));
641
642 function set(first, second, sig, val, def) {
643 if (val === undefined)
644 val = def;
645 if (!result[first])
646 result[first] = { };
647 if (val !== undefined)
648 result[first][second] = cockpit.variant(sig, val);
649 else
650 delete result[first][second];
651 }
652
653 function set_ip(first, dns_ip_sig, ip_from_text) {
654 set(first, "method", 's', settings[first].method);
655 set(first, "ignore-auto-dns", 'b', settings[first].ignore_auto_dns);
656 set(first, "ignore-auto-routes", 'b', settings[first].ignore_auto_routes);
657 set(first, "addr-gen-mode", 'i', settings[first].addr_gen_mode);
658
659 const addresses = settings[first].address_data;
660 if (addresses)
661 set(first, "address-data", "aa{sv}", addresses.map(addr => ip_address_to_nm(addr, first)));
662
663 const gateway = settings[first].gateway;
664 if (gateway && addresses.length > 0) {
665 if (!utils.validate_ip(gateway)) {
666 throw cockpit.format(_("Invalid gateway address: $0"), gateway);
667 }
668 set(first, "gateway", "s", gateway);
669 } else {
670 // gateway cannot be set if there are no addresses
671 delete result[first].gateway;
672 }
673
674 const dns = settings[first].dns_data;
675 if (dns) {
676 const invalid = dns.find(addr => !utils.validate_ip(addr));
677 if (invalid) {
678 throw cockpit.format(_("Invalid DNS address: $0"), invalid);
679 }
680
681 if (self.supports_dns_data) {
682 set(first, "dns-data", "as", dns);
683 } else {
684 set(first, "dns", dns_ip_sig, dns.map(addr => ip_from_text(addr)));
685 }
686 }
687
688 set(first, "dns-search", 'as', settings[first].dns_search);
689
690 const routes = settings[first].route_data;
691 if (routes)
692 set(first, "route-data", "aa{sv}", routes.map(route => route_to_nm(route, first)));
693
694 // Never pass "address-labels" back to NetworkManager. It
695 // is documented as "internal only", but needs to somehow
696 // stay in sync with "addresses". By not passing it back
697 // we don't have to worry about that.
698 //
699 delete result[first]["address-labels"];
700
701 // Never pass "addresses", instead use "address-data" + "gateway"
702 delete result[first].addresses;
703 // Never pass "routes", instead use "route-data"
704 delete result[first].routes;
705 // Never pass "dns" if "dns-data" is supported
706 if (self.supports_dns_data)
707 delete result[first].dns;
708 }
709
710 set("connection", "id", 's', settings.connection.id);
711 set("connection", "autoconnect", 'b', settings.connection.autoconnect);
712 set("connection", "autoconnect-priority", 'i', settings.connection.autoconnect_priority);
713 set("connection", "autoconnect-slaves", 'i', settings.connection.autoconnect_members);
714 set("connection", "uuid", 's', settings.connection.uuid);
715 set("connection", "interface-name", 's', settings.connection.interface_name);
716 set("connection", "type", 's', settings.connection.type);
717 set("connection", "slave-type", 's', settings.connection.member_type);
718 set("connection", "master", 's', settings.connection.group);
719 set("connection", "multi-connect", 'i', settings.connection.multi_connect);
720
721 if (settings.ipv4)
722 set_ip("ipv4", 'au', utils.ip4_from_text);
723 else
724 delete result.ipv4;
725
726 if (settings.ipv6)
727 set_ip("ipv6", 'aay', utils.ip6_from_text);
728 else
729 delete result.ipv6;
730
731 if (settings.bond) {
732 set("bond", "options", 'a{ss}', settings.bond.options);
733 set("bond", "interface-name", 's', settings.bond.interface_name);
734 } else
735 delete result.bond;
736
737 if (settings.team) {
738 set("team", "config", 's', JSON.stringify(settings.team.config));
739 set("team", "interface-name", 's', settings.team.interface_name);
740 } else
741 delete result.team;
742
743 if (settings.team_port)
744 set("team-port", "config", 's', JSON.stringify(settings.team_port.config));
745 else
746 delete result["team-port"];
747
748 if (settings.bridge) {
749 set("bridge", "interface-name", 's', settings.bridge.interface_name);
750 set("bridge", "stp", 'b', settings.bridge.stp);
751 set("bridge", "priority", 'u', settings.bridge.priority);
752 set("bridge", "forward-delay", 'u', settings.bridge.forward_delay);
753 set("bridge", "hello-time", 'u', settings.bridge.hello_time);
754 set("bridge", "max-age", 'u', settings.bridge.max_age);
755 set("bridge", "ageing-time", 'u', settings.bridge.ageing_time);
756 } else
757 delete result.bridge;
758
759 if (settings.bridge_port) {
760 set("bridge-port", "priority", 'u', settings.bridge_port.priority);
761 set("bridge-port", "path-cost", 'u', settings.bridge_port.path_cost);
762 set("bridge-port", "hairpin-mode", 'b', settings.bridge_port.hairpin_mode);
763 } else
764 delete result["bridge-port"];
765
766 if (settings.vlan) {
767 set("vlan", "parent", 's', settings.vlan.parent);
768 set("vlan", "id", 'u', settings.vlan.id);
769 set("vlan", "interface-name", 's', settings.vlan.interface_name);
770 // '1' is the default, but we need to set it explicitly anyway.
771 set("vlan", "flags", 'u', 1);
772 } else
773 delete result.vlan;
774
775 if (settings.ethernet) {
776 set("802-3-ethernet", "mtu", 'u', settings.ethernet.mtu);
777 set("802-3-ethernet", "assigned-mac-address", 's', settings.ethernet.assigned_mac_address);
778 // Delete cloned-mac-address so that assigned-mac-address gets used.
779 delete result["802-3-ethernet"]["cloned-mac-address"];
780 } else
781 delete result["802-3-ethernet"];
782
783 if (settings.wireguard) {
784 set("wireguard", "private-key", "s", settings.wireguard.private_key);
785 set("wireguard", "listen-port", "u", settings.wireguard.listen_port);
786 set("wireguard", "peers", "aa{sv}", settings.wireguard.peers.map(peer => {
787 return {
788 "public-key": {
789 t: "s",
790 v: peer.publicKey
791 },
792 ...peer.endpoint
793 ? {
794 endpoint: {
795 t: "s",
796 v: peer.endpoint
797 }
798 }
799 : {},
800 "allowed-ips": {
801 t: "as",
802 v: peer.allowedIps
803 }
804 };
805 }));
806 } else {
807 delete result.wireguard;
808 }
809
810 if (settings["802-11-wireless"]) {
811 set("802-11-wireless", "ssid", 'ay', settings["802-11-wireless"].ssid);
812 set("802-11-wireless", "mode", 's', settings["802-11-wireless"].mode);
813 } else {
814 delete result["802-11-wireless"];
815 }
816
817 if (settings["802-11-wireless-security"]) {
818 set("802-11-wireless-security", "key-mgmt", 's', settings["802-11-wireless-security"]["key-mgmt"]);
819 set("802-11-wireless-security", "psk", 's', settings["802-11-wireless-security"].psk);
820 } else {
821 delete result["802-11-wireless-security"];
822 }
823
824 return result;
825 }
826
827 function device_type_to_symbol(type) {
828 // This returns a string that is suitable for the connection.type field of
829 // Connection.Settings, except for "ethernet".
830 switch (type) {
831 case 0: return 'unknown';
832 case 1: return 'ethernet'; // 802-3-ethernet
833 case 2: return '802-11-wireless';
834 case 3: return 'unused1';
835 case 4: return 'unused2';
836 case 5: return 'bluetooth';
837 case 6: return '802-11-olpc-mesh';
838 case 7: return 'wimax';
839 case 8: return 'modem';
840 case 9: return 'infiniband';
841 case 10: return 'bond';
842 case 11: return 'vlan';
843 case 12: return 'adsl';
844 case 13: return 'bridge';
845 case 14: return 'generic';
846 case 15: return 'team';
847 case 16: return 'tun';
848 case 17: return 'ip_tunnel';
849 case 18: return 'macvlan';
850 case 19: return 'vxlan';
851 case 20: return 'veth';
852 case 21: return 'macsec';
853 case 22: return 'dummy';
854 case 23: return 'ppp';
855 case 24: return 'ovs_interface';
856 case 25: return 'ovs_port';
857 case 26: return 'ovs_bridge';
858 case 27: return 'wpan';
859 case 28: return '6lowpan';
860 case 29: return 'wireguard';
861 case 30: return 'wifi_p2p';
862 case 31: return 'vrf';
863 case 32: return 'loopback';
864 default: return '';
865 }
866 }
867
868 function device_state_to_text(state) {
869 switch (state) {
870 // NM_DEVICE_STATE_UNKNOWN
871 case 0: return "?";
872 // NM_DEVICE_STATE_UNMANAGED
873 case 10: return "";
874 // NM_DEVICE_STATE_UNAVAILABLE
875 case 20: return _("Not available");
876 // NM_DEVICE_STATE_DISCONNECTED
877 case 30: return _("Inactive");
878 // NM_DEVICE_STATE_PREPARE
879 case 40: return _("Preparing");
880 // NM_DEVICE_STATE_CONFIG
881 case 50: return _("Configuring");
882 // NM_DEVICE_STATE_NEED_AUTH
883 case 60: return _("Authenticating");
884 // NM_DEVICE_STATE_IP_CONFIG
885 case 70: return _("Configuring IP");
886 // NM_DEVICE_STATE_IP_CHECK
887 case 80: return _("Checking IP");
888 // NM_DEVICE_STATE_SECONDARIES
889 case 90: return _("Waiting");
890 // NM_DEVICE_STATE_ACTIVATED
891 case 100: return _("Active");
892 // NM_DEVICE_STATE_DEACTIVATING
893 case 110: return _("Deactivating");
894 // NM_DEVICE_STATE_FAILED
895 case 120: return _("Failed");
896 default: return "";
897 }
898 }
899
900 function access_point_mode_to_text(mode) {
901 switch (mode) {
902 // NM_802_11_MODE_ADHOC
903 case 1: return _("Adhoc");
904 // NM_802_11_MODE_INFRA
905 case 2: return _("Infra");
906 // NM_802_11_MODE_AP
907 case 3: return _("AP");
908 // NM_802_11_MODE_MESH
909 case 4: return _("Mesh");
910 // subsumes NM_802_11_MODE_UNKNOWN
911 default: return _("Unknown");
912 }
913 }
914
915 const connections_by_uuid = { };
916
917 function set_settings(obj, settings) {
918 if (obj.Settings && obj.Settings.connection && obj.Settings.connection.uuid)
919 delete connections_by_uuid[obj.Settings.connection.uuid];
920 obj.Settings = settings;
921 if (settings && settings.connection && settings.connection.uuid)
922 connections_by_uuid[settings.connection.uuid] = obj;
923 }
924
925 function refresh_settings(obj) {
926 push_refresh();
927 client.call(objpath(obj), "org.freedesktop.NetworkManager.Settings.Connection", "GetSettings")
928 .then(function(reply) {
929 const result = reply[0];
930 if (result) {
931 priv(obj).orig = result;
932 set_settings(obj, settings_from_nm(result));
933 }
934 })
935 .catch(complain)
936 .finally(pop_refresh);
937 }
938
939 function refresh_udev(obj) {
940 if (obj.Udi.indexOf("/sys/") !== 0)
941 return;
942
943 push_refresh();
944 cockpit.spawn(["udevadm", "info", obj.Udi], { err: 'message' })
945 .then(function(res) {
946 const props = { };
947 function snarf_prop(line, env, prop) {
948 const prefix = "E: " + env + "=";
949 if (line.indexOf(prefix) === 0) {
950 props[prop] = line.substring(prefix.length);
951 }
952 }
953 res.split('\n').forEach(function(line) {
954 snarf_prop(line, "ID_MODEL_FROM_DATABASE", "IdModel");
955 snarf_prop(line, "ID_VENDOR_FROM_DATABASE", "IdVendor");
956 });
957 set_object_properties(obj, props);
958 })
959 .catch(function(ex) {
960 /* udevadm info exits with 4 when device doesn't exist */
961 if (ex.exit_status !== 4) {
962 console.warn(ex.message);
963 console.warn(ex);
964 }
965 })
966 .finally(pop_refresh);
967 }
968
969 function handle_updated(obj) {
970 refresh_settings(obj);
971 }
972
973 /* NetworkManager specific object types, used by the generic D-Bus
974 * code and using the data conversion functions.
975 */
976
977 const type_Ipv4Config = {
978 interfaces: [
979 "org.freedesktop.NetworkManager.IP4Config"
980 ],
981
982 props: {
983 AddressData: { conv: conv_Array(ip_address_from_nm), def: [] }
984 }
985 };
986
987 const type_Ipv6Config = {
988 interfaces: [
989 "org.freedesktop.NetworkManager.IP6Config"
990 ],
991
992 props: {
993 AddressData: { conv: conv_Array(ip_address_from_nm), def: [] }
994 }
995 };
996
997 const type_AccessPoint = {
998 interfaces: [
999 "org.freedesktop.NetworkManager.AccessPoint"
1000 ],
1001
1002 props: {
1003 Flags: { def: 0 },
1004 WpaFlags: { def: 0 },
1005 RsnFlags: { def: 0 },
1006 Ssid: { conv: utils.ssid_from_nm, def: "" },
1007 Frequency: { def: 0 }, // MHz
1008 HwAddress: { def: "" },
1009 Mode: { conv: access_point_mode_to_text, def: "" },
1010 MaxBitrate: { def: 0 }, // Kbit/s
1011 Bandwidth: { def: 0 }, // MHz
1012 Strength: { def: 0 },
1013 LastSeen: { def: -1 }, // CLOCK_BOOTTIME seconds, -1 if never seen
1014 },
1015
1016 exporters: [
1017 function (obj) {
1018 // Find connection for this SSID (undefined if none exists)
1019 obj.Connection = (self.get_settings()?.Connections || []).find(con => {
1020 if (con.Settings?.["802-11-wireless"]?.ssid)
1021 return utils.ssid_from_nm(con.Settings["802-11-wireless"].ssid) == obj.Ssid;
1022 return false;
1023 });
1024 }
1025 ]
1026 };
1027
1028 const type_Connection = {
1029 interfaces: [
1030 "org.freedesktop.NetworkManager.Settings.Connection"
1031 ],
1032
1033 props: {
1034 Unsaved: { }
1035 },
1036
1037 signals: {
1038 Updated: handle_updated
1039 },
1040
1041 refresh: refresh_settings,
1042
1043 drop: function (obj) {
1044 set_settings(obj, null);
1045 },
1046
1047 prototype: {
1048 apply_settings: function (settings) {
1049 const self = this;
1050 try {
1051 return call_object_method(self,
1052 "org.freedesktop.NetworkManager.Settings.Connection", "Update",
1053 settings_to_nm(settings, priv(self).orig))
1054 .then(() => {
1055 set_settings(self, settings);
1056 });
1057 } catch (e) {
1058 return Promise.reject(e);
1059 }
1060 },
1061
1062 activate: function (dev, specific_object) {
1063 return call_object_method(get_object("/org/freedesktop/NetworkManager", type_Manager),
1064 "org.freedesktop.NetworkManager", "ActivateConnection",
1065 objpath(this), objpath(dev), objpath(specific_object))
1066 .then(([active_connection]) => active_connection);
1067 },
1068
1069 delete_: function () {
1070 return call_object_method(this, "org.freedesktop.NetworkManager.Settings.Connection", "Delete")
1071 .then(() => undefined);
1072 }
1073 },
1074
1075 exporters: [
1076 function (obj) {
1077 obj.Groups = [];
1078 obj.Members = [];
1079 obj.Interfaces = [];
1080 },
1081
1082 null,
1083
1084 null,
1085
1086 // Needs: type_Interface.Connections
1087 //
1088 // Sets: type_Connection.Members
1089 // type_Connection.Groups
1090 //
1091 function (obj) {
1092 // Most of the time, a connection has zero or one groups,
1093 // but when a connection refers to its group by interface
1094 // name, we might end up with more than one group
1095 // connection so we just collect them all.
1096 //
1097 // TODO - Nail down how NM really handles this.
1098
1099 function check_con(con) {
1100 const group_settings = connection_settings(con);
1101 const my_settings = connection_settings(obj);
1102 if (group_settings.type == my_settings.member_type) {
1103 obj.Groups.push(con);
1104 con.Members.push(obj);
1105 }
1106 }
1107
1108 const cs = connection_settings(obj);
1109 if (cs.member_type) {
1110 const group = connections_by_uuid[cs.group];
1111 if (group) {
1112 obj.Groups.push(group);
1113 group.Members.push(obj);
1114 } else {
1115 const iface = peek_interface(cs.group);
1116 if (iface) {
1117 iface.Connections.forEach(check_con);
1118 }
1119 }
1120 }
1121 }
1122 ]
1123
1124 };
1125
1126 const type_ActiveConnection = {
1127 interfaces: [
1128 "org.freedesktop.NetworkManager.Connection.Active"
1129 ],
1130
1131 props: {
1132 Connection: { conv: conv_Object(type_Connection) },
1133 Ip4Config: { conv: conv_Object(type_Ipv4Config) },
1134 Ip6Config: { conv: conv_Object(type_Ipv6Config) },
1135 State: { def: 0 }
1136 // See below for "Group"
1137 },
1138
1139 prototype: {
1140 deactivate: function() {
1141 return call_object_method(get_object("/org/freedesktop/NetworkManager", type_Manager),
1142 "org.freedesktop.NetworkManager", "DeactivateConnection",
1143 objpath(this))
1144 .then(() => undefined);
1145 }
1146 }
1147 };
1148
1149 const type_Device = {
1150 interfaces: [
1151 "org.freedesktop.NetworkManager.Device",
1152 "org.freedesktop.NetworkManager.Device.Wired",
1153 "org.freedesktop.NetworkManager.Device.Bond",
1154 "org.freedesktop.NetworkManager.Device.Team",
1155 "org.freedesktop.NetworkManager.Device.Bridge",
1156 "org.freedesktop.NetworkManager.Device.Vlan",
1157 "org.freedesktop.NetworkManager.Device.Wireless"
1158 ],
1159
1160 props: {
1161 DeviceType: { conv: device_type_to_symbol },
1162 Interface: { },
1163 StateText: { prop: "State", conv: device_state_to_text, def: _("Unknown") },
1164 State: { },
1165 StateReason: { def: [0, 0] }, // [state, reason] tuple
1166 HwAddress: { },
1167 AvailableConnections: { conv: conv_Array(conv_Object(type_Connection)), def: [] },
1168 ActiveConnection: { conv: conv_Object(type_ActiveConnection) },
1169 Ip4Config: { conv: conv_Object(type_Ipv4Config) },
1170 Ip6Config: { conv: conv_Object(type_Ipv6Config) },
1171 Udi: { trigger: refresh_udev },
1172 IdVendor: { def: "" },
1173 IdModel: { def: "" },
1174 Driver: { def: "" },
1175 Carrier: { def: true },
1176 Speed: { },
1177 Managed: { def: false },
1178 // WiFi-specific properties
1179 AccessPoints: { conv: conv_Array(conv_Object(type_AccessPoint)), def: [] },
1180 ActiveAccessPoint: { conv: conv_Object(type_AccessPoint) },
1181 // See below for "Members"
1182 },
1183
1184 prototype: {
1185 activate: function(connection, specific_object) {
1186 priv(this).lastFailureReason = undefined; // Clear stale failure reason from previous attempts
1187 return call_object_method(get_object("/org/freedesktop/NetworkManager", type_Manager),
1188 "org.freedesktop.NetworkManager", "ActivateConnection",
1189 objpath(connection), objpath(this), objpath(specific_object))
1190 .then(([active_connection]) => active_connection);
1191 },
1192
1193 activate_with_settings: function(settings, specific_object) {
1194 priv(this).lastFailureReason = undefined; // Clear stale failure reason from previous attempts
1195 try {
1196 return call_object_method(get_object("/org/freedesktop/NetworkManager", type_Manager),
1197 "org.freedesktop.NetworkManager", "AddAndActivateConnection",
1198 settings_to_nm(settings), objpath(this), objpath(specific_object))
1199 .then(([path, active_connection_path]) => ({
1200 connection: get_object(path, type_Connection),
1201 active_connection: get_object(active_connection_path, type_ActiveConnection)
1202 }));
1203 } catch (e) {
1204 return Promise.reject(e);
1205 }
1206 },
1207
1208 disconnect: function () {
1209 return call_object_method(this, 'org.freedesktop.NetworkManager.Device', 'Disconnect')
1210 .then(() => undefined);
1211 },
1212
1213 // Request a WiFi scan to populate this.AccessPoints
1214 request_scan: function() {
1215 utils.debug("request_scan: requesting scan for", this.Interface);
1216 call_object_method(this, 'org.freedesktop.NetworkManager.Device.Wireless', 'RequestScan', {})
1217 .catch(error => {
1218 // RequestScan can fail if a scan was recently done, that's OK
1219 console.warn("request_scan: scan failed for", this.Interface + ":", error.toString());
1220 });
1221 },
1222
1223 // Get and clear the last connection failure reason
1224 consume_failure_reason: function() {
1225 const reason = priv(this).lastFailureReason;
1226 priv(this).lastFailureReason = undefined;
1227 return reason;
1228 },
1229
1230 // Mark that a pending connection is being cancelled by the user
1231 cancel_pending_connection: function() {
1232 priv(this).connectionCancelled = true;
1233 },
1234
1235 // Wait for a connection to complete
1236 // For WiFi, pass expected_ssid to verify we connected to the right network
1237 // Returns a Promise that resolves on success or cancel, rejects with {reason} on failure
1238 wait_connection: function(expected_ssid) {
1239 priv(this).connectionCancelled = false;
1240 utils.debug("wait_connection: starting, iface:", this.Interface, "expected:", expected_ssid, "initial state:", this.State);
1241 return new Promise((resolve, reject) => {
1242 let activationStarted = false;
1243
1244 const cleanup = () => self.removeEventListener("changed", check);
1245
1246 const check = () => {
1247 utils.debug("wait_connection check: state:", this.State, "ssid:", this.ActiveAccessPoint?.Ssid,
1248 "activeConn:", !!this.ActiveConnection, "activationStarted:", activationStarted,
1249 "lastFailureReason:", priv(this).lastFailureReason,
1250 "connectionCancelled:", priv(this).connectionCancelled);
1251
1252 // captured a failure?
1253 const reason = this.consume_failure_reason();
1254 if (reason) {
1255 cleanup();
1256 console.warn("wait_connection: connection failed for", this.Interface, "reason:", reason);
1257 const error = new Error("Connection failed");
1258 error.reason = reason;
1259 reject(error);
1260 return;
1261 }
1262
1263 // https://networkmanager.dev/docs/api/latest/nm-dbus-types.html#NMDeviceState
1264 switch (this.State) {
1265 case 100: // NM_DEVICE_STATE_ACTIVATED
1266 if (!expected_ssid || this.ActiveAccessPoint?.Ssid === expected_ssid) {
1267 utils.debug("wait_connection: success");
1268 cleanup();
1269 resolve();
1270 }
1271 break;
1272
1273 case 30: // NM_DEVICE_STATE_DISCONNECTED; initial state, so wait for activation to start
1274 case 120: // NM_DEVICE_STATE_FAILED
1275 if (priv(this).connectionCancelled) {
1276 cleanup();
1277 utils.debug("wait_connection: cancelled by user");
1278 resolve();
1279 } else {
1280 // Disconnected/failed after
1281 // activation started means user
1282 // cancelled or failure without reason
1283 if (activationStarted && !this.ActiveConnection) {
1284 cleanup();
1285 console.warn("wait_connection: connection failed for", this.Interface, "without captured reason");
1286 reject(new Error("Connection failed"));
1287 }
1288 }
1289 break;
1290
1291 case 20: // NM_DEVICE_STATE_UNAVAILABLE
1292 case 110: // NM_DEVICE_STATE_DEACTIVATING
1293 break;
1294
1295 // any other state means we're activating
1296 default:
1297 if (!activationStarted) {
1298 utils.debug("wait_connection: activation started");
1299 activationStarted = true;
1300 }
1301 }
1302 };
1303
1304 self.addEventListener("changed", check);
1305 check(); // Check current state immediately in case already connected
1306 });
1307 }
1308 },
1309
1310 exporters: [
1311 function (obj) {
1312 if (obj.DeviceType === '802-11-wireless') {
1313 // When a hidden network (no SSID broadcast) has a saved connection, NetworkManager
1314 // duplicates it in AccessPoints: once without SSID (from the beacon), and once with
1315 // SSID (synthesized from the saved connection). Both have the same HwAddress (MAC).
1316 // We deduplicate by MAC first, preferring the one with a known connection
1317 const apByMac = new Map();
1318 (obj.AccessPoints || []).forEach(ap => {
1319 utils.debug(`AP: Ssid '${ap.Ssid}' HwAddress: ${ap.HwAddress} Strength: ${ap.Strength} hasConnection: ${!!ap.Connection}`);
1320 if (!apByMac.get(ap.HwAddress) || ap.Connection)
1321 apByMac.set(ap.HwAddress, ap);
1322 });
1323
1324 // Deduplicate visible APs by SSID, keeping the strongest signal for each network.
1325 // Count remaining hidden APs (those without SSID after MAC deduplication).
1326 const apBySsid = new Map();
1327 let hiddenCount = 0;
1328 Array.from(apByMac.values()).forEach(ap => {
1329 if (ap.Ssid) {
1330 const existing = apBySsid.get(ap.Ssid);
1331 if (!existing || ap.Strength > existing.Strength) {
1332 apBySsid.set(ap.Ssid, ap);
1333 }
1334 } else {
1335 hiddenCount++;
1336 }
1337 });
1338 obj.visibleSsids = Array.from(apBySsid.values());
1339 obj.hiddenAPCount = hiddenCount;
1340 utils.debug("Device exporter:", obj.Interface, "has", obj.visibleSsids.length, "visible SSIDs and", obj.hiddenAPCount, "hidden APs");
1341 }
1342 }
1343 ]
1344 };
1345
1346 // The 'Interface' type does not correspond to any NetworkManager
1347 // object or interface. We use it to represent a network device
1348 // that might or might not actually be known to the kernel, such
1349 // as the interface of a bond that is currently down.
1350 //
1351 // This is a HACK: NetworkManager should export Device nodes for
1352 // these.
1353
1354 const type_Interface = {
1355 interfaces: [],
1356
1357 exporters: [
1358 function (obj) {
1359 obj.Device = null;
1360 obj._NonDeviceConnections = [];
1361 obj.Connections = [];
1362 obj.MainConnection = null;
1363 },
1364
1365 null,
1366
1367 // Needs: type_Interface.Device
1368 // type_Interface._NonDeviceConnections
1369 //
1370 // Sets: type_Connection.Interfaces
1371 // type_Interface.Connections
1372 // type_Interface.MainConnection
1373
1374 function (obj) {
1375 if (!obj.Device && obj._NonDeviceConnections.length === 0) {
1376 drop_object(priv(obj).path);
1377 return;
1378 }
1379
1380 function consider_for_main(con) {
1381 if (!obj.MainConnection ||
1382 connection_settings(obj.MainConnection).timestamp < connection_settings(con).timestamp) {
1383 obj.MainConnection = con;
1384 }
1385 }
1386
1387 obj.Connections = obj._NonDeviceConnections;
1388
1389 if (obj.Device) {
1390 obj.Device.AvailableConnections.forEach(function (con) {
1391 if (obj.Connections.indexOf(con) == -1)
1392 obj.Connections.push(con);
1393 });
1394 }
1395
1396 obj.Connections.forEach(function (con) {
1397 consider_for_main(con);
1398 con.Interfaces.push(obj);
1399 });
1400
1401 // Explicitly prefer the active connection. The
1402 // active connection should have the most recent
1403 // timestamp, but only when the activation was
1404 // successful. Also, there don't seem to be change
1405 // notifications when the timestamp changes.
1406
1407 if (obj.Device && obj.Device.ActiveConnection && obj.Device.ActiveConnection.Connection) {
1408 obj.MainConnection = obj.Device.ActiveConnection.Connection;
1409 }
1410 }
1411 ]
1412
1413 };
1414
1415 function get_interface(iface) {
1416 const obj = get_object(":interface:" + iface, type_Interface);
1417 obj.Name = iface;
1418 return obj;
1419 }
1420
1421 function peek_interface(iface) {
1422 return peek_object(":interface:" + iface);
1423 }
1424
1425 const type_Settings = {
1426 interfaces: [
1427 "org.freedesktop.NetworkManager.Settings"
1428 ],
1429
1430 props: {
1431 Connections: { conv: conv_Array(conv_Object(type_Connection)), def: [] }
1432 },
1433
1434 prototype: {
1435 add_connection: function (conf) {
1436 // https://www.networkmanager.dev/docs/api/latest/nm-dbus-types.html
1437 const NM_SETTINGS_ADD_CONNECTION2_FLAG_TO_DISK = 0x1;
1438 const NM_SETTINGS_ADD_CONNECTION2_FLAG_BLOCK_AUTOCONNECT = 0x20;
1439 return call_object_method(this,
1440 'org.freedesktop.NetworkManager.Settings',
1441 'AddConnection2',
1442 settings_to_nm(conf, { }), NM_SETTINGS_ADD_CONNECTION2_FLAG_TO_DISK | NM_SETTINGS_ADD_CONNECTION2_FLAG_BLOCK_AUTOCONNECT, { })
1443 .then(([path]) => get_object(path, type_Connection));
1444 }
1445 },
1446
1447 exporters: [
1448 null,
1449
1450 // Sets: type_Interface._NonDeviceConnections
1451 //
1452 function (obj) {
1453 if (obj.Connections) {
1454 obj.Connections.forEach(function (con) {
1455 function add_to_interface(name) {
1456 if (name) {
1457 const cons = get_interface(name)._NonDeviceConnections;
1458 if (cons.indexOf(con) == -1)
1459 cons.push(con);
1460 }
1461 }
1462
1463 if (con.Settings) {
1464 if (con.Settings.connection)
1465 add_to_interface(con.Settings.connection.interface_name);
1466 if (con.Settings.bond)
1467 add_to_interface(con.Settings.bond.interface_name);
1468 if (con.Settings.team)
1469 add_to_interface(con.Settings.team.interface_name);
1470 if (con.Settings.bridge)
1471 add_to_interface(con.Settings.bridge.interface_name);
1472 if (con.Settings.vlan)
1473 add_to_interface(con.Settings.vlan.interface_name);
1474 }
1475 });
1476 }
1477 }
1478 ]
1479 };
1480
1481 const type_Manager = {
1482 interfaces: [
1483 "org.freedesktop.NetworkManager"
1484 ],
1485
1486 props: {
1487 Capabilities: { def: [] },
1488 Version: { },
1489 Devices: {
1490 conv: conv_Array(conv_Object(type_Device)),
1491 def: []
1492 },
1493 ActiveConnections: { conv: conv_Array(conv_Object(type_ActiveConnection)), def: [] }
1494 },
1495
1496 prototype: {
1497 checkpoint_create: function (devices, timeout) {
1498 return call_object_method(this,
1499 'org.freedesktop.NetworkManager',
1500 'CheckpointCreate',
1501 devices.map(objpath),
1502 timeout,
1503 0)
1504 .then(([checkpoint]) => checkpoint)
1505 .catch(function (error) {
1506 if (error.name != "org.freedesktop.DBus.Error.UnknownMethod")
1507 console.warn(error.message || error);
1508 });
1509 },
1510
1511 checkpoint_destroy: function (checkpoint) {
1512 if (checkpoint) {
1513 return call_object_method(this,
1514 'org.freedesktop.NetworkManager',
1515 'CheckpointDestroy',
1516 checkpoint)
1517 .then(() => undefined);
1518 } else
1519 return Promise.resolve();
1520 },
1521
1522 checkpoint_rollback: function (checkpoint) {
1523 if (checkpoint) {
1524 return call_object_method(this,
1525 'org.freedesktop.NetworkManager',
1526 'CheckpointRollback',
1527 checkpoint)
1528 .then(([result]) => result);
1529 } else
1530 return Promise.resolve();
1531 }
1532 },
1533
1534 exporters: [
1535 null,
1536
1537 // Sets: type_Interface.Device
1538 //
1539 function (obj) {
1540 obj.Devices.forEach(function (dev) {
1541 if (dev.Interface) {
1542 const iface = get_interface(dev.Interface);
1543 iface.Device = dev;
1544 }
1545 });
1546 }
1547 ]
1548 };
1549
1550 /* Now create the cyclic declarations.
1551 */
1552 type_ActiveConnection.props.Group = { conv: conv_Object(type_Device) };
1553 type_Device.props.Members = { conv: conv_Array(conv_Object(type_Device)), def: [] };
1554
1555 /* Accessing the model.
1556 */
1557
1558 self.list_interfaces = function list_interfaces() {
1559 const result = [];
1560 for (const path in objects) {
1561 const obj = objects[path];
1562 if (priv(obj).type === type_Interface)
1563 result.push(obj);
1564 }
1565 return result.sort(function (a, b) { return a.Name.localeCompare(b.Name) });
1566 };
1567
1568 self.find_interface = peek_interface;
1569
1570 self.get_manager = function () {
1571 return get_object("/org/freedesktop/NetworkManager",
1572 type_Manager);
1573 };
1574
1575 self.get_settings = function () {
1576 return get_object("/org/freedesktop/NetworkManager/Settings",
1577 type_Settings);
1578 };
1579
1580 /* Initialization.
1581 */
1582
1583 set_object_types([type_Manager,
1584 type_Settings,
1585 type_Device,
1586 type_Ipv4Config,
1587 type_Ipv6Config,
1588 type_Connection,
1589 type_ActiveConnection,
1590 type_AccessPoint
1591 ]);
1592
1593 get_object("/org/freedesktop/NetworkManager", type_Manager);
1594 get_object("/org/freedesktop/NetworkManager/Settings", type_Settings);
1595
1596 self.ready = undefined;
1597 self.operationInProgress = undefined;
1598 self.curtain = undefined;
1599 return self;
1600 }
1601
1602 export function syn_click(model, fun) {
1603 return function() {
1604 const self = this;
1605 const self_args = arguments;
1606 return model.synchronize().then(function() {
1607 fun.apply(self, self_args);
1608 });
1609 };
1610 }
1611
1612 export function is_managed(dev) {
1613 // Never let the user manage loopback devices, nothing good can come from that.
1614 return dev.State != 10 && dev.DeviceType != "loopback" && dev.Interface != "lo";
1615 }
1616
1617 function render_interface_link(iface) {
1618 return <Button variant='link' tabindex="0"
1619 isInline
1620 onClick={() => cockpit.location.go([iface])}>{iface}
1621 </Button>;
1622 }
1623
1624 export function device_state_text(dev) {
1625 if (!dev)
1626 return _("Inactive");
1627 if (dev.State == 100 && dev.Carrier === false)
1628 return _("No carrier");
1629 if (!is_managed(dev)) {
1630 if (!dev.ActiveConnection &&
1631 (!dev.Ip4Config || dev.Ip4Config.AddressData.length === 0) &&
1632 (!dev.Ip6Config || dev.Ip6Config.AddressData.length === 0))
1633 return _("Inactive");
1634 }
1635 return dev.StateText;
1636 }
1637
1638 export function array_join(elts, sep) {
1639 const result = [];
1640 for (let i = 0; i < elts.length; i++) {
1641 result.push(elts[i]);
1642 if (i < elts.length - 1)
1643 result.push(sep);
1644 }
1645 return result;
1646 }
1647
1648 export function render_active_connection(dev, with_link, hide_link_local) {
1649 const parts = [];
1650
1651 if (!dev)
1652 return "";
1653
1654 const con = dev.ActiveConnection;
1655
1656 if (con && con.Group) {
1657 return fmt_to_fragments(_("Part of $0"), with_link ? render_interface_link(con.Group.Interface) : con.Group.Interface);
1658 }
1659
1660 const ip4config = con ? con.Ip4Config : dev.Ip4Config;
1661 if (ip4config) {
1662 ip4config.AddressData.forEach(function (a) {
1663 parts.push(a.address + "/" + a.prefix);
1664 });
1665 }
1666
1667 function is_ipv6_link_local(addr) {
1668 return (addr.indexOf("fe8") === 0 ||
1669 addr.indexOf("fe9") === 0 ||
1670 addr.indexOf("fea") === 0 ||
1671 addr.indexOf("feb") === 0);
1672 }
1673
1674 const ip6config = con ? con.Ip6Config : dev.Ip6Config;
1675 if (ip6config) {
1676 ip6config.AddressData.forEach(function (a) {
1677 if (!(hide_link_local && is_ipv6_link_local(a.address)))
1678 parts.push(a.address + "/" + a.prefix);
1679 });
1680 }
1681
1682 return parts.join(", ");
1683 }
1684
1685 /* Resource usage monitoring
1686 */
1687
1688 export function complete_settings(settings, device) {
1689 if (!device) {
1690 console.warn("No device to complete settings", JSON.stringify(settings));
1691 return;
1692 }
1693
1694 settings.connection.id = device.Interface;
1695 settings.connection.uuid = uuidv4();
1696
1697 if (device.DeviceType == 'ethernet') {
1698 settings.connection.type = '802-3-ethernet';
1699 settings.ethernet = { };
1700 } else {
1701 // The remaining types are identical between Device and Settings, see
1702 // device_type_to_symbol.
1703 settings.connection.type = device.DeviceType;
1704 }
1705 }
1706
1707 export function settings_applier(model, device, connection) {
1708 /* If we have a connection, we can just update it.
1709 * Otherwise if the settings has TYPE set, we can add
1710 * them as a stand-alone object. Otherwise, we
1711 * activate the device with the settings which causes
1712 * NM to fill in the type and other details.
1713 * Non-persistent "Wired Connection" is a special case
1714 * and we make a new connection instead.
1715 *
1716 * HACK - The activation is a hack, we would rather
1717 * just have NM fill in the details and not activate
1718 * the connection. See complete_settings above that
1719 * can do some of this completion.
1720 *
1721 * https://bugzilla.gnome.org/show_bug.cgi?id=775226
1722 */
1723
1724 const specialCon = utils.isNonPersistentMultiCon(connection);
1725
1726 return function (settings) {
1727 if (connection && !specialCon) {
1728 return connection.apply_settings(settings);
1729 } else if (settings.connection.type && !specialCon) {
1730 return model.get_settings().add_connection(settings);
1731 } else if (device && specialCon) {
1732 const newSettings = utils.createNewConnSettings(settings, device.Interface);
1733 return device.activate_with_settings(newSettings);
1734 } else if (device) {
1735 return device.activate_with_settings(settings);
1736 } else {
1737 console.warn("No way to apply settings", connection, settings);
1738 return Promise.resolve();
1739 }
1740 };
1741 }
1742
1743 export function choice_title(choices, choice, def) {
1744 for (let i = 0; i < choices.length; i++) {
1745 if (choices[i].choice == choice)
1746 return choices[i].title;
1747 }
1748 return def;
1749 }
1750
1751 /* Support for automatically rolling back changes that break the
1752 * connection to the server.
1753 *
1754 * The basic idea is to perform the following steps:
1755 *
1756 * 1) Create a checkpoint with automatic rollback
1757 * 2) Make the change
1758 * 3) Destroy the checkpoint
1759 *
1760 * If step 2 breaks the connection, step 3 won't happen and the
1761 * checkpoint will roll back after some time. This is supposed to
1762 * restore connectivity, so steps 2 and 3 will complete at that time,
1763 * and step 3 will fail because the checkpoint doesn't exist anymore.
1764 *
1765 * The failure of step 3 is our indication that the connection was
1766 * temporarily broken, and we inform the user about that.
1767 *
1768 * Usually, step 2 completes successfully also for a change that
1769 * breaks the connection, and connectivity is only lost after some
1770 * delay. Thus, we also delay step 3 by a short amount (settle_time,
1771 * below).
1772 *
1773 * For a change that _doesn't_ break connectivity, this whole process
1774 * is inherently a race: Steps 2 and 3 need to complete before the
1775 * checkpoint created in step 1 reaches its timeout.
1776 *
1777 * It is better to wait a bit longer for salvation after making a
1778 * mistake than to have many of your legitimate changes be cancelled
1779 * by an impatient nanny mechanism. Thus, we use a rather long
1780 * checkpoint rollback timeout (rollback_time, below).
1781 *
1782 * For a good change, all three steps usually happen quickly, and the
1783 * time we wait between steps 2 and 3 doesn't need to be very long
1784 * either, apparently. Thus, we delay any indication that something
1785 * might be wrong by a short delay (curtain_time, below), and most
1786 * changes can thus be made without the "Testing connection" curtain
1787 * coming up.
1788 *
1789 * Some changes will be rolled back although the user really wants to
1790 * make them. For example, the user might want to change the IP
1791 * address of the machine, and although this will disconnect Cockpit,
1792 * the user can connect again on the new address.
1793 *
1794 * In order to give the user the option to avoid this unwanted
1795 * rollback, we let him/her do the same change without a checkpoint
1796 * directly from the dialog that explains the problem.
1797 */
1798
1799 /* To avoid interference, we switch off the global transport health
1800 * check while a checkpoint exists. For example, if the rollback
1801 * takes a really long time, Cockpit would otherwise disconnect itself
1802 * forcefully and the user would not get to see the dialog with the
1803 * "Do it anyway" button. This dialog is the only way to make certain
1804 * changes, and it is thus important to show it if at all possible.
1805 */
1806
1807 /* Considerations for choosing the times below
1808 *
1809 * curtain_time too short: Curtain comes up too often for good changes.
1810 *
1811 * curtain_time too long: User is left with a broken UI for a
1812 * significant time in the case of a mistake.
1813 *
1814 * settle_time too short: Some bad changes that take time to have any
1815 * effect will be let through.
1816 *
1817 * settle_time too high: All operations take a long time and the race
1818 * between Cockpit destroying the checkpoint
1819 * and NetworkManager rolling it back (see
1820 * above) gets tighter. The curtain
1821 * needs to come up to prevent the user from
1822 * interacting with the page. Thus
1823 * settle_time should be shorter than
1824 * curtain_time.
1825 *
1826 * rollback_time too short: Good changes that take a long time to complete
1827 * (on a loaded machine, say) are cancelled spuriously.
1828 *
1829 * rollback_time too long: The user has to wait a long time before
1830 * his/her mistake is corrected and might
1831 * consider Cockpit to be dead already.
1832 * Also, the network connection machinery in
1833 * the kernels and browsers must recover
1834 * after no packages have been flowing for
1835 * this much time. Windows seems to have
1836 * less patience than Linux in this regard.
1837 */
1838 const curtain_time = 1.5;
1839 let settle_time = 1.0;
1840 const rollback_time = 7.0;
1841
1842 export function with_checkpoint(model, modify, options) {
1843 const manager = model.get_manager();
1844
1845 let curtain_timeout;
1846 let curtain_title_timeout;
1847
1848 function show_curtain() {
1849 cockpit.hint("ignore_transport_health_check", { data: true });
1850 curtain_timeout = window.setTimeout(function () {
1851 curtain_timeout = null;
1852 model.set_curtain('testing');
1853 }, curtain_time * 1000);
1854 curtain_title_timeout = window.setTimeout(function () {
1855 curtain_title_timeout = null;
1856 model.set_curtain('restoring');
1857 }, rollback_time * 1000);
1858 }
1859
1860 function hide_curtain() {
1861 if (curtain_timeout)
1862 window.clearTimeout(curtain_timeout);
1863 curtain_timeout = null;
1864 if (curtain_title_timeout)
1865 window.clearTimeout(curtain_title_timeout);
1866 cockpit.hint("ignore_transport_health_check", { data: false });
1867
1868 model.set_curtain(undefined);
1869 }
1870
1871 // HACK - Let's not use checkpoints for changes that involve
1872 // adding or removing connections.
1873 //
1874 // https://bugzilla.redhat.com/show_bug.cgi?id=1378393
1875 // https://bugzilla.redhat.com/show_bug.cgi?id=1398316
1876 //
1877 // We also switch off checkpoints for most of the integration
1878 // tests.
1879
1880 if (options.hack_does_add_or_remove || window.cockpit_tests_disable_checkpoints) {
1881 modify();
1882 return;
1883 }
1884
1885 if (window.cockpit_tests_checkpoints_settle_time)
1886 settle_time = window.cockpit_tests_checkpoints_settle_time;
1887
1888 manager.checkpoint_create(options.devices || [], rollback_time)
1889 .then(function (cp) {
1890 if (!cp) {
1891 modify();
1892 return;
1893 }
1894
1895 // Signal that a checkpoint is active for anaconda-webui
1896 window.sessionStorage.setItem("cockpit_has_checkpoint", "true");
1897
1898 show_curtain();
1899 modify()
1900 .then(function () {
1901 window.setTimeout(function () {
1902 manager.checkpoint_destroy(cp)
1903 .catch(function () {
1904 show_breaking_change_dialog({
1905 ...options,
1906 action: syn_click(model, modify)
1907 });
1908 })
1909 .finally(function() {
1910 hide_curtain();
1911
1912 // Clear checkpoint status when done
1913 window.sessionStorage.setItem("cockpit_has_checkpoint", "false");
1914 });
1915 }, settle_time * 1000);
1916 })
1917 .catch(function () {
1918 hide_curtain();
1919
1920 // HACK
1921 //
1922 // We want to avoid rollbacks for operations that don't actually change anything when they
1923 // fail. Rollback are always disruptive and always seem to reconnect all the included
1924 // devices, even if nothing has actually changed. Thus, if you give invalid input to
1925 // NetworkManager and receive an error in a settings dialog, rolling back the checkpoint
1926 // would cause a temporary disconnection on the interface.
1927 //
1928 // https://bugzilla.redhat.com/show_bug.cgi?id=1427187
1929
1930 if (options.rollback_on_failure)
1931 manager.checkpoint_rollback(cp);
1932 else
1933 manager.checkpoint_destroy(cp);
1934
1935 // Clear checkpoint status on failure
1936 window.sessionStorage.setItem("cockpit_has_checkpoint", "false");
1937 });
1938 });
1939 }
1940
1941 export function with_settings_checkpoint(model, modify, options) {
1942 with_checkpoint(model, modify,
1943 {
1944 ...options,
1945 fail_text: _("Changing the settings will break the connection to the server, and will make the administration UI unavailable."),
1946 anyway_text: _("Change the settings"),
1947 });
1948 }
1949
1950 export function connection_devices(con) {
1951 const devices = [];
1952
1953 if (con)
1954 con.Interfaces.forEach(function (iface) { if (iface.Device) devices.push(iface.Device); });
1955
1956 return devices;
1957 }
1958
1959 export function is_interface_connection(iface, connection) {
1960 return connection && connection.Interfaces.indexOf(iface) != -1;
1961 }
1962
1963 export function is_interesting_interface(iface) {
1964 return !iface.Device || is_managed(iface.Device);
1965 }
1966
1967 export function member_connection_for_interface(group, iface) {
1968 return group?.Members.find(s => is_interface_connection(iface, s));
1969 }
1970
1971 export function member_interface_choices(model, group) {
1972 return model.list_interfaces().filter(function (iface) {
1973 return !is_interface_connection(iface, group) && is_interesting_interface(iface);
1974 });
1975 }
1976
1977 export function free_member_connection(con) {
1978 const cs = connection_settings(con);
1979 if (cs.member_type) {
1980 delete cs.member_type;
1981 delete cs.group;
1982 delete con.Settings.team_port;
1983 delete con.Settings.bridge_port;
1984 return con.apply_settings(con.Settings).then(() => { con.activate(null, null) });
1985 }
1986 }
1987
1988 export function set_member(model, group_connection, group_settings, member_type,
1989 iface_name, val) {
1990 const iface = model.find_interface(iface_name);
1991 if (!iface)
1992 return false;
1993
1994 const main_connection = iface.MainConnection;
1995
1996 if (val) {
1997 /* Turn the main_connection into a member for group.
1998 */
1999
2000 const group_iface = group_settings.connection.interface_name;
2001 if (!group_iface)
2002 return false;
2003
2004 let member_settings;
2005 if (main_connection) {
2006 member_settings = main_connection.Settings;
2007
2008 if (member_settings.connection.group == group_settings.connection.uuid ||
2009 member_settings.connection.group == group_settings.connection.id ||
2010 member_settings.connection.group == group_iface)
2011 return Promise.resolve();
2012
2013 member_settings.connection.member_type = member_type;
2014 member_settings.connection.group = group_iface;
2015 member_settings.connection.autoconnect = true;
2016 delete member_settings.ipv4;
2017 delete member_settings.ipv6;
2018 delete member_settings.team_port;
2019 delete member_settings.bridge_port;
2020 } else {
2021 member_settings = {
2022 connection:
2023 {
2024 autoconnect: true,
2025 interface_name: iface.Name,
2026 member_type,
2027 group: group_iface
2028 }
2029 };
2030 complete_settings(member_settings, iface.Device);
2031 }
2032
2033 return settings_applier(model, iface.Device, main_connection)(member_settings).then(function () {
2034 // If the group already exists (with the correct name),
2035 // activate or deactivate the member immediately so that
2036 // the settings actually apply and the interface becomes a
2037 // member. Otherwise we activate it later when the group
2038 // is created.
2039 if (group_connection && group_connection.Interfaces[0].Name == group_iface) {
2040 const group_dev = group_connection.Interfaces[0].Device;
2041 if (group_dev && group_dev.ActiveConnection)
2042 return main_connection.activate(iface.Device);
2043 else if (iface.Device.ActiveConnection)
2044 return iface.Device.ActiveConnection.deactivate();
2045 }
2046 });
2047 } else {
2048 /* Free the main_connection from being a member if it is our member. If there is
2049 * no main_connection, we don't need to do anything.
2050 */
2051 if (main_connection && main_connection.Groups.indexOf(group_connection) != -1) {
2052 free_member_connection(main_connection);
2053 }
2054 }
2055
2056 return true;
2057 }
2058
2059 export function apply_group_member(choices, model, apply_group, group_connection, group_settings, member_type) {
2060 const active_settings = [];
2061
2062 if (!group_connection) {
2063 if (group_settings.bond &&
2064 group_settings.bond.options &&
2065 group_settings.bond.options.primary) {
2066 const iface = model.find_interface(group_settings.bond.options.primary);
2067 if (iface && iface.MainConnection)
2068 active_settings.push(iface.MainConnection.Settings);
2069 } else {
2070 Object.keys(choices)
2071 .filter(choice => choices[choice])
2072 .forEach(choice => {
2073 const iface = model.find_interface(choice);
2074 if (iface && iface.Device && iface.Device.ActiveConnection && iface.Device.ActiveConnection.Connection) {
2075 active_settings.push(iface.Device.ActiveConnection.Connection.Settings);
2076 }
2077 });
2078 }
2079
2080 if (active_settings.length == 1) {
2081 group_settings.ipv4 = JSON.parse(JSON.stringify(active_settings[0].ipv4));
2082 group_settings.ipv6 = JSON.parse(JSON.stringify(active_settings[0].ipv6));
2083 }
2084
2085 group_settings.connection.autoconnect_members = 1;
2086 }
2087
2088 /* For bonds, the order in which members are added to their group matters since the first members gets to
2089 * set the MAC address of the bond, which matters for DHCP. We leave it to NetworkManager to determine
2090 * the order in which members are added so that the order is consistent with what happens when the bond is
2091 * activated the next time, such as after a reboot.
2092 */
2093
2094 function set_all_members() {
2095 const deferreds = Object.keys(choices).map(iface => {
2096 return model.synchronize().then(function () {
2097 return set_member(model, group_connection, group_settings, member_type,
2098 iface, choices[iface]);
2099 });
2100 });
2101 return Promise.all(deferreds);
2102 }
2103
2104 return set_all_members().then(function () {
2105 return apply_group(group_settings);
2106 });
2107 }
2108
2109 export function init() {
2110 cockpit.translate();
2111 }