summaryrefslogtreecommitdiffstats
path: root/modules-available/serversetup-bwlp-ipxe/inc/scriptbuildergrub.inc.php
blob: 9dce5214352058b2e39e7ea038536d368d0fdc7f (plain) (blame)
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
<?php

class ScriptBuilderGrub extends ScriptBuilderBase
{

	/** @var bool */
	private $confCodeEmited = false;

	public function __construct(?string $platform = null, ?string $serverIp = null)
	{
		if (empty($platform)) {
			$platform = Request::any('platform', null, 'string');
			if ($platform === 'pc' || stripos($platform, 'bios') !== false) {
				$platform = 'PCBIOS';
			}
		}
		parent::__construct($platform, $serverIp, false);
	}

	private function getConfCode(): string
	{
		if ($this->confCodeEmited)
			return '';
		$this->confCodeEmited = true;
		$str = '
if ! [ "$uuid" ] ; then
  smbios --type 1 --get-uuid 8 --set uuid
fi
set serverip="' . $this->getLocalIp() . '"
';
		foreach (['mac', 'ip', 'domain', 'hostname'] as $var) {
			$str .= <<<EOF
if ! [ "\$$var" ] ; then
	set $var="\$net_default_$var"
fi
if ! [ "\$$var" ] ; then
	set $var="\$net_efinet0_dhcp_$var"
fi

EOF;

		}
		return $str;
	}

	private function getLocalIp(): string
	{
		if (isset($_SERVER['SCRIPT_URI']) && preg_match('#^\w+://([^/]+)#', $_SERVER['SCRIPT_URI'], $out)) {
			$host = $out[1];
		} elseif (isset($_SERVER['SERVER_NAME'])) {
			$host = $_SERVER['SERVER_NAME'];
		} elseif (isset($_SERVER['SERVER_ADDR'])) {
			$host = $_SERVER['SERVER_ADDR'];
		} else {
			$host = $this->serverIp;
		}
		return $host;
	}

	private function getGrubBase(): string
	{
		return '(http,' . $this->getLocalIp() . ')';
	}

	private function getUrlBase(): string
	{
		$host = $this->getGrubBase();
		if (isset($_SERVER['REQUEST_URI'])) {
			$url = parse_url($_SERVER['REQUEST_URI']);
			$path = $url['path'];
		} else {
			// Static fallback
			$path = '/boot/ipxe';
		}
		return $host . $path;

	}

	private function getUrlFull(?string $key = null, ?string $value = null): string
	{
		$url = parse_url($_SERVER['REQUEST_URI']);
		$urlbase = $this->getUrlBase();
		if (empty($url['query'])) {
			$fromQuery = [];
		} else {
			parse_str($url['query'], $fromQuery);
			foreach ($fromQuery as &$v) {
				$v = urlencode($v);
			}
			unset($v);
		}
		unset($fromQuery['entryid'], $fromQuery['special'], $fromQuery['redir']);
		if ($key !== null) {
			$fromQuery[$key] = $value;
		}
		$required = [
			'type' => 'grub',
			'uuid' => '$uuid',
			'mac' => '$mac',
			'platform' => '$grub_platform',
		];
		$fullQuery = '?';
		foreach ($required + $fromQuery as $k => $v) { // Loop instead of http_build_query since we don't want escaping for the varnames!
			$fullQuery .= $k . '=' . $v . '&';
		}
		return $urlbase . $fullQuery;
	}

	/**
	 * Redirect to same URL, but add our extended params
	 */
	private function redirect(string $key = null, string $value = null): string
	{
		// Redirect to self with added parameters
		$urlfull = $this->getUrlFull($key, $value);
		return $this->getConfCode() . <<<HERE

set self="${urlfull}"
echo "Chaining to \$self..."
configfile \${self}redir=1

HERE;
	}

	/**
	 * Called when we handle a real client request, and don't just generate static data
	 * for whatever use-case that might have. In the latter case, it wouldn't make much sense
	 * to generate a redirect code snippet.
	 *
	 * @return string
	 */
	public function bootstrapLive()
	{
		// Check if required arguments are given; if not, spit out according script and chain to self
		if ($this->uuid === null || $this->platform === '') {
			// REQUIRED so we can hide incompatible entries
			// but avoid redirect cycle
			if (Request::any('redir', '', 'string') === '') {
				return $this->redirect();
			}
		}
		return false;
	}

	public function getBootEntry(?BootEntry $entry): string
	{
		if ($entry === null) {
			return "echo Invalid boot entry id\nsleep --interruptible --verbose 10\n";
		}
		return $entry->toScript($this);
	}

	public function getMenu(IPxeMenu $menu, bool $bootstrap): string
	{
		$base = $this->getUrlFull();
		return $this->getConfCode()
			. "set self=\"{$base}\"\n"
			. $this->menuToScript($menu);
	}

	public function menuToScript(IPxeMenu $menu): string
	{
		if ($menu->defaultEntryId === null) {
			$output = <<<EOF
set timeout=0

EOF;

		} else {
			$secs = (int)($menu->timeoutMs / 1000);
			$output = <<<EOF
set timeout={$secs}
set default="id-{$menu->defaultEntryId}"

EOF;
		}
		$output .= $this->getConfCode();
		foreach ($menu->items as $item) {
			$output .= $this->getMenuItemScript($item);
		}
		return $output;
	}

	private function getMenuItemScript(MenuEntry $entry): string
	{
		$str = "menuentry '" . str_replace("'", '', $entry->title) . "' --id 'id-" . $entry->menuentryid . "' {\n";
		if ($entry->gap) {
			$str .= "true\n"; // AFAICT, not possible in GRUB
		} elseif ($entry->bootEntry === null || (!empty($this->platform) && !$entry->bootEntry->supportsMode($this->platform))) {
			$str .= "echo Type mismatch\n";
		} elseif ($entry->hidden && $entry->hotkey === false) {
			$str .= "echo Hidden entries without hotkey are illegal\n"; // Hidden entries without hotkey are illegal
		} else {
			if ($entry->hotkey !== false) {
				// Not supported by grub...
			}
			if ($entry->bootEntry instanceof MenuBootEntry) {
				// Link
				$str .= "configfile \${self}entryid={$entry->menuentryid}\n";
			} else {
				// Embed directly
				// TODO: Password. Use read etc.; might need hashsum.mod, in that case, don't embed entry directly but use configfile...
				$str .= $this->getMenuEntry($entry, true);
			}
		}
		return $str . "}\n";
	}

	public function getSpecial(string $special): string
	{
		if ($special === 'localboot') {
			// Sync this with setup-scripts/grub_localboot occasionally...
			$output = <<<'EOF'
insmod chain
if [ "$grub_platform" = "pc" ] ; then
	chainloader (hd0)+1
	chainloader (hd1)+1
	chainloader (hd2)+1
fi
insmod fat
insmod part_gpt
echo "Scanning, first pass..."
for efi in (*,gpt*)/efi/grub/grubx64.efi (*,gpt*)/efi/boot/bootx64.efi (*,gpt*)/efi/*/*/bootmgfw.efi (*,gpt*)/efi/*/*.efi \
		(*,msdos*)/efi/grub/grubx64.efi (*,msdos*)/efi/boot/bootx64.efi (*,msdos*)/efi/*/*/bootmgfw.efi (*,msdos*)/efi/*/*.efi; do
	regexp --set=1:efi_device '^\((.*)\)/' "${efi}"
done

echo "Scanning, second pass..."
for efi in (*,gpt*)/efi/grub/grubx64.efi (*,gpt*)/efi/boot/bootx64.efi (*,gpt*)/efi/*/*/bootmgfw.efi (*,gpt*)/efi/*/*.efi \
		(*,msdos*)/efi/grub/grubx64.efi (*,msdos*)/efi/boot/bootx64.efi (*,msdos*)/efi/*/*/bootmgfw.efi (*,msdos*)/efi/*/*.efi; do
	if [ -e "${efi}" ]; then
		#regexp --set=1:efi_device '^\((.*)\)/' "${efi}"
		regexp --set=1:root '^(\(.*\))/' "${efi}"
		regexp --set=1:efi_path '^\(.*\)(/.*)$' "${efi}"
		echo " >> Found operating system! <<"
		echo " Path: '${efi}' on '${root}'"
		echo " Fallback '${efi_path}'"
		chainloader "${efi}"
		boot
		echo " That failed..."
	fi
done

echo "No EFI known OS found. Exiting."
exit
EOF;

		} else {
			$output = <<<EOF
echo "Unknown special command: $special"
sleep --interruptible --verbose 10
EOF;
		}
		return $output;
	}

	public function output(string $string): void
	{
		Header('Content-Type: text/plain; charset=UTF-8');
		echo $string;
	}

	public function getMenuEntry(?MenuEntry $entry, bool $honorPassword = true): string
	{
		if ($entry === null)
			return "echo Invalid menu entry id\nsleep --interruptible --verbose 10\n";
		// TODO: Check for password
		if ($honorPassword && !empty($entry->md5pass)) {
			return "echo TODO: Implement password check...\nsleep --interruptible --verbose 10\n";
		}
		$meid = $entry->menuEntryId();
		$output = $this->getConfCode() . "set menuentryid=$meid\n";
		// Output actual entry
		$output .= str_replace('%fail%', 'fail', $entry->getBootEntryScript($this));
		return $output;
	}

	public function execDataToScript(?ExecData $agnostic, ?ExecData $bios, ?ExecData $efi): string
	{
		if ($agnostic !== null)
			return $this->execDataToScriptInternal($agnostic);

		if ($efi !== null && $this->platform === BootEntry::EFI)
			return $this->execDataToScriptInternal($efi);
		// Unknown or not EFI, should be BIOS at this point
		return $this->execDataToScriptInternal($bios ?? $efi ?? new ExecData());
	}

	private function execDataToScriptInternal(ExecData $entry): string
	{
		$entry->sanitize();
		$base = $this->getGrubBase();
		$script = '';
		// Overriding dhcpOpts probably not possible/necessary
		$initrds = [];
		if (!empty($entry->initRd)) {
			foreach ($entry->initRd as $initrd) {
				if (empty($initrd))
					continue;
				$initrds[] = $this->combineUrl($base, $initrd);
			}
		}
		$file = $this->combineUrl($base, $entry->executable);
		$script .= "linux $file {$entry->commandLine} slx.ipxe.id=\${menuentryid}\n";
		if (!empty($initrds)) {
			$script .= "initrd " . implode(' ', $initrds) . "\n";
		}
		return $script;
	}

	private function combineUrl(string $base, string $path): string
	{
		$url = parse_url($path);
		if (isset($url['host'])) {
			$scheme = $url['scheme'] ?? 'http';
			$host = $url['host'];
			$base = "($scheme,$host)";
			$path = $url['path'] ?? '/';
			if (isset($url['query'])) {
				$path .= '?' . $url['query'];
			}
		} else {
			if ($path[0] !== '/') {
				$path = '/' . $path;
			}
		}
		return $base . $path;
	}

}