luci-mod-network: interfaces.js: remove references to original MAC/MTU
[project/luci.git] / modules / luci-mod-network / htdocs / luci-static / resources / view / network / interfaces.js
1 'use strict';
2 'require view';
3 'require dom';
4 'require poll';
5 'require fs';
6 'require ui';
7 'require uci';
8 'require form';
9 'require network';
10 'require firewall';
11 'require tools.widgets as widgets';
12 'require tools.network as nettools';
13
14 var isReadonlyView = !L.hasViewPermission() || null;
15
16 function count_changes(section_id) {
17 var changes = ui.changes.changes, n = 0;
18
19 if (!L.isObject(changes))
20 return n;
21
22 if (Array.isArray(changes.network))
23 for (var i = 0; i < changes.network.length; i++)
24 n += (changes.network[i][1] == section_id);
25
26 if (Array.isArray(changes.dhcp))
27 for (var i = 0; i < changes.dhcp.length; i++)
28 n += (changes.dhcp[i][1] == section_id);
29
30 return n;
31 }
32
33 function render_iface(dev, alias) {
34 var type = dev ? dev.getType() : 'ethernet',
35 up = dev ? dev.isUp() : false;
36
37 return E('span', { class: 'cbi-tooltip-container' }, [
38 E('img', { 'class' : 'middle', 'src': L.resource('icons/%s%s.png').format(
39 alias ? 'alias' : type,
40 up ? '' : '_disabled') }),
41 E('span', { 'class': 'cbi-tooltip ifacebadge large' }, [
42 E('img', { 'src': L.resource('icons/%s%s.png').format(
43 type, up ? '' : '_disabled') }),
44 L.itemlist(E('span', { 'class': 'left' }), [
45 _('Type'), dev ? dev.getTypeI18n() : null,
46 _('Device'), dev ? dev.getName() : _('Not present'),
47 _('Connected'), up ? _('yes') : _('no'),
48 _('MAC'), dev ? dev.getMAC() : null,
49 _('RX'), dev ? '%.2mB (%d %s)'.format(dev.getRXBytes(), dev.getRXPackets(), _('Pkts.')) : null,
50 _('TX'), dev ? '%.2mB (%d %s)'.format(dev.getTXBytes(), dev.getTXPackets(), _('Pkts.')) : null
51 ])
52 ])
53 ]);
54 }
55
56 function render_status(node, ifc, with_device) {
57 var desc = null, c = [];
58
59 if (ifc.isDynamic())
60 desc = _('Virtual dynamic interface');
61 else if (ifc.isAlias())
62 desc = _('Alias Interface');
63 else if (!uci.get('network', ifc.getName()))
64 return L.itemlist(node, [
65 null, E('em', _('Interface is marked for deletion'))
66 ]);
67
68 var i18n = ifc.getI18n();
69 if (i18n)
70 desc = desc ? '%s (%s)'.format(desc, i18n) : i18n;
71
72 var changecount = with_device ? 0 : count_changes(ifc.getName()),
73 ipaddrs = changecount ? [] : ifc.getIPAddrs(),
74 ip6addrs = changecount ? [] : ifc.getIP6Addrs(),
75 errors = ifc.getErrors(),
76 maindev = ifc.getL3Device() || ifc.getDevice(),
77 macaddr = maindev ? maindev.getMAC() : null;
78
79 return L.itemlist(node, [
80 _('Protocol'), with_device ? null : (desc || '?'),
81 _('Device'), with_device ? (maindev ? maindev.getShortName() : E('em', _('Not present'))) : null,
82 _('Uptime'), (!changecount && ifc.isUp()) ? '%t'.format(ifc.getUptime()) : null,
83 _('MAC'), (!changecount && !ifc.isDynamic() && !ifc.isAlias() && macaddr) ? macaddr : null,
84 _('RX'), (!changecount && !ifc.isDynamic() && !ifc.isAlias() && maindev) ? '%.2mB (%d %s)'.format(maindev.getRXBytes(), maindev.getRXPackets(), _('Pkts.')) : null,
85 _('TX'), (!changecount && !ifc.isDynamic() && !ifc.isAlias() && maindev) ? '%.2mB (%d %s)'.format(maindev.getTXBytes(), maindev.getTXPackets(), _('Pkts.')) : null,
86 _('IPv4'), ipaddrs[0],
87 _('IPv4'), ipaddrs[1],
88 _('IPv4'), ipaddrs[2],
89 _('IPv4'), ipaddrs[3],
90 _('IPv4'), ipaddrs[4],
91 _('IPv6'), ip6addrs[0],
92 _('IPv6'), ip6addrs[1],
93 _('IPv6'), ip6addrs[2],
94 _('IPv6'), ip6addrs[3],
95 _('IPv6'), ip6addrs[4],
96 _('IPv6'), ip6addrs[5],
97 _('IPv6'), ip6addrs[6],
98 _('IPv6'), ip6addrs[7],
99 _('IPv6'), ip6addrs[8],
100 _('IPv6'), ip6addrs[9],
101 _('IPv6-PD'), changecount ? null : ifc.getIP6Prefix(),
102 _('Information'), with_device ? null : (ifc.get('auto') != '0' ? null : _('Not started on boot')),
103 _('Error'), errors ? errors[0] : null,
104 _('Error'), errors ? errors[1] : null,
105 _('Error'), errors ? errors[2] : null,
106 _('Error'), errors ? errors[3] : null,
107 _('Error'), errors ? errors[4] : null,
108 null, changecount ? E('a', {
109 href: '#',
110 click: L.bind(ui.changes.displayChanges, ui.changes)
111 }, _('Interface has %d pending changes').format(changecount)) : null
112 ]);
113 }
114
115 function render_modal_status(node, ifc) {
116 var dev = ifc ? (ifc.getDevice() || ifc.getL3Device() || ifc.getL3Device()) : null;
117
118 dom.content(node, [
119 E('img', {
120 'src': L.resource('icons/%s%s.png').format(dev ? dev.getType() : 'ethernet', (dev && dev.isUp()) ? '' : '_disabled'),
121 'title': dev ? dev.getTypeI18n() : _('Not present')
122 }),
123 ifc ? render_status(E('span'), ifc, true) : E('em', _('Interface not present or not connected yet.'))
124 ]);
125
126 return node;
127 }
128
129 function render_ifacebox_status(node, ifc) {
130 var dev = ifc.getL3Device() || ifc.getDevice(),
131 subdevs = dev ? dev.getPorts() : null,
132 c = [ render_iface(dev, ifc.isAlias()) ];
133
134 if (subdevs && subdevs.length) {
135 var sifs = [ ' (' ];
136
137 for (var j = 0; j < subdevs.length; j++)
138 sifs.push(render_iface(subdevs[j]));
139
140 sifs.push(')');
141
142 c.push(E('span', {}, sifs));
143 }
144
145 c.push(E('br'));
146 c.push(E('small', {}, ifc.isAlias() ? _('Alias of "%s"').format(ifc.isAlias())
147 : (dev ? dev.getName() : E('em', _('Not present')))));
148
149 dom.content(node, c);
150
151 return firewall.getZoneByNetwork(ifc.getName()).then(L.bind(function(zone) {
152 this.style.backgroundColor = zone ? zone.getColor() : '#EEEEEE';
153 this.title = zone ? _('Part of zone %q').format(zone.getName()) : _('No zone assigned');
154 }, node.previousElementSibling));
155 }
156
157 function iface_updown(up, id, ev, force) {
158 var row = document.querySelector('.cbi-section-table-row[data-sid="%s"]'.format(id)),
159 dsc = row.querySelector('[data-name="_ifacestat"] > div'),
160 btns = row.querySelectorAll('.cbi-section-actions .reconnect, .cbi-section-actions .down');
161
162 btns[+!up].blur();
163 btns[+!up].classList.add('spinning');
164
165 btns[0].disabled = true;
166 btns[1].disabled = true;
167
168 if (!up) {
169 L.resolveDefault(fs.exec_direct('/usr/libexec/luci-peeraddr')).then(function(res) {
170 var info = null; try { info = JSON.parse(res); } catch(e) {}
171
172 if (L.isObject(info) &&
173 Array.isArray(info.inbound_interfaces) &&
174 info.inbound_interfaces.filter(function(i) { return i == id })[0]) {
175
176 ui.showModal(_('Confirm disconnect'), [
177 E('p', _('You appear to be currently connected to the device via the "%h" interface. Do you really want to shut down the interface?').format(id)),
178 E('div', { 'class': 'right' }, [
179 E('button', {
180 'class': 'cbi-button cbi-button-neutral',
181 'click': function(ev) {
182 btns[1].classList.remove('spinning');
183 btns[1].disabled = false;
184 btns[0].disabled = false;
185
186 ui.hideModal();
187 }
188 }, _('Cancel')),
189 ' ',
190 E('button', {
191 'class': 'cbi-button cbi-button-negative important',
192 'click': function(ev) {
193 dsc.setAttribute('disconnect', '');
194 dom.content(dsc, E('em', _('Interface is shutting down...')));
195
196 ui.hideModal();
197 }
198 }, _('Disconnect'))
199 ])
200 ]);
201 }
202 else {
203 dsc.setAttribute('disconnect', '');
204 dom.content(dsc, E('em', _('Interface is shutting down...')));
205 }
206 });
207 }
208 else {
209 dsc.setAttribute(up ? 'reconnect' : 'disconnect', force ? 'force' : '');
210 dom.content(dsc, E('em', up ? _('Interface is reconnecting...') : _('Interface is shutting down...')));
211 }
212 }
213
214 function get_netmask(s, use_cfgvalue) {
215 var readfn = use_cfgvalue ? 'cfgvalue' : 'formvalue',
216 addrs = L.toArray(s[readfn](s.section, 'ipaddr')),
217 mask = s[readfn](s.section, 'netmask'),
218 firstsubnet = mask ? addrs[0] + '/' + mask : addrs.filter(function(a) { return a.indexOf('/') > 0 })[0];
219
220 if (firstsubnet == null)
221 return null;
222
223 var subnetmask = firstsubnet.split('/')[1];
224
225 if (!isNaN(subnetmask))
226 subnetmask = network.prefixToMask(+subnetmask);
227
228 return subnetmask;
229 }
230
231 var cbiRichListValue = form.ListValue.extend({
232 renderWidget: function(section_id, option_index, cfgvalue) {
233 var choices = this.transformChoices();
234 var widget = new ui.Dropdown((cfgvalue != null) ? cfgvalue : this.default, choices, {
235 id: this.cbid(section_id),
236 sort: this.keylist,
237 optional: true,
238 select_placeholder: this.select_placeholder || this.placeholder,
239 custom_placeholder: this.custom_placeholder || this.placeholder,
240 validate: L.bind(this.validate, this, section_id),
241 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
242 });
243
244 return widget.render();
245 },
246
247 value: function(value, title, description) {
248 if (description) {
249 form.ListValue.prototype.value.call(this, value, E([], [
250 E('span', { 'class': 'hide-open' }, [ title ]),
251 E('div', { 'class': 'hide-close', 'style': 'min-width:25vw' }, [
252 E('strong', [ title ]),
253 E('br'),
254 E('span', { 'style': 'white-space:normal' }, description)
255 ])
256 ]));
257 }
258 else {
259 form.ListValue.prototype.value.call(this, value, title);
260 }
261 }
262 });
263
264 return view.extend({
265 poll_status: function(map, networks) {
266 var resolveZone = null;
267
268 for (var i = 0; i < networks.length; i++) {
269 var ifc = networks[i],
270 row = map.querySelector('.cbi-section-table-row[data-sid="%s"]'.format(ifc.getName()));
271
272 if (row == null)
273 continue;
274
275 var dsc = row.querySelector('[data-name="_ifacestat"] > div'),
276 box = row.querySelector('[data-name="_ifacebox"] .ifacebox-body'),
277 btn1 = row.querySelector('.cbi-section-actions .reconnect'),
278 btn2 = row.querySelector('.cbi-section-actions .down'),
279 stat = document.querySelector('[id="%s-ifc-status"]'.format(ifc.getName())),
280 resolveZone = render_ifacebox_status(box, ifc),
281 disabled = ifc ? !ifc.isUp() : true,
282 dynamic = ifc ? ifc.isDynamic() : false;
283
284 if (dsc.hasAttribute('reconnect')) {
285 dom.content(dsc, E('em', _('Interface is starting...')));
286 }
287 else if (dsc.hasAttribute('disconnect')) {
288 dom.content(dsc, E('em', _('Interface is stopping...')));
289 }
290 else if (ifc.getProtocol() || uci.get('network', ifc.getName()) == null) {
291 render_status(dsc, ifc, false);
292 }
293 else if (!ifc.getProtocol()) {
294 var e = map.querySelector('[id="cbi-network-%s"] .cbi-button-edit'.format(ifc.getName()));
295 if (e) e.disabled = true;
296
297 var link = L.url('admin/system/opkg') + '?query=luci-proto';
298 dom.content(dsc, [
299 E('em', _('Unsupported protocol type.')), E('br'),
300 E('a', { href: link }, _('Install protocol extensions...'))
301 ]);
302 }
303 else {
304 dom.content(dsc, E('em', _('Interface not present or not connected yet.')));
305 }
306
307 if (stat) {
308 var dev = ifc.getDevice();
309 dom.content(stat, [
310 E('img', {
311 'src': L.resource('icons/%s%s.png').format(dev ? dev.getType() : 'ethernet', (dev && dev.isUp()) ? '' : '_disabled'),
312 'title': dev ? dev.getTypeI18n() : _('Not present')
313 }),
314 render_status(E('span'), ifc, true)
315 ]);
316 }
317
318 btn1.disabled = isReadonlyView || btn1.classList.contains('spinning') || btn2.classList.contains('spinning') || dynamic;
319 btn2.disabled = isReadonlyView || btn1.classList.contains('spinning') || btn2.classList.contains('spinning') || dynamic || disabled;
320 }
321
322 document.querySelectorAll('.port-status-device[data-device]').forEach(function(node) {
323 nettools.updateDevBadge(node, network.instantiateDevice(node.getAttribute('data-device')));
324 });
325
326 document.querySelectorAll('.port-status-link[data-device]').forEach(function(node) {
327 nettools.updatePortStatus(node, network.instantiateDevice(node.getAttribute('data-device')));
328 });
329
330 return Promise.all([ resolveZone, network.flushCache() ]);
331 },
332
333 load: function() {
334 return Promise.all([
335 network.getDSLModemType(),
336 network.getDevices(),
337 fs.lines('/etc/iproute2/rt_tables'),
338 L.resolveDefault(fs.read('/usr/lib/opkg/info/netifd.control')),
339 uci.changes()
340 ]);
341 },
342
343 interfaceBridgeWithIfnameSections: function() {
344 return uci.sections('network', 'interface').filter(function(ns) {
345 return ns.type == 'bridge' && !ns.ports && ns.ifname;
346 });
347 },
348
349 deviceWithIfnameSections: function() {
350 return uci.sections('network', 'device').filter(function(ns) {
351 return ns.type == 'bridge' && !ns.ports && ns.ifname;
352 });
353 },
354
355 interfaceWithIfnameSections: function() {
356 return uci.sections('network', 'interface').filter(function(ns) {
357 return !ns.device && ns.ifname;
358 });
359 },
360
361 handleBridgeMigration: function(ev) {
362 var tasks = [];
363
364 this.interfaceBridgeWithIfnameSections().forEach(function(ns) {
365 var device_name = 'br-' + ns['.name'];
366
367 tasks.push(uci.callAdd('network', 'device', null, {
368 'name': device_name,
369 'type': 'bridge',
370 'ports': L.toArray(ns.ifname),
371 'mtu': ns.mtu,
372 'macaddr': ns.macaddr,
373 'igmp_snooping': ns.igmp_snooping
374 }));
375
376 tasks.push(uci.callSet('network', ns['.name'], {
377 'type': '',
378 'ifname': '',
379 'mtu': '',
380 'macaddr': '',
381 'igmp_snooping': '',
382 'device': device_name
383 }));
384 });
385
386 return Promise.all(tasks)
387 .then(L.bind(ui.changes.init, ui.changes))
388 .then(L.bind(ui.changes.apply, ui.changes));
389 },
390
391 renderBridgeMigration: function() {
392 ui.showModal(_('Network bridge configuration migration'), [
393 E('p', _('The existing network configuration needs to be changed for LuCI to function properly.')),
394 E('p', _('Upon pressing "Continue", bridges configuration will be updated and the network will be restarted to apply the updated configuration.')),
395 E('div', { 'class': 'right' },
396 E('button', {
397 'class': 'btn cbi-button-action important',
398 'click': ui.createHandlerFn(this, 'handleBridgeMigration')
399 }, _('Continue')))
400 ]);
401 },
402
403 handleIfnameMigration: function(ev) {
404 var tasks = [];
405
406 this.deviceWithIfnameSections().forEach(function(ds) {
407 tasks.push(uci.callSet('network', ds['.name'], {
408 'ifname': '',
409 'ports': L.toArray(ds.ifname)
410 }));
411 });
412
413 this.interfaceWithIfnameSections().forEach(function(ns) {
414 tasks.push(uci.callSet('network', ns['.name'], {
415 'ifname': '',
416 'device': ns.ifname
417 }));
418 });
419
420 return Promise.all(tasks)
421 .then(L.bind(ui.changes.init, ui.changes))
422 .then(L.bind(ui.changes.apply, ui.changes));
423 },
424
425 renderIfnameMigration: function() {
426 ui.showModal(_('Network ifname configuration migration'), [
427 E('p', _('The existing network configuration needs to be changed for LuCI to function properly.')),
428 E('p', _('Upon pressing "Continue", ifname options will get renamed and the network will be restarted to apply the updated configuration.')),
429 E('div', { 'class': 'right' },
430 E('button', {
431 'class': 'btn cbi-button-action important',
432 'click': ui.createHandlerFn(this, 'handleIfnameMigration')
433 }, _('Continue')))
434 ]);
435 },
436
437 render: function(data) {
438 var netifdVersion = (data[3] || '').match(/Version: ([^\n]+)/);
439
440 if (netifdVersion && netifdVersion[1] >= "2021-05-26") {
441 if (this.interfaceBridgeWithIfnameSections().length)
442 return this.renderBridgeMigration();
443 else if (this.deviceWithIfnameSections().length || this.interfaceWithIfnameSections().length)
444 return this.renderIfnameMigration();
445 }
446
447 var dslModemType = data[0],
448 netDevs = data[1],
449 m, s, o;
450
451 var rtTables = data[2].map(function(l) {
452 var m = l.trim().match(/^(\d+)\s+(\S+)$/);
453 return m ? [ +m[1], m[2] ] : null;
454 }).filter(function(e) {
455 return e && e[0] > 0;
456 });
457
458 m = new form.Map('network');
459 m.tabbed = true;
460 m.chain('dhcp');
461
462 s = m.section(form.GridSection, 'interface', _('Interfaces'));
463 s.anonymous = true;
464 s.addremove = true;
465 s.addbtntitle = _('Add new interface...');
466
467 s.load = function() {
468 return Promise.all([
469 network.getNetworks(),
470 firewall.getZones()
471 ]).then(L.bind(function(data) {
472 this.networks = data[0];
473 this.zones = data[1];
474 }, this));
475 };
476
477 s.tab('general', _('General Settings'));
478 s.tab('advanced', _('Advanced Settings'));
479 s.tab('physical', _('Physical Settings'));
480 s.tab('brport', _('Bridge port specific options'));
481 s.tab('bridgevlan', _('Bridge VLAN filtering'));
482 s.tab('firewall', _('Firewall Settings'));
483 s.tab('dhcp', _('DHCP Server'));
484
485 s.cfgsections = function() {
486 return this.networks.map(function(n) { return n.getName() })
487 .filter(function(n) { return n != 'loopback' });
488 };
489
490 s.modaltitle = function(section_id) {
491 return _('Interfaces') + ' » ' + section_id.toUpperCase();
492 };
493
494 s.renderRowActions = function(section_id) {
495 var tdEl = this.super('renderRowActions', [ section_id, _('Edit') ]),
496 net = this.networks.filter(function(n) { return n.getName() == section_id })[0],
497 disabled = net ? !net.isUp() : true,
498 dynamic = net ? net.isDynamic() : false;
499
500 dom.content(tdEl.lastChild, [
501 E('button', {
502 'class': 'cbi-button cbi-button-neutral reconnect',
503 'click': iface_updown.bind(this, true, section_id),
504 'title': _('Reconnect this interface'),
505 'disabled': dynamic ? 'disabled' : null
506 }, _('Restart')),
507 E('button', {
508 'class': 'cbi-button cbi-button-neutral down',
509 'click': iface_updown.bind(this, false, section_id),
510 'title': _('Shutdown this interface'),
511 'disabled': (dynamic || disabled) ? 'disabled' : null
512 }, _('Stop')),
513 tdEl.lastChild.firstChild,
514 tdEl.lastChild.lastChild
515 ]);
516
517 if (!dynamic && net && !uci.get('network', net.getName())) {
518 tdEl.lastChild.childNodes[0].disabled = true;
519 tdEl.lastChild.childNodes[2].disabled = true;
520 tdEl.lastChild.childNodes[3].disabled = true;
521 }
522
523 return tdEl;
524 };
525
526 s.addModalOptions = function(s) {
527 var protoval = uci.get('network', s.section, 'proto'),
528 protoclass = protoval ? network.getProtocol(protoval) : null,
529 o, proto_select, proto_switch, type, stp, igmp, ss, so;
530
531 if (!protoval)
532 return;
533
534 return network.getNetwork(s.section).then(L.bind(function(ifc) {
535 var protocols = network.getProtocols();
536
537 protocols.sort(function(a, b) {
538 return a.getProtocol() > b.getProtocol();
539 });
540
541 o = s.taboption('general', form.DummyValue, '_ifacestat_modal', _('Status'));
542 o.modalonly = true;
543 o.cfgvalue = L.bind(function(section_id) {
544 var net = this.networks.filter(function(n) { return n.getName() == section_id })[0];
545
546 return render_modal_status(E('div', {
547 'id': '%s-ifc-status'.format(section_id),
548 'class': 'ifacebadge large'
549 }), net);
550 }, this);
551 o.write = function() {};
552
553
554 proto_select = s.taboption('general', form.ListValue, 'proto', _('Protocol'));
555 proto_select.modalonly = true;
556
557 proto_switch = s.taboption('general', form.Button, '_switch_proto');
558 proto_switch.modalonly = true;
559 proto_switch.title = _('Really switch protocol?');
560 proto_switch.inputtitle = _('Switch protocol');
561 proto_switch.inputstyle = 'apply';
562 proto_switch.onclick = L.bind(function(ev) {
563 s.map.save()
564 .then(L.bind(m.load, m))
565 .then(L.bind(m.render, m))
566 .then(L.bind(this.renderMoreOptionsModal, this, s.section));
567 }, this);
568
569 o = s.taboption('general', widgets.DeviceSelect, '_net_device', _('Device'));
570 o.ucioption = 'device';
571 o.nobridges = false;
572 o.optional = false;
573 o.network = ifc.getName();
574
575 o = s.taboption('general', form.Flag, 'auto', _('Bring up on boot'));
576 o.modalonly = true;
577 o.default = o.enabled;
578
579 if (L.hasSystemFeature('firewall')) {
580 o = s.taboption('firewall', widgets.ZoneSelect, '_zone', _('Create / Assign firewall-zone'), _('Choose the firewall zone you want to assign to this interface. Select <em>unspecified</em> to remove the interface from the associated zone or fill out the <em>custom</em> field to define a new zone and attach the interface to it.'));
581 o.network = ifc.getName();
582 o.optional = true;
583
584 o.cfgvalue = function(section_id) {
585 return firewall.getZoneByNetwork(ifc.getName()).then(function(zone) {
586 return (zone != null ? zone.getName() : null);
587 });
588 };
589
590 o.write = o.remove = function(section_id, value) {
591 return Promise.all([
592 firewall.getZoneByNetwork(ifc.getName()),
593 (value != null) ? firewall.getZone(value) : null
594 ]).then(function(data) {
595 var old_zone = data[0],
596 new_zone = data[1];
597
598 if (old_zone == null && new_zone == null && (value == null || value == ''))
599 return;
600
601 if (old_zone != null && new_zone != null && old_zone.getName() == new_zone.getName())
602 return;
603
604 if (old_zone != null)
605 old_zone.deleteNetwork(ifc.getName());
606
607 if (new_zone != null)
608 new_zone.addNetwork(ifc.getName());
609 else if (value != null)
610 return firewall.addZone(value).then(function(new_zone) {
611 new_zone.addNetwork(ifc.getName());
612 });
613 });
614 };
615 }
616
617 for (var i = 0; i < protocols.length; i++) {
618 proto_select.value(protocols[i].getProtocol(), protocols[i].getI18n());
619
620 if (protocols[i].getProtocol() != uci.get('network', s.section, 'proto'))
621 proto_switch.depends('proto', protocols[i].getProtocol());
622 }
623
624 if (L.hasSystemFeature('dnsmasq') || L.hasSystemFeature('odhcpd')) {
625 o = s.taboption('dhcp', form.SectionValue, '_dhcp', form.TypedSection, 'dhcp');
626
627 ss = o.subsection;
628 ss.uciconfig = 'dhcp';
629 ss.addremove = false;
630 ss.anonymous = true;
631
632 ss.tab('general', _('General Setup'));
633 ss.tab('advanced', _('Advanced Settings'));
634 ss.tab('ipv6', _('IPv6 Settings'));
635 ss.tab('ipv6-ra', _('IPv6 RA Settings'));
636
637 ss.filter = function(section_id) {
638 return (uci.get('dhcp', section_id, 'interface') == ifc.getName());
639 };
640
641 ss.renderSectionPlaceholder = function() {
642 return E('div', { 'class': 'cbi-section-create' }, [
643 E('p', _('No DHCP Server configured for this interface') + ' &#160; '),
644 E('button', {
645 'class': 'cbi-button cbi-button-add',
646 'title': _('Set up DHCP Server'),
647 'click': ui.createHandlerFn(this, function(section_id, ev) {
648 this.map.save(function() {
649 uci.add('dhcp', 'dhcp', section_id);
650 uci.set('dhcp', section_id, 'interface', section_id);
651
652 if (protoval == 'static') {
653 uci.set('dhcp', section_id, 'start', 100);
654 uci.set('dhcp', section_id, 'limit', 150);
655 uci.set('dhcp', section_id, 'leasetime', '12h');
656 }
657 else {
658 uci.set('dhcp', section_id, 'ignore', 1);
659 }
660 });
661 }, ifc.getName())
662 }, _('Set up DHCP Server'))
663 ]);
664 };
665
666 ss.taboption('general', form.Flag, 'ignore', _('Ignore interface'), _('Disable <abbr title="Dynamic Host Configuration Protocol">DHCP</abbr> for this interface.'));
667
668 if (protoval == 'static') {
669 so = ss.taboption('general', form.Value, 'start', _('Start'), _('Lowest leased address as offset from the network address.'));
670 so.optional = true;
671 so.datatype = 'or(uinteger,ip4addr("nomask"))';
672 so.default = '100';
673
674 so = ss.taboption('general', form.Value, 'limit', _('Limit'), _('Maximum number of leased addresses.'));
675 so.optional = true;
676 so.datatype = 'uinteger';
677 so.default = '150';
678
679 so = ss.taboption('general', form.Value, 'leasetime', _('Lease time'), _('Expiry time of leased addresses, minimum is 2 minutes (<code>2m</code>).'));
680 so.optional = true;
681 so.default = '12h';
682
683 so = ss.taboption('advanced', form.Flag, 'dynamicdhcp', _('Dynamic <abbr title="Dynamic Host Configuration Protocol">DHCP</abbr>'), _('Dynamically allocate DHCP addresses for clients. If disabled, only clients having static leases will be served.'));
684 so.default = so.enabled;
685
686 ss.taboption('advanced', form.Flag, 'force', _('Force'), _('Force DHCP on this network even if another server is detected.'));
687
688 // XXX: is this actually useful?
689 //ss.taboption('advanced', form.Value, 'name', _('Name'), _('Define a name for this network.'));
690
691 so = ss.taboption('advanced', form.Value, 'netmask', _('<abbr title="Internet Protocol Version 4">IPv4</abbr>-Netmask'), _('Override the netmask sent to clients. Normally it is calculated from the subnet that is served.'));
692 so.optional = true;
693 so.datatype = 'ip4addr';
694
695 so.render = function(option_index, section_id, in_table) {
696 this.placeholder = get_netmask(s, true);
697 return form.Value.prototype.render.apply(this, [ option_index, section_id, in_table ]);
698 };
699
700 so.validate = function(section_id, value) {
701 var uielem = this.getUIElement(section_id);
702 if (uielem)
703 uielem.setPlaceholder(get_netmask(s, false));
704 return form.Value.prototype.validate.apply(this, [ section_id, value ]);
705 };
706
707 ss.taboption('advanced', form.DynamicList, 'dhcp_option', _('DHCP-Options'), _('Define additional DHCP options, for example "<code>6,192.168.2.1,192.168.2.2</code>" which advertises different DNS servers to clients.'));
708 }
709
710
711 var has_other_master = uci.sections('dhcp', 'dhcp').filter(function(s) {
712 return (s.interface != ifc.getName() && s.master == '1');
713 })[0];
714
715 so = ss.taboption('ipv6', form.Flag , 'master', _('Designated master'));
716 so.readonly = has_other_master ? true : false;
717 so.description = has_other_master
718 ? _('Interface "%h" is already marked as designated master.').format(has_other_master.interface || has_other_master['.name'])
719 : _('Set this interface as master for RA and DHCPv6 relaying as well as NDP proxying.')
720 ;
721
722 so.validate = function(section_id, value) {
723 var hybrid_downstream_desc = _('Operate in <em>relay mode</em> if a designated master interface is configured and active, otherwise fall back to <em>server mode</em>.'),
724 ndp_downstream_desc = _('Operate in <em>relay mode</em> if a designated master interface is configured and active, otherwise disable <abbr title="Neighbour Discovery Protocol">NDP</abbr> proxying.'),
725 hybrid_master_desc = _('Operate in <em>relay mode</em> if an upstream IPv6 prefix is present, otherwise disable service.'),
726 checked = this.formvalue(section_id),
727 dhcpv6 = this.section.getOption('dhcpv6').getUIElement(section_id),
728 ndp = this.section.getOption('ndp').getUIElement(section_id),
729 ra = this.section.getOption('ra').getUIElement(section_id);
730
731 if (checked == '1' || protoval != 'static') {
732 dhcpv6.node.querySelector('li[data-value="server"]').setAttribute('unselectable', '');
733
734 if (dhcpv6.getValue() == 'server')
735 dhcpv6.setValue('hybrid');
736
737 ra.node.querySelector('li[data-value="server"]').setAttribute('unselectable', '');
738
739 if (ra.getValue() == 'server')
740 ra.setValue('hybrid');
741 }
742
743 if (checked == '1') {
744 dhcpv6.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = hybrid_master_desc;
745 ra.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = hybrid_master_desc;
746 ndp.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = hybrid_master_desc;
747 }
748 else {
749 if (protoval == 'static') {
750 dhcpv6.node.querySelector('li[data-value="server"]').removeAttribute('unselectable');
751 ra.node.querySelector('li[data-value="server"]').removeAttribute('unselectable');
752 }
753
754 dhcpv6.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = hybrid_downstream_desc;
755 ra.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = hybrid_downstream_desc;
756 ndp.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = ndp_downstream_desc ;
757 }
758
759 return true;
760 };
761
762
763 so = ss.taboption('ipv6', cbiRichListValue, 'ra', _('<abbr title="Router Advertisement">RA</abbr>-Service'),
764 _('Configures the operation mode of the <abbr title="Router Advertisement">RA</abbr> service on this interface.'));
765 so.value('', _('disabled'),
766 _('Do not send any <abbr title="Router Advertisement, ICMPv6 Type 134">RA</abbr> messages on this interface.'));
767 so.value('server', _('server mode'),
768 _('Send <abbr title="Router Advertisement, ICMPv6 Type 134">RA</abbr> messages advertising this device as IPv6 router.'));
769 so.value('relay', _('relay mode'),
770 _('Forward <abbr title="Router Advertisement, ICMPv6 Type 134">RA</abbr> messages received on the designated master interface to downstream interfaces.'));
771 so.value('hybrid', _('hybrid mode'), ' ');
772
773
774 so = ss.taboption('ipv6-ra', cbiRichListValue, 'ra_default', _('Default router'),
775 _('Configures the default router advertisement in <abbr title="Router Advertisement">RA</abbr> messages.'));
776 so.value('', _('automatic'),
777 _('Announce this device as default router if a local IPv6 default route is present.'));
778 so.value('1', _('on available prefix'),
779 _('Announce this device as default router if a public IPv6 prefix is available, regardless of local default route availability.'));
780 so.value('2', _('forced'),
781 _('Announce this device as default router regardless of whether a prefix or default route is present.'));
782 so.depends('ra', 'server');
783 so.depends({ ra: 'hybrid', master: '0' });
784
785 so = ss.taboption('ipv6-ra', form.Flag, 'ra_slaac', _('Enable <abbr title="Stateless Address Auto Config">SLAAC</abbr>'),
786 _('Set the autonomous address-configuration flag in the prefix information options of sent <abbr title="Router Advertisement">RA</abbr> messages. When enabled, clients will perform stateless IPv6 address autoconfiguration.'));
787 so.default = so.enabled;
788 so.depends('ra', 'server');
789 so.depends({ ra: 'hybrid', master: '0' });
790
791 so = ss.taboption('ipv6-ra', cbiRichListValue, 'ra_flags', _('<abbr title="Router Advertisement">RA</abbr> Flags'),
792 _('Specifies the flags sent in <abbr title="Router Advertisement">RA</abbr> messages, for example to instruct clients to request further information via stateful DHCPv6.'));
793 so.value('managed-config', _('managed config (M)'),
794 _('The <em>Managed address configuration</em> (M) flag indicates that IPv6 addresses are available via DHCPv6.'));
795 so.value('other-config', _('other config (O)'),
796 _('The <em>Other configuration</em> (O) flag indicates that other information, such as DNS servers, is available via DHCPv6.'));
797 so.value('home-agent', _('mobile home agent (H)'),
798 _('The <em>Mobile IPv6 Home Agent</em> (H) flag indicates that the device is also acting as Mobile IPv6 home agent on this link.'));
799 so.multiple = true;
800 so.select_placeholder = _('none');
801 so.depends('ra', 'server');
802 so.depends({ ra: 'hybrid', master: '0' });
803 so.cfgvalue = function(section_id) {
804 var flags = L.toArray(uci.get('dhcp', section_id, 'ra_flags'));
805 return flags.length ? flags : [ 'other-config' ];
806 };
807 so.remove = function(section_id) {
808 var existing = L.toArray(uci.get('dhcp', section_id, 'ra_flags'));
809 if (this.isActive(section_id)) {
810 if (existing.length != 1 || existing[0] != 'none')
811 uci.set('dhcp', section_id, 'ra_flags', [ 'none' ]);
812 }
813 else if (existing.length) {
814 uci.unset('dhcp', section_id, 'ra_flags');
815 }
816 };
817
818 so = ss.taboption('ipv6-ra', form.Value, 'ra_maxinterval', _('Max <abbr title="Router Advertisement">RA</abbr> interval'), _('Maximum time allowed between sending unsolicited <abbr title="Router Advertisement, ICMPv6 Type 134">RA</abbr>. Default is 600 seconds.'));
819 so.optional = true;
820 so.datatype = 'uinteger';
821 so.placeholder = '600';
822 so.depends('ra', 'server');
823 so.depends({ ra: 'hybrid', master: '0' });
824
825 so = ss.taboption('ipv6-ra', form.Value, 'ra_mininterval', _('Min <abbr title="Router Advertisement">RA</abbr> interval'), _('Minimum time allowed between sending unsolicited <abbr title="Router Advertisement, ICMPv6 Type 134">RA</abbr>. Default is 200 seconds.'));
826 so.optional = true;
827 so.datatype = 'uinteger';
828 so.placeholder = '200';
829 so.depends('ra', 'server');
830 so.depends({ ra: 'hybrid', master: '0' });
831
832 so = ss.taboption('ipv6-ra', form.Value, 'ra_lifetime', _('<abbr title="Router Advertisement">RA</abbr> Lifetime'), _('Router Lifetime published in <abbr title="Router Advertisement, ICMPv6 Type 134">RA</abbr> messages. Maximum is 9000 seconds.'));
833 so.optional = true;
834 so.datatype = 'range(0, 9000)';
835 so.placeholder = '1800';
836 so.depends('ra', 'server');
837 so.depends({ ra: 'hybrid', master: '0' });
838
839 so = ss.taboption('ipv6-ra', form.Value, 'ra_mtu', _('<abbr title="Router Advertisement">RA</abbr> MTU'), _('The <abbr title="Maximum Transmission Unit">MTU</abbr> to be published in <abbr title="Router Advertisement, ICMPv6 Type 134">RA</abbr> messages. Minimum is 1280 bytes.'));
840 so.optional = true;
841 so.datatype = 'range(1280, 65535)';
842 so.depends('ra', 'server');
843 so.depends({ ra: 'hybrid', master: '0' });
844 so.load = function(section_id) {
845 var dev = ifc.getL3Device(),
846 path = dev ? "/proc/sys/net/ipv6/conf/%s/mtu".format(dev.getName()) : null;
847
848 return Promise.all([
849 dev ? L.resolveDefault(fs.read(path), dev.getMTU()) : null,
850 this.super('load', [section_id])
851 ]).then(L.bind(function(res) {
852 this.placeholder = +res[0];
853
854 return res[1];
855 }, this));
856 };
857
858 so = ss.taboption('ipv6-ra', form.Value, 'ra_hoplimit', _('<abbr title="Router Advertisement">RA</abbr> Hop Limit'), _('The maximum hops to be published in <abbr title="Router Advertisement">RA</abbr> messages. Maximum is 255 hops.'));
859 so.optional = true;
860 so.datatype = 'range(0, 255)';
861 so.depends('ra', 'server');
862 so.depends({ ra: 'hybrid', master: '0' });
863 so.load = function(section_id) {
864 var dev = ifc.getL3Device(),
865 path = dev ? "/proc/sys/net/ipv6/conf/%s/hop_limit".format(dev.getName()) : null;
866
867 return Promise.all([
868 dev ? L.resolveDefault(fs.read(path), 64) : null,
869 this.super('load', [section_id])
870 ]).then(L.bind(function(res) {
871 this.placeholder = +res[0];
872
873 return res[1];
874 }, this));
875 };
876
877
878 so = ss.taboption('ipv6', cbiRichListValue, 'dhcpv6', _('DHCPv6-Service'),
879 _('Configures the operation mode of the DHCPv6 service on this interface.'));
880 so.value('', _('disabled'),
881 _('Do not offer DHCPv6 service on this interface.'));
882 so.value('server', _('server mode'),
883 _('Provide a DHCPv6 server on this interface and reply to DHCPv6 solicitations and requests.'));
884 so.value('relay', _('relay mode'),
885 _('Forward DHCPv6 messages between the designated master interface and downstream interfaces.'));
886 so.value('hybrid', _('hybrid mode'), ' ');
887
888
889 so = ss.taboption('ipv6', form.DynamicList, 'dns', _('Announced IPv6 DNS servers'),
890 _('Specifies a fixed list of IPv6 DNS server addresses to announce via DHCPv6. If left unspecified, the device will announce itself as IPv6 DNS server unless the <em>Local IPv6 DNS server</em> option is disabled.'));
891 so.datatype = 'ip6addr("nomask")'; /* restrict to IPv6 only for now since dnsmasq (DHCPv4) does not honour this option */
892 so.depends('ra', 'server');
893 so.depends({ ra: 'hybrid', master: '0' });
894 so.depends('dhcpv6', 'server');
895 so.depends({ dhcpv6: 'hybrid', master: '0' });
896
897 so = ss.taboption('ipv6', form.Flag, 'dns_service', _('Local IPv6 DNS server'),
898 _('Announce this device as IPv6 DNS server.'));
899 so.default = so.enabled;
900 so.depends({ ra: 'server', dns: /^$/ });
901 so.depends({ ra: 'hybrid', dns: /^$/, master: '0' });
902 so.depends({ dhcpv6: 'server', dns: /^$/ });
903 so.depends({ dhcpv6: 'hybrid', dns: /^$/, master: '0' });
904
905 so = ss.taboption('ipv6', form.DynamicList, 'domain', _('Announced DNS domains'),
906 _('Specifies a fixed list of DNS search domains to announce via DHCPv6. If left unspecified, the local device DNS search domain will be announced.'));
907 so.datatype = 'hostname';
908 so.depends('ra', 'server');
909 so.depends({ ra: 'hybrid', master: '0' });
910 so.depends('dhcpv6', 'server');
911 so.depends({ dhcpv6: 'hybrid', master: '0' });
912
913
914 so = ss.taboption('ipv6', cbiRichListValue, 'ndp', _('<abbr title="Neighbour Discovery Protocol">NDP</abbr>-Proxy'),
915 _('Configures the operation mode of the NDP proxy service on this interface.'));
916 so.value('', _('disabled'),
917 _('Do not proxy any <abbr title="Neighbour Discovery Protocol">NDP</abbr> packets.'));
918 so.value('relay', _('relay mode'),
919 _('Forward <abbr title="Neighbour Discovery Protocol">NDP</abbr> <abbr title="Neighbour Solicitation, Type 135">NS</abbr> and <abbr title="Neighbour Advertisement, Type 136">NA</abbr> messages between the designated master interface and downstream interfaces.'));
920 so.value('hybrid', _('hybrid mode'), ' ');
921
922
923 so = ss.taboption('ipv6', form.Flag, 'ndproxy_routing', _('Learn routes'), _('Setup routes for proxied IPv6 neighbours.'));
924 so.default = so.enabled;
925 so.depends('ndp', 'relay');
926 so.depends('ndp', 'hybrid');
927
928 so = ss.taboption('ipv6', form.Flag, 'ndproxy_slave', _('NDP-Proxy slave'), _('Set interface as NDP-Proxy external slave. Default is off.'));
929 so.depends({ ndp: 'relay', master: '0' });
930 so.depends({ ndp: 'hybrid', master: '0' });
931 }
932
933 ifc.renderFormOptions(s);
934
935 // Common interface options
936 o = nettools.replaceOption(s, 'advanced', form.Flag, 'defaultroute', _('Use default gateway'), _('If unchecked, no default route is configured'));
937 o.default = o.enabled;
938
939 if (protoval != 'static') {
940 o = nettools.replaceOption(s, 'advanced', form.Flag, 'peerdns', _('Use DNS servers advertised by peer'), _('If unchecked, the advertised DNS server addresses are ignored'));
941 o.default = o.enabled;
942 }
943
944 o = nettools.replaceOption(s, 'advanced', form.DynamicList, 'dns', _('Use custom DNS servers'));
945 if (protoval != 'static')
946 o.depends('peerdns', '0');
947 o.datatype = 'ipaddr';
948
949 o = nettools.replaceOption(s, 'advanced', form.DynamicList, 'dns_search', _('DNS search domains'));
950 if (protoval != 'static')
951 o.depends('peerdns', '0');
952 o.datatype = 'hostname';
953
954 o = nettools.replaceOption(s, 'advanced', form.Value, 'dns_metric', _('DNS weight'), _('The DNS server entries in the local resolv.conf are primarily sorted by the weight specified here'));
955 o.datatype = 'uinteger';
956 o.placeholder = '0';
957
958 o = nettools.replaceOption(s, 'advanced', form.Value, 'metric', _('Use gateway metric'));
959 o.datatype = 'uinteger';
960 o.placeholder = '0';
961
962 o = nettools.replaceOption(s, 'advanced', form.Value, 'ip4table', _('Override IPv4 routing table'));
963 o.datatype = 'or(uinteger, string)';
964 for (var i = 0; i < rtTables.length; i++)
965 o.value(rtTables[i][1], '%s (%d)'.format(rtTables[i][1], rtTables[i][0]));
966
967 o = nettools.replaceOption(s, 'advanced', form.Value, 'ip6table', _('Override IPv6 routing table'));
968 o.datatype = 'or(uinteger, string)';
969 for (var i = 0; i < rtTables.length; i++)
970 o.value(rtTables[i][1], '%s (%d)'.format(rtTables[i][1], rtTables[i][0]));
971
972 if (protoval == 'dhcpv6') {
973 o = nettools.replaceOption(s, 'advanced', form.Flag, 'sourcefilter', _('IPv6 source routing'), _('Automatically handle multiple uplink interfaces using source-based policy routing.'));
974 o.default = o.enabled;
975 }
976
977 o = nettools.replaceOption(s, 'advanced', form.Flag, 'delegate', _('Delegate IPv6 prefixes'), _('Enable downstream delegation of IPv6 prefixes available on this interface'));
978 o.default = o.enabled;
979
980 o = nettools.replaceOption(s, 'advanced', form.Value, 'ip6assign', _('IPv6 assignment length'), _('Assign a part of given length of every public IPv6-prefix to this interface'));
981 o.value('', _('disabled'));
982 o.value('64');
983 o.datatype = 'max(128)';
984
985 o = nettools.replaceOption(s, 'advanced', form.Value, 'ip6hint', _('IPv6 assignment hint'), _('Assign prefix parts using this hexadecimal subprefix ID for this interface.'));
986 o.placeholder = '0';
987 o.validate = function(section_id, value) {
988 if (value == null || value == '')
989 return true;
990
991 var n = parseInt(value, 16);
992
993 if (!/^(0x)?[0-9a-fA-F]+$/.test(value) || isNaN(n) || n >= 0xffffffff)
994 return _('Expecting a hexadecimal assignment hint');
995
996 return true;
997 };
998 for (var i = 33; i <= 64; i++)
999 o.depends('ip6assign', String(i));
1000
1001
1002 o = nettools.replaceOption(s, 'advanced', form.DynamicList, 'ip6class', _('IPv6 prefix filter'), _('If set, downstream subnets are only allocated from the given IPv6 prefix classes.'));
1003 o.value('local', 'local (%s)'.format(_('Local ULA')));
1004
1005 var prefixClasses = {};
1006
1007 this.networks.forEach(function(net) {
1008 var prefixes = net._ubus('ipv6-prefix');
1009 if (Array.isArray(prefixes)) {
1010 prefixes.forEach(function(pfx) {
1011 if (L.isObject(pfx) && typeof(pfx['class']) == 'string') {
1012 prefixClasses[pfx['class']] = prefixClasses[pfx['class']] || {};
1013 prefixClasses[pfx['class']][net.getName()] = true;
1014 }
1015 });
1016 }
1017 });
1018
1019 Object.keys(prefixClasses).sort().forEach(function(c) {
1020 var networks = Object.keys(prefixClasses[c]).sort().join(', ');
1021 o.value(c, (c != networks) ? '%s (%s)'.format(c, networks) : c);
1022 });
1023
1024
1025 o = nettools.replaceOption(s, 'advanced', form.Value, 'ip6ifaceid', _('IPv6 suffix'), _("Optional. Allowed values: 'eui64', 'random', fixed value like '::1' or '::1:2'. When IPv6 prefix (like 'a:b:c:d::') is received from a delegating server, use the suffix (like '::1') to form the IPv6 address ('a:b:c:d::1') for the interface."));
1026 o.datatype = 'ip6hostid';
1027 o.placeholder = '::1';
1028
1029 o = nettools.replaceOption(s, 'advanced', form.Value, 'ip6weight', _('IPv6 preference'), _('When delegating prefixes to multiple downstreams, interfaces with a higher preference value are considered first when allocating subnets.'));
1030 o.datatype = 'uinteger';
1031 o.placeholder = '0';
1032
1033 for (var i = 0; i < s.children.length; i++) {
1034 o = s.children[i];
1035
1036 switch (o.option) {
1037 case 'proto':
1038 case 'auto':
1039 case '_dhcp':
1040 case '_zone':
1041 case '_switch_proto':
1042 case '_ifacestat_modal':
1043 continue;
1044
1045 case 'igmp_snooping':
1046 case 'stp':
1047 case 'type':
1048 case '_net_device':
1049 var deps = [];
1050 for (var j = 0; j < protocols.length; j++) {
1051 if (!protocols[j].isVirtual()) {
1052 if (o.deps.length)
1053 for (var k = 0; k < o.deps.length; k++)
1054 deps.push(Object.assign({ proto: protocols[j].getProtocol() }, o.deps[k]));
1055 else
1056 deps.push({ proto: protocols[j].getProtocol() });
1057 }
1058 }
1059 o.deps = deps;
1060 break;
1061
1062 default:
1063 if (o.deps.length)
1064 for (var j = 0; j < o.deps.length; j++)
1065 o.deps[j].proto = protoval;
1066 else
1067 o.depends('proto', protoval);
1068 }
1069 }
1070
1071 this.activeSection = s.section;
1072 }, this));
1073 };
1074
1075 s.handleModalCancel = function(/* ... */) {
1076 var type = uci.get('network', this.activeSection || this.addedSection, 'type'),
1077 device = (type == 'bridge') ? 'br-%s'.format(this.activeSection || this.addedSection) : null;
1078
1079 uci.sections('network', 'bridge-vlan', function(bvs) {
1080 if (device != null && bvs.device == device)
1081 uci.remove('network', bvs['.name']);
1082 });
1083
1084 return form.GridSection.prototype.handleModalCancel.apply(this, arguments);
1085 };
1086
1087 s.handleAdd = function(ev) {
1088 var m2 = new form.Map('network'),
1089 s2 = m2.section(form.NamedSection, '_new_'),
1090 protocols = network.getProtocols(),
1091 proto, name, device;
1092
1093 protocols.sort(function(a, b) {
1094 return a.getProtocol() > b.getProtocol();
1095 });
1096
1097 s2.render = function() {
1098 return Promise.all([
1099 {},
1100 this.renderUCISection('_new_')
1101 ]).then(this.renderContents.bind(this));
1102 };
1103
1104 name = s2.option(form.Value, 'name', _('Name'));
1105 name.rmempty = false;
1106 name.datatype = 'uciname';
1107 name.placeholder = _('New interface name…');
1108 name.validate = function(section_id, value) {
1109 if (uci.get('network', value) != null)
1110 return _('The interface name is already used');
1111
1112 var pr = network.getProtocol(proto.formvalue(section_id), value),
1113 ifname = pr.isVirtual() ? '%s-%s'.format(pr.getProtocol(), value) : 'br-%s'.format(value);
1114
1115 if (value.length > 15)
1116 return _('The interface name is too long');
1117
1118 return true;
1119 };
1120
1121 proto = s2.option(form.ListValue, 'proto', _('Protocol'));
1122 proto.validate = name.validate;
1123
1124 device = s2.option(widgets.DeviceSelect, 'device', _('Device'));
1125 device.noaliases = false;
1126 device.optional = false;
1127
1128 for (var i = 0; i < protocols.length; i++) {
1129 proto.value(protocols[i].getProtocol(), protocols[i].getI18n());
1130
1131 if (!protocols[i].isVirtual())
1132 device.depends('proto', protocols[i].getProtocol());
1133 }
1134
1135 m2.render().then(L.bind(function(nodes) {
1136 ui.showModal(_('Add new interface...'), [
1137 nodes,
1138 E('div', { 'class': 'right' }, [
1139 E('button', {
1140 'class': 'btn',
1141 'click': ui.hideModal
1142 }, _('Cancel')), ' ',
1143 E('button', {
1144 'class': 'cbi-button cbi-button-positive important',
1145 'click': ui.createHandlerFn(this, function(ev) {
1146 var nameval = name.isValid('_new_') ? name.formvalue('_new_') : null,
1147 protoval = proto.isValid('_new_') ? proto.formvalue('_new_') : null,
1148 protoclass = protoval ? network.getProtocol(protoval, nameval) : null;
1149
1150 if (nameval == null || protoval == null || nameval == '' || protoval == '')
1151 return;
1152
1153 return protoclass.isCreateable(nameval).then(function(checkval) {
1154 if (checkval != null) {
1155 ui.addNotification(null,
1156 E('p', _('New interface for "%s" can not be created: %s').format(protoclass.getI18n(), checkval)));
1157 ui.hideModal();
1158 return;
1159 }
1160
1161 return m.save(function() {
1162 var section_id = uci.add('network', 'interface', nameval);
1163
1164 protoclass.set('proto', protoval);
1165 protoclass.addDevice(device.formvalue('_new_'));
1166
1167 m.children[0].addedSection = section_id;
1168
1169 ui.hideModal();
1170 ui.showModal(null, E('p', { 'class': 'spinning' }, [ _('Loading data…') ]));
1171 }).then(L.bind(m.children[0].renderMoreOptionsModal, m.children[0], nameval));
1172 });
1173 })
1174 }, _('Create interface'))
1175 ])
1176 ], 'cbi-modal');
1177
1178 nodes.querySelector('[id="%s"] input[type="text"]'.format(name.cbid('_new_'))).focus();
1179 }, this));
1180 };
1181
1182 s.handleRemove = function(section_id, ev) {
1183 return network.deleteNetwork(section_id).then(L.bind(function(section_id, ev) {
1184 return form.GridSection.prototype.handleRemove.apply(this, [section_id, ev]);
1185 }, this, section_id, ev));
1186 };
1187
1188 o = s.option(form.DummyValue, '_ifacebox');
1189 o.modalonly = false;
1190 o.textvalue = function(section_id) {
1191 var net = this.section.networks.filter(function(n) { return n.getName() == section_id })[0],
1192 zone = net ? this.section.zones.filter(function(z) { return !!z.getNetworks().filter(function(n) { return n == section_id })[0] })[0] : null;
1193
1194 if (!net)
1195 return;
1196
1197 var node = E('div', { 'class': 'ifacebox' }, [
1198 E('div', {
1199 'class': 'ifacebox-head',
1200 'style': firewall.getZoneColorStyle(zone),
1201 'title': zone ? _('Part of zone %q').format(zone.getName()) : _('No zone assigned')
1202 }, E('strong', net.getName().toUpperCase())),
1203 E('div', {
1204 'class': 'ifacebox-body',
1205 'id': '%s-ifc-devices'.format(section_id),
1206 'data-network': section_id
1207 }, [
1208 E('img', {
1209 'src': L.resource('icons/ethernet_disabled.png'),
1210 'style': 'width:16px; height:16px'
1211 }),
1212 E('br'), E('small', '?')
1213 ])
1214 ]);
1215
1216 render_ifacebox_status(node.childNodes[1], net);
1217
1218 return node;
1219 };
1220
1221 o = s.option(form.DummyValue, '_ifacestat');
1222 o.modalonly = false;
1223 o.textvalue = function(section_id) {
1224 var net = this.section.networks.filter(function(n) { return n.getName() == section_id })[0];
1225
1226 if (!net)
1227 return;
1228
1229 var node = E('div', { 'id': '%s-ifc-description'.format(section_id) });
1230
1231 render_status(node, net, false);
1232
1233 return node;
1234 };
1235
1236 o = s.taboption('advanced', form.Flag, 'delegate', _('Use builtin IPv6-management'));
1237 o.modalonly = true;
1238 o.default = o.enabled;
1239
1240 o = s.taboption('advanced', form.Flag, 'force_link', _('Force link'), _('Set interface properties regardless of the link carrier (If set, carrier sense events do not invoke hotplug handlers).'));
1241 o.modalonly = true;
1242 o.defaults = {
1243 '1': [{ proto: 'static' }],
1244 '0': []
1245 };
1246
1247
1248 // Device configuration
1249 s = m.section(form.GridSection, 'device', _('Devices'));
1250 s.addremove = true;
1251 s.anonymous = true;
1252 s.addbtntitle = _('Add device configuration…');
1253
1254 s.cfgsections = function() {
1255 var sections = uci.sections('network', 'device'),
1256 section_ids = sections.sort(function(a, b) { return a.name > b.name }).map(function(s) { return s['.name'] });
1257
1258 for (var i = 0; i < netDevs.length; i++) {
1259 if (sections.filter(function(s) { return s.name == netDevs[i].getName() }).length)
1260 continue;
1261
1262 if (netDevs[i].getType() == 'wifi' && !netDevs[i].isUp())
1263 continue;
1264
1265 /* Unless http://lists.openwrt.org/pipermail/openwrt-devel/2020-July/030397.html is implemented,
1266 we cannot properly redefine bridges as devices, so filter them away for now... */
1267
1268 var m = netDevs[i].isBridge() ? netDevs[i].getName().match(/^br-([A-Za-z0-9_]+)$/) : null,
1269 s = m ? uci.get('network', m[1]) : null;
1270
1271 if (s && s['.type'] == 'interface' && s.type == 'bridge')
1272 continue;
1273
1274 section_ids.push('dev:%s'.format(netDevs[i].getName()));
1275 }
1276
1277 return section_ids;
1278 };
1279
1280 s.renderMoreOptionsModal = function(section_id, ev) {
1281 var m = section_id.match(/^dev:(.+)$/);
1282
1283 if (m) {
1284 var devtype = getDevType(section_id);
1285
1286 section_id = uci.add('network', 'device');
1287
1288 uci.set('network', section_id, 'name', m[1]);
1289 uci.set('network', section_id, 'type', (devtype != 'ethernet') ? devtype : null);
1290
1291 this.addedSection = section_id;
1292 }
1293
1294 return this.super('renderMoreOptionsModal', [section_id, ev]);
1295 };
1296
1297 s.renderRowActions = function(section_id) {
1298 var trEl = this.super('renderRowActions', [ section_id, _('Configure…') ]),
1299 deleteBtn = trEl.querySelector('button:last-child');
1300
1301 deleteBtn.firstChild.data = _('Unconfigure');
1302 deleteBtn.setAttribute('title', _('Remove related device settings from the configuration'));
1303 deleteBtn.disabled = section_id.match(/^dev:/) ? true : null;
1304
1305 return trEl;
1306 };
1307
1308 s.modaltitle = function(section_id) {
1309 var m = section_id.match(/^dev:(.+)$/),
1310 name = m ? m[1] : uci.get('network', section_id, 'name');
1311
1312 return name ? '%s: %q'.format(getDevTypeDesc(section_id), name) : _('Add device configuration');
1313 };
1314
1315 s.addModalOptions = function(s) {
1316 var isNew = (uci.get('network', s.section, 'name') == null),
1317 dev = getDevice(s.section);
1318
1319 nettools.addDeviceOptions(s, dev, isNew);
1320 };
1321
1322 s.handleModalCancel = function(map /*, ... */) {
1323 var name = uci.get('network', this.addedSection, 'name')
1324
1325 uci.sections('network', 'bridge-vlan', function(bvs) {
1326 if (name != null && bvs.device == name)
1327 uci.remove('network', bvs['.name']);
1328 });
1329
1330 if (map.addedVLANs)
1331 for (var i = 0; i < map.addedVLANs.length; i++)
1332 uci.remove('network', map.addedVLANs[i]);
1333
1334 return form.GridSection.prototype.handleModalCancel.apply(this, arguments);
1335 };
1336
1337 s.handleRemove = function(section_id /*, ... */) {
1338 var name = uci.get('network', section_id, 'name'),
1339 type = uci.get('network', section_id, 'type');
1340
1341 if (name != null && type == 'bridge') {
1342 uci.sections('network', 'bridge-vlan', function(bvs) {
1343 if (bvs.device == name)
1344 uci.remove('network', bvs['.name']);
1345 });
1346 }
1347
1348 return form.GridSection.prototype.handleRemove.apply(this, arguments);
1349 };
1350
1351 function getDevice(section_id) {
1352 var m = section_id.match(/^dev:(.+)$/),
1353 name = m ? m[1] : uci.get('network', section_id, 'name');
1354
1355 return netDevs.filter(function(d) { return d.getName() == name })[0];
1356 }
1357
1358 function getDevType(section_id) {
1359 var dev = getDevice(section_id),
1360 cfg = uci.get('network', section_id),
1361 type = cfg ? (uci.get('network', section_id, 'type') || 'ethernet') : (dev ? dev.getType() : '');
1362
1363 switch (type) {
1364 case '':
1365 return null;
1366
1367 case 'vlan':
1368 case '8021q':
1369 return '8021q';
1370
1371 case '8021ad':
1372 return '8021ad';
1373
1374 case 'bridge':
1375 return 'bridge';
1376
1377 case 'tunnel':
1378 return 'tunnel';
1379
1380 case 'macvlan':
1381 return 'macvlan';
1382
1383 case 'veth':
1384 return 'veth';
1385
1386 case 'wifi':
1387 case 'alias':
1388 case 'switch':
1389 case 'ethernet':
1390 default:
1391 return 'ethernet';
1392 }
1393 }
1394
1395 function getDevTypeDesc(section_id) {
1396 switch (getDevType(section_id) || '') {
1397 case '':
1398 return E('em', [ _('Device not present') ]);
1399
1400 case '8021q':
1401 return _('VLAN (802.1q)');
1402
1403 case '8021ad':
1404 return _('VLAN (802.1ad)');
1405
1406 case 'bridge':
1407 return _('Bridge device');
1408
1409 case 'tunnel':
1410 return _('Tunnel device');
1411
1412 case 'macvlan':
1413 return _('MAC VLAN');
1414
1415 case 'veth':
1416 return _('Virtual Ethernet');
1417
1418 default:
1419 return _('Network device');
1420 }
1421 }
1422
1423 o = s.option(form.DummyValue, 'name', _('Device'));
1424 o.modalonly = false;
1425 o.textvalue = function(section_id) {
1426 var dev = getDevice(section_id),
1427 ext = section_id.match(/^dev:/),
1428 icon = render_iface(dev);
1429
1430 if (ext)
1431 icon.querySelector('img').style.opacity = '.5';
1432
1433 return E('span', { 'class': 'ifacebadge' }, [
1434 icon,
1435 E('span', { 'style': ext ? 'opacity:.5' : null }, [
1436 dev ? dev.getName() : (uci.get('network', section_id, 'name') || '?')
1437 ])
1438 ]);
1439 };
1440
1441 o = s.option(form.DummyValue, 'type', _('Type'));
1442 o.textvalue = getDevTypeDesc;
1443 o.modalonly = false;
1444
1445 o = s.option(form.DummyValue, 'macaddr', _('MAC Address'));
1446 o.modalonly = false;
1447 o.textvalue = function(section_id) {
1448 var dev = getDevice(section_id),
1449 val = uci.get('network', section_id, 'macaddr'),
1450 mac = dev ? dev.getMAC() : null;
1451
1452 return val ? E('strong', {
1453 'data-tooltip': _('The value is overridden by configuration.')
1454 }, [ val.toUpperCase() ]) : (mac || '-');
1455 };
1456
1457 o = s.option(form.DummyValue, 'mtu', _('MTU'));
1458 o.modalonly = false;
1459 o.textvalue = function(section_id) {
1460 var dev = getDevice(section_id),
1461 val = uci.get('network', section_id, 'mtu'),
1462 mtu = dev ? dev.getMTU() : null;
1463
1464 return val ? E('strong', {
1465 'data-tooltip': _('The value is overridden by configuration.')
1466 }, [ val ]) : (mtu || '-').toString();
1467 };
1468
1469 s = m.section(form.TypedSection, 'globals', _('Global network options'));
1470 s.addremove = false;
1471 s.anonymous = true;
1472
1473 o = s.option(form.Value, 'ula_prefix', _('IPv6 ULA-Prefix'), _('Unique Local Address - in the range <code>fc00::/7</code>. Typically only within the &#8216;local&#8217; half <code>fd00::/8</code>. ULA for IPv6 is analogous to IPv4 private network addressing. This prefix is randomly generated at first install.'));
1474 o.datatype = 'cidr6';
1475
1476 o = s.option(form.Flag, 'packet_steering', _('Packet Steering'), _('Enable packet steering across all CPUs. May help or hinder network speed.'));
1477 o.optional = true;
1478
1479
1480 if (dslModemType != null) {
1481 s = m.section(form.TypedSection, 'dsl', _('DSL'));
1482 s.anonymous = true;
1483
1484 o = s.option(form.ListValue, 'annex', _('Annex'));
1485 o.value('a', _('Annex A + L + M (all)'));
1486 o.value('b', _('Annex B (all)'));
1487 o.value('j', _('Annex J (all)'));
1488 o.value('m', _('Annex M (all)'));
1489 o.value('bdmt', _('Annex B G.992.1'));
1490 o.value('b2', _('Annex B G.992.3'));
1491 o.value('b2p', _('Annex B G.992.5'));
1492 o.value('at1', _('ANSI T1.413'));
1493 o.value('admt', _('Annex A G.992.1'));
1494 o.value('alite', _('Annex A G.992.2'));
1495 o.value('a2', _('Annex A G.992.3'));
1496 o.value('a2p', _('Annex A G.992.5'));
1497 o.value('l', _('Annex L G.992.3 POTS 1'));
1498 o.value('m2', _('Annex M G.992.3'));
1499 o.value('m2p', _('Annex M G.992.5'));
1500
1501 o = s.option(form.ListValue, 'tone', _('Tone'));
1502 o.value('', _('auto'));
1503 o.value('a', _('A43C + J43 + A43'));
1504 o.value('av', _('A43C + J43 + A43 + V43'));
1505 o.value('b', _('B43 + B43C'));
1506 o.value('bv', _('B43 + B43C + V43'));
1507
1508 if (dslModemType == 'vdsl') {
1509 o = s.option(form.ListValue, 'xfer_mode', _('Encapsulation mode'));
1510 o.value('', _('auto'));
1511 o.value('atm', _('ATM (Asynchronous Transfer Mode)'));
1512 o.value('ptm', _('PTM/EFM (Packet Transfer Mode)'));
1513
1514 o = s.option(form.ListValue, 'line_mode', _('DSL line mode'));
1515 o.value('', _('auto'));
1516 o.value('adsl', _('ADSL'));
1517 o.value('vdsl', _('VDSL'));
1518
1519 o = s.option(form.ListValue, 'ds_snr_offset', _('Downstream SNR offset'));
1520 o.default = '0';
1521
1522 for (var i = -100; i <= 100; i += 5)
1523 o.value(i, _('%.1f dB').format(i / 10));
1524 }
1525
1526 s.option(form.Value, 'firmware', _('Firmware File'));
1527 }
1528
1529
1530 // Show ATM bridge section if we have the capabilities
1531 if (L.hasSystemFeature('br2684ctl')) {
1532 s = m.section(form.TypedSection, 'atm-bridge', _('ATM Bridges'), _('ATM bridges expose encapsulated ethernet in AAL5 connections as virtual Linux network interfaces which can be used in conjunction with DHCP or PPP to dial into the provider network.'));
1533
1534 s.addremove = true;
1535 s.anonymous = true;
1536 s.addbtntitle = _('Add ATM Bridge');
1537
1538 s.handleAdd = function(ev) {
1539 var sections = uci.sections('network', 'atm-bridge'),
1540 max_unit = -1;
1541
1542 for (var i = 0; i < sections.length; i++) {
1543 var unit = +sections[i].unit;
1544
1545 if (!isNaN(unit) && unit > max_unit)
1546 max_unit = unit;
1547 }
1548
1549 return this.map.save(function() {
1550 var sid = uci.add('network', 'atm-bridge');
1551
1552 uci.set('network', sid, 'unit', max_unit + 1);
1553 uci.set('network', sid, 'atmdev', 0);
1554 uci.set('network', sid, 'encaps', 'llc');
1555 uci.set('network', sid, 'payload', 'bridged');
1556 uci.set('network', sid, 'vci', 35);
1557 uci.set('network', sid, 'vpi', 8);
1558 });
1559 };
1560
1561 s.tab('general', _('General Setup'));
1562 s.tab('advanced', _('Advanced Settings'));
1563
1564 o = s.taboption('general', form.Value, 'vci', _('ATM Virtual Channel Identifier (VCI)'));
1565 s.taboption('general', form.Value, 'vpi', _('ATM Virtual Path Identifier (VPI)'));
1566
1567 o = s.taboption('general', form.ListValue, 'encaps', _('Encapsulation mode'));
1568 o.value('llc', _('LLC'));
1569 o.value('vc', _('VC-Mux'));
1570
1571 s.taboption('advanced', form.Value, 'atmdev', _('ATM device number'));
1572 s.taboption('advanced', form.Value, 'unit', _('Bridge unit number'));
1573
1574 o = s.taboption('advanced', form.ListValue, 'payload', _('Forwarding mode'));
1575 o.value('bridged', _('bridged'));
1576 o.value('routed', _('routed'));
1577 }
1578
1579
1580 return m.render().then(L.bind(function(m, nodes) {
1581 poll.add(L.bind(function() {
1582 var section_ids = m.children[0].cfgsections(),
1583 tasks = [];
1584
1585 for (var i = 0; i < section_ids.length; i++) {
1586 var row = nodes.querySelector('.cbi-section-table-row[data-sid="%s"]'.format(section_ids[i])),
1587 dsc = row.querySelector('[data-name="_ifacestat"] > div'),
1588 btn1 = row.querySelector('.cbi-section-actions .reconnect'),
1589 btn2 = row.querySelector('.cbi-section-actions .down');
1590
1591 if (dsc.getAttribute('reconnect') == '') {
1592 dsc.setAttribute('reconnect', '1');
1593 tasks.push(fs.exec('/sbin/ifup', [section_ids[i]]).catch(function(e) {
1594 ui.addNotification(null, E('p', e.message));
1595 }));
1596 }
1597 else if (dsc.getAttribute('disconnect') == '') {
1598 dsc.setAttribute('disconnect', '1');
1599 tasks.push(fs.exec('/sbin/ifdown', [section_ids[i]]).catch(function(e) {
1600 ui.addNotification(null, E('p', e.message));
1601 }));
1602 }
1603 else if (dsc.getAttribute('reconnect') == '1') {
1604 dsc.removeAttribute('reconnect');
1605 btn1.classList.remove('spinning');
1606 btn1.disabled = false;
1607 }
1608 else if (dsc.getAttribute('disconnect') == '1') {
1609 dsc.removeAttribute('disconnect');
1610 btn2.classList.remove('spinning');
1611 btn2.disabled = false;
1612 }
1613 }
1614
1615 return Promise.all(tasks)
1616 .then(L.bind(network.getNetworks, network))
1617 .then(L.bind(this.poll_status, this, nodes));
1618 }, this), 5);
1619
1620 return nodes;
1621 }, this, m));
1622 }
1623 });