summaryrefslogtreecommitdiffstats
path: root/vmhtool
blob: f56b133891e3c7bd7d6cf4181791116f72e128aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
#!/usr/bin/env perl
#
# VM helper tools
#
# (C) 2018 Paulo Alcantara. All rights reserved.
# Licensed under GPLv2, see LICENSE

use strict;
use warnings;
use Getopt::Long;
use File::Copy;
use Cwd 'abs_path';
use File::Basename;
use Net::EmptyPort 'empty_port';

sub usage {
    print STDERR "Usage: " . basename($0). " [name] [options]

General options:
  --help                  print this help
  --new                   generate new config file
  --list                  list all vms
  --delete                delete vm
  --install image         create a new vm and install it from an ISO image
  --hdd=img0,img1,...     boot up a vm with additional hdd images
  --bridge                force creating a network bridge

Windows options:
  --win                   MS windows specifics (required)
  --virtio image          attach virtio drivers ISO image into Windows guest

Linux options:
  --initrd                pass initramfs image to kernel
  --kernel path           run the guest with a custom kernel image
                          (requires: --rootfs)
  --rootfs path           specify the rootfs that will get passed through the
                          kernel cmdline (requires: --kernel)
  --build                 build custom kernel before running guest
                          (requires: --kernel,--config)
  --config file           custom kernel config file
                          (requires: --kernel,--build)
  --modules               install kernel modules in rootfs image
                          (requires: --kernel,--rootfs,--build)
  --share=foo,bar,...     share directories between host and guest
  --nographic             disable graphics when running vm
                          (this overrides current settings)
  --gdb                   wait for gdb conn on a random TCP port
  --serial                enable kernel output on serial
                          (requires: --kernel,--rootfs)
  --cmdline=\"foo...\"      append extra cmdline params
                          (requires: --kernel,--rootfs)
  --ncpus num             number of vCPUs that will be used by the guest
";
    exit 1;
}

my %cmd_opts = ();

GetOptions("install=s" => \$cmd_opts{install_iso_path},
	   "virtio=s" => \$cmd_opts{virtio_drv_path},
	   "kernel=s" => \$cmd_opts{kernel_path},
	   "build" => \$cmd_opts{build_kernel},
	   "initrd" => \$cmd_opts{initrd_img},
	   "config=s" => \$cmd_opts{config_path},
	   "modules" => \$cmd_opts{install_modules},
	   "list" => \$cmd_opts{list_vms},
	   "delete" => \$cmd_opts{delete_vm},
	   "help" => \$cmd_opts{print_help},
	   "win" => \$cmd_opts{windows_guest},
	   "share=s" => \$cmd_opts{shared_dirs},
	   "new" => \$cmd_opts{gen_new_conf},
	   "hdd=s" => \$cmd_opts{vm_hdds},
	   "rootfs=s" => \$cmd_opts{rootfs_path},
	   "bridge" => \$cmd_opts{create_bridge},
	   "gdb" => \$cmd_opts{gdb_conn},
	   "serial" => \$cmd_opts{kernel_serial},
	   "cmdline=s" => \$cmd_opts{kernel_cmdline},
	   "ncpus=s" => \$cmd_opts{cpus_num},
	   "nographic" => \$cmd_opts{nographic}) or usage();

usage() if $cmd_opts{print_help};

my $vm_path = $ENV{'VMHELPER_VM_PATH'};
die "VMHELPER_VM_PATH env var is not set" unless $vm_path;
die "$vm_path does not exist" if ! -e $vm_path || ! -d $vm_path;

my $vm_info = $vm_path . '/.vminfo';
my $vm_conf = $vm_path . '/.vmconf';

my $vm_gdb_port = $cmd_opts{gdb_conn} ? 1234 : -1;

my $qemu_bin_path;
my $qemu_img_bin_path;

unless ($ENV{'VMHELPER_QEMU_BIN_PATH'}) {
    $qemu_bin_path = "/usr/bin/qemu-system-x86_64";
} else {
    $qemu_bin_path = $ENV{'VMHELPER_QEMU_BIN_PATH'};
}
unless ($ENV{'VMHELPER_QEMU_IMG_BIN_PATH'}) {
    $qemu_img_bin_path = "/usr/bin/qemu-img";
} else {
    $qemu_img_bin_path = $ENV{'VMHELPER_QEMU_IMG_BIN_PATH'};
}

sub parse_user_hdds {
    return '' unless $cmd_opts{vm_hdds};
    my $args = '';
    my $num = 1;
    my @hdds =  split(/,/, $cmd_opts{vm_hdds});
    foreach (@hdds) {
	my $id = sprintf "hd%02x", rand(256);
	$args .= " -device scsi-hd,drive=$id -drive if=none,file=$_,cache=writeback,id=$id,format=raw,unit=$num ";
	$num++;
    }
    return $args;
}

my %vm_conf_opts = (
    HOST_IFACE => 'eth0',
    BRIDGE_ENABLE => 'no',
    BRIDGE_IFACE => 'br0',
    BRIDGE_CFG_METHOD => 'auto',
    BRIDGE_IP_ADDR => '',
    BRIDGE_GW_ADDR => '',
    TAP_IP_ADDR => '192.168.0.1'
    );

sub in2opts {
    my $v = <STDIN>;
    chomp($v);
    if ($v) {
	$vm_conf_opts{$_[0]} = lc($v);
    }
}

sub gen_conf {
    open(my $f, ">", $vm_conf) or die "failed to create config file: $!";

    print "[*] generate initial config file\n";

    print "  host iface (default $vm_conf_opts{'HOST_IFACE'}): ";
    in2opts('HOST_IFACE');

    print "  enable bridging (default $vm_conf_opts{'BRIDGE_ENABLE'}): ";
    in2opts('BRIDGE_ENABLE');

    unless ($vm_conf_opts{'BRIDGE_ENABLE'} eq 'no') {
	print "  bridge iface (default $vm_conf_opts{'BRIDGE_IFACE'}): ";
	in2opts('BRIDGE_IFACE');

	print "  bridge ip method: (default auto) [auto|static]: ";
	in2opts('BRIDGE_CFG_METHOD');
	if ($vm_conf_opts{'BRIDGE_CFG_METHOD'} eq 'static') {
	    print "  bridge ip: ";
	    in2opts('BRIDGE_IP_ADDR');
	}

	print "  bridge gateway (default auto): ";
	in2opts('BRIDGE_GW_ADDR');
    } else {
	print "  tap ip addr (default $vm_conf_opts{'TAP_IP_ADDR'}): ";
	in2opts('TAP_IP_ADDR');
    }

    print $f "$_ = $vm_conf_opts{$_}\n" for (keys %vm_conf_opts);
    close($f) or die "failed to close config file: $!";

    print "[*] done\n";
};

sub parse_conf {
    open(my $f, "<", $vm_conf) or die "failed to open config file: $!";
    while (<$f>) {
	chomp;
	next if /^#.*$/ or /^\s+$/;
	my ($k, $v) = split /=/;
        $k =~ s/^\s+|\s+$//g;
	$v =~ s/^\s+|\s+$//g;
	next unless exists $vm_conf_opts{$k} or defined $vm_conf_opts{$k};
	$vm_conf_opts{$k} = $v;
    }
    close($f) or die "failed to close config file: $!";
}

if ($cmd_opts{gen_new_conf} || ! -e $vm_conf || ! -s $vm_conf) {
    gen_conf();
    exit 0;
}
parse_conf();

sub resolve_name {
    my $name = $_[0];

    open(my $hosts, "<", "/etc/hosts") or die "failed to open /etc/hosts: $!";
    while (<$hosts>) {
	next if ($_ =~ /^\s.*$/ || $_ =~ /^#.*$/);
	my ($ipaddr, @names) = split(/\s/);
	foreach (@names) {
	    if ($_ eq $name) {
		$ipaddr =~ s/^\s+|\s+$//g;
		close($hosts) or die "failed to close file: $!";
		return $ipaddr;
	    }
	}
    }
    close($hosts) or die "failed to close file: $!";
    return "<unknown>";
}

if ($cmd_opts{list_vms}) {
    exit 0 if ! -e $vm_info || ! -s $vm_info;

    open(my $conf, "<", $vm_info) or die "failed to open vm info file: $!";
    printf STDERR "%-25s%-20s%-15s\n", "name", "macaddr", "ipaddr";
    while (<$conf>) {
	my ($name, $macaddr) = split(/\s/);
	my $ipaddr = resolve_name($name);
	printf STDERR "%-25s%-20s%-20s\n", $name, $macaddr, $ipaddr;
    }
    close($conf) or die "failed to close file: $!";
    exit 0;
}

my $host_iface = $vm_conf_opts{'HOST_IFACE'};
my $bridge_iface = $vm_conf_opts{'BRIDGE_IFACE'};
my $tap_iface = '';
my $bridge_enabled = $vm_conf_opts{BRIDGE_ENABLE} eq 'yes' || $cmd_opts{create_bridge};

sub is_net_iface_created {
    my $iface = $_[0];

    open(my $dev, "<", "/proc/net/dev") or die "failed to open /proc/net/dev: $!";
    while (<$dev>) {
	next unless $_ =~ /:/;
	my ($s, $q) = split /:/;
	if ($s =~ /$iface/) {
	    close($dev) or die "failed to close file: $!";
	    return 1;
	}
    }
    close($dev) or die "failed to close file: $!";
    return 0;
}

sub create_bridge_dev {
    my ($host, $bridge) = @_;

    system("sudo //usr/sbin/brctl addbr $bridge");
    system("sudo /usr/sbin/brctl addif $bridge $host");

    # make traffic go through bridge iface only
    system("sudo /bin/ip addr flush dev $host");

    if ($bridge_enabled) {
	if ($vm_conf_opts{'BRIDGE_CFG_METHOD'} eq 'static') {
	    my $ipaddr = "$vm_conf_opts{'BRIDGE_IP_ADDR'}/24";

	    system("sudo /bin/ip addr add dev $bridge $ipaddr");
	} else {
	    system("sudo dhclient --no-pid $bridge");
	}

	my $gw = $vm_conf_opts{'BRIDGE_GW_ADDR'};
	if ($gw) {
	    system("sudo /bin/ip route delete default dev $bridge >/dev/null 2>&1");
	    system("sudo /bin/ip route add default via $gw dev $bridge");
	}
    } else {
	my $ipaddr = !$vm_conf_opts{'TAP_IP_ADDR'} ? "0.0.0.0/24" : "$vm_conf_opts{'TAP_IP_ADDR'}/24";
	system("sudo /bin/ip addr add dev $bridge $ipaddr");
    }

    system("sudo /bin/ip link set dev $bridge up");
}

sub destroy_tap_dev {
    system("sudo /bin/ip link delete $tap_iface") if $tap_iface;
}

sub create_tap_dev {
    my $iface = shift;
    die "no host iface specified" unless $iface;

    my $user = $ENV{'USER'};
    die "failed to determine username" unless $user;

    $tap_iface = `sudo /sbin/tunctl -u $user -b`;
    $tap_iface =~ s/^\s+|\s+$//g;
    my $ret;
    my $is_bridge_on_tap = $iface ne $host_iface;

    if (($bridge_enabled || $is_bridge_on_tap) &&
	system("sudo /usr/sbin/brctl addif $iface $tap_iface")) {
	$ret = $?;
	destroy_tap_dev();
	die "failed to create tap dev: $ret";
    }
    if (system("sudo /bin/ip link set dev $tap_iface up")) {
	$ret = $?;
	destroy_tap_dev();
	die "failed to create tap dev: $ret";
    }
}

my $tap_bridge_iface = 'vmhbr0';

sub setup_vm_net {
    if ($bridge_enabled) {
	create_bridge_dev($host_iface, $bridge_iface) unless is_net_iface_created($bridge_iface);
	create_tap_dev($bridge_iface);
	return;
    }
    #
    # create a bridge dev on tap so we don't have to assign an ip address for
    # every new tap dev.
    #
    unless (is_net_iface_created($tap_bridge_iface)) {
	create_tap_dev($host_iface);
	create_bridge_dev($tap_iface, $tap_bridge_iface);
    }
    create_tap_dev($tap_bridge_iface);
}

sub destroy_vm_net {
    destroy_tap_dev();
}

my %qemu_linux_opts = (
    mach => "-machine q35",
    cpu => $cmd_opts{cpus_num} ? "-enable-kvm -cpu host -smp $cmd_opts{cpus_num}" : "-enable-kvm -cpu host -smp sockets=1,cores=2,threads=2",
    mem => "-m 4096",
    bus => "-device qemu-xhci,id=xhci -device virtio-scsi-pci,id=scsi",
    hdd => " -device scsi-hd,drive=hd -drive if=none,file=%s,cache=writeback,id=hd,format=raw,unit=0",
    net => "-device e1000,netdev=net0,mac=%s -netdev type=tap,id=net0,ifname=%s,script=no,downscript=no",
    usb => "-device usb-tablet",
    cdrom => "-cdrom %s",
    kernel => "-kernel %s",
    initrd => "-initrd %s",
    share => '',
    mon => "-device virtio-serial-pci -monitor stdio",
    dbg => $vm_gdb_port != -1 ? "-gdb tcp::$vm_gdb_port" : ""
    );

my %qemu_win_opts = (
    mach => "-machine q35",
    cpu => $cmd_opts{cpus_num} ? "-enable-kvm -cpu host -smp $cmd_opts{cpus_num}" : "-enable-kvm -cpu host -smp sockets=1,cores=2,threads=2",
    mem => "-m 2048",
    bus => "-device ich9-ahci,id=ahci -device virtio-scsi-pci,id=scsi -device qemu-xhci,id=xhci",
    hdd => "-device scsi-hd,drive=hd,bootindex=0 -drive if=none,file=%s,cache=writeback,id=hd,format=raw,unit=0",
    cdrom => "-device scsi-cd,drive=cd,bootindex=1 -drive if=none,file=%s,format=raw,id=cd",
    virtio => "-device ide-cd,drive=drv,bus=ahci.0 -drive if=none,file=%s,format=raw,id=drv",
    usb => "-device usb-tablet",
    time => "-rtc base=localtime",
    net => "-device virtio-net-pci,netdev=net0,mac=%s -netdev type=tap,id=net0,ifname=%s,script=no,downscript=no",
    gfx => "-vga qxl",
    mon => "-device virtio-serial-pci -monitor stdio"
    );

my $default_img_size = "128G";

sub create_guest_img {
    my $img = $_[0];
    unless (-f $img) {
	my $cmd = "$qemu_img_bin_path create";
	$cmd .= " -f qcow2 -o compat=1.1 -o cluster_size=65536 -o preallocation=metadata -o lazy_refcounts=on ";
	$cmd .= $img . " $default_img_size";
	system("$cmd >/dev/null 2>&1") == 0 or die "failed to create vm image: $?";
    }
}

sub get_random_macaddr {
    return sprintf "52:54:00:%02x:%02x:%02x", rand(256), rand(256), rand(256);
}

sub rem_vm_info {
    my $name = $_[0];
    open(my $rconf, "+<", $vm_info) or die "failed to open vm info file: $!";
    my @lines = ();
    while (<$rconf>) {
	next if /^$name\s+.*$/;
	push @lines, $_;
    }
    close($rconf) or die "failed to close file: $!";
    open(my $wconf, ">", $vm_info) or die "failed to open vm info file: $!";
    print $wconf @lines;
    close($wconf) or die "failed to close file: $!";
}

sub save_vm_info {
    my ($name, $macaddr) = @_;

    my @lines = ();

    if (-e $vm_info) {
	open(my $rconf, "+<", $vm_info) or die "failed to open vm info file: $!";
	while (<$rconf>) {
	    next if /^$name\s+.*$/;
	    push @lines, $_;
	}
	close($rconf) or die "failed to close file: $!";
    }

    push @lines, "$name $macaddr\n";

    open(my $wconf, ">", $vm_info) or die "failed to open vm info file: $!";
    print $wconf @lines;
    close($wconf) or die "failed to close file: $!";
}

my $vm_name = $ARGV[-1];
usage() unless $vm_name;

my $vm_img_path = "$vm_path/$vm_name.img";

sub get_vm_macaddr {
    return '' if ! -e $vm_info || ! -s $vm_info;

    open(my $conf, "<", $vm_info) or die "failed to open vm info file: $!";
    my $ret = '';
    while (<$conf>) {
	chomp;
	next unless /^$vm_name\s+.*$/;
	my ($name, $macaddr) = split /\s+/;
	$ret = $macaddr;
	last;
    }
    close($conf) or die "failed to close file: $!";
    return $ret;
}

sub do_run_vm {
    my $cmd = shift;

    my $ipaddr = !$vm_conf_opts{'TAP_IP_ADDR'} ? "0.0.0.0" : "$vm_conf_opts{'TAP_IP_ADDR'}";

    print "[*]   name:          $vm_name\n";
    print "[*]   ipaddr:        " . resolve_name($vm_name) . "\n";
    print "[*]   macaddr:       " . get_vm_macaddr() . "\n";
    print "[*]   host iface:    " . ($bridge_enabled ? $bridge_iface : $tap_bridge_iface) . " ($ipaddr)\n";
    print "[*]   vm iface:      " . "$tap_iface\n";
    print "[*]   debug:         listening on localhost:$vm_gdb_port\n" if $vm_gdb_port != -1;
    print "[*]   cmd:           " . "$cmd\n";

    my $ret = system($cmd);
    print "\n[*] done\n" if !$ret;
    return $ret;
}

if ($cmd_opts{install_iso_path}) {
    create_guest_img($vm_img_path);

    setup_vm_net();

    my $macaddr = get_vm_macaddr();
    unless ($macaddr) {
	$macaddr = get_random_macaddr();
    }
    my $qemu_cmd = $qemu_bin_path;

    if ($cmd_opts{windows_guest}) {
	$qemu_cmd .= " $qemu_win_opts{'mach'} $qemu_win_opts{'cpu'}";
	$qemu_cmd .= " $qemu_win_opts{'mem'} $qemu_win_opts{'bus'}";
        $qemu_cmd .= " " . sprintf $qemu_win_opts{'hdd'}, $vm_img_path;

	my $user_hdds = parse_user_hdds();
	$qemu_cmd .= " $user_hdds" if $user_hdds;

	$qemu_cmd .= " " . sprintf $qemu_win_opts{'cdrom'}, $cmd_opts{install_iso_path};
	if ($cmd_opts{virtio_drv_path}) {
	    $qemu_cmd .= " " . sprintf $qemu_win_opts{'virtio'}, $cmd_opts{virtio_drv_path};
	}
	$qemu_cmd .= " " . sprintf $qemu_win_opts{'net'}, $macaddr, $tap_iface;
	$qemu_cmd .= " $qemu_win_opts{'time'} $qemu_win_opts{'usb'}" .
	    " $qemu_win_opts{'gfx'}";
	$qemu_cmd .= " $qemu_win_opts{'mon'}";
    } else {
	$qemu_cmd .= " $qemu_linux_opts{'mach'} $qemu_linux_opts{'cpu'}";
	$qemu_cmd .= " $qemu_linux_opts{'mem'} $qemu_linux_opts{'bus'}";
	$qemu_cmd .= " " . sprintf $qemu_linux_opts{'hdd'}, $vm_img_path;
	$qemu_cmd .= " " . sprintf $qemu_linux_opts{'cdrom'}, $cmd_opts{install_iso_path};
	$qemu_cmd .= " " . sprintf $qemu_linux_opts{'net'}, $macaddr, $tap_iface;
	$qemu_cmd .= " $qemu_linux_opts{'mon'}";
    }

    if (do_run_vm($qemu_cmd)) {
	destroy_vm_net();
	die "failed to exec cmd: $qemu_cmd";
    }

    save_vm_info($vm_name, $macaddr);
    destroy_vm_net();

    exit 0;
}

die "$vm_img_path does not exist" unless -f $vm_img_path;

if ($cmd_opts{delete_vm}) {
    unlink($vm_img_path) or die "failed to remove $vm_img_path: $!";
    rem_vm_info($vm_name);
    print "[*] successfully deleted $vm_name\n";
    exit 0;
}

if ($cmd_opts{windows_guest}) {
    setup_vm_net();

    my $macaddr = get_random_macaddr();
    my $qemu_cmd = $qemu_bin_path;

    $qemu_cmd .= " $qemu_win_opts{'mach'} $qemu_win_opts{'cpu'}";
    $qemu_cmd .= " $qemu_win_opts{'mem'} $qemu_win_opts{'bus'}";
    $qemu_cmd .= " " . sprintf $qemu_win_opts{'hdd'}, $vm_img_path;

    my $user_hdds = parse_user_hdds();
    $qemu_cmd .= $user_hdds if $user_hdds;

    if ($cmd_opts{virtio_drv_path}) {
	$qemu_cmd .= " " . sprintf $qemu_win_opts{'virtio'}, $cmd_opts{virtio_drv_path};
    }
    $qemu_cmd .= " " .
	sprintf $qemu_win_opts{'net'}, get_vm_macaddr(), $tap_iface;
    $qemu_cmd .= " $qemu_win_opts{'time'} $qemu_win_opts{'usb'}" .
	" $qemu_win_opts{'gfx'}";
    $qemu_cmd .= " $qemu_win_opts{'mon'}";

    if (do_run_vm($qemu_cmd)) {
	destroy_vm_net();
	die "failed to exec cmd: $qemu_cmd";
    }

    destroy_vm_net();
    exit 0;
}

my $rootfs_path = `mktemp -d`;
chomp($rootfs_path) if $rootfs_path;

sub mount_rootfs {
    die "$rootfs_path does not exist" if !$rootfs_path || ! -e $rootfs_path || ! -d $rootfs_path;
    system("guestmount -a $vm_img_path -m $cmd_opts{rootfs_path} $rootfs_path") == 0 or
	die "failed to mount rootfs: $?";
}

sub umount_rootfs {
    system("guestunmount $rootfs_path") == 0 or
	die "failed to umount rootfs: $?";
}

sub rem_shared_dirs() {
    return unless $cmd_opts{shared_dirs};
    return unless $cmd_opts{rootfs_path};

    mount_rootfs();

    open(my $rh, "<", "$rootfs_path/etc/fstab") or umount_rootfs() and
	die "failed to open file: $!";

    my @oldents = <$rh>;
    my @newents = ();
    foreach (@oldents) {
	next if /^__sharevh-.*$/;
	push @newents, $_;
    }

    close($rh) or umount_rootfs() and die "failed to close file: $!";

    open(my $wh, ">", "$rootfs_path/etc/fstab") or umount_rootfs() and
	die "failed to open file: $!";
    print $wh @newents;
    close($wh) or umount_rootfs() and die "failed to close file: $!";

    umount_rootfs();
}

sub setup_shared_dirs {
    return unless $cmd_opts{shared_dirs};
    return unless $cmd_opts{rootfs_path};

    my @dirs = split(/,/, $cmd_opts{shared_dirs});
    my $args = '';
    my $count = 0;
    my $arg = "-fsdev local,security_model=none,id=%s,path=%s -device virtio-9p-pci,id=%s,fsdev=%s,mount_tag=%s";

    mount_rootfs();

    open(my $rh, "<", "$rootfs_path/etc/fstab") or umount_rootfs() and
	die "failed to open file: $!";

    my @oldents = <$rh>;
    my @newents = ();
    foreach (@oldents) {
	next if /^__sharevh-.*$/;
	push @newents, $_;
    }

    close($rh) or umount_rootfs() and die "failed to close file: $!";

    foreach (@dirs) {
	my $path = abs_path($_);
	die "$_ does not exist" if ! -e $path || ! -d $path;
	my $tag = "__sharevh-" . sprintf "%d", rand(4096);

	mkdir("$rootfs_path/share/" . basename($path));

	push @newents, "$tag " . "/share/" . basename($path) .
	    " 9p noauto,x-systemd.automount,x-systemd.device-timeout=10," .
	    "timeo=14,x-systemd.idle-timeout=0,trans=virtio,version=9p2000.L," .
	    "posixacl,cache=mmap 0 0\n";

	$args .= sprintf $arg, "fsdev$count", $path, "fs$count", "fsdev$count", $tag . " ";
	$count++;
    }

    $qemu_linux_opts{'share'} = $args;

    open(my $wh, ">", "$rootfs_path/etc/fstab") or umount_rootfs() and
	die "failed to open file: $!";
    print $wh @newents;
    close($wh) or umount_rootfs() and die "failed to close file: $!";

    umount_rootfs();
}

my $qemu_cmd = $qemu_bin_path;

$qemu_cmd .= " $qemu_linux_opts{'mach'} $qemu_linux_opts{'cpu'}";
$qemu_cmd .= " $qemu_linux_opts{'mem'} $qemu_linux_opts{'bus'}";
$qemu_cmd .= " $qemu_linux_opts{'usb'}";
$qemu_cmd .= sprintf $qemu_linux_opts{'hdd'}, $vm_img_path;
$qemu_cmd .= " $qemu_linux_opts{'dbg'}";

my $user_hdds = parse_user_hdds();
$qemu_cmd .= $user_hdds if $user_hdds;

setup_shared_dirs();
$qemu_cmd .= $qemu_linux_opts{'share'};

setup_vm_net();
$qemu_cmd .= " " . sprintf $qemu_linux_opts{'net'}, get_vm_macaddr(), $tap_iface;

my $err;

if ($cmd_opts{kernel_path}) {
    unless ($cmd_opts{rootfs_path}) {
	$err = "rootfs has not been specified";
	goto OUT;
    }

    if (! -e $cmd_opts{kernel_path} || ! -d $cmd_opts{kernel_path}) {
	$err = "$cmd_opts{kernel_path} does not exist";
	goto OUT;
    }

    if ($cmd_opts{build_kernel}) {
	unless (chdir($cmd_opts{kernel_path})) {
	    $err = "failed to change dir: $!";
	    goto OUT;
	}

	if ($cmd_opts{config_path}) {
	    if (! -e $cmd_opts{config_path} || ! -d $cmd_opts{config_path}) {
		$err = "$cmd_opts{config_path} does not exist";
		goto OUT;
	    }
	    copy($cmd_opts{config_path}, "$cmd_opts{kernel_path}/.config") or
		die "failed to copy file: $!";
	    system("make oldconfig");
	}

	if (system('make -j$(getconf _NPROCESSORS_ONLN)')) {
	    $err = "failed to build kernel: $?";
	    goto OUT;
	}

	if ($cmd_opts{install_modules}) {
	    mount_rootfs();
	    if (system("make modules")) {
		$err = "failed to build kernel modules: $?";
		umount_rootfs();
		goto OUT;
	    }
	    system("INSTALL_MOD_PATH=$rootfs_path make modules_install");
	    umount_rootfs();
	}
	chdir();
    }

    my $linux_img = "$cmd_opts{kernel_path}/arch/x86/boot/bzImage";
    if (! -e $linux_img || ! -f $linux_img) {
	$err = "$linux_img does not exist";
	goto OUT;
    }

    $qemu_cmd .= " " . sprintf $qemu_linux_opts{'kernel'}, $linux_img;
    $qemu_cmd .= " -append \"root=$cmd_opts{rootfs_path} rw";
    $qemu_cmd .= " $cmd_opts{kernel_cmdline}" if $cmd_opts{kernel_cmdline};
    unless ($vm_gdb_port == -1) {
	print "[*] NOTE: turning off KASLR by appending 'nokaslr' to the kernel cmdline\n";
	$qemu_cmd .= " nokaslr";
    }
    unless ($cmd_opts{kernel_serial}) {
	$qemu_cmd .= "\" -display none $qemu_linux_opts{'mon'}";
    } else {
	$qemu_cmd .= " console=ttyS0\" -nographic";
    }
    if ($cmd_opts{initrd_img}) {
	if (! -e $cmd_opts{initrd_img} || ! -e $cmd_opts{initrd_img}) {
	    $err = "$cmd_opts{initrd_img} does not exist";
	    goto OUT;
	}
	$qemu_cmd .= " " . sprintf $qemu_linux_opts{'initrd'}, $cmd_opts{initrd_img};
    }
} else {
    $qemu_cmd .= " $qemu_linux_opts{'mon'}";
    $qemu_cmd .= " -display none" if $cmd_opts{nographic};
}

if (do_run_vm($qemu_cmd)) {
    $err = "failed to exec cmd: $qemu_cmd";
    goto OUT;
}

OUT:
rem_shared_dirs();
destroy_vm_net();

die "$err" if $err;
exit 0;