]> rtime.felk.cvut.cz Git - novaboot.git/blob - novaboot
Properly terminate remote command even when it ignores SIGHUP
[novaboot.git] / novaboot
1 #!/usr/bin/perl -w
2
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 2 of the License, or
6 # (at your option) any later version.
7
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12
13 # You should have received a copy of the GNU General Public License
14 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16 ## Initialization
17
18 use strict;
19 use warnings;
20 use warnings (exists $ENV{NOVABOOT_TEST} ? (FATAL => 'all') : ());
21 use Getopt::Long qw(GetOptionsFromString GetOptionsFromArray);
22 use Pod::Usage;
23 use File::Basename;
24 use File::Spec;
25 use IO::Handle;
26 use Time::HiRes("usleep");
27 use Socket;
28 use FileHandle;
29 use IPC::Open2;
30 use POSIX qw(:errno_h sysconf);
31 use Cwd qw(getcwd abs_path);
32 use Expect;
33
34 # always flush
35 $| = 1;
36
37 my $invocation_dir = $ENV{PWD} || getcwd();
38
39 ## Configuration file handling
40
41 # Default configuration
42 $CFG::hypervisor = "";
43 $CFG::hypervisor_params = "serial";
44 $CFG::genisoimage = "genisoimage";
45 $CFG::qemu = 'qemu-system-i386 -cpu coreduo -smp 2';
46 $CFG::default_target = '';
47 %CFG::targets = (
48     'qemu' => '--qemu',
49     "tud" => '--server=erwin.inf.tu-dresden.de:~sojka/boot/novaboot --rsync-flags="--chmod=Dg+s,ug+w,o-w,+rX --rsync-path=\"umask 002 && rsync\"" --grub --grub-prefix=(nd)/tftpboot/sojka/novaboot --grub-preamble="timeout 0" --concat --iprelay=141.76.48.80:2324 --scriptmod=s/\\\\bhostserial\\\\b/hostserialpci/g',
50     "novabox" => '--server=novabox@rtime.felk.cvut.cz:/srv/tftp/novaboot --rsync-flags="--chmod=Dg+s,ug+w,o-w,+rX --rsync-path=\"umask 002 && rsync\"" --pulsar --iprelay-cmd="ssh -tt novabox@rtime.felk.cvut.cz nc localhost 2324"',
51     "localhost" => '--scriptmod=s/console=tty[A-Z0-9,]+// --server=/boot/novaboot/$NAME --grub2 --grub-prefix=/boot/novaboot/$NAME --grub2-prolog="  set root=\'(hd0,msdos1)\'"',
52     "ryu" =>  '--uboot --uboot-init="mw f0000b00 \${psc_cfg}; sleep 1" --uboot-addr kernel=800000 --uboot-addr ramdisk=b00000 --uboot-addr fdt=7f0000',
53     "ryuglab" => '--target ryu --server=pc-sojkam.felk.cvut.cz:/srv/tftp --remote-cmd="ssh -tt pc-sojkam.felk.cvut.cz \"sterm -d -s 115200 /dev/ttyUSB0\""',
54     "ryulocal" => '--target ryu --dhcp-tftp --serial --reset-cmd="if which dtrrts; then dtrrts $NB_SERIAL 0 1; sleep 0.1; dtrrts $NB_SERIAL 1 1; fi"',
55     );
56
57 {
58     my %const;
59     $const{linux}->{_SC_NPROCESSORS_CONF} = 83;
60     my $nproc = sysconf($const{$^O}->{_SC_NPROCESSORS_CONF});
61
62     $CFG::scons = "scons -j$nproc";
63     $CFG::make = "make -j$nproc";
64 }
65
66 my $builddir;
67
68 sub read_config($) {
69     my ($cfg) = @_;
70     {
71         package CFG; # Put config data into a separate namespace
72
73         my $rc = do($cfg);
74
75         # Check for errors
76         if ($@) {
77             die("ERROR: Failure compiling '$cfg' - $@");
78         } elsif (! defined($rc)) {
79             die("ERROR: Failure reading '$cfg' - $!");
80         } elsif (! $rc) {
81             die("ERROR: Failure processing '$cfg'");
82         }
83     }
84     $builddir = File::Spec->rel2abs($CFG::builddir, dirname($cfg)) if defined $CFG::builddir;
85     print STDERR "novaboot: Read $cfg\n";
86 }
87
88 my @cfgs;
89 {
90     # We don't use $0 here, because it points to the novaboot itself and
91     # not to the novaboot script. The problem with this approach is that
92     # when a script is run as "novaboot <options> <script>" then $ARGV[0]
93     # contains the first option. Hence the -f check.
94     my $dir = File::Spec->rel2abs($ARGV[0] && -f $ARGV[0] ? dirname($ARGV[0]) : '', $invocation_dir);
95     while ((-d $dir || -l $dir ) && $dir ne "/") {
96         push @cfgs, "$dir/.novaboot" if -r "$dir/.novaboot";
97         my @dirs = File::Spec->splitdir($dir);
98         $dir = File::Spec->catdir(@dirs[0..$#dirs-1]);
99     }
100     @cfgs = reverse @cfgs;
101
102     my $xdg_config_home = $ENV{'XDG_CONFIG_HOME'} || $ENV{'HOME'}.'/.config';
103     unshift(@cfgs, "$xdg_config_home/novaboot") if -r "$xdg_config_home/novaboot";
104
105     $dir = $ENV{'NOVABOOT_CONFIG_DIR'} || '/etc/novaboot.d';
106     if (opendir(my $dh, $dir)) {
107         my @etccfg = map { "$dir/$_" } grep { /^[-_a-zA-Z0-9]+$/ && -f "$dir/$_" } readdir($dh);
108         closedir $dh;
109         @etccfg = sort(@etccfg);
110         @cfgs = ( @etccfg, @cfgs );
111     }
112 }
113 my $cfg = $ENV{'NOVABOOT_CONFIG'};
114 Getopt::Long::Configure(qw/no_ignore_case pass_through/);
115 GetOptions ("config|c=s" => \$cfg);
116 read_config($_) foreach $cfg or @cfgs;
117
118 ## Command line handling
119
120 my $explicit_target = $ENV{'NOVABOOT_TARGET'};
121 GetOptions ("target|t=s" => \$explicit_target);
122
123 # Variables for command line options
124 my ($amt, @append, $bender, @chainloaders, $concat, $config_name_opt, $dhcp_tftp, $dump_opt, $dump_config, @exiton, $exiton_timeout, @expect_raw, $final_eol, $gen_only, $grub_config, $grub_prefix, $grub_preamble, $grub2_prolog, $grub2_config, $help, $ider, $interaction, $iprelay, $iprelay_cmd, $iso_image, $interactive, $kernel_opt, $make, $man, $netif, $no_file_gen, $off_opt, $on_opt, $pulsar, $pulsar_root, $qemu, $qemu_append, $qemu_flags_cmd, @remote_cmd, $remote_expect, $remote_expect_silent, $remote_expect_timeout, $reset, @reset_cmd, $reset_send, $rom_prefix, $rsync_flags, @scriptmod, $scons, $serial, $server, $stty, $tftp, $tftp_port, $uboot, %uboot_addr, $uboot_cmd, @uboot_init);
125
126 my ($target_reset, $target_power_on, $target_power_off);
127
128 # Default values of certain command line options
129 %uboot_addr = (
130     'kernel'  => '${kernel_addr_r}',
131     'ramdisk' => '${ramdisk_addr_r}',
132     'fdt'     => '${fdt_addr_r}',
133     );
134 $rsync_flags = '';
135 $rom_prefix = 'rom://';
136 $stty = 'raw -crtscts -onlcr 115200';
137 $reset = 1;                     # Reset target by default
138 $interaction = 1;               # Perform target interaction by default
139 $final_eol = 1;
140 $netif = 'eth0';
141 $remote_expect_timeout = 180;
142
143 my @expect_seen = ();
144 sub handle_expect
145 {
146     my ($n, $v) = @_;
147     push(@expect_seen, '-re') if $n eq "expect-re";
148     push(@expect_seen, $v);
149 }
150
151 sub handle_send
152 {
153     my ($n, $v) = @_;
154     unless (@expect_seen) { die("No --expect before --send"); }
155     my $ret = ($n eq "sendcont") ? exp_continue : 0;
156     unshift(@expect_raw, sub { shift->send(eval("\"$v\"")); $ret; });
157     unshift(@expect_raw, @expect_seen);
158     @expect_seen = ();
159 }
160
161 # Options which can be safely specified on the server (via --ssh),
162 # i.e. which cannot cause unwanted local code execution etc.
163 my %opt_spec_safe = (
164     "grub|g:s"       => \$grub_config,
165     "grub-preamble=s"=> \$grub_preamble,
166     "grub2-prolog=s" => \$grub2_prolog,
167     "grub2:s"        => \$grub2_config,
168     "prefix|grub-prefix=s" => \$grub_prefix,
169     "pulsar-root=s"  => \$pulsar_root,
170     "pulsar|p:s"     => \$pulsar,
171     "uboot-addr=s"   => \%uboot_addr,
172     "uboot-cmd=s"    => \$uboot_cmd,
173     "uboot-init=s"   => sub { push @uboot_init, { command => $_[1] }; },
174     "uboot:s"        => \$uboot,
175     );
176
177 my %opt_spec = (
178     %opt_spec_safe,
179     "amt=s"          => \$amt,
180     "append|a=s"     => \@append,
181     "bender|b"       => \$bender,
182     "build-dir=s"    => sub { my ($n, $v) = @_; $builddir = File::Spec->rel2abs($v); },
183     "concat"         => \$concat,
184     "chainloader=s"  => \@chainloaders,
185     "dhcp-tftp|d"    => \$dhcp_tftp,
186     "dump"           => \$dump_opt,
187     "dump-config"    => \$dump_config,
188     "exiton=s"       => \@exiton,
189     "exiton-timeout=i"=> \$exiton_timeout,
190     "exiton-re=s"    => sub { my ($n, $v) = @_; push(@exiton, '-re', $v); },
191     "expect=s"       => \&handle_expect,
192     "expect-re=s"    => \&handle_expect,
193     "expect-raw=s"   => sub { my ($n, $v) = @_; unshift(@expect_raw, eval($v)); },
194     "final-eol!"     => \$final_eol,
195     "gen-only"       => \$gen_only,
196     "ider"           => \$ider,
197     "interaction!"   => \$interaction,
198     "iprelay=s"      => \$iprelay,
199     "iprelay-cmd=s"  => \$iprelay_cmd,
200     "iso:s"          => \$iso_image,
201     "kernel|k=s"     => \$kernel_opt,
202     "interactive|i"  => \$interactive,
203     "name=s"         => \$config_name_opt,
204     "make|m:s"       => \$make,
205     "netif=s"        => \$netif,
206     "no-file-gen"    => \$no_file_gen,
207     "off"            => \$off_opt,
208     "on"             => \$on_opt,
209     "qemu|Q:s"       => \$qemu,
210     "qemu-append=s"  => \$qemu_append,
211     "qemu-flags|q=s" => \$qemu_flags_cmd,
212     "remote-cmd=s"   => sub { @remote_cmd = ($_[1]); },
213     "remote-expect=s"=> \$remote_expect,
214     "remote-expect-silent=s"=> sub { $remote_expect=$_[1]; $remote_expect_silent=1; },
215     "remote-expect-timeout=i"=> \$remote_expect_timeout,
216     "reset!"         => \$reset,
217     "reset-cmd=s"    => sub { @reset_cmd = ($_[1]); },
218     "reset-send=s"   => \$reset_send,
219     "rsync-flags=s"  => \$rsync_flags,
220     "scons:s"        => \$scons,
221     "scriptmod=s"    => \@scriptmod,
222     "send=s"         => \&handle_send,
223     "sendcont=s"     => \&handle_send,
224     "serial|s:s"     => \$serial,
225     "server:s"       => \$server,
226     "ssh:s"          => \&handle_novaboot_server,
227     "strip-rom"      => sub { $rom_prefix = ''; },
228     "stty=s"         => \$stty,
229     "tftp"           => \$tftp,
230     "tftp-port=i"    => \$tftp_port,
231     "no-uboot"       => sub { undef $uboot; },
232     "h"              => \$help,
233     "help"           => \$man,
234     );
235
236 sub handle_novaboot_server
237 {
238     my ($n, $val) = @_;
239     my $xdg_runtime_dir = $ENV{XDG_RUNTIME_DIR} || '/var/run';
240     my $ssh_ctl_path = "${xdg_runtime_dir}/novaboot$$";
241
242     @remote_cmd = ('ssh', '-tt', '-M', '-S', $ssh_ctl_path, $val, 'console');
243     $remote_expect = "novaboot-shell: Connected";
244     $server = "$val:";
245     $rsync_flags = "--rsh='ssh -S \'${ssh_ctl_path}\''";
246     ($grub_prefix = $val) =~ s|(.*)@.*|\/$1\/| if index($val, '@') != -1;
247     @reset_cmd = ('ssh', '-tt', '-S', $ssh_ctl_path, $val, 'reset');
248
249     $target_power_off = sub { system_verbose('ssh', '-tt', '-S', $ssh_ctl_path, $val, 'off'); };
250     $target_power_on  = sub { system_verbose('ssh', '-tt', '-S', $ssh_ctl_path, $val, 'on'); };
251
252     my $cmd = "ssh '${val}' get-config";
253     print STDERR "novaboot: Running: $cmd\n";
254     my @target_config = qx($cmd  < /dev/null);
255     if ($?) { die("Cannot get target configuration from the server"); }
256     printf "novaboot: Received configuration from the server:%s\n", (!@target_config) ? " empty" : "";
257     foreach (@target_config) { chomp; print "  $_\n"; }
258
259     my $p = Getopt::Long::Parser->new;
260     $p->configure(qw/no_ignore_case no_pass_through/);
261     $p->getoptionsfromarray(\@target_config, %opt_spec_safe) or die("Error processing configuration from the server");
262
263     if (scalar @target_config) { die "Unsuported configuration received from the server: ".join(", ", @target_config); }
264 }
265
266 # First process target options
267 {
268     my $t = defined($explicit_target) ? $explicit_target : $CFG::default_target;
269     my @target_expanded;
270     Getopt::Long::Configure(qw/no_ignore_case pass_through/);
271     while ($t) {
272         exists $CFG::targets{$t} or die("Unknown target '$t' (valid targets are: ".join(", ", sort keys(%CFG::targets)).")");
273
274         undef $explicit_target;
275         my ($ret, $remaining_args) = GetOptionsFromString ($CFG::targets{$t}, ("target|t=s" => \$explicit_target));
276         if (!$ret) { die "Error parsing target $t option"; }
277         push(@target_expanded, @$remaining_args);
278         $t = $explicit_target;
279     }
280
281     my @args = (@target_expanded, @ARGV);
282     print STDERR "novaboot: Effective options: @args\n";
283
284     Getopt::Long::Configure(qw/no_ignore_case no_pass_through/);
285     GetOptionsFromArray(\@target_expanded, %opt_spec) or die ("Error in target definition");
286 }
287
288 # Then process other command line options - some of them may override
289 # what was specified by the target
290 GetOptions %opt_spec or die("Error in command line arguments");
291 pod2usage(1) if $help;
292 pod2usage(-exitstatus => 0, -verbose => 2) if $man;
293
294 ### Dump sanitized configuration (if requested)
295
296 if ($dump_config) {
297     use Data::Dumper;
298     $Data::Dumper::Indent=1;
299     print "# This file is in perl syntax.\n";
300     foreach my $key(sort(keys(%CFG::))) { # See "Symbol Tables" in perlmod(1)
301         if (defined ${$CFG::{$key}}) { print Data::Dumper->Dump([${$CFG::{$key}}], ["*$key"]); }
302         if (        @{$CFG::{$key}}) { print Data::Dumper->Dump([\@{$CFG::{$key}}], ["*$key"]); }
303         if (        %{$CFG::{$key}}) { print Data::Dumper->Dump([\%{$CFG::{$key}}], ["*$key"]); }
304     }
305     print "1;\n";
306     exit;
307 }
308
309 ### Sanitize configuration
310
311 if ($interactive && !-t STDIN) {
312     die("novaboot: Interactive mode not supported when not on terminal");
313 }
314
315 if (defined $config_name_opt && scalar(@ARGV) > 1) { die "You cannot use --name with multiple scripts"; }
316
317 if ($ider) {
318     $iso_image //= ''; # IDE-R needs an ISO image
319     if (!defined $amt) { die "Error: --ider requires --amt"; }
320 }
321
322 {
323     my %input_opts = ('--iprelay'    => \$iprelay,
324                       '--iprelay-cmd'=> \$iprelay_cmd,
325                       '--serial'     => \$serial,
326                       '--remote-cmd' => (@remote_cmd ? \$remote_cmd[0] : undef),
327                       '--amt'        => \$amt);
328     my @opts = grep(defined(${$input_opts{$_}}) , keys %input_opts);
329
330     die("novaboot: More than one target connection option: ".join(', ', @opts)) if scalar @opts > 1;
331 }
332
333 # Default options
334 if (defined $serial) {
335     $serial ||= "/dev/ttyUSB0";
336     $ENV{NB_SERIAL} = $serial;
337 }
338 if (defined $grub_config) { $grub_config ||= "menu.lst"; }
339 if (defined $grub2_config) { $grub2_config ||= "grub.cfg"; }
340
341 ## Parse the novaboot script(s)
342 my @scripts;
343 my $file;
344 my $EOF;
345 my $last_fn = '';
346 my ($modules, $variables, $generated, $copy, $chainload, $continuation) = ([], {}, [], []);
347 my $skip_reading = defined($on_opt) || defined($off_opt);
348 while (!$skip_reading && ($_ = <>)) {
349     if ($ARGV ne $last_fn) { # New script
350         die "Missing EOF in $last_fn" if $file;
351         die "Unfinished line in $last_fn" if $continuation;
352         $last_fn = $ARGV;
353         push @scripts, { 'filename' => $ARGV,
354                          'modules' => $modules = [],
355                          'variables' => $variables = {},
356                          'generated' => $generated = [],
357                          'copy' => $copy = [],
358                          'chainload' => $chainload = [],
359         };
360
361     }
362     chomp();
363     next if /^#/ || /^\s*$/;    # Skip comments and empty lines
364
365     $_ =~ s/^[[:space:]]*// if ($continuation);
366
367     if (/\\$/) {                # Line continuation
368         $continuation .= substr($_, 0, length($_)-1);
369         next;
370     }
371
372     if ($continuation) {        # Last continuation line
373         $_ = $continuation . $_;
374         $continuation = '';
375     }
376
377     foreach my $mod(@scriptmod) { eval $mod; }
378
379     if ($file && $_ eq $EOF) {  # Heredoc end
380         undef $file;
381         next;
382     }
383     if ($file) {                # Heredoc content
384         push @{$file}, "$_\n";
385         next;
386     }
387     if (/^([A-Z_]+)=(.*)$/) {   # Internal variable
388         $$variables{$1} = $2;
389         push(@exiton, $2) if ($1 eq "EXITON");
390         next;
391     }
392     sub process_load_copy($) {
393         die("novaboot: '$last_fn' line $.: Missing file name\n") unless /^[^ <]+/;
394         if (/^([^ ]*)(.*?)[[:space:]]*<<([^ ]*)$/) { # Heredoc start
395             $file = [];
396             push @$generated, {filename => $1, content => $file};
397             $EOF = $3;
398             return "$1$2";
399         }
400         if (/^([^ ]*)(.*?)[[:space:]]*< ?(.*)$/) { # Command substitution
401             push @$generated, {filename => $1, command => $3};
402             return "$1$2";
403         }
404         return $_;
405     }
406     if (s/^load *//) {          # Load line
407         push @$modules, process_load_copy($_);
408         next;
409     }
410     if (s/^copy *//) {          # Copy line
411         push @$copy, process_load_copy($_);
412         next;
413     }
414     if (s/^chld *//) {          # Chainload line
415         push @$chainload, process_load_copy($_);
416         next;
417     }
418     if (/^run (.*)/) {          # run line
419         push @$generated, {command => $1};
420         next;
421     }
422     if (/^uboot(?::([0-9]+)s)? +(< *)?(.*)/) {  # uboot line
423         # TODO: If U-Boot supports some interactive menu, it might
424         # make sense to store uboot lines per novaboot script.
425         my ($timeout, $redir, $string, $dest) = ($1, $2, $3);
426         if ($string =~ /(.*) *> *(.*)/) {
427             $string = $1;
428             $dest = $2;
429         }
430         push @uboot_init, { command => $redir ? "" : $string,
431                             system =>  $redir ? $string : "",
432                             timeout => $timeout,
433                             dest => $dest,
434         };
435         next;
436     }
437
438     die("novaboot: Cannot parse script '$last_fn' line $.. Didn't you forget 'load' keyword?\n");
439 }
440 # use Data::Dumper;
441 # print Dumper(\@scripts);
442
443 foreach my $script (@scripts) {
444     $modules = $$script{modules};
445     @$modules[0] =~ s/^[^ ]*/$kernel_opt/ if $kernel_opt;
446     @$modules[0] .= ' ' . join(' ', @append) if @append;
447
448     my $kernel;
449     if (exists $variables->{KERNEL}) {
450         $kernel = $variables->{KERNEL};
451     } else {
452         if ($CFG::hypervisor) {
453             $kernel = $CFG::hypervisor . " ";
454             if (exists $variables->{HYPERVISOR_PARAMS}) {
455                 $kernel .= $variables->{HYPERVISOR_PARAMS};
456             } else {
457                 $kernel .= $CFG::hypervisor_params;
458             }
459         }
460     }
461     @$modules = ($kernel, @$modules) if $kernel;
462     @$modules = (@chainloaders, @$modules);
463     @$modules = ("bin/boot/bender", @$modules) if ($bender || defined $ENV{'NOVABOOT_BENDER'});
464 }
465
466 if ($dump_opt) {
467     foreach my $script (@scripts) {
468         print join("\n", @{$$script{modules}})."\n";
469     }
470     exit(0);
471 }
472
473 ## Helper functions
474
475 sub generate_configs($$$) {
476     my ($base, $generated, $filename) = @_;
477     if ($base) { $base = "$base/"; };
478     foreach my $g(@$generated) {
479       if (exists $$g{content}) {
480         my $config = $$g{content};
481         my $fn = $$g{filename};
482         open(my $f, '>', $fn) || die("$fn: $!");
483         map { s|\brom://([^ ]*)|$rom_prefix$base$1|g; print $f "$_"; } @{$config};
484         close($f);
485         print STDERR "novaboot: Created $fn\n";
486       } elsif (exists $$g{command} && ! $no_file_gen) {
487         $ENV{SRCDIR} = dirname(File::Spec->rel2abs( $filename, $invocation_dir ));
488         if (exists $$g{filename}) {
489             system_verbose("( $$g{command} ) > $$g{filename}");
490         } else {
491             system_verbose($$g{command});
492         }
493       }
494     }
495 }
496
497 sub generate_grub_config($$$$;$)
498 {
499     my ($filename, $title, $base, $modules_ref, $preamble) = @_;
500     if ($base) { $base = "$base/"; };
501     open(my $fg, '>', $filename) or die "$filename: $!";
502     print $fg "$preamble\n" if $preamble;
503     print $fg "title $title\n" if $title;
504     #print $fg "root $base\n"; # root doesn't really work for (nd)
505     my $first = 1;
506     foreach (@$modules_ref) {
507         if ($first) {
508             $first = 0;
509             my ($kbin, $kcmd) = split(' ', $_, 2);
510             $kcmd = '' if !defined $kcmd;
511             print $fg "kernel ${base}$kbin $kcmd\n";
512         } else {
513             s|\brom://([^ ]*)|$rom_prefix$base$1|g; # Translate rom:// files - needed for vdisk parameter of sigma0
514             print $fg "module $base$_\n";
515         }
516     }
517     close($fg);
518     print("novaboot: Created $builddir/$filename\n");
519     return $filename;
520 }
521
522 sub generate_syslinux_config($$$$)
523 {
524     my ($filename, $title, $base, $modules_ref) = @_;
525     if ($base && $base !~ /\/$/) { $base = "$base/"; };
526     open(my $fg, '>', $filename) or die "$filename: $!";
527     print $fg "LABEL $title\n";
528     #TODO print $fg "MENU LABEL $human_readable_title\n";
529
530     my ($kbin, $kcmd) = split(' ', @$modules_ref[0], 2);
531
532     if (system("file $kbin|grep 'Linux kernel'") == 0) {
533         my $initrd = @$modules_ref[1];
534         die('To many "load" lines for Linux kernel') if (scalar @$modules_ref > 2);
535         print $fg "LINUX $base$kbin\n";
536         print $fg "APPEND $kcmd\n";
537         print $fg "INITRD $base$initrd\n";
538     } else {
539         print $fg "KERNEL mboot.c32\n";
540         my @append;
541         foreach (@$modules_ref) {
542             s|\brom://([^ ]*)|$rom_prefix$base$1|g; # Translate rom:// files - needed for vdisk parameter of sigma0
543             push @append, "$base$_";
544             print $fg "APPEND ".join(' --- ', @append)."\n";
545         }
546     }
547     #TODO print $fg "TEXT HELP\n";
548     #TODO print $fg "some help here\n";
549     #TODO print $fg "ENDTEXT\n";
550     close($fg);
551     print("novaboot: Created $builddir/$filename\n");
552     return $filename;
553 }
554
555 sub generate_grub2_config($$$$;$$)
556 {
557     my ($filename, $title, $base, $modules_ref, $preamble, $prolog) = @_;
558     if ($base && substr($base,-1,1) ne '/') { $base = "$base/"; };
559     open(my $fg, '>', $filename) or die "$filename: $!";
560     print $fg "$preamble\n" if $preamble;
561     $title ||= 'novaboot';
562     print $fg "menuentry $title {\n";
563     print $fg "$prolog\n" if $prolog;
564     my $first = 1;
565     foreach (@$modules_ref) {
566         if ($first) {
567             $first = 0;
568             my ($kbin, $kcmd) = split(' ', $_, 2);
569             $kcmd = '' if !defined $kcmd;
570             print $fg "  multiboot ${base}$kbin $kcmd\n";
571         } else {
572             my @args = split;
573             # GRUB2 doesn't pass filename in multiboot info so we have to duplicate it here
574             $_ = join(' ', ($args[0], @args));
575             s|\brom://|$rom_prefix|g; # We do not need to translate path for GRUB2
576             print $fg "  module $base$_\n";
577         }
578     }
579     print $fg "}\n";
580     close($fg);
581     print("novaboot: Created $builddir/$filename\n");
582     return $filename;
583 }
584
585 sub generate_pulsar_config($$$)
586 {
587     my ($filename, $modules_ref, $chainload_ref) = @_;
588     open(my $fg, '>', $filename) or die "$filename: $!";
589     print $fg "root $pulsar_root\n" if defined $pulsar_root;
590     if (scalar(@$chainload_ref) > 0) {
591         print $fg "chld $$chainload_ref[0]\n";
592     } else {
593         my $first = 1;
594         my ($kbin, $kcmd);
595         foreach (@$modules_ref) {
596             if ($first) {
597                 $first = 0;
598                 ($kbin, $kcmd) = split(' ', $_, 2);
599                 $kcmd = '' if !defined $kcmd;
600             } else {
601                 my @args = split;
602                 s|\brom://|$rom_prefix|g;
603                 print $fg "load $_\n";
604             }
605         }
606         # Put kernel as last - this is needed for booting Linux and has no influence on non-Linux OSes
607         print $fg "exec $kbin $kcmd\n";
608     }
609     close($fg);
610     print("novaboot: Created $builddir/$filename\n");
611     return $filename;
612 }
613
614 sub shell_cmd_string(@)
615 {
616     if (scalar(@_) == 1) {
617         return $_[0];
618     } else {
619         return join(' ', map((/^[-_=a-zA-Z0-9\/\.\+]+$/ ? "$_" : "'$_'"), @_));
620     }
621 }
622
623 sub exec_verbose(@)
624 {
625     print STDERR "novaboot: Running: ".shell_cmd_string(@_)."\n";
626     exec(@_);
627     exit(1); # should not be reached
628 }
629
630 sub system_verbose
631 {
632     print STDERR "novaboot: Running: ".shell_cmd_string(@_)."\n";
633     my $ret = system(@_);
634     if ($ret & 0x007f) { die("Command terminated by a signal"); }
635     if ($ret & 0xff00) {die("Command exit with non-zero exit code"); }
636     if ($ret) { die("Command failure $ret"); }
637 }
638
639 sub trim($) {
640     my ($str) = @_;
641     $str =~ s/^\s+|\s+$//g;
642     return $str
643 }
644
645 ## WvTest headline
646
647 if (exists $variables->{WVDESC}) {
648     print STDERR "Testing \"$variables->{WVDESC}\" in $last_fn:\n";
649 } elsif ($last_fn =~ /\.wv$/) {
650     print STDERR "Testing \"all\" in $last_fn:\n";
651 }
652
653 ## Connect to the target and check whether it is not occupied
654
655 # We have to do this before file generation phase, because file
656 # generation is intermixed with file deployment phase and we want to
657 # check whether the target is not used by somebody else before
658 # deploying files. Otherwise, we may rewrite other user's files on a
659 # boot server.
660
661 my $exp; # Expect object to communicate with the target over serial line
662
663 sub kill_exp_on_signal() {
664     # Sometimes, under unclear circumstances (e.g. when running under
665     # both Jenkins and Robotframework), novaboot does not terminate
666     # console command when killed. The console is then blocked by the
667     # stale process forever. Theoretically, this should not happen,
668     # because when novaboot is killed, console command's controlling
669     # terminal sends SIGHUP to the console command and the command
670     # should terminate. It seems that at least SSH sometimes ignores
671     # HUP and does not terminate. The code below seems to work around
672     # that problem by killing the process immediately with SIGTERM,
673     # which is not ignored.
674
675     sub kill_console { kill TERM => $exp->pid if $exp->pid; die "Terminated by SIG$_[0]"; };
676
677     # For our Jenkins/Robotframework use case, it was sufficient to
678     # handle the TERM signal, but to be on the safe side, we also
679     # catch other signals.
680     $SIG{TERM} = \&kill_console;
681     $SIG{HUP} = \&kill_console;
682     $SIG{INT} = \&kill_console;
683     $SIG{QUIT} = \&kill_console;
684 }
685
686
687 my ($amt_user, $amt_password, $amt_host, $amt_port);
688
689 if (defined $iprelay || defined $iprelay_cmd) {
690     if (defined $iprelay) {
691         my $IPRELAY;
692         $iprelay =~ /([.0-9]+)(:([0-9]+))?/;
693         my $addr = $1;
694         my $port = $3 || 23;
695         my $paddr   = sockaddr_in($port, inet_aton($addr));
696         my $proto   = getprotobyname('tcp');
697         socket($IPRELAY, PF_INET, SOCK_STREAM, $proto)  || die "socket: $!";
698         print STDERR "novaboot: Connecting to IP relay... ";
699         connect($IPRELAY, $paddr)    || die "connect: $!";
700         print STDERR "done\n";
701         $exp = Expect->init(\*$IPRELAY);
702         $exp->log_stdout(1);
703     }
704     if (defined $iprelay_cmd) {
705         print STDERR "novaboot: Running: $iprelay_cmd\n";
706         $exp = new Expect;
707         $exp->raw_pty(1);
708         $exp->spawn($iprelay_cmd);
709         kill_exp_on_signal();
710     }
711
712     while (1) {
713         print $exp "\xFF\xF6";  # AYT
714         my $connected = $exp->expect(20, # Timeout in seconds
715                                      '<iprelayd: connected>',
716                                      '-re', '<WEB51 HW[^>]*>')
717             || die "iprelay connection: " . ($! || "timeout");
718         last if $connected;
719     }
720
721     sub relaycmd($$) {
722         my ($relay, $onoff) = @_;
723         die unless ($relay == 1 || $relay == 2);
724
725         my $cmd = ($relay == 1 ? 0x5 : 0x6) | ($onoff ? 0x20 : 0x10);
726         return "\xFF\xFA\x2C\x32".chr($cmd)."\xFF\xF0";
727     }
728
729     sub relayconf($$) {
730         my ($relay, $onoff) = @_;
731         die unless ($relay == 1 || $relay == 2);
732         my $cmd = ($relay == 1 ? 0xdf : 0xbf) | ($onoff ? 0x00 : 0xff);
733         return "\xFF\xFA\x2C\x97".chr($cmd)."\xFF\xF0";
734     }
735
736     sub relay($$;$) {
737         my ($relay, $onoff, $can_giveup) = @_;
738         my $confirmation = '';
739         $exp->log_stdout(0);
740         print $exp relaycmd($relay, $onoff);
741         my $confirmed = $exp->expect(20, # Timeout in seconds
742                                      relayconf($relay, $onoff))
743             || die "iprelay command: " . ($! || "timeout");
744         if (!$confirmed) {
745             if ($can_giveup) {
746                 print("Relay confirmation timeout - ignoring\n");
747             } else {
748                 die "Relay confirmation timeout";
749             }
750         }
751         $exp->log_stdout(1);
752     }
753
754     $target_reset = sub {
755         relay(2, 1, 1); # Reset the machine
756         usleep(100000);
757         relay(2, 0);
758     };
759
760     $target_power_off = sub {
761         relay(1, 1);            # Press power button
762         usleep(6000000);        # Long press to switch off
763         relay(1, 0);
764     };
765
766     $target_power_on = sub {
767         relay(1, 1);            # Press power button
768         usleep(100000);         # Short press
769         relay(1, 0);
770     };
771 }
772 elsif ($serial) {
773     my $CONN;
774     system_verbose("stty -F $serial $stty");
775     open($CONN, "+<", $serial) || die "open $serial: $!";
776     $exp = Expect->init(\*$CONN);
777 }
778 elsif (@remote_cmd) {
779     print STDERR "novaboot: Running: ".shell_cmd_string(@remote_cmd)."\n";
780     $exp = Expect->spawn(@remote_cmd);
781     kill_exp_on_signal();
782 }
783 elsif (defined $amt) {
784     require LWP::UserAgent;
785     require LWP::Authen::Digest;
786
787     sub genXML {
788         my ($host, $username, $password, $schema, $className, $pstate) = @_;
789         #AMT numbers for PowerStateChange (MNI => bluescreen on windows;-)
790         my %pstates = ("on"        => 2,
791                        "standby"   => 4,
792                        "hibernate" => 7,
793                        "off"       => 8,
794                        "reset"     => 10,
795                        "MNI"       => 11);
796         return <<END;
797                 <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">
798                 <s:Header><a:To>http://$host:16992/wsman</a:To>
799                 <w:ResourceURI s:mustUnderstand="true">$schema</w:ResourceURI>
800                 <a:ReplyTo><a:Address s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo>
801                 <a:Action s:mustUnderstand="true">$schema$className</a:Action>
802                 <w:MaxEnvelopeSize s:mustUnderstand="true">153600</w:MaxEnvelopeSize>
803                 <a:MessageID>uuid:709072C9-609C-4B43-B301-075004043C7C</a:MessageID>
804                 <w:Locale xml:lang="en-US" s:mustUnderstand="false" />
805                 <w:OperationTimeout>PT60.000S</w:OperationTimeout>
806                 <w:SelectorSet><w:Selector Name="Name">Intel(r) AMT Power Management Service</w:Selector></w:SelectorSet>
807                 </s:Header><s:Body>
808                 <p:RequestPowerStateChange_INPUT xmlns:p="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_PowerManagementService">
809                 <p:PowerState>$pstates{$pstate}</p:PowerState>
810                 <p:ManagedElement><a:Address>http://$host:16992/wsman</a:Address>
811                 <a:ReferenceParameters><w:ResourceURI>http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ComputerSystem</w:ResourceURI>
812                 <w:SelectorSet><w:Selector Name="Name">ManagedSystem</w:Selector></w:SelectorSet>
813                 </a:ReferenceParameters></p:ManagedElement>
814                 </p:RequestPowerStateChange_INPUT>
815                 </s:Body></s:Envelope>
816 END
817     }
818
819     sub sendPOST {
820         my ($host, $username, $password, $content) = @_;
821
822         my $ua = LWP::UserAgent->new();
823         $ua->agent("novaboot");
824
825         my $req = HTTP::Request->new(POST => "http://$host:16992/wsman");
826         my $res = $ua->request($req);
827         die ("Unexpected AMT response: " . $res->status_line) unless $res->code == 401;
828
829         my ($realm) = $res->header("WWW-Authenticate") =~ /Digest realm="(.*?)"/;
830         $ua->credentials("$host:16992", $realm, $username => $password);
831
832         # Create a request
833         $req = HTTP::Request->new(POST => "http://$host:16992/wsman");
834         $req->content_type('application/x-www-form-urlencoded');
835         $req->content($content);
836         $res = $ua->request($req);
837         die ("AMT power change request failed: " . $res->status_line) unless $res->is_success;
838         $res->content() =~ /<g:ReturnValue>(\d+)<\/g:ReturnValue>/;
839         return $1;
840     }
841
842     sub powerChange  {
843         my ($host, $username, $password, $pstate)=@_;
844         my $schema="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_PowerManagementService";
845         my $className="/RequestPowerStateChange";
846         my $content = genXML($host, $username, $password ,$schema, $className, $pstate);
847         return sendPOST($host, $username, $password, $content);
848     }
849
850     ($amt_user,$amt_password,$amt_host,$amt_port) = ($amt =~ /(?:(.*?)(?::(.*))?@)?([^:]*)(?::([0-9]*))?/);;
851     $amt_user ||= "admin";
852     $amt_password ||= $ENV{'AMT_PASSWORD'} || die "AMT password not specified";
853     $amt_host || die "AMT host not specified";
854     $amt_port ||= 16994;
855
856
857     $target_power_off = sub {
858         $exp->close();
859         my $result = powerChange($amt_host,$amt_user,$amt_password, "off");
860         die "AMT power off failed (ReturnValue $result)" if $result != 0;
861     };
862
863     $target_power_on = sub {
864         my $result = powerChange($amt_host,$amt_user,$amt_password, "on");
865         die "AMT power on failed (ReturnValue $result)" if $result != 0;
866     };
867
868     $target_reset = sub {
869         my $result = powerChange($amt_host,$amt_user,$amt_password, "reset");
870         if ($result != 0) {
871             print STDERR "Warning: Cannot reset $amt_host, trying power on. ";
872             $result = powerChange($amt_host,$amt_user,$amt_password, "on");
873         }
874         die "AMT reset failed (ReturnValue $result)" if $result != 0;
875     };
876
877     my $cmd = "amtterm -u $amt_user -p $amt_password $amt_host $amt_port";
878     print STDERR "novaboot: Running: $cmd\n" =~ s/\Q$amt_password\E/???/r;
879     $exp = Expect->spawn($cmd);
880     $exp->expect(10, "RUN_SOL") || die "Expect for 'RUN_SOL': " . ($! || "timeout");
881 }
882
883
884 if ($remote_expect) {
885     $exp || die("No serial line connection");
886     my $log = $exp->log_stdout;
887     if (defined $remote_expect_silent) {
888         $exp->log_stdout(0);
889     }
890     $exp->expect($remote_expect_timeout >= 0 ? $remote_expect_timeout : undef,
891                  $remote_expect) || die "Expect for '$remote_expect':" . ($! || "timeout");;
892     if (defined $remote_expect_silent) {
893         $exp->log_stdout($log);
894         print $exp->after() if $log;
895     }
896 }
897
898 if (@reset_cmd) {
899     $target_reset = sub {
900         system_verbose(@reset_cmd);
901     };
902 }
903
904 if (defined $reset_send) {
905     $target_reset = sub {
906         $reset_send =~ s/\\n/\n/g;
907         $exp->send($reset_send);
908     };
909 }
910
911 if (defined $on_opt && defined $target_power_on) {
912     &$target_power_on();
913     exit;
914 }
915 if (defined $off_opt && defined $target_power_off) {
916     print STDERR "novaboot: Switching the target off...\n";
917     &$target_power_off();
918     exit;
919 }
920
921 $builddir ||= dirname(File::Spec->rel2abs( ${$scripts[0]}{filename})) if scalar @scripts;
922 if (defined $builddir) {
923     chdir($builddir) or die "Can't change directory to $builddir: $!";
924     print STDERR "novaboot: Entering directory `$builddir'\n";
925 } else {
926     $builddir = $invocation_dir;
927 }
928
929 ## File generation phase
930 my (%files_iso, $menu_iso, $filename);
931 my $config_name = '';
932 my $prefix = '';
933
934 foreach my $script (@scripts) {
935     $filename = $$script{filename};
936     $modules = $$script{modules};
937     $generated = $$script{generated};
938     $variables = $$script{variables};
939
940     ($config_name = $filename) =~ s#.*/##;
941     $config_name = $config_name_opt if (defined $config_name_opt);
942
943     if (exists $variables->{BUILDDIR}) {
944         $builddir = File::Spec->rel2abs($variables->{BUILDDIR});
945         chdir($builddir) or die "Can't change directory to $builddir: $!";
946         print STDERR "novaboot: Entering directory `$builddir'\n";
947     }
948
949     if ($grub_prefix) {
950         $prefix = $grub_prefix;
951         $prefix =~ s/\$NAME/$config_name/;
952         $prefix =~ s/\$BUILDDIR/$builddir/;
953     }
954     # TODO: use $grub_prefix as first parameter if some switch is given
955     generate_configs('', $generated, $filename);
956
957 ### Generate bootloader configuration files
958     my @bootloader_configs;
959     push @bootloader_configs, generate_grub_config($grub_config, $config_name, $prefix, $modules, $grub_preamble) if (defined $grub_config);
960     push @bootloader_configs, generate_grub2_config($grub2_config, $config_name, $prefix, $modules, $grub_preamble, $grub2_prolog) if (defined $grub2_config);
961     push @bootloader_configs, generate_pulsar_config('config-'.($pulsar||'novaboot'), $modules, $chainload) if (defined $pulsar);
962
963 ### Run scons or make
964     {
965         my @all;
966         push @all, @$modules;
967         push @all, @$copy;
968         push @all, @$chainload;
969         my @files = map({ ($file) = m/([^ ]*)/; $file; } @all);
970
971         # Filter-out generated files
972         my @to_build = grep({ my $file = $_; !scalar(grep($file eq ($$_{filename} || ''), @$generated)) } @files);
973
974         system_verbose($scons || $CFG::scons." ".join(" ", @to_build)) if (defined $scons);
975         system_verbose($make  || $CFG::make ." ".join(" ", @to_build)) if (defined $make);
976     }
977
978 ### Copy files (using rsync)
979     if (defined $server && !defined($gen_only)) {
980         (my $real_server = $server) =~ s/\$NAME/$config_name/;
981
982         my ($hostname, $path) = split(":", $real_server, 2);
983         if (! defined $path) {
984             $path = $hostname;
985             $hostname = "";
986         }
987         my $files = join(" ", map({ ($file) = m/([^ ]*)/; $file; } ( @$modules, @bootloader_configs, @$copy)));
988         map({ my $file = (split)[0]; die "$file: $!" if ! -f $file; } @$modules);
989         my $istty = -t STDOUT && ($ENV{'TERM'} || 'dumb') ne 'dumb';
990         my $progress = $istty ? "--progress" : "";
991         if ($files) {
992             system_verbose("rsync $progress -RLp $rsync_flags $files $real_server");
993             if ($server =~ m|/\$NAME$| && $concat) {
994                 my $cmd = join("; ", map { "( cd $path/.. && cat */$_ > $_ )" } @bootloader_configs);
995                 system_verbose($hostname ? "ssh $hostname '$cmd'" : $cmd);
996             }
997         }
998     }
999
1000 ### Prepare ISO image generation
1001     if (defined $iso_image) {
1002         generate_configs("(cd)", $generated, $filename);
1003         my $menu;
1004         generate_syslinux_config(\$menu, $config_name, "/", $modules);
1005         $menu_iso .= "$menu\n";
1006         map { ($file,undef) = split; $files_iso{$file} = 1; } @$modules;
1007     }
1008 }
1009
1010 ## Generate ISO image
1011 if (defined $iso_image) {
1012     system_verbose("mkdir -p isolinux");
1013
1014     my @files;
1015     if (-f '/usr/lib/ISOLINUX/isolinux.bin') {
1016         # Newer ISOLINUX version
1017         @files = qw(/usr/lib/ISOLINUX/isolinux.bin /usr/lib/syslinux/modules/bios/mboot.c32 /usr/lib/syslinux/modules/bios/libcom32.c32 /usr/lib/syslinux/modules/bios/menu.c32 /usr/lib/syslinux/modules/bios/ldlinux.c32);
1018     } else {
1019         # Older ISOLINUX version
1020         @files = qw(/usr/lib/syslinux/isolinux.bin /usr/lib/syslinux/mboot.c32 /usr/lib/syslinux/menu.c32);
1021     }
1022     system_verbose("cp @files isolinux");
1023     open(my $fh, ">isolinux/isolinux.cfg");
1024     if ($#scripts) {
1025         print $fh "TIMEOUT 50\n";
1026         print $fh "DEFAULT menu\n";
1027     } else {
1028         print $fh "DEFAULT $config_name\n";
1029     }
1030     print $fh "$menu_iso";
1031     close($fh);
1032
1033     my $files = join(" ", map("$_=$_", (keys(%files_iso), 'isolinux/isolinux.cfg', map(s|.*/|isolinux/|r, @files))));
1034     $iso_image ||= "$config_name.iso";
1035
1036     # Note: We use -U flag below to "Allow 'untranslated' filenames,
1037     # completely violating the ISO9660 standards". Without this
1038     # option, isolinux is not able to read files names for example
1039     # bzImage-3.0.
1040     system_verbose("$CFG::genisoimage -R -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -hide-rr-moved -U -o $iso_image -graft-points $files");
1041     print("ISO image created: $builddir/$iso_image\n");
1042 }
1043
1044 exit(0) if defined $gen_only;
1045
1046 ## Boot the system using various methods and send serial output to stdout
1047
1048 if (scalar(@scripts) > 1 && ( defined $dhcp_tftp || defined $serial || defined $iprelay)) {
1049     die "You cannot do this with multiple scripts simultaneously";
1050 }
1051
1052 if ($variables->{WVTEST_TIMEOUT}) {
1053     print STDERR "wvtest: timeout ", $variables->{WVTEST_TIMEOUT}, "\n";
1054 }
1055
1056 ### Start in Qemu
1057
1058 if (defined $qemu) {
1059     # Qemu
1060     $qemu ||= $variables->{QEMU} || $CFG::qemu;
1061     my @qemu_flags = split(" ", $qemu);
1062     $qemu = shift(@qemu_flags);
1063
1064     @qemu_flags = split(/ +/, trim($variables->{QEMU_FLAGS})) if exists $variables->{QEMU_FLAGS};
1065     @qemu_flags = split(/ +/, trim($qemu_flags_cmd)) if $qemu_flags_cmd;
1066     push(@qemu_flags, split(/ +/, trim($qemu_append || '')));
1067
1068     if (defined $iso_image) {
1069         # Boot NOVA with grub (and test the iso image)
1070         push(@qemu_flags, ('-cdrom', $iso_image));
1071     } else {
1072         # Boot NOVA without GRUB
1073
1074         # Non-patched qemu doesn't like commas, but NUL can live with pluses instead of commans
1075         foreach (@$modules) {s/,/+/g;}
1076         generate_configs("", $generated, $filename);
1077
1078         if (scalar @$modules) {
1079             my ($kbin, $kcmd) = split(' ', shift(@$modules), 2);
1080             $kcmd = '' if !defined $kcmd;
1081             my $dtb;
1082             @$modules = map { if (/\.dtb$/) { $dtb=$_; (); } else { $_ } } @$modules;
1083             my $initrd = join ",", @$modules;
1084
1085             push(@qemu_flags, ('-kernel', $kbin, '-append', $kcmd));
1086             push(@qemu_flags, ('-initrd', $initrd)) if $initrd;
1087             push(@qemu_flags, ('-dtb', $dtb)) if $dtb;
1088         }
1089     }
1090     if (!grep /^-serial$/, @qemu_flags) {
1091         push(@qemu_flags,  qw(-serial stdio)); # Redirect serial output (for collecting test restuls)
1092     }
1093     unshift(@qemu_flags, ('-name', $config_name));
1094     print STDERR "novaboot: Running: ".shell_cmd_string($qemu, @qemu_flags)."\n";
1095     $exp = Expect->spawn(($qemu, @qemu_flags)) || die("exec() failed: $!");
1096 }
1097
1098 ### Local DHCPD and TFTPD
1099
1100 my ($dhcpd_pid, $tftpd_pid);
1101
1102 $tftp=1 if $tftp_port;
1103
1104 if (defined $dhcp_tftp)
1105 {
1106     generate_configs("(nd)", $generated, $filename);
1107     system_verbose('mkdir -p tftpboot');
1108     generate_grub_config("tftpboot/os-menu.lst", $config_name, "(nd)", \@$modules, "timeout 0");
1109     open(my $fh, '>', 'dhcpd.conf');
1110     my $mac = `cat /sys/class/net/$netif/address`;
1111     chomp $mac;
1112     print $fh "subnet 10.23.23.0 netmask 255.255.255.0 {
1113                       range 10.23.23.10 10.23.23.100;
1114                       filename \"bin/boot/grub/pxegrub.pxe\";
1115                       next-server 10.23.23.1;
1116 }
1117 host server {
1118         hardware ethernet $mac;
1119         fixed-address 10.23.23.1;
1120 }";
1121     close($fh);
1122     system_verbose("sudo ip a add 10.23.23.1/24 dev $netif;
1123             sudo ip l set dev $netif up;
1124             sudo touch dhcpd.leases");
1125
1126     # We run servers by forking ourselves, because the servers end up
1127     # in our process group and get killed by signals sent to the
1128     # process group (e.g. Ctrl-C on terminal).
1129     $dhcpd_pid = fork();
1130     exec_verbose("sudo dhcpd -d -cf dhcpd.conf -lf dhcpd.leases -pf dhcpd.pid") if ($dhcpd_pid == 0);
1131 }
1132
1133 if (defined $dhcp_tftp || defined $tftp) {
1134     $tftp_port ||= 69;
1135     # Unfortunately, tftpd requires root privileges even with
1136     # non-privileged (>1023) port due to initgroups().
1137     system_verbose("sudo in.tftpd --listen --secure -v -v -v --pidfile tftpd.pid  --address :$tftp_port $builddir");
1138
1139     # Kill server when we die
1140     $SIG{__DIE__} = sub { system_verbose('sudo pkill --pidfile=dhcpd.pid') if (defined $dhcp_tftp);
1141                           system_verbose('sudo pkill --pidfile=tftpd.pid'); };
1142
1143     # We have to kill tftpd explicitely, because it is not in our process group
1144     $SIG{INT} = sub { system_verbose('sudo pkill --pidfile=tftpd.pid'); exit(0); };
1145 }
1146
1147 ### AMT IDE-R
1148 if (defined $ider) {
1149     my $ider_cmd= "amtider -c $iso_image -u $amt_user -p $amt_password $amt_host $amt_port"  ;
1150     print STDERR "novaboot: Running: $ider_cmd\n" =~ s/\Q$amt_password\E/???/r;
1151     my $ider_pid = fork();
1152     if ($ider_pid == 0) {
1153         exec($ider_cmd);
1154         die "IDE redirection failed";
1155     }
1156     # FIXME: This collides with --tftp option. Hopefully, nobody needs
1157     # to use both simultaneously.
1158     $SIG{__DIE__} = sub { system_verbose('kill $ider_pid'); };
1159 }
1160
1161 ### Reset target (IP relay, AMT, ...)
1162
1163 if (defined $target_reset && $reset) {
1164     print STDERR "novaboot: Reseting the test box... ";
1165     &$target_reset();
1166     print STDERR "done\n";
1167     if (defined $exp) {
1168         # We don't want to output anything printed by the target
1169         # before reset so we clear the buffers now. This is, however,
1170         # not ideal because we may loose some data that were sent
1171         # after the reset. If this is a problem, one should reset and
1172         # connect to serial line in atomic manner. For example, if
1173         # supported by hardware, use --remote-cmd 'sterm -d ...' and
1174         # do not use separate --reset-cmd.
1175         my $log = $exp->log_stdout;
1176         $exp->log_stdout(0);
1177         $exp->expect(0); # Read data from target
1178         $exp->clear_accum();    # Clear the read data
1179         $exp->log_stdout($log);
1180     }
1181 }
1182
1183 ### U-boot conversation
1184 if (defined $uboot) {
1185     my $uboot_prompt = $uboot || '=> ';
1186     print STDERR "novaboot: Waiting for U-Boot prompt...\n";
1187     $exp || die("No serial line connection");
1188     $exp->log_stdout(1);
1189     #$exp->exp_internal(1);
1190     $exp->expect(20,
1191                  [qr/Hit any key to stop autoboot:/, sub { $exp->send("\n"); exp_continue; }],
1192                  $uboot_prompt) || die "No U-Boot prompt deteceted";
1193     foreach my $cmdspec (@uboot_init) {
1194         my ($cmd, $timeout);
1195         die "Internal error - please report a bug" unless ref($cmdspec) eq "HASH";
1196
1197         if ($cmdspec->{system}) {
1198             $cmd = `$cmdspec->{system}`;
1199         } else {
1200             $cmd = $cmdspec->{command};
1201         }
1202         $timeout = $cmdspec->{timeout} // 10;
1203
1204         if ($cmd =~ /\$NB_MYIP/) {
1205             my $ip = (grep /inet /, `ip addr show $netif`)[0] || die "Problem determining IP address of $netif";
1206             $ip =~ s/\s*inet ([0-9.]*).*/$1/;
1207             $cmd =~ s/\$NB_MYIP/$ip/g;
1208         }
1209         if ($cmd =~ /\$NB_PREFIX/) {
1210             my $p = $prefix;
1211             $p =~ s|/*$||;
1212             $cmd =~ s/\$NB_PREFIX/$p/g;
1213         }
1214         chomp($cmd);
1215         $exp->send("$cmd\n");
1216
1217         my ($matched_pattern_position, $error,
1218             $successfully_matching_string,
1219             $before_match, $after_match) =
1220                 $exp->expect($timeout, $uboot_prompt);
1221         die "No U-Boot prompt: $error" if $error;
1222
1223         if ($cmdspec->{dest}) {
1224             open(my $fh, ">", $cmdspec->{dest}) or die "Cannot open '$cmdspec->{dest}': $!";
1225             print $fh $before_match;
1226             close($fh);
1227         }
1228     }
1229
1230     # Load files if there are some load lines in the script
1231     if (scalar(@$modules) > 0  && !$variables->{NO_BOOT}) {
1232         my ($kbin, $kcmd) = split(' ', shift(@$modules), 2);
1233         my $dtb;
1234         @$modules = map { if (/\.dtb$/) { $dtb=$_; (); } else { $_ } } @$modules;
1235         my $initrd = shift @$modules;
1236
1237         if (defined $kbin) {
1238             die "No '--uboot-addr kernel' given" unless $uboot_addr{kernel};
1239             $exp->send("tftpboot $uboot_addr{kernel} $prefix$kbin\n");
1240             $exp->expect(10,
1241                          [qr/##/, sub { exp_continue; }],
1242                          $uboot_prompt) || die "Kernel load: " . ($! || "timeout");
1243         }
1244         if (defined $dtb) {
1245             die "No '--uboot-addr fdt' given" unless $uboot_addr{fdt};
1246             $exp->send("tftpboot $uboot_addr{fdt} $prefix$dtb\n");
1247             $exp->expect(10,
1248                          [qr/##/, sub { exp_continue; }],
1249                          $uboot_prompt) || die "Device tree load: " . ($! || "timeout");
1250         } else  {
1251             $uboot_addr{fdt} = '';
1252         }
1253         if (defined $initrd) {
1254             die "No '--uboot-addr ramdisk' given" unless $uboot_addr{ramdisk};
1255             $exp->send("tftpboot $uboot_addr{ramdisk} $prefix$initrd\n");
1256             $exp->expect(10,
1257                          [qr/##/, sub { exp_continue; }],
1258                          $uboot_prompt) || die "Initrd load: " . ($! || "timeout");
1259         } else {
1260             $uboot_addr{ramdisk} = '-';
1261         }
1262
1263         $kcmd //= '';
1264         $exp->send("setenv bootargs $kcmd\n");
1265         $exp->expect(5, $uboot_prompt)  || die "U-Boot prompt: " . ($! || "timeout");
1266
1267     }
1268     $uboot_cmd //= $variables->{UBOOT_CMD} // 'bootm $kernel_addr $ramdisk_addr $fdt_addr';
1269     if (!$variables->{NO_BOOT} && $uboot_cmd ne '') {
1270         $uboot_cmd =~ s/\$kernel_addr/$uboot_addr{kernel}/g;
1271         $uboot_cmd =~ s/\$ramdisk_addr/$uboot_addr{ramdisk}/g;
1272         $uboot_cmd =~ s/\$fdt_addr/$uboot_addr{fdt}/g;
1273
1274         $exp->send($uboot_cmd . "\n");
1275         $exp->expect(5, "\n")  || die "U-Boot command: " . ($! || "timeout");
1276     }
1277 }
1278
1279 ### Serial line interaction
1280 if ($interaction && defined $exp) {
1281     # Serial line of the target is available
1282     my $interrupt = 'Ctrl-C';
1283     if ($interactive && !@exiton) {
1284         $interrupt = '"~~."';
1285     }
1286     print STDERR "novaboot: Serial line interaction (press $interrupt to interrupt)...\n";
1287     $exp->log_stdout(1);
1288     if (@exiton) {
1289         $exp->expect($exiton_timeout, @expect_raw, @exiton) || die("exiton: " . ($! || "timeout"));
1290     } else {
1291         my @inputs = ($exp);
1292         my $infile = new IO::File;
1293         $infile->IO::File::fdopen(*STDIN,'r');
1294         my $in_object = Expect->exp_init($infile);
1295         $in_object->set_group($exp);
1296
1297         if ($interactive) {
1298             $in_object->set_seq('~~\.', sub { print STDERR "novaboot: Escape sequence detected\r\n"; undef; });
1299             $in_object->manual_stty(0);   # Use raw terminal mode
1300         } else {
1301             $in_object->manual_stty(1);   # Do not modify terminal settings
1302         }
1303         push(@inputs, $in_object);
1304         #use Data::Dumper;
1305         #print Dumper(\@expect_raw);
1306         $exp->expect(undef, @expect_raw) if @expect_raw;
1307
1308         $^W = 0; # Suppress Expect warning: handle id(3) is not a tty. Not changing mode at /usr/share/perl5/Expect.pm line 393, <> line 8.
1309         Expect::interconnect(@inputs) unless defined($exp->exitstatus);
1310         $^W = 1;
1311     }
1312 }
1313
1314 # When exp-spawned command ignores SIGHUP, Expect waits 5 seconds
1315 # before killing it. We kill it by SIGTERM immediately.
1316 kill TERM => $exp->pid if defined $exp && $exp->pid;
1317
1318 ## Kill dhcpc or tftpd
1319 if (defined $dhcp_tftp || defined $tftp) {
1320     die("novaboot: This should kill servers on background\n");
1321 }
1322
1323 # Always finish novaboot output with newline
1324 print "\n" if $final_eol;
1325
1326 ## Documentation
1327
1328 =encoding utf8
1329 =head1 NAME
1330
1331 novaboot - Boots a locally compiled operating system on a remote
1332 target or in qemu
1333
1334 =head1 SYNOPSIS
1335
1336 B<novaboot> --help
1337
1338 B<novaboot> [option]... [--] script...
1339
1340 B<./script> [option]...
1341
1342 =head1 DESCRIPTION
1343
1344 Novaboot makes booting of a locally compiled operating system (OS)
1345 (e.g. NOVA or Linux) on remote targets as simple as running a program
1346 locally. It automates things like copying OS images to a TFTP server,
1347 generation of bootloader configuration files, resetting of target
1348 hardware or redirection of target's serial line to stdin/out. Novaboot
1349 is highly configurable and makes it easy to boot a single image on
1350 different targets or different images on a single target.
1351
1352 Novaboot operation is controlled by configuration files, command line
1353 options and by a so-called novaboot script, which can be thought as a
1354 generalization of bootloader configuration files (see L</"NOVABOOT
1355 SCRIPT SYNTAX">). The typical way of using novaboot is to make the
1356 novaboot script executable and set its first line to I<#!/usr/bin/env
1357 novaboot>. Then, booting a particular OS configuration becomes the
1358 same as executing a local program â€“ the novaboot script.
1359
1360 Novaboot uses configuration files to, among other things, define
1361 command line options needed for different targets. Users typically use
1362 only the B<-t>/B<--target> command line option to select the target.
1363 Internally, this option expands to the pre-configured options.
1364 Novaboot searches configuration files at multiple places, which allows
1365 having per-system, per-user or per-project configurations.
1366 Configuration file syntax is described in section L</"CONFIGURATION
1367 FILES">.
1368
1369 Simple examples of using C<novaboot>:
1370
1371 =over 3
1372
1373 =item 1.
1374
1375 Running an OS in Qemu can be accomplished by giving the B<--qemu> option.
1376 Thus running
1377
1378  novaboot --qemu myos
1379
1380 (or C<./myos --qemu> as described above) will run Qemu and make it
1381 boot the configuration specified in the F<myos> script.
1382
1383 =item 2.
1384
1385 Create a bootloader configuration file (currently supported
1386 bootloaders are GRUB, GRUB2, ISOLINUX, Pulsar, and U-Boot) and copy it
1387 with all other files needed for booting to a remote boot server. Then
1388 use a TCP/IP-controlled relay/serial-to-TCP converter to reset the
1389 target and receive its serial output.
1390
1391  ./myos --grub2 --server=192.168.1.1:/tftp --iprelay=192.168.1.2
1392
1393 Alternatively, you can put these switches to the configuration file
1394 and run:
1395
1396  ./myos --target mytarget
1397
1398 =item 3.
1399
1400 Run DHCP and TFTP server on developer's machine to boot the target
1401 from it.
1402
1403  ./myos --dhcp-tftp
1404
1405 This usage is useful when no network infrastructure is in place, and
1406 the target is connected directly to developer's box.
1407
1408 =item 4.
1409
1410 Create bootable ISO image.
1411
1412  novaboot --iso -- script1 script2
1413
1414 The created ISO image will have ISOLINUX bootloader installed on it,
1415 and the boot menu will allow selecting between I<script1> and
1416 I<script2> configurations.
1417
1418 =back
1419
1420 =head1 PHASES AND OPTIONS
1421
1422 Novaboot performs its work in several phases. Command like options
1423 described bellow influence the execution of each phase or allow their
1424 skipping. The list of phases (in the execution order) is as follows.
1425
1426 =over
1427
1428 =item 1. L<Configuration reading|/Configuration reading phase>
1429
1430 =item 2. L<Command line processing|/Command line processing phase>
1431
1432 =item 3. L<Script preprocessing|/Script preprocessing phase>
1433
1434 =item 4. L<File generation|/File generation phase>
1435
1436 =item 5. L<Target connection|/Target connection check>
1437
1438 =item 6. L<File deployment|/File deployment phase>
1439
1440 =item 7. L<Target power-on and reset|/Target power-on and reset phase>
1441
1442 =item 8. L<Interaction with the bootloader|/Interaction with the bootloader on the target>
1443
1444 =item 9. L<Target interaction|/Target interaction phase>
1445
1446 =back
1447
1448 Each phase is described in the following sections together with the
1449 command line options that control it.
1450
1451 =head2 Configuration reading phase
1452
1453 After starting, novaboot reads zero or more configuration files. We
1454 describe their content in section L</"CONFIGURATION FILES">. By default, the
1455 configuration is read from multiple locations. First from the system
1456 configuration directory (F</etc/novaboot.d/>), second from the user
1457 configuration file (F<~/.config/novaboot>) and third from F<.novaboot>
1458 files along the path to the current directory. Alternatively, a single
1459 configuration file specified with the B<-c> switch or with the
1460 C<NOVABOOT_CONFIG> environment variable is read. The latter read files
1461 override settings from the former ones.
1462
1463 The system configuration directory is determined by the content of
1464 NOVABOOT_CONFIG_DIR environment variable and defaults to
1465 F</etc/novaboot.d>. Files in this directory with names consisting
1466 solely of English letters, numbers, dashes '-' and underscores '_'
1467 (note that dot '.' is not included) are read in alphabetical order.
1468
1469 Then, the user configuration file is read from
1470 F<$XDG_CONFIG_HOME/novaboot>. If C<$XDG_CONFIG_HOME> environment
1471 variable is not set F<~/.config/novaboot> is read instead.
1472
1473 Finally, novaboot searches for files named F<.novaboot> starting from the
1474 directory of the novaboot script (or working directory, see bellow)
1475 and continuing upwards up to the root directory. The found
1476 configuration files are then read in the opposite order (i.e. from the
1477 root directory downwards). This ordering allows having, for example, a project
1478 specific configuration in F<~/project/.novaboot>.
1479
1480 Note the difference between F<~/.config/novaboot> and F<~/.novaboot>.
1481 The former one is always read, whereas the latter only when novaboot
1482 script or working directory is under the C<$HOME> directory.
1483
1484 In certain cases, the location of the novaboot script cannot be
1485 determined in this early phase. This situation happens either when the script is
1486 read from the standard input or when novaboot is invoked explicitly as
1487 in the example L</"4."> above. In this case, the current working
1488 directory is used as a starting point for configuration file search
1489 instead of the novaboot script directory.
1490
1491 =over 8
1492
1493 =item -c, --config=I<filename>
1494
1495 Use the specified configuration file instead of the default one(s).
1496
1497 =back
1498
1499 =head2 Command line processing phase
1500
1501 =over 8
1502
1503 =item --dump-config
1504
1505 Dump the current configuration to stdout end exit. Useful as an
1506 initial template for a configuration file.
1507
1508 =item -h, --help
1509
1510 Print short (B<-h>) or long (B<--help>) help.
1511
1512 =item -t, --target=I<target>
1513
1514 This option serves as a user configurable shortcut for other novaboot
1515 options. The effect of this option is the same as specifying the
1516 options stored in the C<%targets> configuration variable under key
1517 I<target>. See also L</"CONFIGURATION FILES">.
1518
1519 When this option is not given, novaboot tries to determine the target
1520 to use from either B<NOVABOOT_TARGET> environment variable or
1521 B<$default_target> configuration file variable.
1522
1523 =item --ssh=I<user@hostname>
1524
1525 Configures novaboot to control the target via C<novaboot-shell>
1526 running remotely via SSH.
1527
1528 Using this option is the same as specifying B<--remote-cmd>,
1529 B<--remote-expect>, B<--server> B<--rsync-flags>, B<--prefix> and
1530 B<--reset-cmd> manually in a way compatible with C<novaboot-shell>.
1531 The server can be configured to provide other, safe bootloader-related
1532 options, to the client. When this happens, novaboot prints them to
1533 stdout.
1534
1535 Currently, this in an initial experimental implementation. We plan to
1536 change/extend this feature soon!
1537
1538 =back
1539
1540 =head2 Script preprocessing phase
1541
1542 This phase allows modifying the parsed novaboot script before it is
1543 used in the later phases.
1544
1545 =over 8
1546
1547 =item -a, --append=I<parameters>
1548
1549 Append a string to the first C<load> line in the novaboot script. This option
1550 can be used to append parameters to the kernel's or root task's
1551 command line. This option can appear multiple times.
1552
1553 =item -b, --bender
1554
1555 Use L<Bender|https://github.com/TUD-OS/morbo/blob/master/standalone/bender.c>
1556 chainloader. Bender scans the PCI bus for PCI serial ports and stores
1557 the information about them in the BIOS data area for use by the
1558 kernel.
1559
1560 =item --chainloader=I<chainloader>
1561
1562 Specifies a chainloader that is loaded before the kernel and other
1563 files specified in the novaboot script. E.g. 'bin/boot/bender
1564 promisc'.
1565
1566 =item --dump
1567
1568 Print the modules to boot and their parameters, after this phase
1569 finishes. Then exit. This is useful for seeing the effect of other
1570 options in this section.
1571
1572 =item -k, --kernel=F<file>
1573
1574 Replace the first word on the first C<load> line in the novaboot
1575 script with F<file>.
1576
1577 =item --scriptmod=I<Perl expression>
1578
1579 When novaboot reads the script, I<Perl expression> is executed for every
1580 line (in $_ variable). For example, C<novaboot
1581 --scriptmod=s/sigma0/omega6/g> replaces every occurrence of I<sigma0>
1582 in the script with I<omega6>.
1583
1584 When this option is present, it overrides I<$script_modifier> variable
1585 from the configuration file, which has the same effect. If this option
1586 is given multiple times all expressions are evaluated in the command
1587 line order.
1588
1589 =back
1590
1591 =head2 File generation phase
1592
1593 In this phase, files needed for booting are generated in a so-called
1594 I<build directory> (see L</--build-dir>). In most cases configuration
1595 for a bootloader is generated automatically by novaboot. It is also
1596 possible to generate other files using I<heredoc> or I<"<"> syntax in
1597 novaboot scripts. Finally, novaboot can generate binaries in this phases by
1598 running C<scons> or C<make>.
1599
1600 =over 8
1601
1602 =item --build-dir=I<directory>
1603
1604 Overrides the default build directory location.
1605
1606 The default build directory location is determined as follows: If the
1607 configuration file defines the C<$builddir> variable, its value is
1608 used. Otherwise, it is the directory that contains the first processed
1609 novaboot script.
1610
1611 See also L</BUILDDIR> variable.
1612
1613 =item -g, --grub[=I<filename>]
1614
1615 Generates grub bootloader menu file. If the I<filename> is not
1616 specified, F<menu.lst> is used. The I<filename> is relative to the
1617 build directory (see B<--build-dir>).
1618
1619 =item --grub-preamble=I<prefix>
1620
1621 Specifies the I<preamble> that is at the beginning of the generated
1622 GRUB or GRUB2 config files. This is useful for specifying GRUB's
1623 timeout.
1624
1625 =item --prefix=I<prefix>
1626
1627 Specifies I<prefix> (e.g. F</srv/tftp>) that is put in front of every
1628 filename in generated bootloader configuration files (or in U-Boot
1629 commands).
1630
1631 If the I<prefix> contains string $NAME, it will be replaced with the
1632 name of the novaboot script (see also B<--name>).
1633
1634 If the I<prefix> contains string $BUILDDIR, it will be replaced with
1635 the build directory (see also B<--build-dir>).
1636
1637 =item --grub-prefix
1638
1639 Alias for B<--prefix>.
1640
1641 =item --grub2[=I<filename>]
1642
1643 Generate GRUB2 menu entry in I<filename>. If I<filename> is not
1644 specified F<grub.cfg> is used. The content of the menu entry can be
1645 customized with B<--grub-preamble>, B<--grub2-prolog> or
1646 B<--grub_prefix> options.
1647
1648 To use the generated menu entry on your development
1649 machine that uses GRUB2, append the following snippet to
1650 F</etc/grub.d/40_custom> file and regenerate your grub configuration,
1651 i.e. run update-grub on Debian/Ubuntu.
1652
1653   if [ -f /path/to/nul/build/grub.cfg ]; then
1654     source /path/to/nul/build/grub.cfg
1655   fi
1656
1657 =item --grub2-prolog=I<prolog>
1658
1659 Specifies the text that novaboot puts at the beginning of the GRUB2 menu entry.
1660
1661 =item -m, --make[=make command]
1662
1663 Runs C<make> to build files that are not generated by novaboot itself.
1664
1665 =item --name=I<string>
1666
1667 Use the name I<string> instead of the name of the novaboot script.
1668 This name is used for things like a title of grub menu or for the
1669 server directory where the boot files are copied to.
1670
1671 =item --no-file-gen
1672
1673 Do not run external commands to generate files (i.e. "<" syntax and
1674 C<run> keyword). This switch does not influence the generation of files
1675 specified with "<<WORD" syntax.
1676
1677 =item -p, --pulsar[=mac]
1678
1679 Generates pulsar bootloader configuration file named F<config-I<mac>>
1680 The I<mac> string is typically a MAC address and defaults to
1681 I<novaboot>.
1682
1683 =item --scons[=scons command]
1684
1685 Runs C<scons> to build files that are not generated by novaboot
1686 itself.
1687
1688 =item --strip-rom
1689
1690 Strip I<rom://> prefix from command lines and generated config files.
1691 The I<rom://> prefix is used by NUL. For NRE, it has to be stripped.
1692
1693 =item --gen-only
1694
1695 Exit novaboot after file generation phase.
1696
1697 =back
1698
1699 =head2 Target connection check
1700
1701 In this phase novaboot connects to target's serial port (if it has
1702 one). If another novaboot user/instance occupies the target, novaboot
1703 exits here with an error message.
1704
1705 =over 8
1706
1707 =item --amt=I<"[user[:password]@]host[:port]>
1708
1709 Use Intel AMT technology to control the target machine. WS management
1710 is used to powercycle it and Serial-Over-Lan (SOL) for input/output.
1711 The hostname or (IP address) is given by the I<host> parameter. If the
1712 I<password> is not specified, environment variable AMT_PASSWORD is
1713 used. The I<port> specifies a TCP port for SOL. If not specified, the
1714 default is 16992. The default I<user> is admin.
1715
1716 =item --iprelay=I<addr[:port]>
1717
1718 Use TCP/IP relay and serial port to access the target's serial port
1719 and powercycle it. The I<addr> parameter specifies the IP address of
1720 the relay. If I<port> is not specified, it defaults to 23.
1721
1722 Note: This option is supposed to work with HWG-ER02a IP relays.
1723
1724 =item --iprelay-cmd=I<command>
1725
1726 Similar to B<--iprelay> but uses I<command> to talk to the iprelay
1727 rather than direct network connection.
1728
1729 =item -s, --serial[=device]
1730
1731 Target's serial line is connected to host's serial line (device). The
1732 default value for device is F</dev/ttyUSB0>.
1733
1734 The value of this option is exported in NB_NOVABOOT environment
1735 variable to all subprocesses run by C<novaboot>.
1736
1737 =item --stty=I<settings>
1738
1739 Specifies settings passed to C<stty> invoked on the serial line
1740 specified with B<--serial> option. If this option is not given,
1741 C<stty> is called with C<raw -crtscts -onlcr 115200> settings.
1742
1743 =item --remote-cmd=I<cmd>
1744
1745 Command that mediates connection to the target's serial line. For
1746 example C<ssh server 'cu -l /dev/ttyS0'>.
1747
1748 =item --remote-expect=I<string>
1749
1750 Wait for reception of I<string> after establishing the remote
1751 connection. This option is needed when novaboot should wait for
1752 confirmation before deploying files to the target, e.g. to not
1753 overwrite other user's files when they are using the target.
1754
1755 =item --remote-expect-silent=I<string>
1756
1757 The same as B<--remote-expect> except that the remote output is not
1758 echoed to stdout while waiting for the I<string>. Everything after the
1759 matched string is printed to stdout, so you may want to include line
1760 end characters in the I<string> as well.
1761
1762 =item --remote-expect-timeout=I<seconds>
1763
1764 Timeout in seconds for B<--remote-expect> or
1765 B<--remote-expect-seconds>. When negative, waits forever. The default
1766 is 180 seconds.
1767
1768 =back
1769
1770 =head2 File deployment phase
1771
1772 In some setups, it is necessary to copy the files needed for booting
1773 to a particular location, e.g. to a TFTP boot server or to the
1774 F</boot> partition.
1775
1776 =over 8
1777
1778 =item -d, --dhcp-tftp
1779
1780 Turns your workstation into a DHCP and TFTP server so that the OS can
1781 be booted via PXE BIOS (or similar mechanism) on the test machine
1782 directly connected by a plain Ethernet cable to your workstation.
1783
1784 The DHCP and TFTP servers require root privileges and C<novaboot>
1785 uses C<sudo> command to obtain those. You can put the following to
1786 I</etc/sudoers> to allow running the necessary commands without asking
1787 for a password.
1788
1789  Cmnd_Alias NOVABOOT = /bin/ip a add 10.23.23.1/24 dev eth0, /bin/ip l set dev eth0 up, /usr/sbin/dhcpd -d -cf dhcpd.conf -lf dhcpd.leases -pf dhcpd.pid, /usr/sbin/in.tftpd --listen --secure -v -v -v --pidfile tftpd.pid *, /usr/bin/touch dhcpd.leases, /usr/bin/pkill --pidfile=dhcpd.pid, /usr/bin/pkill --pidfile=tftpd.pid
1790  your_login ALL=NOPASSWD: NOVABOOT
1791
1792 =item --tftp
1793
1794 Starts a TFTP server on your workstation. This is similar to
1795 B<--dhcp-tftp> except that DHCP server is not started.
1796
1797 The TFTP server requires root privileges and C<novaboot> uses C<sudo>
1798 command to obtain those. You can put the following to I</etc/sudoers>
1799 to allow running the necessary commands without asking for a password.
1800
1801  Cmnd_Alias NOVABOOT =  /usr/sbin/in.tftpd --listen --secure -v -v -v --pidfile tftpd.pid *, /usr/bin/pkill --pidfile=tftpd.pid
1802  your_login ALL=NOPASSWD: NOVABOOT
1803
1804 =item --tftp-port=I<port>
1805
1806 Port to run the TFTP server on. Implies B<--tftp>.
1807
1808 =item --netif=I<network interface>
1809
1810 Network interface used to deploy files to the target. The default value is
1811 I<eth0>. This option influences the configuration of the DHCP server started
1812 by B<--dhcp-tftp> and the value that B<$NB_MYIP> get replaced with during
1813 U-Boot conversation.
1814
1815 =item --iso[=filename]
1816
1817 Generates the ISO image that boots NOVA system via GRUB. If no filename
1818 is given, the image is stored under I<NAME>.iso, where I<NAME> is the name
1819 of the novaboot script (see also B<--name>).
1820
1821 =item --server[=[[user@]server:]path]
1822
1823 Copy all files needed for booting to another location. The files will
1824 be copied (by B<rsync> tool) to the directory I<path>. If the I<path>
1825 contains string $NAME, it will be replaced with the name of the
1826 novaboot script (see also B<--name>).
1827
1828 =item --rsync-flags=I<flags>
1829
1830 Specifies I<flags> to append to F<rsync> command line when
1831 copying files as a result of I<--server> option.
1832
1833 =item --concat
1834
1835 If B<--server> is used and its value ends with $NAME, then after
1836 copying the files, a new bootloader configuration file (e.g. menu.lst)
1837 is created at I<path-wo-name>, i.e. the path specified by B<--server>
1838 with $NAME part removed. The content of the file is created by
1839 concatenating all files of the same name from all subdirectories of
1840 I<path-wo-name> found on the "server".
1841
1842 =item --ider
1843
1844 Use Intel AMT technology for IDE redirection. This allows the target
1845 machine to boot from novaboot created ISO image. Implies B<--iso>.
1846
1847 The experimental C<amtider> utility needed by this option can be
1848 obtained from https://github.com/wentasah/amtterm.
1849
1850 =back
1851
1852 =head2 Target power-on and reset phase
1853
1854 At this point, the target is reset (or switched on/off). There are
1855 several ways how this can be accomplished. Resetting a physical target
1856 can currently be accomplished by the following options: B<--amt>,
1857 B<--iprelay>, B<--reset-cmd> and B<--reset-send>.
1858
1859 =over 8
1860
1861 =item --on, --off
1862
1863 Switch on/off the target machine and exit. The script (if any) is
1864 completely ignored. Currently, it works only with the following
1865 options: B<--iprelay>, B<--amt>, B<--ssh>.
1866
1867 =item -Q, --qemu[=I<qemu-binary>]
1868
1869 Boot the configuration in qemu. Optionally, the name of qemu binary
1870 can be specified as a parameter.
1871
1872 =item --qemu-append=I<flags>
1873
1874 Append I<flags> to the default qemu flags (QEMU_FLAGS variable or
1875 C<-cpu coreduo -smp 2>).
1876
1877 =item -q, --qemu-flags=I<flags>
1878
1879 Replace the default qemu flags (QEMU_FLAGS variable or C<-cpu coreduo
1880 -smp 2>) with I<flags> specified here.
1881
1882 =item --reset-cmd=I<cmd>
1883
1884 Runs command I<cmd> to reset the target.
1885
1886 =item --reset-send=I<string>
1887
1888 Reset the target by sending the given I<string> to the remote serial
1889 line. "\n" sequences are replaced with the newline character.
1890
1891 =item --no-reset, --reset
1892
1893 Disable/enable resetting of the target.
1894
1895 =back
1896
1897 =head2 Interaction with the bootloader on the target
1898
1899 =over 8
1900
1901 =item --uboot[=I<prompt>]
1902
1903 Interact with U-Boot bootloader to boot the thing described in the
1904 novaboot script. I<prompt> specifies the U-Boot's prompt (default is
1905 "=> ", other common prompts are "U-Boot> " or "U-Boot# ").
1906
1907 =item --no-uboot
1908
1909 Disable U-Boot interaction previously enabled with B<--uboot>.
1910
1911 =item --uboot-init
1912
1913 Command(s) to send the U-Boot bootloader before loading the images and
1914 booting them. This option can be given multiple times. After sending
1915 commands from each option novaboot waits for U-Boot I<prompt>.
1916
1917 If the command contains string I<$NB_MYIP> then this string is
1918 replaced by IPv4 address of eth0 interface (see also B<--netif>).
1919 Similarly, I<$NB_PREFIX> is replaced with prefix given by B<--prefix>.
1920
1921 See also C<uboot> keyword in L</"NOVABOOT SCRIPT SYNTAX">).
1922
1923 =item --uboot-addr I<name>=I<address>
1924
1925 Load address of U-Boot's C<tftpboot> command for loading I<name>,
1926 where name is one of I<kernel>, I<ramdisk> or I<fdt> (flattened device
1927 tree).
1928
1929 The default addresses are ${I<name>_addr_r}, i.e. U-Boot environment
1930 variables used by convention for this purpose.
1931
1932 =item --uboot-cmd=I<command>
1933
1934 Specifies U-Boot command used to execute the OS. If the command
1935 contains strings C<$kernel_addr>, C<$ramdisk_addr>, C<$fdt_addr>,
1936 these are replaced with the addresses configured with B<--uboot-addr>.
1937
1938 The default value is
1939
1940     bootm $kernel_addr $ramdisk_addr $fdt_addr
1941
1942 or the C<UBOOT_CMD> variable if defined in the novaboot script.
1943
1944 =back
1945
1946 =head2 Target interaction phase
1947
1948 In this phase, target's serial output is redirected to stdout and if
1949 stdin is a TTY, it is redirected to the target's serial input allowing
1950 interactive work with the target.
1951
1952 =over 8
1953
1954 =item --exiton=I<string>
1955
1956 When the I<string> is sent by the target, novaboot exits. This option can
1957 be specified multiple times, in which case novaboot exits whenever
1958 either of the specified strings is sent.
1959
1960 If the I<string> is C<-re>, then the next B<--exiton>'s I<string> is
1961 treated as a regular expression. For example:
1962
1963     --exiton -re --exiton 'error:.*failed'
1964
1965 =item --exiton-re=I<regex>
1966
1967 The same as --exiton -re --exiton I<regex>.
1968
1969 =item --exiton-timeout=I<seconds>
1970
1971 By default B<--exiton> waits for the string match forever. When this
1972 option is specified, "exiton" timeouts after the specifies the number of
1973 seconds and novaboot returns non-zero exit code.
1974
1975 =item -i, --interactive
1976
1977 Setup things for the interactive use of the target. Your terminal will
1978 be switched to raw mode. In raw mode, your local terminal does not
1979 process input in any way (no echoing of entered characters, no
1980 interpretation of special characters). This, among others, means that
1981 Ctrl-C is passed to the target and does not interrupt novaboot. To
1982 exit from novaboot interactive mode type "~~.".
1983
1984 =item --no-interaction, --interaction
1985
1986 Skip resp. force target interaction phase. When skipped, novaboot exits
1987 immediately after the boot is initiated.
1988
1989 =item --expect=I<string>
1990
1991 When the I<string> is received from the target, send the string specified
1992 with the subsequent B<--send*> option to the target.
1993
1994 =item --expect-re=I<regex>
1995
1996 When target's output matches regular expression I<regex>, send the
1997 string specified with the subsequent B<--send*> option to the target.
1998
1999 =item --expect-raw=I<perl-code>
2000
2001 Provides direct control over Perl's Expect module.
2002
2003 =item --send=I<string>
2004
2005 Send I<string> to the target after the previously specified
2006 B<--expect*> was matched in the target's output. The I<string> may
2007 contain escape sequences such as "\n".
2008
2009 Note that I<string> is actually interpreted by Perl, so it can contain
2010 much more that escape sequences. This behavior may change in the
2011 future.
2012
2013 Example: C<--expect='login: ' --send='root\n'>
2014
2015 =item --sendcont=I<string>
2016
2017 Similar to B<--send> but continue expecting more input.
2018
2019 Example: C<--expect='Continue?' --sendcont='yes\n'>
2020
2021 =item --final-eol, --no-final-eol
2022
2023 By default, B<novaboot> always prints an end-of-line character at the
2024 end of its execution in order to ensure that the output of programs
2025 started after novaboot appears at the beginning of the line. When this
2026 is not desired B<--no-final-eol> option can be used to override this
2027 behavior.
2028
2029 =back
2030
2031 =head1 NOVABOOT SCRIPT SYNTAX
2032
2033 The syntax tries to mimic POSIX shell syntax. The syntax is defined
2034 by the following rules.
2035
2036 Lines starting with "#" and empty lines are ignored.
2037
2038 Lines that end with "\" are concatenated with the following line after
2039 removal of the final "\" and leading whitespace of the following line.
2040
2041 Lines of the form I<VARIABLE=...> (i.e. matching '^[A-Z_]+=' regular
2042 expression) assign values to internal variables. See L</VARIABLES>
2043 section.
2044
2045 Otherwise, the first word on the line defines the meaning of the line.
2046 The following keywords are supported:
2047
2048 =over 4
2049
2050 =item C<load>
2051
2052 These lines represent modules to boot. The
2053 word after C<load> is a file name (relative to the build directory
2054 (see B<--build-dir>) of the module to load and the remaining words are
2055 passed to it as the command line parameters.
2056
2057 When the C<load> line ends with "<<WORD" then the subsequent lines
2058 until the line containing solely WORD are copied literally to the file
2059 named on that line. This is similar to shell's heredoc feature.
2060
2061 When the C<load> line ends with "< CMD" then command CMD is executed
2062 with F</bin/sh> and its standard output is stored in the file named on
2063 that line. The SRCDIR variable in CMD's environment is set to the
2064 absolute path of the directory containing the interpreted novaboot
2065 script.
2066
2067 =item C<copy>
2068
2069 These lines are similar to C<load> lines. The
2070 file mentioned there is copied to the same place as in the case of C<load>
2071 (e.g. tftp server), but the file is not used in the bootloader
2072 configuration. Such a file can be used by the target for other
2073 purposes than booting, e.g. at OS runtime or for firmware update.
2074
2075 =item C<chld>
2076
2077 Chainload another bootloader. Instead of loading multiboot modules
2078 identified with C<load> keyword, run another bootloader. This is
2079 currently supported only by pulsar and can be used to load e.g. Grub
2080 as in the example below:
2081
2082  chld boot/grub/i386-pc/core.0
2083
2084
2085 =item C<run>
2086
2087 Lines starting with C<run> keyword contain shell commands that are run
2088 during file generation phase. This is the same as the "< CMD" syntax
2089 for C<load> keyboard except that the command's output is not
2090 redirected to a file. The ordering of commands is the same as they
2091 appear in the novaboot script.
2092
2093 =item C<uboot>
2094
2095 These lines represent U-Boot commands that are sent to the target if
2096 B<--uboot> option is given. Having a U-Boot line in the novaboot
2097 script is the same as giving B<--uboot-init> option to novaboot. The
2098 following syntax variants are supported:
2099
2100
2101   uboot[:<timeout>] <string> [> <file>]
2102   uboot[:<timeout>] < <shell> [> <file>]
2103
2104 C<string> is the literal U-Boot command.
2105
2106 The C<uboot> keyword can be suffixed with timeout specification. The
2107 syntax is C<uboot:Ns>, where C<N> is the whole number of seconds. If
2108 the U-Boot command prompt does not appear before the timeout, novaboot
2109 fails. The default timeout is 10 seconds.
2110
2111 In the second variant with the C<<> character the shell code is
2112 executed and its standard output is sent to U-Boot. Example:
2113
2114   uboot < printf "mmc write \$loadaddr 1 %x" $(($(/usr/bin/stat -c%s rootfs.ext4) / 512))
2115
2116 When C<E<gt> file> part is present, the output of the U-Boot command
2117 is written into the given file.
2118
2119 =back
2120
2121 Example (Linux):
2122
2123   #!/usr/bin/env novaboot
2124   load bzImage console=ttyS0,115200
2125   run  make -C buildroot
2126   load rootfs.cpio < gen_cpio buildroot/images/rootfs.cpio "myapp->/etc/init.d/S99myapp"
2127
2128 Example (NOVA User Land - NUL):
2129
2130   #!/usr/bin/env novaboot
2131   WVDESC=Example program
2132   load bin/apps/sigma0.nul S0_DEFAULT script_start:1,1 \
2133                            verbose hostkeyb:0,0x60,1,12,2
2134   load bin/apps/hello.nul
2135   load hello.nulconfig <<EOF
2136   sigma0::mem:16 name::/s0/log name::/s0/timer name::/s0/fs/rom ||
2137   rom://bin/apps/hello.nul
2138   EOF
2139
2140 This example will load three modules: F<sigma0.nul>, F<hello.nul> and
2141 F<hello.nulconfig>. sigma0 receives some command line parameters and
2142 F<hello.nulconfig> file is generated on the fly from the lines between
2143 C<<<EOF> and C<EOF>.
2144
2145 Example (Zynq system update via U-Boot):
2146
2147   #!/usr/bin/env novaboot
2148
2149   uboot dhcp
2150
2151   # Write kernel to FAT filesystem on the 1st SD card partition
2152   run mkimage -f uboot-image.its image.ub
2153   copy image.ub
2154   uboot:60s tftpboot ${loadaddr} $NB_PREFIX/image.ub
2155   uboot fatwrite mmc 0:1 ${loadaddr} image.ub $filesize
2156   uboot set bootargs console=ttyPS0,115200 root=/dev/mmcblk0p2
2157
2158   # Write root FS image to the 2nd SD card partition
2159   copy rootfs/images/rootfs.ext4
2160   uboot:60s tftpboot ${loadaddr} $NB_PREFIX/rootfs/images/rootfs.ext4
2161   uboot mmc part > mmc-part.txt
2162   uboot < printf "mmc write \$loadaddr %x %x" $(awk '{ if ($1 == "2") { print $2 }}' mmc-part.txt) $(($(/usr/bin/stat -L --printf=%s rootfs/images/rootfs.ext4) / 512))
2163
2164   UBOOT_CMD=boot
2165
2166
2167 =head2 VARIABLES
2168
2169 The following variables are interpreted in the novaboot script:
2170
2171 =over 8
2172
2173 =item BUILDDIR
2174
2175 Novaboot chdir()s to this directory before file generation phase. The
2176 directory name specified here is relative to the build directory
2177 specified by other means (see L</--build-dir>).
2178
2179 =item EXITON
2180
2181 Assigning this variable has the same effect as specifying L</--exiton>
2182 option.
2183
2184 =item HYPERVISOR_PARAMS
2185
2186 Parameters passed to the hypervisor. The default value is "serial", unless
2187 overridden in the configuration file.
2188
2189 =item KERNEL
2190
2191 The kernel to use instead of the hypervisor specified in the
2192 configuration file with the C<$hypervisor> variable. The value should
2193 contain the name of the kernel image as well as its command line
2194 parameters. If this variable is defined and non-empty, the variable
2195 HYPERVISOR_PARAMS is not used.
2196
2197 =item NO_BOOT
2198
2199 If this variable is 1, the system is not booted. This is currently
2200 only implemented for U-Boot bootloader where it is useful for
2201 interacting with the bootloader without booting the system - e.g. for
2202 flashing.
2203
2204 =item QEMU
2205
2206 Use a specific qemu binary (can be overridden with B<-Q>) and flags
2207 when booting this script under qemu. If QEMU_FLAGS variable is also
2208 specified flags specified in QEMU variable are replaced by those in
2209 QEMU_FLAGS.
2210
2211 =item QEMU_FLAGS
2212
2213 Use specific qemu flags (can be overridden with B<-q>).
2214
2215 =item UBOOT_CMD
2216
2217 See L</--uboot-cmd>.
2218
2219 =item WVDESC
2220
2221 Description of the WvTest-compliant program.
2222
2223 =item WVTEST_TIMEOUT
2224
2225 The timeout in seconds for WvTest harness. If no complete line appears
2226 in the test output within the time specified here, the test fails. It
2227 is necessary to specify this for long running tests that produce no
2228 intermediate output.
2229
2230 =back
2231
2232 =head1 CONFIGURATION FILES
2233
2234 Novaboot can read its configuration from one or more files. By
2235 default, novaboot looks for files in F</etc/novaboot.d>, file
2236 F<~/.config/novaboot> and files named F<.novaboot> as described in
2237 L</Configuration reading phase>. Alternatively, configuration file
2238 location can be specified with the B<-c> switch or with the
2239 NOVABOOT_CONFIG environment variable. The configuration file has Perl
2240 syntax (i.e. it is better to put C<1;> as the last line) and should set
2241 values of certain Perl variables. The current configuration can be
2242 dumped with the B<--dump-config> switch. Some configuration variables
2243 can be overridden by environment variables (see below) or by command
2244 line switches.
2245
2246 Supported configuration variables include:
2247
2248 =over 8
2249
2250 =item $builddir
2251
2252 Build directory location relative to the location of the configuration
2253 file.
2254
2255 =item $default_target
2256
2257 Default target (see below) to use when no target is explicitly
2258 specified with the B<--target> command line option or
2259 B<NOVABOOT_TARGET> environment variable.
2260
2261 =item %targets
2262
2263 Hash of target definitions to be used with the B<--target> option. The
2264 key is the identifier of the target, the value is the string with
2265 command line options. For instance, if the configuration file contains:
2266
2267  $targets{'mybox'} = '--server=boot:/tftproot --serial=/dev/ttyUSB0 --grub',
2268
2269 then the following two commands are equivalent:
2270
2271  ./myos --server=boot:/tftproot --serial=/dev/ttyUSB0 --grub
2272  ./myos -t mybox
2273
2274 =back
2275
2276 =head1 ENVIRONMENT VARIABLES
2277
2278 Some options can be specified not only via config file or command line
2279 but also through environment variables. Environment variables override
2280 the values from the configuration file and command line parameters
2281 override the environment variables.
2282
2283 =over 8
2284
2285 =item NOVABOOT_CONFIG
2286
2287 Name of the novaboot configuration file to use instead of the default
2288 one(s).
2289
2290 =item NOVABOOT_CONFIG_DIR
2291
2292 Name of the novaboot configuration directory. When not specified
2293 F</etc/novaboot.d> is used.
2294
2295 =item NOVABOOT_TARGET
2296
2297 Name of the novaboot target to use. This overrides the value of
2298 B<$default_target> from the configuration file and can be overridden
2299 with the B<--target> command line option.
2300
2301 =item NOVABOOT_BENDER
2302
2303 Defining this variable has the same effect as using B<--bender>
2304 option.
2305
2306 =back
2307
2308 =head1 AUTHORS
2309
2310 Michal Sojka <sojka@os.inf.tu-dresden.de>
2311
2312 Latest novaboot version can be found at
2313 L<https://github.com/wentasah/novaboot>.
2314
2315 =cut
2316
2317 # LocalWords:  novaboot Novaboot NOVABOOT TFTP PXE DHCP filename stty
2318 # LocalWords:  chainloader stdout Qemu qemu preprocessing ISOLINUX bootable
2319 # LocalWords:  config subprocesses sudo sudoers tftp dhcp IDE stdin
2320 # LocalWords:  subdirectories TTY whitespace heredoc POSIX WvTest