luci-mod-network: adjust assoclist markup for easier styling
[oweals/luci.git] / modules / luci-mod-network / htdocs / luci-static / resources / view / network / wireless.js
1 'use strict';
2 'require fs';
3 'require ui';
4 'require rpc';
5 'require uci';
6 'require form';
7 'require network';
8 'require firewall';
9 'require tools.widgets as widgets';
10
11 function count_changes(section_id) {
12         var changes = ui.changes.changes, n = 0;
13
14         if (!L.isObject(changes))
15                 return n;
16
17         if (Array.isArray(changes.wireless))
18                 for (var i = 0; i < changes.wireless.length; i++)
19                         n += (changes.wireless[i][1] == section_id);
20
21         return n;
22 }
23
24 function render_radio_badge(radioDev) {
25         return E('span', { 'class': 'ifacebadge' }, [
26                 E('img', { 'src': L.resource('icons/wifi%s.png').format(radioDev.isUp() ? '' : '_disabled') }),
27                 ' ',
28                 radioDev.getName()
29         ]);
30 }
31
32 function render_signal_badge(signalPercent, signalValue, noiseValue, wrap) {
33         var icon, title, value;
34
35         if (signalPercent < 0)
36                 icon = L.resource('icons/signal-none.png');
37         else if (signalPercent == 0)
38                 icon = L.resource('icons/signal-0.png');
39         else if (signalPercent < 25)
40                 icon = L.resource('icons/signal-0-25.png');
41         else if (signalPercent < 50)
42                 icon = L.resource('icons/signal-25-50.png');
43         else if (signalPercent < 75)
44                 icon = L.resource('icons/signal-50-75.png');
45         else
46                 icon = L.resource('icons/signal-75-100.png');
47
48         if (signalValue != null && signalValue != 0 && noiseValue != null && noiseValue != 0) {
49                 value = '%d / %d %s'.format(signalValue, noiseValue, _('dBm'));
50                 title = '%s: %d %s / %s: %d %s / %s %d'.format(
51                         _('Signal'), signalValue, _('dBm'),
52                         _('Noise'), noiseValue, _('dBm'),
53                         _('SNR'), signalValue - noiseValue);
54         }
55         else if (signalValue != null && signalValue != 0) {
56                 value = '%d %s'.format(signalValue, _('dBm'));
57                 title = '%s: %d %s'.format(_('Signal'), signalValue, _('dBm'));
58         }
59         else if (signalPercent > -1) {
60                 value = '\xa0---\xa0';
61                 title = _('No signal');
62         }
63         else {
64                 value = E('em', {}, E('small', {}, [ _('disabled') ]));
65                 title = _('Interface is disabled');
66         }
67
68         return E('div', {
69                 'class': wrap ? 'center' : 'ifacebadge',
70                 'title': title,
71                 'data-signal': signalValue,
72                 'data-noise': noiseValue
73         }, [
74                 E('img', { 'src': icon }),
75                 E('span', {}, [
76                         wrap ? E('br') : ' ',
77                         value
78                 ])
79         ]);
80 }
81
82 function render_network_badge(radioNet) {
83         return render_signal_badge(radioNet.isUp() ? radioNet.getSignalPercent() : -1,  radioNet.getSignal(), radioNet.getNoise());
84 }
85
86 function render_radio_status(radioDev, wifiNets) {
87         var name = radioDev.getI18n().replace(/ Wireless Controller .+$/, ''),
88             node = E('div', [ E('big', {}, E('strong', {}, name)), E('div') ]),
89             channel, frequency, bitrate;
90
91         for (var i = 0; i < wifiNets.length; i++) {
92                 channel   = channel   || wifiNets[i].getChannel();
93                 frequency = frequency || wifiNets[i].getFrequency();
94                 bitrate   = bitrate   || wifiNets[i].getBitRate();
95         }
96
97         if (radioDev.isUp())
98                 L.itemlist(node.lastElementChild, [
99                         _('Channel'), '%s (%s %s)'.format(channel || '?', frequency || '?', _('GHz')),
100                         _('Bitrate'), '%s %s'.format(bitrate || '?', _('Mbit/s'))
101                 ], ' | ');
102         else
103                 node.lastElementChild.appendChild(E('em', _('Device is not active')));
104
105         return node;
106 }
107
108 function render_network_status(radioNet) {
109         var mode = radioNet.getActiveMode(),
110             bssid = radioNet.getActiveBSSID(),
111             channel = radioNet.getChannel(),
112             disabled = (radioNet.get('disabled') == '1' || uci.get('wireless', radioNet.getWifiDeviceName(), 'disabled') == '1'),
113             is_assoc = (bssid && bssid != '00:00:00:00:00:00' && channel && mode != 'Unknown' && !disabled),
114             is_mesh = (radioNet.getMode() == 'mesh'),
115             changecount = count_changes(radioNet.getName()),
116             status_text = null;
117
118         if (changecount)
119                 status_text = E('a', {
120                         href: '#',
121                         click: L.bind(ui.changes.displayChanges, ui.changes)
122                 }, _('Interface has %d pending changes').format(changecount));
123         else if (!is_assoc)
124                 status_text = E('em', disabled ? _('Wireless is disabled') : _('Wireless is not associated'));
125
126         return L.itemlist(E('div'), [
127                 is_mesh ? _('Mesh ID') : _('SSID'), (is_mesh ? radioNet.getMeshID() : radioNet.getSSID()) || '?',
128                 _('Mode'),       mode,
129                 _('BSSID'),      (!changecount && is_assoc) ? bssid : null,
130                 _('Encryption'), (!changecount && is_assoc) ? radioNet.getActiveEncryption() || _('None') : null,
131                 null,            status_text
132         ], [ ' | ', E('br') ]);
133 }
134
135 function render_modal_status(node, radioNet) {
136         var mode = radioNet.getActiveMode(),
137             noise = radioNet.getNoise(),
138             bssid = radioNet.getActiveBSSID(),
139             channel = radioNet.getChannel(),
140             disabled = (radioNet.get('disabled') == '1'),
141             is_assoc = (bssid && bssid != '00:00:00:00:00:00' && channel && mode != 'Unknown' && !disabled);
142
143         if (node == null)
144                 node = E('span', { 'class': 'ifacebadge large', 'data-network': radioNet.getName() }, [ E('small'), E('span') ]);
145
146         L.dom.content(node.firstElementChild, render_signal_badge(disabled ? -1 : radioNet.getSignalPercent(), radioNet.getSignal(), noise, true));
147
148         L.itemlist(node.lastElementChild, [
149                 _('Mode'),       mode,
150                 _('SSID'),       radioNet.getSSID() || '?',
151                 _('BSSID'),      is_assoc ? bssid : null,
152                 _('Encryption'), is_assoc ? radioNet.getActiveEncryption() || _('None') : null,
153                 _('Channel'),    is_assoc ? '%d (%.3f %s)'.format(radioNet.getChannel(), radioNet.getFrequency() || 0, _('GHz')) : null,
154                 _('Tx-Power'),   is_assoc ? '%d %s'.format(radioNet.getTXPower(), _('dBm')) : null,
155                 _('Signal'),     is_assoc ? '%d %s'.format(radioNet.getSignal(), _('dBm')) : null,
156                 _('Noise'),      (is_assoc && noise != null) ? '%d %s'.format(noise, _('dBm')) : null,
157                 _('Bitrate'),    is_assoc ? '%.1f %s'.format(radioNet.getBitRate() || 0, _('Mbit/s')) : null,
158                 _('Country'),    is_assoc ? radioNet.getCountryCode() : null
159         ], [ ' | ', E('br'), E('br'), E('br'), E('br'), E('br'), ' | ', E('br'), ' | ' ]);
160
161         if (!is_assoc)
162                 L.dom.append(node.lastElementChild, E('em', disabled ? _('Wireless is disabled') : _('Wireless is not associated')));
163
164         return node;
165 }
166
167 function format_wifirate(rate) {
168         var s = '%.1f Mbit/s, %dMHz'.format(rate.rate / 1000, rate.mhz);
169
170         if (rate.ht || rate.vht) {
171                 if (rate.vht)      s += ', VHT-MCS %d'.format(rate.mcs);
172                 if (rate.nss)      s += ', VHT-NSS %d'.format(rate.nss);
173                 if (rate.ht)       s += ', MCS %s'.format(rate.mcs);
174                 if (rate.short_gi) s += ', Short GI';
175         }
176
177         return s;
178 }
179
180 function radio_restart(id, ev) {
181         var row = document.querySelector('.cbi-section-table-row[data-sid="%s"]'.format(id)),
182             dsc = row.querySelector('[data-name="_stat"] > div'),
183             btn = row.querySelector('.cbi-section-actions button');
184
185         btn.blur();
186         btn.classList.add('spinning');
187         btn.disabled = true;
188
189         dsc.setAttribute('restart', '');
190         L.dom.content(dsc, E('em', _('Device is restarting…')));
191 }
192
193 function network_updown(id, map, ev) {
194         var radio = uci.get('wireless', id, 'device'),
195             disabled = (uci.get('wireless', id, 'disabled') == '1') ||
196                        (uci.get('wireless', radio, 'disabled') == '1');
197
198         if (disabled) {
199                 uci.unset('wireless', id, 'disabled');
200                 uci.unset('wireless', radio, 'disabled');
201         }
202         else {
203                 uci.set('wireless', id, 'disabled', '1');
204
205                 var all_networks_disabled = true,
206                     wifi_ifaces = uci.sections('wireless', 'wifi-iface');
207
208                 for (var i = 0; i < wifi_ifaces.length; i++) {
209                         if (wifi_ifaces[i].device == radio && wifi_ifaces[i].disabled != '1') {
210                                 all_networks_disabled = false;
211                                 break;
212                         }
213                 }
214
215                 if (all_networks_disabled)
216                         uci.set('wireless', radio, 'disabled', '1');
217         }
218
219         return map.save().then(function() {
220                 ui.changes.apply()
221         });
222 }
223
224 function next_free_sid(offset) {
225         var sid = 'wifinet' + offset;
226
227         while (uci.get('wireless', sid))
228                 sid = 'wifinet' + (++offset);
229
230         return sid;
231 }
232
233 var CBIWifiFrequencyValue = form.Value.extend({
234         callFrequencyList: rpc.declare({
235                 object: 'iwinfo',
236                 method: 'freqlist',
237                 params: [ 'device' ],
238                 expect: { results: [] }
239         }),
240
241         load: function(section_id) {
242                 return Promise.all([
243                         network.getWifiDevice(section_id),
244                         this.callFrequencyList(section_id)
245                 ]).then(L.bind(function(data) {
246                         this.channels = {
247                                 '11g': L.hasSystemFeature('hostapd', 'acs') ? [ 'auto', 'auto', true ] : [],
248                                 '11a': L.hasSystemFeature('hostapd', 'acs') ? [ 'auto', 'auto', true ] : []
249                         };
250
251                         for (var i = 0; i < data[1].length; i++)
252                                 this.channels[(data[1][i].mhz > 2484) ? '11a' : '11g'].push(
253                                         data[1][i].channel,
254                                         '%d (%d Mhz)'.format(data[1][i].channel, data[1][i].mhz),
255                                         !data[1][i].restricted
256                                 );
257
258                         var hwmodelist = L.toArray(data[0] ? data[0].getHWModes() : null)
259                                 .reduce(function(o, v) { o[v] = true; return o }, {});
260
261                         this.modes = [
262                                 '', 'Legacy', true,
263                                 'n', 'N', hwmodelist.n,
264                                 'ac', 'AC', hwmodelist.ac
265                         ];
266
267                         var htmodelist = L.toArray(data[0] ? data[0].getHTModes() : null)
268                                 .reduce(function(o, v) { o[v] = true; return o }, {});
269
270                         this.htmodes = {
271                                 '': [ '', '-', true ],
272                                 'n': [
273                                         'HT20', '20 MHz', htmodelist.HT20,
274                                         'HT40', '40 MHz', htmodelist.HT40
275                                 ],
276                                 'ac': [
277                                         'VHT20', '20 MHz', htmodelist.VHT20,
278                                         'VHT40', '40 MHz', htmodelist.VHT40,
279                                         'VHT80', '80 MHz', htmodelist.VHT80,
280                                         'VHT160', '160 MHz', htmodelist.VHT160
281                                 ]
282                         };
283
284                         this.bands = {
285                                 '': [
286                                         '11g', '2.4 GHz', this.channels['11g'].length > 3,
287                                         '11a', '5 GHz', this.channels['11a'].length > 3
288                                 ],
289                                 'n': [
290                                         '11g', '2.4 GHz', this.channels['11g'].length > 3,
291                                         '11a', '5 GHz', this.channels['11a'].length > 3
292                                 ],
293                                 'ac': [
294                                         '11a', '5 GHz', true
295                                 ]
296                         };
297                 }, this));
298         },
299
300         setValues: function(sel, vals) {
301                 if (sel.vals)
302                         sel.vals.selected = sel.selectedIndex;
303
304                 while (sel.options[0])
305                         sel.remove(0);
306
307                 for (var i = 0; vals && i < vals.length; i += 3)
308                         if (vals[i+2])
309                                 sel.add(E('option', { value: vals[i+0] }, [ vals[i+1] ]));
310
311                 if (vals && !isNaN(vals.selected))
312                         sel.selectedIndex = vals.selected;
313
314                 sel.parentNode.style.display = (sel.options.length <= 1) ? 'none' : '';
315                 sel.vals = vals;
316         },
317
318         toggleWifiMode: function(elem) {
319                 this.toggleWifiHTMode(elem);
320                 this.toggleWifiBand(elem);
321         },
322
323         toggleWifiHTMode: function(elem) {
324                 var mode = elem.querySelector('.mode');
325                 var bwdt = elem.querySelector('.htmode');
326
327                 this.setValues(bwdt, this.htmodes[mode.value]);
328         },
329
330         toggleWifiBand: function(elem) {
331                 var mode = elem.querySelector('.mode');
332                 var band = elem.querySelector('.band');
333
334                 this.setValues(band, this.bands[mode.value]);
335                 this.toggleWifiChannel(elem);
336         },
337
338         toggleWifiChannel: function(elem) {
339                 var band = elem.querySelector('.band');
340                 var chan = elem.querySelector('.channel');
341
342                 this.setValues(chan, this.channels[band.value]);
343         },
344
345         setInitialValues: function(section_id, elem) {
346                 var mode = elem.querySelector('.mode'),
347                     band = elem.querySelector('.band'),
348                     chan = elem.querySelector('.channel'),
349                     bwdt = elem.querySelector('.htmode'),
350                     htval = uci.get('wireless', section_id, 'htmode'),
351                     hwval = uci.get('wireless', section_id, 'hwmode'),
352                     chval = uci.get('wireless', section_id, 'channel');
353
354                 this.setValues(mode, this.modes);
355
356                 if (/VHT20|VHT40|VHT80|VHT160/.test(htval))
357                         mode.value = 'ac';
358                 else if (/HT20|HT40/.test(htval))
359                         mode.value = 'n';
360                 else
361                         mode.value = '';
362
363                 this.toggleWifiMode(elem);
364
365                 if (/a/.test(hwval))
366                         band.value = '11a';
367                 else
368                         band.value = '11g';
369
370                 this.toggleWifiBand(elem);
371
372                 bwdt.value = htval;
373                 chan.value = chval;
374
375                 return elem;
376         },
377
378         renderWidget: function(section_id, option_index, cfgvalue) {
379                 var elem = E('div');
380
381                 L.dom.content(elem, [
382                         E('label', { 'style': 'float:left; margin-right:3px' }, [
383                                 _('Mode'), E('br'),
384                                 E('select', {
385                                         'class': 'mode',
386                                         'style': 'width:auto',
387                                         'change': L.bind(this.toggleWifiMode, this, elem)
388                                 })
389                         ]),
390                         E('label', { 'style': 'float:left; margin-right:3px' }, [
391                                 _('Band'), E('br'),
392                                 E('select', {
393                                         'class': 'band',
394                                         'style': 'width:auto',
395                                         'change': L.bind(this.toggleWifiBand, this, elem)
396                                 })
397                         ]),
398                         E('label', { 'style': 'float:left; margin-right:3px' }, [
399                                 _('Channel'), E('br'),
400                                 E('select', {
401                                         'class': 'channel',
402                                         'style': 'width:auto'
403                                 })
404                         ]),
405                         E('label', { 'style': 'float:left; margin-right:3px' }, [
406                                 _('Width'), E('br'),
407                                 E('select', {
408                                         'class': 'htmode',
409                                         'style': 'width:auto'
410                                 })
411                         ]),
412                         E('br', { 'style': 'clear:left' })
413                 ]);
414
415                 return this.setInitialValues(section_id, elem);
416         },
417
418         cfgvalue: function(section_id) {
419                 return [
420                     uci.get('wireless', section_id, 'htmode'),
421                     uci.get('wireless', section_id, 'hwmode'),
422                     uci.get('wireless', section_id, 'channel')
423                 ];
424         },
425
426         formvalue: function(section_id) {
427                 var node = this.map.findElement('data-field', this.cbid(section_id));
428
429                 return [
430                     node.querySelector('.htmode').value,
431                     node.querySelector('.band').value,
432                         node.querySelector('.channel').value
433                 ];
434         },
435
436         write: function(section_id, value) {
437                 uci.set('wireless', section_id, 'htmode', value[0] || null);
438                 uci.set('wireless', section_id, 'hwmode', value[1]);
439                 uci.set('wireless', section_id, 'channel', value[2]);
440         }
441 });
442
443 var CBIWifiTxPowerValue = form.ListValue.extend({
444         callTxPowerList: rpc.declare({
445                 object: 'iwinfo',
446                 method: 'txpowerlist',
447                 params: [ 'device' ],
448                 expect: { results: [] }
449         }),
450
451         load: function(section_id) {
452                 return this.callTxPowerList(section_id).then(L.bind(function(pwrlist) {
453                         this.powerval = this.wifiNetwork ? this.wifiNetwork.getTXPower() : null;
454                         this.poweroff = this.wifiNetwork ? this.wifiNetwork.getTXPowerOffset() : null;
455
456                         this.value('', _('driver default'));
457
458                         for (var i = 0; i < pwrlist.length; i++)
459                                 this.value(pwrlist[i].dbm, '%d dBm (%d mW)'.format(pwrlist[i].dbm, pwrlist[i].mw));
460
461                         return form.ListValue.prototype.load.apply(this, [section_id]);
462                 }, this));
463         },
464
465         renderWidget: function(section_id, option_index, cfgvalue) {
466                 var widget = form.ListValue.prototype.renderWidget.apply(this, [section_id, option_index, cfgvalue]);
467                     widget.firstElementChild.style.width = 'auto';
468
469                 L.dom.append(widget, E('span', [
470                         ' - ', _('Current power'), ': ',
471                         E('span', [ this.powerval != null ? '%d dBm'.format(this.powerval) : E('em', _('unknown')) ]),
472                         this.poweroff ? ' + %d dB offset = %s dBm'.format(this.poweroff, this.powerval != null ? this.powerval + this.poweroff : '?') : ''
473                 ]));
474
475                 return widget;
476         }
477 });
478
479 var CBIWifiCountryValue = form.Value.extend({
480         callCountryList: rpc.declare({
481                 object: 'iwinfo',
482                 method: 'countrylist',
483                 params: [ 'device' ],
484                 expect: { results: [] }
485         }),
486
487         load: function(section_id) {
488                 return this.callCountryList(section_id).then(L.bind(function(countrylist) {
489                         if (Array.isArray(countrylist) && countrylist.length > 0) {
490                                 this.value('', _('driver default'));
491
492                                 for (var i = 0; i < countrylist.length; i++)
493                                         this.value(countrylist[i].iso3166, '%s - %s'.format(countrylist[i].iso3166, countrylist[i].country));
494                         }
495
496                         return form.Value.prototype.load.apply(this, [section_id]);
497                 }, this));
498         },
499
500         validate: function(section_id, formvalue) {
501                 if (formvalue != null && formvalue != '' && !/^[A-Z0-9][A-Z0-9]$/.test(formvalue))
502                         return _('Use ISO/IEC 3166 alpha2 country codes.');
503
504                 return true;
505         },
506
507         renderWidget: function(section_id, option_index, cfgvalue) {
508                 var typeClass = (this.keylist && this.keylist.length) ? form.ListValue : form.Value;
509                 return typeClass.prototype.renderWidget.apply(this, [section_id, option_index, cfgvalue]);
510         }
511 });
512
513 return L.view.extend({
514         poll_status: function(map, data) {
515                 var rows = map.querySelectorAll('.cbi-section-table-row[data-sid]');
516
517                 for (var i = 0; i < rows.length; i++) {
518                         var section_id = rows[i].getAttribute('data-sid'),
519                             radioDev = data[1].filter(function(d) { return d.getName() == section_id })[0],
520                             radioNet = data[2].filter(function(n) { return n.getName() == section_id })[0],
521                             badge = rows[i].querySelector('[data-name="_badge"] > div'),
522                             stat = rows[i].querySelector('[data-name="_stat"]'),
523                             btns = rows[i].querySelectorAll('.cbi-section-actions button'),
524                             busy = btns[0].classList.contains('spinning') || btns[1].classList.contains('spinning') || btns[2].classList.contains('spinning');
525
526                         if (radioDev) {
527                                 L.dom.content(badge, render_radio_badge(radioDev));
528                                 L.dom.content(stat, render_radio_status(radioDev, data[2].filter(function(n) { return n.getWifiDeviceName() == radioDev.getName() })));
529                         }
530                         else {
531                                 L.dom.content(badge, render_network_badge(radioNet));
532                                 L.dom.content(stat, render_network_status(radioNet));
533                         }
534
535                         if (stat.hasAttribute('restart'))
536                                 L.dom.content(stat, E('em', _('Device is restarting…')));
537
538                         btns[0].disabled = busy;
539                         btns[1].disabled = busy;
540                         btns[2].disabled = busy;
541                 }
542
543                 var table = document.querySelector('#wifi_assoclist_table'),
544                     hosts = data[0],
545                     trows = [];
546
547                 for (var i = 0; i < data[3].length; i++) {
548                         var bss = data[3][i],
549                             name = hosts.getHostnameByMACAddr(bss.mac),
550                             ipv4 = hosts.getIPAddrByMACAddr(bss.mac),
551                             ipv6 = hosts.getIP6AddrByMACAddr(bss.mac);
552
553                         var hint;
554
555                         if (name && ipv4 && ipv6)
556                                 hint = '%s <span class="hide-xs">(%s, %s)</span>'.format(name, ipv4, ipv6);
557                         else if (name && (ipv4 || ipv6))
558                                 hint = '%s <span class="hide-xs">(%s)</span>'.format(name, ipv4 || ipv6);
559                         else
560                                 hint = name || ipv4 || ipv6 || '?';
561
562                         var row = [
563                                 E('span', {
564                                         'class': 'ifacebadge',
565                                         'data-ifname': bss.network.getIfname(),
566                                         'data-ssid': bss.network.getSSID()
567                                 }, [
568                                         E('img', {
569                                                 'src': L.resource('icons/wifi%s.png').format(bss.network.isUp() ? '' : '_disabled'),
570                                                 'title': bss.radio.getI18n()
571                                         }),
572                                         E('span', [
573                                                 ' %s '.format(bss.network.getShortName()),
574                                                 E('small', '(%s)'.format(bss.network.getIfname()))
575                                         ])
576                                 ]),
577                                 bss.mac,
578                                 hint,
579                                 render_signal_badge(Math.min((bss.signal + 110) / 70 * 100, 100), bss.signal, bss.noise),
580                                 E('span', {}, [
581                                         E('span', format_wifirate(bss.rx)),
582                                         E('br'),
583                                         E('span', format_wifirate(bss.tx))
584                                 ])
585                         ];
586
587                         if (bss.network.isClientDisconnectSupported()) {
588                                 if (table.firstElementChild.childNodes.length < 6)
589                                         table.firstElementChild.appendChild(E('div', { 'class': 'th nowrap right'}, [ _('Disconnect') ]));
590
591                                 row.push(E('button', {
592                                         'class': 'cbi-button cbi-button-remove',
593                                         'click': L.bind(function(net, mac, ev) {
594                                                 L.dom.parent(ev.currentTarget, '.tr').style.opacity = 0.5;
595                                                 ev.currentTarget.classList.add('spinning');
596                                                 ev.currentTarget.disabled = true;
597                                                 ev.currentTarget.blur();
598
599                                                 net.disconnectClient(mac, true, 5, 60000);
600                                         }, this, bss.network, bss.mac)
601                                 }, [ _('Disconnect') ]));
602                         }
603                         else {
604                                 row.push('-');
605                         }
606
607                         trows.push(row);
608                 }
609
610                 cbi_update_table(table, trows, E('em', _('No information available')));
611
612                 var stat = document.querySelector('.cbi-modal [data-name="_wifistat_modal"] .ifacebadge.large');
613
614                 if (stat)
615                         render_modal_status(stat, data[2].filter(function(n) { return n.getName() == stat.getAttribute('data-network') })[0]);
616
617                 return network.flushCache();
618         },
619
620         load: function() {
621                 return Promise.all([
622                         uci.changes(),
623                         uci.load('wireless')
624                 ]);
625         },
626
627         checkAnonymousSections: function() {
628                 var wifiIfaces = uci.sections('wireless', 'wifi-iface');
629
630                 for (var i = 0; i < wifiIfaces.length; i++)
631                         if (wifiIfaces[i]['.anonymous'])
632                                 return true;
633
634                 return false;
635         },
636
637         callUciRename: rpc.declare({
638                 object: 'uci',
639                 method: 'rename',
640                 params: [ 'config', 'section', 'name' ]
641         }),
642
643         render: function() {
644                 if (this.checkAnonymousSections())
645                         return this.renderMigration();
646                 else
647                         return this.renderOverview();
648         },
649
650         handleMigration: function(ev) {
651                 var wifiIfaces = uci.sections('wireless', 'wifi-iface'),
652                     id_offset = 0,
653                     tasks = [];
654
655                 for (var i = 0; i < wifiIfaces.length; i++) {
656                         if (!wifiIfaces[i]['.anonymous'])
657                                 continue;
658
659                         var new_name = next_free_sid(id_offset);
660
661                         tasks.push(this.callUciRename('wireless', wifiIfaces[i]['.name'], new_name));
662                         id_offset = +new_name.substring(7) + 1;
663                 }
664
665                 return Promise.all(tasks)
666                         .then(L.bind(ui.changes.init, ui.changes))
667                         .then(L.bind(ui.changes.apply, ui.changes));
668         },
669
670         renderMigration: function() {
671                 ui.showModal(_('Wireless configuration migration'), [
672                         E('p', _('The existing wireless configuration needs to be changed for LuCI to function properly.')),
673                         E('p', _('Upon pressing "Continue", anonymous "wifi-iface" sections will be assigned with a name in the form <em>wifinet#</em> and the network will be restarted to apply the updated configuration.')),
674                         E('div', { 'class': 'right' },
675                                 E('button', {
676                                         'class': 'btn cbi-button-action important',
677                                         'click': ui.createHandlerFn(this, 'handleMigration')
678                                 }, _('Continue')))
679                 ]);
680         },
681
682         renderOverview: function() {
683                 var m, s, o;
684
685                 m = new form.Map('wireless');
686                 m.chain('network');
687                 m.chain('firewall');
688
689                 s = m.section(form.GridSection, 'wifi-device', _('Wireless Overview'));
690                 s.anonymous = true;
691                 s.addremove = false;
692
693                 s.load = function() {
694                         return network.getWifiDevices().then(L.bind(function(radios) {
695                                 this.radios = radios.sort(function(a, b) {
696                                         return a.getName() > b.getName();
697                                 });
698
699                                 var tasks = [];
700
701                                 for (var i = 0; i < radios.length; i++)
702                                         tasks.push(radios[i].getWifiNetworks());
703
704                                 return Promise.all(tasks);
705                         }, this)).then(L.bind(function(data) {
706                                 this.wifis = [];
707
708                                 for (var i = 0; i < data.length; i++)
709                                         this.wifis.push.apply(this.wifis, data[i]);
710                         }, this));
711                 };
712
713                 s.cfgsections = function() {
714                         var rv = [];
715
716                         for (var i = 0; i < this.radios.length; i++) {
717                                 rv.push(this.radios[i].getName());
718
719                                 for (var j = 0; j < this.wifis.length; j++)
720                                         if (this.wifis[j].getWifiDeviceName() == this.radios[i].getName())
721                                                 rv.push(this.wifis[j].getName());
722                         }
723
724                         return rv;
725                 };
726
727                 s.modaltitle = function(section_id) {
728                         var radioNet = this.wifis.filter(function(w) { return w.getName() == section_id})[0];
729                         return radioNet ? radioNet.getI18n() : _('Edit wireless network');
730                 };
731
732                 s.lookupRadioOrNetwork = function(section_id) {
733                         var radioDev = this.radios.filter(function(r) { return r.getName() == section_id })[0];
734                         if (radioDev)
735                                 return radioDev;
736
737                         var radioNet = this.wifis.filter(function(w) { return w.getName() == section_id })[0];
738                         if (radioNet)
739                                 return radioNet;
740
741                         return null;
742                 };
743
744                 s.renderRowActions = function(section_id) {
745                         var inst = this.lookupRadioOrNetwork(section_id), btns;
746
747                         if (inst.getWifiNetworks) {
748                                 btns = [
749                                         E('button', {
750                                                 'class': 'cbi-button cbi-button-neutral',
751                                                 'title': _('Restart radio interface'),
752                                                 'click': ui.createHandlerFn(this, radio_restart, section_id)
753                                         }, _('Restart')),
754                                         E('button', {
755                                                 'class': 'cbi-button cbi-button-action important',
756                                                 'title': _('Find and join network'),
757                                                 'click': ui.createHandlerFn(this, 'handleScan', inst)
758                                         }, _('Scan')),
759                                         E('button', {
760                                                 'class': 'cbi-button cbi-button-add',
761                                                 'title': _('Provide new network'),
762                                                 'click': ui.createHandlerFn(this, 'handleAdd', inst)
763                                         }, _('Add'))
764                                 ];
765                         }
766                         else {
767                                 var isDisabled = (inst.get('disabled') == '1' ||
768                                         uci.get('wireless', inst.getWifiDeviceName(), 'disabled') == '1');
769
770                                 btns = [
771                                         E('button', {
772                                                 'class': 'cbi-button cbi-button-neutral enable-disable',
773                                                 'title': isDisabled ? _('Enable this network') : _('Disable this network'),
774                                                 'click': ui.createHandlerFn(this, network_updown, section_id, this.map)
775                                         }, isDisabled ? _('Enable') : _('Disable')),
776                                         E('button', {
777                                                 'class': 'cbi-button cbi-button-action important',
778                                                 'title': _('Edit this network'),
779                                                 'click': ui.createHandlerFn(this, 'renderMoreOptionsModal', section_id)
780                                         }, _('Edit')),
781                                         E('button', {
782                                                 'class': 'cbi-button cbi-button-negative remove',
783                                                 'title': _('Delete this network'),
784                                                 'click': ui.createHandlerFn(this, 'handleRemove', section_id)
785                                         }, _('Remove'))
786                                 ];
787                         }
788
789                         return E('div', { 'class': 'td middle cbi-section-actions' }, E('div', btns));
790                 };
791
792                 s.addModalOptions = function(s) {
793                         return network.getWifiNetwork(s.section).then(function(radioNet) {
794                                 var hwtype = uci.get('wireless', radioNet.getWifiDeviceName(), 'type');
795                                 var o, ss;
796
797                                 o = s.option(form.SectionValue, '_device', form.NamedSection, radioNet.getWifiDeviceName(), 'wifi-device', _('Device Configuration'));
798                                 o.modalonly = true;
799
800                                 ss = o.subsection;
801                                 ss.tab('general', _('General Setup'));
802                                 ss.tab('advanced', _('Advanced Settings'));
803
804                                 var isDisabled = (radioNet.get('disabled') == '1' ||
805                                         uci.get('wireless', radioNet.getWifiDeviceName(), 'disabled') == 1);
806
807                                 o = ss.taboption('general', form.DummyValue, '_wifistat_modal', _('Status'));
808                                 o.cfgvalue = L.bind(function(radioNet) {
809                                         return render_modal_status(null, radioNet);
810                                 }, this, radioNet);
811                                 o.write = function() {};
812
813                                 o = ss.taboption('general', form.Button, '_toggle', isDisabled ? _('Wireless network is disabled') : _('Wireless network is enabled'));
814                                 o.inputstyle = isDisabled ? 'apply' : 'reset';
815                                 o.inputtitle = isDisabled ? _('Enable') : _('Disable');
816                                 o.onclick = ui.createHandlerFn(s, network_updown, s.section, s.map);
817
818                                 o = ss.taboption('general', CBIWifiFrequencyValue, '_freq', '<br />' + _('Operating frequency'));
819                                 o.ucisection = s.section;
820
821                                 if (hwtype == 'mac80211') {
822                                         o = ss.taboption('general', CBIWifiTxPowerValue, 'txpower', _('Maximum transmit power'), _('Specifies the maximum transmit power the wireless radio may use. Depending on regulatory requirements and wireless usage, the actual transmit power may be reduced by the driver.'));
823                                         o.wifiNetwork = radioNet;
824
825                                         o = ss.taboption('advanced', CBIWifiCountryValue, 'country', _('Country Code'));
826                                         o.wifiNetwork = radioNet;
827
828                                         o = ss.taboption('advanced', form.Flag, 'legacy_rates', _('Allow legacy 802.11b rates'));
829                                         o.default = o.enabled;
830
831                                         o = ss.taboption('advanced', form.Value, 'distance', _('Distance Optimization'), _('Distance to farthest network member in meters.'));
832                                         o.datatype = 'range(0,114750)';
833                                         o.placeholder = 'auto';
834
835                                         o = ss.taboption('advanced', form.Value, 'frag', _('Fragmentation Threshold'));
836                                         o.datatype = 'min(256)';
837                                         o.placeholder = _('off');
838
839                                         o = ss.taboption('advanced', form.Value, 'rts', _('RTS/CTS Threshold'));
840                                         o.datatype = 'uinteger';
841                                         o.placeholder = _('off');
842
843                                         o = ss.taboption('advanced', form.Flag, 'noscan', _('Force 40MHz mode'), _('Always use 40MHz channels even if the secondary channel overlaps. Using this option does not comply with IEEE 802.11n-2009!'));
844                                         o.rmempty = true;
845
846                                         o = ss.taboption('advanced', form.Value, 'beacon_int', _('Beacon Interval'));
847                                         o.datatype = 'range(15,65535)';
848                                         o.placeholder = 100;
849                                         o.rmempty = true;
850                                 }
851
852
853                                 o = s.option(form.SectionValue, '_device', form.NamedSection, radioNet.getName(), 'wifi-iface', _('Interface Configuration'));
854                                 o.modalonly = true;
855
856                                 ss = o.subsection;
857                                 ss.tab('general', _('General Setup'));
858                                 ss.tab('encryption', _('Wireless Security'));
859                                 ss.tab('macfilter', _('MAC-Filter'));
860                                 ss.tab('advanced', _('Advanced Settings'));
861
862                                 o = ss.taboption('general', form.ListValue, 'mode', _('Mode'));
863                                 o.value('ap', _('Access Point'));
864                                 o.value('sta', _('Client'));
865                                 o.value('adhoc', _('Ad-Hoc'));
866
867                                 o = ss.taboption('general', form.Value, 'mesh_id', _('Mesh Id'));
868                                 o.depends('mode', 'mesh');
869
870                                 o = ss.taboption('advanced', form.Flag, 'mesh_fwding', _('Forward mesh peer traffic'));
871                                 o.rmempty = false;
872                                 o.default = '1';
873                                 o.depends('mode', 'mesh');
874
875                                 o = ss.taboption('advanced', form.Value, 'mesh_rssi_threshold', _('RSSI threshold for joining'), _('0 = not using RSSI threshold, 1 = do not change driver default'));
876                                 o.rmempty = false;
877                                 o.default = '0';
878                                 o.datatype = 'range(-255,1)';
879                                 o.depends('mode', 'mesh');
880
881                                 o = ss.taboption('general', form.Value, 'ssid', _('<abbr title="Extended Service Set Identifier">ESSID</abbr>'));
882                                 o.datatype = 'maxlength(32)';
883                                 o.depends('mode', 'ap');
884                                 o.depends('mode', 'sta');
885                                 o.depends('mode', 'adhoc');
886                                 o.depends('mode', 'ahdemo');
887                                 o.depends('mode', 'monitor');
888                                 o.depends('mode', 'ap-wds');
889                                 o.depends('mode', 'sta-wds');
890                                 o.depends('mode', 'wds');
891
892                                 o = ss.taboption('general', form.Value, 'bssid', _('<abbr title="Basic Service Set Identifier">BSSID</abbr>'));
893                                 o.datatype = 'macaddr';
894
895                                 o = ss.taboption('general', widgets.NetworkSelect, 'network', _('Network'), _('Choose the network(s) you want to attach to this wireless interface or fill out the <em>create</em> field to define a new network.'));
896                                 o.rmempty = true;
897                                 o.multiple = true;
898                                 o.novirtual = true;
899                                 o.write = function(section_id, value) {
900                                         return network.getDevice(section_id).then(L.bind(function(dev) {
901                                                 var old_networks = dev.getNetworks().reduce(function(o, v) { o[v.getName()] = v; return o }, {}),
902                                                     new_networks = {},
903                                                     values = L.toArray(value),
904                                                     tasks = [];
905
906                                                 for (var i = 0; i < values.length; i++) {
907                                                         new_networks[values[i]] = true;
908
909                                                         if (old_networks[values[i]])
910                                                                 continue;
911
912                                                         tasks.push(network.getNetwork(values[i]).then(L.bind(function(name, net) {
913                                                                 return net || network.addNetwork(name, { proto: 'none' });
914                                                         }, this, values[i])).then(L.bind(function(dev, net) {
915                                                                 if (net) {
916                                                                         if (!net.isEmpty())
917                                                                                 net.set('type', 'bridge');
918                                                                         net.addDevice(dev);
919                                                                 }
920                                                         }, this, dev)));
921                                                 }
922
923                                                 for (var name in old_networks)
924                                                         if (!new_networks[name])
925                                                                 tasks.push(network.getNetwork(name).then(L.bind(function(dev, net) {
926                                                                         if (net)
927                                                                                 net.deleteDevice(dev);
928                                                                 }, this, dev)));
929
930                                                 return Promise.all(tasks);
931                                         }, this));
932                                 };
933
934                                 if (hwtype == 'mac80211') {
935                                         var mode = ss.children[0],
936                                             bssid = ss.children[5],
937                                             encr;
938
939                                         mode.value('mesh', '802.11s');
940                                         mode.value('ahdemo', _('Pseudo Ad-Hoc (ahdemo)'));
941                                         mode.value('monitor', _('Monitor'));
942
943                                         bssid.depends('mode', 'adhoc');
944                                         bssid.depends('mode', 'sta');
945                                         bssid.depends('mode', 'sta-wds');
946
947                                         o = ss.taboption('macfilter', form.ListValue, 'macfilter', _('MAC-Address Filter'));
948                                         o.depends('mode', 'ap');
949                                         o.depends('mode', 'ap-wds');
950                                         o.value('', _('disable'));
951                                         o.value('allow', _('Allow listed only'));
952                                         o.value('deny', _('Allow all except listed'));
953
954                                         o = ss.taboption('macfilter', form.DynamicList, 'maclist', _('MAC-List'));
955                                         o.datatype = 'macaddr';
956                                         o.depends('macfilter', 'allow');
957                                         o.depends('macfilter', 'deny');
958                                         o.load = function(section_id) {
959                                                 return network.getHostHints().then(L.bind(function(hints) {
960                                                         hints.getMACHints().map(L.bind(function(hint) {
961                                                                 this.value(hint[0], hint[1] ? '%s (%s)'.format(hint[0], hint[1]) : hint[0]);
962                                                         }, this));
963
964                                                         return form.DynamicList.prototype.load.apply(this, [section_id]);
965                                                 }, this));
966                                         };
967
968                                         mode.value('ap-wds', '%s (%s)'.format(_('Access Point'), _('WDS')));
969                                         mode.value('sta-wds', '%s (%s)'.format(_('Client'), _('WDS')));
970
971                                         mode.write = function(section_id, value) {
972                                                 switch (value) {
973                                                 case 'ap-wds':
974                                                         uci.set('wireless', section_id, 'mode', 'ap');
975                                                         uci.set('wireless', section_id, 'wds', '1');
976                                                         break;
977
978                                                 case 'sta-wds':
979                                                         uci.set('wireless', section_id, 'mode', 'sta');
980                                                         uci.set('wireless', section_id, 'wds', '1');
981                                                         break;
982
983                                                 default:
984                                                         uci.set('wireless', section_id, 'mode', value);
985                                                         uci.unset('wireless', section_id, 'wds');
986                                                         break;
987                                                 }
988                                         };
989
990                                         mode.cfgvalue = function(section_id) {
991                                                 var mode = uci.get('wireless', section_id, 'mode'),
992                                                     wds = uci.get('wireless', section_id, 'wds');
993
994                                                 if (mode == 'ap' && wds)
995                                                         return 'ap-wds';
996                                                 else if (mode == 'sta' && wds)
997                                                         return 'sta-wds';
998
999                                                 return mode;
1000                                         };
1001
1002                                         o = ss.taboption('general', form.Flag, 'hidden', _('Hide <abbr title="Extended Service Set Identifier">ESSID</abbr>'));
1003                                         o.depends('mode', 'ap');
1004                                         o.depends('mode', 'ap-wds');
1005
1006                                         o = ss.taboption('general', form.Flag, 'wmm', _('WMM Mode'));
1007                                         o.depends('mode', 'ap');
1008                                         o.depends('mode', 'ap-wds');
1009                                         o.default = o.enabled;
1010
1011                                         o = ss.taboption('advanced', form.Flag, 'isolate', _('Isolate Clients'), _('Prevents client-to-client communication'));
1012                                         o.depends('mode', 'ap');
1013                                         o.depends('mode', 'ap-wds');
1014
1015                                         o = ss.taboption('advanced', form.Value, 'ifname', _('Interface name'), _('Override default interface name'));
1016                                         o.optional = true;
1017                                         o.placeholder = radioNet.getIfname();
1018                                         if (/^radio\d+\.network/.test(o.placeholder))
1019                                                 o.placeholder = '';
1020
1021                                         o = ss.taboption('advanced', form.Flag, 'short_preamble', _('Short Preamble'));
1022                                         o.default = o.enabled;
1023
1024                                         o = ss.taboption('advanced', form.Value, 'dtim_period', _('DTIM Interval'), _('Delivery Traffic Indication Message Interval'));
1025                                         o.optional = true;
1026                                         o.placeholder = 2;
1027                                         o.datatype = 'range(1,255)';
1028
1029                                         o = ss.taboption('advanced', form.Value, 'wpa_group_rekey', _('Time interval for rekeying GTK'), _('sec'));
1030                                         o.optional    = true;
1031                                         o.placeholder = 600;
1032                                         o.datatype    = 'uinteger';
1033
1034                                         o = ss.taboption('advanced', form.Flag , 'skip_inactivity_poll', _('Disable Inactivity Polling'));
1035                                         o.optional    = true;
1036                                         o.datatype    = 'uinteger';
1037
1038                                         o = ss.taboption('advanced', form.Value, 'max_inactivity', _('Station inactivity limit'), _('sec'));
1039                                         o.optional    = true;
1040                                         o.placeholder = 300;
1041                                         o.datatype    = 'uinteger';
1042
1043                                         o = ss.taboption('advanced', form.Value, 'max_listen_interval', _('Maximum allowed Listen Interval'));
1044                                         o.optional    = true;
1045                                         o.placeholder = 65535;
1046                                         o.datatype    = 'uinteger';
1047
1048                                         o = ss.taboption('advanced', form.Flag, 'disassoc_low_ack', _('Disassociate On Low Acknowledgement'), _('Allow AP mode to disconnect STAs based on low ACK condition'));
1049                                         o.default = o.enabled;
1050                                 }
1051
1052
1053                                 encr = o = ss.taboption('encryption', form.ListValue, 'encryption', _('Encryption'));
1054                                 o.depends('mode', 'ap');
1055                                 o.depends('mode', 'sta');
1056                                 o.depends('mode', 'adhoc');
1057                                 o.depends('mode', 'ahdemo');
1058                                 o.depends('mode', 'ap-wds');
1059                                 o.depends('mode', 'sta-wds');
1060                                 o.depends('mode', 'mesh');
1061
1062                                 o.cfgvalue = function(section_id) {
1063                                         var v = String(uci.get('wireless', section_id, 'encryption'));
1064                                         if (v == 'wep')
1065                                                 return 'wep-open';
1066                                         else if (v.match(/\+/))
1067                                                 return v.replace(/\+.+$/, '');
1068                                         return v;
1069                                 };
1070
1071                                 o.write = function(section_id, value) {
1072                                         var e = this.section.children.filter(function(o) { return o.option == 'encryption' })[0].formvalue(section_id),
1073                                             co = this.section.children.filter(function(o) { return o.option == 'cipher' })[0], c = co.formvalue(section_id);
1074
1075                                         if (value == 'wpa' || value == 'wpa2')
1076                                                 uci.unset('wireless', section_id, 'key');
1077
1078                                         if (co.isActive(section_id) && e && (c == 'tkip' || c == 'ccmp' || c == 'tkip+ccmp'))
1079                                                 e += '+' + c;
1080
1081                                         uci.set('wireless', section_id, 'encryption', e);
1082                                 };
1083
1084                                 o = ss.taboption('encryption', form.ListValue, 'cipher', _('Cipher'));
1085                                 o.depends('encryption', 'wpa');
1086                                 o.depends('encryption', 'wpa2');
1087                                 o.depends('encryption', 'psk');
1088                                 o.depends('encryption', 'psk2');
1089                                 o.depends('encryption', 'wpa-mixed');
1090                                 o.depends('encryption', 'psk-mixed');
1091                                 o.value('auto', _('auto'));
1092                                 o.value('ccmp', _('Force CCMP (AES)'));
1093                                 o.value('tkip', _('Force TKIP'));
1094                                 o.value('tkip+ccmp', _('Force TKIP and CCMP (AES)'));
1095                                 o.write = ss.children.filter(function(o) { return o.option == 'encryption' })[0].write;
1096
1097                                 o.cfgvalue = function(section_id) {
1098                                         var v = String(uci.get('wireless', section_id, 'encryption'));
1099                                         if (v.match(/\+/)) {
1100                                                 v = v.replace(/^[^+]+\+/, '');
1101                                                 if (v == 'aes')
1102                                                         v = 'ccmp';
1103                                                 else if (v == 'tkip+aes' || v == 'aes+tkip' || v == 'ccmp+tkip')
1104                                                         v = 'tkip+ccmp';
1105                                         }
1106                                         return v;
1107                                 };
1108
1109
1110                                 var crypto_modes = [];
1111
1112                                 if (hwtype == 'mac80211') {
1113                                         var has_supplicant = L.hasSystemFeature('wpasupplicant'),
1114                                             has_hostapd = L.hasSystemFeature('hostapd');
1115
1116                                         // Probe EAP support
1117                                         var has_ap_eap = L.hasSystemFeature('hostapd', 'eap'),
1118                                             has_sta_eap = L.hasSystemFeature('wpasupplicant', 'eap');
1119
1120                                         // Probe SAE support
1121                                         var has_ap_sae = L.hasSystemFeature('hostapd', 'sae'),
1122                                             has_sta_sae = L.hasSystemFeature('wpasupplicant', 'sae');
1123
1124                                         // Probe OWE support
1125                                         var has_ap_owe = L.hasSystemFeature('hostapd', 'owe'),
1126                                             has_sta_owe = L.hasSystemFeature('wpasupplicant', 'owe');
1127
1128
1129                                         if (has_hostapd || has_supplicant) {
1130                                                 crypto_modes.push(['psk2',      'WPA2-PSK',                    33]);
1131                                                 crypto_modes.push(['psk-mixed', 'WPA-PSK/WPA2-PSK Mixed Mode', 22]);
1132                                                 crypto_modes.push(['psk',       'WPA-PSK',                     21]);
1133                                         }
1134                                         else {
1135                                                 encr.description = _('WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP and ad-hoc mode) to be installed.');
1136                                         }
1137
1138                                         if (has_ap_sae || has_sta_sae) {
1139                                                 crypto_modes.push(['sae',       'WPA3-SAE',                     31]);
1140                                                 crypto_modes.push(['sae-mixed', 'WPA2-PSK/WPA3-SAE Mixed Mode', 30]);
1141                                         }
1142
1143                                         if (has_ap_eap || has_sta_eap) {
1144                                                 crypto_modes.push(['wpa2', 'WPA2-EAP', 32]);
1145                                                 crypto_modes.push(['wpa',  'WPA-EAP',  20]);
1146                                         }
1147
1148                                         if (has_ap_owe || has_sta_owe) {
1149                                                 crypto_modes.push(['owe', 'OWE', 1]);
1150                                         }
1151
1152                                         encr.crypto_support = {
1153                                                 'ap': {
1154                                                         'wep-open': true,
1155                                                         'wep-shared': true,
1156                                                         'psk': has_hostapd || _('Requires hostapd'),
1157                                                         'psk2': has_hostapd || _('Requires hostapd'),
1158                                                         'psk-mixed': has_hostapd || _('Requires hostapd'),
1159                                                         'sae': has_ap_sae || _('Requires hostapd with SAE support'),
1160                                                         'sae-mixed': has_ap_sae || _('Requires hostapd with SAE support'),
1161                                                         'wpa': has_ap_eap || _('Requires hostapd with EAP support'),
1162                                                         'wpa2': has_ap_eap || _('Requires hostapd with EAP support'),
1163                                                         'owe': has_ap_owe || _('Requires hostapd with OWE support')
1164                                                 },
1165                                                 'sta': {
1166                                                         'wep-open': true,
1167                                                         'wep-shared': true,
1168                                                         'psk': has_supplicant || _('Requires wpa-supplicant'),
1169                                                         'psk2': has_supplicant || _('Requires wpa-supplicant'),
1170                                                         'psk-mixed': has_supplicant || _('Requires wpa-supplicant'),
1171                                                         'sae': has_sta_sae || _('Requires wpa-supplicant with SAE support'),
1172                                                         'sae-mixed': has_sta_sae || _('Requires wpa-supplicant with SAE support'),
1173                                                         'wpa': has_sta_eap || _('Requires wpa-supplicant with EAP support'),
1174                                                         'wpa2': has_sta_eap || _('Requires wpa-supplicant with EAP support'),
1175                                                         'owe': has_sta_owe || _('Requires wpa-supplicant with OWE support')
1176                                                 },
1177                                                 'adhoc': {
1178                                                         'wep-open': true,
1179                                                         'wep-shared': true,
1180                                                         'psk': has_supplicant || _('Requires wpa-supplicant'),
1181                                                         'psk2': has_supplicant || _('Requires wpa-supplicant'),
1182                                                         'psk-mixed': has_supplicant || _('Requires wpa-supplicant'),
1183                                                 },
1184                                                 'mesh': {
1185                                                         'sae': has_sta_sae || _('Requires wpa-supplicant with SAE support')
1186                                                 },
1187                                                 'ahdemo': {
1188                                                         'wep-open': true,
1189                                                         'wep-shared': true
1190                                                 },
1191                                                 'wds': {
1192                                                         'wep-open': true,
1193                                                         'wep-shared': true
1194                                                 }
1195                                         };
1196
1197                                         encr.crypto_support['ap-wds'] = encr.crypto_support['ap'];
1198                                         encr.crypto_support['sta-wds'] = encr.crypto_support['sta'];
1199
1200                                         encr.validate = function(section_id, value) {
1201                                                 var modeopt = this.section.children.filter(function(o) { return o.option == 'mode' })[0],
1202                                                     modeval = modeopt.formvalue(section_id),
1203                                                     modetitle = modeopt.vallist[modeopt.keylist.indexOf(modeval)],
1204                                                     enctitle = this.vallist[this.keylist.indexOf(value)];
1205
1206                                                 if (value == 'none')
1207                                                         return true;
1208
1209                                                 if (!L.isObject(this.crypto_support[modeval]) || !this.crypto_support[modeval].hasOwnProperty(value))
1210                                                         return _('The selected %s mode is incompatible with %s encryption').format(modetitle, enctitle);
1211
1212                                                 return this.crypto_support[modeval][value];
1213                                         };
1214                                 }
1215                                 else if (hwtype == 'broadcom') {
1216                                         crypto_modes.push(['psk2',     'WPA2-PSK',                    33]);
1217                                         crypto_modes.push(['psk+psk2', 'WPA-PSK/WPA2-PSK Mixed Mode', 22]);
1218                                         crypto_modes.push(['psk',      'WPA-PSK',                     21]);
1219                                 }
1220
1221                                 crypto_modes.push(['wep-open',   _('WEP Open System'), 11]);
1222                                 crypto_modes.push(['wep-shared', _('WEP Shared Key'),  10]);
1223                                 crypto_modes.push(['none',       _('No Encryption'),   0]);
1224
1225                                 crypto_modes.sort(function(a, b) { return b[2] - a[2] });
1226
1227                                 for (var i = 0; i < crypto_modes.length; i++) {
1228                                         var security_level = (crypto_modes[i][2] >= 30) ? _('strong security')
1229                                                 : (crypto_modes[i][2] >= 20) ? _('medium security')
1230                                                         : (crypto_modes[i][2] >= 10) ? _('weak security') : _('open network');
1231
1232                                         encr.value(crypto_modes[i][0], '%s (%s)'.format(crypto_modes[i][1], security_level));
1233                                 }
1234
1235
1236                                 o = ss.taboption('encryption', form.Value, 'auth_server', _('Radius-Authentication-Server'));
1237                                 o.depends({ mode: 'ap', encryption: 'wpa' });
1238                                 o.depends({ mode: 'ap', encryption: 'wpa2' });
1239                                 o.depends({ mode: 'ap-wds', encryption: 'wpa' });
1240                                 o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1241                                 o.rmempty = true;
1242                                 o.datatype = 'host(0)';
1243
1244                                 o = ss.taboption('encryption', form.Value, 'auth_port', _('Radius-Authentication-Port'), _('Default %d').format(1812));
1245                                 o.depends({ mode: 'ap', encryption: 'wpa' });
1246                                 o.depends({ mode: 'ap', encryption: 'wpa2' });
1247                                 o.depends({ mode: 'ap-wds', encryption: 'wpa' });
1248                                 o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1249                                 o.rmempty = true;
1250                                 o.datatype = 'port';
1251
1252                                 o = ss.taboption('encryption', form.Value, 'auth_secret', _('Radius-Authentication-Secret'));
1253                                 o.depends({ mode: 'ap', encryption: 'wpa' });
1254                                 o.depends({ mode: 'ap', encryption: 'wpa2' });
1255                                 o.depends({ mode: 'ap-wds', encryption: 'wpa' });
1256                                 o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1257                                 o.rmempty = true;
1258                                 o.password = true;
1259
1260                                 o = ss.taboption('encryption', form.Value, 'acct_server', _('Radius-Accounting-Server'));
1261                                 o.depends({ mode: 'ap', encryption: 'wpa' });
1262                                 o.depends({ mode: 'ap', encryption: 'wpa2' });
1263                                 o.depends({ mode: 'ap-wds', encryption: 'wpa' });
1264                                 o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1265                                 o.rmempty = true;
1266                                 o.datatype = 'host(0)';
1267
1268                                 o = ss.taboption('encryption', form.Value, 'acct_port', _('Radius-Accounting-Port'), _('Default %d').format(1813));
1269                                 o.depends({ mode: 'ap', encryption: 'wpa' });
1270                                 o.depends({ mode: 'ap', encryption: 'wpa2' });
1271                                 o.depends({ mode: 'ap-wds', encryption: 'wpa' });
1272                                 o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1273                                 o.rmempty = true;
1274                                 o.datatype = 'port';
1275
1276                                 o = ss.taboption('encryption', form.Value, 'acct_secret', _('Radius-Accounting-Secret'));
1277                                 o.depends({ mode: 'ap', encryption: 'wpa' });
1278                                 o.depends({ mode: 'ap', encryption: 'wpa2' });
1279                                 o.depends({ mode: 'ap-wds', encryption: 'wpa' });
1280                                 o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1281                                 o.rmempty = true;
1282                                 o.password = true;
1283
1284                                 o = ss.taboption('encryption', form.Value, 'dae_client', _('DAE-Client'));
1285                                 o.depends({ mode: 'ap', encryption: 'wpa' });
1286                                 o.depends({ mode: 'ap', encryption: 'wpa2' });
1287                                 o.depends({ mode: 'ap-wds', encryption: 'wpa' });
1288                                 o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1289                                 o.rmempty = true;
1290                                 o.datatype = 'host(0)';
1291
1292                                 o = ss.taboption('encryption', form.Value, 'dae_port', _('DAE-Port'), _('Default %d').format(3799));
1293                                 o.depends({ mode: 'ap', encryption: 'wpa' });
1294                                 o.depends({ mode: 'ap', encryption: 'wpa2' });
1295                                 o.depends({ mode: 'ap-wds', encryption: 'wpa' });
1296                                 o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1297                                 o.rmempty = true;
1298                                 o.datatype = 'port';
1299
1300                                 o = ss.taboption('encryption', form.Value, 'dae_secret', _('DAE-Secret'));
1301                                 o.depends({ mode: 'ap', encryption: 'wpa' });
1302                                 o.depends({ mode: 'ap', encryption: 'wpa2' });
1303                                 o.depends({ mode: 'ap-wds', encryption: 'wpa' });
1304                                 o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1305                                 o.rmempty = true;
1306                                 o.password = true;
1307
1308
1309                                 o = ss.taboption('encryption', form.Value, '_wpa_key', _('Key'));
1310                                 o.depends('encryption', 'psk');
1311                                 o.depends('encryption', 'psk2');
1312                                 o.depends('encryption', 'psk+psk2');
1313                                 o.depends('encryption', 'psk-mixed');
1314                                 o.depends('encryption', 'sae');
1315                                 o.depends('encryption', 'sae-mixed');
1316                                 o.datatype = 'wpakey';
1317                                 o.rmempty = true;
1318                                 o.password = true;
1319
1320                                 o.cfgvalue = function(section_id) {
1321                                         var key = uci.get('wireless', section_id, 'key');
1322                                         return /^[1234]$/.test(key) ? null : key;
1323                                 };
1324
1325                                 o.write = function(section_id, value) {
1326                                         uci.set('wireless', section_id, 'key', value);
1327                                         uci.unset('wireless', section_id, 'key1');
1328                                         uci.unset('wireless', section_id, 'key2');
1329                                         uci.unset('wireless', section_id, 'key3');
1330                                         uci.unset('wireless', section_id, 'key4');
1331                                 };
1332
1333
1334                                 o = ss.taboption('encryption', form.ListValue, '_wep_key', _('Used Key Slot'));
1335                                 o.depends('encryption', 'wep-open');
1336                                 o.depends('encryption', 'wep-shared');
1337                                 o.value('1', _('Key #%d').format(1));
1338                                 o.value('2', _('Key #%d').format(2));
1339                                 o.value('3', _('Key #%d').format(3));
1340                                 o.value('4', _('Key #%d').format(4));
1341
1342                                 o.cfgvalue = function(section_id) {
1343                                         var slot = +uci.get('wireless', section_id, 'key');
1344                                         return (slot >= 1 && slot <= 4) ? String(slot) : '';
1345                                 };
1346
1347                                 o.write = function(section_id, value) {
1348                                         uci.set('wireless', section_id, 'key', value);
1349                                 };
1350
1351                                 for (var slot = 1; slot <= 4; slot++) {
1352                                         o = ss.taboption('encryption', form.Value, 'key%d'.format(slot), _('Key #%d').format(slot));
1353                                         o.depends('encryption', 'wep-open');
1354                                         o.depends('encryption', 'wep-shared');
1355                                         o.datatype = 'wepkey';
1356                                         o.rmempty = true;
1357                                         o.password = true;
1358
1359                                         o.write = function(section_id, value) {
1360                                                 if (value != null && (value.length == 5 || value.length == 13))
1361                                                         value = 's:%s'.format(value);
1362                                                 uci.set('wireless', section_id, this.option, value);
1363                                         };
1364                                 }
1365
1366
1367                                 if (hwtype == 'mac80211') {
1368                                         // Probe 802.11r support (and EAP support as a proxy for Openwrt)
1369                                         var has_80211r = L.hasSystemFeature('hostapd', '11r') || L.hasSystemFeature('hostapd', 'eap');
1370
1371                                         o = ss.taboption('encryption', form.Flag, 'ieee80211r', _('802.11r Fast Transition'), _('Enables fast roaming among access points that belong to the same Mobility Domain'));
1372                                         o.depends({ mode: 'ap', encryption: 'wpa' });
1373                                         o.depends({ mode: 'ap', encryption: 'wpa2' });
1374                                         o.depends({ mode: 'ap-wds', encryption: 'wpa' });
1375                                         o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1376                                         if (has_80211r) {
1377                                                 o.depends({ mode: 'ap', encryption: 'psk' });
1378                                                 o.depends({ mode: 'ap', encryption: 'psk2' });
1379                                                 o.depends({ mode: 'ap', encryption: 'psk-mixed' });
1380                                                 o.depends({ mode: 'ap', encryption: 'sae' });
1381                                                 o.depends({ mode: 'ap', encryption: 'sae-mixed' });
1382                                                 o.depends({ mode: 'ap-wds', encryption: 'psk' });
1383                                                 o.depends({ mode: 'ap-wds', encryption: 'psk2' });
1384                                                 o.depends({ mode: 'ap-wds', encryption: 'psk-mixed' });
1385                                                 o.depends({ mode: 'ap-wds', encryption: 'sae' });
1386                                                 o.depends({ mode: 'ap-wds', encryption: 'sae-mixed' });
1387                                         }
1388                                         o.rmempty = true;
1389
1390                                         o = ss.taboption('encryption', form.Value, 'nasid', _('NAS ID'), _('Used for two different purposes: RADIUS NAS ID and 802.11r R0KH-ID. Not needed with normal WPA(2)-PSK.'));
1391                                         o.depends({ mode: 'ap', encryption: 'wpa' });
1392                                         o.depends({ mode: 'ap', encryption: 'wpa2' });
1393                                         o.depends({ mode: 'ap-wds', encryption: 'wpa' });
1394                                         o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1395                                         o.depends({ ieee80211r: '1' });
1396                                         o.rmempty = true;
1397
1398                                         o = ss.taboption('encryption', form.Value, 'mobility_domain', _('Mobility Domain'), _('4-character hexadecimal ID'));
1399                                         o.depends({ ieee80211r: '1' });
1400                                         o.placeholder = '4f57';
1401                                         o.datatype = 'and(hexstring,length(4))';
1402                                         o.rmempty = true;
1403
1404                                         o = ss.taboption('encryption', form.Value, 'reassociation_deadline', _('Reassociation Deadline'), _('time units (TUs / 1.024 ms) [1000-65535]'));
1405                                         o.depends({ ieee80211r: '1' });
1406                                         o.placeholder = '1000';
1407                                         o.datatype = 'range(1000,65535)';
1408                                         o.rmempty = true;
1409
1410                                         o = ss.taboption('encryption', form.ListValue, 'ft_over_ds', _('FT protocol'));
1411                                         o.depends({ ieee80211r: '1' });
1412                                         o.value('1', _('FT over DS'));
1413                                         o.value('0', _('FT over the Air'));
1414                                         o.rmempty = true;
1415
1416                                         o = ss.taboption('encryption', form.Flag, 'ft_psk_generate_local', _('Generate PMK locally'), _('When using a PSK, the PMK can be automatically generated. When enabled, the R0/R1 key options below are not applied. Disable this to use the R0 and R1 key options.'));
1417                                         o.depends({ ieee80211r: '1' });
1418                                         o.default = o.enabled;
1419                                         o.rmempty = false;
1420
1421                                         o = ss.taboption('encryption', form.Value, 'r0_key_lifetime', _('R0 Key Lifetime'), _('minutes'));
1422                                         o.depends({ ieee80211r: '1' });
1423                                         o.placeholder = '10000';
1424                                         o.datatype = 'uinteger';
1425                                         o.rmempty = true;
1426
1427                                         o = ss.taboption('encryption', form.Value, 'r1_key_holder', _('R1 Key Holder'), _('6-octet identifier as a hex string - no colons'));
1428                                         o.depends({ ieee80211r: '1' });
1429                                         o.placeholder = '00004f577274';
1430                                         o.datatype = 'and(hexstring,length(12))';
1431                                         o.rmempty = true;
1432
1433                                         o = ss.taboption('encryption', form.Flag, 'pmk_r1_push', _('PMK R1 Push'));
1434                                         o.depends({ ieee80211r: '1' });
1435                                         o.placeholder = '0';
1436                                         o.rmempty = true;
1437
1438                                         o = ss.taboption('encryption', form.DynamicList, 'r0kh', _('External R0 Key Holder List'), _('List of R0KHs in the same Mobility Domain. <br />Format: MAC-address,NAS-Identifier,128-bit key as hex string. <br />This list is used to map R0KH-ID (NAS Identifier) to a destination MAC address when requesting PMK-R1 key from the R0KH that the STA used during the Initial Mobility Domain Association.'));
1439                                         o.depends({ ieee80211r: '1' });
1440                                         o.rmempty = true;
1441
1442                                         o = ss.taboption('encryption', form.DynamicList, 'r1kh', _('External R1 Key Holder List'), _ ('List of R1KHs in the same Mobility Domain. <br />Format: MAC-address,R1KH-ID as 6 octets with colons,128-bit key as hex string. <br />This list is used to map R1KH-ID to a destination MAC address when sending PMK-R1 key from the R0KH. This is also the list of authorized R1KHs in the MD that can request PMK-R1 keys.'));
1443                                         o.depends({ ieee80211r: '1' });
1444                                         o.rmempty = true;
1445                                         // End of 802.11r options
1446
1447                                         o = ss.taboption('encryption', form.ListValue, 'eap_type', _('EAP-Method'));
1448                                         o.value('tls',  'TLS');
1449                                         o.value('ttls', 'TTLS');
1450                                         o.value('peap', 'PEAP');
1451                                         o.value('fast', 'FAST');
1452                                         o.depends({ mode: 'sta', encryption: 'wpa' });
1453                                         o.depends({ mode: 'sta', encryption: 'wpa2' });
1454                                         o.depends({ mode: 'sta-wds', encryption: 'wpa' });
1455                                         o.depends({ mode: 'sta-wds', encryption: 'wpa2' });
1456
1457                                         o = ss.taboption('encryption', form.Flag, 'ca_cert_usesystem', _('Use system certificates'), _("Validate server certificate using built-in system CA bundle,<br />requires the \"ca-bundle\" package"));
1458                                         o.enabled = '1';
1459                                         o.disabled = '0';
1460                                         o.default = o.disabled;
1461                                         o.depends({ mode: 'sta', encryption: 'wpa' });
1462                                         o.depends({ mode: 'sta', encryption: 'wpa2' });
1463                                         o.depends({ mode: 'sta-wds', encryption: 'wpa' });
1464                                         o.depends({ mode: 'sta-wds', encryption: 'wpa2' });
1465                                         o.validate = function(section_id, value) {
1466                                                 if (value == '1' && !L.hasSystemFeature('cabundle')) {
1467                                                         return _("This option cannot be used because the ca-bundle package is not installed.");
1468                                                 }
1469                                                 return true;
1470                                         };
1471
1472                                         o = ss.taboption('encryption', form.FileUpload, 'ca_cert', _('Path to CA-Certificate'));
1473                                         o.depends({ mode: 'sta', encryption: 'wpa', ca_cert_usesystem: '0' });
1474                                         o.depends({ mode: 'sta', encryption: 'wpa2', ca_cert_usesystem: '0' });
1475                                         o.depends({ mode: 'sta-wds', encryption: 'wpa', ca_cert_usesystem: '0' });
1476                                         o.depends({ mode: 'sta-wds', encryption: 'wpa2', ca_cert_usesystem: '0' });
1477
1478                                         o = ss.taboption('encryption', form.Value, 'subject_match', _('Certificate constraint (Subject)'), _("Certificate constraint substring - e.g. /CN=wifi.mycompany.com<br />See `logread -f` during handshake for actual values"));
1479                                         o.depends({ mode: 'sta', encryption: 'wpa' });
1480                                         o.depends({ mode: 'sta', encryption: 'wpa2' });
1481                                         o.depends({ mode: 'sta-wds', encryption: 'wpa' });
1482                                         o.depends({ mode: 'sta-wds', encryption: 'wpa2' });
1483
1484                                         o = ss.taboption('encryption', form.DynamicList, 'altsubject_match', _('Certificate constraint (SAN)'), _("Certificate constraint(s) via Subject Alternate Name values<br />(supported attributes: EMAIL, DNS, URI) - e.g. DNS:wifi.mycompany.com"));
1485                                         o.depends({ mode: 'sta', encryption: 'wpa' });
1486                                         o.depends({ mode: 'sta', encryption: 'wpa2' });
1487                                         o.depends({ mode: 'sta-wds', encryption: 'wpa' });
1488                                         o.depends({ mode: 'sta-wds', encryption: 'wpa2' });
1489
1490                                         o = ss.taboption('encryption', form.DynamicList, 'domain_match', _('Certificate constraint (Domain)'), _("Certificate constraint(s) against DNS SAN values (if available)<br />or Subject CN (exact match)"));
1491                                         o.depends({ mode: 'sta', encryption: 'wpa' });
1492                                         o.depends({ mode: 'sta', encryption: 'wpa2' });
1493                                         o.depends({ mode: 'sta-wds', encryption: 'wpa' });
1494                                         o.depends({ mode: 'sta-wds', encryption: 'wpa2' });
1495
1496                                         o = ss.taboption('encryption', form.DynamicList, 'domain_suffix_match', _('Certificate constraint (Wildcard)'), _("Certificate constraint(s) against DNS SAN values (if available)<br />or Subject CN (suffix match)"));
1497                                         o.depends({ mode: 'sta', encryption: 'wpa' });
1498                                         o.depends({ mode: 'sta', encryption: 'wpa2' });
1499                                         o.depends({ mode: 'sta-wds', encryption: 'wpa' });
1500                                         o.depends({ mode: 'sta-wds', encryption: 'wpa2' });
1501
1502                                         o = ss.taboption('encryption', form.FileUpload, 'client_cert', _('Path to Client-Certificate'));
1503                                         o.depends({ mode: 'sta', eap_type: 'tls', encryption: 'wpa' });
1504                                         o.depends({ mode: 'sta', eap_type: 'tls', encryption: 'wpa2' });
1505                                         o.depends({ mode: 'sta-wds', eap_type: 'tls', encryption: 'wpa' });
1506                                         o.depends({ mode: 'sta-wds', eap_type: 'tls', encryption: 'wpa2' });
1507
1508                                         o = ss.taboption('encryption', form.FileUpload, 'priv_key', _('Path to Private Key'));
1509                                         o.depends({ mode: 'sta', eap_type: 'tls', encryption: 'wpa2' });
1510                                         o.depends({ mode: 'sta', eap_type: 'tls', encryption: 'wpa' });
1511                                         o.depends({ mode: 'sta-wds', eap_type: 'tls', encryption: 'wpa2' });
1512                                         o.depends({ mode: 'sta-wds', eap_type: 'tls', encryption: 'wpa' });
1513
1514                                         o = ss.taboption('encryption', form.Value, 'priv_key_pwd', _('Password of Private Key'));
1515                                         o.depends({ mode: 'sta', eap_type: 'tls', encryption: 'wpa2' });
1516                                         o.depends({ mode: 'sta', eap_type: 'tls', encryption: 'wpa' });
1517                                         o.depends({ mode: 'sta-wds', eap_type: 'tls', encryption: 'wpa2' });
1518                                         o.depends({ mode: 'sta-wds', eap_type: 'tls', encryption: 'wpa' });
1519                                         o.password = true;
1520
1521                                         o = ss.taboption('encryption', form.ListValue, 'auth', _('Authentication'));
1522                                         o.value('PAP', 'PAP');
1523                                         o.value('CHAP', 'CHAP');
1524                                         o.value('MSCHAP', 'MSCHAP');
1525                                         o.value('MSCHAPV2', 'MSCHAPv2');
1526                                         o.value('EAP-GTC');
1527                                         o.value('EAP-MD5');
1528                                         o.value('EAP-MSCHAPV2');
1529                                         o.value('EAP-TLS');
1530                                         o.depends({ mode: 'sta', eap_type: 'fast', encryption: 'wpa2' });
1531                                         o.depends({ mode: 'sta', eap_type: 'fast', encryption: 'wpa' });
1532                                         o.depends({ mode: 'sta', eap_type: 'peap', encryption: 'wpa2' });
1533                                         o.depends({ mode: 'sta', eap_type: 'peap', encryption: 'wpa' });
1534                                         o.depends({ mode: 'sta', eap_type: 'ttls', encryption: 'wpa2' });
1535                                         o.depends({ mode: 'sta', eap_type: 'ttls', encryption: 'wpa' });
1536                                         o.depends({ mode: 'sta-wds', eap_type: 'fast', encryption: 'wpa2' });
1537                                         o.depends({ mode: 'sta-wds', eap_type: 'fast', encryption: 'wpa' });
1538                                         o.depends({ mode: 'sta-wds', eap_type: 'peap', encryption: 'wpa2' });
1539                                         o.depends({ mode: 'sta-wds', eap_type: 'peap', encryption: 'wpa' });
1540                                         o.depends({ mode: 'sta-wds', eap_type: 'ttls', encryption: 'wpa2' });
1541                                         o.depends({ mode: 'sta-wds', eap_type: 'ttls', encryption: 'wpa' });
1542
1543                                         o.validate = function(section_id, value) {
1544                                                 var eo = this.section.children.filter(function(o) { return o.option == 'eap_type' })[0],
1545                                                     ev = eo.formvalue(section_id);
1546
1547                                                 if (ev != 'ttls' && (value == 'PAP' || value == 'CHAP' || value == 'MSCHAP' || value == 'MSCHAPV2'))
1548                                                         return _('This authentication type is not applicable to the selected EAP method.');
1549
1550                                                 return true;
1551                                         };
1552
1553                                         o = ss.taboption('encryption', form.Flag, 'ca_cert2_usesystem', _('Use system certificates for inner-tunnel'), _("Validate server certificate using built-in system CA bundle,<br />requires the \"ca-bundle\" package"));
1554                                         o.enabled = '1';
1555                                         o.disabled = '0';
1556                                         o.default = o.disabled;
1557                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa' });
1558                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa2' });
1559                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa' });
1560                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa2' });
1561                                         o.validate = function(section_id, value) {
1562                                                 if (value == '1' && !L.hasSystemFeature('cabundle')) {
1563                                                         return _("This option cannot be used because the ca-bundle package is not installed.");
1564                                                 }
1565                                                 return true;
1566                                         };
1567
1568                                         o = ss.taboption('encryption', form.FileUpload, 'ca_cert2', _('Path to inner CA-Certificate'));
1569                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa', ca_cert2_usesystem: '0' });
1570                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa2', ca_cert2_usesystem: '0' });
1571                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa', ca_cert2_usesystem: '0' });
1572                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa2', ca_cert2_usesystem: '0' });
1573
1574                                         o = ss.taboption('encryption', form.Value, 'subject_match2', _('Inner certificate constraint (Subject)'), _("Certificate constraint substring - e.g. /CN=wifi.mycompany.com<br />See `logread -f` during handshake for actual values"));
1575                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa' });
1576                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa2' });
1577                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa' });
1578                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa2' });
1579
1580                                         o = ss.taboption('encryption', form.DynamicList, 'altsubject_match2', _('Inner certificate constraint (SAN)'), _("Certificate constraint(s) via Subject Alternate Name values<br />(supported attributes: EMAIL, DNS, URI) - e.g. DNS:wifi.mycompany.com"));
1581                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa' });
1582                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa2' });
1583                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa' });
1584                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa2' });
1585
1586                                         o = ss.taboption('encryption', form.DynamicList, 'domain_match2', _('Inner certificate constraint (Domain)'), _("Certificate constraint(s) against DNS SAN values (if available)<br />or Subject CN (exact match)"));
1587                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa' });
1588                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa2' });
1589                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa' });
1590                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa2' });
1591
1592                                         o = ss.taboption('encryption', form.DynamicList, 'domain_suffix_match2', _('Inner certificate constraint (Wildcard)'), _("Certificate constraint(s) against DNS SAN values (if available)<br />or Subject CN (suffix match)"));
1593                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa' });
1594                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa2' });
1595                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa' });
1596                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa2' });
1597
1598                                         o = ss.taboption('encryption', form.FileUpload, 'client_cert2', _('Path to inner Client-Certificate'));
1599                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa' });
1600                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa2' });
1601                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa' });
1602                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa2' });
1603
1604                                         o = ss.taboption('encryption', form.FileUpload, 'priv_key2', _('Path to inner Private Key'));
1605                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa' });
1606                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa2' });
1607                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa' });
1608                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa2' });
1609
1610                                         o = ss.taboption('encryption', form.Value, 'priv_key2_pwd', _('Password of inner Private Key'));
1611                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa' });
1612                                         o.depends({ mode: 'sta', auth: 'EAP-TLS', encryption: 'wpa2' });
1613                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa' });
1614                                         o.depends({ mode: 'sta-wds', auth: 'EAP-TLS', encryption: 'wpa2' });
1615                                         o.password = true;
1616
1617                                         o = ss.taboption('encryption', form.Value, 'identity', _('Identity'));
1618                                         o.depends({ mode: 'sta', eap_type: 'fast', encryption: 'wpa2' });
1619                                         o.depends({ mode: 'sta', eap_type: 'fast', encryption: 'wpa' });
1620                                         o.depends({ mode: 'sta', eap_type: 'peap', encryption: 'wpa2' });
1621                                         o.depends({ mode: 'sta', eap_type: 'peap', encryption: 'wpa' });
1622                                         o.depends({ mode: 'sta', eap_type: 'ttls', encryption: 'wpa2' });
1623                                         o.depends({ mode: 'sta', eap_type: 'ttls', encryption: 'wpa' });
1624                                         o.depends({ mode: 'sta-wds', eap_type: 'fast', encryption: 'wpa2' });
1625                                         o.depends({ mode: 'sta-wds', eap_type: 'fast', encryption: 'wpa' });
1626                                         o.depends({ mode: 'sta-wds', eap_type: 'peap', encryption: 'wpa2' });
1627                                         o.depends({ mode: 'sta-wds', eap_type: 'peap', encryption: 'wpa' });
1628                                         o.depends({ mode: 'sta-wds', eap_type: 'ttls', encryption: 'wpa2' });
1629                                         o.depends({ mode: 'sta-wds', eap_type: 'ttls', encryption: 'wpa' });
1630                                         o.depends({ mode: 'sta', eap_type: 'tls', encryption: 'wpa2' });
1631                                         o.depends({ mode: 'sta', eap_type: 'tls', encryption: 'wpa' });
1632                                         o.depends({ mode: 'sta-wds', eap_type: 'tls', encryption: 'wpa2' });
1633                                         o.depends({ mode: 'sta-wds', eap_type: 'tls', encryption: 'wpa' });
1634
1635                                         o = ss.taboption('encryption', form.Value, 'anonymous_identity', _('Anonymous Identity'));
1636                                         o.depends({ mode: 'sta', eap_type: 'fast', encryption: 'wpa2' });
1637                                         o.depends({ mode: 'sta', eap_type: 'fast', encryption: 'wpa' });
1638                                         o.depends({ mode: 'sta', eap_type: 'peap', encryption: 'wpa2' });
1639                                         o.depends({ mode: 'sta', eap_type: 'peap', encryption: 'wpa' });
1640                                         o.depends({ mode: 'sta', eap_type: 'ttls', encryption: 'wpa2' });
1641                                         o.depends({ mode: 'sta', eap_type: 'ttls', encryption: 'wpa' });
1642                                         o.depends({ mode: 'sta-wds', eap_type: 'fast', encryption: 'wpa2' });
1643                                         o.depends({ mode: 'sta-wds', eap_type: 'fast', encryption: 'wpa' });
1644                                         o.depends({ mode: 'sta-wds', eap_type: 'peap', encryption: 'wpa2' });
1645                                         o.depends({ mode: 'sta-wds', eap_type: 'peap', encryption: 'wpa' });
1646                                         o.depends({ mode: 'sta-wds', eap_type: 'ttls', encryption: 'wpa2' });
1647                                         o.depends({ mode: 'sta-wds', eap_type: 'ttls', encryption: 'wpa' });
1648                                         o.depends({ mode: 'sta', eap_type: 'tls', encryption: 'wpa2' });
1649                                         o.depends({ mode: 'sta', eap_type: 'tls', encryption: 'wpa' });
1650                                         o.depends({ mode: 'sta-wds', eap_type: 'tls', encryption: 'wpa2' });
1651                                         o.depends({ mode: 'sta-wds', eap_type: 'tls', encryption: 'wpa' });
1652
1653                                         o = ss.taboption('encryption', form.Value, 'password', _('Password'));
1654                                         o.depends({ mode: 'sta', eap_type: 'fast', encryption: 'wpa2' });
1655                                         o.depends({ mode: 'sta', eap_type: 'fast', encryption: 'wpa' });
1656                                         o.depends({ mode: 'sta', eap_type: 'peap', encryption: 'wpa2' });
1657                                         o.depends({ mode: 'sta', eap_type: 'peap', encryption: 'wpa' });
1658                                         o.depends({ mode: 'sta', eap_type: 'ttls', encryption: 'wpa2' });
1659                                         o.depends({ mode: 'sta', eap_type: 'ttls', encryption: 'wpa' });
1660                                         o.depends({ mode: 'sta-wds', eap_type: 'fast', encryption: 'wpa2' });
1661                                         o.depends({ mode: 'sta-wds', eap_type: 'fast', encryption: 'wpa' });
1662                                         o.depends({ mode: 'sta-wds', eap_type: 'peap', encryption: 'wpa2' });
1663                                         o.depends({ mode: 'sta-wds', eap_type: 'peap', encryption: 'wpa' });
1664                                         o.depends({ mode: 'sta-wds', eap_type: 'ttls', encryption: 'wpa2' });
1665                                         o.depends({ mode: 'sta-wds', eap_type: 'ttls', encryption: 'wpa' });
1666                                         o.password = true;
1667
1668
1669                                         if (hwtype == 'mac80211') {
1670                                                 // ieee802.11w options
1671                                                 if (L.hasSystemFeature('hostapd', '11w')) {
1672                                                         o = ss.taboption('encryption', form.ListValue, 'ieee80211w', _('802.11w Management Frame Protection'), _("Requires the 'full' version of wpad/hostapd and support from the wifi driver <br />(as of Jan 2019: ath9k, ath10k, mwlwifi and mt76)"));
1673                                                         o.value('', _('Disabled'));
1674                                                         o.value('1', _('Optional'));
1675                                                         o.value('2', _('Required'));
1676                                                         o.depends({ mode: 'ap', encryption: 'wpa2' });
1677                                                         o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1678                                                         o.depends({ mode: 'ap', encryption: 'psk2' });
1679                                                         o.depends({ mode: 'ap', encryption: 'psk-mixed' });
1680                                                         o.depends({ mode: 'ap', encryption: 'sae' });
1681                                                         o.depends({ mode: 'ap', encryption: 'sae-mixed' });
1682                                                         o.depends({ mode: 'ap', encryption: 'owe' });
1683                                                         o.depends({ mode: 'ap-wds', encryption: 'psk2' });
1684                                                         o.depends({ mode: 'ap-wds', encryption: 'psk-mixed' });
1685                                                         o.depends({ mode: 'ap-wds', encryption: 'sae' });
1686                                                         o.depends({ mode: 'ap-wds', encryption: 'sae-mixed' });
1687                                                         o.depends({ mode: 'ap-wds', encryption: 'owe' });
1688                                                         o.depends({ mode: 'sta', encryption: 'wpa2' });
1689                                                         o.depends({ mode: 'sta-wds', encryption: 'wpa2' });
1690                                                         o.depends({ mode: 'sta', encryption: 'psk2' });
1691                                                         o.depends({ mode: 'sta', encryption: 'psk-mixed' });
1692                                                         o.depends({ mode: 'sta', encryption: 'sae' });
1693                                                         o.depends({ mode: 'sta', encryption: 'sae-mixed' });
1694                                                         o.depends({ mode: 'sta', encryption: 'owe' });
1695                                                         o.depends({ mode: 'sta-wds', encryption: 'psk2' });
1696                                                         o.depends({ mode: 'sta-wds', encryption: 'psk-mixed' });
1697                                                         o.depends({ mode: 'sta-wds', encryption: 'sae' });
1698                                                         o.depends({ mode: 'sta-wds', encryption: 'sae-mixed' });
1699                                                         o.depends({ mode: 'sta-wds', encryption: 'owe' });
1700                                                         o.defaults = {
1701                                                                 '2': [{ encryption: 'sae' }, { encryption: 'owe' }],
1702                                                                 '1': [{ encryption: 'sae-mixed'}],
1703                                                                 '':  []
1704                                                         };
1705
1706                                                         o = ss.taboption('encryption', form.Value, 'ieee80211w_max_timeout', _('802.11w maximum timeout'), _('802.11w Association SA Query maximum timeout'));
1707                                                         o.depends('ieee80211w', '1');
1708                                                         o.depends('ieee80211w', '2');
1709                                                         o.datatype = 'uinteger';
1710                                                         o.placeholder = '1000';
1711                                                         o.rmempty = true;
1712
1713                                                         o = ss.taboption('encryption', form.Value, 'ieee80211w_retry_timeout', _('802.11w retry timeout'), _('802.11w Association SA Query retry timeout'));
1714                                                         o.depends('ieee80211w', '1');
1715                                                         o.depends('ieee80211w', '2');
1716                                                         o.datatype = 'uinteger';
1717                                                         o.placeholder = '201';
1718                                                         o.rmempty = true;
1719                                                 };
1720
1721                                                 o = ss.taboption('encryption', form.Flag, 'wpa_disable_eapol_key_retries', _('Enable key reinstallation (KRACK) countermeasures'), _('Complicates key reinstallation attacks on the client side by disabling retransmission of EAPOL-Key frames that are used to install keys. This workaround might cause interoperability issues and reduced robustness of key negotiation especially in environments with heavy traffic load.'));
1722                                                 o.depends({ mode: 'ap', encryption: 'wpa2' });
1723                                                 o.depends({ mode: 'ap', encryption: 'psk2' });
1724                                                 o.depends({ mode: 'ap', encryption: 'psk-mixed' });
1725                                                 o.depends({ mode: 'ap', encryption: 'sae' });
1726                                                 o.depends({ mode: 'ap', encryption: 'sae-mixed' });
1727                                                 o.depends({ mode: 'ap-wds', encryption: 'wpa2' });
1728                                                 o.depends({ mode: 'ap-wds', encryption: 'psk2' });
1729                                                 o.depends({ mode: 'ap-wds', encryption: 'psk-mixed' });
1730                                                 o.depends({ mode: 'ap-wds', encryption: 'sae' });
1731                                                 o.depends({ mode: 'ap-wds', encryption: 'sae-mixed' });
1732
1733                                                 if (L.hasSystemFeature('hostapd', 'cli') && L.hasSystemFeature('wpasupplicant')) {
1734                                                         o = ss.taboption('encryption', form.Flag, 'wps_pushbutton', _('Enable WPS pushbutton, requires WPA(2)-PSK/WPA3-SAE'))
1735                                                         o.enabled = '1';
1736                                                         o.disabled = '0';
1737                                                         o.default = o.disabled;
1738                                                         o.depends('encryption', 'psk');
1739                                                         o.depends('encryption', 'psk2');
1740                                                         o.depends('encryption', 'psk-mixed');
1741                                                         o.depends('encryption', 'sae');
1742                                                         o.depends('encryption', 'sae-mixed');
1743                                                 }
1744                                         }
1745                                 }
1746                         });
1747                 };
1748
1749                 s.handleRemove = function(section_id, ev) {
1750                         document.querySelector('.cbi-section-table-row[data-sid="%s"]'.format(section_id)).style.opacity = 0.5;
1751                         return form.TypedSection.prototype.handleRemove.apply(this, [section_id, ev]);
1752                 };
1753
1754                 s.handleScan = function(radioDev, ev) {
1755                         var table = E('div', { 'class': 'table' }, [
1756                                 E('div', { 'class': 'tr table-titles' }, [
1757                                         E('div', { 'class': 'th col-2 middle center' }, _('Signal')),
1758                                         E('div', { 'class': 'th col-4 middle left' }, _('SSID')),
1759                                         E('div', { 'class': 'th col-2 middle center hide-xs' }, _('Channel')),
1760                                         E('div', { 'class': 'th col-2 middle left hide-xs' }, _('Mode')),
1761                                         E('div', { 'class': 'th col-3 middle left hide-xs' }, _('BSSID')),
1762                                         E('div', { 'class': 'th col-3 middle left' }, _('Encryption')),
1763                                         E('div', { 'class': 'th cbi-section-actions right' }, ' '),
1764                                 ])
1765                         ]);
1766
1767                         var stop = E('button', {
1768                                 'class': 'btn',
1769                                 'click': L.bind(this.handleScanStartStop, this),
1770                                 'style': 'display:none',
1771                                 'data-state': 'stop'
1772                         }, _('Stop refresh'));
1773
1774                         cbi_update_table(table, [], E('em', { class: 'spinning' }, _('Starting wireless scan...')));
1775
1776                         var md = ui.showModal(_('Join Network: Wireless Scan'), [
1777                                 table,
1778                                 E('div', { 'class': 'right' }, [
1779                                         stop,
1780                                         ' ',
1781                                         E('button', {
1782                                                 'class': 'btn',
1783                                                 'click': L.bind(this.handleScanAbort, this)
1784                                         }, _('Dismiss'))
1785                                 ])
1786                         ]);
1787
1788                         md.style.maxWidth = '90%';
1789                         md.style.maxHeight = 'none';
1790
1791                         this.pollFn = L.bind(this.handleScanRefresh, this, radioDev, {}, table, stop);
1792
1793                         L.Poll.add(this.pollFn);
1794                         L.Poll.start();
1795                 };
1796
1797                 s.handleScanRefresh = function(radioDev, scanCache, table, stop) {
1798                         return radioDev.getScanList().then(L.bind(function(results) {
1799                                 var rows = [];
1800
1801                                 for (var i = 0; i < results.length; i++)
1802                                         scanCache[results[i].bssid] = results[i];
1803
1804                                 for (var k in scanCache)
1805                                         if (scanCache[k].stale)
1806                                                 results.push(scanCache[k]);
1807
1808                                 results.sort(function(a, b) {
1809                                         var diff = (b.quality - a.quality) || (a.channel - b.channel);
1810
1811                                         if (diff)
1812                                                 return diff;
1813
1814                                         if (a.ssid < b.ssid)
1815                                                 return -1;
1816                                         else if (a.ssid > b.ssid)
1817                                                 return 1;
1818
1819                                         if (a.bssid < b.bssid)
1820                                                 return -1;
1821                                         else if (a.bssid > b.bssid)
1822                                                 return 1;
1823                                 });
1824
1825                                 for (var i = 0; i < results.length; i++) {
1826                                         var res = results[i],
1827                                             qv = res.quality || 0,
1828                                             qm = res.quality_max || 0,
1829                                             q = (qv > 0 && qm > 0) ? Math.floor((100 / qm) * qv) : 0,
1830                                             s = res.stale ? 'opacity:0.5' : '';
1831
1832                                         rows.push([
1833                                                 E('span', { 'style': s }, render_signal_badge(q, res.signal, res.noise)),
1834                                                 E('span', { 'style': s }, (res.ssid != null) ? '%h'.format(res.ssid) : E('em', _('hidden'))),
1835                                                 E('span', { 'style': s }, '%d'.format(res.channel)),
1836                                                 E('span', { 'style': s }, '%h'.format(res.mode)),
1837                                                 E('span', { 'style': s }, '%h'.format(res.bssid)),
1838                                                 E('span', { 'style': s }, '%h'.format(network.formatWifiEncryption(res.encryption))),
1839                                                 E('div', { 'class': 'right' }, E('button', {
1840                                                         'class': 'cbi-button cbi-button-action important',
1841                                                         'click': L.bind(this.handleJoin, this, radioDev, res)
1842                                                 }, _('Join Network')))
1843                                         ]);
1844
1845                                         res.stale = true;
1846                                 }
1847
1848                                 cbi_update_table(table, rows);
1849
1850                                 stop.disabled = false;
1851                                 stop.style.display = '';
1852                                 stop.classList.remove('spinning');
1853                         }, this));
1854                 };
1855
1856                 s.handleScanStartStop = function(ev) {
1857                         var btn = ev.currentTarget;
1858
1859                         if (btn.getAttribute('data-state') == 'stop') {
1860                                 L.Poll.remove(this.pollFn);
1861                                 btn.firstChild.data = _('Start refresh');
1862                                 btn.setAttribute('data-state', 'start');
1863                         }
1864                         else {
1865                                 L.Poll.add(this.pollFn);
1866                                 btn.firstChild.data = _('Stop refresh');
1867                                 btn.setAttribute('data-state', 'stop');
1868                                 btn.classList.add('spinning');
1869                                 btn.disabled = true;
1870                         }
1871                 };
1872
1873                 s.handleScanAbort = function(ev) {
1874                         var md = L.dom.parent(ev.target, 'div[aria-modal="true"]');
1875                         if (md) {
1876                                 md.style.maxWidth = '';
1877                                 md.style.maxHeight = '';
1878                         }
1879
1880                         ui.hideModal();
1881                         L.Poll.remove(this.pollFn);
1882
1883                         this.pollFn = null;
1884                 };
1885
1886                 s.handleJoinConfirm = function(radioDev, bss, form, ev) {
1887                         var nameopt = L.toArray(form.lookupOption('name', '_new_'))[0],
1888                             passopt = L.toArray(form.lookupOption('password', '_new_'))[0],
1889                             bssidopt = L.toArray(form.lookupOption('bssid', '_new_'))[0],
1890                             zoneopt = L.toArray(form.lookupOption('zone', '_new_'))[0],
1891                             replopt = L.toArray(form.lookupOption('replace', '_new_'))[0],
1892                             nameval = (nameopt && nameopt.isValid('_new_')) ? nameopt.formvalue('_new_') : null,
1893                             passval = (passopt && passopt.isValid('_new_')) ? passopt.formvalue('_new_') : null,
1894                             bssidval = (bssidopt && bssidopt.isValid('_new_')) ? bssidopt.formvalue('_new_') : null,
1895                             zoneval = zoneopt ? zoneopt.formvalue('_new_') : null,
1896                             enc = L.isObject(bss.encryption) ? bss.encryption : null,
1897                             is_wep = (enc && Array.isArray(enc.wep)),
1898                             is_psk = (enc && Array.isArray(enc.wpa) && L.toArray(enc.authentication).filter(function(a) { return a == 'psk' })),
1899                             is_sae = (enc && Array.isArray(enc.wpa) && L.toArray(enc.authentication).filter(function(a) { return a == 'sae' }));
1900
1901                         if (nameval == null || (passopt && passval == null))
1902                                 return;
1903
1904                         var section_id = null;
1905
1906                         return this.map.save(function() {
1907                                 var wifi_sections = uci.sections('wireless', 'wifi-iface');
1908
1909                                 if (replopt.formvalue('_new_') == '1') {
1910                                         for (var i = 0; i < wifi_sections.length; i++)
1911                                                 if (wifi_sections[i].device == radioDev.getName())
1912                                                         uci.remove('wireless', wifi_sections[i]['.name']);
1913                                 }
1914
1915                                 if (uci.get('wireless', radioDev.getName(), 'disabled') == '1') {
1916                                         for (var i = 0; i < wifi_sections.length; i++)
1917                                                 if (wifi_sections[i].device == radioDev.getName())
1918                                                         uci.set('wireless', wifi_sections[i]['.name'], 'disabled', '1');
1919
1920                                         uci.unset('wireless', radioDev.getName(), 'disabled');
1921                                 }
1922
1923                                 section_id = next_free_sid(wifi_sections.length);
1924
1925                                 uci.add('wireless', 'wifi-iface', section_id);
1926                                 uci.set('wireless', section_id, 'device', radioDev.getName());
1927                                 uci.set('wireless', section_id, 'mode', (bss.mode == 'Ad-Hoc') ? 'adhoc' : 'sta');
1928                                 uci.set('wireless', section_id, 'network', nameval);
1929
1930                                 if (bss.ssid != null) {
1931                                         uci.set('wireless', section_id, 'ssid', bss.ssid);
1932
1933                                         if (bssidval == '1')
1934                                                 uci.set('wireless', section_id, 'bssid', bss.bssid);
1935                                 }
1936                                 else if (bss.bssid != null) {
1937                                         uci.set('wireless', section_id, 'bssid', bss.bssid);
1938                                 }
1939
1940                                 if (is_sae) {
1941                                         uci.set('wireless', section_id, 'encryption', 'sae');
1942                                         uci.set('wireless', section_id, 'key', passval);
1943                                 }
1944                                 else if (is_psk) {
1945                                         for (var i = enc.wpa.length - 1; i >= 0; i--) {
1946                                                 if (enc.wpa[i] == 2) {
1947                                                         uci.set('wireless', section_id, 'encryption', 'psk2');
1948                                                         break;
1949                                                 }
1950                                                 else if (enc.wpa[i] == 1) {
1951                                                         uci.set('wireless', section_id, 'encryption', 'psk');
1952                                                         break;
1953                                                 }
1954                                         }
1955
1956                                         uci.set('wireless', section_id, 'key', passval);
1957                                 }
1958                                 else if (is_wep) {
1959                                         uci.set('wireless', section_id, 'encryption', 'wep-open');
1960                                         uci.set('wireless', section_id, 'key', '1');
1961                                         uci.set('wireless', section_id, 'key1', passval);
1962                                 }
1963                                 else {
1964                                         uci.set('wireless', section_id, 'encryption', 'none');
1965                                 }
1966
1967                                 return network.addNetwork(nameval, { proto: 'dhcp' }).then(function(net) {
1968                                         firewall.deleteNetwork(net.getName());
1969
1970                                         var zonePromise = zoneval
1971                                                 ? firewall.getZone(zoneval).then(function(zone) { return zone || firewall.addZone(zoneval) })
1972                                                 : Promise.resolve();
1973
1974                                         return zonePromise.then(function(zone) {
1975                                                 if (zone)
1976                                                         zone.addNetwork(net.getName());
1977                                         });
1978                                 });
1979                         }).then(L.bind(function() {
1980                                 return this.renderMoreOptionsModal(section_id);
1981                         }, this));
1982                 };
1983
1984                 s.handleJoin = function(radioDev, bss, ev) {
1985                         this.handleScanAbort(ev);
1986
1987                         var m2 = new form.Map('wireless'),
1988                             s2 = m2.section(form.NamedSection, '_new_'),
1989                             enc = L.isObject(bss.encryption) ? bss.encryption : null,
1990                             is_wep = (enc && Array.isArray(enc.wep)),
1991                             is_psk = (enc && Array.isArray(enc.wpa) && L.toArray(enc.authentication).filter(function(a) { return a == 'psk' || a == 'sae' })),
1992                             replace, passphrase, name, bssid, zone;
1993
1994                         var nameUsed = function(name) {
1995                                 var s = uci.get('network', name);
1996                                 if (s != null && s['.type'] != 'interface')
1997                                         return true;
1998
1999                                 var net = (s != null) ? network.instantiateNetwork(name) : null;
2000                                 return (net != null && !net.isEmpty());
2001                         };
2002
2003                         s2.render = function() {
2004                                 return Promise.all([
2005                                         {},
2006                                         this.renderUCISection('_new_')
2007                                 ]).then(this.renderContents.bind(this));
2008                         };
2009
2010                         replace = s2.option(form.Flag, 'replace', _('Replace wireless configuration'), _('Check this option to delete the existing networks from this radio.'));
2011
2012                         name = s2.option(form.Value, 'name', _('Name of the new network'), _('The allowed characters are: <code>A-Z</code>, <code>a-z</code>, <code>0-9</code> and <code>_</code>'));
2013                         name.datatype = 'uciname';
2014                         name.default = 'wwan';
2015                         name.rmempty = false;
2016                         name.validate = function(section_id, value) {
2017                                 if (nameUsed(value))
2018                                         return _('The network name is already used');
2019
2020                                 return true;
2021                         };
2022
2023                         for (var i = 2; nameUsed(name.default); i++)
2024                                 name.default = 'wwan%d'.format(i);
2025
2026                         if (is_wep || is_psk) {
2027                                 passphrase = s2.option(form.Value, 'password', is_wep ? _('WEP passphrase') : _('WPA passphrase'), _('Specify the secret encryption key here.'));
2028                                 passphrase.datatype = is_wep ? 'wepkey' : 'wpakey';
2029                                 passphrase.password = true;
2030                                 passphrase.rmempty = false;
2031                         }
2032
2033                         if (bss.ssid != null) {
2034                                 bssid = s2.option(form.Flag, 'bssid', _('Lock to BSSID'), _('Instead of joining any network with a matching SSID, only connect to the BSSID <code>%h</code>.').format(bss.bssid));
2035                                 bssid.default = '0';
2036                         }
2037
2038                         zone = s2.option(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>create</em> field to define a new zone and attach the interface to it.'));
2039                         zone.default = 'wan';
2040
2041                         return m2.render().then(L.bind(function(nodes) {
2042                                 ui.showModal(_('Joining Network: %q').replace(/%q/, '"%h"'.format(bss.ssid)), [
2043                                         nodes,
2044                                         E('div', { 'class': 'right' }, [
2045                                                 E('button', {
2046                                                         'class': 'btn',
2047                                                         'click': ui.hideModal
2048                                                 }, _('Cancel')), ' ',
2049                                                 E('button', {
2050                                                         'class': 'cbi-button cbi-button-positive important',
2051                                                         'click': ui.createHandlerFn(this, 'handleJoinConfirm', radioDev, bss, m2)
2052                                                 }, _('Submit'))
2053                                         ])
2054                                 ], 'cbi-modal').querySelector('[id="%s"] input[class][type]'.format((passphrase || name).cbid('_new_'))).focus();
2055                         }, this));
2056                 };
2057
2058                 s.handleAdd = function(radioDev, ev) {
2059                         var section_id = next_free_sid(uci.sections('wireless', 'wifi-iface').length);
2060
2061                         uci.unset('wireless', radioDev.getName(), 'disabled');
2062
2063                         uci.add('wireless', 'wifi-iface', section_id);
2064                         uci.set('wireless', section_id, 'device', radioDev.getName());
2065                         uci.set('wireless', section_id, 'mode', 'ap');
2066                         uci.set('wireless', section_id, 'ssid', 'OpenWrt');
2067                         uci.set('wireless', section_id, 'encryption', 'none');
2068
2069                         this.addedSection = section_id;
2070                         return this.renderMoreOptionsModal(section_id);
2071                 };
2072
2073                 o = s.option(form.DummyValue, '_badge');
2074                 o.modalonly = false;
2075                 o.textvalue = function(section_id) {
2076                         var inst = this.section.lookupRadioOrNetwork(section_id),
2077                             node = E('div', { 'class': 'center' });
2078
2079                         if (inst.getWifiNetworks)
2080                                 node.appendChild(render_radio_badge(inst));
2081                         else
2082                                 node.appendChild(render_network_badge(inst));
2083
2084                         return node;
2085                 };
2086
2087                 o = s.option(form.DummyValue, '_stat');
2088                 o.modalonly = false;
2089                 o.textvalue = function(section_id) {
2090                         var inst = this.section.lookupRadioOrNetwork(section_id);
2091
2092                         if (inst.getWifiNetworks)
2093                                 return render_radio_status(inst, this.section.wifis.filter(function(e) {
2094                                         return (e.getWifiDeviceName() == inst.getName());
2095                                 }));
2096                         else
2097                                 return render_network_status(inst);
2098                 };
2099
2100                 return m.render().then(L.bind(function(m, nodes) {
2101                         L.Poll.add(L.bind(function() {
2102                                 var section_ids = m.children[0].cfgsections(),
2103                                     tasks = [ network.getHostHints(), network.getWifiDevices() ];
2104
2105                                 for (var i = 0; i < section_ids.length; i++) {
2106                                         var row = nodes.querySelector('.cbi-section-table-row[data-sid="%s"]'.format(section_ids[i])),
2107                                             dsc = row.querySelector('[data-name="_stat"] > div'),
2108                                             btns = row.querySelectorAll('.cbi-section-actions button');
2109
2110                                         if (dsc.getAttribute('restart') == '') {
2111                                                 dsc.setAttribute('restart', '1');
2112                                                 tasks.push(fs.exec('/sbin/wifi', ['up', section_ids[i]]).catch(function(e) {
2113                                                         ui.addNotification(null, E('p', e.message));
2114                                                 }));
2115                                         }
2116                                         else if (dsc.getAttribute('restart') == '1') {
2117                                                 dsc.removeAttribute('restart');
2118                                                 btns[0].classList.remove('spinning');
2119                                                 btns[0].disabled = false;
2120                                         }
2121                                 }
2122
2123                                 return Promise.all(tasks)
2124                                         .then(L.bind(function(hosts_radios) {
2125                                                 var tasks = [];
2126
2127                                                 for (var i = 0; i < hosts_radios[1].length; i++)
2128                                                         tasks.push(hosts_radios[1][i].getWifiNetworks());
2129
2130                                                 return Promise.all(tasks).then(function(data) {
2131                                                         hosts_radios[2] = [];
2132
2133                                                         for (var i = 0; i < data.length; i++)
2134                                                                 hosts_radios[2].push.apply(hosts_radios[2], data[i]);
2135
2136                                                         return hosts_radios;
2137                                                 });
2138                                         }, network))
2139                                         .then(L.bind(function(hosts_radios_wifis) {
2140                                                 var tasks = [];
2141
2142                                                 for (var i = 0; i < hosts_radios_wifis[2].length; i++)
2143                                                         tasks.push(hosts_radios_wifis[2][i].getAssocList());
2144
2145                                                 return Promise.all(tasks).then(function(data) {
2146                                                         hosts_radios_wifis[3] = [];
2147
2148                                                         for (var i = 0; i < data.length; i++) {
2149                                                                 var wifiNetwork = hosts_radios_wifis[2][i],
2150                                                                     radioDev = hosts_radios_wifis[1].filter(function(d) { return d.getName() == wifiNetwork.getWifiDeviceName() })[0];
2151
2152                                                                 for (var j = 0; j < data[i].length; j++)
2153                                                                         hosts_radios_wifis[3].push(Object.assign({ radio: radioDev, network: wifiNetwork }, data[i][j]));
2154                                                         }
2155
2156                                                         return hosts_radios_wifis;
2157                                                 });
2158                                         }, network))
2159                                         .then(L.bind(this.poll_status, this, nodes));
2160                         }, this), 5);
2161
2162                         var table = E('div', { 'class': 'table assoclist', 'id': 'wifi_assoclist_table' }, [
2163                                 E('div', { 'class': 'tr table-titles' }, [
2164                                         E('div', { 'class': 'th nowrap' }, _('Network')),
2165                                         E('div', { 'class': 'th hide-xs' }, _('MAC-Address')),
2166                                         E('div', { 'class': 'th' }, _('Host')),
2167                                         E('div', { 'class': 'th nowrap' }, _('Signal / Noise')),
2168                                         E('div', { 'class': 'th nowrap' }, _('RX Rate / TX Rate'))
2169                                 ])
2170                         ]);
2171
2172                         cbi_update_table(table, [], E('em', { 'class': 'spinning' }, _('Collecting data...')))
2173
2174                         return E([ nodes, E('h3', _('Associated Stations')), table ]);
2175                 }, this, m));
2176         }
2177 });