luci-mod-network: 'relay' tab added
[project/luci.git] / modules / luci-mod-network / htdocs / luci-static / resources / view / network / dhcp.js
1 'use strict';
2 'require view';
3 'require dom';
4 'require poll';
5 'require rpc';
6 'require uci';
7 'require form';
8 'require network';
9 'require validation';
10 'require tools.widgets as widgets';
11
12 var callHostHints, callDUIDHints, callDHCPLeases, CBILeaseStatus, CBILease6Status;
13
14 callHostHints = rpc.declare({
15 object: 'luci-rpc',
16 method: 'getHostHints',
17 expect: { '': {} }
18 });
19
20 callDUIDHints = rpc.declare({
21 object: 'luci-rpc',
22 method: 'getDUIDHints',
23 expect: { '': {} }
24 });
25
26 callDHCPLeases = rpc.declare({
27 object: 'luci-rpc',
28 method: 'getDHCPLeases',
29 expect: { '': {} }
30 });
31
32 CBILeaseStatus = form.DummyValue.extend({
33 renderWidget: function(section_id, option_id, cfgvalue) {
34 return E([
35 E('h4', _('Active DHCP Leases')),
36 E('table', { 'id': 'lease_status_table', 'class': 'table' }, [
37 E('tr', { 'class': 'tr table-titles' }, [
38 E('th', { 'class': 'th' }, _('Hostname')),
39 E('th', { 'class': 'th' }, _('IPv4 address')),
40 E('th', { 'class': 'th' }, _('MAC address')),
41 E('th', { 'class': 'th' }, _('Lease time remaining'))
42 ]),
43 E('tr', { 'class': 'tr placeholder' }, [
44 E('td', { 'class': 'td' }, E('em', _('Collecting data...')))
45 ])
46 ])
47 ]);
48 }
49 });
50
51 CBILease6Status = form.DummyValue.extend({
52 renderWidget: function(section_id, option_id, cfgvalue) {
53 return E([
54 E('h4', _('Active DHCPv6 Leases')),
55 E('table', { 'id': 'lease6_status_table', 'class': 'table' }, [
56 E('tr', { 'class': 'tr table-titles' }, [
57 E('th', { 'class': 'th' }, _('Host')),
58 E('th', { 'class': 'th' }, _('IPv6 address')),
59 E('th', { 'class': 'th' }, _('DUID')),
60 E('th', { 'class': 'th' }, _('Lease time remaining'))
61 ]),
62 E('tr', { 'class': 'tr placeholder' }, [
63 E('td', { 'class': 'td' }, E('em', _('Collecting data...')))
64 ])
65 ])
66 ]);
67 }
68 });
69
70 function calculateNetwork(addr, mask) {
71 addr = validation.parseIPv4(String(addr));
72
73 if (!isNaN(mask))
74 mask = validation.parseIPv4(network.prefixToMask(+mask));
75 else
76 mask = validation.parseIPv4(String(mask));
77
78 if (addr == null || mask == null)
79 return null;
80
81 return [
82 [
83 addr[0] & (mask[0] >>> 0 & 255),
84 addr[1] & (mask[1] >>> 0 & 255),
85 addr[2] & (mask[2] >>> 0 & 255),
86 addr[3] & (mask[3] >>> 0 & 255)
87 ].join('.'),
88 mask.join('.')
89 ];
90 }
91
92 function getDHCPPools() {
93 return uci.load('dhcp').then(function() {
94 let sections = uci.sections('dhcp', 'dhcp'),
95 tasks = [], pools = [];
96
97 for (var i = 0; i < sections.length; i++) {
98 if (sections[i].ignore == '1' || !sections[i].interface)
99 continue;
100
101 tasks.push(network.getNetwork(sections[i].interface).then(L.bind(function(section_id, net) {
102 var cidr = net ? (net.getIPAddrs()[0] || '').split('/') : null;
103
104 if (cidr && cidr.length == 2) {
105 var net_mask = calculateNetwork(cidr[0], cidr[1]);
106
107 pools.push({
108 section_id: section_id,
109 network: net_mask[0],
110 netmask: net_mask[1]
111 });
112 }
113 }, null, sections[i]['.name'])));
114 }
115
116 return Promise.all(tasks).then(function() {
117 return pools;
118 });
119 });
120 }
121
122 function validateHostname(sid, s) {
123 if (s == null || s == '')
124 return true;
125
126 if (s.length > 256)
127 return _('Expecting: %s').format(_('valid hostname'));
128
129 var labels = s.replace(/^\.+|\.$/g, '').split(/\./);
130
131 for (var i = 0; i < labels.length; i++)
132 if (!labels[i].match(/^[a-z0-9_](?:[a-z0-9-]{0,61}[a-z0-9])?$/i))
133 return _('Expecting: %s').format(_('valid hostname'));
134
135 return true;
136 }
137
138 function validateAddressList(sid, s) {
139 if (s == null || s == '')
140 return true;
141
142 var m = s.match(/^\/(.+)\/$/),
143 names = m ? m[1].split(/\//) : [ s ];
144
145 for (var i = 0; i < names.length; i++) {
146 var res = validateHostname(sid, names[i]);
147
148 if (res !== true)
149 return res;
150 }
151
152 return true;
153 }
154
155 function validateServerSpec(sid, s) {
156 if (s == null || s == '')
157 return true;
158
159 var m = s.match(/^(?:\/(.+)\/)?(.*)$/);
160 if (!m)
161 return _('Expecting: %s').format(_('valid hostname'));
162
163 var res = validateAddressList(sid, m[1]);
164 if (res !== true)
165 return res;
166
167 if (m[2] == '' || m[2] == '#')
168 return true;
169
170 // ipaddr%scopeid#srvport@source@interface#srcport
171
172 m = m[2].match(/^([0-9a-f:.]+)(?:%[^#@]+)?(?:#(\d+))?(?:@([0-9a-f:.]+)(?:@[^#]+)?(?:#(\d+))?)?$/);
173
174 if (!m)
175 return _('Expecting: %s').format(_('valid IP address'));
176
177 if (validation.parseIPv4(m[1])) {
178 if (m[3] != null && !validation.parseIPv4(m[3]))
179 return _('Expecting: %s').format(_('valid IPv4 address'));
180 }
181 else if (validation.parseIPv6(m[1])) {
182 if (m[3] != null && !validation.parseIPv6(m[3]))
183 return _('Expecting: %s').format(_('valid IPv6 address'));
184 }
185 else {
186 return _('Expecting: %s').format(_('valid IP address'));
187 }
188
189 if ((m[2] != null && +m[2] > 65535) || (m[4] != null && +m[4] > 65535))
190 return _('Expecting: %s').format(_('valid port value'));
191
192 return true;
193 }
194
195 function validateMACAddr(pools, sid, s) {
196 if (s == null || s == '')
197 return true;
198
199 var leases = uci.sections('dhcp', 'host'),
200 this_macs = L.toArray(s).map(function(m) { return m.toUpperCase() });
201
202 for (var i = 0; i < pools.length; i++) {
203 var this_net_mask = calculateNetwork(this.section.formvalue(sid, 'ip'), pools[i].netmask);
204
205 if (!this_net_mask)
206 continue;
207
208 for (var j = 0; j < leases.length; j++) {
209 if (leases[j]['.name'] == sid || !leases[j].ip)
210 continue;
211
212 var lease_net_mask = calculateNetwork(leases[j].ip, pools[i].netmask);
213
214 if (!lease_net_mask || this_net_mask[0] != lease_net_mask[0])
215 continue;
216
217 var lease_macs = L.toArray(leases[j].mac).map(function(m) { return m.toUpperCase() });
218
219 for (var k = 0; k < lease_macs.length; k++)
220 for (var l = 0; l < this_macs.length; l++)
221 if (lease_macs[k] == this_macs[l])
222 return _('The MAC address %h is already used by another static lease in the same DHCP pool').format(this_macs[l]);
223 }
224 }
225
226 return true;
227 }
228
229 return view.extend({
230 load: function() {
231 return Promise.all([
232 callHostHints(),
233 callDUIDHints(),
234 getDHCPPools(),
235 network.getDevices()
236 ]);
237 },
238
239 render: function(hosts_duids_pools) {
240 var has_dhcpv6 = L.hasSystemFeature('dnsmasq', 'dhcpv6') || L.hasSystemFeature('odhcpd'),
241 hosts = hosts_duids_pools[0],
242 duids = hosts_duids_pools[1],
243 pools = hosts_duids_pools[2],
244 ndevs = hosts_duids_pools[3],
245 m, s, o, ss, so;
246
247 m = new form.Map('dhcp', _('DHCP and DNS'),
248 _('Dnsmasq is a lightweight <abbr title="Dynamic Host Configuration Protocol">DHCP</abbr> server and <abbr title="Domain Name System">DNS</abbr> forwarder.'));
249
250 s = m.section(form.TypedSection, 'dnsmasq');
251 s.anonymous = true;
252 s.addremove = false;
253
254 s.tab('general', _('General Settings'));
255 s.tab('relay', _('Relay'));
256 s.tab('files', _('Resolv and Hosts Files'));
257 s.tab('pxe_tftp', _('PXE/TFTP Settings'));
258 s.tab('advanced', _('Advanced Settings'));
259 s.tab('leases', _('Static Leases'));
260 s.tab('hosts', _('Hostnames'));
261 s.tab('ipsets', _('IP Sets'));
262
263 s.taboption('general', form.Flag, 'domainneeded',
264 _('Domain required'),
265 _('Do not forward DNS queries without dots or domain parts.'));
266
267 s.taboption('general', form.Flag, 'authoritative',
268 _('Authoritative'),
269 _('This is the only DHCP server in the local network.'));
270
271 s.taboption('general', form.Value, 'local',
272 _('Local server'),
273 _('Never forward matching domains and subdomains, resolve from DHCP or hosts files only.'));
274
275 s.taboption('general', form.Value, 'domain',
276 _('Local domain'),
277 _('Local domain suffix appended to DHCP names and hosts file entries.'));
278
279 o = s.taboption('general', form.Flag, 'logqueries',
280 _('Log queries'),
281 _('Write received DNS queries to syslog.'));
282 o.optional = true;
283
284 o = s.taboption('general', form.DynamicList, 'server',
285 _('DNS forwardings'),
286 _('List of upstream resolvers to forward queries to.'));
287 o.optional = true;
288 o.placeholder = '/example.org/10.1.2.3';
289 o.validate = validateServerSpec;
290
291 o = s.taboption('general', form.DynamicList, 'address',
292 _('Addresses'),
293 _('List of domains to force to an IP address.'));
294 o.optional = true;
295 o.placeholder = '/router.local/192.168.0.1';
296
297 o = s.taboption('general', form.DynamicList, 'ipset',
298 _('IP sets'),
299 _('List of IP sets to populate with the specified domain IPs.'));
300 o.optional = true;
301 o.placeholder = '/example.org/ipset,ipset6';
302
303 o = s.taboption('general', form.Flag, 'rebind_protection',
304 _('Rebind protection'),
305 _('Discard upstream responses containing <a href="%s">RFC1918</a> addresses.').format('https://datatracker.ietf.org/doc/html/rfc1918'));
306 o.rmempty = false;
307
308 o = s.taboption('general', form.Flag, 'rebind_localhost',
309 _('Allow localhost'),
310 _('Exempt <code>127.0.0.0/8</code> and <code>::1</code> from rebinding checks, e.g. for RBL services.'));
311 o.depends('rebind_protection', '1');
312
313 o = s.taboption('general', form.DynamicList, 'rebind_domain',
314 _('Domain whitelist'),
315 _('List of domains to allow RFC1918 responses for.'));
316 o.depends('rebind_protection', '1');
317 o.optional = true;
318 o.placeholder = 'ihost.netflix.com';
319 o.validate = validateAddressList;
320
321 o = s.taboption('general', form.Flag, 'localservice',
322 _('Local service only'),
323 _('Accept DNS queries only from hosts whose address is on a local subnet.'));
324 o.optional = false;
325 o.rmempty = false;
326
327 o = s.taboption('general', form.Flag, 'nonwildcard',
328 _('Non-wildcard'),
329 _('Bind dynamically to interfaces rather than wildcard address.'));
330 o.default = o.enabled;
331 o.optional = false;
332 o.rmempty = true;
333
334 o = s.taboption('general', form.DynamicList, 'interface',
335 _('Listen interfaces'),
336 _('Listen only on the specified interfaces, and loopback if not excluded explicitly.'));
337 o.optional = true;
338 o.placeholder = 'lan';
339
340 o = s.taboption('general', form.DynamicList, 'notinterface',
341 _('Exclude interfaces'),
342 _('Do not listen on the specified interfaces.'));
343 o.optional = true;
344 o.placeholder = 'loopback';
345
346 o = s.taboption('relay', form.SectionValue, '__relays__', form.TableSection, 'relay', null,
347 _('Relay DHCP requests elsewhere. OK: v4<->v4, v6<->v6. Not OK: v4<->v6, v6<->v4.')
348 + '<br />' + _('Note: you may also need a DHCP Proxy (currently unavailable) when specifying a non-standard Relay To port(<code>addr#port</code>).')
349 + '<br />' + _('You may add multiple unique Relay To on the same Listen addr.'));
350
351 ss = o.subsection;
352
353 ss.addremove = true;
354 ss.anonymous = true;
355 ss.sortable = true;
356 ss.rowcolors = true;
357 ss.nodescriptions = true;
358
359 so = ss.option(form.Value, 'id', _('ID'));
360 so.rmempty = false;
361 so.optional = true;
362
363 so = ss.option(widgets.NetworkSelect, 'interface', _('Interface'));
364 so.optional = true;
365 so.rmempty = false;
366 so.placeholder = 'lan';
367
368 so = ss.option(form.Value, 'local_addr', _('Listen address'));
369 so.rmempty = false;
370 so.datatype = 'ipaddr';
371
372 for (var family = 4; family <= 6; family += 2) {
373 for (var i = 0; i < ndevs.length; i++) {
374 var addrs = (family == 6) ? ndevs[i].getIP6Addrs() : ndevs[i].getIPAddrs();
375 for (var j = 0; j < addrs.length; j++)
376 so.value(addrs[j].split('/')[0]);
377 }
378 }
379
380 so = ss.option(form.Value, 'server_addr', _('Relay To address'));
381 so.rmempty = false;
382 so.optional = false;
383 so.placeholder = '192.168.10.1#535';
384
385 so.validate = function(section, value) {
386 var m = this.section.formvalue(section, 'local_addr'),
387 n = this.section.formvalue(section, 'server_addr'),
388 p;
389 if (n != null && n != '')
390 p = n.split('#');
391 if (p.length > 1 && !/^[0-9]+$/.test(p[1]))
392 return _('Expected port number.');
393 else
394 n = p[0];
395
396 if ((m == null || m == '') && (n == null || n == ''))
397 return _('Both Listen addr and Relay To must be specified.');
398
399 if ((validation.parseIPv6(m) && validation.parseIPv6(n)) ||
400 validation.parseIPv4(m) && validation.parseIPv4(n))
401 return true;
402 else
403 return _('Listen and Relay To IP family must be homogeneous.')
404 };
405
406 s.taboption('files', form.Flag, 'readethers',
407 _('Use <code>/etc/ethers</code>'),
408 _('Read <code>/etc/ethers</code> to configure the DHCP server.'));
409
410 s.taboption('files', form.Value, 'leasefile',
411 _('Lease file'),
412 _('File to store DHCP lease information.'));
413
414 o = s.taboption('files', form.Flag, 'noresolv',
415 _('Ignore resolv file'));
416 o.optional = true;
417
418 o = s.taboption('files', form.Value, 'resolvfile',
419 _('Resolv file'),
420 _('File with upstream resolvers.'));
421 o.depends('noresolv', '0');
422 o.placeholder = '/tmp/resolv.conf.d/resolv.conf.auto';
423 o.optional = true;
424
425 o = s.taboption('files', form.Flag, 'nohosts',
426 _('Ignore <code>/etc/hosts</code>'));
427 o.optional = true;
428
429 o = s.taboption('files', form.DynamicList, 'addnhosts',
430 _('Additional hosts files'));
431 o.optional = true;
432 o.placeholder = '/etc/dnsmasq.hosts';
433
434 o = s.taboption('advanced', form.Flag, 'quietdhcp',
435 _('Suppress logging'),
436 _('Suppress logging of the routine operation for the DHCP protocol.'));
437 o.optional = true;
438
439 o = s.taboption('advanced', form.Flag, 'sequential_ip',
440 _('Allocate IPs sequentially'),
441 _('Allocate IP addresses sequentially, starting from the lowest available address.'));
442 o.optional = true;
443
444 o = s.taboption('advanced', form.Flag, 'boguspriv',
445 _('Filter private'),
446 _('Do not forward reverse lookups for local networks.'));
447 o.default = o.enabled;
448
449 s.taboption('advanced', form.Flag, 'filterwin2k',
450 _('Filter useless'),
451 _('Avoid uselessly triggering dial-on-demand links (filters SRV/SOA records and names with underscores).') + '<br />' +
452 _('May prevent VoIP or other services from working.'));
453
454 s.taboption('advanced', form.Flag, 'localise_queries',
455 _('Localise queries'),
456 _('Return answers to DNS queries matching the subnet from which the query was received if multiple IPs are available.'));
457
458 if (L.hasSystemFeature('dnsmasq', 'dnssec')) {
459 o = s.taboption('advanced', form.Flag, 'dnssec',
460 _('DNSSEC'),
461 _('Validate DNS replies and cache DNSSEC data, requires upstream to support DNSSEC.'));
462 o.optional = true;
463
464 o = s.taboption('advanced', form.Flag, 'dnsseccheckunsigned',
465 _('DNSSEC check unsigned'),
466 _('Verify unsigned domain responses really come from unsigned domains.'));
467 o.default = o.enabled;
468 o.optional = true;
469 }
470
471 s.taboption('advanced', form.Flag, 'expandhosts',
472 _('Expand hosts'),
473 _('Add local domain suffix to names served from hosts files.'));
474
475 s.taboption('advanced', form.Flag, 'nonegcache',
476 _('No negative cache'),
477 _('Do not cache negative replies, e.g. for non-existent domains.'));
478
479 o = s.taboption('advanced', form.Value, 'serversfile',
480 _('Additional servers file'),
481 _('File listing upstream resolvers, optionally domain-specific, e.g. <code>server=1.2.3.4</code>, <code>server=/domain/1.2.3.4</code>.'));
482 o.placeholder = '/etc/dnsmasq.servers';
483
484 o = s.taboption('advanced', form.Flag, 'strictorder',
485 _('Strict order'),
486 _('Upstream resolvers will be queried in the order of the resolv file.'));
487 o.optional = true;
488
489 o = s.taboption('advanced', form.Flag, 'allservers',
490 _('All servers'),
491 _('Query all available upstream resolvers.'));
492 o.optional = true;
493
494 o = s.taboption('advanced', form.DynamicList, 'bogusnxdomain',
495 _('IPs to override with NXDOMAIN'),
496 _('List of IP addresses to convert into NXDOMAIN responses.'));
497 o.optional = true;
498 o.placeholder = '64.94.110.11';
499
500 o = s.taboption('advanced', form.Value, 'port',
501 _('DNS server port'),
502 _('Listening port for inbound DNS queries.'));
503 o.optional = true;
504 o.datatype = 'port';
505 o.placeholder = 53;
506
507 o = s.taboption('advanced', form.Value, 'queryport',
508 _('DNS query port'),
509 _('Fixed source port for outbound DNS queries.'));
510 o.optional = true;
511 o.datatype = 'port';
512 o.placeholder = _('any');
513
514 o = s.taboption('advanced', form.Value, 'dhcpleasemax',
515 _('Max. DHCP leases'),
516 _('Maximum allowed number of active DHCP leases.'));
517 o.optional = true;
518 o.datatype = 'uinteger';
519 o.placeholder = _('unlimited');
520
521 o = s.taboption('advanced', form.Value, 'ednspacket_max',
522 _('Max. EDNS0 packet size'),
523 _('Maximum allowed size of EDNS0 UDP packets.'));
524 o.optional = true;
525 o.datatype = 'uinteger';
526 o.placeholder = 1280;
527
528 o = s.taboption('advanced', form.Value, 'dnsforwardmax',
529 _('Max. concurrent queries'),
530 _('Maximum allowed number of concurrent DNS queries.'));
531 o.optional = true;
532 o.datatype = 'uinteger';
533 o.placeholder = 150;
534
535 o = s.taboption('advanced', form.Value, 'cachesize',
536 _('Size of DNS query cache'),
537 _('Number of cached DNS entries, 10000 is maximum, 0 is no caching.'));
538 o.optional = true;
539 o.datatype = 'range(0,10000)';
540 o.placeholder = 150;
541
542 o = s.taboption('pxe_tftp', form.Flag, 'enable_tftp',
543 _('Enable TFTP server'),
544 _('Enable the built-in single-instance TFTP server.'));
545 o.optional = true;
546
547 o = s.taboption('pxe_tftp', form.Value, 'tftp_root',
548 _('TFTP server root'),
549 _('Root directory for files served via TFTP. <em>Enable TFTP server</em> and <em>TFTP server root</em> turn on the TFTP server and serve files from <em>TFTP server root</em>.'));
550 o.depends('enable_tftp', '1');
551 o.optional = true;
552 o.placeholder = '/';
553
554 o = s.taboption('pxe_tftp', form.Value, 'dhcp_boot',
555 _('Network boot image'),
556 _('Filename of the boot image advertised to clients.'));
557 o.depends('enable_tftp', '1');
558 o.optional = true;
559 o.placeholder = 'pxelinux.0';
560
561 /* PXE - https://openwrt.org/docs/guide-user/base-system/dhcp#booting_options */
562 o = s.taboption('pxe_tftp', form.SectionValue, '__pxe__', form.GridSection, 'boot', null,
563 _('Special <abbr title="Preboot eXecution Environment">PXE</abbr> boot options for Dnsmasq.'));
564 ss = o.subsection;
565 ss.addremove = true;
566 ss.anonymous = true;
567 ss.nodescriptions = true;
568
569 so = ss.option(form.Value, 'filename',
570 _('Filename'),
571 _('Host requests this filename from the boot server.'));
572 so.optional = false;
573 so.placeholder = 'pxelinux.0';
574
575 so = ss.option(form.Value, 'servername',
576 _('Server name'),
577 _('The hostname of the boot server'));
578 so.optional = false;
579 so.placeholder = 'myNAS';
580
581 so = ss.option(form.Value, 'serveraddress',
582 _('Server address'),
583 _('The IP address of the boot server'));
584 so.optional = false;
585 so.placeholder = '192.168.1.2';
586
587 so = ss.option(form.DynamicList, 'dhcp_option',
588 _('DHCP Options'),
589 _('Options for the Network-ID. (Note: needs also Network-ID.) E.g. "<code>42,192.168.1.4</code>" for NTP server, "<code>3,192.168.4.4</code>" for default route. <code>0.0.0.0</code> means "the address of the system running dnsmasq".'));
590 so.optional = true;
591 so.placeholder = '42,192.168.1.4';
592
593 so = ss.option(widgets.DeviceSelect, 'networkid',
594 _('Network-ID'),
595 _('Apply DHCP Options to this net. (Empty = all clients).'));
596 so.optional = true;
597 so.noaliases = true;
598
599 so = ss.option(form.Flag, 'force',
600 _('Force'),
601 _('Always send DHCP Options. Sometimes needed, with e.g. PXELinux.'));
602 so.optional = true;
603
604 so = ss.option(form.Value, 'instance',
605 _('Instance'),
606 _('Dnsmasq instance to which this boot section is bound. If unspecified, the section is valid for all dnsmasq instances.'));
607 so.optional = true;
608
609 Object.values(L.uci.sections('dhcp', 'dnsmasq')).forEach(function(val, index) {
610 so.value(index, '%s (Domain: %s, Local: %s)'.format(index, val.domain || '?', val.local || '?'));
611 });
612
613 o = s.taboption('hosts', form.SectionValue, '__hosts__', form.GridSection, 'domain', null,
614 _('Hostnames are used to bind a domain name to an IP address. This setting is redundant for hostnames already configured with static leases, but it can be useful to rebind an FQDN.'));
615
616 ss = o.subsection;
617
618 ss.addremove = true;
619 ss.anonymous = true;
620 ss.sortable = true;
621
622 so = ss.option(form.Value, 'name', _('Hostname'));
623 so.rmempty = false;
624 so.datatype = 'hostname';
625
626 so = ss.option(form.Value, 'ip', _('IP address'));
627 so.rmempty = false;
628 so.datatype = 'ipaddr';
629
630 var ipaddrs = {};
631
632 Object.keys(hosts).forEach(function(mac) {
633 var addrs = L.toArray(hosts[mac].ipaddrs || hosts[mac].ipv4);
634
635 for (var i = 0; i < addrs.length; i++)
636 ipaddrs[addrs[i]] = hosts[mac].name || mac;
637 });
638
639 L.sortedKeys(ipaddrs, null, 'addr').forEach(function(ipv4) {
640 so.value(ipv4, '%s (%s)'.format(ipv4, ipaddrs[ipv4]));
641 });
642
643 o = s.taboption('ipsets', form.SectionValue, '__ipsets__', form.GridSection, 'ipset', null,
644 _('List of IP sets to populate with the specified domain IPs.'));
645
646 ss = o.subsection;
647
648 ss.addremove = true;
649 ss.anonymous = true;
650 ss.sortable = true;
651
652 so = ss.option(form.DynamicList, 'name', _('IP set'));
653 so.rmempty = false;
654 so.datatype = 'string';
655
656 so = ss.option(form.DynamicList, 'domain', _('Domain'));
657 so.rmempty = false;
658 so.datatype = 'hostname';
659
660 o = s.taboption('leases', form.SectionValue, '__leases__', form.GridSection, 'host', null,
661 _('Static leases are used to assign fixed IP addresses and symbolic hostnames to DHCP clients. They are also required for non-dynamic interface configurations where only hosts with a corresponding lease are served.') + '<br />' +
662 _('Use the <em>Add</em> Button to add a new lease entry. The <em>MAC address</em> identifies the host, the <em>IPv4 address</em> specifies the fixed address to use, and the <em>Hostname</em> is assigned as a symbolic name to the requesting host. The optional <em>Lease time</em> can be used to set non-standard host-specific lease time, e.g. 12h, 3d or infinite.'));
663
664 ss = o.subsection;
665
666 ss.addremove = true;
667 ss.anonymous = true;
668 ss.sortable = true;
669
670 so = ss.option(form.Value, 'name', _('Hostname'));
671 so.validate = validateHostname;
672 so.rmempty = true;
673 so.write = function(section, value) {
674 uci.set('dhcp', section, 'name', value);
675 uci.set('dhcp', section, 'dns', '1');
676 };
677 so.remove = function(section) {
678 uci.unset('dhcp', section, 'name');
679 uci.unset('dhcp', section, 'dns');
680 };
681
682 so = ss.option(form.Value, 'mac', _('MAC address'));
683 so.datatype = 'list(macaddr)';
684 so.rmempty = true;
685 so.cfgvalue = function(section) {
686 var macs = L.toArray(uci.get('dhcp', section, 'mac')),
687 result = [];
688
689 for (var i = 0, mac; (mac = macs[i]) != null; i++)
690 if (/^([0-9a-fA-F]{1,2}):([0-9a-fA-F]{1,2}):([0-9a-fA-F]{1,2}):([0-9a-fA-F]{1,2}):([0-9a-fA-F]{1,2}):([0-9a-fA-F]{1,2})$/.test(mac))
691 result.push('%02X:%02X:%02X:%02X:%02X:%02X'.format(
692 parseInt(RegExp.$1, 16), parseInt(RegExp.$2, 16),
693 parseInt(RegExp.$3, 16), parseInt(RegExp.$4, 16),
694 parseInt(RegExp.$5, 16), parseInt(RegExp.$6, 16)));
695
696 return result.length ? result.join(' ') : null;
697 };
698 so.renderWidget = function(section_id, option_index, cfgvalue) {
699 var node = form.Value.prototype.renderWidget.apply(this, [section_id, option_index, cfgvalue]),
700 ipopt = this.section.children.filter(function(o) { return o.option == 'ip' })[0];
701
702 node.addEventListener('cbi-dropdown-change', L.bind(function(ipopt, section_id, ev) {
703 var mac = ev.detail.value.value;
704 if (mac == null || mac == '' || !hosts[mac])
705 return;
706
707 var iphint = L.toArray(hosts[mac].ipaddrs || hosts[mac].ipv4)[0];
708 if (iphint == null)
709 return;
710
711 var ip = ipopt.formvalue(section_id);
712 if (ip != null && ip != '')
713 return;
714
715 var node = ipopt.map.findElement('id', ipopt.cbid(section_id));
716 if (node)
717 dom.callClassMethod(node, 'setValue', iphint);
718 }, this, ipopt, section_id));
719
720 return node;
721 };
722 so.validate = validateMACAddr.bind(so, pools);
723 Object.keys(hosts).forEach(function(mac) {
724 var hint = hosts[mac].name || L.toArray(hosts[mac].ipaddrs || hosts[mac].ipv4)[0];
725 so.value(mac, hint ? '%s (%s)'.format(mac, hint) : mac);
726 });
727
728 so = ss.option(form.Value, 'ip', _('IPv4 address'));
729 so.datatype = 'or(ip4addr,"ignore")';
730 so.validate = function(section, value) {
731 var m = this.section.formvalue(section, 'mac'),
732 n = this.section.formvalue(section, 'name');
733
734 if ((m == null || m == '') && (n == null || n == ''))
735 return _('One of hostname or MAC address must be specified!');
736
737 if (value == null || value == '' || value == 'ignore')
738 return true;
739
740 var leases = uci.sections('dhcp', 'host');
741
742 for (var i = 0; i < leases.length; i++)
743 if (leases[i]['.name'] != section && leases[i].ip == value)
744 return _('The IP address %h is already used by another static lease').format(value);
745
746 for (var i = 0; i < pools.length; i++) {
747 var net_mask = calculateNetwork(value, pools[i].netmask);
748
749 if (net_mask && net_mask[0] == pools[i].network)
750 return true;
751 }
752
753 return _('The IP address is outside of any DHCP pool address range');
754 };
755
756 L.sortedKeys(ipaddrs, null, 'addr').forEach(function(ipv4) {
757 so.value(ipv4, ipaddrs[ipv4] ? '%s (%s)'.format(ipv4, ipaddrs[ipv4]) : ipv4);
758 });
759
760 so = ss.option(form.Value, 'leasetime', _('Lease time'));
761 so.rmempty = true;
762
763 so = ss.option(form.Value, 'duid', _('DUID'));
764 so.datatype = 'and(rangelength(20,36),hexstring)';
765 Object.keys(duids).forEach(function(duid) {
766 so.value(duid, '%s (%s)'.format(duid, duids[duid].hostname || duids[duid].macaddr || duids[duid].ip6addr || '?'));
767 });
768
769 so = ss.option(form.Value, 'hostid', _('IPv6 suffix (hex)'));
770
771 o = s.taboption('leases', CBILeaseStatus, '__status__');
772
773 if (has_dhcpv6)
774 o = s.taboption('leases', CBILease6Status, '__status6__');
775
776 return m.render().then(function(mapEl) {
777 poll.add(function() {
778 return callDHCPLeases().then(function(leaseinfo) {
779 var leases = Array.isArray(leaseinfo.dhcp_leases) ? leaseinfo.dhcp_leases : [],
780 leases6 = Array.isArray(leaseinfo.dhcp6_leases) ? leaseinfo.dhcp6_leases : [];
781
782 cbi_update_table(mapEl.querySelector('#lease_status_table'),
783 leases.map(function(lease) {
784 var exp;
785
786 if (lease.expires === false)
787 exp = E('em', _('unlimited'));
788 else if (lease.expires <= 0)
789 exp = E('em', _('expired'));
790 else
791 exp = '%t'.format(lease.expires);
792
793 var hint = lease.macaddr ? hosts[lease.macaddr] : null,
794 name = hint ? hint.name : null,
795 host = null;
796
797 if (name && lease.hostname && lease.hostname != name)
798 host = '%s (%s)'.format(lease.hostname, name);
799 else if (lease.hostname)
800 host = lease.hostname;
801
802 return [
803 host || '-',
804 lease.ipaddr,
805 lease.macaddr,
806 exp
807 ];
808 }),
809 E('em', _('There are no active leases')));
810
811 if (has_dhcpv6) {
812 cbi_update_table(mapEl.querySelector('#lease6_status_table'),
813 leases6.map(function(lease) {
814 var exp;
815
816 if (lease.expires === false)
817 exp = E('em', _('unlimited'));
818 else if (lease.expires <= 0)
819 exp = E('em', _('expired'));
820 else
821 exp = '%t'.format(lease.expires);
822
823 var hint = lease.macaddr ? hosts[lease.macaddr] : null,
824 name = hint ? (hint.name || L.toArray(hint.ipaddrs || hint.ipv4)[0] || L.toArray(hint.ip6addrs || hint.ipv6)[0]) : null,
825 host = null;
826
827 if (name && lease.hostname && lease.hostname != name && lease.ip6addr != name)
828 host = '%s (%s)'.format(lease.hostname, name);
829 else if (lease.hostname)
830 host = lease.hostname;
831 else if (name)
832 host = name;
833
834 return [
835 host || '-',
836 lease.ip6addrs ? lease.ip6addrs.join(' ') : lease.ip6addr,
837 lease.duid,
838 exp
839 ];
840 }),
841 E('em', _('There are no active leases')));
842 }
843 });
844 });
845
846 return mapEl;
847 });
848 }
849 });