summaryrefslogtreecommitdiffstats
path: root/applications/luci-app-lxc/ucode/controller/lxc.uc
blob: 1f4f041c7da60886c0e8b6696632e553ab86cc1b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
// LXC management endpoint
// Copyright 2026 Paul Donald <newtwen+github@gmail.com>
// Licensed to the public under the Apache License 2.0.
// Built against the lxc API v6
'use strict';

import * as fs from 'fs';
import { cursor } from 'uci';
import { connect } from 'ubus';
const ctx = cursor();
const LXC_URL  = ctx.get('lxc', 'lxc', 'url');

function shellquote(value) {
	if (value == null)
		value = '';

	return "'" + replace(value, "'", "'\\''") + "'";
}

function is_valid_lxc_name(value) {
	// LXC container names: start with alphanumeric or underscore, followed by
	// alphanumeric, underscore, dash. No periods, no slashes, no leading dash
	return type(value) == 'string' && match(value, /^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}$/) != null;
}

function is_valid_lxc_template(value) {
	return type(value) == 'string' && match(value, /^.+:.+$/) != null;
}

function statfs(path) {
	let p = fs.popen('df -kP ' + path);
	p.read('line');               // header
	let line = p.read('line');    // data line
	p.close();

	if (!line) return null;
	let cols = split(trim(line), /\s+/);
	// return {
	// 	filesystem: cols[0],
	// 	blocks_kb: int(cols[1],10),
	// 	used_kb:    int(cols[2],10),
	// 	avail_kb:   int(cols[3],10),
	// 	used_pct:   cols[4],
	// 	mount:      cols.slice(5).join(' ')
	// };
	return int(cols[3],10);
}

const LXCController = {

	lxc_get_downloadable: function() {
		let target = this.lxc_get_arch_target(LXC_URL);
		let templates = [];
		let content = fs.popen(`sh /usr/share/lxc/templates/lxc-download --list --server ${shellquote(LXC_URL)} 2>/dev/null`, 'r').read('all');
		content = split(content, '\n');
		for (let line in content) {
			let arr = match(line, /^(\S+)\s+(\S+)\s+(\S+)\s+default\s+(\S+)\s*$/);
			if(length(arr) < 3) continue;
			let dist = trim(arr[1]);
			let version = trim(arr[2]);
			let dist_target = trim(arr[3]);
			if (dist && version && dist_target && dist_target == target) 
				push(templates, `${ dist }:${ version }`);
		}
		// content.close();

		http.prepare_content('application/json');
		http.write_json(templates);
	},

	lxc_create: function(lxc_name, lxc_template) {
		http.prepare_content('text/plain');
		if (!is_valid_lxc_name(lxc_name)) {
			return;
		}
		if (!is_valid_lxc_template(lxc_template)) {
			return;
		}

		let path = this.lxc_get_config_path();
		if (!path) return;
		let arr = match(lxc_template, /^(.+):(.+)$/);
		let lxc_dist = arr[1], lxc_release = arr[2];

		system(`/usr/bin/lxc-create --quiet --name ${shellquote(lxc_name)} --bdev best --template download -- --dist ${shellquote(lxc_dist)} --release ${shellquote(lxc_release)} --arch ${this.lxc_get_arch_target(LXC_URL)} --server ${shellquote(LXC_URL)}`);

		while (fs.access(path + lxc_name + '/partial')) {
			sleep(1000);
		}

		http.write('0');
	},

	lxc_action: function(lxc_action, lxc_name) {
		let ubus = connect();
		let data = ubus.call('lxc', lxc_action, { name: lxc_name });

		http.prepare_content('application/json');
		http.write_json(data ? data : '');
	},

	lxc_get_config_path: function() {
		let content = fs.readfile('/etc/lxc/lxc.conf');
		let ret = match(content, /^\s*lxc.lxcpath\s*=\s*(\S*)/);
		if (ret && length(ret) == 2) {
			if (fs.access(ret[1])) {
				let min_space = int(ctx.get('lxc', 'lxc', 'min_space')) || 100000;
				let free_space = statfs(ret[1]);
				if (free_space && free_space >= min_space) {
					let min_temp = int(ctx.get('lxc', 'lxc', 'min_temp')) || 100000;
					let free_temp = statfs('/tmp');
					if (free_temp && free_temp >= min_temp)
						return ret[1] + '/';
					else
						return 'lxc error: not enough temporary space (< ' + min_temp + ' KB)';
				}
				else
					return 'lxc error: not enough space (< ' + min_space + ' KB)';
			}
			else
				return 'lxc error: directory not found';
		}
		else
			return 'lxc error: config path is empty';
	},

	lxc_configuration_get: function(lxc_name) {
		http.prepare_content('text/plain');

		// Re-validate before fs.readfile as lxc_name,
		// escapes the lxcpath base and reaches arbitrary files
		if (!is_valid_lxc_name(lxc_name)) {
			http.status(400, 'Bad Request');
			return;
		}

		// lxc_get_config_path() returns an 'lxc error: …' string on failure
		// rather than null. Refuse to proceed instead of concatenating that
		// into a real filesystem path
		let base = this.lxc_get_config_path();
		if (!base || index(base, 'lxc error') == 0) {
			http.status(500, base);
			return;
		}
		let content = fs.readfile(base + lxc_name + '/config');
		http.write(content);
	},

	lxc_configuration_set: function(lxc_name) {
		http.prepare_content('text/plain');

		// Re-validate before fs.writefile as lxc_name,
		// escapes the lxcpath
		if (!is_valid_lxc_name(lxc_name)) {
			http.status(400, 'Bad Request');
			return;
		}

		// lxc_get_config_path() returns an 'lxc error: …' string on failure
		// rather than null. Refuse to proceed instead of concatenating that
		// into a real filesystem path
		let base = this.lxc_get_config_path();
		if (!base || index(base, 'lxc error') == 0) {
			http.status(500, base);
			return;
		}
		let lxc_configuration = http.formvalue('lxc_conf');
		lxc_configuration = http.urldecode(lxc_configuration, true);
		if (!lxc_configuration) {
			return 'lxc error: config formvalue is empty';
		}
		fs.writefile(base + lxc_name + '/config', lxc_configuration);
		http.write('0');
	},

	lxc_get_arch_target: function(url) {
		let target = split(fs.popen('uname -m', 'r').read('line'), '\n');
		if (url && match(url, /images.linuxcontainers.org/)) {
			let target_map = {
				armv5:  'armel',
				armv6:  'armel',
				armv7:  'armhf',
				armv8:  'arm64',
				aarch64:'arm64',
				i686 :  'i386',
				x86_64: 'amd64',
			};
			for (let k, v in target_map) {
				if (target[0] == k) {
					return v;
				}
			}
		}
		return target[0];
	},
};

// Export all handlers with automatic error wrapping
let controller = LXCController;
let exports = {};
for (let k, v in controller) {
	if (type(v) == 'function')
		exports[k] = v;
}

return exports;