Debian Codegraph @

pkg/networkmanager/ip-settings.jsx

raw
1 /*
2 * Copyright (C) 2021 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import React, { useState, useContext, useEffect } from 'react';
7 import cockpit from 'cockpit';
8 import * as ipaddr from "ipaddr.js";
9 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
10 import { Flex } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
11 import { FormFieldGroup, FormFieldGroupHeader, FormGroup } from "@patternfly/react-core/dist/esm/components/Form/index.js";
12 import { FormSelect, FormSelectOption } from "@patternfly/react-core/dist/esm/components/FormSelect/index.js";
13 import { Grid } from "@patternfly/react-core/dist/esm/layouts/Grid/index.js";
14 import { Switch } from "@patternfly/react-core/dist/esm/components/Switch/index.js";
15 import { TextInput } from "@patternfly/react-core/dist/esm/components/TextInput/index.js";
16 import { Tooltip } from "@patternfly/react-core/dist/esm/components/Tooltip/index.js";
17
18 import { PlusIcon, TrashIcon } from '@patternfly/react-icons';
19
20 import { NetworkModal, dialogSave } from './dialogs-common.jsx';
21 import { ModelContext } from './model-context.jsx';
22 import { useDialogs } from "dialogs.jsx";
23 import { ip_first_usable_address, ip_network_address, validate_ip, ip_prefix_from_text, ip4_prefix_from_text } from './utils.js';
24
25 const _ = cockpit.gettext;
26
27 const ip_method_choices = [
28 { choice: 'auto', title: _("Automatic") },
29 { choice: 'dhcp', title: _("Automatic (DHCP only)") },
30 { choice: 'link-local', title: _("Link local") },
31 { choice: 'manual', title: _("Manual") },
32 { choice: 'ignore', title: _("Ignore") },
33 { choice: 'shared', title: _("Shared") },
34 { choice: 'disabled', title: _("Disabled") }
35 ];
36
37 const supported_ipv4_methods = ['auto', 'link-local', 'manual', 'shared', 'disabled'];
38 // NM only supports a subset of IPv4 and IPv6 methods for wireguard
39 // See: https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/blob/1.42.8/src/libnm-core-impl/nm-setting-wireguard.c#L1723
40 const wg_supported_ipv4_methods = ['manual', 'disabled'];
41 const wg_supported_ipv6_methods = ['link-local', 'manual', 'ignored', 'disabled'];
42
43 export function get_ip_method_choices(topic, device_type) {
44 if (topic === 'ipv4') {
45 if (device_type === 'wireguard')
46 return ip_method_choices.filter(item => wg_supported_ipv4_methods.includes(item.choice));
47 return ip_method_choices.filter(item => supported_ipv4_methods.includes(item.choice));
48 }
49
50 if (device_type === 'wireguard')
51 return ip_method_choices.filter(item => wg_supported_ipv6_methods.includes(item.choice));
52
53 // IPv6 supports all the choices
54 return ip_method_choices;
55 }
56
57 export const IpSettingsDialog = ({ topic, connection, dev, settings }) => {
58 const Dialogs = useDialogs();
59 const idPrefix = "network-ip-settings";
60 const model = useContext(ModelContext);
61
62 const params = settings[topic];
63 const [addresses, setAddresses] = useState(params.address_data);
64 const [defaultGateway, setDefaultGateway] = useState(params.gateway);
65 const [gatewaySetExplicitly, setGatewaySetExplicitly] = useState(false);
66 const [dialogError, setDialogError] = useState(undefined);
67 const [dns, setDns] = useState(params.dns_data || []);
68 const [dnsSearch, setDnsSearch] = useState(params.dns_search || []);
69 const [ignoreAutoDns, setIgnoreAutoDns] = useState(params.ignore_auto_dns);
70 const [ignoreAutoRoutes, setIgnoreAutoRoutes] = useState(params.ignore_auto_routes);
71 const [method, setMethod] = useState(params.method);
72 const [routes, setRoutes] = useState(params.route_data);
73
74 // The link local, shared, and disabled methods can't take any
75 // addresses, dns servers, or dns search domains. Routes,
76 // however, are ok, even for "disabled" and "ignored". But
77 // since that doesn't make sense, we remove routes as well for
78 // these methods.
79 const isOff = (method == "disabled" || method == "ignore");
80 const canHaveExtra = !(method == "link-local" || method == "shared" || isOff);
81
82 // The auto_*_btns only make sense when the address method
83 // is "auto" or "dhcp".
84 const canAuto = (method == "auto" || method == "dhcp");
85
86 const prefixText = (topic == "ipv4") ? _("Prefix length or netmask") : _("Prefix length");
87
88 useEffect(() => {
89 // The manual method needs at least one address
90 if (method == 'manual' && addresses.length == 0)
91 setAddresses([{ address: "", prefix: "" }]);
92
93 if (!canHaveExtra) {
94 setAddresses([]);
95 setDns([]);
96 setDnsSearch([]);
97 }
98
99 if (isOff)
100 setRoutes([]);
101 }, [method, addresses.length, canHaveExtra, isOff]);
102
103 const onSubmit = (_ev) => {
104 const createSettingsObj = () => ({
105 ...settings,
106 [topic]: {
107 ...settings[topic],
108 method,
109 address_data: addresses,
110 gateway: defaultGateway,
111 dns_data: dns,
112 dns_search: dnsSearch,
113 route_data: routes,
114 ignore_auto_dns: ignoreAutoDns,
115 ignore_auto_routes: ignoreAutoRoutes,
116 }
117 });
118
119 dialogSave({
120 model,
121 dev,
122 connection,
123 settings: createSettingsObj(),
124 setDialogError,
125 onClose: Dialogs.close,
126 });
127 };
128
129 const ipDefaultPrefix = (address) => {
130 if (address.kind() === "ipv6") {
131 return "64";
132 }
133
134 // use classful IPv4 prefixes when only host address is specified
135 const octets = address.octets;
136 if (octets[0] >= 0 && octets[0] <= 127) {
137 return "8";
138 } else if (octets[0] >= 128 && octets[0] <= 191) {
139 return "16";
140 } else if (octets[0] >= 192 && octets[0] <= 223) {
141 return "24";
142 }
143
144 return "";
145 };
146
147 const addressHelper = (address_str, prefix_str, i, prefixField) => {
148 const config = { address: address_str, prefix: prefix_str };
149
150 if (!validate_ip(address_str)) {
151 return config;
152 }
153
154 const address = ipaddr.parse(address_str);
155 if (address.kind() !== topic) {
156 return config;
157 }
158
159 if (prefix_str === "" && !prefixField) {
160 config.prefix = ipDefaultPrefix(address);
161 }
162
163 // prefix_str can contain prefix or IPv4 subnet mask
164 let numericPrefix;
165 try {
166 numericPrefix = (address.kind() === "ipv4") ? ip4_prefix_from_text(config.prefix) : ip_prefix_from_text(config.prefix);
167 } catch (_e) {
168 return config;
169 }
170
171 // do not set gateway for last three prefixes
172 // /30 and /126 only has two usable addresses
173 // /31 and /127 is a point-to-point link with no gateway
174 // /32 and /128 is a single host address
175 const maxPrefix = (address.kind() === "ipv4") ? 30 : 126;
176
177 if (i === 0 && numericPrefix < maxPrefix && !gatewaySetExplicitly) {
178 const netAddr = ip_network_address(address, numericPrefix);
179 const firstAddr = ip_first_usable_address(address, numericPrefix);
180 const addrCompactStr = address.toString();
181
182 // do not set the default gateway automatically if the host address
183 // is the first address in the subnet or network address
184 if (firstAddr !== null && addrCompactStr !== firstAddr &&
185 netAddr !== null && netAddr !== addrCompactStr) {
186 setDefaultGateway(firstAddr);
187 } else {
188 setDefaultGateway("");
189 }
190 } else if (!gatewaySetExplicitly) {
191 // reset
192 setDefaultGateway("");
193 }
194
195 return config;
196 };
197
198 const removeAddress = (i) => {
199 // also reset gateway when removing the last address
200 if (addresses.length === 1) {
201 setDefaultGateway("");
202 setGatewaySetExplicitly(false);
203 }
204
205 setAddresses(addresses.filter((_, index) => index !== i));
206 };
207
208 // Prefer device type if the device exists, otherwise fallback to a connection type
209 // of an existing connection that is down in which case the device may not exist.
210 const deviceType = dev?.DeviceType ?? connection?.Settings.connection.type;
211
212 return (
213 <NetworkModal dialogError={dialogError}
214 idPrefix={idPrefix}
215 onSubmit={onSubmit}
216 title={topic == "ipv4" ? _("IPv4 settings") : _("IPv6 settings")}
217 isFormHorizontal={false}
218 >
219 <FormFieldGroup
220 data-field='addresses'
221 header={
222 <FormFieldGroupHeader
223 titleText={{ text: _("Addresses") }}
224 actions={
225 <Flex>
226 <FormSelect className="network-ip-settings-method"
227 id={idPrefix + "-select-method"}
228 aria-label={_("Select method")}
229 onChange={(_, val) => setMethod(val)}
230 value={method}>
231 {get_ip_method_choices(topic, deviceType).map(choice => <FormSelectOption value={choice.choice} label={choice.title} key={choice.choice} />)}
232 </FormSelect>
233 <Tooltip content={_("Add address")}>
234 <Button icon={<PlusIcon />} variant="secondary"
235 isDisabled={!canHaveExtra}
236 onClick={() => setAddresses([...addresses, { address: "", prefix: "" }])}
237 id={idPrefix + "-address-add"}
238 aria-label={_("Add address")} />
239 </Tooltip>
240 </Flex>
241 }
242 />
243 }
244 >
245 <Grid hasGutter>
246 {addresses.map((address, i) => {
247 return (
248 <React.Fragment key={i}>
249 <FormGroup fieldId={idPrefix + "-address-" + i} label={_("Address")} className="pf-m-6-col-on-sm">
250 <TextInput id={idPrefix + "-address-" + i} value={address.address} onChange={(_event, value) => setAddresses(
251 addresses.map((item, index) =>
252 i === index
253 ? addressHelper(value, item.prefix, i, false)
254 : item
255 ))} />
256 </FormGroup>
257 <FormGroup fieldId={idPrefix + "-netmask-" + i} label={prefixText} className="pf-m-6-col-on-sm">
258 <TextInput id={idPrefix + "-netmask-" + i} value={address.prefix} onChange={(_event, value) => setAddresses(
259 addresses.map((item, index) =>
260 i === index
261 ? addressHelper(item.address, value, i, true)
262 : item
263 ))} />
264 </FormGroup>
265 <FormGroup className="pf-m-1-col-on-sm remove-button-group">
266 <Button variant='plain'
267 isDisabled={method == 'manual' && i == 0}
268 onClick={() => removeAddress(i)}
269 aria-label={_("Remove item")}
270 icon={<TrashIcon />} />
271 </FormGroup>
272 </React.Fragment>
273 );
274 })}
275 {addresses.length > 0 &&
276 <FormGroup fieldId={idPrefix + "-gateway"} label={_("Gateway")}>
277 <TextInput id={idPrefix + "-gateway"}
278 value={defaultGateway}
279 onChange={(_event, value) => { setDefaultGateway(value); setGatewaySetExplicitly(true) }}
280 />
281 </FormGroup>
282 }
283 </Grid>
284 </FormFieldGroup>
285 <FormFieldGroup
286 data-field='dns'
287 header={
288 <FormFieldGroupHeader
289 titleText={{ text: _("DNS") }}
290 actions={
291 <Flex alignItems={{ default: 'alignItemsCenter' }}>
292 <Switch
293 isChecked={!ignoreAutoDns}
294 isDisabled={!canAuto}
295 onChange={(_event, value) => setIgnoreAutoDns(!value)}
296 label={_("Automatic")} />
297 <Tooltip content={_("Add DNS server")}>
298 <Button icon={<PlusIcon />} variant="secondary"
299 isDisabled={!canHaveExtra}
300 onClick={() => setDns([...dns, ""])}
301 id={idPrefix + "-dns-add"}
302 aria-label={_("Add DNS server")} />
303 </Tooltip>
304 </Flex>
305 }
306 />
307 }
308 >
309 {dns.map((server, i) => {
310 return (
311 <Grid key={i} hasGutter>
312 <FormGroup fieldId={idPrefix + "-dns-server-" + i} label={_("Server")}>
313 <TextInput id={idPrefix + "-dns-server-" + i} value={server} onChange={(_event, value) => setDns(
314 dns.map((item, index) =>
315 i === index
316 ? value
317 : item
318 ))} />
319 </FormGroup>
320 <FormGroup className="pf-m-1-col-on-sm remove-button-group">
321 <Button variant='plain'
322 size="sm"
323 onClick={() => setDns(dns.filter((_, index) => index !== i))}
324 aria-label={_("Remove item")}
325 icon={<TrashIcon />} />
326 </FormGroup>
327 </Grid>
328 );
329 })}
330 </FormFieldGroup>
331 <FormFieldGroup
332 data-field='dns_search'
333 header={
334 <FormFieldGroupHeader
335 titleText={{ text: _("DNS search domains") }}
336 actions={
337 <Flex alignItems={{ default: 'alignItemsCenter' }}>
338 <Switch
339 isChecked={!ignoreAutoDns}
340 isDisabled={!canAuto}
341 onChange={(_event, value) => setIgnoreAutoDns(!value)}
342 label={_("Automatic")} />
343 <Tooltip content={_("Add search domain")}>
344 <Button icon={<PlusIcon />} variant="secondary"
345 isDisabled={!canHaveExtra}
346 onClick={() => setDnsSearch([...dnsSearch, ""])}
347 id={idPrefix + "-dns-search-add"}
348 aria-label={_("Add search domain")} />
349 </Tooltip>
350 </Flex>
351 }
352 />
353 }
354 >
355 {dnsSearch.map((domain, i) => {
356 return (
357 <Grid key={i} hasGutter>
358 <FormGroup fieldId={idPrefix + "-search-domain-" + i} label={_("Search domain")}>
359 <TextInput id={idPrefix + "-search-domain-" + i} value={domain} onChange={(_event, value) => setDnsSearch(
360 dnsSearch.map((item, index) =>
361 i === index
362 ? value
363 : item
364 ))} />
365 </FormGroup>
366 <FormGroup className="pf-m-1-col-on-sm remove-button-group">
367 <Button variant='plain'
368 size="sm"
369 onClick={() => setDnsSearch(dnsSearch.filter((_, index) => index !== i))}
370 aria-label={_("Remove item")}
371 icon={<TrashIcon />} />
372 </FormGroup>
373 </Grid>
374 );
375 })}
376 </FormFieldGroup>
377 <FormFieldGroup
378 data-field='routes'
379 header={
380 <FormFieldGroupHeader
381 titleText={{ text: _("Routes") }}
382 actions={
383 <Flex alignItems={{ default: 'alignItemsCenter' }}>
384 <Switch
385 isChecked={!ignoreAutoRoutes}
386 isDisabled={!canAuto}
387 onChange={(_event, value) => setIgnoreAutoRoutes(!value)}
388 label={_("Automatic")} />
389 <Tooltip content={_("Add route")}>
390 <Button icon={<PlusIcon />} variant="secondary"
391 isDisabled={isOff}
392 onClick={() => setRoutes([...routes, { dest: "", prefix: "", next_hop: "", metric: "" }])}
393 id={idPrefix + "-route-add"}
394 aria-label={_("Add route")} />
395 </Tooltip>
396 </Flex>
397 }
398 />
399 }
400 >
401 {routes.map((route, i) => {
402 return (
403 <Grid key={i} hasGutter>
404 <FormGroup fieldId={idPrefix + "-route-address-" + i} label={_("Address")} className="pf-m-3-col-on-sm">
405 <TextInput id={idPrefix + "-route-address-" + i} value={route.dest} onChange={(_event, value) => setRoutes(
406 routes.map((item, index) =>
407 i === index
408 ? { ...item, dest: value }
409 : item
410 ))} />
411 </FormGroup>
412 <FormGroup fieldId={idPrefix + "-route-netmask-" + i} label={prefixText} className="pf-m-4-col-on-sm">
413 <TextInput id={idPrefix + "-route-netmask-" + i} value={route.prefix} onChange={(_event, value) => setRoutes(
414 routes.map((item, index) =>
415 i === index
416 ? { ...item, prefix: value }
417 : item
418 ))} />
419 </FormGroup>
420 <FormGroup fieldId={idPrefix + "-route-gateway-" + i} label={_("Gateway")} className="pf-m-3-col-on-sm">
421 <TextInput id={idPrefix + "-route-gateway-" + i} value={route.next_hop} onChange={(_event, value) => setRoutes(
422 routes.map((item, index) =>
423 i === index
424 ? { ...item, next_hop: value }
425 : item
426 ))} />
427 </FormGroup>
428 <FormGroup fieldId={idPrefix + "-route-metric-" + i} label={_("Metric")} className="pf-m-2-col-on-sm">
429 <TextInput id={idPrefix + "-route-metric-" + i} value={route.metric} onChange={(_event, value) => setRoutes(
430 routes.map((item, index) =>
431 i === index
432 ? { ...item, metric: value }
433 : item
434 ))} />
435 </FormGroup>
436 <FormGroup className="pf-m-1-col-on-sm remove-button-group">
437 <Button variant='plain'
438 size="sm"
439 onClick={() => setRoutes(routes.filter((_, index) => index !== i))}
440 aria-label={_("Remove item")}
441 icon={<TrashIcon />} />
442 </FormGroup>
443 </Grid>
444 );
445 })}
446 </FormFieldGroup>
447 </NetworkModal>
448 );
449 };