luci-mod-network: interfaces: restructure DHCPv6 and IPv6 RA options
[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 = ifc.getDevices(),
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 return Promise.all([ resolveZone, network.flushCache() ]);
323 },
324
325 load: function() {
326 return Promise.all([
327 network.getDSLModemType(),
328 network.getDevices(),
329 fs.lines('/etc/iproute2/rt_tables'),
330 L.resolveDefault(fs.read('/usr/lib/opkg/info/netifd.control')),
331 uci.changes()
332 ]);
333 },
334
335 interfaceBridgeWithIfnameSections: function() {
336 return uci.sections('network', 'interface').filter(function(ns) {
337 return ns.type == 'bridge' && !ns.ports && ns.ifname;
338 });
339 },
340
341 deviceWithIfnameSections: function() {
342 return uci.sections('network', 'device').filter(function(ns) {
343 return ns.type == 'bridge' && !ns.ports && ns.ifname;
344 });
345 },
346
347 interfaceWithIfnameSections: function() {
348 return uci.sections('network', 'interface').filter(function(ns) {
349 return !ns.device && ns.ifname;
350 });
351 },
352
353 handleBridgeMigration: function(ev) {
354 var tasks = [];
355
356 this.interfaceBridgeWithIfnameSections().forEach(function(ns) {
357 var device_name = 'br-' + ns['.name'];
358
359 tasks.push(uci.callAdd('network', 'device', null, {
360 'name': device_name,
361 'type': 'bridge',
362 'ports': L.toArray(ns.ifname),
363 'macaddr': ns.macaddr
364 }));
365
366 tasks.push(uci.callSet('network', ns['.name'], {
367 'type': '',
368 'ifname': '',
369 'macaddr': '',
370 'device': device_name
371 }));
372 });
373
374 return Promise.all(tasks)
375 .then(L.bind(ui.changes.init, ui.changes))
376 .then(L.bind(ui.changes.apply, ui.changes));
377 },
378
379 renderBridgeMigration: function() {
380 ui.showModal(_('Network bridge configuration migration'), [
381 E('p', _('The existing network configuration needs to be changed for LuCI to function properly.')),
382 E('p', _('Upon pressing "Continue", bridges configuration will be updated and the network will be restarted to apply the updated configuration.')),
383 E('div', { 'class': 'right' },
384 E('button', {
385 'class': 'btn cbi-button-action important',
386 'click': ui.createHandlerFn(this, 'handleBridgeMigration')
387 }, _('Continue')))
388 ]);
389 },
390
391 handleIfnameMigration: function(ev) {
392 var tasks = [];
393
394 this.deviceWithIfnameSections().forEach(function(ds) {
395 tasks.push(uci.add('network', ds['.name'], {
396 'ifname': '',
397 'ports': L.toArray(ds.ifname)
398 }));
399 });
400
401 this.interfaceWithIfnameSections().forEach(function(ns) {
402 tasks.push(uci.callSet('network', ns['.name'], {
403 'ifname': '',
404 'device': ns.ifname
405 }));
406 });
407
408 return Promise.all(tasks)
409 .then(L.bind(ui.changes.init, ui.changes))
410 .then(L.bind(ui.changes.apply, ui.changes));
411 },
412
413 renderIfnameMigration: function() {
414 ui.showModal(_('Network ifname configuration migration'), [
415 E('p', _('The existing network configuration needs to be changed for LuCI to function properly.')),
416 E('p', _('Upon pressing "Continue", ifname options will get renamed and the network will be restarted to apply the updated configuration.')),
417 E('div', { 'class': 'right' },
418 E('button', {
419 'class': 'btn cbi-button-action important',
420 'click': ui.createHandlerFn(this, 'handleIfnameMigration')
421 }, _('Continue')))
422 ]);
423 },
424
425 render: function(data) {
426 var netifdVersion = (data[3] || '').match(/Version: ([^\n]+)/);
427
428 if (netifdVersion && netifdVersion[1] >= "2021-05-26") {
429 if (this.interfaceBridgeWithIfnameSections().length)
430 return this.renderBridgeMigration();
431 else if (this.deviceWithIfnameSections().length || this.interfaceWithIfnameSections().length)
432 return this.renderIfnameMigration();
433 }
434
435 var dslModemType = data[0],
436 netDevs = data[1],
437 m, s, o;
438
439 var rtTables = data[2].map(function(l) {
440 var m = l.trim().match(/^(\d+)\s+(\S+)$/);
441 return m ? [ +m[1], m[2] ] : null;
442 }).filter(function(e) {
443 return e && e[0] > 0;
444 });
445
446 m = new form.Map('network');
447 m.tabbed = true;
448 m.chain('dhcp');
449
450 s = m.section(form.GridSection, 'interface', _('Interfaces'));
451 s.anonymous = true;
452 s.addremove = true;
453 s.addbtntitle = _('Add new interface...');
454
455 s.load = function() {
456 return Promise.all([
457 network.getNetworks(),
458 firewall.getZones()
459 ]).then(L.bind(function(data) {
460 this.networks = data[0];
461 this.zones = data[1];
462 }, this));
463 };
464
465 s.tab('general', _('General Settings'));
466 s.tab('advanced', _('Advanced Settings'));
467 s.tab('physical', _('Physical Settings'));
468 s.tab('brport', _('Bridge port specific options'));
469 s.tab('bridgevlan', _('Bridge VLAN filtering'));
470 s.tab('firewall', _('Firewall Settings'));
471 s.tab('dhcp', _('DHCP Server'));
472
473 s.cfgsections = function() {
474 return this.networks.map(function(n) { return n.getName() })
475 .filter(function(n) { return n != 'loopback' });
476 };
477
478 s.modaltitle = function(section_id) {
479 return _('Interfaces') + ' » ' + section_id.toUpperCase();
480 };
481
482 s.renderRowActions = function(section_id) {
483 var tdEl = this.super('renderRowActions', [ section_id, _('Edit') ]),
484 net = this.networks.filter(function(n) { return n.getName() == section_id })[0],
485 disabled = net ? !net.isUp() : true,
486 dynamic = net ? net.isDynamic() : false;
487
488 dom.content(tdEl.lastChild, [
489 E('button', {
490 'class': 'cbi-button cbi-button-neutral reconnect',
491 'click': iface_updown.bind(this, true, section_id),
492 'title': _('Reconnect this interface'),
493 'disabled': dynamic ? 'disabled' : null
494 }, _('Restart')),
495 E('button', {
496 'class': 'cbi-button cbi-button-neutral down',
497 'click': iface_updown.bind(this, false, section_id),
498 'title': _('Shutdown this interface'),
499 'disabled': (dynamic || disabled) ? 'disabled' : null
500 }, _('Stop')),
501 tdEl.lastChild.firstChild,
502 tdEl.lastChild.lastChild
503 ]);
504
505 if (!dynamic && net && !uci.get('network', net.getName())) {
506 tdEl.lastChild.childNodes[0].disabled = true;
507 tdEl.lastChild.childNodes[2].disabled = true;
508 tdEl.lastChild.childNodes[3].disabled = true;
509 }
510
511 return tdEl;
512 };
513
514 s.addModalOptions = function(s) {
515 var protoval = uci.get('network', s.section, 'proto'),
516 protoclass = protoval ? network.getProtocol(protoval) : null,
517 o, proto_select, proto_switch, type, stp, igmp, ss, so;
518
519 if (!protoval)
520 return;
521
522 return network.getNetwork(s.section).then(L.bind(function(ifc) {
523 var protocols = network.getProtocols();
524
525 protocols.sort(function(a, b) {
526 return a.getProtocol() > b.getProtocol();
527 });
528
529 o = s.taboption('general', form.DummyValue, '_ifacestat_modal', _('Status'));
530 o.modalonly = true;
531 o.cfgvalue = L.bind(function(section_id) {
532 var net = this.networks.filter(function(n) { return n.getName() == section_id })[0];
533
534 return render_modal_status(E('div', {
535 'id': '%s-ifc-status'.format(section_id),
536 'class': 'ifacebadge large'
537 }), net);
538 }, this);
539 o.write = function() {};
540
541
542 proto_select = s.taboption('general', form.ListValue, 'proto', _('Protocol'));
543 proto_select.modalonly = true;
544
545 proto_switch = s.taboption('general', form.Button, '_switch_proto');
546 proto_switch.modalonly = true;
547 proto_switch.title = _('Really switch protocol?');
548 proto_switch.inputtitle = _('Switch protocol');
549 proto_switch.inputstyle = 'apply';
550 proto_switch.onclick = L.bind(function(ev) {
551 s.map.save()
552 .then(L.bind(m.load, m))
553 .then(L.bind(m.render, m))
554 .then(L.bind(this.renderMoreOptionsModal, this, s.section));
555 }, this);
556
557 o = s.taboption('general', widgets.DeviceSelect, '_net_device', _('Device'));
558 o.ucioption = 'device';
559 o.nobridges = false;
560 o.optional = false;
561 o.network = ifc.getName();
562
563 o = s.taboption('general', form.Flag, 'auto', _('Bring up on boot'));
564 o.modalonly = true;
565 o.default = o.enabled;
566
567 if (L.hasSystemFeature('firewall')) {
568 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.'));
569 o.network = ifc.getName();
570 o.optional = true;
571
572 o.cfgvalue = function(section_id) {
573 return firewall.getZoneByNetwork(ifc.getName()).then(function(zone) {
574 return (zone != null ? zone.getName() : null);
575 });
576 };
577
578 o.write = o.remove = function(section_id, value) {
579 return Promise.all([
580 firewall.getZoneByNetwork(ifc.getName()),
581 (value != null) ? firewall.getZone(value) : null
582 ]).then(function(data) {
583 var old_zone = data[0],
584 new_zone = data[1];
585
586 if (old_zone == null && new_zone == null && (value == null || value == ''))
587 return;
588
589 if (old_zone != null && new_zone != null && old_zone.getName() == new_zone.getName())
590 return;
591
592 if (old_zone != null)
593 old_zone.deleteNetwork(ifc.getName());
594
595 if (new_zone != null)
596 new_zone.addNetwork(ifc.getName());
597 else if (value != null)
598 return firewall.addZone(value).then(function(new_zone) {
599 new_zone.addNetwork(ifc.getName());
600 });
601 });
602 };
603 }
604
605 for (var i = 0; i < protocols.length; i++) {
606 proto_select.value(protocols[i].getProtocol(), protocols[i].getI18n());
607
608 if (protocols[i].getProtocol() != uci.get('network', s.section, 'proto'))
609 proto_switch.depends('proto', protocols[i].getProtocol());
610 }
611
612 if (L.hasSystemFeature('dnsmasq') || L.hasSystemFeature('odhcpd')) {
613 o = s.taboption('dhcp', form.SectionValue, '_dhcp', form.TypedSection, 'dhcp');
614
615 ss = o.subsection;
616 ss.uciconfig = 'dhcp';
617 ss.addremove = false;
618 ss.anonymous = true;
619
620 ss.tab('general', _('General Setup'));
621 ss.tab('advanced', _('Advanced Settings'));
622 ss.tab('ipv6', _('IPv6 Settings'));
623 ss.tab('ipv6-ra', _('IPv6 RA Settings'));
624
625 ss.filter = function(section_id) {
626 return (uci.get('dhcp', section_id, 'interface') == ifc.getName());
627 };
628
629 ss.renderSectionPlaceholder = function() {
630 return E('div', { 'class': 'cbi-section-create' }, [
631 E('p', _('No DHCP Server configured for this interface') + ' &#160; '),
632 E('button', {
633 'class': 'cbi-button cbi-button-add',
634 'title': _('Setup DHCP Server'),
635 'click': ui.createHandlerFn(this, function(section_id, ev) {
636 this.map.save(function() {
637 uci.add('dhcp', 'dhcp', section_id);
638 uci.set('dhcp', section_id, 'interface', section_id);
639
640 if (protoval == 'static') {
641 uci.set('dhcp', section_id, 'start', 100);
642 uci.set('dhcp', section_id, 'limit', 150);
643 uci.set('dhcp', section_id, 'leasetime', '12h');
644 }
645 else {
646 uci.set('dhcp', section_id, 'ignore', 1);
647 }
648 });
649 }, ifc.getName())
650 }, _('Setup DHCP Server'))
651 ]);
652 };
653
654 ss.taboption('general', form.Flag, 'ignore', _('Ignore interface'), _('Disable <abbr title="Dynamic Host Configuration Protocol">DHCP</abbr> for this interface.'));
655
656 if (protoval == 'static') {
657 so = ss.taboption('general', form.Value, 'start', _('Start'), _('Lowest leased address as offset from the network address.'));
658 so.optional = true;
659 so.datatype = 'or(uinteger,ip4addr("nomask"))';
660 so.default = '100';
661
662 so = ss.taboption('general', form.Value, 'limit', _('Limit'), _('Maximum number of leased addresses.'));
663 so.optional = true;
664 so.datatype = 'uinteger';
665 so.default = '150';
666
667 so = ss.taboption('general', form.Value, 'leasetime', _('Lease time'), _('Expiry time of leased addresses, minimum is 2 minutes (<code>2m</code>).'));
668 so.optional = true;
669 so.default = '12h';
670
671 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.'));
672 so.default = so.enabled;
673
674 ss.taboption('advanced', form.Flag, 'force', _('Force'), _('Force DHCP on this network even if another server is detected.'));
675
676 // XXX: is this actually useful?
677 //ss.taboption('advanced', form.Value, 'name', _('Name'), _('Define a name for this network.'));
678
679 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.'));
680 so.optional = true;
681 so.datatype = 'ip4addr';
682
683 so.render = function(option_index, section_id, in_table) {
684 this.placeholder = get_netmask(s, true);
685 return form.Value.prototype.render.apply(this, [ option_index, section_id, in_table ]);
686 };
687
688 so.validate = function(section_id, value) {
689 var uielem = this.getUIElement(section_id);
690 if (uielem)
691 uielem.setPlaceholder(get_netmask(s, false));
692 return form.Value.prototype.validate.apply(this, [ section_id, value ]);
693 };
694
695 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.'));
696 }
697
698
699 var has_other_master = uci.sections('dhcp', 'dhcp').filter(function(s) {
700 return (s.interface != ifc.getName() && s.master == '1');
701 })[0];
702
703 so = ss.taboption('ipv6', form.Flag , 'master', _('Designated master'));
704 so.readonly = has_other_master ? true : false;
705 so.description = has_other_master
706 ? _('Interface "%h" is already marked as designated master.').format(has_other_master.interface || has_other_master['.name'])
707 : _('Set this interface as master for RA and DHCPv6 relaying as well as NDP proxying.')
708 ;
709
710 so.validate = function(section_id, value) {
711 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>.'),
712 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.'),
713 hybrid_master_desc = _('Operate in <em>relay mode</em> if an upstream IPv6 prefix is present, otherwise disable service.'),
714 checked = this.formvalue(section_id),
715 dhcpv6 = this.section.getOption('dhcpv6').getUIElement(section_id),
716 ndp = this.section.getOption('ndp').getUIElement(section_id),
717 ra = this.section.getOption('ra').getUIElement(section_id);
718
719 if (checked == '1' || protoval != 'static') {
720 dhcpv6.node.querySelector('li[data-value="server"]').setAttribute('unselectable', '');
721
722 if (dhcpv6.getValue() == 'server')
723 dhcpv6.setValue('hybrid');
724
725 ra.node.querySelector('li[data-value="server"]').setAttribute('unselectable', '');
726
727 if (ra.getValue() == 'server')
728 ra.setValue('hybrid');
729 }
730
731 if (checked == '1') {
732 dhcpv6.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = hybrid_master_desc;
733 ra.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = hybrid_master_desc;
734 ndp.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = hybrid_master_desc;
735 }
736 else {
737 if (protoval == 'static') {
738 dhcpv6.node.querySelector('li[data-value="server"]').removeAttribute('unselectable');
739 ra.node.querySelector('li[data-value="server"]').removeAttribute('unselectable');
740 }
741
742 dhcpv6.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = hybrid_downstream_desc;
743 ra.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = hybrid_downstream_desc;
744 ndp.node.querySelector('li[data-value="hybrid"] > div > span').innerHTML = ndp_downstream_desc ;
745 }
746
747 return true;
748 };
749
750
751 so = ss.taboption('ipv6', cbiRichListValue, 'ra', _('<abbr title="Router Advertisement">RA</abbr>-Service'),
752 _('Configures the operation mode of the <abbr title="Router Advertisement">RA</abbr> service on this interface.'));
753 so.value('', _('disabled'),
754 _('Do not send any <abbr title="Router Advertisement, ICMPv6 Type 134">RA</abbr> messages on this interface.'));
755 so.value('server', _('server mode'),
756 _('Send <abbr title="Router Advertisement, ICMPv6 Type 134">RA</abbr> messages advertising this device as IPv6 router.'));
757 so.value('relay', _('relay mode'),
758 _('Forward <abbr title="Router Advertisement, ICMPv6 Type 134">RA</abbr> messages received on the designated master interface to downstream interfaces.'));
759 so.value('hybrid', _('hybrid mode'), ' ');
760
761
762 so = ss.taboption('ipv6-ra', cbiRichListValue, 'ra_default', _('Default router'),
763 _('Configures the default router advertisement in <abbr title="Router Advertisement">RA</abbr> messages.'));
764 so.value('', _('automatic'),
765 _('Announce this device as default router if a local IPv6 default route is present.'));
766 so.value('1', _('on available prefix'),
767 _('Announce this device as default router if a public IPv6 prefix is available, regardless of local default route availability.'));
768 so.value('2', _('forced'),
769 _('Announce this device as default router regardless of whether a prefix or default route is present.'));
770 so.depends('ra', 'server');
771 so.depends({ ra: 'hybrid', master: '0' });
772
773 so = ss.taboption('ipv6-ra', form.Flag, 'ra_slaac', _('Enable <abbr title="Stateless Address Auto Config">SLAAC</abbr>'),
774 _('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.'));
775 so.default = so.enabled;
776 so.depends('ra', 'server');
777 so.depends({ ra: 'hybrid', master: '0' });
778
779 so = ss.taboption('ipv6-ra', cbiRichListValue, 'ra_flags', _('<abbr title="Router Advertisement">RA</abbr> Flags'),
780 _('Specifies the flags sent in <abbr title="Router Advertisement">RA</abbr> messages, for example to instruct clients to request further information via stateful DHCPv6.'));
781 so.value('managed-config', _('managed config (M)'),
782 _('The <em>Managed address configuration</em> (M) flag indicates that IPv6 addresses are available via DHCPv6.'));
783 so.value('other-config', _('other config (O)'),
784 _('The <em>Other configuration</em> (O) flag indicates that other information, such as DNS servers, is available via DHCPv6.'));
785 so.value('home-agent', _('mobile home agent (H)'),
786 _('The <em>Mobile IPv6 Home Agent</em> (H) flag indicates that the device is also acting as Mobile IPv6 home agent on this link.'));
787 so.multiple = true;
788 so.select_placeholder = _('none');
789 so.depends('ra', 'server');
790 so.depends({ ra: 'hybrid', master: '0' });
791 so.cfgvalue = function(section_id) {
792 var flags = L.toArray(uci.get('dhcp', section_id, 'ra_flags'));
793 return flags.length ? flags : [ 'other-config' ];
794 };
795 so.remove = function(section_id) {
796 uci.set('dhcp', section_id, 'ra_flags', [ 'none' ]);
797 };
798
799 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.'));
800 so.optional = true;
801 so.datatype = 'uinteger';
802 so.placeholder = '600';
803 so.depends('ra', 'server');
804 so.depends({ ra: 'hybrid', master: '0' });
805
806 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.'));
807 so.optional = true;
808 so.datatype = 'uinteger';
809 so.placeholder = '200';
810 so.depends('ra', 'server');
811 so.depends({ ra: 'hybrid', master: '0' });
812
813 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.'));
814 so.optional = true;
815 so.datatype = 'range(0, 9000)';
816 so.placeholder = '1800';
817 so.depends('ra', 'server');
818 so.depends({ ra: 'hybrid', master: '0' });
819
820 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.'));
821 so.optional = true;
822 so.datatype = 'range(1280, 65535)';
823 so.depends('ra', 'server');
824 so.depends({ ra: 'hybrid', master: '0' });
825 so.load = function(section_id) {
826 var dev = ifc.getL3Device();
827
828 if (dev) {
829 var path = "/proc/sys/net/ipv6/conf/%s/mtu".format(dev.getName());
830
831 return L.resolveDefault(fs.read(path), dev.getMTU()).then(L.bind(function(data) {
832 this.placeholder = data;
833 }, this));
834 }
835 };
836
837 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.'));
838 so.optional = true;
839 so.datatype = 'range(0, 255)';
840 so.depends('ra', 'server');
841 so.depends({ ra: 'hybrid', master: '0' });
842 so.load = function(section_id) {
843 var dev = ifc.getL3Device();
844
845 if (dev) {
846 var path = "/proc/sys/net/ipv6/conf/%s/hop_limit".format(dev.getName());
847
848 return L.resolveDefault(fs.read(path), 64).then(L.bind(function(data) {
849 this.placeholder = data;
850 }, this));
851 }
852 };
853
854
855 so = ss.taboption('ipv6', cbiRichListValue, 'dhcpv6', _('DHCPv6-Service'),
856 _('Configures the operation mode of the DHCPv6 service on this interface.'));
857 so.value('', _('disabled'),
858 _('Do not offer DHCPv6 service on this interface.'));
859 so.value('server', _('server mode'),
860 _('Provide a DHCPv6 server on this interface and reply to DHCPv6 solicitations and requests.'));
861 so.value('relay', _('relay mode'),
862 _('Forward DHCPv6 messages between the designated master interface and downstream interfaces.'));
863 so.value('hybrid', _('hybrid mode'), ' ');
864
865
866 so = ss.taboption('ipv6', form.DynamicList, 'dns', _('Announced IPv6 DNS servers'),
867 _('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.'));
868 so.datatype = 'ip6addr("nomask")'; /* restrict to IPv6 only for now since dnsmasq (DHCPv4) does not honour this option */
869 so.depends('dhcpv6', 'server');
870 so.depends({ dhcpv6: 'hybrid', master: '0' });
871
872 so = ss.taboption('ipv6', form.Flag, 'dns_service', _('Local IPv6 DNS server'),
873 _('Announce this device as IPv6 DNS server.'));
874 so.default = so.enabled;
875 so.depends({ dhcpv6: 'server', dns: /^$/ });
876 so.depends({ dhcpv6: 'hybrid', dns: /^$/, master: '0' });
877
878 so = ss.taboption('ipv6', form.DynamicList, 'domain', _('Announced DNS domains'),
879 _('Specifies a fixed list of DNS search domains to announce via DHCPv6. If left unspecified, the local device DNS search domain will be announced.'));
880 so.datatype = 'hostname';
881 so.depends('dhcpv6', 'server');
882 so.depends({ dhcpv6: 'hybrid', master: '0' });
883
884
885 so = ss.taboption('ipv6', cbiRichListValue, 'ndp', _('<abbr title="Neighbour Discovery Protocol">NDP</abbr>-Proxy'),
886 _('Configures the operation mode of the NDP proxy service on this interface.'));
887 so.value('', _('disabled'),
888 _('Do not proxy any <abbr title="Neighbour Discovery Protocol">NDP</abbr> packets.'));
889 so.value('relay', _('relay mode'),
890 _('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.'));
891 so.value('hybrid', _('hybrid mode'), ' ');
892
893
894 so = ss.taboption('ipv6', form.Flag, 'ndproxy_routing', _('Learn routes'), _('Setup routes for proxied IPv6 neighbours.'));
895 so.default = so.enabled;
896 so.depends('ndp', 'relay');
897 so.depends('ndp', 'hybrid');
898
899 so = ss.taboption('ipv6', form.Flag, 'ndproxy_slave', _('NDP-Proxy slave'), _('Set interface as NDP-Proxy external slave. Default is off.'));
900 so.depends({ ndp: 'relay', master: '0' });
901 so.depends({ ndp: 'hybrid', master: '0' });
902 }
903
904 ifc.renderFormOptions(s);
905
906 // Common interface options
907 o = nettools.replaceOption(s, 'advanced', form.Flag, 'defaultroute', _('Use default gateway'), _('If unchecked, no default route is configured'));
908 o.default = o.enabled;
909
910 if (protoval != 'static') {
911 o = nettools.replaceOption(s, 'advanced', form.Flag, 'peerdns', _('Use DNS servers advertised by peer'), _('If unchecked, the advertised DNS server addresses are ignored'));
912 o.default = o.enabled;
913 }
914
915 o = nettools.replaceOption(s, 'advanced', form.DynamicList, 'dns', _('Use custom DNS servers'));
916 if (protoval != 'static')
917 o.depends('peerdns', '0');
918 o.datatype = 'ipaddr';
919
920 o = nettools.replaceOption(s, 'advanced', form.DynamicList, 'dns_search', _('DNS search domains'));
921 if (protoval != 'static')
922 o.depends('peerdns', '0');
923 o.datatype = 'hostname';
924
925 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'));
926 o.datatype = 'uinteger';
927 o.placeholder = '0';
928
929 o = nettools.replaceOption(s, 'advanced', form.Value, 'metric', _('Use gateway metric'));
930 o.datatype = 'uinteger';
931 o.placeholder = '0';
932
933 o = nettools.replaceOption(s, 'advanced', form.Value, 'ip4table', _('Override IPv4 routing table'));
934 o.datatype = 'or(uinteger, string)';
935 for (var i = 0; i < rtTables.length; i++)
936 o.value(rtTables[i][1], '%s (%d)'.format(rtTables[i][1], rtTables[i][0]));
937
938 o = nettools.replaceOption(s, 'advanced', form.Value, 'ip6table', _('Override IPv6 routing table'));
939 o.datatype = 'or(uinteger, string)';
940 for (var i = 0; i < rtTables.length; i++)
941 o.value(rtTables[i][1], '%s (%d)'.format(rtTables[i][0], rtTables[i][1]));
942
943 o = nettools.replaceOption(s, 'advanced', form.Flag, 'delegate', _('Delegate IPv6 prefixes'), _('Enable downstream delegation of IPv6 prefixes available on this interface'));
944 o.default = o.enabled;
945
946 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'));
947 o.value('', _('disabled'));
948 o.value('64');
949 o.datatype = 'max(128)';
950
951 o = nettools.replaceOption(s, 'advanced', form.Value, 'ip6hint', _('IPv6 assignment hint'), _('Assign prefix parts using this hexadecimal subprefix ID for this interface.'));
952 o.placeholder = '0';
953 o.validate = function(section_id, value) {
954 if (value == null || value == '')
955 return true;
956
957 var n = parseInt(value, 16);
958
959 if (!/^(0x)?[0-9a-fA-F]+$/.test(value) || isNaN(n) || n >= 0xffffffff)
960 return _('Expecting a hexadecimal assignment hint');
961
962 return true;
963 };
964 for (var i = 33; i <= 64; i++)
965 o.depends('ip6assign', String(i));
966
967
968 o = nettools.replaceOption(s, 'advanced', form.DynamicList, 'ip6class', _('IPv6 prefix filter'), _('If set, downstream subnets are only allocated from the given IPv6 prefix classes.'));
969 o.value('local', 'local (%s)'.format(_('Local ULA')));
970
971 var prefixClasses = {};
972
973 this.networks.forEach(function(net) {
974 var prefixes = net._ubus('ipv6-prefix');
975 if (Array.isArray(prefixes)) {
976 prefixes.forEach(function(pfx) {
977 if (L.isObject(pfx) && typeof(pfx['class']) == 'string') {
978 prefixClasses[pfx['class']] = prefixClasses[pfx['class']] || {};
979 prefixClasses[pfx['class']][net.getName()] = true;
980 }
981 });
982 }
983 });
984
985 Object.keys(prefixClasses).sort().forEach(function(c) {
986 var networks = Object.keys(prefixClasses[c]).sort().join(', ');
987 o.value(c, (c != networks) ? '%s (%s)'.format(c, networks) : c);
988 });
989
990
991 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."));
992 o.datatype = 'ip6hostid';
993 o.placeholder = '::1';
994
995 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.'));
996 o.datatype = 'uinteger';
997 o.placeholder = '0';
998
999 for (var i = 0; i < s.children.length; i++) {
1000 o = s.children[i];
1001
1002 switch (o.option) {
1003 case 'proto':
1004 case 'auto':
1005 case '_dhcp':
1006 case '_zone':
1007 case '_switch_proto':
1008 case '_ifacestat_modal':
1009 continue;
1010
1011 case 'igmp_snooping':
1012 case 'stp':
1013 case 'type':
1014 case '_net_device':
1015 var deps = [];
1016 for (var j = 0; j < protocols.length; j++) {
1017 if (!protocols[j].isVirtual()) {
1018 if (o.deps.length)
1019 for (var k = 0; k < o.deps.length; k++)
1020 deps.push(Object.assign({ proto: protocols[j].getProtocol() }, o.deps[k]));
1021 else
1022 deps.push({ proto: protocols[j].getProtocol() });
1023 }
1024 }
1025 o.deps = deps;
1026 break;
1027
1028 default:
1029 if (o.deps.length)
1030 for (var j = 0; j < o.deps.length; j++)
1031 o.deps[j].proto = protoval;
1032 else
1033 o.depends('proto', protoval);
1034 }
1035 }
1036
1037 this.activeSection = s.section;
1038 }, this));
1039 };
1040
1041 s.handleModalCancel = function(/* ... */) {
1042 var type = uci.get('network', this.activeSection || this.addedSection, 'type'),
1043 device = (type == 'bridge') ? 'br-%s'.format(this.activeSection || this.addedSection) : null;
1044
1045 uci.sections('network', 'bridge-vlan', function(bvs) {
1046 if (device != null && bvs.device == device)
1047 uci.remove('network', bvs['.name']);
1048 });
1049
1050 return form.GridSection.prototype.handleModalCancel.apply(this, arguments);
1051 };
1052
1053 s.handleAdd = function(ev) {
1054 var m2 = new form.Map('network'),
1055 s2 = m2.section(form.NamedSection, '_new_'),
1056 protocols = network.getProtocols(),
1057 proto, name, device;
1058
1059 protocols.sort(function(a, b) {
1060 return a.getProtocol() > b.getProtocol();
1061 });
1062
1063 s2.render = function() {
1064 return Promise.all([
1065 {},
1066 this.renderUCISection('_new_')
1067 ]).then(this.renderContents.bind(this));
1068 };
1069
1070 name = s2.option(form.Value, 'name', _('Name'));
1071 name.rmempty = false;
1072 name.datatype = 'uciname';
1073 name.placeholder = _('New interface name…');
1074 name.validate = function(section_id, value) {
1075 if (uci.get('network', value) != null)
1076 return _('The interface name is already used');
1077
1078 var pr = network.getProtocol(proto.formvalue(section_id), value),
1079 ifname = pr.isVirtual() ? '%s-%s'.format(pr.getProtocol(), value) : 'br-%s'.format(value);
1080
1081 if (value.length > 15)
1082 return _('The interface name is too long');
1083
1084 return true;
1085 };
1086
1087 proto = s2.option(form.ListValue, 'proto', _('Protocol'));
1088 proto.validate = name.validate;
1089
1090 device = s2.option(widgets.DeviceSelect, 'device', _('Device'));
1091 device.noaliases = false;
1092 device.optional = false;
1093
1094 for (var i = 0; i < protocols.length; i++) {
1095 proto.value(protocols[i].getProtocol(), protocols[i].getI18n());
1096
1097 if (!protocols[i].isVirtual())
1098 device.depends('proto', protocols[i].getProtocol());
1099 }
1100
1101 m2.render().then(L.bind(function(nodes) {
1102 ui.showModal(_('Add new interface...'), [
1103 nodes,
1104 E('div', { 'class': 'right' }, [
1105 E('button', {
1106 'class': 'btn',
1107 'click': ui.hideModal
1108 }, _('Cancel')), ' ',
1109 E('button', {
1110 'class': 'cbi-button cbi-button-positive important',
1111 'click': ui.createHandlerFn(this, function(ev) {
1112 var nameval = name.isValid('_new_') ? name.formvalue('_new_') : null,
1113 protoval = proto.isValid('_new_') ? proto.formvalue('_new_') : null,
1114 protoclass = protoval ? network.getProtocol(protoval, nameval) : null;
1115
1116 if (nameval == null || protoval == null || nameval == '' || protoval == '')
1117 return;
1118
1119 return protoclass.isCreateable(nameval).then(function(checkval) {
1120 if (checkval != null) {
1121 ui.addNotification(null,
1122 E('p', _('New interface for "%s" can not be created: %s').format(protoclass.getI18n(), checkval)));
1123 ui.hideModal();
1124 return;
1125 }
1126
1127 return m.save(function() {
1128 var section_id = uci.add('network', 'interface', nameval);
1129
1130 protoclass.set('proto', protoval);
1131 protoclass.addDevice(device.formvalue('_new_'));
1132
1133 m.children[0].addedSection = section_id;
1134 }).then(L.bind(m.children[0].renderMoreOptionsModal, m.children[0], nameval));
1135 });
1136 })
1137 }, _('Create interface'))
1138 ])
1139 ], 'cbi-modal');
1140
1141 nodes.querySelector('[id="%s"] input[type="text"]'.format(name.cbid('_new_'))).focus();
1142 }, this));
1143 };
1144
1145 s.handleRemove = function(section_id, ev) {
1146 return network.deleteNetwork(section_id).then(L.bind(function(section_id, ev) {
1147 return form.GridSection.prototype.handleRemove.apply(this, [section_id, ev]);
1148 }, this, section_id, ev));
1149 };
1150
1151 o = s.option(form.DummyValue, '_ifacebox');
1152 o.modalonly = false;
1153 o.textvalue = function(section_id) {
1154 var net = this.section.networks.filter(function(n) { return n.getName() == section_id })[0],
1155 zone = net ? this.section.zones.filter(function(z) { return !!z.getNetworks().filter(function(n) { return n == section_id })[0] })[0] : null;
1156
1157 if (!net)
1158 return;
1159
1160 var node = E('div', { 'class': 'ifacebox' }, [
1161 E('div', {
1162 'class': 'ifacebox-head',
1163 'style': 'background-color:%s'.format(zone ? zone.getColor() : '#EEEEEE'),
1164 'title': zone ? _('Part of zone %q').format(zone.getName()) : _('No zone assigned')
1165 }, E('strong', net.getName().toUpperCase())),
1166 E('div', {
1167 'class': 'ifacebox-body',
1168 'id': '%s-ifc-devices'.format(section_id),
1169 'data-network': section_id
1170 }, [
1171 E('img', {
1172 'src': L.resource('icons/ethernet_disabled.png'),
1173 'style': 'width:16px; height:16px'
1174 }),
1175 E('br'), E('small', '?')
1176 ])
1177 ]);
1178
1179 render_ifacebox_status(node.childNodes[1], net);
1180
1181 return node;
1182 };
1183
1184 o = s.option(form.DummyValue, '_ifacestat');
1185 o.modalonly = false;
1186 o.textvalue = function(section_id) {
1187 var net = this.section.networks.filter(function(n) { return n.getName() == section_id })[0];
1188
1189 if (!net)
1190 return;
1191
1192 var node = E('div', { 'id': '%s-ifc-description'.format(section_id) });
1193
1194 render_status(node, net, false);
1195
1196 return node;
1197 };
1198
1199 o = s.taboption('advanced', form.Flag, 'delegate', _('Use builtin IPv6-management'));
1200 o.modalonly = true;
1201 o.default = o.enabled;
1202
1203 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).'));
1204 o.modalonly = true;
1205 o.defaults = {
1206 '1': [{ proto: 'static' }],
1207 '0': []
1208 };
1209
1210
1211 // Device configuration
1212 s = m.section(form.GridSection, 'device', _('Devices'));
1213 s.addremove = true;
1214 s.anonymous = true;
1215 s.addbtntitle = _('Add device configuration…');
1216
1217 s.cfgsections = function() {
1218 var sections = uci.sections('network', 'device'),
1219 section_ids = sections.sort(function(a, b) { return a.name > b.name }).map(function(s) { return s['.name'] });
1220
1221 for (var i = 0; i < netDevs.length; i++) {
1222 if (sections.filter(function(s) { return s.name == netDevs[i].getName() }).length)
1223 continue;
1224
1225 if (netDevs[i].getType() == 'wifi' && !netDevs[i].isUp())
1226 continue;
1227
1228 /* Unless http://lists.openwrt.org/pipermail/openwrt-devel/2020-July/030397.html is implemented,
1229 we cannot properly redefine bridges as devices, so filter them away for now... */
1230
1231 var m = netDevs[i].isBridge() ? netDevs[i].getName().match(/^br-([A-Za-z0-9_]+)$/) : null,
1232 s = m ? uci.get('network', m[1]) : null;
1233
1234 if (s && s['.type'] == 'interface' && s.type == 'bridge')
1235 continue;
1236
1237 section_ids.push('dev:%s'.format(netDevs[i].getName()));
1238 }
1239
1240 return section_ids;
1241 };
1242
1243 s.renderMoreOptionsModal = function(section_id, ev) {
1244 var m = section_id.match(/^dev:(.+)$/);
1245
1246 if (m) {
1247 var devtype = getDevType(section_id);
1248
1249 section_id = uci.add('network', 'device');
1250
1251 uci.set('network', section_id, 'name', m[1]);
1252 uci.set('network', section_id, 'type', (devtype != 'ethernet') ? devtype : null);
1253
1254 this.addedSection = section_id;
1255 }
1256
1257 return this.super('renderMoreOptionsModal', [section_id, ev]);
1258 };
1259
1260 s.renderRowActions = function(section_id) {
1261 var trEl = this.super('renderRowActions', [ section_id, _('Configure…') ]),
1262 deleteBtn = trEl.querySelector('button:last-child');
1263
1264 deleteBtn.firstChild.data = _('Reset');
1265 deleteBtn.setAttribute('title', _('Remove related device settings from the configuration'));
1266 deleteBtn.disabled = section_id.match(/^dev:/) ? true : null;
1267
1268 return trEl;
1269 };
1270
1271 s.modaltitle = function(section_id) {
1272 var m = section_id.match(/^dev:(.+)$/),
1273 name = m ? m[1] : uci.get('network', section_id, 'name');
1274
1275 return name ? '%s: %q'.format(getDevTypeDesc(section_id), name) : _('Add device configuration');
1276 };
1277
1278 s.addModalOptions = function(s) {
1279 var isNew = (uci.get('network', s.section, 'name') == null),
1280 dev = getDevice(s.section);
1281
1282 nettools.addDeviceOptions(s, dev, isNew);
1283 };
1284
1285 s.handleModalCancel = function(/* ... */) {
1286 var name = uci.get('network', this.addedSection, 'name')
1287
1288 uci.sections('network', 'bridge-vlan', function(bvs) {
1289 if (name != null && bvs.device == name)
1290 uci.remove('network', bvs['.name']);
1291 });
1292
1293 return form.GridSection.prototype.handleModalCancel.apply(this, arguments);
1294 };
1295
1296 function getDevice(section_id) {
1297 var m = section_id.match(/^dev:(.+)$/),
1298 name = m ? m[1] : uci.get('network', section_id, 'name');
1299
1300 return netDevs.filter(function(d) { return d.getName() == name })[0];
1301 }
1302
1303 function getDevType(section_id) {
1304 var cfgtype = uci.get('network', section_id, 'type'),
1305 dev = getDevice(section_id);
1306
1307 switch (cfgtype || (dev ? dev.getType() : '')) {
1308 case '':
1309 return null;
1310
1311 case 'vlan':
1312 case '8021q':
1313 return '8021q';
1314
1315 case '8021ad':
1316 return '8021ad';
1317
1318 case 'bridge':
1319 return 'bridge';
1320
1321 case 'tunnel':
1322 return 'tunnel';
1323
1324 case 'macvlan':
1325 return 'macvlan';
1326
1327 case 'veth':
1328 return 'veth';
1329
1330 case 'wifi':
1331 case 'alias':
1332 case 'switch':
1333 case 'ethernet':
1334 default:
1335 return 'ethernet';
1336 }
1337 }
1338
1339 function getDevTypeDesc(section_id) {
1340 switch (getDevType(section_id) || '') {
1341 case '':
1342 return E('em', [ _('Device not present') ]);
1343
1344 case '8021q':
1345 return _('VLAN (802.1q)');
1346
1347 case '8021ad':
1348 return _('VLAN (802.1ad)');
1349
1350 case 'bridge':
1351 return _('Bridge device');
1352
1353 case 'tunnel':
1354 return _('Tunnel device');
1355
1356 case 'macvlan':
1357 return _('MAC VLAN');
1358
1359 case 'veth':
1360 return _('Virtual Ethernet');
1361
1362 default:
1363 return _('Network device');
1364 }
1365 }
1366
1367 o = s.option(form.DummyValue, 'name', _('Device'));
1368 o.modalonly = false;
1369 o.textvalue = function(section_id) {
1370 var dev = getDevice(section_id),
1371 ext = section_id.match(/^dev:/),
1372 icon = render_iface(dev);
1373
1374 if (ext)
1375 icon.querySelector('img').style.opacity = '.5';
1376
1377 return E('span', { 'class': 'ifacebadge' }, [
1378 icon,
1379 E('span', { 'style': ext ? 'opacity:.5' : null }, [
1380 dev ? dev.getName() : (uci.get('network', section_id, 'name') || '?')
1381 ])
1382 ]);
1383 };
1384
1385 o = s.option(form.DummyValue, 'type', _('Type'));
1386 o.textvalue = getDevTypeDesc;
1387 o.modalonly = false;
1388
1389 o = s.option(form.DummyValue, 'macaddr', _('MAC Address'));
1390 o.modalonly = false;
1391 o.textvalue = function(section_id) {
1392 var dev = getDevice(section_id),
1393 val = uci.get('network', section_id, 'macaddr'),
1394 mac = dev ? dev.getMAC() : null;
1395
1396 return val ? E('strong', {
1397 'data-tooltip': _('The value is overridden by configuration. Original: %s').format(mac || _('unknown'))
1398 }, [ val.toUpperCase() ]) : (mac || '-');
1399 };
1400
1401 o = s.option(form.DummyValue, 'mtu', _('MTU'));
1402 o.modalonly = false;
1403 o.textvalue = function(section_id) {
1404 var dev = getDevice(section_id),
1405 val = uci.get('network', section_id, 'mtu'),
1406 mtu = dev ? dev.getMTU() : null;
1407
1408 return val ? E('strong', {
1409 'data-tooltip': _('The value is overridden by configuration. Original: %s').format(mtu || _('unknown'))
1410 }, [ val ]) : (mtu || '-').toString();
1411 };
1412
1413 s = m.section(form.TypedSection, 'globals', _('Global network options'));
1414 s.addremove = false;
1415 s.anonymous = true;
1416
1417 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.'));
1418 o.datatype = 'cidr6';
1419
1420 o = s.option(form.Flag, 'packet_steering', _('Packet Steering'), _('Enable packet steering across all CPUs. May help or hinder network speed.'));
1421 o.optional = true;
1422
1423
1424 if (dslModemType != null) {
1425 s = m.section(form.TypedSection, 'dsl', _('DSL'));
1426 s.anonymous = true;
1427
1428 o = s.option(form.ListValue, 'annex', _('Annex'));
1429 o.value('a', _('Annex A + L + M (all)'));
1430 o.value('b', _('Annex B (all)'));
1431 o.value('j', _('Annex J (all)'));
1432 o.value('m', _('Annex M (all)'));
1433 o.value('bdmt', _('Annex B G.992.1'));
1434 o.value('b2', _('Annex B G.992.3'));
1435 o.value('b2p', _('Annex B G.992.5'));
1436 o.value('at1', _('ANSI T1.413'));
1437 o.value('admt', _('Annex A G.992.1'));
1438 o.value('alite', _('Annex A G.992.2'));
1439 o.value('a2', _('Annex A G.992.3'));
1440 o.value('a2p', _('Annex A G.992.5'));
1441 o.value('l', _('Annex L G.992.3 POTS 1'));
1442 o.value('m2', _('Annex M G.992.3'));
1443 o.value('m2p', _('Annex M G.992.5'));
1444
1445 o = s.option(form.ListValue, 'tone', _('Tone'));
1446 o.value('', _('auto'));
1447 o.value('a', _('A43C + J43 + A43'));
1448 o.value('av', _('A43C + J43 + A43 + V43'));
1449 o.value('b', _('B43 + B43C'));
1450 o.value('bv', _('B43 + B43C + V43'));
1451
1452 if (dslModemType == 'vdsl') {
1453 o = s.option(form.ListValue, 'xfer_mode', _('Encapsulation mode'));
1454 o.value('', _('auto'));
1455 o.value('atm', _('ATM (Asynchronous Transfer Mode)'));
1456 o.value('ptm', _('PTM/EFM (Packet Transfer Mode)'));
1457
1458 o = s.option(form.ListValue, 'line_mode', _('DSL line mode'));
1459 o.value('', _('auto'));
1460 o.value('adsl', _('ADSL'));
1461 o.value('vdsl', _('VDSL'));
1462
1463 o = s.option(form.ListValue, 'ds_snr_offset', _('Downstream SNR offset'));
1464 o.default = '0';
1465
1466 for (var i = -100; i <= 100; i += 5)
1467 o.value(i, _('%.1f dB').format(i / 10));
1468 }
1469
1470 s.option(form.Value, 'firmware', _('Firmware File'));
1471 }
1472
1473
1474 // Show ATM bridge section if we have the capabilities
1475 if (L.hasSystemFeature('br2684ctl')) {
1476 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.'));
1477
1478 s.addremove = true;
1479 s.anonymous = true;
1480 s.addbtntitle = _('Add ATM Bridge');
1481
1482 s.handleAdd = function(ev) {
1483 var sections = uci.sections('network', 'atm-bridge'),
1484 max_unit = -1;
1485
1486 for (var i = 0; i < sections.length; i++) {
1487 var unit = +sections[i].unit;
1488
1489 if (!isNaN(unit) && unit > max_unit)
1490 max_unit = unit;
1491 }
1492
1493 return this.map.save(function() {
1494 var sid = uci.add('network', 'atm-bridge');
1495
1496 uci.set('network', sid, 'unit', max_unit + 1);
1497 uci.set('network', sid, 'atmdev', 0);
1498 uci.set('network', sid, 'encaps', 'llc');
1499 uci.set('network', sid, 'payload', 'bridged');
1500 uci.set('network', sid, 'vci', 35);
1501 uci.set('network', sid, 'vpi', 8);
1502 });
1503 };
1504
1505 s.tab('general', _('General Setup'));
1506 s.tab('advanced', _('Advanced Settings'));
1507
1508 o = s.taboption('general', form.Value, 'vci', _('ATM Virtual Channel Identifier (VCI)'));
1509 s.taboption('general', form.Value, 'vpi', _('ATM Virtual Path Identifier (VPI)'));
1510
1511 o = s.taboption('general', form.ListValue, 'encaps', _('Encapsulation mode'));
1512 o.value('llc', _('LLC'));
1513 o.value('vc', _('VC-Mux'));
1514
1515 s.taboption('advanced', form.Value, 'atmdev', _('ATM device number'));
1516 s.taboption('advanced', form.Value, 'unit', _('Bridge unit number'));
1517
1518 o = s.taboption('advanced', form.ListValue, 'payload', _('Forwarding mode'));
1519 o.value('bridged', _('bridged'));
1520 o.value('routed', _('routed'));
1521 }
1522
1523
1524 return m.render().then(L.bind(function(m, nodes) {
1525 poll.add(L.bind(function() {
1526 var section_ids = m.children[0].cfgsections(),
1527 tasks = [];
1528
1529 for (var i = 0; i < section_ids.length; i++) {
1530 var row = nodes.querySelector('.cbi-section-table-row[data-sid="%s"]'.format(section_ids[i])),
1531 dsc = row.querySelector('[data-name="_ifacestat"] > div'),
1532 btn1 = row.querySelector('.cbi-section-actions .reconnect'),
1533 btn2 = row.querySelector('.cbi-section-actions .down');
1534
1535 if (dsc.getAttribute('reconnect') == '') {
1536 dsc.setAttribute('reconnect', '1');
1537 tasks.push(fs.exec('/sbin/ifup', [section_ids[i]]).catch(function(e) {
1538 ui.addNotification(null, E('p', e.message));
1539 }));
1540 }
1541 else if (dsc.getAttribute('disconnect') == '') {
1542 dsc.setAttribute('disconnect', '1');
1543 tasks.push(fs.exec('/sbin/ifdown', [section_ids[i]]).catch(function(e) {
1544 ui.addNotification(null, E('p', e.message));
1545 }));
1546 }
1547 else if (dsc.getAttribute('reconnect') == '1') {
1548 dsc.removeAttribute('reconnect');
1549 btn1.classList.remove('spinning');
1550 btn1.disabled = false;
1551 }
1552 else if (dsc.getAttribute('disconnect') == '1') {
1553 dsc.removeAttribute('disconnect');
1554 btn2.classList.remove('spinning');
1555 btn2.disabled = false;
1556 }
1557 }
1558
1559 return Promise.all(tasks)
1560 .then(L.bind(network.getNetworks, network))
1561 .then(L.bind(this.poll_status, this, nodes));
1562 }, this), 5);
1563
1564 return nodes;
1565 }, this, m));
1566 }
1567 });