Correct PPTP server firewall rules chain.
[tomato/davidwu.git] / release / src / router / www / tomato.js
blobfc683cb0c2c9156eaa4f9347715dc5225b757186
1 /*
2         Tomato GUI
3         Copyright (C) 2006-2010 Jonathan Zarate
4         http://www.polarcloud.com/tomato/
6         For use with Tomato Firmware only.
7         No part of this file may be used without permission.
8 */
10 // -----------------------------------------------------------------------------
12 Array.prototype.find = function(v) {
13         for (var i = 0; i < this.length; ++i)
14                 if (this[i] == v) return i;
15         return -1;
18 Array.prototype.remove = function(v) {
19         for (var i = 0; i < this.length; ++i) {
20                 if (this[i] == v) {
21                         this.splice(i, 1);
22                         return true;
23                 }
24         }
25         return false;
28 // -----------------------------------------------------------------------------
30 String.prototype.trim = function() {
31         return this.replace(/^\s+/, '').replace(/\s+$/, '');
34 // -----------------------------------------------------------------------------
36 Number.prototype.pad = function(min) {
37         var s = this.toString();
38         while (s.length < min) s = '0' + s;
39         return s;
42 Number.prototype.hex = function(min)
44         var h = '0123456789ABCDEF';
45         var n = this;
46         var s = '';
47         do {
48                 s = h.charAt(n & 15) + s;
49                 n = n >>> 4;
50         } while ((--min > 0) || (n > 0));
51         return s;
54 // -----------------------------------------------------------------------------
56 // ---- Element.protoype. doesn't work with all browsers
58 var elem = {
59         getOffset: function(e) {
60                 var r = { x: 0, y: 0 };
61                 e = E(e);
62                 while (e.offsetParent) {
63                         r.x += e.offsetLeft;
64                         r.y += e.offsetTop;
65                         e = e.offsetParent;
66                 }
67                 return r;
68         },
70         addClass: function(e, name) {
71                 if ((e = E(e)) == null) return;
72                 var a = e.className.split(/\s+/);
73                 var k = 0;
74                 for (var i = 1; i < arguments.length; ++i) {
75                         if (a.find(arguments[i]) == -1) {
76                                 a.push(arguments[i]);
77                                 k = 1;
78                         }
79                 }
80                 if (k) e.className = a.join(' ');
81         },
83         removeClass: function(e, name) {
84                 if ((e = E(e)) == null) return;
85                 var a = e.className.split(/\s+/);
86                 var k = 0;
87                 for (var i = 1; i < arguments.length; ++i)
88                         k |= a.remove(arguments[i]);
89                 if (k) e.className = a.join(' ');
90         },
92         remove: function(e) {
93                  if ((e = E(e)) != null) e.parentNode.removeChild(e);
94         },
96     parentElem: function(e, tagName) {
97                 e = E(e);
98                 tagName = tagName.toUpperCase();
99                 while (e.parentNode) {
100                         e = e.parentNode;
101                         if (e.tagName == tagName) return e;
102                 }
103                 return null;
104         },
106         display: function() {
107                 var enable = arguments[arguments.length - 1];
108                 for (var i = 0; i < arguments.length - 1; ++i) {
109                         E(arguments[i]).style.display = enable ? '' : 'none';
110                 }
111         },
113         isVisible: function(e) {
114                 e = E(e);
115                 while (e) {
116                         if ((e.style.visibility != 'visible') || (e.style.display == 'none')) return false;
117                         e = e.parentNode;
118                 }
119                 return true;
120         },
122         setInnerHTML: function(e, html) {
123                  e = E(e);
124                  if (e.innerHTML != html) e.innerHTML = html;   // reduce flickering
125         }
128 // -----------------------------------------------------------------------------
130 var docu = {
131         getViewSize: function() {
132                 if (window.innerHeight) {
133                         return { width: window.innerWidth, height: window.innerHeight };
134                 }
135                 else if (document.documentElement && document.documentElement.clientHeight) {
136                         return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight };
137                 }
138                 return { width: document.body.clientWidth, height: document.body.clientHeight };
139         },
141         getPageOffset: function()
142         {
143                 if (typeof(window.pageYOffset) != 'undefined') {
144                         return { x: window.pageXOffset, y: window.pageYOffset };
145                 }
146                 else if ((document.documentElement) && (typeof(document.documentElement.scrollTop) != 'undefined')) {
147                         return { x: document.documentElement.scrollLeft, y: document.documentElement.scrollTop };
148                 }
149                 return { x: document.body.scrollLeft, y: document.body.scrollTop };
150         }
153 // -----------------------------------------------------------------------------
155 var fields = {
156         getAll: function(e) {
157                 var a = [];
158                 switch (e.tagName) {
159                 case 'INPUT':
160                 case 'SELECT':
161                         a.push(e);
162                         break;
163                 default:
164                         if (e.childNodes) {
165                                 for (var i = 0; i < e.childNodes.length; ++i) {
166                                         a = a.concat(fields.getAll(e.childNodes[i]));
167                                 }
168                         }
169                 }
170                 return a;
171         },
172         disableAll: function(e, d) {
173                 var i;
175                 if ((typeof(e.tagName) == 'undefined') && (typeof(e) != 'string')) {
176                         for (i = e.length - 1; i >= 0; --i) {
177                                 e[i].disabled = d;
178                         }
179                 }
180                 else {
181                         var a = this.getAll(E(e));
182                         for (var i = a.length - 1; i >= 0; --i) {
183                                 a[i].disabled = d;
184                         }
185                 }
186         },
187         radio: {
188                 selected: function(e) {
189                         for (var i = 0; i < e.length; ++i) {
190                                 if (e[i].checked) return e[i];
191                         }
192                         return null;
193                 },
194                 find: function(e, value) {
195                         for (var i = 0; i < e.length; ++i) {
196                                 if (e[i].value == value) return e[i];
197                         }
198                         return null;
199                 }
200         }
203 // -----------------------------------------------------------------------------
205 var form = {
206         submitHidden: function(url, fields) {
207                 var fom, body;
209                 fom = document.createElement('FORM');
210                 fom.action = url;
211                 fom.method = 'post';
212                 for (var f in fields) {
213                         var e = document.createElement('INPUT');
214                         e.type = 'hidden';
215                         e.name = f;
216                         e.value = fields[f];
217                         fom.appendChild(e);
218                 }
219                 body = document.getElementsByTagName('body')[0];
220                 fom = body.appendChild(fom);
221                 this.submit(fom);
222                 body.removeChild(fom);
223         },
225         submit: function(fom, async, url) {
226                 var e, v, f, i, wait, msg, sb, cb;
228                 fom = E(fom);
230                 if (isLocal()) {
231                         this.dump(fom, async, url);
232                         return;
233                 }
235                 if (this.xhttp) return;
237                 if ((sb = E('save-button')) != null) sb.disabled = 1;
238                 if ((cb = E('cancel-button')) != null) cb.disabled = 1;
240                 if ((!async) || (!useAjax())) {
241                         this.addId(fom);
242                         if (url) fom.action = url;
243                         fom.submit();
244                         return;
245                 }
247                 v = ['_ajax=1'];
248                 wait = 5;
249                 for (var i = 0; i < fom.elements.length; ++i) {
250                         f = fom.elements[i];
251                         if ((f.disabled) || (f.name == '') || (f.name.substr(0, 2) == 'f_')) continue;
252                         if ((f.tagName == 'INPUT') && ((f.type == 'CHECKBOX') || (f.type == 'RADIO')) && (!f.checked)) continue;
253                         if (f.name == '_nextwait') {
254                                 wait = f.value * 1;
255                                 if (isNaN(wait)) wait = 5;
256                                         else wait = Math.abs(wait);
257                         }
258                         v.push(escapeCGI(f.name) + '=' + escapeCGI(f.value));
259                 }
261                 if ((msg = E('footer-msg')) != null) {
262                         msg.innerHTML = 'Saving...';
263                         msg.style.visibility = 'visible';
264                 }
266                 this.xhttp = new XmlHttp();
267                 this.xhttp.onCompleted = function(text, xml) {
268                         if (msg) {
269                                 if (text.match(/@msg:(.+)/)) msg.innerHTML = escapeHTML(RegExp.$1);
270                                         else msg.innerHTML = 'Saved';
271                         }
272                         setTimeout(
273                                 function() {
274                                         if (sb) sb.disabled = 0;
275                                         if (cb) cb.disabled = 0;
276                                         if (msg) msg.style.visibility = 'hidden';
277                                         if (typeof(submit_complete) != 'undefined') submit_complete();
278                                 }, wait * 1100);
279                         form.xhttp = null;
280                 }
281                 this.xhttp.onError = function(x) {
282                         if (url) fom.action = url;
283                         fom.submit();
284                 }
286                 this.xhttp.post(url ? url : fom.action, v.join('&'));
287         },
289         addId: function(fom) {
290                 var e;
292                 if (typeof(fom._http_id) == 'undefined') {
293                         e = document.createElement('INPUT');
294                         e.type = 'hidden';
295                         e.name = '_http_id';
296                         e.value = nvram.http_id;
297                         fom.appendChild(e);
298                 }
299                 else {
300                         fom._http_id.value = nvram.http_id;
301                 }
302         },
304         addIdAction: function(fom) {
305                 if (fom.action.indexOf('?') != -1) fom.action += '&_http_id=' + nvram.http_id;
306                         else fom.action += '?_http_id=' + nvram.http_id;
307         },
309         dump: function(fom, async, url) {
310         }
313 // -----------------------------------------------------------------------------
315 var ferror = {
316         set: function(e, message, quiet) {
317                 if ((e = E(e)) == null) return;
318                 e._error_msg = message;
319                 e._error_org = e.title;
320                 e.title = message;
321                 elem.addClass(e, 'error');
322                 if (!quiet) this.show(e);
323         },
325         clear: function(e) {
326                 if ((e = E(e)) == null) return;
327                 e.title = e._error_org || '';
328                 elem.removeClass(e, 'error');
329                 e._error_msg = null;
330                 e._error_org = null;
331         },
333         clearAll: function(e) {
334                 for (var i = 0; i < e.length; ++i)
335                         this.clear(e[i]);
336         },
338         show: function(e) {
339                 if ((e = E(e)) == null) return;
340                 if (!e._error_msg) return;
341                 elem.addClass(e, 'error-focused');
342                 e.focus();
343                 alert(e._error_msg);
344                 elem.removeClass(e, 'error-focused');
345         },
347         ok: function(e) {
348                 if ((e = E(e)) == null) return 0;
349         return !e._error_msg;
350         }
353 // -----------------------------------------------------------------------------
355 function fixFile(name)
357         var i;
358         if (((i = name.lastIndexOf('/')) > 0) || ((i = name.lastIndexOf('\\')) > 0))
359                 name = name.substring(i + 1, name.length);
360         return name;
363 function _v_range(e, quiet, min, max, name)
365         if ((e = E(e)) == null) return 0;
366         var v = e.value;
367         if ((!v.match(/^ *[-\+]?\d+ *$/)) || (v < min) || (v > max)) {
368                 ferror.set(e, 'Invalid ' + name + '. Valid range: ' + min + '-' + max, quiet);
369                 return 0;
370         }
371         e.value = v * 1;
372         ferror.clear(e);
373         return 1;
376 function v_range(e, quiet, min, max)
378         return _v_range(e, quiet, min, max, 'number');
381 function v_port(e, quiet)
383         return _v_range(e, quiet, 1, 0xFFFF, 'port');
386 function v_octet(e, quiet)
388         return _v_range(e, quiet, 1, 254, 'address');
391 function v_mins(e, quiet, min, max)
393         var v, m;
395         if ((e = E(e)) == null) return 0;
396         if (e.value.match(/^\s*(.+?)([mhd])?\s*$/)) {
397                 m = 1;
398                 if (RegExp.$2 == 'h') m = 60;
399                         else if (RegExp.$2 == 'd') m = 60 * 24;
400                 v = Math.round(RegExp.$1 * m);
401                 if (!isNaN(v)) {
402                         e.value = v;
403                         return _v_range(e, quiet, min, max, 'minutes');
404                 }
405         }
406         ferror.set(e, 'Invalid number of minutes.', quiet);
407         return 0;
410 function v_macip(e, quiet, bok, lan_ipaddr, lan_netmask)
412         var s, a, b, c, d, i;
413         var ipp, temp;
415         temp = lan_ipaddr.split('.');
416         ipp = temp[0]+'.'+temp[1]+'.'+temp[2]+'.';
418         if ((e = E(e)) == null) return 0;
419         s = e.value.replace(/\s+/g, '');
421         if ((a = fixMAC(s)) != null) {
422                 if (isMAC0(a)) {
423                         if (bok) {
424                                 e.value = '';
425                         }
426                         else {
427                                 ferror.set(e, 'Invalid MAC or IP address');
428                                 return false;
429                         }
430                 }
431                 else e.value = a;
432                 ferror.clear(e);
433                 return true;
434         }
436         a = s.split('-');
437     
438         if (a.length > 2) {
439                 ferror.set(e, 'Invalid IP address range', quiet);
440                 return false;
441         }
442         
443         if (a[0].match(/^\d+$/)){
444                 a[0]=ipp+a[0];
445                 if ((a.length == 2) && (a[1].match(/^\d+$/)))
446                         a[1]=ipp+a[1];
447         }
448         else{
449                 if ((a.length == 2) && (a[1].match(/^\d+$/))){
450                         temp=a[0].split('.');
451                         a[1]=temp[0]+'.'+temp[1]+'.'+temp[2]+'.'+a[1];
452                 }
453         }
454         for (i = 0; i < a.length; ++i) {
455                 b = a[i];    
456                 b = fixIP(b);
457                 if (!b) {
458                         ferror.set(e, 'Invalid IP address', quiet);
459                         return false;
460                 }
462                 if ((aton(b) & aton(lan_netmask))!=(aton(lan_ipaddr) & aton(lan_netmask))) {
463                         ferror.set(e, 'IP address outside of LAN', quiet);
464                         return false;
465                 }
467                 d = (b.split('.'))[3];
468                 if (parseInt(d) <= parseInt(c)) {
469                         ferror.set(e, 'Invalid IP address range', quiet);
470                         return false;
471                 }
473                 a[i] = c = d;
474         }
475         e.value = b.split('.')[0] + '.' + b.split('.')[1] + '.' + b.split('.')[2] + '.' + a.join('-');
476         return true;
479 function fixIP(ip, x)
481         var a, n, i;
482         a = ip;
483         i = a.indexOf("<br>");
484         if (i > 0)
485                 a = a.slice(0,i);
487         a = a.split('.');
488         if (a.length != 4) return null;
489         for (i = 0; i < 4; ++i) {
490                 n = a[i] * 1;
491                 if ((isNaN(n)) || (n < 0) || (n > 255)) return null;
492                 a[i] = n;
493         }
494         if ((x) && ((a[3] == 0) || (a[3] == 255))) return null;
495         return a.join('.');
498 function v_ip(e, quiet, x)
500         var ip;
502         if ((e = E(e)) == null) return 0;
503         ip = fixIP(e.value, x);
504         if (!ip) {
505                 ferror.set(e, 'Invalid IP address', quiet);
506                 return false;
507         }
508         e.value = ip;
509         ferror.clear(e);
510         return true;
513 function v_ipz(e, quiet)
515         if ((e = E(e)) == null) return 0;
516         if (e.value == '') e.value = '0.0.0.0';
517         return v_ip(e, quiet);
520 function v_dns(e, quiet)
522         if ((e = E(e)) == null) return 0;       
523         if (e.value == '') {
524                 e.value = '0.0.0.0';
525         }
526         else {
527                 var s = e.value.split(':');
528                 if (s.length == 1) {
529                         s.push(53);
530                 }
531                 else if (s.length != 2) {
532                         ferror.set(e, 'Invalid IP address or port', quiet);
533                         return false;
534                 }
535                 
536                 if ((s[0] = fixIP(s[0])) == null) {
537                         ferror.set(e, 'Invalid IP address', quiet);
538                         return false;
539                 }
541                 if ((s[1] = fixPort(s[1], -1)) == -1) {
542                         ferror.set(e, 'Invalid port', quiet);
543                         return false;
544                 }
545         
546                 if (s[1] == 53) {
547                         e.value = s[0];
548                 }
549                 else {
550                         e.value = s.join(':');
551                 }
552         }
554         ferror.clear(e);
555         return true;
558 function aton(ip)
560         var o, x, i;
562         // ---- this is goofy because << mangles numbers as signed
563         o = ip.split('.');
564         x = '';
565         for (i = 0; i < 4; ++i) x += (o[i] * 1).hex(2);
566         return parseInt(x, 16);
569 function ntoa(ip)
571         return ((ip >> 24) & 255) + '.' + ((ip >> 16) & 255) + '.' + ((ip >> 8) & 255) + '.' + (ip & 255);
575 // ---- 1.2.3.4, 1.2.3.4/24, 1.2.3.4/255.255.255.0, 1.2.3.4-1.2.3.5
576 function _v_iptip(e, ip, quiet)
578         var ma, x, y, z, oip;
579         var a, b;
581         oip = ip;
583         // x.x.x.x - y.y.y.y
584         if (ip.match(/^(.*)-(.*)$/)) {
585                 a = fixIP(RegExp.$1);
586                 b = fixIP(RegExp.$2);
587                 if ((a == null) || (b == null)) {
588                         ferror.set(e, oip + ' - invalid IP address range', quiet);
589                         return null;
590                 }
591                 ferror.clear(e);
593                 if (aton(a) > aton(b)) return b + '-' + a;
594                 return a + '-' + b;
595         }
597         ma = '';
599         // x.x.x.x/nn
600         // x.x.x.x/y.y.y.y
601         if (ip.match(/^(.*)\/(.*)$/)) {
602                 ip = RegExp.$1;
603                 b = RegExp.$2;
605                 ma = b * 1;
606                 if (isNaN(ma)) {
607                         ma = fixIP(b);
608                         if ((ma == null) || (!_v_netmask(ma))) {
609                                 ferror.set(e, oip + ' - invalid netmask', quiet);
610                                 return null;
611                         }
612                 }
613                 else {
614                         if ((ma < 0) || (ma > 32)) {
615                                 ferror.set(e, oip + ' - invalid netmask', quiet);
616                                 return null;
617                         }
618                 }
619         }
621         ip = fixIP(ip);
622         if (!ip) {
623                 ferror.set(e, oip + ' - invalid IP address', quiet);
624                 return null;
625         }
627         ferror.clear(e);
628         return ip + ((ma != '') ? ('/' + ma) : '');
631 function v_iptip(e, quiet, multi)
633         var v, i;
635         if ((e = E(e)) == null) return 0;
636         v = e.value.split(',');
637         if (multi) {
638                 if (v.length > multi) {
639                         ferror.set(e, 'Too many IP addresses', quiet);
640                         return 0;
641                 }
642         }
643         else {
644                 if (v.length > 1) {
645                         ferror.set(e, 'Invalid IP address', quiet);
646                         return 0;
647                 }
648         }
649         for (i = 0; i < v.length; ++i) {
650                 if ((v[i] = _v_iptip(e, v[i], quiet)) == null) return 0;
651         }
652         e.value = v.join(', ');
653         return 1;
656 function _v_subnet(e, ip, quiet)
658         var ma, oip;
659         oip = ip;
661         // x.x.x.x/nn
662         if (ip.match(/^(.*)\/(.*)$/)) {
663                 ip = RegExp.$1;
664                 ma = RegExp.$2;
666                 if ((ma < 0) || (ma > 32)) {
667                         ferror.set(e, oip + ' - invalid subnet', quiet);
668                         return null;
669                 }
670         }
671         else {
672                 ferror.set(e, oip + ' - invalid subnet', quiet);
673                 return null;
674         }
676         ferror.clear(e);
677         return ip + ((ma != '') ? ('/' + ma) : '');
680 function v_subnet(e, quiet)
682         if ((_v_subnet(e, e.value, quiet)) == null) return 0;
684         return 1;
687 function _v_domain(e, dom, quiet)
689         var s;
691         s = dom.replace(/\s+/g, ' ').trim();
692         if (s.length > 0) {
693                 s = _v_hostname(e, s, 1, 1, 7, '.', true);
694                 if (s == null) {
695                         ferror.set(e, "Invalid name. Only characters \"A-Z 0-9 . -\" are allowed.", quiet);
696                         return null;
697                 }
698         }
699         ferror.clear(e);
700         return s;
703 function v_domain(e, quiet)
705         var v;
707         if ((e = E(e)) == null) return 0;
708         if ((v = _v_domain(e, e.value, quiet)) == null) return 0;
710         e.value = v;
711         return 1;
714 /* IPV6-BEGIN */
715 function ExpandIPv6Address(ip)
717         var a, pre, n, i, fill, post;
719         ip = ip.toLowerCase();
720         if (!ip.match(/^(::)?([a-f0-9]{1,4}::?){0,7}([a-f0-9]{1,4})(::)?$/)) return null;
722         a = ip.split('::');
723         switch (a.length) {
724         case 1:
725                 if (a[0] == '') return null;
726                 pre = a[0].split(':');
727                 if (pre.length != 8) return null;
728                 ip = pre.join(':');
729                 break;
730         case 2:
731                 pre = a[0].split(':');
732                 post = a[1].split(':');
733                 n = 8 - pre.length - post.length;
734                 for (i=0; i<2; i++) {
735                         if (a[i]=='') n++;
736                 }
737                 if (n < 0) return null;
738                 fill = '';
739                 while (n-- > 0) fill += ':0';
740                 ip = pre.join(':') + fill + ':' + post.join(':');
741                 ip = ip.replace(/^:/, '').replace(/:$/, '');
742                 break;
743         default:
744                 return null;
745         }
746         
747         ip = ip.replace(/([a-f0-9]{1,4})/ig, '000$1');
748         ip = ip.replace(/0{0,3}([a-f0-9]{4})/ig, '$1');
749         return ip;
752 function CompressIPv6Address(ip)
754         var a, segments;
755         
756         ip = ExpandIPv6Address(ip);
757         if (!ip) return null;
758         
759         // if (ip.match(/(?:^00)|(?:^fe[8-9a-b])|(?:^ff)/)) return null; // not valid routable unicast address
761         ip = ip.replace(/(^|:)0{1,3}/g, '$1');
762         ip = ip.replace(/(:0)+$/, '::');
763         ip = ip.replace(/(?:(?:^|:)0){2,}(?!.*(?:::|(?::0){3,}))/, ':');
764         return ip;
767 function ZeroIPv6PrefixBits(ip, prefix_length)
769         var b, c, m, n;
770         ip = ExpandIPv6Address(ip);
771         ip = ip.replace(/:/g,'');
772         n = Math.floor(prefix_length/4);
773         m = 32 - Math.ceil(prefix_length/4);
774         b = prefix_length % 4;
775         if (b != 0) 
776                 c = (parseInt(ip.charAt(n), 16) & (0xf << 4-b)).toString(16);
777         else
778                 c = '';
779         
780         ip = ip.substring(0, n) + c + Array((m%4)+1).join('0') + (m>=4 ? '::' : '');
781         ip = ip.replace(/([a-f0-9]{4})(?=[a-f0-9])/g,'$1:');
782         ip = ip.replace(/(^|:)0{1,3}/g, '$1');
783         return ip;
786 function ipv6ton(ip)
788         var o, x, i;
790         ip = ExpandIPv6Address(ip);
791         if (!ip) return 0;
793         o = ip.split(':');
794         x = '';
795         for (i = 0; i < 8; ++i) x += (('0x' + o[i]) * 1).hex(4);
796         return parseInt(x, 16);
799 function _v_ipv6_addr(e, ip, ipt, quiet)
801         var oip;
802         var a, b;
804         oip = ip;
806         // ip range
807         if ((ipt) && ip.match(/^(.*)-(.*)$/)) {
808                 a = RegExp.$1;
809                 b = RegExp.$2;
810                 a = CompressIPv6Address(a);
811                 b = CompressIPv6Address(b);
812                 if ((a == null) || (b == null)) {
813                         ferror.set(e, oip + ' - invalid IPv6 address range', quiet);
814                         return null;
815                 }
816                 ferror.clear(e);
818                 if (ipv6ton(a) > ipv6ton(b)) return b + '-' + a;
819                 return a + '-' + b;
820         }
821         
822         if ((ipt) && ip.match(/^([A-Fa-f0-9:]+)\/(\d+)$/)) {
823                 a = RegExp.$1;
824                 b = parseInt(RegExp.$2, 10);
825                 a = ExpandIPv6Address(a);
826                 if ((a == null) || (b == null)) {
827                         ferror.set(e, oip + ' - invalid IPv6 address', quiet);
828                         return null;
829                 }
830                 if (b < 0 || b > 128) {
831                         ferror.set(e, oip + ' - invalid CIDR notation on IPv6 address', quiet);
832                         return null;
833                 }
834                 ferror.clear(e);
836                 ip = ZeroIPv6PrefixBits(a, b);
837                 return ip + '/' + b.toString(10);
838         }
840         ip = CompressIPv6Address(oip);
841         if (!ip) {
842                 ferror.set(e, oip + ' - invalid IPv6 address', quiet);
843                 return null;
844         }
846         ferror.clear(e);
847         return ip;
850 function v_ipv6_addr(e, quiet)
852         if ((e = E(e)) == null) return 0;
854         ip = _v_ipv6_addr(e, e.value, false, quiet);
855         if (ip) e.value = ip;
856         return (ip != null);
858 /* IPV6-END */
860 function fixPort(p, def)
862         if (def == null) def = -1;
863         if (p == null) return def;
864         p *= 1;
865         if ((isNaN(p) || (p < 1) || (p > 65535) || (('' + p).indexOf('.') != -1))) return def;
866         return p;
869 function _v_portrange(e, quiet, v)
871         if (v.match(/^(.*)[-:](.*)$/)) {
872                 var x = RegExp.$1;
873                 var y = RegExp.$2;
875                 x = fixPort(x, -1);
876                 y = fixPort(y, -1);
877                 if ((x == -1) || (y == -1)) {
878                         ferror.set(e, 'Invalid port range: ' + v, quiet);
879                         return null;
880                 }
881                 if (x > y) {
882                         v = x;
883                         x = y;
884                         y = v;
885                 }
886                 ferror.clear(e);
887                 if (x == y) return x;
888                 return x + '-' + y;
889         }
891         v = fixPort(v, -1);
892         if (v == -1) {
893                 ferror.set(e, 'Invalid port', quiet);
894                 return null;
895         }
897         ferror.clear(e);
898         return v;
901 function v_portrange(e, quiet)
903         var v;
905         if ((e = E(e)) == null) return 0;
906         v = _v_portrange(e, quiet, e.value);
907         if (v == null) return 0;
908         e.value = v;
909         return 1;
912 function v_iptport(e, quiet)
914         var a, i, v, q;
916         if ((e = E(e)) == null) return 0;
918         a = e.value.split(/[,\.]/);
920         if (a.length == 0) {
921                 ferror.set(e, 'Expecting a list of ports or port range.', quiet);
922                 return 0;
923         }
924         if (a.length > 10) {
925                 ferror.set(e, 'Only 10 ports/range sets are allowed.', quiet);
926                 return 0;
927         }
929         q = [];
930         for (i = 0; i < a.length; ++i) {
931                 v = _v_portrange(e, quiet, a[i]);
932                 if (v == null) return 0;
933                 q.push(v);
934         }
936         e.value = q.join(',');
937         ferror.clear(e);
938         return 1;
941 function _v_netmask(mask)
943         var v = aton(mask) ^ 0xFFFFFFFF;
944         return (((v + 1) & v) == 0);
947 function v_netmask(e, quiet)
949         var n, b;
951         if ((e = E(e)) == null) return 0;
952         n = fixIP(e.value);
953         if (n) {
954                 if (_v_netmask(n)) {
955                         e.value = n;
956                         ferror.clear(e);
957                         return 1;
958                 }
959         }
960         else if (e.value.match(/^\s*\/\s*(\d+)\s*$/)) {
961                 b = RegExp.$1 * 1;
962                 if ((b >= 1) && (b <= 32)) {
963                         if (b == 32) n = 0xFFFFFFFF;    // js quirk
964                                 else n = (0xFFFFFFFF >>> b) ^ 0xFFFFFFFF;
965                         e.value = (n >>> 24) + '.' + ((n >>> 16) & 0xFF) + '.' + ((n >>> 8) & 0xFF) + '.' + (n & 0xFF);
966                         ferror.clear(e);
967                         return 1;
968                 }
969         }
970         ferror.set(e, 'Invalid netmask', quiet);
971         return 0;
974 function fixMAC(mac)
976         var t, i;
978         mac = mac.replace(/\s+/g, '').toUpperCase();
979         if (mac.length == 0) {
980                 mac = [0,0,0,0,0,0];
981         }
982         else if (mac.length == 12) {
983                 mac = mac.match(/../g);
984         }
985         else {
986                 mac = mac.split(/[:\-]/);
987                 if (mac.length != 6) return null;
988         }
989         for (i = 0; i < 6; ++i) {
990                 t = '' + mac[i];
991                 if (t.search(/^[0-9A-F]+$/) == -1) return null;
992                 if ((t = parseInt(t, 16)) > 255) return null;
993                 mac[i] = t.hex(2);
994         }
995         return mac.join(':');
998 function v_mac(e, quiet)
1000         var mac;
1002         if ((e = E(e)) == null) return 0;
1003         mac = fixMAC(e.value);
1004         if ((!mac) || (isMAC0(mac))) {
1005                 ferror.set(e, 'Invalid MAC address', quiet);
1006                 return 0;
1007         }
1008         e.value = mac;
1009         ferror.clear(e);
1010         return 1;
1013 function v_macz(e, quiet)
1015         var mac;
1017         if ((e = E(e)) == null) return 0;
1018         mac = fixMAC(e.value);
1019         if (!mac) {
1020                 ferror.set(e, 'Invalid MAC address', quiet);
1021                 return false;
1022         }
1023         e.value = mac;
1024         ferror.clear(e);
1025         return true;
1028 function v_length(e, quiet, min, max)
1030         var s, n;
1032         if ((e = E(e)) == null) return 0;
1033         s = e.value.trim();
1034         n = s.length;
1035         if (min == undefined) min = 1;
1036         if (n < min) {
1037                 ferror.set(e, 'Invalid length. Please enter at least ' + min + ' character' + (min == 1 ? '.' : 's.'), quiet);
1038                 return 0;
1039         }
1040         max = max || e.maxlength;
1041         if (n > max) {
1042                 ferror.set(e, 'Invalid length. Please reduce the length to ' + max + ' characters or less.', quiet);
1043                 return 0;
1044         }
1045         e.value = s;
1046         ferror.clear(e);
1047         return 1;
1050 function _v_iptaddr(e, quiet, multi, ipv4, ipv6)
1052         var v, t, i;
1054         if ((e = E(e)) == null) return 0;
1055         v = e.value.split(',');
1056         if (multi) {
1057                 if (v.length > multi) {
1058                         ferror.set(e, 'Too many addresses', quiet);
1059                         return 0;
1060                 }
1061         }
1062         else {
1063                 if (v.length > 1) {
1064                         ferror.set(e, 'Invalid domain name or IP address', quiet);
1065                         return 0;
1066                 }
1067         }
1069         for (i = 0; i < v.length; ++i) {
1070                 if ((t = _v_domain(e, v[i], 1)) == null) {
1071 /* IPV6-BEGIN */
1072                         if ((!ipv6) && (!ipv4)) {
1073                                 if (!quiet) ferror.show(e);
1074                                 return 0;
1075                         }
1076                         if ((!ipv6) || ((t = _v_ipv6_addr(e, v[i], 1, 1)) == null)) {
1077 /* IPV6-END */
1078                                 if (!ipv4) {
1079                                         if (!quiet) ferror.show(e);
1080                                         return 0;
1081                                 }
1082                                 if ((t = _v_iptip(e, v[i], 1)) == null) {
1083                                         ferror.set(e, e._error_msg + ', or invalid domain name', quiet);
1084                                         return 0;
1085                                 }
1086 /* IPV6-BEGIN */
1087                         }
1088 /* IPV6-END */
1089                 }
1090                 v[i] = t;
1091         }
1093         e.value = v.join(', ');
1094         ferror.clear(e);
1095         return 1;
1098 function v_iptaddr(e, quiet, multi)
1100         return _v_iptaddr(e, quiet, multi, 1, 0);
1103 function _v_hostname(e, h, quiet, required, multi, delim, cidr)
1105         var s;
1106         var v, i;
1107         var re;
1109         v = (typeof(delim) == 'undefined') ? h.split(/\s+/) : h.split(delim);
1111         if (multi) {
1112                 if (v.length > multi) {
1113                         ferror.set(e, 'Too many hostnames.', quiet);
1114                         return null;
1115                 }
1116         }
1117         else {
1118                 if (v.length > 1) {
1119                         ferror.set(e, 'Invalid hostname.', quiet);
1120                         return null;
1121                 }
1122         }
1124         re = /^[a-zA-Z0-9](([a-zA-Z0-9\-]{0,61})[a-zA-Z0-9]){0,1}$/;
1126         for (i = 0; i < v.length; ++i) {
1127                 s = v[i].replace(/_+/g, '-').replace(/\s+/g, '-');
1128                 if (s.length > 0) {
1129                         if (cidr && i == v.length-1)
1130                                 re = /^[a-zA-Z0-9](([a-zA-Z0-9\-]{0,61})[a-zA-Z0-9]){0,1}(\/\d{1,3})?$/;
1131                         if (s.search(re) == -1 || s.search(/^\d+$/) != -1) {
1132                                 ferror.set(e, 'Invalid hostname. Only "A-Z 0-9" and "-" in the middle are allowed (up to 63 characters).', quiet);
1133                                 return null;
1134                         }
1135                 } else if (required) {
1136                         ferror.set(e, 'Invalid hostname.', quiet);
1137                         return null;
1138                 }
1139                 v[i] = s;
1140         }
1142         ferror.clear(e);
1143         return v.join((typeof(delim) == 'undefined') ? ' ' : delim);
1146 function v_hostname(e, quiet, multi, delim)
1148         var v;
1150         if ((e = E(e)) == null) return 0;
1152         v = _v_hostname(e, e.value, quiet, 0, multi, delim, false);
1154         if (v == null) return 0;
1156         e.value = v;
1157         return 1;
1160 function v_nodelim(e, quiet, name, checklist)
1162         if ((e = E(e)) == null) return 0;
1164         e.value = e.value.trim();
1165         if (e.value.indexOf('<') != -1 ||
1166            (checklist && e.value.indexOf('>') != -1)) {
1167                 ferror.set(e, 'Invalid ' + name + ': \"<\" ' + (checklist ? 'or \">\" are' : 'is') + ' not allowed.', quiet);
1168                 return 0;
1169         }
1170         ferror.clear(e);
1171         return 1;
1174 function v_path(e, quiet, required)
1176         if ((e = E(e)) == null) return 0;
1177         if (required && !v_length(e, quiet, 1)) return 0;
1179         if (!required && e.value.trim().length == 0) {
1180                 ferror.clear(e);
1181                 return 1;
1182         }
1183         if (e.value.substr(0, 1) != '/') {
1184                 ferror.set(e, 'Please start at the / root directory.', quiet);
1185                 return 0;
1186         }
1187         ferror.clear(e);
1188         return 1;
1191 function isMAC0(mac)
1193         return (mac == '00:00:00:00:00:00');
1196 // -----------------------------------------------------------------------------
1198 function cmpIP(a, b)
1200         if ((a = fixIP(a)) == null) a = '255.255.255.255';
1201         if ((b = fixIP(b)) == null) b = '255.255.255.255';
1202         return aton(a) - aton(b);
1205 function cmpText(a, b)
1207         if (a == '') a = '\xff';
1208         if (b == '') b = '\xff';
1209         return (a < b) ? -1 : ((a > b) ? 1 : 0);
1212 function cmpInt(a, b)
1214         a = parseInt(a, 10);
1215         b = parseInt(b, 10);
1216         return ((isNaN(a)) ? -0x7FFFFFFF : a) - ((isNaN(b)) ? -0x7FFFFFFF : b);
1219 function cmpFloat(a, b)
1221         a = parseFloat(a);
1222         b = parseFloat(b);
1223         return ((isNaN(a)) ? -Number.MAX_VALUE : a) - ((isNaN(b)) ? -Number.MAX_VALUE : b);
1226 function cmpDate(a, b)
1228         return b.getTime() - a.getTime();
1231 // -----------------------------------------------------------------------------
1233 // ---- todo: cleanup this mess
1235 function TGO(e)
1237         return elem.parentElem(e, 'TABLE').gridObj;
1240 function tgHideIcons()
1242         var e;
1243         while ((e = document.getElementById('tg-row-panel')) != null) e.parentNode.removeChild(e);
1246 // ---- options = sort, move, delete
1247 function TomatoGrid(tb, options, maxAdd, editorFields)
1249         this.init(tb, options, maxAdd, editorFields);
1250         return this;
1253 TomatoGrid.prototype = {
1254         init: function(tb, options, maxAdd, editorFields) {
1255                 if (tb) {
1256                         this.tb = E(tb);
1257                         this.tb.gridObj = this;
1258                 }
1259                 else {
1260                         this.tb = null;
1261                 }
1262                 if (!options) options = '';
1263                 this.header = null;
1264                 this.footer = null;
1265                 this.editor = null;
1266                 this.canSort = options.indexOf('sort') != -1;
1267                 this.canMove = options.indexOf('move') != -1;
1268                 this.maxAdd = maxAdd || 500;
1269                 this.canEdit = (editorFields != null);
1270                 this.canDelete = this.canEdit || (options.indexOf('delete') != -1);
1271                 this.editorFields = editorFields;
1272                 this.sortColumn = -1;
1273                 this.sortAscending = true;
1274         },
1276         _insert: function(at, cells, escCells) {
1277                 var tr, td, c;
1278                 var i, t;
1280                 tr = this.tb.insertRow(at);
1281                 for (i = 0; i < cells.length; ++i) {
1282                         c = cells[i];
1283                         if (typeof(c) == 'string') {
1284                                 td = tr.insertCell(i);
1285                                 td.className = 'co' + (i + 1);
1286                                 if (escCells) td.appendChild(document.createTextNode(c));
1287                                         else td.innerHTML = c;
1288                         }
1289                         else {
1290                                 tr.appendChild(c);
1291                         }
1292                 }
1293                 return tr;
1294         },
1296         // ---- header
1298         headerClick: function(cell) {
1299                 if (this.canSort) {
1300                         this.sort(cell.cellN);
1301                 }
1302         },
1304         headerSet: function(cells, escCells) {
1305                 var e, i;
1307                 elem.remove(this.header);
1308                 this.header = e = this._insert(0, cells, escCells);
1309                 e.className = 'header';
1311                 for (i = 0; i < e.cells.length; ++i) {
1312                         e.cells[i].cellN = i;   // cellIndex broken in Safari
1313                         e.cells[i].onclick = function() { return TGO(this).headerClick(this); };
1314                 }
1315                 return e;
1316         },
1318         // ---- footer
1320         footerClick: function(cell) {
1321         },
1323         footerSet: function(cells, escCells) {
1324                 var e, i;
1326                 elem.remove(this.footer);
1327                 this.footer = e = this._insert(-1, cells, escCells);
1328                 e.className = 'footer';
1329                 for (i = 0; i < e.cells.length; ++i) {
1330                         e.cells[i].cellN = i;
1331                         e.cells[i].onclick = function() { TGO(this).footerClick(this) };
1332                 }
1333                 return e;
1334         },
1336         // ----
1338         rpUp: function(e) {
1339                 var i;
1341                 e = PR(e);
1342                 TGO(e).moving = null;
1343                 i = e.previousSibling;
1344                 if (i == this.header) return;
1345                 e.parentNode.removeChild(e);
1346                 i.parentNode.insertBefore(e, i);
1348                 this.recolor();
1349                 this.rpHide();
1350         },
1352         rpDn: function(e) {
1353                 var i;
1355                 e = PR(e);
1356                 TGO(e).moving = null;
1357                 i = e.nextSibling;
1358                 if (i == this.footer) return;
1359                 e.parentNode.removeChild(e);
1360                 i.parentNode.insertBefore(e, i.nextSibling);
1362                 this.recolor();
1363                 this.rpHide();
1364         },
1366         rpMo: function(img, e) {
1367                 var me;
1369                 e = PR(e);
1370                 me = TGO(e);
1371                 if (me.moving == e) {
1372                         me.moving = null;
1373                         this.rpHide();
1374                         return;
1375                 }
1376                 me.moving = e;
1377                 img.style.border = "1px dotted red";
1378         },
1380         rpDel: function(e) {
1381                 e = PR(e);
1382                 TGO(e).moving = null;
1383                 e.parentNode.removeChild(e);
1384                 this.recolor();
1385                 this.rpHide();
1386         },
1388         rpMouIn: function(evt) {
1389                 var e, x, ofs, me, s, n;
1391                 if ((evt = checkEvent(evt)) == null) return;
1393                 me = TGO(evt.target);
1394                 if (me.isEditing()) return;
1395                 if (me.moving) return;
1397                 me.rpHide();
1398                 e = document.createElement('div');
1399                 e.tgo = me;
1400                 e.ref = evt.target;
1401                 e.setAttribute('id', 'tg-row-panel');
1403                 n = 0;
1404                 s = '';
1405                 if (me.canMove) {
1406                         s = '<img src="rpu.gif" onclick="this.parentNode.tgo.rpUp(this.parentNode.ref)" title="Move Up"><img src="rpd.gif" onclick="this.parentNode.tgo.rpDn(this.parentNode.ref)" title="Move Down"><img src="rpm.gif" onclick="this.parentNode.tgo.rpMo(this,this.parentNode.ref)" title="Move">';
1407                         n += 3;
1408                 }
1409                 if (me.canDelete) {
1410                         s += '<img src="rpx.gif" onclick="this.parentNode.tgo.rpDel(this.parentNode.ref)" title="Delete">';
1411                         ++n;
1412                 }
1413                 x = PR(evt.target);
1414                 x = x.cells[x.cells.length - 1];
1415                 ofs = elem.getOffset(x);
1416                 n *= 18;
1417                 e.style.left = (ofs.x + x.offsetWidth - n) + 'px';
1418                 e.style.top = ofs.y + 'px';
1419                 e.style.width = n + 'px';
1420                 e.innerHTML = s;
1422                 document.body.appendChild(e);
1423         },
1425         rpHide: tgHideIcons,
1427         // ----
1429         onClick: function(cell) {
1430                 if (this.canEdit) {
1431                         if (this.moving) {
1432                                 var p = this.moving.parentNode;
1433                                 var q = PR(cell);
1434                                 if (this.moving != q) {
1435                                         var v = this.moving.rowIndex > q.rowIndex;
1436                                         p.removeChild(this.moving);
1437                                         if (v) p.insertBefore(this.moving, q);
1438                                                 else p.insertBefore(this.moving, q.nextSibling);
1439                                         this.recolor();
1440                                 }
1441                                 this.moving = null;
1442                                 this.rpHide();
1443                                 return;
1444                         }
1445                         this.edit(cell);
1446                 }
1447         },
1449         insert: function(at, data, cells, escCells) {
1450                 var e, i;
1452                 if ((this.footer) && (at == -1)) at = this.footer.rowIndex;
1453                 e = this._insert(at, cells, escCells);
1454                 e.className = (e.rowIndex & 1) ? 'even' : 'odd';
1456                 for (i = 0; i < e.cells.length; ++i) {
1457                         e.cells[i].onclick = function() { return TGO(this).onClick(this); };
1458                 }
1460                 e._data = data;
1461                 e.getRowData = function() { return this._data; }
1462                 e.setRowData = function(data) { this._data = data; }
1464                 if ((this.canMove) || (this.canEdit) || (this.canDelete)) {
1465                         e.onmouseover = this.rpMouIn;
1466 // ----                 e.onmouseout = this.rpMouOut;
1467                         if (this.canEdit) e.title = 'Click to edit';
1468                 }
1470                 return e;
1471         },
1473         // ----
1475         insertData: function(at, data) {
1476                 return this.insert(at, data, this.dataToView(data), false);
1477         },
1479         dataToView: function(data) {
1480                 var v = [];
1481                 for (var i = 0; i < data.length; ++i) {
1482                         var s = escapeHTML('' + data[i]);
1483                         if (this.editorFields && this.editorFields.length > i) {
1484                                 var ef = this.editorFields[i].multi;
1485                                 if (!ef) ef = [this.editorFields[i]];
1486                                 var f = (ef && ef.length > 0 ? ef[0] : null);
1487                                 if (f && f.type == 'password') {
1488                                         if (!f.peekaboo || get_config('web_pb', '1') != '0')
1489                                                 s = s.replace(/./g, '&#x25CF;');
1490                                 }
1491                         }
1492                         v.push(s);
1493                 }
1494                 return v;
1495         },
1497         dataToFieldValues: function(data) {
1498                 return data;
1499         },
1501         fieldValuesToData: function(row) {
1502                 var e, i, data;
1504                 data = [];
1505                 e = fields.getAll(row);
1506                 for (i = 0; i < e.length; ++i) data.push(e[i].value);
1507                 return data;
1508         },
1510         // ----
1512         edit: function(cell) {
1513                 var sr, er, e, c;
1515                 if (this.isEditing()) return;
1517                 sr = PR(cell);
1518                 sr.style.display = 'none';
1519                 elem.removeClass(sr, 'hover');
1520                 this.source = sr;
1522                 er = this.createEditor('edit', sr.rowIndex, sr);
1523                 er.className = 'editor';
1524                 this.editor = er;
1526                 c = er.cells[cell.cellIndex || 0];
1527                 e = c.getElementsByTagName('input');
1528                 if ((e) && (e.length > 0)) {
1529                         try {   // IE quirk
1530                                 e[0].focus();
1531                         }
1532                         catch (ex) {
1533                         }
1534                 }
1536                 this.controls = this.createControls('edit', sr.rowIndex);
1538                 this.disableNewEditor(true);
1539                 this.rpHide();
1540                 this.verifyFields(this.editor, true);
1541         },
1543         createEditor: function(which, rowIndex, source) {
1544                 var values;
1546                 if (which == 'edit') values = this.dataToFieldValues(source.getRowData());
1548                 var row = this.tb.insertRow(rowIndex);
1549                 row.className = 'editor';
1551                 var common = ' onkeypress="return TGO(this).onKey(\'' + which + '\', event)" onchange="TGO(this).onChange(\'' + which + '\', this)"';
1553                 var vi = 0;
1554                 for (var i = 0; i < this.editorFields.length; ++i) {
1555                         var s = '';
1556                         var ef = this.editorFields[i].multi;
1557                         if (!ef) ef = [this.editorFields[i]];
1559                         for (var j = 0; j < ef.length; ++j) {
1560                                 var f = ef[j];
1562                                 if (f.prefix) s += f.prefix;
1563                                 var attrib = ' class="fi' + (vi + 1) + '" ' + (f.attrib || '');
1564                                 var id = (this.tb ? ('_' + this.tb + '_' + (vi + 1)) : null);
1565                                 if (id) attrib += ' id="' + id + '"';
1566                                 switch (f.type) {
1567                                 case 'password':
1568                                         if (f.peekaboo) {
1569                                                 switch (get_config('web_pb', '1')) {
1570                                                 case '0':
1571                                                         f.type = 'text';
1572                                                 case '2':
1573                                                         f.peekaboo = 0;
1574                                                         break;
1575                                                 }
1576                                         }
1577                                         attrib += ' autocomplete="off"';
1578                                         if (f.peekaboo && id) attrib += ' onfocus=\'peekaboo("' + id + '",1)\'';
1579                                         // drop
1580                                 case 'text':
1581                                         s += '<input type="' + f.type + '" maxlength=' + f.maxlen + common + attrib;
1582                                         if (which == 'edit') s += ' value="' + escapeHTML('' + values[vi]) + '">';
1583                                                 else s += '>';
1584                                         break;
1585                                 case 'clear':
1586                                         s += '';
1587                                         break;
1588                                 case 'select':
1589                                         s += '<select' + common + attrib + '>';
1590                                         for (var k = 0; k < f.options.length; ++k) {
1591                                                 a = f.options[k];
1592                                                 if (which == 'edit') {
1593                                                         s += '<option value="' + a[0] + '"' + ((a[0] == values[vi]) ? ' selected>' : '>') + a[1] + '</option>';
1594                                                 }
1595                                                 else {
1596                                                         s += '<option value="' + a[0] + '">' + a[1] + '</option>';
1597                                                 }
1598                                         }
1599                                         s += '</select>';
1600                                         break;
1601                                 case 'checkbox':
1602                                         s += '<input type="checkbox"' + common + attrib;
1603                                         if ((which == 'edit') && (values[vi])) s += ' checked';
1604                                         s += '>';
1605                                         break;
1606                                 case 'textarea':
1607                                         if (which == 'edit'){
1608                                                 document.getElementById(f.proxy).value = values[vi];
1609                                         }
1610                                         break;
1611                                 default:
1612                                         s += f.custom.replace(/\$which\$/g, which);
1613                                 }
1614                                 if (f.suffix) s += f.suffix;
1616                                 ++vi;
1617                         }
1618                         if(this.editorFields[i].type != 'textarea'){
1619                                 var c = row.insertCell(i);
1620                                 c.innerHTML = s;
1621                                 if (this.editorFields[i].vtop) c.vAlign = 'top';
1622                         }
1623                 }
1625                 return row;
1626         },
1628         createControls: function(which, rowIndex) {
1629                 var r, c;
1631                 r = this.tb.insertRow(rowIndex);
1632                 r.className = 'controls';
1634                 c = r.insertCell(0);
1635                 c.colSpan = this.header.cells.length;
1636                 if (which == 'edit') {
1637                         c.innerHTML =
1638                                 '<input type=button value="Delete" onclick="TGO(this).onDelete()"> &nbsp; ' +
1639                                 '<input type=button value="OK" onclick="TGO(this).onOK()"> ' +
1640                                 '<input type=button value="Cancel" onclick="TGO(this).onCancel()">';
1641                 }
1642                 else {
1643                         c.innerHTML =
1644                                 '<input type=button value="Add" onclick="TGO(this).onAdd()">';
1645                 }
1646                 return r;
1647         },
1649         removeEditor: function() {
1650                 if (this.editor) {
1652                         elem.remove(this.editor);
1653                         this.editor = null;
1654                 }
1655                 if (this.controls) {
1656                         elem.remove(this.controls);
1657                         this.controls = null;
1658                 }
1659         },
1661         showSource: function() {
1662                 if (this.source) {
1663                         this.source.style.display = '';
1664                         this.source = null;
1665                 }
1666         },
1668         onChange: function(which, cell) {
1669                 return this.verifyFields((which == 'new') ? this.newEditor : this.editor, true);
1670         },
1672         onKey: function(which, ev) {
1673                 switch (ev.keyCode) {
1674                 case 27:
1675                         if (which == 'edit') this.onCancel();
1676                         return false;
1677                 case 13:
1678                         if (((ev.srcElement) && (ev.srcElement.tagName == 'SELECT')) ||
1679                                 ((ev.target) && (ev.target.tagName == 'SELECT'))) return true;
1680                         if (which == 'edit') this.onOK();
1681                                 else this.onAdd();
1682                         return false;
1683                 }
1684                 return true;
1685         },
1687         onDelete: function() {
1688                 this.removeEditor();
1689                 elem.remove(this.source);
1690                 this.source = null;
1691                 this.disableNewEditor(false);
1692                 this.clearTextarea();
1693         },
1695         onCancel: function() {
1696                 this.removeEditor();
1697                 this.showSource();
1698                 this.disableNewEditor(false);
1699                 this.clearTextarea();
1700         },
1702         onOK: function() {
1703                 var i, data, view;
1705                 if (!this.verifyFields(this.editor, false)) return;
1707                 data = this.fieldValuesToData(this.editor);
1708                 view = this.dataToView(data);
1710                 this.source.setRowData(data);
1711                 for (i = 0; i < this.source.cells.length; ++i) {
1712                         this.source.cells[i].innerHTML = view[i];
1713                 }
1715                 this.removeEditor();
1716                 this.showSource();
1717                 this.disableNewEditor(false);
1718                 this.clearTextarea();
1719         },
1721         onAdd: function() {
1722                 var data;
1724                 this.moving = null;
1725                 this.rpHide();
1727                 if (!this.verifyFields(this.newEditor, false)) return;
1729                 data = this.fieldValuesToData(this.newEditor);
1730                 this.insertData(-1, data);
1732                 this.disableNewEditor(false);
1733                 this.resetNewEditor();
1734         },
1736         clearTextarea: function() {
1737                 for (var i = 0; i < this.editorFields.length; ++i){
1738                         if(this.editorFields[i].type == 'textarea'){
1739                                 document.getElementById(this.editorFields[i].proxy).value = '';
1740                                 ferror.clear(document.getElementById(this.editorFields[i].proxy));
1741                         }
1742                 }
1743         },
1745         verifyFields: function(row, quiet) {
1746                 return true;
1747         },
1749         showNewEditor: function() {
1750                 var r;
1752                 r = this.createEditor('new', -1, null);
1753                 this.footer = this.newEditor = r;
1755                 r = this.createControls('new', -1);
1756                 this.newControls = r;
1758                 this.disableNewEditor(false);
1759         },
1761         disableNewEditor: function(disable) {
1762                 if (this.getDataCount() >= this.maxAdd) disable = true;
1763                 if (this.newEditor) fields.disableAll(this.newEditor, disable);
1764                 if (this.newControls) fields.disableAll(this.newControls, disable);
1765         },
1767         resetNewEditor: function() {
1768                 var i, e;
1770                 e = fields.getAll(this.newEditor);
1771                 ferror.clearAll(e);
1772                 for (i = 0; i < e.length; ++i) {
1773                         var f = e[i];
1774                         if (f.selectedIndex) f.selectedIndex = 0;
1775                                 else f.value = '';
1776                 }
1777                 try { if (e.length) e[0].focus(); } catch (er) { }
1778         },
1780         getDataCount: function() {
1781                 var n;
1782                 n = this.tb.rows.length;
1783                 if (this.footer) n = this.footer.rowIndex;
1784                 if (this.header) n -= this.header.rowIndex + 1;
1785                 return n;
1786         },
1788         sortCompare: function(a, b) {
1789                 var obj = TGO(a);
1790                 var col = obj.sortColumn;
1791                 var r = cmpText(a.cells[col].innerHTML, b.cells[col].innerHTML);
1792                 return obj.sortAscending ? r : -r;
1793         },
1795         sort: function(column) {
1796                 if (this.editor) return;
1798                 if (this.sortColumn >= 0) {
1799                         elem.removeClass(this.header.cells[this.sortColumn], 'sortasc', 'sortdes');
1800                 }
1801                 if (column == this.sortColumn) {
1802                         this.sortAscending = !this.sortAscending;
1803                 }
1804                 else {
1805                         this.sortAscending = true;
1806                         this.sortColumn = column;
1807                 }
1808                 elem.addClass(this.header.cells[column], this.sortAscending ? 'sortasc' : 'sortdes');
1810                 this.resort();
1811         },
1813         resort: function() {
1814                 if ((this.sortColumn < 0) || (this.getDataCount() == 0) || (this.editor)) return;
1816                 var p = this.header.parentNode;
1817                 var a = [];
1818                 var i, j, max, e, p;
1819                 var top;
1821                 this.moving = null;
1823                 top = this.header ? this.header.rowIndex + 1 : 0;
1824                 max = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1825                 for (i = top; i < max; ++i) a.push(p.rows[i]);
1826                 a.sort(THIS(this, this.sortCompare));
1827                 this.removeAllData();
1828                 j = top;
1829                 for (i = 0; i < a.length; ++i) {
1830                         e = p.insertBefore(a[i], this.footer);
1831                         e.className = (j & 1) ? 'even' : 'odd';
1832                         ++j;
1833                 }
1834         },
1836         recolor: function() {
1837                  var i, e, o;
1839                  i = this.header ? this.header.rowIndex + 1 : 0;
1840                  e = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1841                  for (; i < e; ++i) {
1842                          o = this.tb.rows[i];
1843                          o.className = (o.rowIndex & 1) ? 'even' : 'odd';
1844                  }
1845         },
1847         removeAllData: function() {
1848                 var i, count;
1850                 i = this.header ? this.header.rowIndex + 1 : 0;
1851                 count = (this.footer ? this.footer.rowIndex : this.tb.rows.length) - i;
1852                 while (count-- > 0) elem.remove(this.tb.rows[i]);
1853         },
1855         getAllData: function() {
1856                 var i, max, data, r;
1858                 data = [];
1859                 max = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1860                 for (i = this.header ? this.header.rowIndex + 1 : 0; i < max; ++i) {
1861                         r = this.tb.rows[i];
1862                         if ((r.style.display != 'none') && (r._data)) data.push(r._data);
1863                 }
1864                 return data;
1865         },
1867         isEditing: function() {
1868                 return (this.editor != null);
1869         }
1873 // -----------------------------------------------------------------------------
1876 function xmlHttpObj()
1878         var ob;
1879         try {
1880                 ob = new XMLHttpRequest();
1881                 if (ob) return ob;
1882         }
1883         catch (ex) { }
1884         try {
1885                 ob = new ActiveXObject('Microsoft.XMLHTTP');
1886                 if (ob) return ob;
1887         }
1888         catch (ex) { }
1889         return null;
1892 var _useAjax = -1;
1893 var _holdAjax = null;
1895 function useAjax()
1897         if (_useAjax == -1) _useAjax = ((_holdAjax = xmlHttpObj()) != null);
1898         return _useAjax;
1901 function XmlHttp()
1903         if ((!useAjax()) || ((this.xob = xmlHttpObj()) == null)) return null;
1904         return this;
1907 XmlHttp.prototype = {
1908         addId: function(vars) {
1909                 if (vars) vars += '&';
1910                         else vars = '';
1911                 vars += '_http_id=' + escapeCGI(nvram.http_id);
1912                 return vars;
1913         },
1915         get: function(url, vars) {
1916                 try {
1917                         vars = this.addId(vars);
1918                         url += '?' + vars;
1920                         this.xob.onreadystatechange = THIS(this, this.onReadyStateChange);
1921                         this.xob.open('GET', url, true);
1922                         this.xob.send(null);
1923                 }
1924                 catch (ex) {
1925                         this.onError(ex);
1926                 }
1927         },
1929         post: function(url, vars) {
1930                 try {
1931                         vars = this.addId(vars);
1933                         this.xob.onreadystatechange = THIS(this, this.onReadyStateChange);
1934                         this.xob.open('POST', url, true);
1935                         this.xob.send(vars);
1936                 }
1937                 catch (ex) {
1938                         this.onError(ex);
1939                 }
1940         },
1942         abort: function() {
1943                 try {
1944                         this.xob.onreadystatechange = function () { }
1945                         this.xob.abort();
1946                 }
1947                 catch (ex) {
1948                 }
1949         },
1951         onReadyStateChange: function() {
1952                 try {
1953                         if (typeof(E) == 'undefined') return;   // oddly late? testing for bug...
1955                         if (this.xob.readyState == 4) {
1956                                 if (this.xob.status == 200) {
1957                                         this.onCompleted(this.xob.responseText, this.xob.responseXML);
1958                                 }
1959                                 else {
1960                                         this.onError('' + (this.xob.status || 'unknown'));
1961                                 }
1962                         }
1963                 }
1964                 catch (ex) {
1965                         this.onError(ex);
1966                 }
1967         },
1969         onCompleted: function(text, xml) { },
1970         onError: function(ex) { }
1974 // -----------------------------------------------------------------------------
1977 function TomatoTimer(func, ms)
1979         this.tid = null;
1980         this.onTimer = func;
1981         if (ms) this.start(ms);
1982         return this;
1985 TomatoTimer.prototype = {
1986         start: function(ms) {
1987                 this.stop();
1988                 this.tid = setTimeout(THIS(this, this._onTimer), ms);
1989         },
1990         stop: function() {
1991                 if (this.tid) {
1992                         clearTimeout(this.tid);
1993                         this.tid = null;
1994                 }
1995         },
1997         isRunning: function() {
1998                 return (this.tid != null);
1999         },
2001         _onTimer: function() {
2002                 this.tid = null;
2003                 this.onTimer();
2004         },
2006         onTimer: function() {
2007         }
2011 // -----------------------------------------------------------------------------
2014 function TomatoRefresh(actionURL, postData, refreshTime, cookieTag)
2016         this.setup(actionURL, postData, refreshTime, cookieTag);
2017         this.timer = new TomatoTimer(THIS(this, this.start));
2020 TomatoRefresh.prototype = {
2021         running: 0,
2023         setup: function(actionURL, postData, refreshTime, cookieTag) {
2024                 var e, v;
2026                 this.actionURL = actionURL;
2027                 this.postData = postData;
2028                 this.refreshTime = refreshTime * 1000;
2029                 this.cookieTag = cookieTag;
2030         },
2032         start: function() {
2033                 var e;
2035                 if ((e = E('refresh-time')) != null) {
2036                         if (this.cookieTag) cookie.set(this.cookieTag, e.value);
2037                         this.refreshTime = e.value * 1000;
2038                 }
2039                 e = undefined;
2041                 this.updateUI('start');
2043                 this.running = 1;
2044                 if ((this.http = new XmlHttp()) == null) {
2045                         reloadPage();
2046                         return;
2047                 }
2049                 this.http.parent = this;
2051                 this.http.onCompleted = function(text, xml) {
2052                         var p = this.parent;
2054                         if (p.cookieTag) cookie.unset(p.cookieTag + '-error');
2055                         if (!p.running) {
2056                                 p.stop();
2057                                 return;
2058                         }
2060                         p.refresh(text);
2062                         if ((p.refreshTime > 0) && (!p.once)) {
2063                                 p.updateUI('wait');
2064                                 p.timer.start(Math.round(p.refreshTime));
2065                         }
2066                         else {
2067                                 p.stop();
2068                         }
2070                         p.errors = 0;
2071                 }
2073                 this.http.onError = function(ex) {
2074                         var p = this.parent;
2075                         if ((!p) || (!p.running)) return;
2077                         p.timer.stop();
2079                         if (++p.errors <= 3) {
2080                                 p.updateUI('wait');
2081                                 p.timer.start(3000);
2082                                 return;
2083                         }
2085                         if (p.cookieTag) {
2086                                 var e = cookie.get(p.cookieTag + '-error') * 1;
2087                                 if (isNaN(e)) e = 0;
2088                                         else ++e;
2089                                 cookie.unset(p.cookieTag);
2090                                 cookie.set(p.cookieTag + '-error', e, 1);
2091                                 if (e >= 3) {
2092                                         alert('XMLHTTP: ' + ex);
2093                                         return;
2094                                 }
2095                         }
2097                         setTimeout(reloadPage, 2000);
2098                 }
2100                 this.errors = 0;
2101                 this.http.post(this.actionURL, this.postData);
2102         },
2104         stop: function() {
2105                 if (this.cookieTag) cookie.set(this.cookieTag, -(this.refreshTime / 1000));
2106                 this.running = 0;
2107                 this.updateUI('stop');
2108                 this.timer.stop();
2109                 this.http = null;
2110                 this.once = undefined;
2111         },
2113         toggle: function(delay) {
2114                 if (this.running) this.stop();
2115                         else this.start(delay);
2116         },
2118         updateUI: function(mode) {
2119                 var e, b;
2121                 if (typeof(E) == 'undefined') return;   // for a bizzare bug...
2123                 b = (mode != 'stop') && (this.refreshTime > 0);
2124                 if ((e = E('refresh-button')) != null) {
2125                         e.value = b ? 'Stop' : 'Refresh';
2126                         e.disabled = ((mode == 'start') && (!b));
2127                 }
2128                 if ((e = E('refresh-time')) != null) e.disabled = b;
2129                 if ((e = E('refresh-spinner')) != null) e.style.visibility = b ? 'visible' : 'hidden';
2130         },
2132         initPage: function(delay, def) {
2133                 var e, v;
2135                 e = E('refresh-time');
2136                 if (((this.cookieTag) && (e != null)) &&
2137                         ((v = cookie.get(this.cookieTag)) != null) && (!isNaN(v *= 1))) {
2138                         e.value = Math.abs(v);
2139                         if (v > 0) v = (v * 1000) + (delay || 0);
2140                 }
2141                 else if (def) {
2142                         v = def;
2143                         if (e) e.value = def;
2144                 }
2145                 else v = 0;
2147                 if (delay < 0) {
2148                         v = -delay;
2149                         this.once = 1;
2150                 }
2152                 if (v > 0) {
2153                         this.running = 1;
2154                         this.refreshTime = v;
2155                         this.timer.start(v);
2156                         this.updateUI('wait');
2157                 }
2158         }
2161 function genStdTimeList(id, zero, min)
2163         var b = [];
2164         var t = [0.5,1,2,3,4,5,10,15,30,60,120,180,240,300,10*60,15*60,20*60,30*60];
2165         var i, v;
2167         if (min >= 0) {
2168                 b.push('<select id="' + id + '"><option value=0>' + zero);
2169                 for (i = 0; i < t.length; ++i) {
2170                         v = t[i];
2171                         if (v < min) continue;
2172                         b.push('<option value=' + v + '>');
2173                         if (v == 60) b.push('1 minute');
2174                                 else if (v > 60) b.push((v / 60) + ' minutes');
2175                                 else b.push(v + ' seconds');
2176                 }
2177                 b.push('</select> ');
2178         }
2179         document.write(b.join(''));
2182 function genStdRefresh(spin, min, exec)
2184         W('<div style="text-align:right">');
2185         if (spin) W('<img src="spin.gif" id="refresh-spinner"> ');
2186         genStdTimeList('refresh-time', 'Auto Refresh', min);
2187         W('<input type="button" value="Refresh" onclick="' + (exec ? exec : 'refreshClick()') + '" id="refresh-button"></div>');
2191 // -----------------------------------------------------------------------------
2194 function _tabCreate(tabs)
2196         var buf = [];
2197         buf.push('<ul id="tabs">');
2198         for (var i = 0; i < arguments.length; ++i)
2199                 buf.push('<li><a href="javascript:tabSelect(\'' + arguments[i][0] + '\')" id="' + arguments[i][0] + '">' + arguments[i][1] + '</a>');
2200         buf.push('</ul><div id="tabs-bottom"></div>');
2201         return buf.join('');
2204 function tabCreate(tabs)
2206         document.write(_tabCreate.apply(this, arguments));
2209 function tabHigh(id)
2211         var a = E('tabs').getElementsByTagName('A');
2212         for (var i = 0; i < a.length; ++i) {
2213                 if (id != a[i].id) elem.removeClass(a[i], 'active');
2214         }
2215         elem.addClass(id, 'active');
2218 // -----------------------------------------------------------------------------
2220 var cookie = {
2221         // The value 2147483647000 is ((2^31)-1)*1000, which is the number of
2222         // milliseconds (minus 1 second) which correlates with the year 2038 counter
2223         // rollover. This effectively makes the cookie never expire.
2225         set: function(key, value, days) {
2226                 document.cookie = 'tomato_' + encodeURIComponent(key) + '=' + encodeURIComponent(value) + '; expires=' +
2227                 new Date(2147483647000).toUTCString() + '; path=/';
2228         },
2229         get: function(key) {
2230                 var r = ('; ' + document.cookie + ';').match('; tomato_' + encodeURIComponent(key) + '=(.*?);');
2231                 return r ? decodeURIComponent(r[1]) : null;
2232         },
2233         unset: function(key) {
2234                 document.cookie = 'tomato_' + encodeURIComponent(key) + '=; expires=' +
2235                 (new Date(1)).toUTCString() + '; path=/';
2236         }
2239 // -----------------------------------------------------------------------------
2241 function checkEvent(evt)
2243         if (typeof(evt) == 'undefined') {
2244                 // ---- IE
2245                 evt = event;
2246                 evt.target = evt.srcElement;
2247                 evt.relatedTarget = evt.toElement;
2248         }
2249         return evt;
2252 function W(s)
2254         document.write(s);
2257 function E(e)
2259         return (typeof(e) == 'string') ? document.getElementById(e) : e;
2262 function PR(e)
2264         return elem.parentElem(e, 'TR');
2267 function THIS(obj, func)
2269         return function() { return func.apply(obj, arguments); }
2272 function UT(v)
2274         return (typeof(v) == 'undefined') ? '' : '' + v;
2277 function escapeHTML(s)
2279         function esc(c) {
2280                 return '&#' + c.charCodeAt(0) + ';';
2281         }
2282         return s.replace(/[&"'<>\r\n]/g, esc);
2285 function escapeCGI(s)
2287         return escape(s).replace(/\+/g, '%2B'); // escape() doesn't handle +
2290 function escapeD(s)
2292         function esc(c) {
2293                 return '%' + c.charCodeAt(0).hex(2);
2294         }
2295         return s.replace(/[<>|%]/g, esc);
2298 function ellipsis(s, max) {
2299         return (s.length <= max) ? s : s.substr(0, max - 3) + '...';
2302 function MIN(a, b)
2304         return (a < b) ? a : b;
2307 function MAX(a, b)
2309         return (a > b) ? a : b;
2312 function fixInt(n, min, max, def)
2314         if (n === null) return def;
2315         n *= 1;
2316         if (isNaN(n)) return def;
2317         if (n < min) return min;
2318         if (n > max) return max;
2319         return n;
2322 function comma(n)
2324         n = '' + n;
2325         var p = n;
2326         while ((n = n.replace(/(\d+)(\d{3})/g, '$1,$2')) != p) p = n;
2327         return n;
2330 function doScaleSize(n, sm)
2332         if (isNaN(n *= 1)) return '-';
2333         if (n <= 9999) return '' + n;
2334         var s = -1;
2335         do {
2336                 n /= 1024;
2337                 ++s;
2338         } while ((n > 9999) && (s < 2));
2339         return comma(n.toFixed(2)) + (sm ? '<small> ' : ' ') + (['KB', 'MB', 'GB'])[s] + (sm ? '</small>' : '');
2342 function scaleSize(n)
2344         return doScaleSize(n, 1);
2347 function timeString(mins)
2349         var h = Math.floor(mins / 60);
2350         if ((new Date(2000, 0, 1, 23, 0, 0, 0)).toLocaleString().indexOf('23') != -1)
2351                 return h + ':' + (mins % 60).pad(2);
2352         return ((h == 0) ? 12 : ((h > 12) ? h - 12 : h)) + ':' + (mins % 60).pad(2) + ((h >= 12) ? ' PM' : ' AM');
2355 function features(s)
2357         var features = ['ses','brau','aoss','wham','hpamp','!nve','11n','1000et','11ac'];
2358         var i;
2360         for (i = features.length - 1; i >= 0; --i) {
2361                 if (features[i] == s) return (parseInt(nvram.t_features) & (1 << i)) != 0;
2362         }
2363         return 0;
2366 function get_config(name, def)
2368         return ((typeof(nvram) != 'undefined') && (typeof(nvram[name]) != 'undefined')) ? nvram[name] : def;
2371 function nothing()
2375 // -----------------------------------------------------------------------------
2377 function show_notice1(s)
2379 // ---- !!TB - USB Support: multi-line notices
2380         if (s.length) document.write('<div id="notice1">' + s.replace(/\n/g, '<br>') + '</div><br style="clear:both">');
2383 // -----------------------------------------------------------------------------
2385 function myName()
2387         var name, i;
2389         name = document.location.pathname;
2390         name = name.replace(/\\/g, '/');        // IE local testing
2391         if ((i = name.lastIndexOf('/')) != -1) name = name.substring(i + 1, name.length);
2392         if (name == '') name = 'status-overview.asp';
2393         return name;
2396 function navi()
2398         var menu = [
2399                 ['Status',                      'status', 0, [
2400                         ['Overview',                    'overview.asp'],
2401                         ['Device List',                 'devices.asp'],
2402                         ['Web Usage',                   'webmon.asp'],
2403                         ['Logs',                        'log.asp'] ] ],
2404                 ['Bandwidth',                   'bwm', 0, [
2405                         ['Real-Time',                   'realtime.asp'],
2406                         ['Last 24 Hours',               '24.asp'],
2407                         ['Daily',                       'daily.asp'],
2408                         ['Weekly',                      'weekly.asp'],
2409                         ['Monthly',                     'monthly.asp']
2410                         ] ],
2411                 ['IP Traffic',                  'ipt', 0, [
2412                         ['Real-Time',                   'realtime.asp'],
2413                         ['Last 24 Hours',               '24.asp'],
2414                         ['View Graphs',                 'graphs.asp'],
2415                         ['Transfer Rates',              'details.asp'],
2416                         ['Daily',                       'daily.asp'],
2417                         ['Monthly',                     'monthly.asp']
2418                         ] ],
2419                 ['Tools',                       'tools', 0, [
2420                         ['Ping',                        'ping.asp'],
2421                         ['Trace',                       'trace.asp'],
2422                         ['System Commands',             'shell.asp'],
2423                         ['Wireless Survey',             'survey.asp'],
2424                         ['WOL',                         'wol.asp'] ] ],
2425                 null,
2426                 ['Basic',                       'basic', 0, [
2427                         ['Network',                     'network.asp'],
2428 /* IPV6-BEGIN */
2429                         ['IPv6',                        'ipv6.asp'],
2430 /* IPV6-END */
2431                         ['Identification',              'ident.asp'],
2432                         ['Time',                        'time.asp'],
2433                         ['DDNS',                        'ddns.asp'],
2434                         ['Static DHCP/ARP/IPT',         'static.asp'],
2435                         ['Wireless Filter',             'wfilter.asp'] ] ],
2436                 ['Advanced',                    'advanced', 0, [
2437                         ['Conntrack/Netfilter',         'ctnf.asp'],
2438                         ['DHCP/DNS',                    'dhcpdns.asp'],
2439                         ['Firewall',                    'firewall.asp'],
2440                         ['MAC Address',                 'mac.asp'],
2441                         ['Miscellaneous',               'misc.asp'],
2442                         ['Routing',                     'routing.asp'],
2443 /* TOR-BEGIN */
2444                         ['TOR Project',                 'tor.asp'],
2445 /* TOR-END */
2446                         ['VLAN',                        'vlan.asp'],
2447                         ['LAN Access',                  'access.asp'],
2448                         ['Virtual Wireless',            'wlanvifs.asp'],
2449                         ['Wireless',                    'wireless.asp'] ] ],
2450                 ['Port Forwarding',             'forward', 0, [
2451                         ['Basic',                       'basic.asp'],
2452 /* IPV6-BEGIN */
2453                         ['Basic IPv6',                  'basic-ipv6.asp'],
2454 /* IPV6-END */
2455                         ['DMZ',                         'dmz.asp'],
2456                         ['Triggered',                   'triggered.asp'],
2457                         ['UPnP/NAT-PMP',                'upnp.asp'] ] ],
2458                 ['Access Restriction',          'restrict.asp'],
2459                 ['QoS',                         'qos', 0, [
2460                         ['Basic Settings',              'settings.asp'],
2461                         ['Classification',              'classify.asp'],
2462                         ['View Graphs',                 'graphs.asp'],
2463                         ['View Details',                'detailed.asp'],
2464                         ['Transfer Rates',              'ctrate.asp']
2465                         ] ],
2466                 ['Bandwidth Limiter',           'bwlimit.asp'],
2467                 null,
2468 /* NOCAT-BEGIN */
2469                 ['Captive Portal',              'splashd.asp'],
2470 /* NOCAT-END */
2471 /* NGINX-BEGIN */
2472                 ['Web Server',                  'nginx.asp'],
2473 /* NGINX-END */
2474 /* REMOVE-BEGIN
2475                 ['Scripts',                             'sc', 0, [
2476                         ['Startup',             'startup.asp'],
2477                         ['Shutdown',            'shutdown.asp'],
2478                         ['Firewall',            'firewall.asp'],
2479                         ['WAN Up',              'wanup.asp']
2480                         ] ],
2481 REMOVE-END */
2482 /* USB-BEGIN */
2483 // ---- !!TB - USB, FTP, Samba, Media Server
2484                 ['USB and NAS',                 'nas', 0, [
2485                         ['USB Support',                 'usb.asp']
2486 /* FTP-BEGIN */
2487                         ,['FTP Server',                 'ftp.asp']
2488 /* FTP-END */
2489 /* SAMBA-BEGIN */
2490                         ,['File Sharing',               'samba.asp']
2491 /* SAMBA-END */
2492 /* MEDIA-SRV-BEGIN */
2493                         ,['Media Server',               'media.asp']
2494 /* MEDIA-SRV-END */
2495 /* UPS-BEGIN */
2496                         ,['UPS Monitor',                'ups.asp']
2497 /* UPS-END */
2498 /* BT-BEGIN */
2499                         ,['BitTorrent Client',          'bittorrent.asp']
2500 /* BT-END */
2501                         ] ],
2502 /* USB-END */
2503 /* VPN-BEGIN */
2504                 ['VPN Tunneling',                       'vpn', 0, [
2505 /* OPENVPN-BEGIN */
2506                         ['OpenVPN Server',              'server.asp'],
2507                         ['OpenVPN Client',              'client.asp'],
2508 /* OPENVPN-END */
2509 /* PPTPD-BEGIN */
2510                         ['PPTP Server',                 'pptp-server.asp'],
2511                         ['PPTP Online',                 'pptp-online.asp'],
2512                         ['PPTP Client',                 'pptp.asp']
2513 /* PPTPD-END */
2514 /* TINC-BEGIN */
2515                         ,['Tinc Daemon',                'tinc.asp']
2516 /* TINC-END */
2517                 ] ],
2518 /* VPN-END */
2519                 null,
2520                 ['Administration',              'admin', 0, [
2521                         ['Admin Access',                'access.asp'],
2522                         ['TomatoAnon',                  'tomatoanon.asp'],
2523                         ['Bandwidth Monitoring',        'bwm.asp'],
2524                         ['IP Traffic Monitoring',       'iptraffic.asp'],
2525                         ['Buttons/LED',                 'buttons.asp'],
2526 /* CIFS-BEGIN */
2527                         ['CIFS Client',                 'cifs.asp'],
2528 /* CIFS-END */
2529 /* SDHC-BEGIN */
2530                         ['SDHC/MMC',                    'sdhc.asp'],
2531 /* SDHC-END */
2532                         ['Configuration',               'config.asp'],
2533                         ['Debugging',                   'debug.asp'],
2534 /* JFFS2-BEGIN */
2535                         ['JFFS',                        'jffs2.asp'],
2536 /* JFFS2-END */
2537 /* NFS-BEGIN */
2538                         ['NFS Server',                  'nfs.asp'],
2539 /* NFS-END */
2540 /* SNMP-BEGIN */
2541                         ['SNMP',                        'snmp.asp'],
2542 /* SNMP-END */
2543                         ['Logging',                     'log.asp'],
2544                         ['Scheduler',                   'sched.asp'],
2545                         ['Scripts',                     'scripts.asp'],
2546                         ['Upgrade',                     'upgrade.asp'] ] ],
2547                 null,
2548                 ['About',                       'about.asp'],
2549                 ['Reboot...',                   'javascript:reboot()'],
2550                 ['Shutdown...',                 'javascript:shutdown()'],
2551                 ['Logout',                      'javascript:logout()']
2552         ];
2553         var name, base;
2554         var i, j;
2555         var buf = [];
2556         var sm;
2557         var a, b, c;
2558         var on1;
2559         var cexp = get_config('web_mx', '').toLowerCase();
2561         name = myName();
2562         if (name == 'restrict-edit.asp') name = 'restrict.asp';
2563         if ((i = name.indexOf('-')) != -1) {
2564                 base = name.substring(0, i);
2565                 name = name.substring(i + 1, name.length);
2566         }
2567         else base = '';
2569         for (i = 0; i < menu.length; ++i) {
2570                 var m = menu[i];
2571                 if (!m) {
2572                         buf.push("<br>");
2573                         continue;
2574                 }
2575                 if (m.length == 2) {
2576                         buf.push('<a href="' + m[1] + '" class="indent1' + (((base == '') && (name == m[1])) ? ' active' : '') + '">' + m[0] + '</a>');
2577                 }
2578                 else {
2579                         if (base == m[1]) {
2580                                 b = name;
2581                         }
2582                         else {
2583                                 a = cookie.get('menu_' + m[1]);
2584                                 b = m[3][0][1];
2585                                 for (j = 0; j < m[3].length; ++j) {
2586                                         if (m[3][j][1] == a) {
2587                                                 b = a;
2588                                                 break;
2589                                         }
2590                                 }
2591                         }
2592                         a = m[1] + '-' + b;
2593                         if (a == 'status-overview.asp') a = '/';
2594                         on1 = (base == m[1]);
2595                         buf.push('<a href="' + a + '" class="indent1' + (on1 ? ' active' : '') + '">' + m[0] + '</a>');
2596                         if ((!on1) && (m[2] == 0) && (cexp.indexOf(m[1]) == -1)) continue;
2598                         for (j = 0; j < m[3].length; ++j) {
2599                                 sm = m[3][j];
2600                                 a = m[1] + '-' + sm[1];
2601                                 if (a == 'status-overview.asp') a = '/';
2602                                 buf.push('<a href="' + a + '" class="indent2' + (((on1) && (name == sm[1])) ? ' active' : '') + '">' + sm[0] + '</a>');
2603                         }
2604                 }
2605         }
2606         document.write(buf.join(''));
2608         if (base.length) {
2609                 if ((base == 'qos') && (name == 'detailed.asp')) name = 'view.asp';
2610                 cookie.set('menu_' + base, name);
2611         }
2614 function createFieldTable(flags, desc)
2616         var common;
2617         var i, n;
2618         var name;
2619         var id;
2620         var fields;
2621         var f;
2622         var a;
2623         var buf = [];
2624         var buf2;
2625         var id1;
2626         var tr;
2628         if ((flags.indexOf('noopen') == -1)) buf.push('<table class="fields">');
2629         for (desci = 0; desci < desc.length; ++desci) {
2630                 var v = desc[desci];
2632                 if (!v) {
2633                         buf.push('<tr><td colspan=2 class="spacer">&nbsp;</td></tr>');
2634                         continue;
2635                 }
2637                 if (v.ignore) continue;
2639                 buf.push('<tr');
2640                 if (v.rid) buf.push(' id="' + v.rid + '"');
2641                 if (v.hidden) buf.push(' style="display:none"');
2642                 buf.push('>');
2644                 if (v.text) {
2645                         if (v.title) {
2646                                 buf.push('<td class="title indent' + (v.indent || 1) + '">' + v.title + '</td><td class="content">' + v.text + '</td></tr>');
2647                         }
2648                         else {
2649                                 buf.push('<td colspan=2>' + v.text + '</td></tr>');
2650                         }
2651                         continue;
2652                 }
2654                 id1 = '';
2655                 buf2 = [];
2656                 buf2.push('<td class="content">');
2658                 if (v.multi) fields = v.multi;
2659                         else fields = [v];
2661                 for (n = 0; n < fields.length; ++n) {
2662                         f = fields[n];
2663                         if (f.prefix) buf2.push(f.prefix);
2665                         if ((f.type == 'radio') && (!f.id)) id = '_' + f.name + '_' + i;
2666                                 else id = (f.id ? f.id : ('_' + f.name));
2668                         if (id1 == '') id1 = id;
2670                         common = ' onchange="verifyFields(this, 1)" id="' + id + '"';
2671                         if (f.attrib) common += ' ' + f.attrib;
2672                         name = f.name ? (' name="' + f.name + '"') : '';
2674                         switch (f.type) {
2675                         case 'checkbox':
2676                                 buf2.push('<input type="checkbox"' + name + (f.value ? ' checked' : '') + ' onclick="verifyFields(this, 1)"' + common + '>');
2677                                 break;
2678                         case 'radio':
2679                                 buf2.push('<input type="radio"' + name + (f.value ? ' checked' : '') + ' onclick="verifyFields(this, 1)"' + common + '>');
2680                                 break;
2681                         case 'password':
2682                                 if (f.peekaboo) {
2683                                         switch (get_config('web_pb', '1')) {
2684                                         case '0':
2685                                                 f.type = 'text';
2686                                         case '2':
2687                                                 f.peekaboo = 0;
2688                                                 break;
2689                                         }
2690                                 }
2691                                 if (f.type == 'password') {
2692                                         common += ' autocomplete="off"';
2693                                         if (f.peekaboo) common += ' onfocus=\'peekaboo("' + id + '",1)\'';
2694                                 }
2695                                 // drop
2696                         case 'text':
2697                                 buf2.push('<input type="' + f.type + '"' + name + ' value="' + escapeHTML(UT(f.value)) + '" maxlength=' + f.maxlen + (f.size ? (' size=' + f.size) : '') + common + '>');
2698                                 break;
2699                         case 'clear':
2700                                 s += '';
2701                                 break;
2702                         case 'select':
2703                                 buf2.push('<select' + name + common + '>');
2704                                 for (i = 0; i < f.options.length; ++i) {
2705                                         a = f.options[i];
2706                                         if (a.length == 1) a.push(a[0]);
2707                                         buf2.push('<option value="' + a[0] + '"' + ((a[0] == f.value) ? ' selected' : '') + '>' + a[1] + '</option>');
2708                                 }
2709                                 buf2.push('</select>');
2710                                 break;
2711                         case 'textarea':
2712                                 buf2.push('<textarea' + name + common + (f.wrap ? (' wrap=' + f.wrap) : '') + '>' + escapeHTML(UT(f.value)) + '</textarea>');
2713                                 break;
2714                         default:
2715                                 if (f.custom) buf2.push(f.custom);
2716                                 break;
2717                         }
2718                         if (f.suffix) buf2.push(f.suffix);
2719                 }
2720                 buf2.push('</td>');
2722                 buf.push('<td class="title indent' + (v.indent ? v.indent : 1) + '">');
2723                 if (id1 != '') buf.push('<label for="' + id + '">' + v.title + '</label></td>');
2724                         else buf.push(+ v.title + '</td>');
2726                 buf.push(buf2.join(''));
2727                 buf.push('</tr>');
2728         }
2729         if ((!flags) || (flags.indexOf('noclose') == -1)) buf.push('</table>');
2730         document.write(buf.join(''));
2733 function peekaboo(id, show)
2735         try {
2736                 var o = document.createElement('INPUT');
2737                 var e = E(id);
2738                 var name = e.name;
2739                 o.type = show ? 'text' : 'password';
2740                 o.value = e.value;
2741                 o.size = e.size;
2742                 o.maxLength = e.maxLength;
2743                 o.autocomplete = e.autocomplete;
2744                 o.title = e.title;
2745                 o.disabled = e.disabled;
2746                 o.onchange = e.onchange;
2747                 e.parentNode.replaceChild(o, e);
2748                 e = null;
2749                 o.id = id;
2750                 o.name = name;
2752                 if (show) {
2753                         o.onblur = function(ev) { setTimeout('peekaboo("' + this.id + '", 0)', 0) };
2754                         setTimeout('try { E("' + id + '").focus() } catch (ex) { }', 0)
2755                 }
2756                 else {
2757                         o.onfocus = function(ev) { peekaboo(this.id, 1); };
2758                 }
2759         }
2760         catch (ex) {
2761 //              alert(ex);
2762         }
2764 /* REMOVE-BEGIN
2765 notes:
2766  - e.type= doesn't work in IE, ok in FF
2767  - may mess keyboard tabing (bad: IE; ok: FF, Opera)... setTimeout() delay seems to help a little.
2768 REMOVE-END */
2771 // -----------------------------------------------------------------------------
2773 function reloadPage()
2775         document.location.reload(1);
2778 function reboot()
2780         if (confirm("Reboot?")) form.submitHidden('tomato.cgi', { _reboot: 1, _commit: 0, _nvset: 0 });
2783 function shutdown()
2785         if (confirm("Shutdown?")) form.submitHidden('shutdown.cgi', { });
2788 function logout()
2790         form.submitHidden('logout.asp', { });
2793 // -----------------------------------------------------------------------------
2797 // ---- debug
2799 function isLocal()
2801         return location.href.search('file://') == 0;
2804 function console(s)