luci2: add LuCI2.UCIContext class, this proxies the remote uci state within the ui
[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 = {
1148
1149                 writable: function()
1150                 {
1151                         return _luci2.session.access('ubus', 'uci', 'commit');
1152                 },
1153
1154                 add: _luci2.rpc.declare({
1155                         object: 'uci',
1156                         method: 'add',
1157                         params: [ 'config', 'type', 'name', 'values' ],
1158                         expect: { section: '' }
1159                 }),
1160
1161                 apply: function()
1162                 {
1163
1164                 },
1165
1166                 configs: _luci2.rpc.declare({
1167                         object: 'uci',
1168                         method: 'configs',
1169                         expect: { configs: [ ] }
1170                 }),
1171
1172                 _changes: _luci2.rpc.declare({
1173                         object: 'uci',
1174                         method: 'changes',
1175                         params: [ 'config' ],
1176                         expect: { changes: [ ] }
1177                 }),
1178
1179                 changes: function(config)
1180                 {
1181                         if (typeof(config) == 'string')
1182                                 return this._changes(config);
1183
1184                         var configlist;
1185                         return this.configs().then(function(configs) {
1186                                 _luci2.rpc.batch();
1187                                 configlist = configs;
1188
1189                                 for (var i = 0; i < configs.length; i++)
1190                                         _luci2.uci._changes(configs[i]);
1191
1192                                 return _luci2.rpc.flush();
1193                         }).then(function(changes) {
1194                                 var rv = { };
1195
1196                                 for (var i = 0; i < configlist.length; i++)
1197                                         if (changes[i].length)
1198                                                 rv[configlist[i]] = changes[i];
1199
1200                                 return rv;
1201                         });
1202                 },
1203
1204                 commit: _luci2.rpc.declare({
1205                         object: 'uci',
1206                         method: 'commit',
1207                         params: [ 'config' ]
1208                 }),
1209
1210                 _delete_one: _luci2.rpc.declare({
1211                         object: 'uci',
1212                         method: 'delete',
1213                         params: [ 'config', 'section', 'option' ]
1214                 }),
1215
1216                 _delete_multiple: _luci2.rpc.declare({
1217                         object: 'uci',
1218                         method: 'delete',
1219                         params: [ 'config', 'section', 'options' ]
1220                 }),
1221
1222                 'delete': function(config, section, option)
1223                 {
1224                         if ($.isArray(option))
1225                                 return this._delete_multiple(config, section, option);
1226                         else
1227                                 return this._delete_one(config, section, option);
1228                 },
1229
1230                 delete_all: _luci2.rpc.declare({
1231                         object: 'uci',
1232                         method: 'delete',
1233                         params: [ 'config', 'type', 'match' ]
1234                 }),
1235
1236                 _foreach: _luci2.rpc.declare({
1237                         object: 'uci',
1238                         method: 'get',
1239                         params: [ 'config', 'type' ],
1240                         expect: { values: { } }
1241                 }),
1242
1243                 foreach: function(config, type, cb)
1244                 {
1245                         return this._foreach(config, type).then(function(sections) {
1246                                 for (var s in sections)
1247                                         cb(sections[s]);
1248                         });
1249                 },
1250
1251                 get: _luci2.rpc.declare({
1252                         object: 'uci',
1253                         method: 'get',
1254                         params: [ 'config', 'section', 'option' ],
1255                         expect: { '': { } },
1256                         filter: function(data, params) {
1257                                 if (typeof(params.option) == 'undefined')
1258                                         return data.values ? data.values['.type'] : undefined;
1259                                 else
1260                                         return data.value;
1261                         }
1262                 }),
1263
1264                 get_all: _luci2.rpc.declare({
1265                         object: 'uci',
1266                         method: 'get',
1267                         params: [ 'config', 'section' ],
1268                         expect: { values: { } },
1269                         filter: function(data, params) {
1270                                 if (typeof(params.section) == 'string')
1271                                         data['.section'] = params.section;
1272                                 else if (typeof(params.config) == 'string')
1273                                         data['.package'] = params.config;
1274                                 return data;
1275                         }
1276                 }),
1277
1278                 get_first: function(config, type, option)
1279                 {
1280                         return this._foreach(config, type).then(function(sections) {
1281                                 for (var s in sections)
1282                                 {
1283                                         var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
1284
1285                                         if (typeof(val) != 'undefined')
1286                                                 return val;
1287                                 }
1288
1289                                 return undefined;
1290                         });
1291                 },
1292
1293                 section: _luci2.rpc.declare({
1294                         object: 'uci',
1295                         method: 'add',
1296                         params: [ 'config', 'type', 'name', 'values' ],
1297                         expect: { section: '' }
1298                 }),
1299
1300                 _set: _luci2.rpc.declare({
1301                         object: 'uci',
1302                         method: 'set',
1303                         params: [ 'config', 'section', 'values' ]
1304                 }),
1305
1306                 set: function(config, section, option, value)
1307                 {
1308                         if (typeof(value) == 'undefined' && typeof(option) == 'string')
1309                                 return this.section(config, section, option); /* option -> type */
1310                         else if ($.isPlainObject(option))
1311                                 return this._set(config, section, option); /* option -> values */
1312
1313                         var values = { };
1314                             values[option] = value;
1315
1316                         return this._set(config, section, values);
1317                 },
1318
1319                 order: _luci2.rpc.declare({
1320                         object: 'uci',
1321                         method: 'order',
1322                         params: [ 'config', 'sections' ]
1323                 })
1324         };
1325
1326         this.network = {
1327                 listNetworkNames: function() {
1328                         return _luci2.rpc.list('network.interface.*').then(function(list) {
1329                                 var names = [ ];
1330                                 for (var name in list)
1331                                         if (name != 'network.interface.loopback')
1332                                                 names.push(name.substring(18));
1333                                 names.sort();
1334                                 return names;
1335                         });
1336                 },
1337
1338                 listDeviceNames: _luci2.rpc.declare({
1339                         object: 'network.device',
1340                         method: 'status',
1341                         expect: { '': { } },
1342                         filter: function(data) {
1343                                 var names = [ ];
1344                                 for (var name in data)
1345                                         if (name != 'lo')
1346                                                 names.push(name);
1347                                 names.sort();
1348                                 return names;
1349                         }
1350                 }),
1351
1352                 getNetworkStatus: function()
1353                 {
1354                         var nets = [ ];
1355                         var devs = { };
1356
1357                         return this.listNetworkNames().then(function(names) {
1358                                 _luci2.rpc.batch();
1359
1360                                 for (var i = 0; i < names.length; i++)
1361                                         _luci2.network.getInterfaceStatus(names[i]);
1362
1363                                 return _luci2.rpc.flush();
1364                         }).then(function(networks) {
1365                                 for (var i = 0; i < networks.length; i++)
1366                                 {
1367                                         var net = nets[i] = networks[i];
1368                                         var dev = net.l3_device || net.l2_device;
1369                                         if (dev)
1370                                                 net.device = devs[dev] || (devs[dev] = { });
1371                                 }
1372
1373                                 _luci2.rpc.batch();
1374
1375                                 for (var dev in devs)
1376                                         _luci2.network.getDeviceStatus(dev);
1377
1378                                 return _luci2.rpc.flush();
1379                         }).then(function(devices) {
1380                                 _luci2.rpc.batch();
1381
1382                                 for (var i = 0; i < devices.length; i++)
1383                                 {
1384                                         var brm = devices[i]['bridge-members'];
1385                                         delete devices[i]['bridge-members'];
1386
1387                                         $.extend(devs[devices[i]['device']], devices[i]);
1388
1389                                         if (!brm)
1390                                                 continue;
1391
1392                                         devs[devices[i]['device']].subdevices = [ ];
1393
1394                                         for (var j = 0; j < brm.length; j++)
1395                                         {
1396                                                 if (!devs[brm[j]])
1397                                                 {
1398                                                         devs[brm[j]] = { };
1399                                                         _luci2.network.getDeviceStatus(brm[j]);
1400                                                 }
1401
1402                                                 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
1403                                         }
1404                                 }
1405
1406                                 return _luci2.rpc.flush();
1407                         }).then(function(subdevices) {
1408                                 for (var i = 0; i < subdevices.length; i++)
1409                                         $.extend(devs[subdevices[i]['device']], subdevices[i]);
1410
1411                                 _luci2.rpc.batch();
1412
1413                                 for (var dev in devs)
1414                                         _luci2.wireless.getDeviceStatus(dev);
1415
1416                                 return _luci2.rpc.flush();
1417                         }).then(function(wifidevices) {
1418                                 for (var i = 0; i < wifidevices.length; i++)
1419                                         if (wifidevices[i])
1420                                                 devs[wifidevices[i]['device']].wireless = wifidevices[i];
1421
1422                                 nets.sort(function(a, b) {
1423                                         if (a['interface'] < b['interface'])
1424                                                 return -1;
1425                                         else if (a['interface'] > b['interface'])
1426                                                 return 1;
1427                                         else
1428                                                 return 0;
1429                                 });
1430
1431                                 return nets;
1432                         });
1433                 },
1434
1435                 findWanInterfaces: function(cb)
1436                 {
1437                         return this.listNetworkNames().then(function(names) {
1438                                 _luci2.rpc.batch();
1439
1440                                 for (var i = 0; i < names.length; i++)
1441                                         _luci2.network.getInterfaceStatus(names[i]);
1442
1443                                 return _luci2.rpc.flush();
1444                         }).then(function(interfaces) {
1445                                 var rv = [ undefined, undefined ];
1446
1447                                 for (var i = 0; i < interfaces.length; i++)
1448                                 {
1449                                         if (!interfaces[i].route)
1450                                                 continue;
1451
1452                                         for (var j = 0; j < interfaces[i].route.length; j++)
1453                                         {
1454                                                 var rt = interfaces[i].route[j];
1455
1456                                                 if (typeof(rt.table) != 'undefined')
1457                                                         continue;
1458
1459                                                 if (rt.target == '0.0.0.0' && rt.mask == 0)
1460                                                         rv[0] = interfaces[i];
1461                                                 else if (rt.target == '::' && rt.mask == 0)
1462                                                         rv[1] = interfaces[i];
1463                                         }
1464                                 }
1465
1466                                 return rv;
1467                         });
1468                 },
1469
1470                 getDHCPLeases: _luci2.rpc.declare({
1471                         object: 'luci2.network',
1472                         method: 'dhcp_leases',
1473                         expect: { leases: [ ] }
1474                 }),
1475
1476                 getDHCPv6Leases: _luci2.rpc.declare({
1477                         object: 'luci2.network',
1478                         method: 'dhcp6_leases',
1479                         expect: { leases: [ ] }
1480                 }),
1481
1482                 getRoutes: _luci2.rpc.declare({
1483                         object: 'luci2.network',
1484                         method: 'routes',
1485                         expect: { routes: [ ] }
1486                 }),
1487
1488                 getIPv6Routes: _luci2.rpc.declare({
1489                         object: 'luci2.network',
1490                         method: 'routes',
1491                         expect: { routes: [ ] }
1492                 }),
1493
1494                 getARPTable: _luci2.rpc.declare({
1495                         object: 'luci2.network',
1496                         method: 'arp_table',
1497                         expect: { entries: [ ] }
1498                 }),
1499
1500                 getInterfaceStatus: _luci2.rpc.declare({
1501                         object: 'network.interface',
1502                         method: 'status',
1503                         params: [ 'interface' ],
1504                         expect: { '': { } },
1505                         filter: function(data, params) {
1506                                 data['interface'] = params['interface'];
1507                                 data['l2_device'] = data['device'];
1508                                 delete data['device'];
1509                                 return data;
1510                         }
1511                 }),
1512
1513                 getDeviceStatus: _luci2.rpc.declare({
1514                         object: 'network.device',
1515                         method: 'status',
1516                         params: [ 'name' ],
1517                         expect: { '': { } },
1518                         filter: function(data, params) {
1519                                 data['device'] = params['name'];
1520                                 return data;
1521                         }
1522                 }),
1523
1524                 getConntrackCount: _luci2.rpc.declare({
1525                         object: 'luci2.network',
1526                         method: 'conntrack_count',
1527                         expect: { '': { count: 0, limit: 0 } }
1528                 }),
1529
1530                 listSwitchNames: _luci2.rpc.declare({
1531                         object: 'luci2.network',
1532                         method: 'switch_list',
1533                         expect: { switches: [ ] }
1534                 }),
1535
1536                 getSwitchInfo: _luci2.rpc.declare({
1537                         object: 'luci2.network',
1538                         method: 'switch_info',
1539                         params: [ 'switch' ],
1540                         expect: { info: { } },
1541                         filter: function(data, params) {
1542                                 data['attrs']      = data['switch'];
1543                                 data['vlan_attrs'] = data['vlan'];
1544                                 data['port_attrs'] = data['port'];
1545                                 data['switch']     = params['switch'];
1546
1547                                 delete data.vlan;
1548                                 delete data.port;
1549
1550                                 return data;
1551                         }
1552                 }),
1553
1554                 getSwitchStatus: _luci2.rpc.declare({
1555                         object: 'luci2.network',
1556                         method: 'switch_status',
1557                         params: [ 'switch' ],
1558                         expect: { ports: [ ] }
1559                 }),
1560
1561
1562                 runPing: _luci2.rpc.declare({
1563                         object: 'luci2.network',
1564                         method: 'ping',
1565                         params: [ 'data' ],
1566                         expect: { '': { code: -1 } }
1567                 }),
1568
1569                 runPing6: _luci2.rpc.declare({
1570                         object: 'luci2.network',
1571                         method: 'ping6',
1572                         params: [ 'data' ],
1573                         expect: { '': { code: -1 } }
1574                 }),
1575
1576                 runTraceroute: _luci2.rpc.declare({
1577                         object: 'luci2.network',
1578                         method: 'traceroute',
1579                         params: [ 'data' ],
1580                         expect: { '': { code: -1 } }
1581                 }),
1582
1583                 runTraceroute6: _luci2.rpc.declare({
1584                         object: 'luci2.network',
1585                         method: 'traceroute6',
1586                         params: [ 'data' ],
1587                         expect: { '': { code: -1 } }
1588                 }),
1589
1590                 runNslookup: _luci2.rpc.declare({
1591                         object: 'luci2.network',
1592                         method: 'nslookup',
1593                         params: [ 'data' ],
1594                         expect: { '': { code: -1 } }
1595                 }),
1596
1597
1598                 setUp: _luci2.rpc.declare({
1599                         object: 'luci2.network',
1600                         method: 'ifup',
1601                         params: [ 'data' ],
1602                         expect: { '': { code: -1 } }
1603                 }),
1604
1605                 setDown: _luci2.rpc.declare({
1606                         object: 'luci2.network',
1607                         method: 'ifdown',
1608                         params: [ 'data' ],
1609                         expect: { '': { code: -1 } }
1610                 })
1611         };
1612
1613         this.wireless = {
1614                 listDeviceNames: _luci2.rpc.declare({
1615                         object: 'iwinfo',
1616                         method: 'devices',
1617                         expect: { 'devices': [ ] },
1618                         filter: function(data) {
1619                                 data.sort();
1620                                 return data;
1621                         }
1622                 }),
1623
1624                 getDeviceStatus: _luci2.rpc.declare({
1625                         object: 'iwinfo',
1626                         method: 'info',
1627                         params: [ 'device' ],
1628                         expect: { '': { } },
1629                         filter: function(data, params) {
1630                                 if (!$.isEmptyObject(data))
1631                                 {
1632                                         data['device'] = params['device'];
1633                                         return data;
1634                                 }
1635                                 return undefined;
1636                         }
1637                 }),
1638
1639                 getAssocList: _luci2.rpc.declare({
1640                         object: 'iwinfo',
1641                         method: 'assoclist',
1642                         params: [ 'device' ],
1643                         expect: { results: [ ] },
1644                         filter: function(data, params) {
1645                                 for (var i = 0; i < data.length; i++)
1646                                         data[i]['device'] = params['device'];
1647
1648                                 data.sort(function(a, b) {
1649                                         if (a.bssid < b.bssid)
1650                                                 return -1;
1651                                         else if (a.bssid > b.bssid)
1652                                                 return 1;
1653                                         else
1654                                                 return 0;
1655                                 });
1656
1657                                 return data;
1658                         }
1659                 }),
1660
1661                 getWirelessStatus: function() {
1662                         return this.listDeviceNames().then(function(names) {
1663                                 _luci2.rpc.batch();
1664
1665                                 for (var i = 0; i < names.length; i++)
1666                                         _luci2.wireless.getDeviceStatus(names[i]);
1667
1668                                 return _luci2.rpc.flush();
1669                         }).then(function(networks) {
1670                                 var rv = { };
1671
1672                                 var phy_attrs = [
1673                                         'country', 'channel', 'frequency', 'frequency_offset',
1674                                         'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1675                                 ];
1676
1677                                 var net_attrs = [
1678                                         'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1679                                         'signal', 'noise', 'bitrate', 'encryption'
1680                                 ];
1681
1682                                 for (var i = 0; i < networks.length; i++)
1683                                 {
1684                                         var phy = rv[networks[i].phy] || (
1685                                                 rv[networks[i].phy] = { networks: [ ] }
1686                                         );
1687
1688                                         var net = {
1689                                                 device: networks[i].device
1690                                         };
1691
1692                                         for (var j = 0; j < phy_attrs.length; j++)
1693                                                 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1694
1695                                         for (var j = 0; j < net_attrs.length; j++)
1696                                                 net[net_attrs[j]] = networks[i][net_attrs[j]];
1697
1698                                         phy.networks.push(net);
1699                                 }
1700
1701                                 return rv;
1702                         });
1703                 },
1704
1705                 getAssocLists: function()
1706                 {
1707                         return this.listDeviceNames().then(function(names) {
1708                                 _luci2.rpc.batch();
1709
1710                                 for (var i = 0; i < names.length; i++)
1711                                         _luci2.wireless.getAssocList(names[i]);
1712
1713                                 return _luci2.rpc.flush();
1714                         }).then(function(assoclists) {
1715                                 var rv = [ ];
1716
1717                                 for (var i = 0; i < assoclists.length; i++)
1718                                         for (var j = 0; j < assoclists[i].length; j++)
1719                                                 rv.push(assoclists[i][j]);
1720
1721                                 return rv;
1722                         });
1723                 },
1724
1725                 formatEncryption: function(enc)
1726                 {
1727                         var format_list = function(l, s)
1728                         {
1729                                 var rv = [ ];
1730                                 for (var i = 0; i < l.length; i++)
1731                                         rv.push(l[i].toUpperCase());
1732                                 return rv.join(s ? s : ', ');
1733                         }
1734
1735                         if (!enc || !enc.enabled)
1736                                 return _luci2.tr('None');
1737
1738                         if (enc.wep)
1739                         {
1740                                 if (enc.wep.length == 2)
1741                                         return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1742                                 else if (enc.wep[0] == 'shared')
1743                                         return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1744                                 else
1745                                         return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1746                         }
1747                         else if (enc.wpa)
1748                         {
1749                                 if (enc.wpa.length == 2)
1750                                         return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1751                                                 format_list(enc.authentication, '/'),
1752                                                 format_list(enc.ciphers, ', ')
1753                                         );
1754                                 else if (enc.wpa[0] == 2)
1755                                         return 'WPA2 %s (%s)'.format(
1756                                                 format_list(enc.authentication, '/'),
1757                                                 format_list(enc.ciphers, ', ')
1758                                         );
1759                                 else
1760                                         return 'WPA %s (%s)'.format(
1761                                                 format_list(enc.authentication, '/'),
1762                                                 format_list(enc.ciphers, ', ')
1763                                         );
1764                         }
1765
1766                         return _luci2.tr('Unknown');
1767                 }
1768         };
1769
1770         this.firewall = {
1771                 getZoneColor: function(zone)
1772                 {
1773                         if ($.isPlainObject(zone))
1774                                 zone = zone.name;
1775
1776                         if (zone == 'lan')
1777                                 return '#90f090';
1778                         else if (zone == 'wan')
1779                                 return '#f09090';
1780
1781                         for (var i = 0, hash = 0;
1782                                  i < zone.length;
1783                                  hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1784
1785                         for (var i = 0, color = '#';
1786                                  i < 3;
1787                                  color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1788
1789                         return color;
1790                 },
1791
1792                 findZoneByNetwork: function(network)
1793                 {
1794                         var self = this;
1795                         var zone = undefined;
1796
1797                         return _luci2.uci.foreach('firewall', 'zone', function(z) {
1798                                 if (!z.name || !z.network)
1799                                         return;
1800
1801                                 if (!$.isArray(z.network))
1802                                         z.network = z.network.split(/\s+/);
1803
1804                                 for (var i = 0; i < z.network.length; i++)
1805                                 {
1806                                         if (z.network[i] == network)
1807                                         {
1808                                                 zone = z;
1809                                                 break;
1810                                         }
1811                                 }
1812                         }).then(function() {
1813                                 if (zone)
1814                                         zone.color = self.getZoneColor(zone);
1815
1816                                 return zone;
1817                         });
1818                 }
1819         };
1820
1821         this.system = {
1822                 getSystemInfo: _luci2.rpc.declare({
1823                         object: 'system',
1824                         method: 'info',
1825                         expect: { '': { } }
1826                 }),
1827
1828                 getBoardInfo: _luci2.rpc.declare({
1829                         object: 'system',
1830                         method: 'board',
1831                         expect: { '': { } }
1832                 }),
1833
1834                 getDiskInfo: _luci2.rpc.declare({
1835                         object: 'luci2.system',
1836                         method: 'diskfree',
1837                         expect: { '': { } }
1838                 }),
1839
1840                 getInfo: function(cb)
1841                 {
1842                         _luci2.rpc.batch();
1843
1844                         this.getSystemInfo();
1845                         this.getBoardInfo();
1846                         this.getDiskInfo();
1847
1848                         return _luci2.rpc.flush().then(function(info) {
1849                                 var rv = { };
1850
1851                                 $.extend(rv, info[0]);
1852                                 $.extend(rv, info[1]);
1853                                 $.extend(rv, info[2]);
1854
1855                                 return rv;
1856                         });
1857                 },
1858
1859                 getProcessList: _luci2.rpc.declare({
1860                         object: 'luci2.system',
1861                         method: 'process_list',
1862                         expect: { processes: [ ] },
1863                         filter: function(data) {
1864                                 data.sort(function(a, b) { return a.pid - b.pid });
1865                                 return data;
1866                         }
1867                 }),
1868
1869                 getSystemLog: _luci2.rpc.declare({
1870                         object: 'luci2.system',
1871                         method: 'syslog',
1872                         expect: { log: '' }
1873                 }),
1874
1875                 getKernelLog: _luci2.rpc.declare({
1876                         object: 'luci2.system',
1877                         method: 'dmesg',
1878                         expect: { log: '' }
1879                 }),
1880
1881                 getZoneInfo: function(cb)
1882                 {
1883                         return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1884                 },
1885
1886                 sendSignal: _luci2.rpc.declare({
1887                         object: 'luci2.system',
1888                         method: 'process_signal',
1889                         params: [ 'pid', 'signal' ],
1890                         filter: function(data) {
1891                                 return (data == 0);
1892                         }
1893                 }),
1894
1895                 initList: _luci2.rpc.declare({
1896                         object: 'luci2.system',
1897                         method: 'init_list',
1898                         expect: { initscripts: [ ] },
1899                         filter: function(data) {
1900                                 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1901                                 return data;
1902                         }
1903                 }),
1904
1905                 initEnabled: function(init, cb)
1906                 {
1907                         return this.initList().then(function(list) {
1908                                 for (var i = 0; i < list.length; i++)
1909                                         if (list[i].name == init)
1910                                                 return !!list[i].enabled;
1911
1912                                 return false;
1913                         });
1914                 },
1915
1916                 initRun: _luci2.rpc.declare({
1917                         object: 'luci2.system',
1918                         method: 'init_action',
1919                         params: [ 'name', 'action' ],
1920                         filter: function(data) {
1921                                 return (data == 0);
1922                         }
1923                 }),
1924
1925                 initStart:   function(init, cb) { return _luci2.system.initRun(init, 'start',   cb) },
1926                 initStop:    function(init, cb) { return _luci2.system.initRun(init, 'stop',    cb) },
1927                 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1928                 initReload:  function(init, cb) { return _luci2.system.initRun(init, 'reload',  cb) },
1929                 initEnable:  function(init, cb) { return _luci2.system.initRun(init, 'enable',  cb) },
1930                 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1931
1932
1933                 getRcLocal: _luci2.rpc.declare({
1934                         object: 'luci2.system',
1935                         method: 'rclocal_get',
1936                         expect: { data: '' }
1937                 }),
1938
1939                 setRcLocal: _luci2.rpc.declare({
1940                         object: 'luci2.system',
1941                         method: 'rclocal_set',
1942                         params: [ 'data' ]
1943                 }),
1944
1945
1946                 getCrontab: _luci2.rpc.declare({
1947                         object: 'luci2.system',
1948                         method: 'crontab_get',
1949                         expect: { data: '' }
1950                 }),
1951
1952                 setCrontab: _luci2.rpc.declare({
1953                         object: 'luci2.system',
1954                         method: 'crontab_set',
1955                         params: [ 'data' ]
1956                 }),
1957
1958
1959                 getSSHKeys: _luci2.rpc.declare({
1960                         object: 'luci2.system',
1961                         method: 'sshkeys_get',
1962                         expect: { keys: [ ] }
1963                 }),
1964
1965                 setSSHKeys: _luci2.rpc.declare({
1966                         object: 'luci2.system',
1967                         method: 'sshkeys_set',
1968                         params: [ 'keys' ]
1969                 }),
1970
1971
1972                 setPassword: _luci2.rpc.declare({
1973                         object: 'luci2.system',
1974                         method: 'password_set',
1975                         params: [ 'user', 'password' ]
1976                 }),
1977
1978
1979                 listLEDs: _luci2.rpc.declare({
1980                         object: 'luci2.system',
1981                         method: 'led_list',
1982                         expect: { leds: [ ] }
1983                 }),
1984
1985                 listUSBDevices: _luci2.rpc.declare({
1986                         object: 'luci2.system',
1987                         method: 'usb_list',
1988                         expect: { devices: [ ] }
1989                 }),
1990
1991
1992                 testUpgrade: _luci2.rpc.declare({
1993                         object: 'luci2.system',
1994                         method: 'upgrade_test',
1995                         expect: { '': { } }
1996                 }),
1997
1998                 startUpgrade: _luci2.rpc.declare({
1999                         object: 'luci2.system',
2000                         method: 'upgrade_start',
2001                         params: [ 'keep' ]
2002                 }),
2003
2004                 cleanUpgrade: _luci2.rpc.declare({
2005                         object: 'luci2.system',
2006                         method: 'upgrade_clean'
2007                 }),
2008
2009
2010                 restoreBackup: _luci2.rpc.declare({
2011                         object: 'luci2.system',
2012                         method: 'backup_restore'
2013                 }),
2014
2015                 cleanBackup: _luci2.rpc.declare({
2016                         object: 'luci2.system',
2017                         method: 'backup_clean'
2018                 }),
2019
2020
2021                 getBackupConfig: _luci2.rpc.declare({
2022                         object: 'luci2.system',
2023                         method: 'backup_config_get',
2024                         expect: { config: '' }
2025                 }),
2026
2027                 setBackupConfig: _luci2.rpc.declare({
2028                         object: 'luci2.system',
2029                         method: 'backup_config_set',
2030                         params: [ 'data' ]
2031                 }),
2032
2033
2034                 listBackup: _luci2.rpc.declare({
2035                         object: 'luci2.system',
2036                         method: 'backup_list',
2037                         expect: { files: [ ] }
2038                 }),
2039
2040
2041                 testReset: _luci2.rpc.declare({
2042                         object: 'luci2.system',
2043                         method: 'reset_test',
2044                         expect: { supported: false }
2045                 }),
2046
2047                 startReset: _luci2.rpc.declare({
2048                         object: 'luci2.system',
2049                         method: 'reset_start'
2050                 }),
2051
2052
2053                 performReboot: _luci2.rpc.declare({
2054                         object: 'luci2.system',
2055                         method: 'reboot'
2056                 })
2057         };
2058
2059         this.opkg = {
2060                 updateLists: _luci2.rpc.declare({
2061                         object: 'luci2.opkg',
2062                         method: 'update',
2063                         expect: { '': { } }
2064                 }),
2065
2066                 _allPackages: _luci2.rpc.declare({
2067                         object: 'luci2.opkg',
2068                         method: 'list',
2069                         params: [ 'offset', 'limit', 'pattern' ],
2070                         expect: { '': { } }
2071                 }),
2072
2073                 _installedPackages: _luci2.rpc.declare({
2074                         object: 'luci2.opkg',
2075                         method: 'list_installed',
2076                         params: [ 'offset', 'limit', 'pattern' ],
2077                         expect: { '': { } }
2078                 }),
2079
2080                 _findPackages: _luci2.rpc.declare({
2081                         object: 'luci2.opkg',
2082                         method: 'find',
2083                         params: [ 'offset', 'limit', 'pattern' ],
2084                         expect: { '': { } }
2085                 }),
2086
2087                 _fetchPackages: function(action, offset, limit, pattern)
2088                 {
2089                         var packages = [ ];
2090
2091                         return action(offset, limit, pattern).then(function(list) {
2092                                 if (!list.total || !list.packages)
2093                                         return { length: 0, total: 0 };
2094
2095                                 packages.push.apply(packages, list.packages);
2096                                 packages.total = list.total;
2097
2098                                 if (limit <= 0)
2099                                         limit = list.total;
2100
2101                                 if (packages.length >= limit)
2102                                         return packages;
2103
2104                                 _luci2.rpc.batch();
2105
2106                                 for (var i = offset + packages.length; i < limit; i += 100)
2107                                         action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
2108
2109                                 return _luci2.rpc.flush();
2110                         }).then(function(lists) {
2111                                 for (var i = 0; i < lists.length; i++)
2112                                 {
2113                                         if (!lists[i].total || !lists[i].packages)
2114                                                 continue;
2115
2116                                         packages.push.apply(packages, lists[i].packages);
2117                                         packages.total = lists[i].total;
2118                                 }
2119
2120                                 return packages;
2121                         });
2122                 },
2123
2124                 listPackages: function(offset, limit, pattern)
2125                 {
2126                         return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
2127                 },
2128
2129                 installedPackages: function(offset, limit, pattern)
2130                 {
2131                         return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
2132                 },
2133
2134                 findPackages: function(offset, limit, pattern)
2135                 {
2136                         return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
2137                 },
2138
2139                 installPackage: _luci2.rpc.declare({
2140                         object: 'luci2.opkg',
2141                         method: 'install',
2142                         params: [ 'package' ],
2143                         expect: { '': { } }
2144                 }),
2145
2146                 removePackage: _luci2.rpc.declare({
2147                         object: 'luci2.opkg',
2148                         method: 'remove',
2149                         params: [ 'package' ],
2150                         expect: { '': { } }
2151                 }),
2152
2153                 getConfig: _luci2.rpc.declare({
2154                         object: 'luci2.opkg',
2155                         method: 'config_get',
2156                         expect: { config: '' }
2157                 }),
2158
2159                 setConfig: _luci2.rpc.declare({
2160                         object: 'luci2.opkg',
2161                         method: 'config_set',
2162                         params: [ 'data' ]
2163                 })
2164         };
2165
2166         this.session = {
2167
2168                 login: _luci2.rpc.declare({
2169                         object: 'session',
2170                         method: 'login',
2171                         params: [ 'username', 'password' ],
2172                         expect: { '': { } }
2173                 }),
2174
2175                 access: _luci2.rpc.declare({
2176                         object: 'session',
2177                         method: 'access',
2178                         params: [ 'scope', 'object', 'function' ],
2179                         expect: { access: false }
2180                 }),
2181
2182                 isAlive: function()
2183                 {
2184                         return _luci2.session.access('ubus', 'session', 'access');
2185                 },
2186
2187                 startHeartbeat: function()
2188                 {
2189                         this._hearbeatInterval = window.setInterval(function() {
2190                                 _luci2.session.isAlive().then(function(alive) {
2191                                         if (!alive)
2192                                         {
2193                                                 _luci2.session.stopHeartbeat();
2194                                                 _luci2.ui.login(true);
2195                                         }
2196
2197                                 });
2198                         }, _luci2.globals.timeout * 2);
2199                 },
2200
2201                 stopHeartbeat: function()
2202                 {
2203                         if (typeof(this._hearbeatInterval) != 'undefined')
2204                         {
2205                                 window.clearInterval(this._hearbeatInterval);
2206                                 delete this._hearbeatInterval;
2207                         }
2208                 }
2209         };
2210
2211         this.ui = {
2212
2213                 saveScrollTop: function()
2214                 {
2215                         this._scroll_top = $(document).scrollTop();
2216                 },
2217
2218                 restoreScrollTop: function()
2219                 {
2220                         if (typeof(this._scroll_top) == 'undefined')
2221                                 return;
2222
2223                         $(document).scrollTop(this._scroll_top);
2224
2225                         delete this._scroll_top;
2226                 },
2227
2228                 loading: function(enable)
2229                 {
2230                         var win = $(window);
2231                         var body = $('body');
2232
2233                         var state = _luci2.ui._loading || (_luci2.ui._loading = {
2234                                 modal: $('<div />')
2235                                         .addClass('modal fade')
2236                                         .append($('<div />')
2237                                                 .addClass('modal-dialog')
2238                                                 .append($('<div />')
2239                                                         .addClass('modal-content luci2-modal-loader')
2240                                                         .append($('<div />')
2241                                                                 .addClass('modal-body')
2242                                                                 .text(_luci2.tr('Loading data…')))))
2243                                         .appendTo(body)
2244                                         .modal({
2245                                                 backdrop: 'static',
2246                                                 keyboard: false
2247                                         })
2248                         });
2249
2250                         state.modal.modal(enable ? 'show' : 'hide');
2251                 },
2252
2253                 dialog: function(title, content, options)
2254                 {
2255                         var win = $(window);
2256                         var body = $('body');
2257
2258                         var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
2259                                 dialog: $('<div />')
2260                                         .addClass('modal fade')
2261                                         .append($('<div />')
2262                                                 .addClass('modal-dialog')
2263                                                 .append($('<div />')
2264                                                         .addClass('modal-content')
2265                                                         .append($('<div />')
2266                                                                 .addClass('modal-header')
2267                                                                 .append('<h4 />')
2268                                                                         .addClass('modal-title'))
2269                                                         .append($('<div />')
2270                                                                 .addClass('modal-body'))
2271                                                         .append($('<div />')
2272                                                                 .addClass('modal-footer')
2273                                                                 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2274                                                                         .click(function() {
2275                                                                                 $(this).parents('div.modal').modal('hide');
2276                                                                         })))))
2277                                         .appendTo(body)
2278                         });
2279
2280                         if (typeof(options) != 'object')
2281                                 options = { };
2282
2283                         if (title === false)
2284                         {
2285                                 state.dialog.modal('hide');
2286
2287                                 return;
2288                         }
2289
2290                         var cnt = state.dialog.children().children().children('div.modal-body');
2291                         var ftr = state.dialog.children().children().children('div.modal-footer');
2292
2293                         ftr.empty();
2294
2295                         if (options.style == 'confirm')
2296                         {
2297                                 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
2298                                         .click(options.confirm || function() { _luci2.ui.dialog(false) }));
2299
2300                                 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
2301                                         .click(options.cancel || function() { _luci2.ui.dialog(false) }));
2302                         }
2303                         else if (options.style == 'close')
2304                         {
2305                                 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2306                                         .click(options.close || function() { _luci2.ui.dialog(false) }));
2307                         }
2308                         else if (options.style == 'wait')
2309                         {
2310                                 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2311                                         .attr('disabled', true));
2312                         }
2313
2314                         state.dialog.find('h4:first').text(title);
2315                         state.dialog.modal('show');
2316
2317                         cnt.empty().append(content);
2318                 },
2319
2320                 upload: function(title, content, options)
2321                 {
2322                         var state = _luci2.ui._upload || (_luci2.ui._upload = {
2323                                 form: $('<form />')
2324                                         .attr('method', 'post')
2325                                         .attr('action', '/cgi-bin/luci-upload')
2326                                         .attr('enctype', 'multipart/form-data')
2327                                         .attr('target', 'cbi-fileupload-frame')
2328                                         .append($('<p />'))
2329                                         .append($('<input />')
2330                                                 .attr('type', 'hidden')
2331                                                 .attr('name', 'sessionid'))
2332                                         .append($('<input />')
2333                                                 .attr('type', 'hidden')
2334                                                 .attr('name', 'filename'))
2335                                         .append($('<input />')
2336                                                 .attr('type', 'file')
2337                                                 .attr('name', 'filedata')
2338                                                 .addClass('cbi-input-file'))
2339                                         .append($('<div />')
2340                                                 .css('width', '100%')
2341                                                 .addClass('progress progress-striped active')
2342                                                 .append($('<div />')
2343                                                         .addClass('progress-bar')
2344                                                         .css('width', '100%')))
2345                                         .append($('<iframe />')
2346                                                 .addClass('pull-right')
2347                                                 .attr('name', 'cbi-fileupload-frame')
2348                                                 .css('width', '1px')
2349                                                 .css('height', '1px')
2350                                                 .css('visibility', 'hidden')),
2351
2352                                 finish_cb: function(ev) {
2353                                         $(this).off('load');
2354
2355                                         var body = (this.contentDocument || this.contentWindow.document).body;
2356                                         if (body.firstChild.tagName.toLowerCase() == 'pre')
2357                                                 body = body.firstChild;
2358
2359                                         var json;
2360                                         try {
2361                                                 json = $.parseJSON(body.innerHTML);
2362                                         } catch(e) {
2363                                                 json = {
2364                                                         message: _luci2.tr('Invalid server response received'),
2365                                                         error: [ -1, _luci2.tr('Invalid data') ]
2366                                                 };
2367                                         };
2368
2369                                         if (json.error)
2370                                         {
2371                                                 L.ui.dialog(L.tr('File upload'), [
2372                                                         $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
2373                                                         $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
2374                                                         $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
2375                                                 ], { style: 'close' });
2376                                         }
2377                                         else if (typeof(state.success_cb) == 'function')
2378                                         {
2379                                                 state.success_cb(json);
2380                                         }
2381                                 },
2382
2383                                 confirm_cb: function() {
2384                                         var f = state.form.find('.cbi-input-file');
2385                                         var b = state.form.find('.progress');
2386                                         var p = state.form.find('p');
2387
2388                                         if (!f.val())
2389                                                 return;
2390
2391                                         state.form.find('iframe').on('load', state.finish_cb);
2392                                         state.form.submit();
2393
2394                                         f.hide();
2395                                         b.show();
2396                                         p.text(_luci2.tr('File upload in progress …'));
2397
2398                                         state.form.parent().parent().find('button').prop('disabled', true);
2399                                 }
2400                         });
2401
2402                         state.form.find('.progress').hide();
2403                         state.form.find('.cbi-input-file').val('').show();
2404                         state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
2405
2406                         state.form.find('[name=sessionid]').val(_luci2.globals.sid);
2407                         state.form.find('[name=filename]').val(options.filename);
2408
2409                         state.success_cb = options.success;
2410
2411                         _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
2412                                 style: 'confirm',
2413                                 confirm: state.confirm_cb
2414                         });
2415                 },
2416
2417                 reconnect: function()
2418                 {
2419                         var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
2420                         var ports     = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
2421                         var address   = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
2422                         var images    = $();
2423                         var interval, timeout;
2424
2425                         _luci2.ui.dialog(
2426                                 _luci2.tr('Waiting for device'), [
2427                                         $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
2428                                         $('<div />')
2429                                                 .css('width', '100%')
2430                                                 .addClass('progressbar')
2431                                                 .addClass('intermediate')
2432                                                 .append($('<div />')
2433                                                         .css('width', '100%'))
2434                                 ], { style: 'wait' }
2435                         );
2436
2437                         for (var i = 0; i < protocols.length; i++)
2438                                 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
2439
2440                         //_luci2.network.getNetworkStatus(function(s) {
2441                         //      for (var i = 0; i < protocols.length; i++)
2442                         //      {
2443                         //              for (var j = 0; j < s.length; j++)
2444                         //              {
2445                         //                      for (var k = 0; k < s[j]['ipv4-address'].length; k++)
2446                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
2447                         //
2448                         //                      for (var l = 0; l < s[j]['ipv6-address'].length; l++)
2449                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
2450                         //              }
2451                         //      }
2452                         //}).then(function() {
2453                                 images.on('load', function() {
2454                                         var url = this.getAttribute('url');
2455                                         _luci2.session.isAlive().then(function(access) {
2456                                                 if (access)
2457                                                 {
2458                                                         window.clearTimeout(timeout);
2459                                                         window.clearInterval(interval);
2460                                                         _luci2.ui.dialog(false);
2461                                                         images = null;
2462                                                 }
2463                                                 else
2464                                                 {
2465                                                         location.href = url;
2466                                                 }
2467                                         });
2468                                 });
2469
2470                                 interval = window.setInterval(function() {
2471                                         images.each(function() {
2472                                                 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
2473                                         });
2474                                 }, 5000);
2475
2476                                 timeout = window.setTimeout(function() {
2477                                         window.clearInterval(interval);
2478                                         images.off('load');
2479
2480                                         _luci2.ui.dialog(
2481                                                 _luci2.tr('Device not responding'),
2482                                                 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2483                                                 { style: 'close' }
2484                                         );
2485                                 }, 180000);
2486                         //});
2487                 },
2488
2489                 login: function(invalid)
2490                 {
2491                         var state = _luci2.ui._login || (_luci2.ui._login = {
2492                                 form: $('<form />')
2493                                         .attr('target', '')
2494                                         .attr('method', 'post')
2495                                         .append($('<p />')
2496                                                 .addClass('alert-message')
2497                                                 .text(_luci2.tr('Wrong username or password given!')))
2498                                         .append($('<p />')
2499                                                 .append($('<label />')
2500                                                         .text(_luci2.tr('Username'))
2501                                                         .append($('<br />'))
2502                                                         .append($('<input />')
2503                                                                 .attr('type', 'text')
2504                                                                 .attr('name', 'username')
2505                                                                 .attr('value', 'root')
2506                                                                 .addClass('form-control')
2507                                                                 .keypress(function(ev) {
2508                                                                         if (ev.which == 10 || ev.which == 13)
2509                                                                                 state.confirm_cb();
2510                                                                 }))))
2511                                         .append($('<p />')
2512                                                 .append($('<label />')
2513                                                         .text(_luci2.tr('Password'))
2514                                                         .append($('<br />'))
2515                                                         .append($('<input />')
2516                                                                 .attr('type', 'password')
2517                                                                 .attr('name', 'password')
2518                                                                 .addClass('form-control')
2519                                                                 .keypress(function(ev) {
2520                                                                         if (ev.which == 10 || ev.which == 13)
2521                                                                                 state.confirm_cb();
2522                                                                 }))))
2523                                         .append($('<p />')
2524                                                 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
2525
2526                                 response_cb: function(response) {
2527                                         if (!response.ubus_rpc_session)
2528                                         {
2529                                                 _luci2.ui.login(true);
2530                                         }
2531                                         else
2532                                         {
2533                                                 _luci2.globals.sid = response.ubus_rpc_session;
2534                                                 _luci2.setHash('id', _luci2.globals.sid);
2535                                                 _luci2.session.startHeartbeat();
2536                                                 _luci2.ui.dialog(false);
2537                                                 state.deferred.resolve();
2538                                         }
2539                                 },
2540
2541                                 confirm_cb: function() {
2542                                         var u = state.form.find('[name=username]').val();
2543                                         var p = state.form.find('[name=password]').val();
2544
2545                                         if (!u)
2546                                                 return;
2547
2548                                         _luci2.ui.dialog(
2549                                                 _luci2.tr('Logging in'), [
2550                                                         $('<p />').text(_luci2.tr('Log in in progress …')),
2551                                                         $('<div />')
2552                                                                 .css('width', '100%')
2553                                                                 .addClass('progressbar')
2554                                                                 .addClass('intermediate')
2555                                                                 .append($('<div />')
2556                                                                         .css('width', '100%'))
2557                                                 ], { style: 'wait' }
2558                                         );
2559
2560                                         _luci2.globals.sid = '00000000000000000000000000000000';
2561                                         _luci2.session.login(u, p).then(state.response_cb);
2562                                 }
2563                         });
2564
2565                         if (!state.deferred || state.deferred.state() != 'pending')
2566                                 state.deferred = $.Deferred();
2567
2568                         /* try to find sid from hash */
2569                         var sid = _luci2.getHash('id');
2570                         if (sid && sid.match(/^[a-f0-9]{32}$/))
2571                         {
2572                                 _luci2.globals.sid = sid;
2573                                 _luci2.session.isAlive().then(function(access) {
2574                                         if (access)
2575                                         {
2576                                                 _luci2.session.startHeartbeat();
2577                                                 state.deferred.resolve();
2578                                         }
2579                                         else
2580                                         {
2581                                                 _luci2.setHash('id', undefined);
2582                                                 _luci2.ui.login();
2583                                         }
2584                                 });
2585
2586                                 return state.deferred;
2587                         }
2588
2589                         if (invalid)
2590                                 state.form.find('.alert-message').show();
2591                         else
2592                                 state.form.find('.alert-message').hide();
2593
2594                         _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2595                                 style: 'confirm',
2596                                 confirm: state.confirm_cb
2597                         });
2598
2599                         state.form.find('[name=password]').focus();
2600
2601                         return state.deferred;
2602                 },
2603
2604                 cryptPassword: _luci2.rpc.declare({
2605                         object: 'luci2.ui',
2606                         method: 'crypt',
2607                         params: [ 'data' ],
2608                         expect: { crypt: '' }
2609                 }),
2610
2611
2612                 _acl_merge_scope: function(acl_scope, scope)
2613                 {
2614                         if ($.isArray(scope))
2615                         {
2616                                 for (var i = 0; i < scope.length; i++)
2617                                         acl_scope[scope[i]] = true;
2618                         }
2619                         else if ($.isPlainObject(scope))
2620                         {
2621                                 for (var object_name in scope)
2622                                 {
2623                                         if (!$.isArray(scope[object_name]))
2624                                                 continue;
2625
2626                                         var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2627
2628                                         for (var i = 0; i < scope[object_name].length; i++)
2629                                                 acl_object[scope[object_name][i]] = true;
2630                                 }
2631                         }
2632                 },
2633
2634                 _acl_merge_permission: function(acl_perm, perm)
2635                 {
2636                         if ($.isPlainObject(perm))
2637                         {
2638                                 for (var scope_name in perm)
2639                                 {
2640                                         var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2641                                         this._acl_merge_scope(acl_scope, perm[scope_name]);
2642                                 }
2643                         }
2644                 },
2645
2646                 _acl_merge_group: function(acl_group, group)
2647                 {
2648                         if ($.isPlainObject(group))
2649                         {
2650                                 if (!acl_group.description)
2651                                         acl_group.description = group.description;
2652
2653                                 if (group.read)
2654                                 {
2655                                         var acl_perm = acl_group.read || (acl_group.read = { });
2656                                         this._acl_merge_permission(acl_perm, group.read);
2657                                 }
2658
2659                                 if (group.write)
2660                                 {
2661                                         var acl_perm = acl_group.write || (acl_group.write = { });
2662                                         this._acl_merge_permission(acl_perm, group.write);