luci2: append markup for uci change indicator when rendering main menu
[project/luci2/ui.git] / luci2 / htdocs / luci2 / luci2.js
1 /*
2         LuCI2 - OpenWrt Web Interface
3
4         Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
5
6         Licensed under the Apache License, Version 2.0 (the "License");
7         you may not use this file except in compliance with the License.
8         You may obtain a copy of the License at
9
10                 http://www.apache.org/licenses/LICENSE-2.0
11 */
12
13 String.prototype.format = function()
14 {
15         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
16         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
17
18         function esc(s, r) {
19                 for( var i = 0; i < r.length; i += 2 )
20                         s = s.replace(r[i], r[i+1]);
21                 return s;
22         }
23
24         var str = this;
25         var out = '';
26         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27         var a = b = [], numSubstitutions = 0, numMatches = 0;
28
29         while ((a = re.exec(str)) != null)
30         {
31                 var m = a[1];
32                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33                 var pPrecision = a[6], pType = a[7];
34
35                 numMatches++;
36
37                 if (pType == '%')
38                 {
39                         subst = '%';
40                 }
41                 else
42                 {
43                         if (numSubstitutions < arguments.length)
44                         {
45                                 var param = arguments[numSubstitutions++];
46
47                                 var pad = '';
48                                 if (pPad && pPad.substr(0,1) == "'")
49                                         pad = leftpart.substr(1,1);
50                                 else if (pPad)
51                                         pad = pPad;
52
53                                 var justifyRight = true;
54                                 if (pJustify && pJustify === "-")
55                                         justifyRight = false;
56
57                                 var minLength = -1;
58                                 if (pMinLength)
59                                         minLength = parseInt(pMinLength);
60
61                                 var precision = -1;
62                                 if (pPrecision && pType == 'f')
63                                         precision = parseInt(pPrecision.substring(1));
64
65                                 var subst = param;
66
67                                 switch(pType)
68                                 {
69                                         case 'b':
70                                                 subst = (parseInt(param) || 0).toString(2);
71                                                 break;
72
73                                         case 'c':
74                                                 subst = String.fromCharCode(parseInt(param) || 0);
75                                                 break;
76
77                                         case 'd':
78                                                 subst = (parseInt(param) || 0);
79                                                 break;
80
81                                         case 'u':
82                                                 subst = Math.abs(parseInt(param) || 0);
83                                                 break;
84
85                                         case 'f':
86                                                 subst = (precision > -1)
87                                                         ? ((parseFloat(param) || 0.0)).toFixed(precision)
88                                                         : (parseFloat(param) || 0.0);
89                                                 break;
90
91                                         case 'o':
92                                                 subst = (parseInt(param) || 0).toString(8);
93                                                 break;
94
95                                         case 's':
96                                                 subst = param;
97                                                 break;
98
99                                         case 'x':
100                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
101                                                 break;
102
103                                         case 'X':
104                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
105                                                 break;
106
107                                         case 'h':
108                                                 subst = esc(param, html_esc);
109                                                 break;
110
111                                         case 'q':
112                                                 subst = esc(param, quot_esc);
113                                                 break;
114
115                                         case 'j':
116                                                 subst = String.serialize(param);
117                                                 break;
118
119                                         case 't':
120                                                 var td = 0;
121                                                 var th = 0;
122                                                 var tm = 0;
123                                                 var ts = (param || 0);
124
125                                                 if (ts > 60) {
126                                                         tm = Math.floor(ts / 60);
127                                                         ts = (ts % 60);
128                                                 }
129
130                                                 if (tm > 60) {
131                                                         th = Math.floor(tm / 60);
132                                                         tm = (tm % 60);
133                                                 }
134
135                                                 if (th > 24) {
136                                                         td = Math.floor(th / 24);
137                                                         th = (th % 24);
138                                                 }
139
140                                                 subst = (td > 0)
141                                                         ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142                                                         : '%dh %dm %ds'.format(th, tm, ts);
143
144                                                 break;
145
146                                         case 'm':
147                                                 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148                                                 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
149
150                                                 var i = 0;
151                                                 var val = parseFloat(param || 0);
152                                                 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
153
154                                                 for (i = 0; (i < units.length) && (val > mf); i++)
155                                                         val /= mf;
156
157                                                 subst = val.toFixed(pr) + ' ' + units[i];
158                                                 break;
159                                 }
160
161                                 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
162
163                                 if (minLength > 0 && pad.length > 0)
164                                         for (var i = 0; i < (minLength - subst.length); i++)
165                                                 subst = justifyRight ? (pad + subst) : (subst + pad);
166                         }
167                 }
168
169                 out += leftpart + subst;
170                 str = str.substr(m.length);
171         }
172
173         return out + str;
174 }
175
176 function LuCI2()
177 {
178         var _luci2 = this;
179
180         var Class = function() { };
181
182         Class.extend = function(properties)
183         {
184                 Class.initializing = true;
185
186                 var prototype = new this();
187                 var superprot = this.prototype;
188
189                 Class.initializing = false;
190
191                 $.extend(prototype, properties, {
192                         callSuper: function() {
193                                 var args = [ ];
194                                 var meth = arguments[0];
195
196                                 if (typeof(superprot[meth]) != 'function')
197                                         return undefined;
198
199                                 for (var i = 1; i < arguments.length; i++)
200                                         args.push(arguments[i]);
201
202                                 return superprot[meth].apply(this, args);
203                         }
204                 });
205
206                 function _class()
207                 {
208                         this.options = arguments[0] || { };
209
210                         if (!Class.initializing && typeof(this.init) == 'function')
211                                 this.init.apply(this, arguments);
212                 }
213
214                 _class.prototype = prototype;
215                 _class.prototype.constructor = _class;
216
217                 _class.extend = Class.extend;
218
219                 return _class;
220         };
221
222         this.defaults = function(obj, def)
223         {
224                 for (var key in def)
225                         if (typeof(obj[key]) == 'undefined')
226                                 obj[key] = def[key];
227
228                 return obj;
229         };
230
231         this.isDeferred = function(x)
232         {
233                 return (typeof(x) == 'object' &&
234                         typeof(x.then) == 'function' &&
235                         typeof(x.promise) == 'function');
236         };
237
238         this.deferrable = function()
239         {
240                 if (this.isDeferred(arguments[0]))
241                         return arguments[0];
242
243                 var d = $.Deferred();
244                     d.resolve.apply(d, arguments);
245
246                 return d.promise();
247         };
248
249         this.i18n = {
250
251                 loaded: false,
252                 catalog: { },
253                 plural:  function(n) { return 0 + (n != 1) },
254
255                 init: function() {
256                         if (_luci2.i18n.loaded)
257                                 return;
258
259                         var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260                         var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
261
262                         for (var i = 0; i < langs.length; i++)
263                                 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
264                                         async:    false,
265                                         cache:    true,
266                                         dataType: 'json',
267                                         success:  function(data) {
268                                                 $.extend(_luci2.i18n.catalog, data);
269
270                                                 var pe = _luci2.i18n.catalog[''];
271                                                 if (pe)
272                                                 {
273                                                         delete _luci2.i18n.catalog[''];
274                                                         try {
275                                                                 var pf = new Function('n', 'return 0 + (' + pe + ')');
276                                                                 _luci2.i18n.plural = pf;
277                                                         } catch (e) { };
278                                                 }
279                                         }
280                                 });
281
282                         _luci2.i18n.loaded = true;
283                 }
284
285         };
286
287         this.tr = function(msgid)
288         {
289                 _luci2.i18n.init();
290
291                 var msgstr = _luci2.i18n.catalog[msgid];
292
293                 if (typeof(msgstr) == 'undefined')
294                         return msgid;
295                 else if (typeof(msgstr) == 'string')
296                         return msgstr;
297                 else
298                         return msgstr[0];
299         };
300
301         this.trp = function(msgid, msgid_plural, count)
302         {
303                 _luci2.i18n.init();
304
305                 var msgstr = _luci2.i18n.catalog[msgid];
306
307                 if (typeof(msgstr) == 'undefined')
308                         return (count == 1) ? msgid : msgid_plural;
309                 else if (typeof(msgstr) == 'string')
310                         return msgstr;
311                 else
312                         return msgstr[_luci2.i18n.plural(count)];
313         };
314
315         this.trc = function(msgctx, msgid)
316         {
317                 _luci2.i18n.init();
318
319                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
320
321                 if (typeof(msgstr) == 'undefined')
322                         return msgid;
323                 else if (typeof(msgstr) == 'string')
324                         return msgstr;
325                 else
326                         return msgstr[0];
327         };
328
329         this.trcp = function(msgctx, msgid, msgid_plural, count)
330         {
331                 _luci2.i18n.init();
332
333                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
334
335                 if (typeof(msgstr) == 'undefined')
336                         return (count == 1) ? msgid : msgid_plural;
337                 else if (typeof(msgstr) == 'string')
338                         return msgstr;
339                 else
340                         return msgstr[_luci2.i18n.plural(count)];
341         };
342
343         this.setHash = function(key, value)
344         {
345                 var h = '';
346                 var data = this.getHash(undefined);
347
348                 if (typeof(value) == 'undefined')
349                         delete data[key];
350                 else
351                         data[key] = value;
352
353                 var keys = [ ];
354                 for (var k in data)
355                         keys.push(k);
356
357                 keys.sort();
358
359                 for (var i = 0; i < keys.length; i++)
360                 {
361                         if (i > 0)
362                                 h += ',';
363
364                         h += keys[i] + ':' + data[keys[i]];
365                 }
366
367                 if (h.length)
368                         location.hash = '#' + h;
369                 else
370                         location.hash = '';
371         };
372
373         this.getHash = function(key)
374         {
375                 var data = { };
376                 var tuples = (location.hash || '#').substring(1).split(/,/);
377
378                 for (var i = 0; i < tuples.length; i++)
379                 {
380                         var tuple = tuples[i].split(/:/);
381                         if (tuple.length == 2)
382                                 data[tuple[0]] = tuple[1];
383                 }
384
385                 if (typeof(key) != 'undefined')
386                         return data[key];
387
388                 return data;
389         };
390
391         this.toArray = function(x)
392         {
393                 switch (typeof(x))
394                 {
395                 case 'number':
396                 case 'boolean':
397                         return [ x ];
398
399                 case 'string':
400                         var r = [ ];
401                         var l = x.split(/\s+/);
402                         for (var i = 0; i < l.length; i++)
403                                 if (l[i].length > 0)
404                                         r.push(l[i]);
405                         return r;
406
407                 case 'object':
408                         if ($.isArray(x))
409                         {
410                                 var r = [ ];
411                                 for (var i = 0; i < x.length; i++)
412                                         r.push(x[i]);
413                                 return r;
414                         }
415                         else if ($.isPlainObject(x))
416                         {
417                                 var r = [ ];
418                                 for (var k in x)
419                                         if (x.hasOwnProperty(k))
420                                                 r.push(k);
421                                 return r.sort();
422                         }
423                 }
424
425                 return [ ];
426         };
427
428         this.toObject = function(x)
429         {
430                 switch (typeof(x))
431                 {
432                 case 'number':
433                 case 'boolean':
434                         return { x: true };
435
436                 case 'string':
437                         var r = { };
438                         var l = x.split(/\x+/);
439                         for (var i = 0; i < l.length; i++)
440                                 if (l[i].length > 0)
441                                         r[l[i]] = true;
442                         return r;
443
444                 case 'object':
445                         if ($.isArray(x))
446                         {
447                                 var r = { };
448                                 for (var i = 0; i < x.length; i++)
449                                         r[x[i]] = true;
450                                 return r;
451                         }
452                         else if ($.isPlainObject(x))
453                         {
454                                 return x;
455                         }
456                 }
457
458                 return { };
459         };
460
461         this.filterArray = function(array, item)
462         {
463                 if (!$.isArray(array))
464                         return [ ];
465
466                 for (var i = 0; i < array.length; i++)
467                         if (array[i] === item)
468                                 array.splice(i--, 1);
469
470                 return array;
471         };
472
473         this.toClassName = function(str, suffix)
474         {
475                 var n = '';
476                 var l = str.split(/[\/.]/);
477
478                 for (var i = 0; i < l.length; i++)
479                         if (l[i].length > 0)
480                                 n += l[i].charAt(0).toUpperCase() + l[i].substr(1).toLowerCase();
481
482                 if (typeof(suffix) == 'string')
483                         n += suffix;
484
485                 return n;
486         };
487
488         this.globals = {
489                 timeout:  15000,
490                 resource: '/luci2',
491                 sid:      '00000000000000000000000000000000'
492         };
493
494         this.rpc = {
495
496                 _id: 1,
497                 _batch: undefined,
498                 _requests: { },
499
500                 _call: function(req, cb)
501                 {
502                         return $.ajax('/ubus', {
503                                 cache:       false,
504                                 contentType: 'application/json',
505                                 data:        JSON.stringify(req),
506                                 dataType:    'json',
507                                 type:        'POST',
508                                 timeout:     _luci2.globals.timeout,
509                                 _rpc_req:   req
510                         }).then(cb, cb);
511                 },
512
513                 _list_cb: function(msg)
514                 {
515                         var list = msg.result;
516
517                         /* verify message frame */
518                         if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id || !$.isArray(list))
519                                 list = [ ];
520
521                         return $.Deferred().resolveWith(this, [ list ]);
522                 },
523
524                 _call_cb: function(msg)
525                 {
526                         var data = [ ];
527                         var type = Object.prototype.toString;
528                         var reqs = this._rpc_req;
529
530                         if (!$.isArray(reqs))
531                         {
532                                 msg = [ msg ];
533                                 reqs = [ reqs ];
534                         }
535
536                         for (var i = 0; i < msg.length; i++)
537                         {
538                                 /* fetch related request info */
539                                 var req = _luci2.rpc._requests[reqs[i].id];
540                                 if (typeof(req) != 'object')
541                                         throw 'No related request for JSON response';
542
543                                 /* fetch response attribute and verify returned type */
544                                 var ret = undefined;
545
546                                 /* verify message frame */
547                                 if (typeof(msg[i]) == 'object' && msg[i].jsonrpc == '2.0')
548                                         if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
549                                                 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
550
551                                 if (req.expect)
552                                 {
553                                         for (var key in req.expect)
554                                         {
555                                                 if (typeof(ret) != 'undefined' && key != '')
556                                                         ret = ret[key];
557
558                                                 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
559                                                         ret = req.expect[key];
560
561                                                 break;
562                                         }
563                                 }
564
565                                 /* apply filter */
566                                 if (typeof(req.filter) == 'function')
567                                 {
568                                         req.priv[0] = ret;
569                                         req.priv[1] = req.params;
570                                         ret = req.filter.apply(_luci2.rpc, req.priv);
571                                 }
572
573                                 /* store response data */
574                                 if (typeof(req.index) == 'number')
575                                         data[req.index] = ret;
576                                 else
577                                         data = ret;
578
579                                 /* delete request object */
580                                 delete _luci2.rpc._requests[reqs[i].id];
581                         }
582
583                         return $.Deferred().resolveWith(this, [ data ]);
584                 },
585
586                 list: function()
587                 {
588                         var params = [ ];
589                         for (var i = 0; i < arguments.length; i++)
590                                 params[i] = arguments[i];
591
592                         var msg = {
593                                 jsonrpc: '2.0',
594                                 id:      this._id++,
595                                 method:  'list',
596                                 params:  (params.length > 0) ? params : undefined
597                         };
598
599                         return this._call(msg, this._list_cb);
600                 },
601
602                 batch: function()
603                 {
604                         if (!$.isArray(this._batch))
605                                 this._batch = [ ];
606                 },
607
608                 flush: function()
609                 {
610                         if (!$.isArray(this._batch))
611                                 return _luci2.deferrable([ ]);
612
613                         var req = this._batch;
614                         delete this._batch;
615
616                         /* call rpc */
617                         return this._call(req, this._call_cb);
618                 },
619
620                 declare: function(options)
621                 {
622                         var _rpc = this;
623
624                         return function() {
625                                 /* build parameter object */
626                                 var p_off = 0;
627                                 var params = { };
628                                 if ($.isArray(options.params))
629                                         for (p_off = 0; p_off < options.params.length; p_off++)
630                                                 params[options.params[p_off]] = arguments[p_off];
631
632                                 /* all remaining arguments are private args */
633                                 var priv = [ undefined, undefined ];
634                                 for (; p_off < arguments.length; p_off++)
635                                         priv.push(arguments[p_off]);
636
637                                 /* store request info */
638                                 var req = _rpc._requests[_rpc._id] = {
639                                         expect: options.expect,
640                                         filter: options.filter,
641                                         params: params,
642                                         priv:   priv
643                                 };
644
645                                 /* build message object */
646                                 var msg = {
647                                         jsonrpc: '2.0',
648                                         id:      _rpc._id++,
649                                         method:  'call',
650                                         params:  [
651                                                 _luci2.globals.sid,
652                                                 options.object,
653                                                 options.method,
654                                                 params
655                                         ]
656                                 };
657
658                                 /* when a batch is in progress then store index in request data
659                                  * and push message object onto the stack */
660                                 if ($.isArray(_rpc._batch))
661                                 {
662                                         req.index = _rpc._batch.push(msg) - 1;
663                                         return _luci2.deferrable(msg);
664                                 }
665
666                                 /* call rpc */
667                                 return _rpc._call(msg, _rpc._call_cb);
668                         };
669                 }
670         };
671
672         this.UCIContext = Class.extend({
673
674                 init: function()
675                 {
676                         this.state = {
677                                 newid:   0,
678                                 values:  { },
679                                 creates: { },
680                                 changes: { },
681                                 deletes: { },
682                                 reorder: { }
683                         };
684                 },
685
686                 _load: _luci2.rpc.declare({
687                         object: 'uci',
688                         method: 'get',
689                         params: [ 'config' ],
690                         expect: { values: { } }
691                 }),
692
693                 _order: _luci2.rpc.declare({
694                         object: 'uci',
695                         method: 'order',
696                         params: [ 'config', 'sections' ]
697                 }),
698
699                 _add: _luci2.rpc.declare({
700                         object: 'uci',
701                         method: 'add',
702                         params: [ 'config', 'type', 'name', 'values' ],
703                         expect: { section: '' }
704                 }),
705
706                 _set: _luci2.rpc.declare({
707                         object: 'uci',
708                         method: 'set',
709                         params: [ 'config', 'section', 'values' ]
710                 }),
711
712                 _delete: _luci2.rpc.declare({
713                         object: 'uci',
714                         method: 'delete',
715                         params: [ 'config', 'section', 'options' ]
716                 }),
717
718                 load: function(packages)
719                 {
720                         var self = this;
721                         var seen = { };
722                         var pkgs = [ ];
723
724                         if (!$.isArray(packages))
725                                 packages = [ packages ];
726
727                         _luci2.rpc.batch();
728
729                         for (var i = 0; i < packages.length; i++)
730                                 if (!seen[packages[i]])
731                                 {
732                                         pkgs.push(packages[i]);
733                                         seen[packages[i]] = true;
734                                         self._load(packages[i]);
735                                 }
736
737                         return _luci2.rpc.flush().then(function(responses) {
738                                 for (var i = 0; i < responses.length; i++)
739                                         self.state.values[pkgs[i]] = responses[i];
740
741                                 return pkgs;
742                         });
743                 },
744
745                 unload: function(packages)
746                 {
747                         if (!$.isArray(packages))
748                                 packages = [ packages ];
749
750                         for (var i = 0; i < packages.length; i++)
751                         {
752                                 delete this.state.values[packages[i]];
753                                 delete this.state.creates[packages[i]];
754                                 delete this.state.changes[packages[i]];
755                                 delete this.state.deletes[packages[i]];
756                         }
757                 },
758
759                 add: function(conf, type, name)
760                 {
761                         var c = this.state.creates;
762                         var s = '.new.%d'.format(this.state.newid++);
763
764                         if (!c[conf])
765                                 c[conf] = { };
766
767                         c[conf][s] = {
768                                 '.type':      type,
769                                 '.name':      s,
770                                 '.create':    name,
771                                 '.anonymous': !name,
772                                 '.index':     1000 + this.state.newid
773                         };
774
775                         return s;
776                 },
777
778                 remove: function(conf, sid)
779                 {
780                         var n = this.state.creates;
781                         var c = this.state.changes;
782                         var d = this.state.deletes;
783
784                         /* requested deletion of a just created section */
785                         if (sid.indexOf('.new.') == 0)
786                         {
787                                 if (n[conf])
788                                         delete n[conf][sid];
789                         }
790                         else
791                         {
792                                 if (c[conf])
793                                         delete c[conf][sid];
794
795                                 if (!d[conf])
796                                         d[conf] = { };
797
798                                 d[conf][sid] = true;
799                         }
800                 },
801
802                 sections: function(conf, type, cb)
803                 {
804                         var sa = [ ];
805                         var v = this.state.values[conf];
806                         var n = this.state.creates[conf];
807                         var c = this.state.changes[conf];
808                         var d = this.state.deletes[conf];
809
810                         if (!v)
811                                 return sa;
812
813                         for (var s in v)
814                                 if (!d || d[s] !== true)
815                                         if (!type || v[s]['.type'] == type)
816                                                 sa.push($.extend({ }, v[s], c ? c[s] : undefined));
817
818                         if (n)
819                                 for (var s in n)
820                                         if (!type || n[s]['.type'] == type)
821                                                 sa.push(n[s]);
822
823                         sa.sort(function(a, b) {
824                                 return a['.index'] - b['.index'];
825                         });
826
827                         for (var i = 0; i < sa.length; i++)
828                                 sa[i]['.index'] = i;
829
830                         if (typeof(cb) == 'function')
831                                 for (var i = 0; i < sa.length; i++)
832                                         cb.call(this, sa[i], sa[i]['.name']);
833
834                         return sa;
835                 },
836
837                 get: function(conf, sid, opt)
838                 {
839                         var v = this.state.values;
840                         var n = this.state.creates;
841                         var c = this.state.changes;
842                         var d = this.state.deletes;
843
844                         if (typeof(sid) == 'undefined')
845                                 return undefined;
846
847                         /* requested option in a just created section */
848                         if (sid.indexOf('.new.') == 0)
849                         {
850                                 if (!n[conf])
851                                         return undefined;
852
853                                 if (typeof(opt) == 'undefined')
854                                         return n[conf][sid];
855
856                                 return n[conf][sid][opt];
857                         }
858
859                         /* requested an option value */
860                         if (typeof(opt) != 'undefined')
861                         {
862                                 /* check whether option was deleted */
863                                 if (d[conf] && d[conf][sid])
864                                 {
865                                         if (d[conf][sid] === true)
866                                                 return undefined;
867
868                                         for (var i = 0; i < d[conf][sid].length; i++)
869                                                 if (d[conf][sid][i] == opt)
870                                                         return undefined;
871                                 }
872
873                                 /* check whether option was changed */
874                                 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
875                                         return c[conf][sid][opt];
876
877                                 /* return base value */
878                                 if (v[conf] && v[conf][sid])
879                                         return v[conf][sid][opt];
880
881                                 return undefined;
882                         }
883
884                         /* requested an entire section */
885                         if (v[conf])
886                                 return v[conf][sid];
887
888                         return undefined;
889                 },
890
891                 set: function(conf, sid, opt, val)
892                 {
893                         var n = this.state.creates;
894                         var c = this.state.changes;
895                         var d = this.state.deletes;
896
897                         if (typeof(sid) == 'undefined' ||
898                             typeof(opt) == 'undefined' ||
899                             opt.charAt(0) == '.')
900                                 return;
901
902                         if (sid.indexOf('.new.') == 0)
903                         {
904                                 if (n[conf] && n[conf][sid])
905                                 {
906                                         if (typeof(val) != 'undefined')
907                                                 n[conf][sid][opt] = val;
908                                         else
909                                                 delete n[conf][sid][opt];
910                                 }
911                         }
912                         else if (typeof(val) != 'undefined')
913                         {
914                                 /* do not set within deleted section */
915                                 if (d[conf] && d[conf][sid] === true)
916                                         return;
917
918                                 if (!c[conf])
919                                         c[conf] = { };
920
921                                 if (!c[conf][sid])
922                                         c[conf][sid] = { };
923
924                                 /* undelete option */
925                                 if (d[conf] && d[conf][sid])
926                                         d[conf][sid] = _luci2.filterArray(d[conf][sid], opt);
927
928                                 c[conf][sid][opt] = val;
929                         }
930                         else
931                         {
932                                 if (!d[conf])
933                                         d[conf] = { };
934
935                                 if (!d[conf][sid])
936                                         d[conf][sid] = [ ];
937
938                                 if (d[conf][sid] !== true)
939                                         d[conf][sid].push(opt);
940                         }
941                 },
942
943                 unset: function(conf, sid, opt)
944                 {
945                         return this.set(conf, sid, opt, undefined);
946                 },
947
948                 _reload: function()
949                 {
950                         var pkgs = [ ];
951
952                         for (var pkg in this.state.values)
953                                 pkgs.push(pkg);
954
955                         this.init();
956
957                         return this.load(pkgs);
958                 },
959
960                 _reorder: function()
961                 {
962                         var v = this.state.values;
963                         var n = this.state.creates;
964                         var r = this.state.reorder;
965
966                         if ($.isEmptyObject(r))
967                                 return _luci2.deferrable();
968
969                         _luci2.rpc.batch();
970
971                         /*
972                          gather all created and existing sections, sort them according
973                          to their index value and issue an uci order call
974                         */
975                         for (var c in r)
976                         {
977                                 var o = [ ];
978
979                                 if (n && n[c])
980                                         for (var s in n[c])
981                                                 o.push(n[c][s]);
982
983                                 for (var s in v[c])
984                                         o.push(v[c][s]);
985
986                                 if (o.length > 0)
987                                 {
988                                         o.sort(function(a, b) {
989                                                 return (a['.index'] - b['.index']);
990                                         });
991
992                                         var sids = [ ];
993
994                                         for (var i = 0; i < o.length; i++)
995                                                 sids.push(o[i]['.name']);
996
997                                         this._order(c, sids);
998                                 }
999                         }
1000
1001                         this.state.reorder = { };
1002                         return _luci2.rpc.flush();
1003                 },
1004
1005                 swap: function(conf, sid1, sid2)
1006                 {
1007                         var s1 = this.get(conf, sid1);
1008                         var s2 = this.get(conf, sid2);
1009                         var n1 = s1 ? s1['.index'] : NaN;
1010                         var n2 = s2 ? s2['.index'] : NaN;
1011
1012                         if (isNaN(n1) || isNaN(n2))
1013                                 return false;
1014
1015                         s1['.index'] = n2;
1016                         s2['.index'] = n1;
1017
1018                         this.state.reorder[conf] = true;
1019
1020                         return true;
1021                 },
1022
1023                 save: function()
1024                 {
1025                         _luci2.rpc.batch();
1026
1027                         var self = this;
1028                         var snew = [ ];
1029
1030                         if (self.state.creates)
1031                                 for (var c in self.state.creates)
1032                                         for (var s in self.state.creates[c])
1033                                         {
1034                                                 var r = {
1035                                                         config: c,
1036                                                         values: { }
1037                                                 };
1038
1039                                                 for (var k in self.state.creates[c][s])
1040                                                 {
1041                                                         if (k == '.type')
1042                                                                 r.type = self.state.creates[c][s][k];
1043                                                         else if (k == '.create')
1044                                                                 r.name = self.state.creates[c][s][k];
1045                                                         else if (k.charAt(0) != '.')
1046                                                                 r.values[k] = self.state.creates[c][s][k];
1047                                                 }
1048
1049                                                 snew.push(self.state.creates[c][s]);
1050
1051                                                 self._add(r.config, r.type, r.name, r.values);
1052                                         }
1053
1054                         if (self.state.changes)
1055                                 for (var c in self.state.changes)
1056                                         for (var s in self.state.changes[c])
1057                                                 self._set(c, s, self.state.changes[c][s]);
1058
1059                         if (self.state.deletes)
1060                                 for (var c in self.state.deletes)
1061                                         for (var s in self.state.deletes[c])
1062                                         {
1063                                                 var o = self.state.deletes[c][s];
1064                                                 self._delete(c, s, (o === true) ? undefined : o);
1065                                         }
1066
1067                         return _luci2.rpc.flush().then(function(responses) {
1068                                 /*
1069                                  array "snew" holds references to the created uci sections,
1070                                  use it to assign the returned names of the new sections
1071                                 */
1072                                 for (var i = 0; i < snew.length; i++)
1073                                         snew[i]['.name'] = responses[i];
1074
1075                                 return self._reorder();
1076                         });
1077                 },
1078
1079                 _apply: _luci2.rpc.declare({
1080                         object: 'uci',
1081                         method: 'apply',
1082                         params: [ 'timeout', 'rollback' ]
1083                 }),
1084
1085                 _confirm: _luci2.rpc.declare({
1086                         object: 'uci',
1087                         method: 'confirm'
1088                 }),
1089
1090                 apply: function(timeout)
1091                 {
1092                         var self = this;
1093                         var date = new Date();
1094                         var deferred = $.Deferred();
1095
1096                         if (typeof(timeout) != 'number' || timeout < 1)
1097                                 timeout = 10;
1098
1099                         self._apply(timeout, true).then(function(rv) {
1100                                 if (rv != 0)
1101                                 {
1102                                         deferred.rejectWith(self, [ rv ]);
1103                                         return;
1104                                 }
1105
1106                                 var try_deadline = date.getTime() + 1000 * timeout;
1107                                 var try_confirm = function()
1108                                 {
1109                                         return self._confirm().then(function(rv) {
1110                                                 if (rv != 0)
1111                                                 {
1112                                                         if (date.getTime() < try_deadline)
1113                                                                 window.setTimeout(try_confirm, 250);
1114                                                         else
1115                                                                 deferred.rejectWith(self, [ rv ]);
1116
1117                                                         return;
1118                                                 }
1119
1120                                                 deferred.resolveWith(self, [ rv ]);
1121                                         });
1122                                 };
1123
1124                                 window.setTimeout(try_confirm, 1000);
1125                         });
1126
1127                         return deferred;
1128                 },
1129
1130                 changes: _luci2.rpc.declare({
1131                         object: 'uci',
1132                         method: 'changes',
1133                         expect: { changes: { } }
1134                 }),
1135
1136                 readable: function(conf)
1137                 {
1138                         return _luci2.session.hasACL('uci', conf, 'read');
1139                 },
1140
1141                 writable: function(conf)
1142                 {
1143                         return _luci2.session.hasACL('uci', conf, 'write');
1144                 }
1145         });
1146
1147         this.uci = new this.UCIContext();
1148
1149         this.wireless = {
1150                 listDeviceNames: _luci2.rpc.declare({
1151                         object: 'iwinfo',
1152                         method: 'devices',
1153                         expect: { 'devices': [ ] },
1154                         filter: function(data) {
1155                                 data.sort();
1156                                 return data;
1157                         }
1158                 }),
1159
1160                 getDeviceStatus: _luci2.rpc.declare({
1161                         object: 'iwinfo',
1162                         method: 'info',
1163                         params: [ 'device' ],
1164                         expect: { '': { } },
1165                         filter: function(data, params) {
1166                                 if (!$.isEmptyObject(data))
1167                                 {
1168                                         data['device'] = params['device'];
1169                                         return data;
1170                                 }
1171                                 return undefined;
1172                         }
1173                 }),
1174
1175                 getAssocList: _luci2.rpc.declare({
1176                         object: 'iwinfo',
1177                         method: 'assoclist',
1178                         params: [ 'device' ],
1179                         expect: { results: [ ] },
1180                         filter: function(data, params) {
1181                                 for (var i = 0; i < data.length; i++)
1182                                         data[i]['device'] = params['device'];
1183
1184                                 data.sort(function(a, b) {
1185                                         if (a.bssid < b.bssid)
1186                                                 return -1;
1187                                         else if (a.bssid > b.bssid)
1188                                                 return 1;
1189                                         else
1190                                                 return 0;
1191                                 });
1192
1193                                 return data;
1194                         }
1195                 }),
1196
1197                 getWirelessStatus: function() {
1198                         return this.listDeviceNames().then(function(names) {
1199                                 _luci2.rpc.batch();
1200
1201                                 for (var i = 0; i < names.length; i++)
1202                                         _luci2.wireless.getDeviceStatus(names[i]);
1203
1204                                 return _luci2.rpc.flush();
1205                         }).then(function(networks) {
1206                                 var rv = { };
1207
1208                                 var phy_attrs = [
1209                                         'country', 'channel', 'frequency', 'frequency_offset',
1210                                         'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1211                                 ];
1212
1213                                 var net_attrs = [
1214                                         'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1215                                         'signal', 'noise', 'bitrate', 'encryption'
1216                                 ];
1217
1218                                 for (var i = 0; i < networks.length; i++)
1219                                 {
1220                                         var phy = rv[networks[i].phy] || (
1221                                                 rv[networks[i].phy] = { networks: [ ] }
1222                                         );
1223
1224                                         var net = {
1225                                                 device: networks[i].device
1226                                         };
1227
1228                                         for (var j = 0; j < phy_attrs.length; j++)
1229                                                 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1230
1231                                         for (var j = 0; j < net_attrs.length; j++)
1232                                                 net[net_attrs[j]] = networks[i][net_attrs[j]];
1233
1234                                         phy.networks.push(net);
1235                                 }
1236
1237                                 return rv;
1238                         });
1239                 },
1240
1241                 getAssocLists: function()
1242                 {
1243                         return this.listDeviceNames().then(function(names) {
1244                                 _luci2.rpc.batch();
1245
1246                                 for (var i = 0; i < names.length; i++)
1247                                         _luci2.wireless.getAssocList(names[i]);
1248
1249                                 return _luci2.rpc.flush();
1250                         }).then(function(assoclists) {
1251                                 var rv = [ ];
1252
1253                                 for (var i = 0; i < assoclists.length; i++)
1254                                         for (var j = 0; j < assoclists[i].length; j++)
1255                                                 rv.push(assoclists[i][j]);
1256
1257                                 return rv;
1258                         });
1259                 },
1260
1261                 formatEncryption: function(enc)
1262                 {
1263                         var format_list = function(l, s)
1264                         {
1265                                 var rv = [ ];
1266                                 for (var i = 0; i < l.length; i++)
1267                                         rv.push(l[i].toUpperCase());
1268                                 return rv.join(s ? s : ', ');
1269                         }
1270
1271                         if (!enc || !enc.enabled)
1272                                 return _luci2.tr('None');
1273
1274                         if (enc.wep)
1275                         {
1276                                 if (enc.wep.length == 2)
1277                                         return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1278                                 else if (enc.wep[0] == 'shared')
1279                                         return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1280                                 else
1281                                         return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1282                         }
1283                         else if (enc.wpa)
1284                         {
1285                                 if (enc.wpa.length == 2)
1286                                         return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1287                                                 format_list(enc.authentication, '/'),
1288                                                 format_list(enc.ciphers, ', ')
1289                                         );
1290                                 else if (enc.wpa[0] == 2)
1291                                         return 'WPA2 %s (%s)'.format(
1292                                                 format_list(enc.authentication, '/'),
1293                                                 format_list(enc.ciphers, ', ')
1294                                         );
1295                                 else
1296                                         return 'WPA %s (%s)'.format(
1297                                                 format_list(enc.authentication, '/'),
1298                                                 format_list(enc.ciphers, ', ')
1299                                         );
1300                         }
1301
1302                         return _luci2.tr('Unknown');
1303                 }
1304         };
1305
1306         this.firewall = {
1307                 getZoneColor: function(zone)
1308                 {
1309                         if ($.isPlainObject(zone))
1310                                 zone = zone.name;
1311
1312                         if (zone == 'lan')
1313                                 return '#90f090';
1314                         else if (zone == 'wan')
1315                                 return '#f09090';
1316
1317                         for (var i = 0, hash = 0;
1318                                  i < zone.length;
1319                                  hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1320
1321                         for (var i = 0, color = '#';
1322                                  i < 3;
1323                                  color += ('00' + ((hash >> i++ * 8) & 0xFF).tostring(16)).slice(-2));
1324
1325                         return color;
1326                 },
1327
1328                 findZoneByNetwork: function(network)
1329                 {
1330                         var self = this;
1331                         var zone = undefined;
1332
1333                         return _luci2.uci.sections('firewall', 'zone', function(z) {
1334                                 if (!z.name || !z.network)
1335                                         return;
1336
1337                                 if (!$.isArray(z.network))
1338                                         z.network = z.network.split(/\s+/);
1339
1340                                 for (var i = 0; i < z.network.length; i++)
1341                                 {
1342                                         if (z.network[i] == network)
1343                                         {
1344                                                 zone = z;
1345                                                 break;
1346                                         }
1347                                 }
1348                         }).then(function() {
1349                                 if (zone)
1350                                         zone.color = self.getZoneColor(zone);
1351
1352                                 return zone;
1353                         });
1354                 }
1355         };
1356
1357         this.NetworkModel = {
1358                 _device_blacklist: [
1359                         /^gre[0-9]+$/,
1360                         /^gretap[0-9]+$/,
1361                         /^ifb[0-9]+$/,
1362                         /^ip6tnl[0-9]+$/,
1363                         /^sit[0-9]+$/,
1364                         /^wlan[0-9]+\.sta[0-9]+$/
1365                 ],
1366
1367                 _cache_functions: [
1368                         'protolist', 0, _luci2.rpc.declare({
1369                                 object: 'network',
1370                                 method: 'get_proto_handlers',
1371                                 expect: { '': { } }
1372                         }),
1373                         'ifstate', 1, _luci2.rpc.declare({
1374                                 object: 'network.interface',
1375                                 method: 'dump',
1376                                 expect: { 'interface': [ ] }
1377                         }),
1378                         'devstate', 2, _luci2.rpc.declare({
1379                                 object: 'network.device',
1380                                 method: 'status',
1381                                 expect: { '': { } }
1382                         }),
1383                         'wifistate', 0, _luci2.rpc.declare({
1384                                 object: 'network.wireless',
1385                                 method: 'status',
1386                                 expect: { '': { } }
1387                         }),
1388                         'bwstate', 2, _luci2.rpc.declare({
1389                                 object: 'luci2.network.bwmon',
1390                                 method: 'statistics',
1391                                 expect: { 'statistics': { } }
1392                         }),
1393                         'devlist', 2, _luci2.rpc.declare({
1394                                 object: 'luci2.network',
1395                                 method: 'device_list',
1396                                 expect: { 'devices': [ ] }
1397                         }),
1398                         'swlist', 0, _luci2.rpc.declare({
1399                                 object: 'luci2.network',
1400                                 method: 'switch_list',
1401                                 expect: { 'switches': [ ] }
1402                         })
1403                 ],
1404
1405                 _fetch_protocol: function(proto)
1406                 {
1407                         var url = _luci2.globals.resource + '/proto/' + proto + '.js';
1408                         var self = _luci2.NetworkModel;
1409
1410                         var def = $.Deferred();
1411
1412                         $.ajax(url, {
1413                                 method: 'GET',
1414                                 cache: true,
1415                                 dataType: 'text'
1416                         }).then(function(data) {
1417                                 try {
1418                                         var protoConstructorSource = (
1419                                                 '(function(L, $) { ' +
1420                                                         'return %s' +
1421                                                 '})(_luci2, $);\n\n' +
1422                                                 '//@ sourceURL=%s'
1423                                         ).format(data, url);
1424
1425                                         var protoClass = eval(protoConstructorSource);
1426
1427                                         self._protos[proto] = new protoClass();
1428                                 }
1429                                 catch(e) {
1430                                         alert('Unable to instantiate proto "%s": %s'.format(url, e));
1431                                 };
1432
1433                                 def.resolve();
1434                         }).fail(function() {
1435                                 def.resolve();
1436                         });
1437
1438                         return def;
1439                 },
1440
1441                 _fetch_protocols: function()
1442                 {
1443                         var self = _luci2.NetworkModel;
1444                         var deferreds = [ ];
1445
1446                         for (var proto in self._cache.protolist)
1447                                 deferreds.push(self._fetch_protocol(proto));
1448
1449                         return $.when.apply($, deferreds);
1450                 },
1451
1452                 _fetch_swstate: _luci2.rpc.declare({
1453                         object: 'luci2.network',
1454                         method: 'switch_info',
1455                         params: [ 'switch' ],
1456                         expect: { 'info': { } }
1457                 }),
1458
1459                 _fetch_swstate_cb: function(responses) {
1460                         var self = _luci2.NetworkModel;
1461                         var swlist = self._cache.swlist;
1462                         var swstate = self._cache.swstate = { };
1463
1464                         for (var i = 0; i < responses.length; i++)
1465                                 swstate[swlist[i]] = responses[i];
1466                 },
1467
1468                 _fetch_cache_cb: function(level)
1469                 {
1470                         var self = _luci2.NetworkModel;
1471                         var name = '_fetch_cache_cb_' + level;
1472
1473                         return self[name] || (
1474                                 self[name] = function(responses)
1475                                 {
1476                                         for (var i = 0; i < self._cache_functions.length; i += 3)
1477                                                 if (!level || self._cache_functions[i + 1] == level)
1478                                                         self._cache[self._cache_functions[i]] = responses.shift();
1479
1480                                         if (!level)
1481                                         {
1482                                                 _luci2.rpc.batch();
1483
1484                                                 for (var i = 0; i < self._cache.swlist.length; i++)
1485                                                         self._fetch_swstate(self._cache.swlist[i]);
1486
1487                                                 return _luci2.rpc.flush().then(self._fetch_swstate_cb);
1488                                         }
1489
1490                                         return _luci2.deferrable();
1491                                 }
1492                         );
1493                 },
1494
1495                 _fetch_cache: function(level)
1496                 {
1497                         var self = _luci2.NetworkModel;
1498
1499                         return _luci2.uci.load(['network', 'wireless']).then(function() {
1500                                 _luci2.rpc.batch();
1501
1502                                 for (var i = 0; i < self._cache_functions.length; i += 3)
1503                                         if (!level || self._cache_functions[i + 1] == level)
1504                                                 self._cache_functions[i + 2]();
1505
1506                                 return _luci2.rpc.flush().then(self._fetch_cache_cb(level || 0));
1507                         });
1508                 },
1509
1510                 _get: function(pkg, sid, key)
1511                 {
1512                         return _luci2.uci.get(pkg, sid, key);
1513                 },
1514
1515                 _set: function(pkg, sid, key, val)
1516                 {
1517                         return _luci2.uci.set(pkg, sid, key, val);
1518                 },
1519
1520                 _is_blacklisted: function(dev)
1521                 {
1522                         for (var i = 0; i < this._device_blacklist.length; i++)
1523                                 if (dev.match(this._device_blacklist[i]))
1524                                         return true;
1525
1526                         return false;
1527                 },
1528
1529                 _sort_devices: function(a, b)
1530                 {
1531                         if (a.options.kind < b.options.kind)
1532                                 return -1;
1533                         else if (a.options.kind > b.options.kind)
1534                                 return 1;
1535
1536                         if (a.options.name < b.options.name)
1537                                 return -1;
1538                         else if (a.options.name > b.options.name)
1539                                 return 1;
1540
1541                         return 0;
1542                 },
1543
1544                 _get_dev: function(ifname)
1545                 {
1546                         var alias = (ifname.charAt(0) == '@');
1547                         return this._devs[ifname] || (
1548                                 this._devs[ifname] = {
1549                                         ifname:  ifname,
1550                                         kind:    alias ? 'alias' : 'ethernet',
1551                                         type:    alias ? 0 : 1,
1552                                         up:      false,
1553                                         changed: { }
1554                                 }
1555                         );
1556                 },
1557
1558                 _get_iface: function(name)
1559                 {
1560                         return this._ifaces[name] || (
1561                                 this._ifaces[name] = {
1562                                         name:    name,
1563                                         proto:   this._protos.none,
1564                                         changed: { }
1565                                 }
1566                         );
1567                 },
1568
1569                 _parse_devices: function()
1570                 {
1571                         var self = _luci2.NetworkModel;
1572                         var wificount = { };
1573
1574                         for (var ifname in self._cache.devstate)
1575                         {
1576                                 if (self._is_blacklisted(ifname))
1577                                         continue;
1578
1579                                 var dev = self._cache.devstate[ifname];
1580                                 var entry = self._get_dev(ifname);
1581
1582                                 entry.up = dev.up;
1583
1584                                 switch (dev.type)
1585                                 {
1586                                 case 'IP tunnel':
1587                                         entry.kind = 'tunnel';
1588                                         break;
1589
1590                                 case 'Bridge':
1591                                         entry.kind = 'bridge';
1592                                         //entry.ports = dev['bridge-members'].sort();
1593                                         break;
1594                                 }
1595                         }
1596
1597                         for (var i = 0; i < self._cache.devlist.length; i++)
1598                         {
1599                                 var dev = self._cache.devlist[i];
1600
1601                                 if (self._is_blacklisted(dev.device))
1602                                         continue;
1603
1604                                 var entry = self._get_dev(dev.device);
1605
1606                                 entry.up   = dev.is_up;
1607                                 entry.type = dev.type;
1608
1609                                 switch (dev.type)
1610                                 {
1611                                 case 1: /* Ethernet */
1612                                         if (dev.is_bridge)
1613                                                 entry.kind = 'bridge';
1614                                         else if (dev.is_tuntap)
1615                                                 entry.kind = 'tunnel';
1616                                         else if (dev.is_wireless)
1617                                                 entry.kind = 'wifi';
1618                                         break;
1619
1620                                 case 512: /* PPP */
1621                                 case 768: /* IP-IP Tunnel */
1622                                 case 769: /* IP6-IP6 Tunnel */
1623                                 case 776: /* IPv6-in-IPv4 */
1624                                 case 778: /* GRE over IP */
1625                                         entry.kind = 'tunnel';
1626                                         break;
1627                                 }
1628                         }
1629
1630                         var net = _luci2.uci.sections('network');
1631                         for (var i = 0; i < net.length; i++)
1632                         {
1633                                 var s = net[i];
1634                                 var sid = s['.name'];
1635
1636                                 if (s['.type'] == 'device' && s.name)
1637                                 {
1638                                         var entry = self._get_dev(s.name);
1639
1640                                         switch (s.type)
1641                                         {
1642                                         case 'macvlan':
1643                                         case 'tunnel':
1644                                                 entry.kind = 'tunnel';
1645                                                 break;
1646                                         }
1647
1648                                         entry.sid = sid;
1649                                 }
1650                                 else if (s['.type'] == 'interface' && !s['.anonymous'] && s.ifname)
1651                                 {
1652                                         var ifnames = _luci2.toArray(s.ifname);
1653
1654                                         for (var j = 0; j < ifnames.length; j++)
1655                                                 self._get_dev(ifnames[j]);
1656
1657                                         if (s['.name'] != 'loopback')
1658                                         {
1659                                                 var entry = self._get_dev('@%s'.format(s['.name']));
1660
1661                                                 entry.type = 0;
1662                                                 entry.kind = 'alias';
1663                                                 entry.sid  = sid;
1664                                         }
1665                                 }
1666                                 else if (s['.type'] == 'switch_vlan' && s.device)
1667                                 {
1668                                         var sw = self._cache.swstate[s.device];
1669                                         var vid = parseInt(s.vid || s.vlan);
1670                                         var ports = _luci2.toArray(s.ports);
1671
1672                                         if (!sw || !ports.length || isNaN(vid))
1673                                                 continue;
1674
1675                                         var ifname = undefined;
1676
1677                                         for (var j = 0; j < ports.length; j++)
1678                                         {
1679                                                 var port = parseInt(ports[j]);
1680                                                 var tag = (ports[j].replace(/[^tu]/g, '') == 't');
1681
1682                                                 if (port == sw.cpu_port)
1683                                                 {
1684                                                         // XXX: need a way to map switch to netdev
1685                                                         if (tag)
1686                                                                 ifname = 'eth0.%d'.format(vid);
1687                                                         else
1688                                                                 ifname = 'eth0';
1689
1690                                                         break;
1691                                                 }
1692                                         }
1693
1694                                         if (!ifname)
1695                                                 continue;
1696
1697                                         var entry = self._get_dev(ifname);
1698
1699                                         entry.kind = 'vlan';
1700                                         entry.sid  = sid;
1701                                         entry.vsw  = sw;
1702                                         entry.vid  = vid;
1703                                 }
1704                         }
1705
1706                         var wifi = _luci2.uci.sections('wireless');
1707                         for (var i = 0; i < wifi.length; i++)
1708                         {
1709                                 var s = wifi[i];
1710                                 var sid = s['.name'];
1711
1712                                 if (s['.type'] == 'wifi-iface' && s.device)
1713                                 {
1714                                         var r = parseInt(s.device.replace(/^[^0-9]+/, ''));
1715                                         var n = wificount[s.device] = (wificount[s.device] || 0) + 1;
1716                                         var id = 'radio%d.network%d'.format(r, n);
1717                                         var ifname = id;
1718
1719                                         if (self._cache.wifistate[s.device])
1720                                         {
1721                                                 var ifcs = self._cache.wifistate[s.device].interfaces;
1722                                                 for (var ifc in ifcs)
1723                                                 {
1724                                                         if (ifcs[ifc].section == sid)
1725                                                         {
1726                                                                 ifname = ifcs[ifc].ifname;
1727                                                                 break;
1728                                                         }
1729                                                 }
1730                                         }
1731
1732                                         var entry = self._get_dev(ifname);
1733
1734                                         entry.kind   = 'wifi';
1735                                         entry.sid    = sid;
1736                                         entry.wid    = id;
1737                                         entry.wdev   = s.device;
1738                                         entry.wmode  = s.mode;
1739                                         entry.wssid  = s.ssid;
1740                                         entry.wbssid = s.bssid;
1741                                 }
1742                         }
1743
1744                         for (var i = 0; i < net.length; i++)
1745                         {
1746                                 var s = net[i];
1747                                 var sid = s['.name'];
1748
1749                                 if (s['.type'] == 'interface' && !s['.anonymous'] && s.type == 'bridge')
1750                                 {
1751                                         var ifnames = _luci2.toArray(s.ifname);
1752
1753                                         for (var ifname in self._devs)
1754                                         {
1755                                                 var dev = self._devs[ifname];
1756
1757                                                 if (dev.kind != 'wifi')
1758                                                         continue;
1759
1760                                                 var wnets = _luci2.toArray(_luci2.uci.get('wireless', dev.sid, 'network'));
1761                                                 if ($.inArray(sid, wnets) > -1)
1762                                                         ifnames.push(ifname);
1763                                         }
1764
1765                                         entry = self._get_dev('br-%s'.format(s['.name']));
1766                                         entry.type  = 1;
1767                                         entry.kind  = 'bridge';
1768                                         entry.sid   = sid;
1769                                         entry.ports = ifnames.sort();
1770                                 }
1771                         }
1772                 },
1773
1774                 _parse_interfaces: function()
1775                 {
1776                         var self = _luci2.NetworkModel;
1777                         var net = _luci2.uci.sections('network');
1778
1779                         for (var i = 0; i < net.length; i++)
1780                         {
1781                                 var s = net[i];
1782                                 var sid = s['.name'];
1783
1784                                 if (s['.type'] == 'interface' && !s['.anonymous'] && s.proto)
1785                                 {
1786                                         var entry = self._get_iface(s['.name']);
1787                                         var proto = self._protos[s.proto] || self._protos.none;
1788
1789                                         var l3dev = undefined;
1790                                         var l2dev = undefined;
1791
1792                                         var ifnames = _luci2.toArray(s.ifname);
1793
1794                                         for (var ifname in self._devs)
1795                                         {
1796                                                 var dev = self._devs[ifname];
1797
1798                                                 if (dev.kind != 'wifi')
1799                                                         continue;
1800
1801                                                 var wnets = _luci2.toArray(_luci2.uci.get('wireless', dev.sid, 'network'));
1802                                                 if ($.inArray(entry.name, wnets) > -1)
1803                                                         ifnames.push(ifname);
1804                                         }
1805
1806                                         if (proto.virtual)
1807                                                 l3dev = '%s-%s'.format(s.proto, entry.name);
1808                                         else if (s.type == 'bridge')
1809                                                 l3dev = 'br-%s'.format(entry.name);
1810                                         else
1811                                                 l3dev = ifnames[0];
1812
1813                                         if (!proto.virtual && s.type == 'bridge')
1814                                                 l2dev = 'br-%s'.format(entry.name);
1815                                         else if (!proto.virtual)
1816                                                 l2dev = ifnames[0];
1817
1818                                         entry.proto = proto;
1819                                         entry.sid   = sid;
1820                                         entry.l3dev = l3dev;
1821                                         entry.l2dev = l2dev;
1822                                 }
1823                         }
1824
1825                         for (var i = 0; i < self._cache.ifstate.length; i++)
1826                         {
1827                                 var iface = self._cache.ifstate[i];
1828                                 var entry = self._get_iface(iface['interface']);
1829                                 var proto = self._protos[iface.proto] || self._protos.none;
1830
1831                                 /* this is a virtual interface, either deleted from config but
1832                                    not applied yet or set up from external tools (6rd) */
1833                                 if (!entry.sid)
1834                                 {
1835                                         entry.proto = proto;
1836                                         entry.l2dev = iface.device;
1837                                         entry.l3dev = iface.l3_device;
1838                                 }
1839                         }
1840                 },
1841
1842                 init: function()
1843                 {
1844                         var self = this;
1845
1846                         if (self._cache)
1847                                 return _luci2.deferrable();
1848
1849                         self._cache  = { };
1850                         self._devs   = { };
1851                         self._ifaces = { };
1852                         self._protos = { };
1853
1854                         return self._fetch_cache()
1855                                 .then(self._fetch_protocols)
1856                                 .then(self._parse_devices)
1857                                 .then(self._parse_interfaces);
1858                 },
1859
1860                 update: function()
1861                 {
1862                         delete this._cache;
1863                         return this.init();
1864                 },
1865
1866                 refreshInterfaceStatus: function()
1867                 {
1868                         return this._fetch_cache(1).then(this._parse_interfaces);
1869                 },
1870
1871                 refreshDeviceStatus: function()
1872                 {
1873                         return this._fetch_cache(2).then(this._parse_devices);
1874                 },
1875
1876                 refreshStatus: function()
1877                 {
1878                         return this._fetch_cache(1)
1879                                 .then(this._fetch_cache(2))
1880                                 .then(this._parse_devices)
1881                                 .then(this._parse_interfaces);
1882                 },
1883
1884                 getDevices: function()
1885                 {
1886                         var devs = [ ];
1887
1888                         for (var ifname in this._devs)
1889                                 if (ifname != 'lo')
1890                                         devs.push(new _luci2.NetworkModel.Device(this._devs[ifname]));
1891
1892                         return devs.sort(this._sort_devices);
1893                 },
1894
1895                 getDeviceByInterface: function(iface)
1896                 {
1897                         if (iface instanceof _luci2.NetworkModel.Interface)
1898                                 iface = iface.name();
1899
1900                         if (this._ifaces[iface])
1901                                 return this.getDevice(this._ifaces[iface].l3dev) ||
1902                                        this.getDevice(this._ifaces[iface].l2dev);
1903
1904                         return undefined;
1905                 },
1906
1907                 getDevice: function(ifname)
1908                 {
1909                         if (this._devs[ifname])
1910                                 return new _luci2.NetworkModel.Device(this._devs[ifname]);
1911
1912                         return undefined;
1913                 },
1914
1915                 createDevice: function(name)
1916                 {
1917                         return new _luci2.NetworkModel.Device(this._get_dev(name));
1918                 },
1919
1920                 getInterfaces: function()
1921                 {
1922                         var ifaces = [ ];
1923
1924                         for (var name in this._ifaces)
1925                                 if (name != 'loopback')
1926                                         ifaces.push(this.getInterface(name));
1927
1928                         ifaces.sort(function(a, b) {
1929                                 if (a.name() < b.name())
1930                                         return -1;
1931                                 else if (a.name() > b.name())
1932                                         return 1;
1933                                 else
1934                                         return 0;
1935                         });
1936
1937                         return ifaces;
1938                 },
1939
1940                 getInterfacesByDevice: function(dev)
1941                 {
1942                         var ifaces = [ ];
1943
1944                         if (dev instanceof _luci2.NetworkModel.Device)
1945                                 dev = dev.name();
1946
1947                         for (var name in this._ifaces)
1948                         {
1949                                 var iface = this._ifaces[name];
1950                                 if (iface.l2dev == dev || iface.l3dev == dev)
1951                                         ifaces.push(this.getInterface(name));
1952                         }
1953
1954                         ifaces.sort(function(a, b) {
1955                                 if (a.name() < b.name())
1956                                         return -1;
1957                                 else if (a.name() > b.name())
1958                                         return 1;
1959                                 else
1960                                         return 0;
1961                         });
1962
1963                         return ifaces;
1964                 },
1965
1966                 getInterface: function(iface)
1967                 {
1968                         if (this._ifaces[iface])
1969                                 return new _luci2.NetworkModel.Interface(this._ifaces[iface]);
1970
1971                         return undefined;
1972                 },
1973
1974                 getProtocols: function()
1975                 {
1976                         var rv = [ ];
1977
1978                         for (var proto in this._protos)
1979                         {
1980                                 var pr = this._protos[proto];
1981
1982                                 rv.push({
1983                                         name:        proto,
1984                                         description: pr.description,
1985                                         virtual:     pr.virtual,
1986                                         tunnel:      pr.tunnel
1987                                 });
1988                         }
1989
1990                         return rv.sort(function(a, b) {
1991                                 if (a.name < b.name)
1992                                         return -1;
1993                                 else if (a.name > b.name)
1994                                         return 1;
1995                                 else
1996                                         return 0;
1997                         });
1998                 },
1999
2000                 _find_wan: function(ipaddr)
2001                 {
2002                         for (var i = 0; i < this._cache.ifstate.length; i++)
2003                         {
2004                                 var ifstate = this._cache.ifstate[i];
2005
2006                                 if (!ifstate.route)
2007                                         continue;
2008
2009                                 for (var j = 0; j < ifstate.route.length; j++)
2010                                         if (ifstate.route[j].mask == 0 &&
2011                                             ifstate.route[j].target == ipaddr &&
2012                                             typeof(ifstate.route[j].table) == 'undefined')
2013                                         {
2014                                                 return this.getInterface(ifstate['interface']);
2015                                         }
2016                         }
2017
2018                         return undefined;
2019                 },
2020
2021                 findWAN: function()
2022                 {
2023                         return this._find_wan('0.0.0.0');
2024                 },
2025
2026                 findWAN6: function()
2027                 {
2028                         return this._find_wan('::');
2029                 },
2030
2031                 resolveAlias: function(ifname)
2032                 {
2033                         if (ifname instanceof _luci2.NetworkModel.Device)
2034                                 ifname = ifname.name();
2035
2036                         var dev = this._devs[ifname];
2037                         var seen = { };
2038
2039                         while (dev && dev.kind == 'alias')
2040                         {
2041                                 // loop
2042                                 if (seen[dev.ifname])
2043                                         return undefined;
2044
2045                                 var ifc = this._ifaces[dev.sid];
2046
2047                                 seen[dev.ifname] = true;
2048                                 dev = ifc ? this._devs[ifc.l3dev] : undefined;
2049                         }
2050
2051                         return dev ? this.getDevice(dev.ifname) : undefined;
2052                 }
2053         };
2054
2055         this.NetworkModel.Device = Class.extend({
2056                 _wifi_modes: {
2057                         ap: _luci2.tr('Master'),
2058                         sta: _luci2.tr('Client'),
2059                         adhoc: _luci2.tr('Ad-Hoc'),
2060                         monitor: _luci2.tr('Monitor'),
2061                         wds: _luci2.tr('Static WDS')
2062                 },
2063
2064                 _status: function(key)
2065                 {
2066                         var s = _luci2.NetworkModel._cache.devstate[this.options.ifname];
2067
2068                         if (s)
2069                                 return key ? s[key] : s;
2070
2071                         return undefined;
2072                 },
2073
2074                 get: function(key)
2075                 {
2076                         var sid = this.options.sid;
2077                         var pkg = (this.options.kind == 'wifi') ? 'wireless' : 'network';
2078                         return _luci2.NetworkModel._get(pkg, sid, key);
2079                 },
2080
2081                 set: function(key, val)
2082                 {
2083                         var sid = this.options.sid;
2084                         var pkg = (this.options.kind == 'wifi') ? 'wireless' : 'network';
2085                         return _luci2.NetworkModel._set(pkg, sid, key, val);
2086                 },
2087
2088                 init: function()
2089                 {
2090                         if (typeof(this.options.type) == 'undefined')
2091                                 this.options.type = 1;
2092
2093                         if (typeof(this.options.kind) == 'undefined')
2094                                 this.options.kind = 'ethernet';
2095
2096                         if (typeof(this.options.networks) == 'undefined')
2097                                 this.options.networks = [ ];
2098                 },
2099
2100                 name: function()
2101                 {
2102                         return this.options.ifname;
2103                 },
2104
2105                 description: function()
2106                 {
2107                         switch (this.options.kind)
2108                         {
2109                         case 'alias':
2110                                 return _luci2.tr('Alias for network "%s"').format(this.options.ifname.substring(1));
2111
2112                         case 'bridge':
2113                                 return _luci2.tr('Network bridge');
2114
2115                         case 'ethernet':
2116                                 return _luci2.tr('Network device');
2117
2118                         case 'tunnel':
2119                                 switch (this.options.type)
2120                                 {
2121                                 case 1: /* tuntap */
2122                                         return _luci2.tr('TAP device');
2123
2124                                 case 512: /* PPP */
2125                                         return _luci2.tr('PPP tunnel');
2126
2127                                 case 768: /* IP-IP Tunnel */
2128                                         return _luci2.tr('IP-in-IP tunnel');
2129
2130                                 case 769: /* IP6-IP6 Tunnel */
2131                                         return _luci2.tr('IPv6-in-IPv6 tunnel');
2132
2133                                 case 776: /* IPv6-in-IPv4 */
2134                                         return _luci2.tr('IPv6-over-IPv4 tunnel');
2135                                         break;
2136
2137                                 case 778: /* GRE over IP */
2138                                         return _luci2.tr('GRE-over-IP tunnel');
2139
2140                                 default:
2141                                         return _luci2.tr('Tunnel device');
2142                                 }
2143
2144                         case 'vlan':
2145                                 return _luci2.tr('VLAN %d on %s').format(this.options.vid, this.options.vsw.model);
2146
2147                         case 'wifi':
2148                                 var o = this.options;
2149                                 return _luci2.trc('(Wifi-Mode) "(SSID)" on (radioX)', '%s "%h" on %s').format(
2150                                         o.wmode ? this._wifi_modes[o.wmode] : _luci2.tr('Unknown mode'),
2151                                         o.wssid || '?', o.wdev
2152                                 );
2153                         }
2154
2155                         return _luci2.tr('Unknown device');
2156                 },
2157
2158                 icon: function(up)
2159                 {
2160                         var kind = this.options.kind;
2161
2162                         if (kind == 'alias')
2163                                 kind = 'ethernet';
2164
2165                         if (typeof(up) == 'undefined')
2166                                 up = this.isUp();
2167
2168                         return _luci2.globals.resource + '/icons/%s%s.png'.format(kind, up ? '' : '_disabled');
2169                 },
2170
2171                 isUp: function()
2172                 {
2173                         var l = _luci2.NetworkModel._cache.devlist;
2174
2175                         for (var i = 0; i < l.length; i++)
2176                                 if (l[i].device == this.options.ifname)
2177                                         return (l[i].is_up === true);
2178
2179                         return false;
2180                 },
2181
2182                 isAlias: function()
2183                 {
2184                         return (this.options.kind == 'alias');
2185                 },
2186
2187                 isBridge: function()
2188                 {
2189                         return (this.options.kind == 'bridge');
2190                 },
2191
2192                 isBridgeable: function()
2193                 {
2194                         return (this.options.type == 1 && this.options.kind != 'bridge');
2195                 },
2196
2197                 isWireless: function()
2198                 {
2199                         return (this.options.kind == 'wifi');
2200                 },
2201
2202                 isInNetwork: function(net)
2203                 {
2204                         if (!(net instanceof _luci2.NetworkModel.Interface))
2205                                 net = _luci2.NetworkModel.getInterface(net);
2206
2207                         if (net)
2208                         {
2209                                 if (net.options.l3dev == this.options.ifname ||
2210                                     net.options.l2dev == this.options.ifname)
2211                                         return true;
2212
2213                                 var dev = _luci2.NetworkModel._devs[net.options.l2dev];
2214                                 if (dev && dev.kind == 'bridge' && dev.ports)
2215                                         return ($.inArray(this.options.ifname, dev.ports) > -1);
2216                         }
2217
2218                         return false;
2219                 },
2220
2221                 getMTU: function()
2222                 {
2223                         var dev = _luci2.NetworkModel._cache.devstate[this.options.ifname];
2224                         if (dev && !isNaN(dev.mtu))
2225                                 return dev.mtu;
2226
2227                         return undefined;
2228                 },
2229
2230                 getMACAddress: function()
2231                 {
2232                         if (this.options.type != 1)
2233                                 return undefined;
2234
2235                         var dev = _luci2.NetworkModel._cache.devstate[this.options.ifname];
2236                         if (dev && dev.macaddr)
2237                                 return dev.macaddr.toUpperCase();
2238
2239                         return undefined;
2240                 },
2241
2242                 getInterfaces: function()
2243                 {
2244                         return _luci2.NetworkModel.getInterfacesByDevice(this.options.name);
2245                 },
2246
2247                 getStatistics: function()
2248                 {
2249                         var s = this._status('statistics') || { };
2250                         return {
2251                                 rx_bytes: (s.rx_bytes || 0),
2252                                 tx_bytes: (s.tx_bytes || 0),
2253                                 rx_packets: (s.rx_packets || 0),
2254                                 tx_packets: (s.tx_packets || 0)
2255                         };
2256                 },
2257
2258                 getTrafficHistory: function()
2259                 {
2260                         var def = new Array(120);
2261
2262                         for (var i = 0; i < 120; i++)
2263                                 def[i] = 0;
2264
2265                         var h = _luci2.NetworkModel._cache.bwstate[this.options.ifname] || { };
2266                         return {
2267                                 rx_bytes: (h.rx_bytes || def),
2268                                 tx_bytes: (h.tx_bytes || def),
2269                                 rx_packets: (h.rx_packets || def),
2270                                 tx_packets: (h.tx_packets || def)
2271                         };
2272                 },
2273
2274                 removeFromInterface: function(iface)
2275                 {
2276                         if (!(iface instanceof _luci2.NetworkModel.Interface))
2277                                 iface = _luci2.NetworkModel.getInterface(iface);
2278
2279                         if (!iface)
2280                                 return;
2281
2282                         var ifnames = _luci2.toArray(iface.get('ifname'));
2283                         if ($.inArray(this.options.ifname, ifnames) > -1)
2284                                 iface.set('ifname', _luci2.filterArray(ifnames, this.options.ifname));
2285
2286                         if (this.options.kind != 'wifi')
2287                                 return;
2288
2289                         var networks = _luci2.toArray(this.get('network'));
2290                         if ($.inArray(iface.name(), networks) > -1)
2291                                 this.set('network', _luci2.filterArray(networks, iface.name()));
2292                 },
2293
2294                 attachToInterface: function(iface)
2295                 {
2296                         if (!(iface instanceof _luci2.NetworkModel.Interface))
2297                                 iface = _luci2.NetworkModel.getInterface(iface);
2298
2299                         if (!iface)
2300                                 return;
2301
2302                         if (this.options.kind != 'wifi')
2303                         {
2304                                 var ifnames = _luci2.toArray(iface.get('ifname'));
2305                                 if ($.inArray(this.options.ifname, ifnames) < 0)
2306                                 {
2307                                         ifnames.push(this.options.ifname);
2308                                         iface.set('ifname', (ifnames.length > 1) ? ifnames : ifnames[0]);
2309                                 }
2310                         }
2311                         else
2312                         {
2313                                 var networks = _luci2.toArray(this.get('network'));
2314                                 if ($.inArray(iface.name(), networks) < 0)
2315                                 {
2316                                         networks.push(iface.name());
2317                                         this.set('network', (networks.length > 1) ? networks : networks[0]);
2318                                 }
2319                         }
2320                 }
2321         });
2322
2323         this.NetworkModel.Interface = Class.extend({
2324                 _status: function(key)
2325                 {
2326                         var s = _luci2.NetworkModel._cache.ifstate;
2327
2328                         for (var i = 0; i < s.length; i++)
2329                                 if (s[i]['interface'] == this.options.name)
2330                                         return key ? s[i][key] : s[i];
2331
2332                         return undefined;
2333                 },
2334
2335                 get: function(key)
2336                 {
2337                         return _luci2.NetworkModel._get('network', this.options.name, key);
2338                 },
2339
2340                 set: function(key, val)
2341                 {
2342                         return _luci2.NetworkModel._set('network', this.options.name, key, val);
2343                 },
2344
2345                 name: function()
2346                 {
2347                         return this.options.name;
2348                 },
2349
2350                 protocol: function()
2351                 {
2352                         return (this.get('proto') || 'none');
2353                 },
2354
2355                 isUp: function()
2356                 {
2357                         return (this._status('up') === true);
2358                 },
2359
2360                 isVirtual: function()
2361                 {
2362                         return (typeof(this.options.sid) != 'string');
2363                 },
2364
2365                 getProtocol: function()
2366                 {
2367                         var prname = this.get('proto') || 'none';
2368                         return _luci2.NetworkModel._protos[prname] || _luci2.NetworkModel._protos.none;
2369                 },
2370
2371                 getUptime: function()
2372                 {
2373                         var uptime = this._status('uptime');
2374                         return isNaN(uptime) ? 0 : uptime;
2375                 },
2376
2377                 getDevice: function(resolveAlias)
2378                 {
2379                         if (this.options.l3dev)
2380                                 return _luci2.NetworkModel.getDevice(this.options.l3dev);
2381
2382                         return undefined;
2383                 },
2384
2385                 getPhysdev: function()
2386                 {
2387                         if (this.options.l2dev)
2388                                 return _luci2.NetworkModel.getDevice(this.options.l2dev);
2389
2390                         return undefined;
2391                 },
2392
2393                 getSubdevices: function()
2394                 {
2395                         var rv = [ ];
2396                         var dev = this.options.l2dev ?
2397                                 _luci2.NetworkModel._devs[this.options.l2dev] : undefined;
2398
2399                         if (dev && dev.kind == 'bridge' && dev.ports && dev.ports.length)
2400                                 for (var i = 0; i < dev.ports.length; i++)
2401                                         rv.push(_luci2.NetworkModel.getDevice(dev.ports[i]));
2402
2403                         return rv;
2404                 },
2405
2406                 getIPv4Addrs: function(mask)
2407                 {
2408                         var rv = [ ];
2409                         var addrs = this._status('ipv4-address');
2410
2411                         if (addrs)
2412                                 for (var i = 0; i < addrs.length; i++)
2413                                         if (!mask)
2414                                                 rv.push(addrs[i].address);
2415                                         else
2416                                                 rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
2417
2418                         return rv;
2419                 },
2420
2421                 getIPv6Addrs: function(mask)
2422                 {
2423                         var rv = [ ];
2424                         var addrs;
2425
2426                         addrs = this._status('ipv6-address');
2427
2428                         if (addrs)
2429                                 for (var i = 0; i < addrs.length; i++)
2430                                         if (!mask)
2431                                                 rv.push(addrs[i].address);
2432                                         else
2433                                                 rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
2434
2435                         addrs = this._status('ipv6-prefix-assignment');
2436
2437                         if (addrs)
2438                                 for (var i = 0; i < addrs.length; i++)
2439                                         if (!mask)
2440                                                 rv.push('%s1'.format(addrs[i].address));
2441                                         else
2442                                                 rv.push('%s1/%d'.format(addrs[i].address, addrs[i].mask));
2443
2444                         return rv;
2445                 },
2446
2447                 getDNSAddrs: function()
2448                 {
2449                         var rv = [ ];
2450                         var addrs = this._status('dns-server');
2451
2452                         if (addrs)
2453                                 for (var i = 0; i < addrs.length; i++)
2454                                         rv.push(addrs[i]);
2455
2456                         return rv;
2457                 },
2458
2459                 getIPv4DNS: function()
2460                 {
2461                         var rv = [ ];
2462                         var dns = this._status('dns-server');
2463
2464                         if (dns)
2465                                 for (var i = 0; i < dns.length; i++)
2466                                         if (dns[i].indexOf(':') == -1)
2467                                                 rv.push(dns[i]);
2468
2469                         return rv;
2470                 },
2471
2472                 getIPv6DNS: function()
2473                 {
2474                         var rv = [ ];
2475                         var dns = this._status('dns-server');
2476
2477                         if (dns)
2478                                 for (var i = 0; i < dns.length; i++)
2479                                         if (dns[i].indexOf(':') > -1)
2480                                                 rv.push(dns[i]);
2481
2482                         return rv;
2483                 },
2484
2485                 getIPv4Gateway: function()
2486                 {
2487                         var rt = this._status('route');
2488
2489                         if (rt)
2490                                 for (var i = 0; i < rt.length; i++)
2491                                         if (rt[i].target == '0.0.0.0' && rt[i].mask == 0)
2492                                                 return rt[i].nexthop;
2493
2494                         return undefined;
2495                 },
2496
2497                 getIPv6Gateway: function()
2498                 {
2499                         var rt = this._status('route');
2500
2501                         if (rt)
2502                                 for (var i = 0; i < rt.length; i++)
2503                                         if (rt[i].target == '::' && rt[i].mask == 0)
2504                                                 return rt[i].nexthop;
2505
2506                         return undefined;
2507                 },
2508
2509                 getStatistics: function()
2510                 {
2511                         var dev = this.getDevice() || new _luci2.NetworkModel.Device({});
2512                         return dev.getStatistics();
2513                 },
2514
2515                 getTrafficHistory: function()
2516                 {
2517                         var dev = this.getDevice() || new _luci2.NetworkModel.Device({});
2518                         return dev.getTrafficHistory();
2519                 },
2520
2521                 setDevices: function(devs)
2522                 {
2523                         var dev = this.getPhysdev();
2524                         var old_devs = [ ];
2525                         var changed = false;
2526
2527                         if (dev && dev.isBridge())
2528                                 old_devs = this.getSubdevices();
2529                         else if (dev)
2530                                 old_devs = [ dev ];
2531
2532                         if (old_devs.length != devs.length)
2533                                 changed = true;
2534                         else
2535                                 for (var i = 0; i < old_devs.length; i++)
2536                                 {
2537                                         var dev = devs[i];
2538
2539                                         if (dev instanceof _luci2.NetworkModel.Device)
2540                                                 dev = dev.name();
2541
2542                                         if (!dev || old_devs[i].name() != dev)
2543                                         {
2544                                                 changed = true;
2545                                                 break;
2546                                         }
2547                                 }
2548
2549                         if (changed)
2550                         {
2551                                 for (var i = 0; i < old_devs.length; i++)
2552                                         old_devs[i].removeFromInterface(this);
2553
2554                                 for (var i = 0; i < devs.length; i++)
2555                                 {
2556                                         var dev = devs[i];
2557
2558                                         if (!(dev instanceof _luci2.NetworkModel.Device))
2559                                                 dev = _luci2.NetworkModel.getDevice(dev);
2560
2561                                         if (dev)
2562                                                 dev.attachToInterface(this);
2563                                 }
2564                         }
2565                 },
2566
2567                 changeProtocol: function(proto)
2568                 {
2569                         var pr = _luci2.NetworkModel._protos[proto];
2570
2571                         if (!pr)
2572                                 return;
2573
2574                         for (var opt in (this.get() || { }))
2575                         {
2576                                 switch (opt)
2577                                 {
2578                                 case 'type':
2579                                 case 'ifname':
2580                                 case 'macaddr':
2581                                         if (pr.virtual)
2582                                                 this.set(opt, undefined);
2583                                         break;
2584
2585                                 case 'auto':
2586                                 case 'mtu':
2587                                         break;
2588
2589                                 case 'proto':
2590                                         this.set(opt, pr.protocol);
2591                                         break;
2592
2593                                 default:
2594                                         this.set(opt, undefined);
2595                                         break;
2596                                 }
2597                         }
2598                 },
2599
2600                 createForm: function(mapwidget)
2601                 {
2602                         var self = this;
2603                         var proto = self.getProtocol();
2604                         var device = self.getDevice();
2605
2606                         if (!mapwidget)
2607                                 mapwidget = _luci2.cbi.Map;
2608
2609                         var map = new mapwidget('network', {
2610                                 caption:     _luci2.tr('Configure "%s"').format(self.name())
2611                         });
2612
2613                         var section = map.section(_luci2.cbi.SingleSection, self.name(), {
2614                                 anonymous:   true
2615                         });
2616
2617                         section.tab({
2618                                 id:      'general',
2619                                 caption: _luci2.tr('General Settings')
2620                         });
2621
2622                         section.tab({
2623                                 id:      'advanced',
2624                                 caption: _luci2.tr('Advanced Settings')
2625                         });
2626
2627                         section.tab({
2628                                 id:      'ipv6',
2629                                 caption: _luci2.tr('IPv6')
2630                         });
2631
2632                         section.tab({
2633                                 id:      'physical',
2634                                 caption: _luci2.tr('Physical Settings')
2635                         });
2636
2637
2638                         section.taboption('general', _luci2.cbi.CheckboxValue, 'auto', {
2639                                 caption:     _luci2.tr('Start on boot'),
2640                                 optional:    true,
2641                                 initial:     true
2642                         });
2643
2644                         var pr = section.taboption('general', _luci2.cbi.ListValue, 'proto', {
2645                                 caption:     _luci2.tr('Protocol')
2646                         });
2647
2648                         pr.ucivalue = function(sid) {
2649                                 return self.get('proto') || 'none';
2650                         };
2651
2652                         var ok = section.taboption('general', _luci2.cbi.ButtonValue, '_confirm', {
2653                                 caption:     _luci2.tr('Really switch?'),
2654                                 description: _luci2.tr('Changing the protocol will clear all configuration for this interface!'),
2655                                 text:        _luci2.tr('Change protocol')
2656                         });
2657
2658                         ok.on('click', function(ev) {
2659                                 self.changeProtocol(pr.formvalue(ev.data.sid));
2660                                 self.createForm(mapwidget).show();
2661                         });
2662
2663                         var protos = _luci2.NetworkModel.getProtocols();
2664
2665                         for (var i = 0; i < protos.length; i++)
2666                                 pr.value(protos[i].name, protos[i].description);
2667
2668                         proto.populateForm(section, self);
2669
2670                         if (!proto.virtual)
2671                         {
2672                                 var br = section.taboption('physical', _luci2.cbi.CheckboxValue, 'type', {
2673                                         caption:     _luci2.tr('Network bridge'),
2674                                         description: _luci2.tr('Merges multiple devices into one logical bridge'),
2675                                         optional:    true,
2676                                         enabled:     'bridge',
2677                                         disabled:    '',
2678                                         initial:     ''
2679                                 });
2680
2681                                 section.taboption('physical', _luci2.cbi.DeviceList, '__iface_multi', {
2682                                         caption:     _luci2.tr('Devices'),
2683                                         multiple:    true,
2684                                         bridges:     false
2685                                 }).depends('type', true);
2686
2687                                 section.taboption('physical', _luci2.cbi.DeviceList, '__iface_single', {
2688                                         caption:     _luci2.tr('Device'),
2689                                         multiple:    false,
2690                                         bridges:     true
2691                                 }).depends('type', false);
2692
2693                                 var mac = section.taboption('physical', _luci2.cbi.InputValue, 'macaddr', {
2694                                         caption:     _luci2.tr('Override MAC'),
2695                                         optional:    true,
2696                                         placeholder: device ? device.getMACAddress() : undefined,
2697                                         datatype:    'macaddr'
2698                                 })
2699
2700                                 mac.ucivalue = function(sid)
2701                                 {