Debian Codegraph @

cgi-bin/qemu-web-desktop.pl

raw
1 #!/usr/bin/env perl
2
3 # Main qemu-web-desktop service script.
4 #
5 # You must edit the /etc/qemu-web-desktop/config.pl file or config.d/*.pl to configure the service.
6 # Think about editing the /usr/share/qemu-web-desktop/html/desktop/index.html
7 # to comment/un-comment sections (GPU, oneshot).
8 #
9 # When relevant, the equivalent OpenStack naming is indicated (as documented
10 # in https://docs.openstack.org/nova/latest/configuration/config.html)
11 #
12 # This script is triggered by a FORM or runs as a script.
13 # to test this script, launch from the project root level something like:
14 #
15 # cd remote-desktop
16 # perl cgi-bin/qemu-web-desktop.pl --dir_service=html/desktop \
17 # --dir_html=html --dir_snapshots=/tmp \
18 # --dir_machines=html/desktop/machines/ --oneshot=1
19 #
20 # Then follow printed instructions in the terminal:
21 # open a browser at something like:
22 # - http://localhost:38443/vnc.html?host=localhost&port=38443
23 #
24 # The script is effectively used in two steps (when executed as a CGI):
25 # - The HTML FORM launches the script as a CGI which starts the session.
26 # QEMU and VNC are initiated, the message is displayed, but does not wait for
27 # the end of the session.
28 #
29 # A running session with an attached JSON file can be stopped with:
30 #
31 # perl qemu-web-desktop.pl --session_stop=/path/to/json
32 #
33 # To stop and clear all running sessions use:
34 #
35 # perl qemu-web-desktop.pl --dir_snapshots=/tmp --service_purge=1
36 #
37 # To monitor all running sessions, use:
38 #
39 # perl cgi-bin/qemu-web-desktop.pl --service_monitor=1
40 #
41 #
42 # Requirements
43 # ============
44 # sudo apt install apache2 libapache2-mod-perl2
45 # sudo apt install qemu-system bridge-utils qemu iptables dnsmasq libguestfs-tools
46 # sudo apt install novnc websockify
47 #
48 # sudo apt install libsys-cpu-perl libsys-cpuload-perl libsys-meminfo-perl \
49 # libcgi-pm-perl liblist-moreutils-perl libnet-dns-perl libjson-perl \
50 # libproc-background-perl libproc-processtable-perl libemail-valid-perl \
51 # libnet-smtps-perl libmail-imapclient-perl libnet-ldap-perl libemail-valid-perl \
52 # libwww-perl liburi-perl libnet-ssh2-perl libtext-qrcode-perl
53 #
54 # (c) 2020- Emmanuel Farhi - GRADES - Synchrotron Soleil. AGPL3.
55 # https://gitlab.com/soleil-data-treatment/soleil-software-projects/qemu-web-desktop
56
57 # See 'support subroutines' below for in-line functions.
58
59 # ensure all fatals go to browser during debugging and set-up
60 # comment this BEGIN block out on production code for security
61 # BEGIN {
62 # $|=1;
63 # use CGI::Carp('fatalsToBrowser');
64 # }
65
66 # dependencies -----------------------------------------------------------------
67
68 use strict;
69 use warnings qw( all );
70
71 use CGI; # use CGI.pm
72 use Cwd 'abs_path'; # for abs_path
73 use Date::Parse; # to convert date/time
74 use File::Temp qw/ tempdir tempfile /;
75 use File::Path qw/ rmtree /;
76 use File::Basename qw/ fileparse dirname /;
77 use File::Copy qw/ copy/;
78 use File::Spec;
79 use List::MoreUtils qw(uniq); # liblist-moreutils-perl
80 use List::Util;
81 use IO::Socket::INET;
82 use IO::Socket::IP;
83 use JSON; # libjson-perl for JSON
84 use Proc::Background; # libproc-background-perl for Background->new
85 use Proc::ProcessTable; # libproc-processtable-perl
86 use Proc::Killfam; # libproc-processtable-perl for killfam (kill pid and children)
87 use Sys::MemInfo;
88
89 use Email::Valid; # libemail-valid-perl
90 use Mail::IMAPClient; # libmail-imapclient-perl for imap user check
91 use LWP::UserAgent; # libwww-perl for new and get(URL)
92 use Net::Ping; # perl to test server up-down
93 use Net::LDAP; # libnet-ldap-perl for ldap user check
94 use Net::SSH2; # libnet-ssh2-perl for local user check
95 use URI; # liburi-perl to split URL into parts
96
97 # Sys::CpuLoad libsys-cpuload-perl for CpuLoad::load
98 # Sys::CPU libsys-cpu-perl for CPU::cpu_count
99 # System::CPU for System::CPU::get_ncpu()
100 # Net::SMTPS; libnet-smtps-perl for smtp user check and emailing
101 # NOTE: we trap import errors (when not present)
102 BEGIN { eval { require Net::SMTPS; }; Net::SMTPS->import; }
103 BEGIN { eval { require Sys::CpuLoad; }; Sys::CpuLoad->import; }
104 BEGIN { eval { require Sys::CPU; }; Sys::CPU->import; }
105 BEGIN { eval { require System::CPU; }; System::CPU->import; }
106
107 # see http://honglus.blogspot.com/2010/08/resolving-perl-cgi-buffering-issue.html
108 $| = 1;
109 CGI->nph(1);
110
111 # use https://perl.apache.org/docs/2.0/api/Apache2/RequestIO.html
112 # for flush with CGI
113 my $r = shift;
114 if (not $r or not $r->can("rflush")) {
115 push @ARGV, $r; # put back into ARGV when not a RequestIO object
116 }
117
118 use constant IS_MOD_PERL => exists $ENV{'MOD_PERL'};
119 use constant IS_CGI => IS_MOD_PERL || exists $ENV{'GATEWAY_INTERFACE'} || exists $ENV{'REQUEST_METHOD'};
120
121 # ------------------------------------------------------------------------------
122 # service configuration: tune for your needs
123 # ------------------------------------------------------------------------------
124
125 # NOTE: This is where you can tune the default service configuration.
126 # Adapt the path, and default VM specifications.
127
128 # we use a Hash to store the configuration. This is simpler to pass to functions.
129 our %config;
130
131 $config{version} = "26.07.23"; # year.month.day
132
133 my $dirname = abs_path(dirname(__FILE__));
134
135 # Locations for configuration files
136 my @config_locations = (
137 "$dirname/../etc/config.pl",
138 "$dirname/../etc/config.d/*.pl",
139 '/etc/qemu-web-desktop/config.pl',
140 '/etc/qemu-web-desktop/config.d/*.pl',
141 '/opt/homebrew/etc/qemu-web-desktop/config.pl',
142 '/opt/homebrew/etc/qemu-web-desktop/config.d/*.pl',
143 );
144
145 my $config_found = 0;
146
147 # Search configuration file
148 foreach my $location (@config_locations) {
149 # Unique file
150 if (-e $location) {
151 require $location;
152 $config_found = 1;
153 } else {
154 # Files in config.d
155 my @files = glob ($location);
156 foreach my $file (@files) {
157 if (-e $file) {
158 require $file;
159 $config_found = 1;
160 }
161 }
162 }
163 }
164
165 unless ($config_found) {
166 die "$0: Can not find config.pl or any .pl file in config.d (e.g. /etc/qemu-web-desktop/config.pl or $dirname/../config.pl)";
167 }
168
169 # search detached GPU (via vfio-pci). Only use video part, no audio.
170 # WARNING: Not supported on MacOS
171 if ($^O ne 'darwin') {
172 # can be a VGA adaptor or a 'controller'
173 my ($device_pci1, $device_model1, $device_name1) = pci_devices("lspci -nnk","vga","vfio");
174 my ($device_pci2, $device_model2, $device_name2) = pci_devices("lspci -nnk","3d controller","vfio");
175
176 my @gpu_pci = (@$device_pci1, @$device_pci2);
177 my @gpu_model= (@$device_model1, @$device_model2);
178 my @gpu_name = (@$device_name1, @$device_name2);
179 $config{gpu_model} = \@gpu_model;
180 $config{gpu_name} = \@gpu_name;
181 $config{gpu_pci} = \@gpu_pci;
182 }
183
184 # ------------------------------------------------------------------------------
185 # update config with input arguments from the command line (when run as script)
186 # ------------------------------------------------------------------------------
187
188 # the 'service_monitor' can be set to true to generate a list of running sessions.
189 # each of these can display its configuration, and be stopped/cleaned.
190 $config{service_monitor} = 0;
191 $config{session_stop} = ""; # contains a json ref, stop service
192 $config{service_purge} = 0; # when true stop/clean all
193 $config{oneshot} = 0;
194
195 for(my $i = 0; $i < @ARGV; $i++) {
196 $_ = $ARGV[$i];
197 if(! $_) { next; }
198 if(/--help|-h$/) {
199 print STDERR "$0: launch a QEMU/KVM machine in a browser window. Version $config{version}\n\n";
200 print STDERR "Usage: $0 --option1=value1 ...\n\n";
201 print STDERR "Valid options are:\n";
202 foreach my $key (sort keys %config) {
203 print STDERR " --$key=VALUE [$config{$key}]\n";
204 }
205 print STDERR "\nTo manually start virtual machine in DIR_VM/VM :\n";
206 print STDERR "$0 --dir_machines=DIR_VM --machine=VM --dir_snapshots=/tmp --dir_cfg=/tmp --oneshot=1 --service_max_mem_fraction_nb_per_user=0.8 --service_max_cpu_fraction_nb_per_user=0.8 --snapshot_alloc_disk=30\n";
207 print STDERR "or use: 'qwdctl start VM'.\n";
208 exit;
209 } elsif (/--version|-v$/) {
210 print STDERR "$0 $config{version}\n\n";
211 print STDERR "Copyright (C) 2020- Synchrotron Soleil, AGPL3.\n";
212 print STDERR "This is free software; see the source for copying conditions. There is NO\n";
213 print STDERR "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n";
214 print STDERR "Written by Emmanuel Farhi <emmanuel.farhi\@synchrotron-soleil.fr>\n";
215 exit;
216 } elsif (/^--(\w+)=(\w+)$/) { # e.g. '--opt=value'
217 if (exists($config{$1})) {
218 $config{$1} = $2;
219 }
220 } elsif (/^--(\w+)=([a-zA-Z0-9_\ \"\.\-\:\~\\\/]+)$/) { # e.g. '--opt=file'
221 if (exists($config{$1})) {
222 $config{$1} = $2;
223 }
224 }
225 }
226
227 $config{session_nb} = 0;
228
229 if ($config{session_stop}) { # from ARGS (command line)
230 # wait for session to end, and clean files/PIDs.
231 my $session_ref = session_load(\%config, $config{session_stop});
232 if ($session_ref) {
233 session_stop($session_ref);
234 }
235 exit;
236 }
237
238 # for I/O, to generate HTML display and email content.
239 my $error = "";
240 my $output = "";
241 my $output_email= ""; # message sent via email when MFA and check via email
242
243 # Check running snapshots and clean any left over.
244 {
245 (my $err, my $nb) = service_housekeeping(\%config); # see below for private subroutines.
246 $error .= $err;
247 $config{session_nb} = $nb;
248 };
249
250
251 if ($config{certificate_crt} and -e $config{certificate_crt}
252 and $config{certificate_key} and -e $config{certificate_key}) {
253 $config{http} = "https"; # secured connection with certificates
254 } else { $config{http} = "http"; }
255
256
257 # ------------------------------------------------------------------------------
258 # Session variables: into a hash as well.
259 # ------------------------------------------------------------------------------
260
261 my %session;
262
263 # transfer defaults
264 $session{machine} = $config{machine};
265 # OpenStack DEFAULT.instance_name_template ?
266 $session{dir_snapshot}= tempdir(TEMPLATE => "$config{service}" . "_XXXXXXXX",
267 DIR => $config{dir_snapshots}) || die "$0: Can not create snapshot directory in $config{dir_snapshots}.";
268 $session{name} = File::Basename::fileparse($session{dir_snapshot});
269 $session{snapshot} = safe_path($session{dir_snapshot}, $config{service} . ".qcow2");
270 $session{json} = safe_path($config{dir_cfg}, $session{name} . ".json");
271 $session{output} = safe_path($session{dir_snapshot}, "index.html");
272 $session{qrcode} = "";
273
274 $session{user} = "";
275 $session{password} = "";
276 $session{persistent} = ""; # not persistent implies lower server load
277 $session{cpu} = int($config{snapshot_alloc_cpu}); # default: cores
278 $session{memory} = int($config{snapshot_alloc_mem}); # default: in GB
279 $session{disk} = int($config{snapshot_alloc_disk}); # default: only for ISO
280 $session{gpu} = ""; # indicates PCI GPU passthrough request when not empty
281 $session{snapshot_lifetime} = int($config{snapshot_lifetime}); # default [sec]
282 $session{oneshot} = $config{oneshot};
283
284 $session{user_email} = "";
285
286 $session{date} = localtime();
287 # see https://www.oreilly.com/library/view/perl-cookbook/1565922433/ch11s03.html#:~:text=To%20append%20a%20new%20value,values%20for%20the%20same%20key.
288 # on how to handle arrays in a hash.
289 # push new PID: push @{ $session{pid} }, 1234;
290 # get PIDs: my @pid = @{ $session{pid} };
291 $session{pid} = (); # we search all children in session_stop
292 # push @{ $session{pid} }, $$; # do NOT add our own PID = common Perl for all cgi's
293 $session{pid_wait} = $$; # PID to wait for (daemon).
294 $session{port} = $config{service_port}; # e.g. 6080 for websockify
295 $session{qemuvnc_ip} = "127.0.0.1"; # OpenStack vnc.server_listen vnc.proxyclient_address
296 # cast a random token key for VNC: 8 random chars in [a-z A-Z digits]
297 sub rndStr{ join'', @_[ map{ rand @_ } 1 .. shift ] };
298 $session{token_vnc} = rndStr (20, 'a'..'z', 'A'..'Z', 0..9);
299 $session{password_vnc}= rndStr (20, 'a'..'z', 'A'..'Z', 0..9);
300 $session{token_file} = "";
301 $session{runs_as_cgi} = IS_CGI;
302 $session{url} = "";
303
304 # auto: default QEMU executable
305 if ($config{qemu_exec} =~ /^(auto|host)$/) {
306 my $arch=`uname -m`;
307 if ($arch =~ 'x86_64') { $config{qemu_exec} = 'qemu-system-x86_64'; }
308 elsif ($arch =~ /(aarch64|arm64)/) { $config{qemu_exec} = 'qemu-system-aarch64'; }
309 else { die "$0: Can not determine qemu-system for architecture $arch. Set config{qemu_exec} in config.pl\n"; }
310 }
311 # auto: best QEMU options from host capabilities
312 if (not $error and $config{qemu_exec_options} =~ 'auto') {
313 $config{qemu_exec_options} =~ s/auto//;
314 my $accel=`$config{qemu_exec} -accel help`;
315 my $mach=`$config{qemu_exec} -M help`;
316
317 # test type of accelerator
318 # usual case on Intel/AMD and Apple/Silicon
319 if ($accel =~ "kvm") {
320 $config{qemu_exec_options} .= " -enable-kvm -cpu host";
321 if ($mach =~ "Standard PC") { $config{qemu_exec_options} .= ",kvm=off"; }
322 } elsif ($accel =~ "hvf") { $config{qemu_exec_options} .= " -accel hvf -cpu host"; }
323
324 # test type of target machine
325 if ($mach =~ "Standard PC") {
326 # usual case on Intel/AMD "PC"
327 $config{qemu_exec_options} .= " -M pc";
328 # test type of VGA (not on ARM)
329 my $mach_vga= `$config{qemu_exec} -M pc -vga help`;
330 if ($mach_vga =~ "virtio") { $config{qemu_exec_options} .= " -vga virtio"; }
331 elsif ($mach_vga =~ "qxl") { $config{qemu_exec_options} .= " -vga qxl"; }
332 else { $config{qemu_exec_options} .= " -device ramfb"; }
333 } elsif ($mach =~ "virt") {
334 # Other, e.g. ARM
335 $config{qemu_exec_options} .= " -M virt,iommu=smmuv3";
336 $config{qemu_exec_options} .= " -device ramfb";
337 }
338
339 # the device virtio-gpu is nice, but brings mouse pointer offset
340 # if (`$config{qemu_exec} -device help` =~ "virtio-gpu") {
341 # $config{qemu_exec_options} .= " -device virtio-gpu";
342 # }
343
344 # special case for ARM: require EFI boot
345 if (`uname -m` =~ /(aarch64|arm64)/) {
346 # search for EFI/ARM
347 my @EFIs=('/usr/share/qemu-efi-aarch64/QEMU_EFI.fd',
348 '/usr/share/qemu-efi/QEMU_EFI.fd',
349 '/usr/share/ovmf/AARCH64/QEMU_EFI.fd',
350 '/usr/share/edk2/arm/QEMU_EFI.fd',
351 '/opt/homebrew/share/qemu/edk2-aarch64-code.fd');
352 foreach my $EFI (@EFIs) {
353 if (-f $EFI) {
354 # Debian arm
355 # https://documentation.ubuntu.com/server/how-to/virtualisation/qemu/index.html
356 # https://wiki.debian.org/Arm64Qemu recommends to use the '-bios $EFI'
357 # Special case for Apple/Silicon
358 # https://ww2.coastal.edu/mmurphy2/oer/qemu/aarch64/
359 $config{qemu_exec_options} .= " -bios $EFI";
360 last;
361 }
362 }
363 }
364 } # end auto qemu options
365
366 # ------------------------------------------------------------------------------
367 # Update session info from CGI
368 # ------------------------------------------------------------------------------
369
370 $CGI::POST_MAX = 65535; # max size of POST message
371 my $q = new CGI; # create new CGI object "query"
372
373 if (my $res = $q->cgi_error()){
374 if ($res =~ /^413\b/o) { $error .= "Maximum data limit exceeded. \n"; }
375 else { $error .= "An unknown error has occured. \n"; }
376 }
377
378 $session{remote_host} = safe_path("",$q->remote_host()); # the 'client'
379 if ($session{remote_host} =~ "::1") {
380 $session{remote_host} = "localhost";
381 }
382 $session{server_name} = safe_path("",$q->server_name()); # the 'server' OpenStack DEFAULT.host
383 if ($session{server_name} =~ "::1") {
384 $session{server_name} = "localhost";
385 }
386 $config{server_name} = $session{server_name};
387
388 # check input arguments values (not 'password')
389 for ('machine','user','cpu','memory','gpu','snapshot_lifetime',
390 'session_stop','service_purge','session_extend','oneshot','fallback_servers') {
391 my $val = $q->param($_);
392 if (defined($val)) {
393 if ( $val =~ /^([a-zA-Z0-9_.\-@\: ]+)$/ ) {
394 # all is fine
395 $session{$_} = $val;
396 } else {
397 $error .= "$_ is not defined or contains invalid characters. \n";
398 }
399 }
400 }
401
402 # these are the "input" to collect from the HTML FORM. Store in $session
403 for ('password') {
404 my $val = $q->param($_);
405 if (defined($val)) {
406 $session{$_} = $val;
407 }
408 }
409
410 # we get the list of fallback servers to be used when current machine is over-subscribed.
411 # The POST message will be updated with a reduced fallback_servers list
412 # and sent via LWP::UserAgent -> post
413 if (not defined $session{fallback_servers} and defined $config{fallback_servers}) {
414 $session{fallback_servers} = $config{fallback_servers};
415 }
416 my $need_fallback_server = 0;
417
418
419 # check if the 'Manage button' was hit, instead of Create
420 if (defined $q->param('manage')) {
421 $session{machine} = 'monitor';
422 }
423
424 if (not $session{runs_as_cgi}) {
425 # not a CGI: running as detached script
426 print STDERR $0.": WARNING: Running as detached script. No token. NO AUTHENTICATION.\n";
427 $config{check_user_with_email} = 0;
428 $config{check_user_with_ldap} = 0;
429 $config{check_user_with_imap} = 0;
430 $config{check_user_with_smtp} = 0;
431 $session{password_vnc} = "";
432 }
433
434 # assemble welcome message -----------------------------------------------------
435 #
436 # NOTE on HTML generation: from here on, $output only accumulates BODY content
437 # (status list, tables, messages). The full HTML document (doctype, <head>,
438 # shared <style>, and closing tags) is assembled exactly once, on demand, by
439 # html_page_wrap($title, $body_html) -- see 'support subroutines' below.
440 # This avoids duplicating the page skeleton at every exit point (session
441 # stop/extend, admin monitor/purge, error path, normal success path).
442
443 my $ok = '<span class="badge ok">OK</span>';
444 my $title = "$config{service}: $session{machine}";
445
446 $output .= "<div class='card'>\n";
447
448 if (-f "$config{layout_header}") {
449 # use custom header as file
450 open FILE, "$config{layout_header}";
451 $output .= join "", <FILE>;
452 close FILE;
453 } elsif ("$config{layout_header}" ne "") {
454 # use custom header as string
455 $output .= "$config{layout_header}";
456 } else { # default header
457 $output .= <<END_HTML;
458 <a href="$config{http}://$session{server_name}/$config{service}/" target=_blank>
459 <img alt="DARTS" title="DARTS" class="logo"
460 src="$config{http}://$session{server_name}/$config{service}/images/darts_logo.png"></a>
461 END_HTML
462 }
463
464 # add title if missing
465 if ($output !~ m/<h1>/i) {
466 $output .= "<h1>$config{layout_title}";
467
468 if ($config{layout_level} >= 1) {
469 $output .= ": $session{machine}";
470 }
471 $output .= "</h1>";
472 }
473 $output .= "<ul class='status'>"; # status list. Card + list are closed further down.
474
475 if ($config{layout_level} >= 2) {
476 $output .= "<li>$ok Starting on $session{date}.</li>\n";
477 $output .= "<li>$ok You are accessing this service from $session{remote_host}.</li>\n";
478 }
479
480 # stop/purge session from FORM - authentication is not needed as it was checked via previous form
481 if ($session{session_stop}) {
482 # trigger session to end, and clean files/PIDs.
483 my $session_ref = session_load(\%config, $session{session_stop});
484 if ($session_ref) {
485 session_stop($session_ref);
486 my %session = %{ $session_ref };
487 $output .= "</ul></div>"; # close status card
488 $output .= "<div class='card'><p>$ok Stopped <b>$session{name} $session{machine}</b> that was started on [$session{date}] by "
489 . safe_path("","$session{user} $session{user_email}") . "</p></div>";
490 print "Content-type:text/html\r\n\r\n";
491 print html_page_wrap($title, $output);
492 }
493 exit;
494 }
495
496 # extend session from FORM - authentication is not needed as it was checked via previous form
497 if ($session{session_extend}) {
498 print STDERR $0.": Request session extension for $session{session_extend} +24h.\n";
499 # add +24h to session life-time.
500 my $session_ref = session_load(\%config, $session{session_extend});
501 if ($session_ref) {
502 session_extend($session_ref, 24*3600); # +24h
503 my %session = %{ $session_ref };
504 $output .= "</ul></div>"; # close status card
505 $output .= "<div class='card'><p>$ok Extend <b>$session{name} $session{machine}</b> started on [$session{date}] by "
506 . safe_path("","$session{user} $session{user_email}") . ": +24h</p></div>";
507 print "Content-type:text/html\r\n\r\n";
508 print html_page_wrap($title, $output);
509 }
510 exit;
511 }
512
513
514 # service monitoring requires user authentication
515 if ($session{machine} =~ 'monitor') {
516 $config{service_monitor} = 1;
517 }
518
519 if ($session{machine} =~ 'purge' or $session{service_purge}) {
520 $config{service_purge} = 1;
521 }
522
523 # handle 'admin' actions as well as stop/extend
524 if (not $error and ($config{service_monitor} or $config{service_purge} or $session{session_extend} or $session{session_stop})) {
525 (my $out, my $err) = session_authenticate(\%config, \%session);
526
527 if (not $err) { # must be identified
528 my $user = $session{user};
529 my @admin = @{ $config{user_admin} };
530 my $isadmin = 0;
531 $session{machine} = "administration";
532 if ($session{runs_as_cgi} and not grep( /^$user$/, @admin ) ) {
533 $isadmin = 0;
534 } else { $isadmin = 1; }
535
536 if ($config{service_monitor}) {
537 $output = service_monitor(\%config, $output, $isadmin, $user);
538 } elsif ($config{service_purge}) {
539 print STDERR $0." [$session{date}] Stopping all sessions.\n";
540 service_purge(\%config);
541 $output .= "</ul></div><div class='card'><h1>$ok Purged all</h1></div>";
542 }
543 }
544
545 if (not $err) {
546 # display...
547 print "Content-type:text/html\r\n\r\n";
548 print html_page_wrap($title, $output);
549 if (defined($r) and $r->can("rflush")) {
550 $r->rflush;
551 }
552 exit;
553 } else {
554 $error .= $err;
555 }
556 } # services
557
558
559 # ------------------------------------------------------------------------------
560 # Session checks: cpu, memory, disk, VM, config_script
561 # ------------------------------------------------------------------------------
562 $session{memory} = $session{memory}*1024; # GB -> MB
563
564 my $cpu_count = 0;
565 if ($cpu_count == 0) {eval { $cpu_count = Sys::CPU::cpu_count(); }}
566 if ($cpu_count == 0) {eval { $cpu_count = System::CPU::get_ncpu(); }}
567
568 if ($config{service_monitor} or $config{service_purge}) {
569 # admin actions must always be possible
570 } else {
571 if ($config{service_max_session_nb} and $config{session_nb} > $config{service_max_session_nb}) {
572 $error .= "Too many active sessions $config{session_nb}. Max $config{service_max_session_nb}. Try again later. \n";
573 $need_fallback_server = 1;
574 }
575 # ignore error when CpuLoad module is not installed (Arch)
576 eval {
577 if ($config{service_max_load} and $config{service_max_load} < 1 and $cpu_count and $cpu_count-Sys::CpuLoad::load() < $session{cpu}) {
578 $error .= "Not enough free CPU's (out of $cpu_count). Try again later. \n";
579 $need_fallback_server = 1;
580 }
581 if ($config{service_max_load} and $config{service_max_load} < 1 and $cpu_count and Sys::CpuLoad::load() / $cpu_count > $config{service_max_load}) {
582 $error .= "Server load exceeded. Try again later. \n";
583 $need_fallback_server = 1;
584 }
585 };
586 my ($total_memory_kb, $free_memory_kb, $avail_memory_kb) = get_freemem();
587 if ($config{service_max_mem_fraction_nb_per_user} and $config{service_max_mem_fraction_nb_per_user} < 1 and $config{qemu_exec_options} !~ 'hvf' and $avail_memory_kb and $avail_memory_kb / 1024 < $session{memory}) { # in MB
588 # The memory info is wrong on Mac OSX. Skip test in this case.
589 $error .= "Not enough free memory ($avail_memory_kb kB), request $session{memory} MB. Try again later. \n";
590 $need_fallback_server = 1;
591 }
592 if (not -e "$config{dir_machines}/$session{machine}") {
593 $error .= "Can not find virtual machine $session{machine}.\n";
594 }
595 (my $nb_session, my $nb_cpu, my $nb_mem, my $nb_gpu) = service_check_user_max(\%config, $session{user});
596 if ($config{service_max_session_nb_per_user} and $nb_session > $config{service_max_session_nb_per_user}) {
597 $error .= "Too many opened sessions ($nb_session) for user, max $config{service_max_session_nb_per_user}. Please use [Manage sessions] to clear or reconnect to some already active sessions. \n";
598 $need_fallback_server = 1;
599 }
600 if ($config{service_max_cpu_fraction_nb_per_user} and $config{service_max_cpu_fraction_nb_per_user} < 1 and $cpu_count and $nb_cpu/$cpu_count > $config{service_max_cpu_fraction_nb_per_user}) {
601 $error .= "Too many used CPUs ($nb_cpu) for user, max $config{service_max_cpu_fraction_nb_per_user} fraction. Please use [Manage sessions] to clear or reconnect to some already active sessions. \n";
602 $need_fallback_server = 1;
603 }
604 if ($config{service_max_mem_fraction_nb_per_user} and $config{service_max_mem_fraction_nb_per_user} < 1 and $avail_memory_kb and $nb_mem/($avail_memory_kb / 1024) > $config{service_max_mem_fraction_nb_per_user}) {
605 $error .= "Too much memory ($nb_mem / $avail_memory_kb) for user, max $config{service_max_mem_fraction_nb_per_user} fraction. Please use [Manage sessions] to clear or reconnect to some already active sessions. \n";
606 $need_fallback_server = 1;
607 }
608 if ($config{service_max_gpu_nb_per_user} and $nb_gpu > $config{service_max_gpu_nb_per_user}) {
609 $error .= "Too many GPU ($nb_gpu) for user, max ($config{service_max_gpu_nb_per_user}). \n";
610 $need_fallback_server = 1;
611 }
612 }
613
614 # find a free GPU when requested
615 if (defined($session{gpu}) and $session{gpu} =~ /yes|gpu|true|1/i) {
616 # look for detached GPU PCI, and check if it is used by a running session
617 $session{gpu} = "";
618 foreach my $pci (@{ $config{gpu_pci} }) {
619 if (not $session{gpu} and not session_use_gpu(\%config, $pci)) {
620 $session{gpu} = $pci; # this is what we need to pass to qemu
621 }
622 }
623 if ($session{gpu}) {
624 if ($config{layout_level} >= 2) {
625 $output .= "<li>$ok Assigned GPU at PCI $session{gpu}.</li>\n";
626 }
627 } else {
628 $error .= "Can not find a free GPU as requested. Try again without. \n";
629 $need_fallback_server = 1;
630 }
631 }
632
633 # check if the current server is oversubscribed and there are fallback servers
634 if ($need_fallback_server and length($session{fallback_servers})) {
635
636 # for loop: search a valid server separated with ','
637 my $host="";
638 my $fallback_server = "";
639 my %valid_hosts = map { $_ => 1 } split /,/, $config{fallback_servers};
640
641 for $host (split /,/, $session{fallback_servers}) {
642 # get server to try: test if $host is not empty and active
643 if ($valid_hosts{$host}) { # host must exist in the server config (to avoid injection)
644 my $p = Net::Ping->new();
645 my $url = URI->new($host);
646 my $h = $host;
647 if ($url->can("host")) { $h = $url->host; }
648 if (length($host) and $url and $p->ping($h, 0.1)) {
649 # server is active, remove it from the list of fallback_servers (replace with ' ')
650 $session{fallback_servers} =~ s/$host/ /ig;
651 if (not $url->scheme) {
652 # add protocol/scheme
653 $host = "$config{http}://$host";
654 }
655 if (not $url->path and IS_CGI) {
656 # add CGI path
657 $host .= $ENV{SCRIPT_NAME};
658 }
659 $fallback_server = $host;
660 last;
661 }
662 $p->close();
663 } else { $error .= "Invalid $host (not in server configuration). \n"; }
664 }
665 # end for. $host now contains the server to forward the POST to.
666
667 if ($fallback_server) {
668 # update the fallback_servers in the POST message
669 print STDERR "$0: Warning: $error\n";
670 print STDERR "$0: forwarding request to: $fallback_server\n";
671
672 $q->param( fallback_servers => $session{fallback_servers} );
673
674 # send POST message to $host server
675 # ignore SSL certificate failures (we trust our fallback servers)
676 my $ua = LWP::UserAgent->new(
677 ssl_opts => { SSL_verify_mode => 0, verify_hostname => 0});
678 # use a specific proxy, or system configuration (e.g. HTTP_PROXY env var)
679 if ($config{service_proxy}) {
680 $ua->proxy(['http', 'ftp', 'https'], $config{service_proxy});
681 } else { $ua->env_proxy; }
682
683 # forward POST with updated fallback_servers list
684 my %params; # hash to store CGI arguments from the form
685 foreach my $p ($q->param) {
686 $params{$p} = $q->param($p);
687 }
688
689 # send to fallback server
690 my $response = $ua->post($fallback_server, \%params);
691
692 # display message
693 # NOTE: this is a full HTML document already rendered by the fallback
694 # server itself, so it is passed through as-is (NOT re-wrapped with
695 # html_page_wrap, which would double the page skeleton).
696 if ($response->is_success) {
697 my $output = $response->as_string();
698 # must clean the message up to '<!DOCTYPE html'
699 my $doctype_index = index($output, '<!DOCTYPE html'); # start at 0
700 if ($doctype_index > -1) {
701 $output = substr($output, $doctype_index); # skip protocol info
702 }
703 print "Content-type:text/html\r\n\r\n";
704 print "$output\n\n";
705 $session{server_name} = $fallback_server;
706 session_save(\%session);
707
708 # exit
709 exit
710 } else {
711 print STDERR "$0: forward not succesful from $fallback_server:\n";
712 print STDERR $response->as_string();
713 }
714 } # else proceed with error message: no localhost cpu/mem/gpu resource left
715 } # fallback server handling (load levelling)
716
717 # ------------------------------------------------------------------------------
718 # User credentials checks, find communication ports
719 # ------------------------------------------------------------------------------
720 {
721 (my $out, my $err, my $session_ref) = session_authenticate(\%config, \%session);
722 $output .= $out;
723 $error .= $err;
724 %session = %{ $session_ref };
725 }
726
727 if (defined($session{oneshot}) and $session{oneshot} =~ /yes|oneshot|true|1/i) {
728 if ($config{layout_level} >= 2) {
729 $output .= "<li>$ok Using single login session (<b>one-shot</b> login).</li>\n";
730 }
731 $session{oneshot} = "yes";
732 $session{token_vnc}= "";
733 # must use one websockify per session
734 $config{service_port_multiple} = 1;
735 } else {
736 if ($config{layout_level} >= 2) {
737 $output .= "<li>$ok Using multiple login session (reconnect/share).</li>\n";
738 }
739 $session{oneshot} = "";
740 }
741
742 # find a free port for websockify/noVNC on server. This is what goes in the URL given to user.
743 if ($session{port} and $config{service_port_multiple}) {
744 # range [service_port service_port+service_max_session_nb]
745 my @port_list = List::Util::shuffle( $config{service_port} .. $config{service_port}+$config{service_max_session_nb}-1 );
746 foreach my $port (@port_list) {
747 my $socket = IO::Socket::INET->new(Proto => 'tcp',
748 LocalAddr => $session{qemuvnc_ip}, LocalPort => $port);
749 if ($socket) { # must have been created on server
750 $session{port} = $port;
751 $socket->close;
752 last;
753 }
754 }
755 } elsif (not $session{port}) {
756 # port=0: request random port (0) to system in range [0 65535]
757 my $socket = IO::Socket::INET->new(Proto => 'tcp', LocalAddr => $session{qemuvnc_ip});
758 $session{port} = $socket->sockport();
759 $socket->close;
760 }
761
762 my $port_vnc = undef;
763 # find another free VNC port at qemuvnc_ip (client). Random in 5900 range + max_nb
764 my @vnc_list = List::Util::shuffle(
765 $config{service_port_vnc} .. $config{service_port_vnc}+$config{service_max_session_nb}-1 );
766 for my $port (@vnc_list) {
767 my $socket = IO::Socket::IP->new(Proto => 'tcp',
768 PeerAddr => $session{qemuvnc_ip}, PeerPort => $port);
769 if (not $socket) { # must not exist yet on client
770 $port_vnc = $port;
771 last;
772 } else { $socket->close; }
773 }
774 if (not defined($port_vnc)) {
775 $error .= "Can not find a port for the display. \n";
776 }
777 $session{port_vnc} = $port_vnc;
778
779 # ==============================================================================
780 # DO the work
781 # ==============================================================================
782
783 # NOTES: must make sure all commands redirect STDOUT to /dev/null not to collide
784 # with HTML generation. We use Proc::Background to launch tasks.
785
786 # Create snapshot --------------------------------------------------------------
787 if (not $error) {
788
789 my $cmd = "";
790 my $res = "";
791
792 if ($session{machine} =~ /\.iso$/i) { # machine ends with .ISO
793 $cmd = `qemu-img create -f qcow2 '$session{snapshot}' '$session{disk}G' > /dev/null 2>&1`;
794 if ($config{layout_level} >= 2) {
795 $output .= "<li>$ok Will use ISO from ";
796 }
797 } else {
798 # qemu-img now requires to specify master "backing" file format with '-F FMT'
799 if ($config{snapshot_use_master} and -w "$config{dir_machines}/$session{machine}") {
800 # option to NOT use snapshot. Work on master when writable.
801 $session{snapshot} = "$config{dir_machines}/$session{machine}";
802 if ($config{layout_level} >= 2) {
803 $output .= "<li>$ok Using master (changes will be kept) ";
804 }
805 } else {
806 my $img_info = `qemu-img info '$config{dir_machines}/$session{machine}'`;
807 my @backing_format = $img_info =~ /file format:\s*([a-z0-9]+)/i;
808 my $F = $backing_format[0];
809 $res = `qemu-img create -F $F -b '$config{dir_machines}/$session{machine}' -f qcow2 '$session{snapshot}' > /dev/null 2>&1`;
810 if ($config{layout_level} >= 2) {
811 $output .= "<li>$ok Creating snapshot from ";
812 }
813 }
814 }
815 if ($config{layout_level} >= 2) {
816 $output .= "<a href='$config{http}://$session{server_name}/$config{service}/machines/$session{machine}' target=_blank>$session{machine}</a> as session $session{name}</li>\n";
817 }
818
819 # check for existence of cloned VM
820 sleep(1); # make sure the VM has been cloned
821 if (not $error and not -e $session{snapshot}) {
822 $error .= "Could not clone $session{machine} into snapshot. \n";
823 }
824 } # Create snapshot
825
826 # LAUNCH optional 'configuration' scripts (system wide, and user level)
827 my $qemu_options="";
828 {
829 my $virt_options="";
830 my $cmd_vc="";
831 my $cmd_qemu="";
832 if (not $error and $config{config_script}) {
833 if (!ref($config{config_script})) { # is string
834 ($cmd_vc, $cmd_qemu) = session_run_script(\%config, \%session, $config{config_script});
835 $qemu_options .= " $cmd_qemu";
836 $virt_options .= " $cmd_vc";
837 } else { # is ARRAY
838 foreach my $c (@{ $config{config_script} }) {
839 ($cmd_vc, $cmd_qemu) = session_run_script(\%config, \%session, $c);
840 $qemu_options .= " $cmd_qemu";
841 $virt_options .= " $cmd_vc";
842 }
843 }
844 }
845 if ($virt_options && $virt_options =~ /\S/) {
846 # execute virt-customize with the list of all scripts to execute, in order
847 # WARNING: NOT supported under macos
848 my $res = `virt-customize -a '$session{snapshot}' $virt_options`;
849 }
850 if ($qemu_options && $qemu_options =~ /\S/) {
851 if (rindex($qemu_options, "qemu:", 0) == 0) {
852 # set QEMU options
853 $qemu_options =~ s/qemu:/ /g; # replace by space
854 }
855 }
856 }
857
858 # LAUNCH CLONED VM -------------------------------------------------------------
859 my $proc_qemu = ""; # REQUIRED killed at END
860 if (not $error) {
861
862 # common options for QEMU
863 my $cmd = "$config{qemu_exec} -smp $session{cpu} "
864 . " -name $session{name}:$session{user}:$session{machine}"
865 . " $config{qemu_exec_options}"
866 . " -m $session{memory} -device virtio-balloon"
867 . " -hda $session{snapshot} -device ich9-ahci,id=ahci"
868 . " -netdev user,id=mynet0 -device virtio-net,netdev=mynet0 -usb"
869 . " -device qemu-xhci -device usb-kbd -device usb-tablet $qemu_options";
870
871 # add copy/paste support (not always functional)
872 $cmd .= " -chardev qemu-vdagent,id=ch1,name=vdagent,clipboard=on -device virtio-serial-pci"
873 . " -device virtserialport,chardev=ch1,id=ch1,name=com.redhat.spice.0";
874
875
876 # performance options: network
877 # see: https://elinux.org/images/3/3b/Kvm-network-performance.pdf
878 # should use virtio-net. e1000 is best among emulated devices
879 # -netdev user,id=mynet0 -device virtio-net,netdev=mynet0
880
881 # performance options: disk
882 # -device ich9-ahci,id=ahci
883
884 # performance options: memory
885 # -device virtio-balloon (allows to only assign what is used by guests)
886
887 # handle ISO boot
888 if ($session{machine} =~ /\.iso$/i) {
889 $cmd .= " -boot d -cdrom $config{dir_machines}/$session{machine}";
890 } else {
891 $cmd .= " -boot c";
892 }
893
894 # attach GPU on pre-assigned PCI
895 if ($session{gpu}) {
896 $cmd .= " -device vfio-pci,host=$session{gpu},multifunction=on";
897 }
898
899 # we add mounts using QEMU virt-9p, with tags 'host_<last_word>'
900 # see https://wiki.qemu.org/Documentation/9psetup
901 # mounts are activated in the guest with:
902 # mount -t 9p -o trans=virtio,access=client [mount tag] [mount point]
903 my @mounts = @{ $config{dir_mounts} };
904 for(my $i = 0; $i <= $#mounts; $i++) {
905 if (-d $mounts[$i]) { # mount must exist as a directory
906 my $tag = (split '/', $mounts[$i])[-1];
907 $cmd .= " -fsdev local,security_model=none,id=fsdev$i,path=$mounts[$i] -device virtio-9p-pci,id=fs$i,fsdev=fsdev$i,mount_tag=host_$tag";
908 }
909 }
910
911 # add QEMU internal VNC
912 my $port_vnc_5900=$port_vnc-5900;
913 $cmd .= " -vnc $session{qemuvnc_ip}:$port_vnc_5900";
914
915 my ($token_handle, $token_name) = tempfile(UNLINK => 1);
916 # request VNC token when using multiple ports or MFA
917 if ($session{password_vnc} and ($config{service_port_multiple} or $config{check_user_mfa})) {
918 # must avoid output to STDOUT, so redirect STDOUT to NULL.
919 # file created just for the launch, removed immediately.
920 # Any 'pipe' such as "echo 'change vnc password\n$token_vnc\n' | qemu ..." is shown in 'ps'.
921 # With a temp file and redirection, the token does not appear in the process list (ps).
922
923 print $token_handle "change vnc password\n$session{password_vnc}\n";
924 close($token_handle);
925 # redirect 'token' to QEMU monitor STDIN to set the VNC password
926 $cmd .= ",password=on -monitor stdio > /dev/null < $token_name";
927 } else {
928 $cmd .= ' > /dev/null';
929 }
930
931 # as stated in
932 # https://stackoverflow.com/questions/6024472/start-background-process-daemon-from-cgi-script
933 # it is probably better to use 'batch' to launch background tasks.
934 # system("at now <<< '$cmd'")
935 # $proc_qemu = system("echo '$cmd' | at now") || "";
936 $proc_qemu = Proc::Background->new($cmd);
937 if (not $proc_qemu or not $proc_qemu->pid) {
938 $error .= "Could not start QEMU/KVM for $session{machine}.\n";
939 } else {
940 print STDERR $0.": $session{name}: START: $cmd\n";
941 if ($config{layout_level} >= 2) {
942 $output .= "<li>$ok Started QEMU/KVM for $session{machine} with VNC.</li>\n";
943 }
944 push @{ $session{pid} }, $proc_qemu->pid;
945 }
946 sleep(1);
947 unlink($token_name);
948 } # LAUNCH CLONED VM
949
950 # LAUNCH NOVNC (do not wait for VNC to stop) -----------------------------------
951 my $proc_novnc = ""; # REQUIRED killed at END
952 # default is to use a single websockify instance (daemon)
953 my $dir_token = $config{dir_snapshots} . "/websockify-target.d";
954 if ($config{service_port_multiple}) {
955 # store the token in each snapshot
956 $dir_token = $session{dir_snapshot} . "/websockify-target.d";
957 }
958 if (not $error and not -e "$dir_token") {
959 if (not mkdir($dir_token), 0700) {
960 $error .= "Could not create directory for tokens. \n"
961 };
962 }
963
964 # push the token into websocket dir
965 if (not $error and $session{token_vnc}) {
966 $session{token_file} = "$dir_token/$session{token_vnc}";
967 open my $fh, ">", $session{token_file} or die "$0: FATAL: Cannot open $session{token_file}: $!";;
968 print $fh "$session{token_vnc}: $session{qemuvnc_ip}:$session{port_vnc}\n";
969 close $fh;
970 }
971
972 if (not $error) {
973 # we set a timeout for 1st connection, to make sure the session does not block
974 # resources. Also, by setting a log record to the snapshot, we can add the
975 # session name to the process command line. Used for parsing PIDs.
976 my $cmd = "$config{dir_websockify}" .
977 " --web $config{dir_novnc}";
978
979 if (not $config{service_port_multiple} and $session{token_file}) {
980 $cmd .= " -D" .
981 " --token-plugin=TokenFile" .
982 " --token-source=$dir_token";
983 }
984
985 if ($session{oneshot}) { $cmd .= " --run-once"; }
986
987 if ($config{certificate_crt} and -e $config{certificate_crt}) {
988 $cmd .= " --cert=$config{certificate_crt}";
989 }
990 if ($config{certificate_key} and -e $config{certificate_key}) {
991 $cmd .= " --key=$config{certificate_key}";
992 }
993
994 # extremely important: the websockify must run ONLY on localhost.
995 # The Apache server ensures the connection via the reverse proxy.
996 if ($config{service_reverse_proxy}) {
997 # websockify serves 127.0.0.1
998 $cmd .= " $session{qemuvnc_ip}:$session{port}";
999 } else {
1000 # websockify serves 0.0.0.0 (all)
1001 $cmd .= " $session{port}";
1002 }
1003 if ($config{service_port_multiple}) {
1004 $cmd .= " $session{qemuvnc_ip}:$session{port_vnc}";
1005 }
1006
1007 # $proc_novnc = system("echo '$cmd' | at now") || "";
1008 $proc_novnc = Proc::Background->new($cmd);
1009
1010 if ($config{service_port_multiple}) {
1011 if (not $proc_novnc or not $proc_novnc->pid) {
1012 $error .= "Could not start websockify/noVNC. \n";
1013 } else {
1014 # need to clear the multiple websockify calls
1015 push @{ $session{pid} }, $proc_novnc->pid;
1016 }
1017 }
1018 } # LAUNCH NOVNC
1019
1020 # store the PID to wait for. Depends on persistent state.
1021 if (not $error) {
1022 if ($proc_novnc and $proc_qemu) {
1023 if (not $session{oneshot}) {
1024 # qemu and session{name} alow to find the PID
1025 $session{pid_wait} = $proc_qemu->pid;
1026 } else {
1027 # $config{dir_novnc}/utils/websockify/run and $session{port}
1028 $session{pid_wait} = $proc_novnc->pid;
1029 }
1030 }
1031 # build the session URL
1032 my $append=$config{service_reverse_proxy}; # may be "" or ":port" or "/alias"
1033 if ($append eq "" or $config{service_port_multiple}) {
1034 $append=":$session{port}"; # default
1035 }
1036 # set resize='scale' or 'remote'
1037 my $resize='scale';
1038 if ($config{layout_resize}) { $resize=$config{layout_resize}; }
1039 if ($config{service_port_multiple}) {
1040 $session{url} = "$config{http}://$session{server_name}$append/vnc.html?resize=$resize&autoconnect=true&host=$session{server_name}&port=$session{port}";
1041 } else {
1042 # in case of an Apache2 port redirection, set configuration:
1043 # $config{service_port_multiple} = 0;
1044 # $config{service_reverse_proxy} = "/darts";
1045 $session{url} = "$config{http}://$session{server_name}$append/vnc.html?resize=$resize&autoconnect=true&path=?token=$session{token_vnc}";
1046 }
1047 }
1048
1049 # COMPLETE OUTPUT MESSAGE ------------------------------------------------------
1050 if (not $error) {
1051
1052 # save session info only when no error if found
1053 session_save(\%session);
1054
1055 if ($config{layout_level} >= 2) {
1056 $output .= "<li>$ok Connect to your machine at <a href=$session{url} target=_blank>$session{url}</a>.</li>\n";
1057 }
1058 if ($session{password_vnc} and $config{service_port_multiple}
1059 and $config{layout_level} >= 2) {
1060 # this is also displayed as an H2 tag below
1061 $output .= "<li><b>$ok Connection password (noVNC) is: $session{password_vnc}</b></li>\n";
1062 }
1063 if ($session{snapshot_lifetime}) {
1064 if ($config{layout_level} >= 1) {
1065 my $datestring = localtime(time()+$session{snapshot_lifetime});
1066 $output .= "<li>$ok You can use your session until <b>$datestring.</b></li>\n";
1067 }
1068 }
1069 $output .= "</ul></div>\n"; # close status card
1070
1071 # prepare some snippets
1072 my $output_token = ""; # security code if any
1073 my $output_share = ""; # how to share
1074 my $output_persistent = ""; # show reconnect info
1075 my $output_icon = ""; # QR code
1076
1077 if ($session{password_vnc} and ($config{service_port_multiple} or $config{check_user_mfa})) {
1078 $output_token = "<h2>Session password: $session{password_vnc}</h2>";
1079 }
1080 if (not $session{oneshot}) {
1081
1082 if ($config{layout_level} >= 1) {
1083 $output_share = "<button onClick=\"SelfCopy(this.id)\" id=\"$session{url} $session{password_vnc}\" class=\"btn copy\" title=\"Copy link to clipboard, share it with your colleagues.\">&#128279;&nbsp;Share</button>";
1084
1085 $output_persistent = "NOTES: <ul>" .
1086 "<li>You can close the browser and reconnect any time (within life-time) with the link above.</li>" .
1087 "<li>Select the <b><span style=\"color:green\">[Manage sessions]</span></b> item in the service login page to list, reconnect or abort your sessions.</li>" .
1088 "<li>You can collaborate in the same session with your colleagues. Just send them the link above.</li>";
1089 }
1090 } elsif ($config{layout_level} >= 1) {
1091 $output_persistent = "NOTES: <ul>";
1092 }
1093
1094 # Conditional import of Text::QRCode module when installed
1095 if ($config{layout_level} >= 1) {
1096 $output_icon = "<img alt='$session{machine}' title='$session{machine}'
1097 src='$config{http}://$session{server_name}/$config{service}/images/logo-system.png'
1098 align='center' border='1' height='128'>";
1099
1100 my $qr_enabled = eval
1101 {
1102 require Text::QRCode;
1103 Text::QRCode->import();
1104 1;
1105 };
1106
1107 if ($qr_enabled) {
1108 # https://metacpan.org/pod/Text::QRCode
1109 my $arrayref = Text::QRCode->new()->plot("$session{url}");
1110 $session{qrcode} = join "\n", map { join '', @$_ } @$arrayref;
1111
1112 # code from HTML::QRCode
1113 my $w = "<td style=\"border:0;margin:0;padding:0;width:3px;height:3px;background-color: white;\">";
1114 my $b = "<td style=\"border:0;margin:0;padding:0;width:3px;height:3px;background-color: black;\">";
1115
1116 $output_icon
1117 = '<table class="qrcode" style="margin:0;padding:0;border-width:0;border-spacing:0;">';
1118 $output_icon
1119 .= '<tr style="border:0;margin:0;padding:0;">'
1120 . join( '', map { $_ eq '*' ? $b : $w } @$_ ) . '</tr>'
1121 for (@$arrayref);
1122 $output_icon .= '</table>';
1123 }
1124 } # qr code
1125
1126 if ($config{layout_level} >= 1) {
1127 $output_persistent .= "<li>This session has been created on request, and is NOT kept. ".
1128 "Your work <b>must be saved elsewhere</b> " .
1129 "(e.g. mounted disk, sshfs/scp/sftp, Dropbox, OwnCloud...).</li></ul>";
1130 }
1131
1132 $output_email = $output;
1133
1134 # generate main text for the email/MFA, always with VNC token, no QR code (too big)
1135 $output_email .= session_message(\%config, \%session,
1136 "<h2>Session: $session{name}</h2><h2>Connect: $session{url}</h2>", "", $output_token, "");
1137 # generate main text for the user (skip VNC token when MFA is on)
1138 if ($config{check_user_mfa} && $session{user_email}) {
1139 $output_token = "<h2>The session password has been sent to $session{user_email}</h2>\n";
1140 }
1141 $output .= session_message(\%config, \%session,
1142 $output_icon, $output_share, $output_token, $output_persistent);
1143
1144
1145 } else {
1146 $output .= "</ul></div>\n"; # close status card
1147 $output .= "<div class='card'><h2><span class='badge err'>ERROR</span></h2>\n";
1148 $output .= "<p>$error</p></div>\n";
1149 }
1150
1151 # send message via email when possible
1152 if (($config{check_user_with_email} or $config{check_user_mfa}) and not $error) {
1153 # send the full output message (with URL and VNC token) - must be a
1154 # complete, standalone HTML document, since it goes out as an email body.
1155 if ($session{user_email}) {
1156 my $ret = session_email(\%config, \%session, html_page_wrap($title, $output_email));
1157 if ($ret) {
1158 print STDERR $0.": $session{name}: FAILED sending email to $session{user_email}: $ret\n";
1159 $error .= "FAILED sending email to $session{user_email}: $ret \n";
1160 }
1161 } else {
1162 $error .= "This service requires a valid email. \n"; # fall-back to display
1163 }
1164 }
1165
1166 if ($config{service_logfile} and ! -f $config{service_logfile}) {
1167 # create log file if not there yet
1168 if (open my $fh, ">", $config{service_logfile}) {
1169 print $fh "# $config{service} log file\n";
1170 close $fh;
1171 } else {
1172 print STDERR "$0: WARNING: No log file. Cannot open $config{service_logfile}: $!\n";
1173 $config{service_logfile} = "";
1174 }
1175
1176 }
1177
1178 # write an HTML file to store the message output
1179 # display the output message (redirect) ----------------------------------------
1180 if (not $error) {
1181 open my $fh, ">", $session{output} or die "$0: FATAL: Cannot open $session{output}: $!\n";
1182 print $fh html_page_wrap($title, $output);
1183 close $fh;
1184
1185 print STDERR $0.": $session{name}: START $session{machine} on $session{date}\n";
1186 print STDERR $0.": $session{name}: USER: $session{user} $session{user_email}\n";
1187 # print STDERR $0.": $session{name}: json: $session{json}\n";
1188 print STDERR $0.": $session{name}: GPU: $session{gpu}\n" if ($session{gpu});
1189 # print STDERR $0.": $session{name}: PIDs: @{$session{pid}}\n" if ($session{pid});
1190 print STDERR $0.": $session{name}: URL: $session{url}\n";
1191
1192 if ($config{service_logfile}) {
1193 if (open my $fh, ">>", $config{service_logfile}) {
1194 print $fh "[$session{date}] START CPU=$session{cpu} MEM=$session{memory} GPU=$session{gpu} USER=$session{user} VM=$session{machine} NAME=$session{name}\n";
1195 close $fh;
1196 }
1197 }
1198 } else {
1199 print STDERR $0.": $session{name}: $session{date}: ERROR $error\n";
1200 if ($config{service_logfile}) {
1201 if (open my $fh, ">>", $config{service_logfile}) {
1202 print $fh "[$session{date}] ERROR CPU=$session{cpu} MEM=$session{memory} GPU=$session{gpu} USER=$session{user} VM=$session{machine} $error\n";
1203 close $fh;
1204 }
1205 }
1206 }
1207 if ($session{runs_as_cgi}) {
1208 # CGI redirect works, but requires that the temporary file be accessible
1209 # my $redirect="http://$session{server_name}/qemu-web-desktop/snapshots/$session{name}.html";
1210 # print $q->redirect($redirect); # this works (does not wait for script to end before redirecting)
1211
1212 if (not $error) { sleep($config{boot_delay}); } # make sure the display comes in.
1213
1214 print "Content-type:text/html;\r\n\r\n";
1215 print html_page_wrap($title, $output);
1216
1217 # the 1st argument of CGI is an Apache RequestIO
1218 if (defined($r) and $r->can("rflush")) {
1219 $r->rflush;
1220 }
1221 }
1222
1223 # wait for end of processes.
1224 if (not $error and $proc_novnc and $proc_qemu and $session{oneshot}) {
1225 $proc_novnc->wait;
1226 session_stop(\%session);
1227 }
1228
1229 exit; # end main
1230
1231 # ==============================================================================
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259 # ==============================================================================
1260 # support subroutines
1261 #
1262 # sub html_page_wrap
1263 # sub session_save
1264 # sub session_load
1265 # sub session_stop
1266 # sub session_extend
1267 # sub session_test_script
1268 # sub session_run_script
1269 # sub service_housekeeping
1270 # sub service_monitor
1271 # sub service_purge
1272 # sub session_email
1273 # sub session_message
1274 # sub service_check_user_max
1275 # sub session_authenticate
1276 # sub session_check_smtp
1277 # sub session_check_imap
1278 # sub session_check_ldap
1279 # sub session_check_local
1280 # sub session_check_custom
1281 # sub session_use_gpu
1282 # sub flatten
1283 # sub proc_getchildren
1284 # sub proc_running
1285 # sub pci_devices
1286 # sub get_freemem
1287 # sub safe_path
1288
1289 # ==============================================================================
1290
1291 # html_page_wrap($title, $body_html): wrap a body fragment into a complete,
1292 # standalone HTML document (doctype, head, shared style, body, closing tags).
1293 # This is the ONLY place the page skeleton and CSS are defined, so every
1294 # exit point in the script (session create/stop/extend, admin monitor/purge,
1295 # error display, email body, saved snapshot index.html) renders identically
1296 # and consistently, without duplicating markup.
1297 # $body_html is expected to be body-only content (no <html>/<head>/<body> tags).
1298 # return: $html (complete document, string)
1299 sub html_page_wrap {
1300 my $title = shift;
1301 my $body_html = shift;
1302
1303 $title = "" if not defined $title;
1304 $body_html = "" if not defined $body_html;
1305
1306 my $html = <<END_HTML;
1307 <!DOCTYPE html>
1308 <html lang="en">
1309 <head>
1310 <meta charset="utf-8">
1311 <meta name="viewport" content="width=device-width, initial-scale=1">
1312 <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-src 'self';">
1313 <meta http-equiv="X-Content-Type-Options" content="nosniff">
1314 <meta http-equiv="X-Frame-Options" content="DENY">
1315 <meta http-equiv="X-XSS-Protection" content="1; mode=block">
1316 <title>$title</title>
1317 <style>
1318 :root{
1319 --bg:#f4f6f8; --card:#ffffff; --border:#d9e0e6;
1320 --text:#1f2933; --muted:#6b7785;
1321 --ok:#1b8a3d; --warn:#b8860b; --err:#c0392b;
1322 --accent:#2563eb;
1323 }
1324 *{box-sizing:border-box}
1325 body{
1326 margin:0; padding:24px; background:var(--bg);
1327 font-family:-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;
1328 color:var(--text); line-height:1.5;
1329 }
1330 .wrap{max-width:900px; margin:0 auto}
1331 .card{
1332 background:var(--card); border:1px solid var(--border);
1333 border-radius:10px; padding:20px 24px; margin-bottom:18px;
1334 box-shadow:0 1px 3px rgba(0,0,0,.05);
1335 }
1336 .card h1{font-size:1.4rem; margin:0 0 4px 0}
1337 .card h2{font-size:1.1rem; margin:0 0 10px 0}
1338 .logo{float:right; height:64px; width:auto; border-radius:6px}
1339 .badge{
1340 display:inline-block; padding:2px 9px; border-radius:12px;
1341 font-size:.8rem; font-weight:600; color:#fff;
1342 }
1343 .badge.ok{background:var(--ok)}
1344 .badge.warn{background:var(--warn)}
1345 .badge.err{background:var(--err)}
1346 ul.status{list-style:none; margin:0; padding:0}
1347 ul.status li{padding:4px 0; border-bottom:1px dashed var(--border)}
1348 ul.status li:last-child{border-bottom:none}
1349 table{width:100%; border-collapse:collapse; margin-top:8px; font-size:.92rem}
1350 th, td{padding:8px 10px; border:1px solid var(--border); text-align:left; vertical-align:middle}
1351 th{background:#eef1f4; font-weight:600}
1352 tr:hover td{background:#fbfbe8}
1353 table.qrcode{width:auto; margin:0 auto; border-collapse:collapse}
1354 table.qrcode td{padding:0; border:0}
1355 input:hover{background-color:lightgreen; color:black}
1356 select:hover{background-color:lightgreen}
1357 .btn{
1358 display:inline-block; padding:6px 14px; border-radius:6px;
1359 background:var(--accent); color:#fff !important; text-decoration:none;
1360 font-weight:600; font-size:.9rem; font-family:inherit; border:none; cursor:pointer;
1361 line-height:1.4;
1362 }
1363 .btn.connect{background:var(--ok)}
1364 .btn.stop{background:var(--err)}
1365 .btn.copy{background:#fff; color:var(--accent) !important; border:1px solid var(--accent)}
1366 .footer{color:var(--muted); font-size:.85rem; text-align:center; margin-top:20px}
1367 </style>
1368 </head>
1369 <body>
1370 <div class="wrap">
1371 $body_html
1372 </div>
1373 <script>
1374 function SelfCopy(copyText)
1375 {
1376 navigator.clipboard.writeText(copyText);
1377 alert("Copied to clipboard for sharing: " + copyText);
1378 }
1379 </script>
1380 </body>
1381 </html>
1382 END_HTML
1383
1384 return $html;
1385 } # html_page_wrap
1386
1387 # session_save(\%session): save session hash into a JSON.
1388 sub session_save {
1389 my $session_ref = shift;
1390
1391 if (not $session_ref) { return; }
1392 my %session = %{ $session_ref };
1393
1394 # Remove sensitive data before saving
1395 my %safe_session = %session;
1396 delete $safe_session{password};
1397 delete $safe_session{token_vnc};
1398
1399 # Set restrictive permissions
1400 umask(0077);
1401 open my $fh, ">", $session{json} or die "$0: Cannot write $session{json}: $!";
1402 print $fh JSON::encode_json(\%safe_session);
1403 close $fh;
1404 chmod(0600, $session{json}); # Owner read/write only
1405 } # session_save
1406
1407 # $session = session_load(\%config, $file): load session hash from JSON.
1408 # return $session reference
1409 sub session_load {
1410 my $config_ref = shift;
1411 my $file = shift;
1412
1413 if (not $config_ref or not $file) { return undef; }
1414 my %config = %{ $config_ref };
1415
1416 # we test if the given ref is partial (just session name)
1417 if (not -e $file) {
1418 if (-e "$config{dir_cfg}/$file" or -e "$config{dir_cfg}/$file.json") {
1419 $file = "$config{dir_cfg}/$file";
1420 }
1421 if (-e "$file.json") {
1422 $file = "$file.json";
1423 }
1424 }
1425 if (not -e $file) { return undef; }
1426
1427 open my $fh, "<", $file or return undef; # "$0: Cannot read $file: $!";
1428 my $json = <$fh>;
1429 close $fh;
1430 my $session = decode_json($json);
1431 return $session;
1432 } # session_load
1433
1434 # session_stop(\%session): stop given session, and remove files.
1435 sub session_stop {
1436 my $session_ref = shift;
1437 if (not $session_ref) { return; }
1438
1439 my %session = %{ $session_ref };
1440
1441 # remove directory and JSON config
1442 if ($session{dir_snapshot} and -e $session{dir_snapshot})
1443 { rmtree($session{dir_snapshot}); }
1444 if ($session{json} and -e $session{json})
1445 { unlink($session{json}); }
1446 if ($session{output} and -e $session{output})
1447 { unlink($session{output}); }
1448 if ($session{token_file} and -e $session{token_file})
1449 { unlink($session{token_file}); }
1450 if ($session{qrcode} and -e $session{qrcode})
1451 { unlink($session{qrcode}); }
1452
1453 my $now = localtime();
1454 if ($session{remote_host}) {
1455 print STDERR $0." [$now] STOP $session{name} $session{machine} started on [$session{date}] for $session{user}\@$session{remote_host} $session{user_email}\n";
1456 }
1457
1458 # make sure QEMU/noVNC and asssigned SHELLs are killed
1459 # sometimes, PID's can change (more forks e.g. by websocket)
1460 if ($session{pid}) {
1461 my @pids = reverse uniq sort @{ $session{pid} };
1462 print STDERR $0." [$now] Kill @pids\n";
1463 map {
1464 my @all = flatten(proc_getchildren($_)); # get all children from that PID
1465 killfam('KILL', reverse uniq sort @all); # by reverse creation date/PID
1466 } reverse uniq sort @pids;
1467 }
1468 if ($config{service_logfile}) {
1469 if (open my $fh, ">>", $config{service_logfile}) {
1470 print $fh "[$now] STOP CPU=$session{cpu} MEM=$session{memory} GPU=$session{gpu} USER=$session{user} VM=$session{machine} NAME=$session{name}\n";
1471 close $fh;
1472 }
1473 }
1474
1475 } # session_stop
1476
1477 # $session = session_extend(\%session, $extension): sextend session life-time
1478 sub session_extend {
1479 my $session_ref = shift;
1480 my $time_extension = shift;
1481 if (not $session_ref) { return; }
1482
1483 my %session = %{ $session_ref };
1484
1485 # extend snapshot_lifetime when it does not exceed $config{snapshot_lifetime}
1486 if ($session{snapshot_lifetime}
1487 and ($session{snapshot_lifetime} < $config{snapshot_lifetime}) ) {
1488 print STDERR $0." [$session{date}] Extend session $session{name} by $time_extension s.\n";
1489 $session{snapshot_lifetime} = $session{snapshot_lifetime} + $time_extension;
1490 # save new config
1491 session_save(\%session);
1492 }
1493
1494 } # session_extend
1495
1496 # (TF, $content) = session_test_script(\%session, content)
1497 # Test the script '$content' after replacing symbols
1498 # The test expression must be found with syntax 'if(exp):'. It is extracted,
1499 # removed from the $content (which is returned after removal). Then it is
1500 # evaluated, and its result is placed in TF (returned). False is returned
1501 # when the test can not be evaluated (fails).
1502 # return (TF, $content)
1503 sub session_test_script {
1504 my $session_ref = shift;
1505 my $content = shift;
1506 my $TF = 0;
1507
1508 if (not $session_ref) { return (0,$content); }
1509 if (not $content) { return (0,$content); }
1510
1511 my %session = %{ $session_ref };
1512
1513 # replace @symbols@ (globally)
1514 $content=~s/\@USER\@/$session{user}/g;
1515 $content=~s/\@SESSION_NAME\@/$session{name}/g;
1516 $content=~s/\@VM\@/$session{machine}/g;
1517 $content=~s/\@PW\@/$session{password}/g;
1518
1519 # trim
1520 $content =~ s/^\s+|\s+$//g ;
1521
1522 # now search for the expression "if(EXPR):". Get 1st match.
1523 if ($content =~ m/if\((.*)\):/) {
1524 my $test = $1;
1525 $content =~ s/if\((.*)\)://; # remove match
1526 $content =~ s/^\s+|\s+$//g ; # trim again
1527 # evaluate the EXPR in test.
1528 $TF = eval $test;
1529 if ($@) { $TF = 0; } # error -> fails
1530 return ($TF,$content);
1531 } else {
1532 # no match: use content as is.
1533 return (1, $content);
1534 }
1535
1536 } # session_test_script
1537
1538 # session_run_script(\%config, \%session, $script): install a script for boot in VM
1539 # The script can be specifyed as:
1540 # "http://some/url"
1541 # "/some/local/path/to/script"
1542 # "exec: some commands" separated by EOL (\n) or ';'
1543 # "virt-customize: commands" separated by EOL (\n)
1544 # "qemu: QEMU options" separated by spaces
1545 #
1546 # In addition, the script text (expression, file or URL) may contain the syntax:
1547 # if(EXPR):
1548 # so that the script content is evaluated when EXPR is true.
1549 # The script content and EXPR may use the @USER@ @PW@ @SESSION_NAME@ and @VM@ symbols,
1550 # which are replaced by the user name, the session name and the VM name.
1551 #
1552 # The returned value is ($virt_customize_cmd, $qemu_cmd)
1553 sub session_run_script {
1554 my $config_ref = shift;
1555 my $session_ref = shift;
1556 my $script = shift;
1557
1558 my $virt_customize_cmd = "";
1559 my $qemu_cmd = "";
1560
1561 if (not $session_ref) { return ("",""); }
1562 if (not $config_ref) { return ("",""); }
1563 my %config = %{ $config_ref };
1564 my %session = %{ $session_ref };
1565
1566 if (length($script) > $config{service_max_script_length} || not $script) {
1567 return ("","");
1568 }
1569 my $TF=0;
1570 ($TF,$script) = session_test_script(\%session, $script); # handle any 'if(EXPR)' statement
1571 if (not $TF) { return ("",""); }
1572
1573 my $content = undef;
1574 my $virt_customize_commands = 0;
1575
1576 # add 'file://' for local file
1577 if (rindex($script, "bash:", 0) == 0 or rindex($script, "exec:", 0) == 0) {
1578 $content = substr($script, 5);
1579 }
1580 elsif (rindex($script, "virt-customize:", 0) == 0) {
1581 $content = substr($script, 15);
1582 $virt_customize_commands = 1;
1583 }
1584 elsif (-e "$script") {
1585 $script = "file://".$script;
1586 }
1587 elsif (rindex($script, "qemu:", 0) == 0) {
1588 return ("", $script);
1589 }
1590
1591 # get script from $script URL
1592 # we try a few times to get the content. A single attempt is often not enough.
1593 if (not defined ($content) or not $content) {
1594 for (1..5) {
1595 my $ua = LWP::UserAgent->new(timeout => 2);
1596 # use a specific proxy, or system configuration (e.g. HTTP_PROXY env var)
1597 if ($config{service_proxy}) {
1598 $ua->proxy(['http', 'ftp', 'https'], $config{service_proxy});
1599 } else { $ua->env_proxy; }
1600 my $response = $ua->get($script);
1601 if (not $response->is_error) {
1602 $content = $response->content;
1603 last;
1604 }
1605 }
1606 }
1607
1608 if (defined ($content) and length($content)) {
1609 # remove invalid characters
1610 $content=~s/[^\x00-\x7f]//g;
1611 if (length($content) < $config{service_max_script_length}) {
1612
1613 # replace symbols. Script is known to be active from previous call to session_test_script
1614 ($TF, $content) = session_test_script(\%session, $content);
1615
1616 # store script in our 'snapshot' directory for local exec.
1617 my ($script_handle, $script_name) = tempfile(TEMPLATE => "$session{dir_snapshot}/configuration_script_XXXXXXXX");
1618 if (not $script_name) { return ("",""); }
1619 print $script_handle "$content\n";
1620 close $script_handle;
1621
1622 # output script into apache2/log
1623 print STDERR $0.": $session{name}: $session{date}: $session{user} uses config_script=$script -> $script_name\n";
1624 # print STDERR "$content\n";
1625
1626 # call virt-customize: start VM, execute script, stop it. Only runs on stopped VMs.
1627 # virt-customize -a vm.qcow2 --run snapshot/script
1628 # my $cmd = "virt-customize -a $session{snapshot} ";
1629 my $cmd= "";
1630 if ($virt_customize_commands == 0) {
1631 $cmd = " --firstboot $script_name";
1632 } else {
1633 $cmd = " --commands-from-file $script_name";
1634 }
1635 return ($cmd, "");
1636 }
1637 }
1638 } # session_run_script
1639
1640 # service_housekeeping(\%config): scan 'snapshot' and 'cfg' directories.
1641 # - kill over-time sessions
1642 # - check that 'snapshots' have a 'cfg'.
1643 # - remove orphan 'snapshots' (may be left from a hard reboot).
1644 # return ($error,$nb) string (or empty when all is OK) and number of sessions.
1645 sub service_housekeeping {
1646 my $config_ref = shift;
1647
1648 if (not $config_ref) { return; }
1649 my %config = %{ $config_ref };
1650
1651 my $dir = $config{dir_snapshots};
1652 my $cfg = $config{dir_cfg};
1653 my $service = $config{service};
1654
1655 # clean:
1656 # - remove orphan snapshots (no corresponding JSON file)
1657 # - remove orphan JSON (no corresponding snapshots)
1658 # - remove snapshots that have gone above their lifetime
1659 my $now = localtime();
1660 foreach my $snapshot (glob("$dir/$service"."_*")) {
1661
1662 if (-d $snapshot && time - (stat($snapshot))[9] > 10*$config{boot_delay}) { # is a snapshot directory
1663 my $snaphot_name = fileparse($snapshot); # just the session name
1664
1665 if (not -e "$cfg/$snaphot_name.json") {
1666 # remove orphan $snapshot (no JSON)
1667 print STDERR $0." [$now] housekeeping: $snapshot (left-over, no JSON - internal command)\n";
1668 rmtree( $snapshot ) || print STDERR $0." [$now] Failed removing $snapshot\n";
1669 } else {
1670 my $session_ref = session_load(\%config, "$cfg/$snaphot_name.json");
1671 if ($session_ref) {
1672 my %session = %{ $session_ref };
1673 if ($session{snapshot_lifetime}
1674 and (time > (stat $snapshot)[9] + $session{snapshot_lifetime})
1675 or (time > (stat $snapshot)[9] + $config{snapshot_lifetime}) ) {
1676 # json exists, lifetime exceeded
1677 print STDERR $0." [$now] housekeeping: $cfg/$snaphot_name.json (exceeded life-time)\n";
1678 session_stop($session_ref);
1679 }
1680 } else { rmtree( $snapshot ) || print STDERR $0." [$now] Failed removing $snapshot\n"; }
1681 }
1682 }
1683 } # for snapshot
1684
1685 # scan JSON files
1686 foreach my $json (glob("$cfg/*.json")) {
1687
1688 # session exists, load JSON
1689 my $session_ref = session_load(\%config, $json);
1690 if ($session_ref && time - (stat($json))[9] > 10*$config{boot_delay}) {
1691 my %session = %{ $session_ref };
1692 if (not -d $session{dir_snapshot}) {
1693 print STDERR $0." [$now] housekeeping: $json (left-over, no snapshot)\n";
1694 unlink($json);
1695 } # snapshot does not exist
1696 }
1697 }
1698
1699 # now count how many active sessions we have.
1700 my @jsons = glob("$cfg/$service"."_*.json");
1701 my $nb = scalar(@jsons);
1702 my $err = "";
1703 $config{session_nb} = $nb;
1704 $err = "";
1705 return ($err,$nb);
1706 } # service_housekeeping
1707
1708 # service_monitor(\%config, $out, $isadmin, $user): present a list of running sessions
1709 # as well as the server usage and history.
1710 # $out is expected to arrive with an OPEN '<ul class="status">...<div class="card">'
1711 # (as built in the main flow); this sub closes it and appends its own cards.
1712 # return appended string $out
1713 sub service_monitor {
1714 my $config_ref = shift;
1715 my $out = shift;
1716 my $isadmin = shift;
1717 my $user = shift;
1718
1719 if (not $config_ref) { return; }
1720 my %config = %{ $config_ref };
1721
1722 # first display server ID and usage
1723 my $cpu_count = 0;
1724 if ($cpu_count == 0) {eval { $cpu_count = Sys::CPU::cpu_count(); }}
1725 if ($cpu_count == 0) {eval { $cpu_count = System::CPU::get_ncpu(); }}
1726 if ($cpu_count == 0) {$cpu_count=1;}
1727 my $cpu_load = 0;
1728 eval {
1729 $cpu_load = Sys::CpuLoad::load();
1730 };
1731 if (not $cpu_load and $^O eq 'darwin') {
1732 my $load_avg = `sysctl -n vm.loadavg`;
1733 chomp($load_avg);
1734
1735 # Remove curly braces and trim whitespace
1736 $load_avg =~ s/[{}]//g;
1737 $load_avg =~ s/^\s+|\s+$//g;
1738
1739 # Replace commas with dots
1740 $load_avg =~ s/,/./g;
1741
1742 # Split and get the 1-min load average
1743 $cpu_load = split(/\s+/, $load_avg);
1744 }
1745 my $load = $cpu_load / $cpu_count;
1746 my ($total_memory_kb, $free_memory_kb, $avail_memory_kb) = get_freemem(); # in kB
1747 my $avail_memory_GB = $avail_memory_kb / 1024/1024; # in GB
1748 my $total_memory_GB = $total_memory_kb / 1024/1024;
1749 my $now = localtime();
1750
1751 # close the status card opened by the main flow, then start a new one
1752 $out .= "</ul></div>\n";
1753
1754 # display a table with current info
1755 $out .= "<div class='card'>";
1756 $out .= "<h1>Current $config{service} status ($now)</h1>";
1757 $out .= "<img class='logo' src=\"$config{http}://$config{server_name}/$config{service}/images/virtualmachines.png\" height=128>";
1758 $out .= "<table>\n";
1759 $out .= "<tr><th>Server </th><th>$config{server_name} running '$config{service}' version $config{version}</th></tr>\n";
1760 $out .= "<tr><td>#CPU total </td><td>$cpu_count</td></tr>\n";
1761 $out .= "<tr><td>#CPU used </td><td>$cpu_load</td></tr>\n";
1762 $out .= "<tr><td>Load [0-1] </td><td>$load</td></tr>\n";
1763 $out .= "<tr><td>Total memory (GB)</td><td>$total_memory_GB</td></tr>\n";
1764 $out .= "<tr><td>Available memory (GB) </td><td>$avail_memory_GB</td></tr>\n";
1765 $out .= "<tr><td>Active sessions </td><td>$config{session_nb} (total)</td></tr>\n";
1766 $out .= "</table>\n";
1767 $out .= "</div>\n";
1768
1769 # display a list of active sessions for the given user
1770 my $dir = $config{dir_snapshots};
1771 my $cfg = $config{dir_cfg};
1772 my $service = $config{service};
1773
1774 # iter=1: normal user; 2: admin user
1775 for my $iter (1..2) {
1776
1777 # {name} {machine} {user} {date} {cpu} {mem} {lifetime} {url} {PIDs}
1778 if ($iter == 1) {
1779 $out .= "<div class='card'><h2>Active sessions for $user</h2><table>\n";
1780 $out .= "<tr><th>Start Date</th><th>Name</th><th>Machine</th><th>User</th>";
1781 $out .= "<th>life-time (h)</th><th>URL</th>";
1782 $out .= "<th>Process</th><th>CPU</th><th>Memory (MB)</th><th>GPU</th></tr>\n";
1783 } elsif ($iter == 2 and $isadmin) {
1784 $out .= "<div class='card'><h2>Active sessions [$config{session_nb}] (administration)</h2><table>\n";
1785 $out .= "<tr><th>Start Date</th><th>Name</th><th>Machine</th><th>User</th>";
1786 $out .= "<th>life-time (h)</th><th>URL</th>";
1787 $out .= "<th>Process</th><th>CPU</th><th>Memory (MB)</th><th>GPU</th></tr>\n";
1788 }
1789
1790 foreach my $snapshot (glob("$dir/$service"."_*")) {
1791 if (-d $snapshot) { # is a snapshot directory
1792 my $snaphot_name = fileparse($snapshot); # just the session name
1793 if (-e "$cfg/$snaphot_name.json") {
1794 my $session_ref = session_load(\%config, "$cfg/$snaphot_name.json");
1795 if ($session_ref) {
1796 my %session = %{ $session_ref };
1797 my $flag=0;
1798
1799 if ($iter == 1 and $user eq $session{user}) { $flag = 1; }
1800 elsif ($iter == 2 and $isadmin) { $flag = 1; }
1801 if ($session{pid} and $flag) {
1802 my @pids = @{ $session{pid} };
1803 $out .= "<tr>";
1804 $out .= "<td>$session{date}</td>";
1805 if ($iter == 2) { # admin only. Appear as a collapsible text
1806 $out .= "<td><details><summary>$session{name}</summary><p><small>";
1807 my %hash = %session;
1808 $hash{password}="XXXX"; # hide user pw
1809 $out .= "<b>$_</b>=$hash{$_}; " for (keys %hash);
1810 $out .= "</small></p></details>";
1811 } else {
1812 $out .= "<td>$session{name}</td>";
1813 }
1814 $out .= "<td><a href='$config{http}://$session{server_name}/$config{service}/machines/$session{machine}'>$session{machine}</a></td>";
1815 if ($session{user_email}) {
1816 $out .= "<td><a href='mailto:$session{user_email}'>$session{user}</a></td>";
1817 } else {
1818 $out .= "<td>$session{user}</td>";
1819 }
1820
1821 my $lt = $session{snapshot_lifetime}/3600;
1822 my $end_date = localtime(str2time($session{date}) + $session{snapshot_lifetime});
1823 $out .= "<td>$lt [<small>$end_date</small>] ";
1824 my $extend_by = 24; # hours
1825 if ($session{snapshot_lifetime} + 3600*$extend_by < $config{snapshot_lifetime}) {
1826 $out .= "<br><form action=\"$config{http}://$session{server_name}/cgi-bin/qemu-web-desktop.pl\" method=post target=_blank><input type=hidden name=session_extend value=\"$session{name}\"><input type=submit class=\"btn\" value=\"+$extend_by h\"></input></form>";
1827 }
1828 $out .= "</td>\n";
1829
1830 if ($session{oneshot}) {
1831 $out .= "<td>one-shot";
1832 } else {
1833 $out .= "<td><a href='$session{url}' target=_blank class='btn connect' title='Connect'>&#9654;&nbsp;Connect</a>";
1834 if ($session{password_vnc} && ($config{service_port_multiple} or ($config{check_user_mfa} and $iter == 2))) {
1835 $out .= " $session{password_vnc}";
1836 }
1837 }
1838 $out .= "</td>";
1839 # create a STOP button for each
1840 $out .= "<td><form action=\"$config{http}://$session{server_name}/cgi-bin/qemu-web-desktop.pl\" method=post target=_blank style=\"display:inline;margin:0\"><input type=hidden name=session_stop value=\"$session{name}\"><button type=submit class=\"btn stop\" title=\"STOP\">&#9632;&nbsp;Stop</button></form></td>\n";
1841
1842
1843 $out .= "<td>$session{cpu}</td>";
1844 $out .= "<td>$session{memory}</td>";
1845 if ($session{gpu}) {
1846 $out .= "<td>$session{gpu}</td>";
1847 } else { $out .= "<td></td>"; }
1848 }
1849 }
1850 }
1851 }
1852 } # foreach snapshot
1853 $out .= "</table></div>";
1854
1855 # display full list of sessions (when user is marked as 'admin')
1856 if (not $isadmin) { return $out; }
1857 } # for 1..2
1858
1859 return $out;
1860 } # service_monitor
1861
1862 # service_purge(\%config): kill all running sessions
1863 sub service_purge {
1864 my $config_ref = shift;
1865
1866 if (not $config_ref) { return; }
1867 my %config = %{ $config_ref };
1868
1869 my $dir = $config{dir_snapshots};
1870 my $cfg = $config{dir_cfg};
1871 my $service = $config{service};
1872
1873 foreach my $snapshot (glob("$dir/$service"."_*")) {
1874 if (-d $snapshot) { # is a snapshot directory
1875 my $snaphot_name = fileparse($snapshot); # just the session name
1876 if (-e "$cfg/$snaphot_name.json") {
1877 my $session_ref = session_load(\%config, "$cfg/$snaphot_name.json");
1878 session_stop($session_ref);
1879 }
1880 }
1881 } # for
1882
1883
1884 } # service_purge
1885
1886 # session_email(\%config, \%session, $output): send an email with URL
1887 # $output is expected to already be a complete HTML document (see
1888 # html_page_wrap) since it is used verbatim as the email body.
1889 # return: "" or error message
1890 sub session_email {
1891 my $config_ref = shift;
1892 my $session_ref = shift;
1893 my $out = shift;
1894
1895 if (not $config_ref or not $session_ref or not $out) { return "Invalid session/config"; }
1896 my %config = %{ $config_ref };
1897 my %session = %{ $session_ref };
1898 if (not $session{user} or not $config{smtp_server}) {
1899 return "Invalid user or SMTP server";
1900 }
1901
1902 # auto use the provided smtp/email settings to decide what to do
1903 # SSL use the server, port SSL, and email_from with email_passwd
1904 # simple just use the server, and port 25
1905 # port just use the server with given port
1906
1907 my $smtp;
1908 my $method = $config{email_method};
1909 if ($method =~ 'auto') {
1910 if ( not $config{smtp_port} and not $config{smtp_use_ssl}) {
1911 $method = 'simple';
1912 } elsif ($config{smtp_port} and $config{smtp_use_ssl} and $config{email_passwd}) {
1913 $method = 'SSL';
1914 } else {
1915 $method = 'port';
1916 }
1917 }
1918
1919 if ($method =~ 'SSL' and $config{smtp_port} and $config{smtp_use_ssl}
1920 and $config{email_passwd}) {
1921 eval {
1922 $smtp = Net::SMTPS->new($config{smtp_server}, Port => $config{smtp_port},
1923 doSSL => $config{smtp_use_ssl}, SSL_version=>'TLSv1');
1924 };
1925 $method .= " $@" if $@; # add error from SMTP if any
1926 } elsif ($method =~ 'port' and $config{smtp_port}) {
1927 $smtp = Net::SMTP->new($config{smtp_server}, Port=>$config{smtp_port}, Timeout => 10);
1928 } else {
1929 $smtp = Net::SMTP->new($config{smtp_server}, Timeout => 10); # e.g. port 25
1930 }
1931
1932 if ($smtp) {
1933 if ($config{email_passwd}) {
1934 $smtp->auth($config{email_from},$config{email_passwd}) || return "Failed SMTP authentication for $config{email_from}";
1935 }
1936 $smtp->mail($config{email_from});
1937 $smtp->recipient($session{user_email});
1938 $smtp->data();
1939 $smtp->datasend("From: $config{email_from}\n");
1940 $smtp->datasend("To: $session{user_email}\n");
1941 # could add BCC to internal monitoring address $smtp->datasend("BCC: address\@example.com\n");
1942 $smtp->datasend("Subject: [$config{service}] Remote $session{name} connection information $session{password_vnc}\n");
1943 $smtp->datasend("Content-Type: text/html; charset=\"UTF-8\" \n");
1944 $smtp->datasend("\n"); # end of header
1945 $smtp->datasend($out);
1946 $smtp->dataend;
1947 $smtp->quit;
1948 return ""; # sent
1949 } else {
1950 return "Invalid SMTP connection: $method";
1951 }
1952
1953 } # session_email
1954
1955 # session_message(\%config, \%session,
1956 # $output_icon, $output_share, $output_token, $output_persistent);
1957 # assemble a "Hello user" card to display/send.
1958 # Returns BODY content only (no <body>/<script>/<html> closing tags -
1959 # those belong to html_page_wrap, which is applied once at print/save time).
1960 # return: $message
1961 sub session_message {
1962
1963 my $config_ref = shift;
1964 my $session_ref = shift;
1965
1966 my $output_icon = shift;
1967 my $output_share= shift;
1968 my $output_token= shift;
1969 my $output_persistent= shift;
1970
1971 if (not $config_ref or not $session_ref) { return "Invalid session/coonfig.\n"; }
1972 my %config = %{ $config_ref };
1973 my %session = %{ $session_ref };
1974 my $footer = "";
1975
1976 if (-f "$config{layout_footer}") {
1977 # use custom header as file
1978 open FILE, "$config{layout_footer}";
1979 $footer .= join "", <FILE>;
1980 close FILE;
1981 } elsif ("$config{layout_footer}" ne "") {
1982 # use custom header as string
1983 $footer .= "$config{layout_footer}";
1984 } else { # default header
1985 $footer .= <<END_HTML;
1986 <span class="footer"><a href="$config{http}://$session{server_name}/$config{service}/" target=_blank>$config{layout_title}</a> - <a href="https://gitlab.com/soleil-data-treatment/remote-desktop">$config{service}</a></span>
1987 END_HTML
1988 }
1989 my $u = $session{user};
1990 my $message = <<END_HTML;
1991 <div class="card">
1992 <h1>Hello $u !</h1>
1993
1994 <div style="text-align: center;">
1995 <a href=$session{url} target=_blank>$output_icon</a>
1996 <br><br>
1997
1998 <table><tr>
1999
2000 <td><a href="$session{url}" target=_blank class="btn connect" title="Connect to your machine">&#9654;&nbsp;Connect</a>
2001 $output_share</td>
2002
2003 <td style="text-align: right"><form action="$config{http}://$session{server_name}/cgi-bin/qemu-web-desktop.pl" method=post style="display:inline;margin:0">
2004 <input type=hidden name=session_stop value="$session{name}">
2005 <button type=submit class="btn stop" title="Stop this session">&#9632;&nbsp;Stop</button>
2006 </form></td>
2007
2008 </tr></table>
2009 $output_token
2010 </div>
2011
2012 <p>
2013 $output_persistent
2014 </p>
2015
2016 <hr>
2017 $footer
2018 </div>
2019 END_HTML
2020
2021 return $message;
2022 } # session_message
2023
2024 # ==============================================================================
2025
2026 # service_check_user_max(\%config, $user)
2027 # check resources used by user
2028 # return: ($nb_session, $nb_cpu, $nb_mem, $nb_gpu)
2029 sub service_check_user_max {
2030
2031 my $config_ref = shift;
2032 my $user = shift;
2033
2034 if (not $config_ref ) { return(0,0,0); }
2035 my %config = %{ $config_ref };
2036
2037 my $nb_session = 0;
2038 my $nb_cpu = 0;
2039 my $nb_mem = 0;
2040 my $nb_gpu = 0;
2041
2042 # get the list of active sessions for the given user
2043 my $dir = $config{dir_snapshots};
2044 my $cfg = $config{dir_cfg};
2045 my $service = $config{service};
2046
2047 foreach my $snapshot (glob("$dir/$service"."_*")) {
2048 if (-d $snapshot) { # is a snapshot directory
2049 my $snaphot_name = fileparse($snapshot); # just the session name
2050 if (-e "$cfg/$snaphot_name.json") {
2051 my $session_ref = session_load(\%config, "$cfg/$snaphot_name.json");
2052 if ($session_ref) {
2053 my %session = %{ $session_ref };
2054 if ($session{pid} and $user eq $session{user}) {
2055 $nb_cpu += $session{cpu};
2056 $nb_session ++;
2057 $nb_mem += $session{memory};
2058 if ($session{gpu}) { $nb_gpu ++; }
2059 }
2060 }
2061 }
2062 }
2063 }
2064
2065 return ($nb_session, $nb_cpu, $nb_mem, $nb_gpu);
2066
2067 } # service_check_user_max
2068
2069 # session_authenticate(\%config, \%session)
2070 # check user credentials with SMTP, LDAP, IMAP and sendemail.
2071 # return: ($out, $err, $session)
2072 sub session_authenticate {
2073
2074 my $config_ref = shift;
2075 my $session_ref = shift;
2076
2077 if (not $config_ref or not $session_ref) { return ("",""); }
2078 my %config = %{ $config_ref };
2079 my %session = %{ $session_ref };
2080
2081 my $out = "";
2082 my $err = "";
2083
2084 if ($session{runs_as_cgi}) { # authentication block
2085 my $authenticated = "";
2086 if (not $err) {
2087 # $out .= "<li>$ok Hello <b>$session{user}</b> !</li>\n";
2088 }
2089 # when all fails or is not checked, consider sending an email.
2090
2091 if (index($authenticated, "SUCCESS") < 0 and $config{check_user_with_email}
2092 and Email::Valid->address($session{user})) {
2093 $authenticated = "EMAIL";
2094 $session{user_email} = $session{user};
2095 if ($config{layout_level} > 1) {
2096 $out .= "<li>[OK] An email will be sent to indicate the URL.</li>\n";
2097 }
2098 }
2099 if (index($authenticated, "SUCCESS") < 0 and $config{check_user_with_local}) {
2100 $authenticated .= session_check_local(\%config, \%session); # checks local with ssh("user","password")
2101 }
2102 if (index($authenticated, "SUCCESS") < 0 and $config{check_user_with_imap}) {
2103 $authenticated .= session_check_imap(\%config, \%session); # checks IMAP("user","password")
2104 $session{user_email} = "$session{user}\@$config{imap_server}" if (not $session{user_email});
2105 }
2106 if (index($authenticated, "SUCCESS") < 0 and $config{check_user_with_smtp}) {
2107 $authenticated .= session_check_smtp(\%config, \%session); # checks SMTP("user","password")
2108 $session{user_email} = "$session{user}\@$config{smtp_server}" if (not $session{user_email});
2109 }
2110 if (index($authenticated, "SUCCESS") < 0 and $config{check_user_with_ldap}) {
2111 my $authenticated_ldap = "";
2112 my $session_ref;
2113 ($authenticated_ldap, $session_ref) = session_check_ldap(\%config, \%session); # checks LDAP("user","password")
2114 $authenticated .= $authenticated_ldap;
2115 if ($session_ref) {
2116 %session = %{ $session_ref };
2117 }
2118 }
2119 if ($config{check_user_custom}) {
2120 $authenticated = session_check_custom(\%config, \%session, $authenticated); # checks custom("user","password",$authenticated)
2121 }
2122 # now we search for a "SUCCESS"
2123 if (index($authenticated, "SUCCESS") > -1) {
2124 # $out .= "<li>$ok You are authenticated: $authenticated</li>\n";
2125 } elsif (not $authenticated) {
2126 if ($config{layout_level} >= 2) {
2127 $out .= "<li><span class='badge warn'>WARNING</span> Service is running without user authentication.</li>\n";
2128 }
2129 # no authentication configured...
2130 } else {
2131 $err .= "User $session{user} failed authentication. Check your username / password: $authenticated ";
2132 }
2133
2134
2135 } # authentication block
2136 return ($out, $err, \%session);
2137
2138 } # session_authenticate
2139
2140 # session_check_smtp(\%config, \%session)
2141 # smtp_server, smtp_port, smtp_use_ssl are all needed.
2142 # return "" when no check is done
2143 # "FAILED" when authentication failed
2144 # "SUCCESS" when authentication succeeded
2145 sub session_check_smtp {
2146 my $config_ref = shift;
2147 my $session_ref = shift;
2148
2149 if (not $config_ref or not $session_ref) { return; }
2150 my %config = %{ $config_ref };
2151 my %session = %{ $session_ref };
2152 my $res="";
2153
2154 # return when check can not be done
2155 if (not $config{check_user_with_smtp} or not $config{smtp_server}
2156 or not $config{smtp_port} or not $config{smtp_use_ssl}) { return ""; }
2157
2158 if (not $session{user} or not $session{password}) {
2159 return "FAILED: [SMTP] Missing Username/Password. \n ";
2160 }
2161
2162 # must use encryption to check user.
2163 my $smtps = Net::SMTPS->new($config{smtp_server}, Port => $config{smtp_port},
2164 doSSL => $config{smtp_use_ssl}, SSL_version=>'TLSv1')
2165 or return "FAILED: [SMTP] Cannot connect to server. $@ \n ";
2166
2167 # when USERNAME/PW is wrong, dies with no auth.
2168 if (not $smtps->auth ( $session{user}, $session{password} )) {
2169 $res = "FAILED: [SMTP] Wrong username/password (failed authentication). \n ";
2170 } else {
2171 $res = "SUCCESS: [SMTP] $session{user} authenticated. \n ";
2172 }
2173
2174 $smtps->quit;
2175 return $res;
2176
2177 } # session_check_smtp
2178
2179 # session_check_imap(\%config, \%session)
2180 # imap_server, imap_port are all needed.
2181 # return "" when no check is done
2182 # "FAILED" when authentication failed
2183 # "SUCCESS" when authentication succeeded
2184 sub session_check_imap {
2185 my $config_ref = shift;
2186 my $session_ref = shift;
2187
2188 if (not $config_ref or not $session_ref) { return; }
2189 my %config = %{ $config_ref };
2190 my %session = %{ $session_ref };
2191 my $res = "";
2192
2193 # return when check can not be done
2194 if (not $config{check_user_with_imap} or not $config{imap_server}
2195 or not $config{imap_port}) { return ""; }
2196
2197 if (not $session{user} or not $session{password}) {
2198 return "FAILED: [IMAP] Missing Username/Password. \n ";
2199 }
2200
2201 # Connect to IMAP server
2202 my $client = Mail::IMAPClient->new(
2203 Server => $config{imap_server},
2204 User => $session{user},
2205 Password => $session{password},
2206 Port => $config{imap_port},
2207 Timeout => 10,
2208 Ssl => 1)
2209 or return "FAILED: [IMAP] Cannot authenticate username/password. $@ \n "; # die when not auth
2210
2211 # List folders on remote server (see if all is ok)
2212 if ($client->IsAuthenticated()) {
2213 $res = "SUCCESS: [IMAP] $session{user} authenticated. \n";
2214 } else {
2215 $res = "FAILED: [IMAP] Wrong username/password (failed authentication). \n";
2216 }
2217
2218 $client->logout();
2219 return $res;
2220
2221 } # session_check_imap
2222
2223 # session_check_ldap(\%config, \%session)
2224 # ldap_server is needed. Return ($res, $session)
2225 # return "" when no check is done
2226 # "FAILED" when authentication failed
2227 # "SUCCESS" when authentication succeeded
2228
2229 # used: http://articles.mongueurs.net/magazines/linuxmag68.html
2230 sub session_check_ldap {
2231 my $config_ref = shift;
2232 my $session_ref = shift;
2233
2234 if (not $config_ref or not $session_ref) { return ""; }
2235 my %config = %{ $config_ref };
2236 my %session = %{ $session_ref };
2237
2238 if (not %config or not %session) { return ""; }
2239 my $res = "";
2240 my $filter = "";
2241
2242 # return when check can not be done
2243 if (not $config{check_user_with_ldap} or not $config{ldap_server}
2244 or not $config{ldap_port}) { return ""; }
2245
2246 if (not $session{user} or not $session{password}) {
2247 return "FAILED: [LDAP] Missing Username/Password. \n";
2248 }
2249
2250 my $ldap = Net::LDAP->new($config{ldap_server}, port=>$config{ldap_port})
2251 or return "FAILED: [LDAP] Cannot connect to server. $@ \n";
2252
2253 # check if "user" was given as an email.
2254 if (Email::Valid->address($session{user})) {
2255 $session{user_email} = $session{user};
2256 $filter = "mail=$session{user}";
2257 } else {
2258 $filter = "cn=$session{user}"; # may also be "uid=$session{user}"
2259 }
2260
2261 # identify the DN
2262 my $mesg = $ldap->search(
2263 base => "dc=$config{ldap_domain}",
2264 filter => $filter,
2265 attrs => ['dn','mail','cn','uid']);
2266
2267 if (not $mesg or not $mesg->count) {
2268 $res = "FAILED: [LDAP] empty LDAP search. \n";
2269 } else {
2270
2271 foreach my $entry ($mesg->all_entries) {
2272 my $dn = $entry->dn();
2273 my $email = $entry->get_value('mail');
2274 my $cn = $entry->get_value('cn'); # may also be 'uid'
2275 my $bmesg = $ldap->bind($dn,password=>$session{password});
2276 if ( $bmesg and $bmesg->code() == 0 ) {
2277 if (not Email::Valid->address($session{user}) && $email) {
2278 $session{user_email} = $email;
2279 } elsif (Email::Valid->address($session{user})) {
2280 $session{user} = $cn;
2281 }
2282 $res = "SUCCESS: [LDAP] $session{user} authenticated. \n";
2283 }
2284 else{
2285 my $error = $bmesg->error();
2286 $res = "FAILED: [LDAP] Wrong username/password (failed authentication). $error \n";
2287 }
2288 }
2289 }
2290
2291 $ldap->unbind;
2292 return ($res,\%session);
2293
2294 } # session_check_ldap
2295
2296 # session_check_local(\%config, \%session)
2297 # local authentication. Return ($res, $session)
2298 # return "" when no check is done
2299 # "FAILED" when authentication failed
2300 # "SUCCESS" when authentication succeeded
2301 sub session_check_local {
2302 my $config_ref = shift;
2303 my $session_ref = shift;
2304
2305 if (not $config_ref or not $session_ref) { return ""; }
2306 my %config = %{ $config_ref };
2307 my %session = %{ $session_ref };
2308
2309 if (not %config or not %session) { return ""; }
2310 my $res = "";
2311
2312 if (not $session{user} or not $session{password}) {
2313 return "FAILED: [local] Missing Username/Password.\n ";
2314 }
2315
2316 # we use perl Net::SSH2 with $session{user} and $session{password}
2317 # the target server must have openssh installed (apt install openssh-server)
2318 my $ssh = Net::SSH2->new();
2319 $ssh->connect($session{server_name}) || return "FAILED: [local] Could not connect to server $session{server_name}.\n ";
2320 $ssh->auth_password ( $session{user}, $session{password} ) || return "FAILED: [local] Wrong username/password (failed authentication).\n ";
2321 $ssh->disconnect;
2322
2323 undef $ssh; # close connexion
2324
2325 return "SUCCESS: [local] $session{user} authenticated.\n ";
2326
2327 } # session_check_local
2328
2329 # session_check_custom(\%config, \%session, $authenticated)
2330 # check with a user function defined in %config
2331 # return "" when no check is done
2332 # "FAILED" when authentication failed
2333 # "SUCCESS" when authentication succeeded
2334 #
2335 # specify an authenticator function in /etc/qemu-web-desktop/config.pl or config.d/*.pl such as:
2336 #
2337 # sub check_user_func {
2338 # my $user = shift;
2339 # my $pw = shift;
2340 # my $authenticated = shift; # previous authenticator results
2341 # my $session_ref = shift;
2342 # if (not $session_ref) { return $authenticated; }
2343 # my %session = %{ $session_ref };
2344 # return "$auth and SUCCESS: [Custom] $user authenticated.";
2345 # }
2346 #
2347 # $config{check_user_custom} = \&check_user_func;
2348
2349 sub session_check_custom {
2350 my $config_ref = shift;
2351 my $session_ref = shift;
2352 my $authenticated = shift;
2353
2354 if (not $config_ref or not $session_ref) { return ""; }
2355 my %config = %{ $config_ref };
2356 my %session = %{ $session_ref };
2357
2358 if (not %config or not %session) { return ""; }
2359
2360 # check if existing custom auth
2361 if (not $config{check_user_custom}) { return ""; }
2362 my $res = "";
2363
2364 if (not $session{user}) {
2365 return "FAILED: [custom auth] Missing Username. \n";
2366 }
2367
2368 # execute the referenced function
2369 my $cref = $config{check_user_custom};
2370 eval { $res = &$cref($session{user}, $session{password}, $authenticated, \%session); };
2371 print STDERR "$0: Error when executing custom authenticator: $@ \n" if $@;
2372
2373 return $res;
2374
2375 } # session_check_custom
2376
2377 # session_use_gpu(\%config, $pci): return true if the given PCI is used by any running session
2378 sub session_use_gpu {
2379 my $config_ref = shift;
2380 my $pci = shift;
2381
2382 if (not $config_ref) { return 0; }
2383 my %config = %{ $config_ref };
2384 my $cfg = $config{dir_cfg};
2385
2386 if ($config{gpu_blacklist} and $pci =~ $config{gpu_blacklist}) {
2387 return 1; # PCI is black-listed
2388 }
2389
2390 # scan JSON files
2391 foreach my $json (glob("$cfg/*.json")) {
2392
2393 # session exists, load JSON
2394 my $session_ref = session_load(\%config, $json);
2395 if ($session_ref) {
2396 my %session = %{ $session_ref };
2397 if ($session{gpu} eq $pci) { return 1; } # PCI is used
2398 }
2399 }
2400 return 0; # no session is using that PCI slot
2401 } # session_use_gpu
2402
2403 # proc_getchildren($pid): return all children PID's from parent.
2404 # use: my @children = flatten(proc_getchildren($$));
2405 sub flatten {
2406 map { ref $_ ? flatten(@{$_}) : $_ } @_;
2407 }
2408
2409 sub proc_getchildren {
2410 my $parent= shift;
2411 my @pid = [];
2412 push @pid, $parent;
2413 if (not $parent) { return; }
2414
2415 my $proc_table=Proc::ProcessTable->new();
2416 for my $proc (@{$proc_table->table()}) {
2417 if ($proc->ppid == $parent) {
2418 my $child = $proc->pid;
2419 push @pid, $child;
2420 my @pid_children = flatten(proc_getchildren($child));
2421 push @pid, @pid_children;
2422 }
2423 }
2424 return flatten(@pid);
2425 } # proc_getchildren
2426
2427 # proc_running($pid): checks if $pid is running.
2428 # input $pid is a PID number.
2429 # return 0 or 1 (running).
2430 sub proc_running {
2431 my $pid = shift;
2432 if (not $pid) { return 0; }
2433
2434 my $found = 0; # we now search for the PID.
2435 my $proc_table=Proc::ProcessTable->new();
2436 for my $proc (@{$proc_table->table()}) {
2437 if ($proc->pid == $pid) {
2438 # session is still running
2439 $found = $pid;
2440 last;
2441 }
2442 }
2443 return $found;
2444 } # proc_running
2445
2446 # pci_devices($cmd,$type,$module): extract GPU info from lspci and identify the devices
2447 # input: $cmd command to execute, e.g. 'lspci -nnk'
2448 # $type type of devive, e.g. "vga" or empty (can be any word to search for)
2449 # $module used kernel module, e.g. "nvidia" or "vfio" or empty
2450 # output: list of devices matching criteria, (@$device_pci, @$device_model, @$device_name)
2451 #
2452 # example: my ($device_pci, $device_model, $device_name) = pci_devices("lspci -nnk","audio","");
2453 # print "$_\n" for @$device_pci;
2454 # example: pci_devices("lspci -nnk","vga", "vfio");
2455 sub pci_devices {
2456 my ($cmd, $type, $module) = @_;
2457 my @device_pci;
2458 my @device_model;
2459 my @device_name;
2460
2461 # Execute the command and capture its output
2462 open(my $pipe, '-|', $cmd) or return (\@device_pci, \@device_model, \@device_name);
2463 my @lines;
2464 while (my $line = <$pipe>) {
2465 chomp $line;
2466 push @lines, $line;
2467 }
2468 close($pipe);
2469
2470 # Process each block of device information
2471 my $current_block = '';
2472 for my $line (@lines) {
2473 if ($line =~ /^([0-9a-f]{2}:[0-9a-f]{2}\.[0-9a-f])/) {
2474 # New device block starts
2475 if ($current_block) {
2476 # Process the previous block
2477 my ($pci, $model, $name) = _parse_device_block($current_block, $type, $module);
2478 push @device_pci, $pci if $pci;
2479 push @device_model, $model if $model;
2480 push @device_name, $name if $name;
2481 }
2482 $current_block = $line . "\n";
2483 } else {
2484 $current_block .= $line . "\n" if $current_block;
2485 }
2486 }
2487
2488 # Process the last block
2489 if ($current_block) {
2490 my ($pci, $model, $name) = _parse_device_block($current_block, $type, $module);
2491 push @device_pci, $pci if $pci;
2492 push @device_model, $model if $model;
2493 push @device_name, $name if $name;
2494 }
2495
2496 return (\@device_pci, \@device_model, \@device_name);
2497 }
2498
2499 sub _parse_device_block {
2500 my ($block, $type, $module) = @_;
2501 my $pci;
2502 my $model;
2503 my $name;
2504
2505 # Extract PCI address
2506 if ($block =~ /^([0-9a-f]{2}:[0-9a-f]{2}\.[0-9a-f])/) {
2507 $pci = $1;
2508 }
2509
2510 # Extract vendor:ID
2511 if ($block =~ /\[([0-9a-f]{4}:[0-9a-f]{4})\]/) {
2512 $model = $1;
2513 }
2514
2515 # Extract full device description (first line)
2516 if ($block =~ /^([^\n]+)/) {
2517 $name = $1;
2518 }
2519
2520 # Check if the block matches the search criteria
2521 my $matches_type = !$type || ($block =~ /\b$type\b/i);
2522 my $matches_module = !$module || ($block =~ /\b$module\b/i);
2523
2524 if ($matches_type && $matches_module) {
2525 return ($pci, $model, $name);
2526 } else {
2527 return (undef, undef, undef);
2528 }
2529 } # pci_devices
2530
2531 # get_freemem(): get the total/free/available memory, in kB
2532 # The available memory is the sum of the free and cached memory.
2533 #
2534 # ($total_mem, $free_mem, $avail_mem) = get_freemem()
2535 sub get_freemem {
2536 my $free_memory_kb = 0;
2537 my $avail_memory_kb = 0;
2538 my $total_memory_kb = 0;
2539
2540 if ($^O eq 'darwin') {
2541 $avail_memory_kb = 0; # vm_stat and Sys::MemInfo under-evaluate the free/available memory
2542 $total_memory_kb = `sysctl -n hw.memsize`;
2543 chomp($total_memory_kb);
2544 $total_memory_kb = $total_memory_kb/1024;
2545
2546 my $used_memory_kb = 0;
2547 open(my $ps, '-|', 'ps -A -o rss=') or die "Failed to run ps: $!";
2548 while (my $line = <$ps>) {
2549 chomp $line;
2550 $used_memory_kb += $line if $line =~ /^\d+$/;
2551 }
2552 close($ps);
2553 $avail_memory_kb = $total_memory_kb - $used_memory_kb;
2554
2555 } elsif (-f "/proc/meminfo") {
2556 my @meminfo;
2557 @meminfo = `/bin/cat /proc/meminfo`;
2558 foreach (@meminfo) {
2559 chomp;
2560 if (/^Mem(Total|Free|Available):\s+(\d+) kB/) {
2561 my $counter_name = $1;
2562 if ($counter_name eq 'Free') {
2563 $free_memory_kb = $2;
2564 }
2565 elsif ($counter_name eq 'Total') {
2566 $total_memory_kb = $2;
2567 }
2568 elsif ($counter_name eq 'Available') {
2569 $avail_memory_kb = $2;
2570 }
2571 }
2572 }
2573 if (not $total_memory_kb) { $total_memory_kb = Sys::MemInfo::totalmem()/1024; }
2574 if (not $free_memory_kb) { $free_memory_kb = Sys::MemInfo::freemem() /1024; }
2575 if (not $avail_memory_kb) { $avail_memory_kb = $free_memory_kb; }
2576 }
2577
2578
2579
2580 return ($total_memory_kb, $free_memory_kb, $avail_memory_kb);
2581 } # get_freemem
2582
2583 # Validate and sanitize file paths/names
2584 sub safe_path {
2585 my ($base, $path) = @_;
2586 $path =~ s|[^a-zA-Z0-9._\ \@\-]||g; # Remove dangerous chars
2587 if (not $base) { return $path; }
2588 my $full = File::Spec->catfile($base, $path);
2589 # Ensure the resolved path is within $base
2590 my $abs = File::Spec->rel2abs($full);
2591 return $abs =~ /^\Q$base\E/ ? $abs : die "Path traversal attempt";
2592 } # safe_path