Debian Codegraph @

pkg/networkmanager/network-interface.jsx

raw
1 /*
2 * Copyright (C) 2021 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5 import cockpit from "cockpit";
6 import React, { useContext, useEffect, useRef, useState } from "react";
7 import { useEvent, useInit } from "hooks";
8 import { Breadcrumb, BreadcrumbItem } from "@patternfly/react-core/dist/esm/components/Breadcrumb/index.js";
9 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
10 import { Card, CardBody, CardHeader, CardTitle } from '@patternfly/react-core/dist/esm/components/Card/index.js';
11 import { Checkbox } from "@patternfly/react-core/dist/esm/components/Checkbox/index.js";
12 import { DescriptionList, DescriptionListDescription, DescriptionListGroup, DescriptionListTerm } from "@patternfly/react-core/dist/esm/components/DescriptionList/index.js";
13 import { DropdownItem } from "@patternfly/react-core/dist/esm/components/Dropdown/index.js";
14 import { Form } from "@patternfly/react-core/dist/esm/components/Form/index.js";
15 import { Flex, FlexItem } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
16 import { Gallery } from "@patternfly/react-core/dist/esm/layouts/Gallery/index.js";
17 import { Modal, ModalBody, ModalFooter, ModalHeader } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
18 import { Page, PageBreadcrumb, PageSection } from "@patternfly/react-core/dist/esm/components/Page/index.js";
19 import { Progress } from "@patternfly/react-core/dist/esm/components/Progress/index.js";
20 import { SearchInput } from "@patternfly/react-core/dist/esm/components/SearchInput/index.js";
21 import { Spinner } from "@patternfly/react-core/dist/esm/components/Spinner/index.js";
22 import { Switch } from "@patternfly/react-core/dist/esm/components/Switch/index.js";
23 import { Tooltip } from "@patternfly/react-core/dist/esm/components/Tooltip/index.js";
24 import { SortByDirection } from '@patternfly/react-table';
25 import {
26 ConnectedIcon,
27 DisconnectedIcon,
28 LockIcon,
29 LockOpenIcon,
30 PlusIcon,
31 RedoIcon,
32 ThumbtackIcon,
33 } from "@patternfly/react-icons";
34
35 import { KebabDropdown } from "cockpit-components-dropdown";
36 import { ListingTable } from "cockpit-components-table.jsx";
37 import { Privileged } from "cockpit-components-privileged";
38 import { distanceToNow } from "timeformat";
39 import { fmt_to_fragments, in_anaconda_mode } from "utils";
40 import { useDialogs } from "dialogs.jsx";
41
42 import { ModelContext } from './model-context.jsx';
43 import { NetworkInterfaceMembers } from "./network-interface-members.jsx";
44 import { NetworkAction } from './dialogs-common.jsx';
45 import { NetworkPlots } from "./plots";
46 import * as utils from "./utils.js";
47
48 import {
49 array_join,
50 choice_title,
51 complete_settings,
52 connection_settings,
53 free_member_connection,
54 is_managed,
55 render_active_connection,
56 settings_applier,
57 show_error_dialog,
58 show_unexpected_error,
59 syn_click,
60 with_checkpoint,
61 } from './interfaces.js';
62 import {
63 team_runner_choices,
64 team_watch_choices,
65 } from './team.jsx';
66 import {
67 bond_mode_choices,
68 } from './bond.jsx';
69
70 import { get_ip_method_choices } from './ip-settings.jsx';
71
72 import {
73 useDialogState,
74 DialogError, DialogErrorMessage,
75 DialogTextInput,
76 DialogPasswordInput,
77 DialogDropdownSelect,
78 DialogActionButton, DialogCancelButton,
79 } from 'cockpit/dialog';
80
81 const _ = cockpit.gettext;
82
83 // known networks: with ssid; hidden networks: no ssid
84 const WiFiConnectDialog = ({ dev, model, ssid: knownSsid, ap }) => {
85 useEvent(model, "changed");
86 const Dialogs = useDialogs();
87
88 const isHidden = !knownSsid;
89 const idPrefix = "network-wifi-connect";
90
91 function validate() {
92 if (isHidden) {
93 dlg.field("ssid").validate(val => {
94 if (val.trim() === "")
95 return _("SSID can not be empty");
96 });
97 }
98 if (!isHidden || dlg.values.security != "none") {
99 dlg.field("password").validate(val => {
100 if (val.trim() === "")
101 return _("Password can not be empty");
102 });
103 }
104 }
105
106 const dlg = useDialogState({
107 ssid: knownSsid || "",
108 security: "wpa-psk",
109 password: "",
110 }, validate);
111
112 const onConnect = async ({ ssid, security, password }) => {
113 utils.debug("Connecting to", ssid, isHidden ? `with security ${security}` : "with password");
114
115 const settings = {
116 connection: {
117 id: ssid,
118 type: "802-11-wireless",
119 autoconnect: true,
120 },
121 "802-11-wireless": {
122 ssid: utils.ssid_to_nm(ssid),
123 mode: "infrastructure",
124 },
125 };
126
127 if (isHidden) {
128 settings["802-11-wireless"].hidden = true;
129 }
130
131 if (!isHidden || security !== "none") {
132 settings["802-11-wireless-security"] = {
133 "key-mgmt": isHidden ? security : "wpa-psk",
134 psk: password,
135 };
136 }
137
138 let connection = null;
139 try {
140 // ap might be stale if there was a scan since opening the dialog, so pass NULL
141 // NM will find the right AP by SSID
142 const result = await dev.activate_with_settings(settings, null);
143 connection = result.connection;
144
145 dlg.set_cancel(
146 () => {
147 utils.debug("Cancelling connection to", ssid);
148 dev.cancel_pending_connection();
149 connection.delete_()
150 .catch(err => console.warn("Failed to delete connection:", err));
151 });
152
153 utils.debug("Connection activation started");
154 await dev.wait_connection(ssid);
155 utils.debug("Connected successfully to", ssid);
156 } catch (err) {
157 // just in case something survived, clean up
158 connection?.delete_()
159 .catch(err => utils.debug("Failed to delete failed connection:", err));
160
161 throw new DialogError(
162 _("Failed to connect"),
163 err.reason === 7 // NM_DEVICE_STATE_REASON_NO_SECRETS
164 ? _("Check your password.")
165 : err.toString());
166 }
167 };
168
169 return (
170 <Modal id={idPrefix + "-dialog"}
171 position="top"
172 variant="small"
173 isOpen
174 onClose={Dialogs.close}>
175 <ModalHeader title={isHidden ? _("Connect to hidden network") : cockpit.format(_("Connect to $0"), knownSsid)} />
176 <ModalBody>
177 <DialogErrorMessage dialog={dlg} />
178 <Form id={idPrefix + "-body"} onSubmit={ev => ev.preventDefault()} isHorizontal>
179 {isHidden && (
180 <>
181 <DialogTextInput
182 label={_("Network name")}
183 field={dlg.field("ssid")}
184 />
185 <DialogDropdownSelect
186 label={_("Security")}
187 field={dlg.field("security")}
188 options={[
189 { value: "none", label: _("None") },
190 { value: "wpa-psk", label: _("WPA/WPA2 Personal") },
191 ]}
192 />
193 </>
194 )}
195 {(!isHidden || dlg.values.security !== "none") && (
196 <DialogPasswordInput
197 label={_("Password")}
198 field={dlg.field("password")}
199 autoFocus={!isHidden} // eslint-disable-line jsx-a11y/no-autofocus
200 />
201 )}
202 </Form>
203 </ModalBody>
204 <ModalFooter>
205 <DialogActionButton dialog={dlg} action={onConnect} onClose={Dialogs.close}>
206 {_("Connect")}
207 </DialogActionButton>
208 <DialogCancelButton dialog={dlg} onClose={Dialogs.close} />
209 </ModalFooter>
210 </Modal>
211 );
212 };
213
214 export const NetworkInterfacePage = ({
215 privileged,
216 operationInProgress,
217 usage_monitor,
218 plot_state,
219 interfaces,
220 iface
221 }) => {
222 const model = useContext(ModelContext);
223 useEvent(model, "changed");
224 const [isScanning, setIsScanning] = useState(false);
225 const [prevAPCount, setPrevAPCount] = useState(0);
226 const [networkSearch, setNetworkSearch] = useState("");
227
228 const dev_name = iface.Name;
229 const dev = iface.Device;
230 const isManaged = iface && (!dev || is_managed(dev));
231
232 const accessPointCount = dev?.DeviceType === '802-11-wireless' ? (dev.AccessPoints?.length || 0) : 0;
233
234 const Dialogs = useDialogs();
235
236 // Trigger (passive) scan on page load for wireless devices on page load
237 useInit(() => {
238 if (dev?.DeviceType === '802-11-wireless') {
239 utils.debug("Requesting initial WiFi scan for", dev_name);
240 dev.request_scan();
241 }
242 });
243
244 // WiFi scanning: re-enable button when APs change or after timeout
245 useEffect(() => {
246 if (isScanning) {
247 if (accessPointCount !== prevAPCount && prevAPCount !== 0)
248 setIsScanning(false);
249 const timer = setTimeout(() => setIsScanning(false), 5000);
250 return () => clearTimeout(timer);
251 }
252 setPrevAPCount(accessPointCount);
253 }, [isScanning, accessPointCount, prevAPCount]);
254
255 // Track stable WiFi network order (by signal strength on first scan, preserved thereafter)
256 const stableAPOrder = useRef([]);
257
258 // Update stable AP order when APs are added/removed
259 useEffect(() => {
260 if (dev?.DeviceType !== '802-11-wireless')
261 return;
262
263 const accessPoints = dev.AccessPoints || [];
264 const currentMACs = new Set(accessPoints.map(ap => ap.HwAddress));
265 const stableMACs = new Set(stableAPOrder.current);
266
267 // Re-sort if APs added/removed
268 const needsResort = currentMACs.size !== stableMACs.size ||
269 ![...currentMACs].every(mac => stableMACs.has(mac));
270
271 if (needsResort) {
272 // Sort by signal strength
273 const sorted = [...accessPoints].sort((a, b) => b.Strength - a.Strength);
274 // Store MAC addresses
275 stableAPOrder.current = sorted.map(ap => ap.HwAddress);
276 }
277 }, [dev?.AccessPoints, dev?.DeviceType]);
278
279 let ghostSettings = null;
280 let connectionSettings = null;
281
282 if (iface) {
283 if (iface.MainConnection) {
284 connectionSettings = iface.MainConnection.Settings;
285 } else {
286 ghostSettings = createGhostConnectionSettings();
287 connectionSettings = ghostSettings;
288 }
289 }
290
291 function deleteConnections() {
292 function deleteConnectionAndMembers(con) {
293 return Promise.all(con.Members.map(s => free_member_connection(s))).then(() => con.delete_());
294 }
295
296 function deleteConnections(cons) {
297 return Promise.all(cons.map(deleteConnectionAndMembers));
298 }
299
300 function deleteIfaceConnections(iface) {
301 return deleteConnections(iface.Connections);
302 }
303
304 const location = cockpit.location;
305
306 function modify() {
307 return deleteIfaceConnections(iface)
308 .then(function () {
309 location.go("/");
310 })
311 .catch(show_unexpected_error);
312 }
313
314 if (iface) {
315 with_checkpoint(model, modify,
316 {
317 devices: dev ? [dev] : [],
318 fail_text: fmt_to_fragments(_("Deleting $0 will break the connection to the server, and will make the administration UI unavailable."), <b>{dev_name}</b>),
319 anyway_text: cockpit.format(_("Delete $0"), dev_name),
320 hack_does_add_or_remove: true,
321 rollback_on_failure: true
322 });
323 }
324 }
325
326 function connect() {
327 if (!(iface.MainConnection || (dev && ghostSettings)))
328 return;
329
330 function fail(error) {
331 show_unexpected_error(error);
332 }
333
334 function modify() {
335 if (iface.MainConnection) {
336 return iface.MainConnection.activate(dev, null).catch(fail);
337 } else {
338 return dev.activate_with_settings(ghostSettings, null).catch(fail);
339 }
340 }
341
342 with_checkpoint(model, modify,
343 {
344 devices: dev ? [dev] : [],
345 fail_text: fmt_to_fragments(_("Switching on $0 will break the connection to the server, and will make the administration UI unavailable."), <b>{dev_name}</b>),
346 anyway_text: cockpit.format(_("Switch on $0"), dev_name)
347 });
348 }
349
350 function disconnect() {
351 if (!dev) {
352 console.log("Trying to switch off without a device?");
353 return;
354 }
355
356 function modify () {
357 return dev.disconnect()
358 .catch(error => show_unexpected_error(error));
359 }
360
361 with_checkpoint(model, modify,
362 {
363 devices: [dev],
364 fail_text: fmt_to_fragments(_("Switching off $0 will break the connection to the server, and will make the administration UI unavailable."), <b>{dev_name}</b>),
365 anyway_text: cockpit.format(_("Switch off $0"), dev_name)
366 });
367 }
368
369 function renderDesc() {
370 let desc;
371 let cs;
372 if (dev) {
373 if (dev.DeviceType == 'ethernet' || dev.IdVendor || dev.IdModel) {
374 desc = cockpit.format("$IdVendor $IdModel $Driver", dev);
375 } else if (dev.DeviceType == 'bond') {
376 desc = _("Bond");
377 } else if (dev.DeviceType == 'team') {
378 desc = _("Team");
379 } else if (dev.DeviceType == 'vlan') {
380 desc = _("VLAN");
381 } else if (dev.DeviceType == 'bridge') {
382 desc = _("Bridge");
383 } else if (dev.Driver == 'wireguard') {
384 desc = "WireGuard";
385 } else
386 desc = cockpit.format(_("Unknown \"$0\""), dev.DeviceType);
387 } else if (iface) {
388 cs = connection_settings(iface.Connections[0]);
389 if (cs.type == "bond")
390 desc = _("Bond");
391 else if (cs.type == "team")
392 desc = _("Team");
393 else if (cs.type == "vlan")
394 desc = _("VLAN");
395 else if (cs.type == "bridge")
396 desc = _("Bridge");
397 else if (cs.type == "wireguard")
398 desc = "WireGuard";
399 else if (cs.type)
400 desc = cockpit.format(_("Unknown \"$0\""), cs.type);
401 else
402 desc = _("Unknown");
403 } else
404 desc = _("Unknown");
405
406 return desc;
407 }
408
409 function renderMac() {
410 let mac;
411 if (dev &&
412 dev.HwAddress) {
413 mac = dev.HwAddress;
414 } else if (iface &&
415 iface.MainConnection &&
416 iface.MainConnection.Settings &&
417 iface.MainConnection.Settings.ethernet &&
418 iface.MainConnection.Settings.ethernet.assigned_mac_address) {
419 mac = iface.MainConnection.Settings.ethernet.assigned_mac_address;
420 }
421
422 const can_edit_mac = (privileged && iface && iface.MainConnection &&
423 (connection_settings(iface.MainConnection).type == "802-3-ethernet" ||
424 connection_settings(iface.MainConnection).type == "bond"));
425
426 let mac_desc;
427 if (can_edit_mac) {
428 mac_desc = (
429 <NetworkAction type="mac" iface={iface} buttonText={mac} connectionSettings={iface.MainConnection.Settings} />
430 );
431 } else {
432 mac_desc = mac;
433 }
434
435 return mac_desc;
436 }
437
438 function renderCarrierStatusRow() {
439 if (dev && dev.Carrier !== undefined) {
440 return (
441 <DescriptionListGroup>
442 <DescriptionListTerm>{_("Carrier")}</DescriptionListTerm>
443 <DescriptionListDescription data-label="Carrier">
444 {dev.Carrier ? (dev.Speed ? cockpit.format_bits_per_sec(dev.Speed * 1e6) : _("Yes")) : _("No")}
445 </DescriptionListDescription>
446 </DescriptionListGroup>
447 );
448 } else
449 return null;
450 }
451
452 function renderActiveStatusRow() {
453 let state;
454
455 if (iface.MainConnection && iface.MainConnection.Groups.length > 0)
456 return null;
457
458 if (!dev)
459 state = _("Inactive");
460 else if (isManaged && dev.State != 100)
461 state = dev.StateText;
462 else
463 state = null;
464
465 const activeConnection = render_active_connection(dev, true, false);
466 return (
467 <DescriptionListGroup>
468 <DescriptionListTerm>{_("Status")}</DescriptionListTerm>
469 <DescriptionListDescription data-label="Status" className="networking-interface-status">
470 {[activeConnection, state].filter(val => val).join(", ")}
471 </DescriptionListDescription>
472 </DescriptionListGroup>
473 );
474 }
475
476 function renderConnectionSettingsRows(con, settings) {
477 if (!isManaged || !settings)
478 return [];
479
480 let group_settings = null;
481 if (con && con.Groups.length > 0)
482 group_settings = con.Groups[0].Settings;
483
484 function renderIpSettings(topic) {
485 const params = settings[topic];
486 const parts = [];
487
488 if (params.method != "manual")
489 parts.push(choice_title(get_ip_method_choices(topic), params.method, _("Unknown configuration")));
490
491 const addr_is_extra = (params.method != "manual");
492 const addrs = [];
493 params.address_data?.forEach(function (a) {
494 addrs.push(a.address + "/" + a.prefix);
495 });
496
497 if (addrs.length > 0)
498 parts.push(cockpit.format(addr_is_extra ? _("Additional address $val") : _("Address $val"),
499 { val: addrs.join(", ") }));
500
501 const gateway = params.gateway;
502 if (gateway && gateway != "0.0.0.0" && gateway != "::")
503 parts.push(cockpit.format(_("Gateway $gateway"), { gateway }));
504
505 const dns_is_extra = (!params["ignore-auto-dns"] && params.method != "manual");
506 if (params.dns_data?.length > 0)
507 parts.push(cockpit.format(dns_is_extra ? _("Additional DNS $val") : _("DNS $val"),
508 { val: params.dns_data.join(", ") }));
509 if (params.dns_search?.length > 0)
510 parts.push(cockpit.format(dns_is_extra ? _("Additional DNS search domains $val") : _("DNS search domains $val"),
511 { val: params.dns_search.join(", ") }));
512
513 return parts;
514 }
515
516 function renderAutoconnectRow() {
517 if (settings.connection.autoconnect !== undefined) {
518 return (
519 <DescriptionListGroup>
520 <DescriptionListTerm>{_("General")}</DescriptionListTerm>
521 <DescriptionListDescription data-label="General">
522 <Checkbox id="autoreconnect" isDisabled={!privileged}
523 onChange={(_event, checked) => {
524 settings.connection.autoconnect = checked;
525 settings_applier(model, dev, con)(settings);
526 }}
527 isChecked={settings.connection.autoconnect}
528 label={_("Connect automatically")} />
529 </DescriptionListDescription>
530 </DescriptionListGroup>
531 );
532 }
533 }
534
535 function renderSettingsRow(title, rows, configure) {
536 const link_text = [];
537 for (let i = 0; i < rows.length; i++) {
538 link_text.push(rows[i]);
539 if (i < rows.length - 1)
540 link_text.push(<br key={"break-" + i} />);
541 }
542
543 return (
544 <DescriptionListGroup>
545 <DescriptionListTerm>{title}</DescriptionListTerm>
546 <DescriptionListDescription data-label={title}>
547 {link_text.length
548 ? <span className="network-interface-settings-text">
549 {link_text}
550 </span>
551 : null}
552 {privileged
553 ? (typeof configure === 'function' ? <Button variant="link" isInline onClick={syn_click(model, configure)}>{_("edit")}</Button> : configure)
554 : null}
555 </DescriptionListDescription>
556 </DescriptionListGroup>
557 );
558 }
559
560 function renderIpSettingsRow(topic, title) {
561 if (!settings[topic])
562 return null;
563
564 const configure = <NetworkAction type={topic} iface={iface} connectionSettings={settings} />;
565 return renderSettingsRow(title, renderIpSettings(topic), configure);
566 }
567
568 function renderMtuSettingsRow() {
569 const rows = [];
570 const options = settings.ethernet;
571
572 if (!options)
573 return null;
574
575 function addRow(fmt, args) {
576 rows.push(cockpit.format(fmt, args));
577 }
578
579 if (options.mtu)
580 addRow("$mtu", options);
581 else
582 addRow(_("Automatic"), options);
583
584 const configure = <NetworkAction type="mtu" iface={iface} connectionSettings={settings} />;
585 return renderSettingsRow(_("MTU"), rows, configure);
586 }
587
588 function render_connection_link(con, key) {
589 return <span key={key}>
590 {
591 array_join(
592 con.Interfaces.map(iface =>
593 <Button variant="link" key={iface.Name}
594 isInline
595 onClick={() => cockpit.location.go([iface.Name])}>{iface.Name}</Button>),
596 ", ")
597 }
598 </span>;
599 }
600
601 function render_group() {
602 if (con && con.Groups.length > 0) {
603 return (
604 <DescriptionListGroup>
605 <DescriptionListTerm>{_("Group")}</DescriptionListTerm>
606 <DescriptionListDescription data-label="Group">
607 {array_join(con.Groups.map(render_connection_link), ", ")}
608 </DescriptionListDescription>
609 </DescriptionListGroup>
610 );
611 } else
612 return null;
613 }
614
615 function renderBondSettingsRow() {
616 const parts = [];
617 const rows = [];
618
619 if (!settings.bond)
620 return null;
621
622 const options = settings.bond.options;
623
624 parts.push(choice_title(bond_mode_choices, options.mode, options.mode));
625 if (options.arp_interval)
626 parts.push(_("ARP monitoring"));
627
628 if (parts.length > 0)
629 rows.push(parts.join(", "));
630
631 const configure = <NetworkAction type="bond" iface={iface} connectionSettings={settings} />;
632 return renderSettingsRow(_("Bond"), rows, configure);
633 }
634
635 function renderTeamSettingsRow() {
636 const parts = [];
637 const rows = [];
638
639 if (!settings.team)
640 return null;
641
642 const config = settings.team.config;
643
644 if (config === null)
645 parts.push(_("Broken configuration"));
646 else {
647 if (config.runner)
648 parts.push(choice_title(team_runner_choices, config.runner.name, config.runner.name));
649 if (config.link_watch && config.link_watch.name != "ethtool")
650 parts.push(choice_title(team_watch_choices, config.link_watch.name, config.link_watch.name));
651 }
652
653 if (parts.length > 0)
654 rows.push(parts.join(", "));
655
656 const configure = <NetworkAction type="team" iface={iface} connectionSettings={settings} />;
657 return renderSettingsRow(_("Team"), rows, configure);
658 }
659
660 function renderTeamPortSettingsRow() {
661 const parts = [];
662 const rows = [];
663
664 if (!settings.team_port)
665 return null;
666
667 /* Only "activebackup" and "lacp" team ports have
668 * something to configure.
669 */
670 if (!group_settings ||
671 !group_settings.team ||
672 !group_settings.team.config ||
673 !group_settings.team.config.runner ||
674 !(group_settings.team.config.runner.name == "activebackup" ||
675 group_settings.team.config.runner.name == "lacp"))
676 return null;
677
678 const config = settings.team_port.config;
679
680 if (config === null)
681 parts.push(_("Broken configuration"));
682
683 if (parts.length > 0)
684 rows.push(parts.join(", "));
685
686 const configure = <NetworkAction type="teamport" iface={iface} connectionSettings={settings} />;
687 return renderSettingsRow(_("Team port"), rows, configure);
688 }
689
690 function renderBridgeSettingsRow() {
691 const rows = [];
692 const options = settings.bridge;
693
694 if (!options)
695 return null;
696
697 function addRow(fmt, args) {
698 rows.push(cockpit.format(fmt, args));
699 }
700
701 if (options.stp) {
702 addRow(_("Spanning tree protocol"));
703 if (options.priority != 32768)
704 addRow(_("Priority $priority"), options);
705 if (options.forward_delay != 15)
706 addRow(_("Forward delay $forward_delay"), options);
707 if (options.hello_time != 2)
708 addRow(_("Hello time $hello_time"), options);
709 if (options.max_age != 20)
710 addRow(_("Maximum message age $max_age"), options);
711 }
712
713 const configure = <NetworkAction type="bridge" iface={iface} connectionSettings={settings} />;
714 return renderSettingsRow(_("Bridge"), rows, configure);
715 }
716
717 function renderBridgePortSettingsRow() {
718 const rows = [];
719 const options = settings.bridge_port;
720
721 if (!options)
722 return null;
723
724 function addRow(fmt, args) {
725 rows.push(cockpit.format(fmt, args));
726 }
727
728 if (options.priority != 32)
729 addRow(_("Priority $priority"), options);
730 if (options.path_cost != 100)
731 addRow(_("Path cost $path_cost"), options);
732 if (options.hairpin_mode)
733 addRow(_("Hairpin mode"));
734
735 const configure = <NetworkAction type="bridgeport" iface={iface} connectionSettings={settings} />;
736 return renderSettingsRow(_("Bridge port"), rows, configure);
737 }
738
739 function renderVlanSettingsRow() {
740 const rows = [];
741 const options = settings.vlan;
742
743 if (!options)
744 return null;
745
746 function addRow(fmt, args) {
747 rows.push(cockpit.format(fmt, args));
748 }
749
750 addRow(_("Parent $parent"), options);
751 addRow(_("ID $id"), options);
752
753 const configure = <NetworkAction type="vlan" iface={iface} connectionSettings={settings} />;
754 return renderSettingsRow(_("VLAN"), rows, configure);
755 }
756
757 function renderWireGuardSettingsRow() {
758 const rows = [];
759 const options = settings.wireguard;
760
761 if (!options) {
762 return null;
763 }
764
765 const configure = <NetworkAction type="wg" iface={iface} connectionSettings={settings} />;
766
767 return renderSettingsRow(_("WireGuard"), rows, configure);
768 }
769
770 return [
771 render_group(),
772 renderAutoconnectRow(),
773 renderIpSettingsRow("ipv4", _("IPv4")),
774 renderIpSettingsRow("ipv6", _("IPv6")),
775 renderMtuSettingsRow(),
776 renderVlanSettingsRow(),
777 renderBridgeSettingsRow(),
778 renderBridgePortSettingsRow(),
779 renderBondSettingsRow(),
780 renderTeamSettingsRow(),
781 renderTeamPortSettingsRow(),
782 renderWireGuardSettingsRow(),
783 ];
784 }
785
786 function renderWiFiNetworks() {
787 if (!dev || dev.DeviceType !== '802-11-wireless')
788 return null;
789
790 const accessPoints = dev.AccessPoints || [];
791 if (accessPoints.length === 0)
792 return null;
793
794 const activeSSID = dev.ActiveAccessPoint ? dev.ActiveAccessPoint.Ssid : null;
795
796 function forgetNetwork(ap) {
797 utils.debug("Forgetting network", ap.Ssid);
798
799 if (ap.Connection) {
800 ap.Connection.delete_()
801 .then(() => utils.debug("Forgot network", ap.Ssid))
802 .catch(show_unexpected_error);
803 }
804 }
805
806 async function connectToAP(ap) {
807 // we don't show a Connect button for hidden networks
808 cockpit.assert(ap.Ssid);
809 utils.debug("Connecting to", ap.Ssid);
810
811 try {
812 if (ap.Connection) {
813 // Activate existing connection (which already has password if needed)
814 utils.debug("Activating existing connection for", ap.Ssid);
815 await ap.Connection.activate(dev, ap);
816 utils.debug("Connection activation started for", ap.Ssid);
817 await dev.wait_connection(ap.Ssid);
818 utils.debug("Connected successfully to", ap.Ssid);
819 return;
820 }
821
822 // Create new connection
823 const isSecured = !!(ap.WpaFlags || ap.RsnFlags);
824
825 if (isSecured) {
826 // Show password dialog for secured networks
827 utils.debug("Showing password dialog for", ap.Ssid);
828 Dialogs.show(<WiFiConnectDialog dev={dev} ap={ap} ssid={ap.Ssid} model={model} />);
829 return;
830 }
831
832 // Create new connection for open networks
833 utils.debug("Creating new connection for", ap.Ssid);
834 const settings = {
835 connection: {
836 id: ap.Ssid,
837 type: "802-11-wireless",
838 autoconnect: true,
839 },
840 "802-11-wireless": {
841 ssid: utils.ssid_to_nm(ap.Ssid),
842 mode: "infrastructure",
843 }
844 };
845
846 // Pass null for specific_object - NM will find the right AP by SSID
847 await dev.activate_with_settings(settings, null);
848 utils.debug("Connection activation started for", ap.Ssid);
849 await dev.wait_connection(ap.Ssid);
850 utils.debug("Connected successfully to", ap.Ssid);
851 } catch (error) {
852 // Provide context-appropriate error message
853 const errorMsg = error.reason === 7 // NM_DEVICE_STATE_REASON_NO_SECRETS
854 ? _("Network password is not stored. Please forget and reconnect to this network.")
855 : error.toString();
856 show_error_dialog(
857 cockpit.format(_("Failed to connect to $0"), ap.Ssid),
858 errorMsg
859 );
860 }
861 }
862
863 const networkSort = (rows, direction, columnIndex) => {
864 // Separate hidden networks row from named networks rows
865 const hiddenRow = rows.find(r => r.props["data-hidden"]);
866 const namedRows = rows.filter(r => !r.props["data-hidden"]);
867
868 if (columnIndex === 0) {
869 // Network column: simple alphabetical sort, no special cases
870 const sorted = [...namedRows].sort((a, b) =>
871 a.columns[0].sortKey.localeCompare(b.columns[0].sortKey)
872 );
873 // Always put hidden networks at the bottom
874 const result = direction === SortByDirection.asc ? sorted : sorted.reverse();
875 return hiddenRow ? [...result, hiddenRow] : result;
876 } else {
877 // Signal column (default): group by connected > known > unknown, each sorted by signal strength
878
879 // Separate into groups
880 const activeRows = [];
881 const knownRows = [];
882 const unknownRows = [];
883
884 namedRows.forEach(r => {
885 const isActive = activeSSID && r.props["data-ssid"] === activeSSID;
886 if (isActive) {
887 activeRows.push(r);
888 } else if (r.props["data-known"]) {
889 knownRows.push(r);
890 } else {
891 unknownRows.push(r);
892 }
893 });
894
895 // Sort each group by stable signal order
896 // Build a map for O(1) lookups instead of O(n) indexOf
897 const orderMap = new Map();
898 stableAPOrder.current.forEach((mac, index) => orderMap.set(mac, index));
899
900 const sortByStableOrder = (a, b) => {
901 const aMAC = a.props.key;
902 const bMAC = b.props.key;
903 const aOrder = orderMap.get(aMAC);
904 const bOrder = orderMap.get(bMAC);
905 if (aOrder === undefined || bOrder === undefined) {
906 return a.columns[2].sortKey.localeCompare(b.columns[2].sortKey);
907 }
908 return aOrder - bOrder;
909 };
910
911 knownRows.sort(sortByStableOrder);
912 unknownRows.sort(sortByStableOrder);
913
914 // Concatenate groups
915 const result = [...activeRows, ...knownRows, ...unknownRows];
916 const sortedResult = direction === SortByDirection.asc ? result : result.reverse();
917 // Always put hidden networks at the bottom
918 return hiddenRow ? [...sortedResult, hiddenRow] : sortedResult;
919 }
920 };
921
922 // Filter by name
923 let filteredVisibleAPs = dev.visibleSsids;
924 if (networkSearch) {
925 const searchLower = networkSearch.toLowerCase();
926 filteredVisibleAPs = dev.visibleSsids.filter(ap => ap.Ssid.toLowerCase().includes(searchLower));
927 }
928
929 const rows = filteredVisibleAPs.map((ap, index) => {
930 const isActive = activeSSID && ap.Ssid === activeSSID;
931 const isSecured = !!(ap.WpaFlags || ap.RsnFlags);
932
933 const securityIcon = isSecured
934 ? <LockIcon aria-label={_("secured")} />
935 : <LockOpenIcon aria-label={_("open")} />;
936
937 const nameContent = (
938 <>
939 {ap.Ssid}
940 {isActive && <>{" "} <ConnectedIcon className="nm-icon-connected" /></>}
941 {!isActive && ap.Connection && <>{" "} <ThumbtackIcon className="nm-icon-known" /></>}
942 </>
943 );
944
945 const timestamp = ap.Connection?.Settings?.connection?.timestamp || 0;
946 const nameColumn = timestamp > 0
947 ? (
948 <Tooltip content={cockpit.format(_("Last connected: $0"), distanceToNow(timestamp * 1000))}>
949 <span>{nameContent}</span>
950 </Tooltip>
951 )
952 : nameContent;
953
954 const signalColumn = (
955 <Progress value={ap.Strength}
956 label={ap.Strength + "%"}
957 aria-label={_("Signal strength")}
958 size="sm" />
959 );
960
961 let actionColumn;
962 if (isActive) {
963 actionColumn = (
964 <Privileged allowed={privileged}
965 tooltipId={"wifi-disconnect-" + index}
966 excuse={_("Not permitted to disconnect network")}>
967 <Button variant="danger"
968 size="sm"
969 icon={<DisconnectedIcon />}
970 isDisabled={!privileged}
971 onClick={() => {
972 dev.disconnect()
973 .then(() => utils.debug("Disconnected successfully from", ap.Ssid))
974 .catch(show_unexpected_error);
975 }}
976 aria-label={_("Disconnect")}>
977 {_("Disconnect")}
978 </Button>
979 </Privileged>
980 );
981 } else {
982 actionColumn = (
983 <>
984 <Privileged allowed={privileged}
985 tooltipId={"wifi-connect-" + index}
986 excuse={_("Not permitted to connect to network")}>
987 <Button variant="secondary"
988 size="sm"
989 icon={<ConnectedIcon />}
990 isDisabled={!privileged}
991 onClick={() => connectToAP(ap)}
992 aria-label={_("Connect")}>
993 {_("Connect")}
994 </Button>
995 </Privileged>
996 {ap.Connection && (
997 <>
998 {" "}
999 <KebabDropdown
1000 toggleButtonId={"wifi-kebab-" + index}
1001 isDisabled={!privileged}
1002 dropdownItems={[
1003 <DropdownItem key="forget"
1004 className="pf-m-danger"
1005 onClick={() => forgetNetwork(ap)}
1006 aria-label={_("Forget")}>
1007 {_("Forget")}
1008 </DropdownItem>
1009 ]} />
1010 </>
1011 )}
1012 </>
1013 );
1014 }
1015
1016 return {
1017 columns: [
1018 { title: nameColumn, sortKey: ap.Ssid, header: true },
1019 { title: <>{securityIcon} {ap.Mode}</>, sortKey: ap.Mode },
1020 { title: signalColumn, sortKey: String(ap.Strength).padStart(3, '0') },
1021 { title: cockpit.format_bits_per_sec(ap.MaxBitrate * 1000) },
1022 { title: actionColumn },
1023 ],
1024 props: { key: ap.HwAddress, "data-ssid": ap.Ssid, "data-known": !!ap.Connection }
1025 };
1026 });
1027
1028 // Add aggregated hidden access points row at the bottom
1029 if (dev.hiddenAPCount > 0) {
1030 const hiddenLabel = cockpit.ngettext("$0 hidden network", "$0 hidden networks", dev.hiddenAPCount);
1031 rows.push({
1032 columns: [
1033 { title: cockpit.format(hiddenLabel, dev.hiddenAPCount), sortKey: "zzz-hidden", header: true },
1034 { title: "" },
1035 { title: "" },
1036 { title: "" },
1037 { title: "" },
1038 ],
1039 props: { key: "hidden-networks", "data-hidden": true }
1040 });
1041 }
1042
1043 return (
1044 <Card isPlain id="network-interface-wifi-networks">
1045 <CardHeader actions={{
1046 actions: (
1047 <Flex>
1048 {dev.visibleSsids.length >= 3 && (
1049 <FlexItem>
1050 <SearchInput
1051 placeholder={_("Filter")}
1052 value={networkSearch}
1053 onChange={(_event, value) => setNetworkSearch(value)}
1054 onClear={() => setNetworkSearch("")}
1055 />
1056 </FlexItem>
1057 )}
1058 <FlexItem>
1059 <Button variant="secondary"
1060 onClick={() => Dialogs.show(<WiFiConnectDialog dev={dev} model={model} />)}
1061 icon={<PlusIcon />}>
1062 {_("Connect to hidden network")}
1063 </Button>
1064 </FlexItem>
1065 <FlexItem>
1066 <Button variant="secondary"
1067 onClick={() => { setIsScanning(true); dev.request_scan() }}
1068 isDisabled={isScanning}
1069 icon={isScanning ? <Spinner size="md" /> : <RedoIcon />}>
1070 {_("Refresh")}
1071 </Button>
1072 </FlexItem>
1073 </Flex>
1074 )
1075 }}>
1076 <CardTitle component="h2">{_("Available networks")}</CardTitle>
1077 </CardHeader>
1078 <ListingTable aria-label={_("Available networks")}
1079 variant='compact'
1080 columns={[
1081 { title: _("Network"), header: true, sortable: true },
1082 { title: _("Mode") },
1083 { title: _("Signal"), sortable: true },
1084 { title: _("Rate") },
1085 { title: "", props: { screenReaderText: _("Actions") } },
1086 ]}
1087 sortBy={{ index: 2, direction: SortByDirection.asc }}
1088 sortMethod={networkSort}
1089 rows={rows} />
1090 </Card>
1091 );
1092 }
1093
1094 function renderConnectionMembers(con) {
1095 const memberIfaces = { };
1096 const members = { };
1097
1098 const rx_plot_data = {
1099 direct: "network.interface.in.bytes",
1100 internal: "network.interface.rx",
1101 units: "bytes",
1102 derive: "rate",
1103 factor: 8
1104 };
1105
1106 const tx_plot_data = {
1107 direct: "network.interface.out.bytes",
1108 internal: "network.interface.tx",
1109 units: "bytes",
1110 derive: "rate",
1111 factor: 8
1112 };
1113
1114 const cs = con && connection_settings(con);
1115 if (!con || (cs.type != "bond" && cs.type != "team" && cs.type != "bridge")) {
1116 plot_state.plot_instances('rx', rx_plot_data, [dev_name], true);
1117 plot_state.plot_instances('tx', tx_plot_data, [dev_name], true);
1118 return null;
1119 }
1120
1121 const plot_ifaces = [];
1122
1123 con.Members.forEach(member_con => {
1124 member_con.Interfaces.forEach(iface => {
1125 if (iface.MainConnection != member_con)
1126 return;
1127
1128 const dev = iface.Device;
1129
1130 /* Unmanaged devices shouldn't show up as members
1131 * but let's not take any chances.
1132 */
1133 if (dev && !is_managed(dev))
1134 return;
1135
1136 plot_ifaces.push(iface.Name);
1137 usage_monitor.add(iface.Name);
1138 members[iface.Name] = iface;
1139 memberIfaces[iface.Name] = true;
1140 });
1141 });
1142
1143 plot_state.plot_instances('rx', rx_plot_data, plot_ifaces, true);
1144 plot_state.plot_instances('tx', tx_plot_data, plot_ifaces, true);
1145
1146 const sorted_members = Object.keys(members).sort()
1147 .map(name => members[name]);
1148
1149 return (
1150 <NetworkInterfaceMembers members={sorted_members}
1151 memberIfaces={memberIfaces}
1152 interfaces={interfaces}
1153 iface={iface}
1154 usage_monitor={usage_monitor}
1155 privileged={privileged} />
1156 );
1157 }
1158
1159 function createGhostConnectionSettings() {
1160 const settings = {
1161 connection: {
1162 interface_name: iface.Name
1163 },
1164 ipv4: {
1165 method: "auto",
1166 address_data: [],
1167 dns_data: [],
1168 dns_search: [],
1169 route_data: []
1170 },
1171 ipv6: {
1172 method: "auto",
1173 address_data: [],
1174 dns_data: [],
1175 dns_search: [],
1176 route_data: []
1177 }
1178 };
1179 complete_settings(settings, dev);
1180 return settings;
1181 }
1182
1183 /* Disable the On/Off button for interfaces that we don't know about at all,
1184 and for devices that NM declares to be unavailable. Neither can be activated.
1185 */
1186
1187 let onoff;
1188 if (isManaged) {
1189 onoff = (
1190 <Privileged allowed={privileged}
1191 tooltipId="interface-switch"
1192 excuse={ _("Not permitted to configure network devices") }>
1193 <Switch id="interface-switch"
1194 isChecked={!!(dev && dev.ActiveConnection)}
1195 isDisabled={!iface || (dev && dev.State == 20) || !privileged}
1196 onChange={(_event, enable) => enable ? connect() : disconnect()}
1197 aria-label={_("Enable or disable the device")} />
1198 </Privileged>
1199 );
1200 }
1201
1202 const isDeletable = (iface && !dev) || (dev && (dev.DeviceType == 'bond' ||
1203 dev.DeviceType == 'team' ||
1204 dev.DeviceType == 'vlan' ||
1205 dev.DeviceType == 'bridge' ||
1206 dev.DeviceType == 'wireguard'));
1207
1208 const settingsRows = renderConnectionSettingsRows(iface.MainConnection, connectionSettings)
1209 .map((component, idx) => <React.Fragment key={idx}>{component}</React.Fragment>);
1210
1211 const anaconda = in_anaconda_mode();
1212
1213 return (
1214 <Page id="network-interface"
1215 data-test-wait={operationInProgress}
1216 className={"pf-m-no-sidebar" + (anaconda ? " anaconda" : "")}>
1217 <PageBreadcrumb hasBodyWrapper={false} stickyOnBreakpoint={{ default: "top" }}>
1218 <Breadcrumb>
1219 <BreadcrumbItem to='#/'>
1220 {_("Networking")}
1221 </BreadcrumbItem>
1222 <BreadcrumbItem isActive>
1223 {dev_name}
1224 </BreadcrumbItem>
1225 </Breadcrumb>
1226 </PageBreadcrumb>
1227 <PageSection hasBodyWrapper={false}>
1228 <NetworkPlots plot_state={plot_state} />
1229 </PageSection>
1230 <PageSection hasBodyWrapper={false}>
1231 <Gallery hasGutter>
1232 <Card isPlain className="network-interface-details">
1233 <CardHeader actions={{
1234 actions: (
1235 <>
1236 {isDeletable && isManaged &&
1237 <Button variant="danger"
1238 onClick={syn_click(model, deleteConnections)}
1239 id="network-interface-delete">
1240 {_("Delete")}
1241 </Button>}
1242 {onoff}
1243 </>
1244 ),
1245 }}>
1246 <CardTitle className="network-interface-details-title">
1247 <span id="network-interface-name">{dev_name}</span>
1248 <span id="network-interface-hw">{renderDesc()}</span>
1249 <span id="network-interface-mac">{renderMac()}</span>
1250 </CardTitle>
1251 </CardHeader>
1252 <CardBody>
1253 <DescriptionList id="network-interface-settings" className="network-interface-settings pf-m-horizontal-on-sm">
1254 {renderActiveStatusRow()}
1255 {renderCarrierStatusRow()}
1256 {settingsRows}
1257 </DescriptionList>
1258 </CardBody>
1259 { !isManaged
1260 ? <CardBody>
1261 {_("This device cannot be managed here.")}
1262 </CardBody>
1263 : null
1264 }
1265 </Card>
1266 {renderWiFiNetworks()}
1267 {renderConnectionMembers(iface.MainConnection)}
1268 </Gallery>
1269 </PageSection>
1270 </Page>
1271 );
1272 };