5 var callFileStat, callFileRead, callFileWrite, callFileExec, callFileRemove;
7 callFileStat = rpc.declare({
14 callFileRead = rpc.declare({
19 filter: function(s) { return (s || '').trim() }
22 callFileWrite = rpc.declare({
25 params: [ 'path', 'data' ]
28 callFileExec = rpc.declare({
31 params: [ 'command', 'params' ],
32 expect: { '': { code: -1 } }
35 callFileRemove = rpc.declare({
41 function pingDevice(proto, ipaddr) {
42 var target = '%s://%s%s?%s'.format(proto || 'http', ipaddr || window.location.host, L.resource('icons/loading.gif'), Math.random());
44 return new Promise(function(resolveFn, rejectFn) {
45 var img = new Image();
47 img.onload = resolveFn;
48 img.onerror = rejectFn;
50 window.setTimeout(rejectFn, 1000);
56 function awaitReconnect(/* ... */) {
57 var ipaddrs = arguments.length ? arguments : [ window.location.host ];
59 window.setTimeout(function() {
60 L.Poll.add(function() {
61 var tasks = [], reachable = false;
63 for (var i = 0; i < 2; i++)
64 for (var j = 0; j < ipaddrs.length; j++)
65 tasks.push(pingDevice(i ? 'https' : 'http', ipaddrs[j])
66 .then(function(ev) { reachable = ev.target.src.replace(/^(https?:\/\/[^\/]+).*$/, '$1/') }, function() {}));
68 return Promise.all(tasks).then(function() {
71 window.location = reachable;
78 function fileUpload(node, path) {
79 return new Promise(function(resolveFn, rejectFn) {
80 L.ui.showModal(_('Uploading file…'), [
81 E('p', _('Please select the file to upload.')),
82 E('div', { 'style': 'display:flex' }, [
83 E('div', { 'class': 'left', 'style': 'flex:1' }, [
86 style: 'display:none',
87 change: function(ev) {
88 L.dom.parent(ev.target, '.modal').querySelector('.cbi-button-action.important').disabled = false;
93 'click': function(ev) {
94 ev.target.previousElementSibling.click();
98 E('div', { 'class': 'right', 'style': 'flex:1' }, [
101 'click': function() {
103 rejectFn(new Error('Upload has been cancelled'));
108 'class': 'btn cbi-button-action important',
110 'click': function(ev) {
111 var input = L.dom.parent(ev.target, '.modal').querySelector('input[type="file"]');
116 var progress = E('div', { 'class': 'cbi-progressbar', 'title': '0%' }, E('div', { 'style': 'width:0' }));
118 L.ui.showModal(_('Uploading file…'), [ progress ]);
120 var data = new FormData();
122 data.append('sessionid', rpc.getSessionID());
123 data.append('filename', path);
124 data.append('filedata', input.files[0]);
126 L.Request.post('/cgi-bin/cgi-upload', data, {
128 progress: function(pev) {
129 var percent = (pev.loaded / pev.total) * 100;
131 node.data = '%.2f%%'.format(percent);
133 progress.setAttribute('title', '%.2f%%'.format(percent));
134 progress.firstElementChild.style.width = '%.2f%%'.format(percent);
136 }).then(function(res) {
137 var reply = res.json();
141 if (L.isObject(reply) && reply.failure) {
142 L.ui.addNotification(null, E('p', _('Upload request failed: %s').format(reply.message)));
143 rejectFn(new Error(reply.failure));
160 function findStorageSize(procmtd, procpart) {
161 var kernsize = 0, rootsize = 0, wholesize = 0;
163 procmtd.split(/\n/).forEach(function(ln) {
164 var match = ln.match(/^mtd\d+: ([0-9a-f]+) [0-9a-f]+ "(.+)"$/),
165 size = match ? parseInt(match[1], 16) : 0;
167 switch (match ? match[2] : '') {
170 if (size > wholesize)
190 else if (kernsize > 0 && rootsize > kernsize)
191 return kernsize + rootsize;
193 procpart.split(/\n/).forEach(function(ln) {
194 var match = ln.match(/^\s*\d+\s+\d+\s+(\d+)\s+(\S+)$/);
196 var size = parseInt(match[1], 10);
198 if (!match[2].match(/\d/) && size > 2048 && wholesize == 0)
199 wholesize = size * 1024;
207 var mapdata = { actions: {}, config: {} };
209 return L.view.extend({
211 var max_mtd = 10, max_ubi = 2, max_ubi_vol = 4;
213 callFileStat('/lib/upgrade/platform.sh'),
214 callFileRead('/proc/sys/kernel/hostname'),
215 callFileRead('/proc/mtd'),
216 callFileRead('/proc/partitions')
219 for (var i = 0; i < max_mtd; i++)
220 tasks.push(callFileRead('/sys/devices/virtual/mtd/mtd%d/name'.format(i)));
222 for (var i = 0; i < max_ubi; i++)
223 for (var j = 0; j < max_ubi_vol; j++)
224 tasks.push(callFileRead('/sys/devices/virtual/ubi/ubi%d/ubi%d_%d/name'.format(i, i, j)));
226 return Promise.all(tasks);
229 handleBackup: function(ev) {
230 var form = E('form', {
232 action: '/cgi-bin/cgi-backup',
233 enctype: 'application/x-www-form-urlencoded'
234 }, E('input', { type: 'hidden', name: 'sessionid', value: rpc.getSessionID() }));
236 ev.currentTarget.parentNode.appendChild(form);
239 form.parentNode.removeChild(form);
242 handleFirstboot: function(ev) {
243 if (!confirm(_('Do you really want to erase all settings?')))
246 return callFileExec('/sbin/firstboot', [ '-r', '-y' ]).then(function(res) {
248 return L.ui.addNotification(null, E('p', _('The firstboot command failed with code %d').format(res.code)));
250 L.ui.showModal(_('Erasing...'), [
251 E('p', { 'class': 'spinning' }, _('The system is erasing the configuration partition now and will reboot itself when finished.'))
254 awaitReconnect('192.168.1.1', 'openwrt.lan');
258 handleRestore: function(ev) {
259 return fileUpload(ev.target, '/tmp/backup.tar.gz')
260 .then(L.bind(function(btn, res) {
261 btn.firstChild.data = _('Checking archive…');
262 return callFileExec('/bin/tar', [ '-tzf', '/tmp/backup.tar.gz' ]);
264 .then(L.bind(function(btn, res) {
266 L.ui.addNotification(null, E('p', _('The uploaded backup archive is not readable')));
267 return callFileRemove('/tmp/backup.tar.gz');
270 L.ui.showModal(_('Apply backup?'), [
271 E('p', _('The uploaded backup archive appears to be valid and contains the files listed below. Press "Continue" to restore the backup and reboot, or "Cancel" to abort the operation.')),
272 E('pre', {}, [ res.stdout ]),
273 E('div', { 'class': 'right' }, [
276 'click': L.ui.createHandlerFn(this, function(ev) {
277 return callFileRemove('/tmp/backup.tar.gz').finally(L.ui.hideModal);
279 }, [ _('Cancel') ]), ' ',
281 'class': 'btn cbi-button-action important',
282 'click': L.ui.createHandlerFn(this, 'handleRestoreConfirm', btn)
283 }, [ _('Continue') ])
287 .finally(L.bind(function(btn, input) {
288 btn.firstChild.data = _('Upload archive...');
289 }, this, ev.target));
292 handleRestoreConfirm: function(btn, ev) {
293 return callFileExec('/sbin/sysupgrade', [ '--restore-backup', '/tmp/backup.tar.gz' ])
294 .then(L.bind(function(btn, res) {
296 L.ui.addNotification(null, [
297 E('p', _('The restore command failed with code %d').format(res.code)),
298 res.stderr ? E('pre', {}, [ res.stderr ]) : ''
300 L.raise('Error', 'Unpack failed');
303 btn.firstChild.data = _('Rebooting…');
304 return callFileExec('/sbin/reboot');
306 .then(L.bind(function(res) {
308 L.ui.addNotification(null, E('p', _('The reboot command failed with code %d').format(res.code)));
309 L.raise('Error', 'Reboot failed');
312 L.ui.showModal(_('Rebooting…'), [
313 E('p', { 'class': 'spinning' }, _('The system is rebooting now. If the restored configuration changed the current LAN IP address, you might need to reconnect manually.'))
316 awaitReconnect(window.location.host, '192.168.1.1', 'openwrt.lan');
318 .catch(function() { btn.firstChild.data = _('Upload archive...') });
321 handleBlock: function(hostname, ev) {
322 var mtdblock = L.dom.parent(ev.target, '.cbi-section').querySelector('[data-name="mtdselect"] select').value;
323 var form = E('form', {
325 'action': '/cgi-bin/cgi-download',
326 'enctype': 'application/x-www-form-urlencoded'
328 E('input', { 'type': 'hidden', 'name': 'sessionid', 'value': rpc.getSessionID() }),
329 E('input', { 'type': 'hidden', 'name': 'path', 'value': '/dev/mtdblock%d'.format(mtdblock) }),
330 E('input', { 'type': 'hidden', 'name': 'filename', 'value': '%s.mtd%d.bin'.format(hostname, mtdblock) })
333 ev.currentTarget.parentNode.appendChild(form);
336 form.parentNode.removeChild(form);
339 handleSysupgrade: function(storage_size, ev) {
340 return fileUpload(ev.target.firstChild, '/tmp/firmware.bin')
341 .then(L.bind(function(btn, reply) {
342 btn.firstChild.data = _('Checking image…');
344 L.ui.showModal(_('Checking image…'), [
345 E('span', { 'class': 'spinning' }, _('Verifying the uploaded image file.'))
348 return callFileExec('/sbin/sysupgrade', [ '--test', '/tmp/firmware.bin' ])
349 .then(function(res) { return [ reply, res ] });
351 .then(L.bind(function(btn, res) {
352 var keep = document.querySelector('[data-name="keep"] input[type="checkbox"]'),
353 force = E('input', { type: 'checkbox' }),
354 is_invalid = (res[1].code != 0),
355 is_too_big = (storage_size > 0 && res[0].size > storage_size),
358 body.push(E('p', _('The flash image was uploaded. Below is the checksum and file size listed, compare them with the original file to ensure data integrity. <br /> Click "Proceed" below to start the flash procedure.')));
359 body.push(E('ul', {}, [
360 res[0].size ? E('li', {}, '%s: %1024.2mB'.format(_('Size'), res[0].size)) : '',
361 res[0].checksum ? E('li', {}, '%s: %s'.format(_('MD5'), res[0].checksum)) : '',
362 res[0].sha256sum ? E('li', {}, '%s: %s'.format(_('SHA256'), res[0].sha256sum)) : '',
363 E('li', {}, keep.checked ? _('Configuration files will be kept') : _('Caution: Configuration files will be erased'))
366 if (is_invalid || is_too_big)
370 body.push(E('p', { 'class': 'alert-message' }, [
371 _('It appears that you are trying to flash an image that does not fit into the flash memory, please verify the image file!')
375 body.push(E('p', { 'class': 'alert-message' }, [
376 res[1].stderr ? res[1].stderr : '',
377 res[1].stderr ? E('br') : '',
378 res[1].stderr ? E('br') : '',
379 _('The uploaded image file does not contain a supported format. Make sure that you choose the generic image format for your platform.')
382 if (is_invalid || is_too_big)
383 body.push(E('p', {}, E('label', { 'class': 'btn alert-message danger' }, [
384 force, ' ', _('Force upgrade'),
386 _('Select \'Force upgrade\' to flash the image even if the image format check fails. Use only if you are sure that the firmware is correct and meant for your device!')
389 var cntbtn = E('button', {
390 'class': 'btn cbi-button-action important',
391 'click': L.ui.createHandlerFn(this, 'handleSysupgradeConfirm', btn, keep.checked, force.checked),
392 'disabled': (is_invalid || is_too_big) ? true : null
393 }, [ _('Continue') ]);
395 body.push(E('div', { 'class': 'right' }, [
398 'click': L.ui.createHandlerFn(this, function(ev) {
399 return callFileRemove('/tmp/firmware.bin').finally(L.ui.hideModal);
401 }, [ _('Cancel') ]), ' ', cntbtn
404 force.addEventListener('change', function(ev) {
405 cntbtn.disabled = !ev.target.checked;
408 L.ui.showModal(_('Flash image?'), body);
410 .finally(L.bind(function(btn) {
411 btn.firstChild.data = _('Flash image...');
412 }, this, ev.target));
415 handleSysupgradeConfirm: function(btn, keep, force, ev) {
416 btn.firstChild.data = _('Flashing…');
418 L.ui.showModal(_('Flashing…'), [
419 E('p', { 'class': 'spinning' }, _('The system is flashing now.<br /> DO NOT POWER OFF THE DEVICE!<br /> Wait a few minutes before you try to reconnect. It might be necessary to renew the address of your computer to reach the device again, depending on your settings.'))
428 opts.push('--force');
430 opts.push('/tmp/firmware.bin');
432 /* Currently the sysupgrade rpc call will not return, hence no promise handling */
433 callFileExec('/sbin/sysupgrade', opts);
435 awaitReconnect(window.location.host, '192.168.1.1', 'openwrt.lan');
438 handleBackupList: function(ev) {
439 return callFileExec('/sbin/sysupgrade', [ '--list-backup' ]).then(function(res) {
441 L.ui.addNotification(null, [
442 E('p', _('The sysupgrade command failed with code %d').format(res.code)),
443 res.stderr ? E('pre', {}, [ res.stderr ]) : ''
445 L.raise('Error', 'Sysupgrade failed');
448 L.ui.showModal(_('Backup file list'), [
449 E('p', _('Below is the determined list of files to backup. It consists of changed configuration files marked by opkg, essential base files and the user defined backup patterns.')),
450 E('ul', {}, (res.stdout || '').trim().split(/\n/).map(function(ln) { return E('li', {}, ln) })),
451 E('div', { 'class': 'right' }, [
454 'click': L.ui.hideModal
461 handleBackupSave: function(m, ev) {
462 return m.save(function() {
463 return callFileWrite('/etc/sysupgrade.conf', mapdata.config.editlist.trim().replace(/\r\n/g, '\n') + '\n');
465 L.ui.addNotification(null, E('p', _('Contents have been saved.')), 'info');
466 }).catch(function(e) {
467 L.ui.addNotification(null, E('p', _('Unable to save contents: %s').format(e)));
471 render: function(rpc_replies) {
472 var has_sysupgrade = (rpc_replies[0].type == 'file'),
473 hostname = rpc_replies[1],
474 procmtd = rpc_replies[2],
475 procpart = rpc_replies[3],
476 has_rootfs_data = rpc_replies.slice(4).filter(function(n) { return n == 'rootfs_data' })[0],
477 storage_size = findStorageSize(procmtd, procpart),
480 m = new form.JSONMap(mapdata, _('Flash operations'));
483 s = m.section(form.NamedSection, 'actions', _('Actions'));
486 o = s.option(form.SectionValue, 'actions', form.NamedSection, 'actions', 'actions', _('Backup'), _('Click "Generate archive" to download a tar archive of the current configuration files.'));
489 o = ss.option(form.Button, 'dl_backup', _('Download backup'));
490 o.inputstyle = 'action important';
491 o.inputtitle = _('Generate archive');
492 o.onclick = this.handleBackup;
495 o = s.option(form.SectionValue, 'actions', form.NamedSection, 'actions', 'actions', _('Restore'), _('To restore configuration files, you can upload a previously generated backup archive here. To reset the firmware to its initial state, click "Perform reset" (only possible with squashfs images).'));
498 if (has_rootfs_data) {
499 o = ss.option(form.Button, 'reset', _('Reset to defaults'));
500 o.inputstyle = 'negative important';
501 o.inputtitle = _('Perform reset');
502 o.onclick = this.handleFirstboot;
505 o = ss.option(form.Button, 'restore', _('Restore backup'), _('Custom files (certificates, scripts) may remain on the system. To prevent this, perform a factory-reset first.'));
506 o.inputstyle = 'action important';
507 o.inputtitle = _('Upload archive...');
508 o.onclick = L.bind(this.handleRestore, this);
511 if (procmtd.length) {
512 o = s.option(form.SectionValue, 'actions', form.NamedSection, 'actions', 'actions', _('Save mtdblock contents'), _('Click "Save mtdblock" to download specified mtdblock file. (NOTE: THIS FEATURE IS FOR PROFESSIONALS! )'));
515 o = ss.option(form.ListValue, 'mtdselect', _('Choose mtdblock'));
516 procmtd.split(/\n/).forEach(function(ln) {
517 var match = ln.match(/^mtd(\d+): .+ "(.+?)"$/);
519 o.value(match[1], match[2]);
522 o = ss.option(form.Button, 'mtddownload', _('Download mtdblock'));
523 o.inputstyle = 'action important';
524 o.inputtitle = _('Save mtdblock');
525 o.onclick = L.bind(this.handleBlock, this, hostname);
529 o = s.option(form.SectionValue, 'actions', form.NamedSection, 'actions', 'actions', _('Flash new firmware image'),
531 ? _('Upload a sysupgrade-compatible image here to replace the running firmware. Check "Keep settings" to retain the current configuration (requires a compatible firmware image).')
532 : _('Sorry, there is no sysupgrade support present; a new firmware image must be flashed manually. Please refer to the wiki for device specific install instructions.'));
536 if (has_sysupgrade) {
537 o = ss.option(form.Flag, 'keep', _('Keep settings'));
538 o.default = o.enabled;
540 o = ss.option(form.Button, 'sysupgrade', _('Image'));
541 o.inputstyle = 'action important';
542 o.inputtitle = _('Flash image...');
543 o.onclick = L.bind(this.handleSysupgrade, this, storage_size);
547 s = m.section(form.NamedSection, 'config', 'config', _('Configuration'), _('This is a list of shell glob patterns for matching files and directories to include during sysupgrade. Modified files in /etc/config/ and certain other configurations are automatically preserved.'));
548 s.render = L.bind(function(view /*, ... */) {
549 return form.NamedSection.prototype.render.apply(this, this.varargs(arguments, 1))
550 .then(L.bind(function(node) {
551 node.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
553 'class': 'cbi-button cbi-button-save',
554 'click': L.ui.createHandlerFn(view, 'handleBackupSave', this.map)
562 o = s.option(form.Button, 'showlist', _('Show current backup file list'));
563 o.inputstyle = 'action';
564 o.inputtitle = _('Open list...');
565 o.onclick = L.bind(this.handleBackupList, this);
567 o = s.option(form.TextValue, 'editlist');
570 o.load = function(section_id) {
571 return callFileRead('/etc/sysupgrade.conf');
578 handleSaveApply: null,