Project

General

Profile

Download (67.2 KB) Statistics
| Branch: | Revision:
1 95b003ff Origo
#!/usr/bin/perl
2
3
# All rights reserved and Copyright (c) 2020 Origo Systems ApS.
4
# This file is provided with no warranty, and is subject to the terms and conditions defined in the license file LICENSE.md.
5
# The license file is part of this source code package and its content is also available at:
6
# https://www.origo.io/info/stabiledocs/licensing/stabile-open-source-license
7
8
# Clear up tainted environment
9
$ENV{PATH} = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin';
10
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
11
12
#use warnings FATAL => 'all';
13
use CGI::Carp qw(fatalsToBrowser);
14 f222b89c hq
use CGI qw(:standard -head);
15 95b003ff Origo
use Getopt::Std;
16
use JSON;
17
use URI::Escape qw(uri_escape uri_unescape);
18
use Tie::DBI;
19
use Data::Dumper;
20
use Encode;
21
use Text::SimpleTable;
22
use ConfigReader::Simple;
23
use Sys::Syslog qw( :DEFAULT setlogsock);
24
use Digest::SHA qw(sha512_base64 sha512_hex);
25
use utf8;
26
use Hash::Merge qw( merge );
27
use Storable qw(freeze thaw);
28
use Gearman::Client;
29
use Proc::ProcessTable;
30
use HTTP::Async;
31
use HTTP::Request::Common;
32
use LWP::Simple qw(!head);
33
use Error::Simple;
34
35
our %options=();
36
# -a action -h help -f full list -p full update -u uuid -i image -m match pattern -k keywords -g args to gearman task
37
# -v verbose, include HTTP headers -s impersonate subaccount -t target [uuid or image] -c force console
38
Getopt::Std::getopts("a:hfpu:i:g:m:k:vs:t:c", \%options);
39
40
$Stabile::config = ConfigReader::Simple->new("/etc/stabile/config.cfg",
41
    [qw(
42
        AMT_PASSWD
43
        DBI_PASSWD
44
        DBI_USER
45
        DO_DNS
46
        DNS_DOMAIN
47
        DO_XMPP
48
        ENGINEID
49
        ENGINENAME
50
        ENGINE_DATA_NIC
51
        ENGINE_LINKED
52
        EXTERNAL_IP_RANGE_START
53
        EXTERNAL_IP_RANGE_END
54
        EXTERNAL_IP_QUOTA
55
        EXTERNAL_NIC
56
        EXTERNAL_SUBNET_SIZE
57
        MEMORY_QUOTA
58
        NODE_STORAGE_OVERCOMMISSION
59
        NODESTORAGE_QUOTA
60
        PROXY_GW
61
        PROXY_IP
62
        PROXY_IP_RANGE_END
63
        PROXY_IP_RANGE_START
64
        PROXY_SUBNET_SIZE
65
        RDIFF-BACKUP_ENABLED
66
        RDIFF-BACKUP_USERS
67 6372a66e hq
        REMOTE_IP_ENABLED
68
        REMOTE_IP_PROVIDER
69 95b003ff Origo
        RX_QUOTA
70
        SHOW_COST
71
        STORAGE_BACKUPDIR
72
        STORAGE_POOLS_ADDRESS_PATHS
73
        STORAGE_POOLS_DEFAULTS
74
        STORAGE_POOLS_LOCAL_PATHS
75
        STORAGE_POOLS_NAMES
76
        STORAGE_POOLS_RDIFF-BACKUP_ENABLED
77
        STORAGE_QUOTA
78
        Z_IMAGE_RETENTION
79
        Z_BACKUP_RETENTION
80
        TX_QUOTA
81
        VCPU_QUOTA
82
        VLAN_RANGE_START
83
        VLAN_RANGE_END
84
        VERSION
85
    )]);
86
87
$dbiuser =  $Stabile::config->get('DBI_USER') || "irigo";
88
$dbipasswd = $Stabile::config->get('DBI_PASSWD') || "";
89
$dnsdomain = $Stabile::config->get('DNS_DOMAIN') || "stabile.io";
90 2a63870a Christian Orellana
$appstoreurl = $Stabile::config->get('APPSTORE_URL') || "https://www.origo.io/registry";
91 c899e439 Origo
$appstores = $Stabile::config->get('APPSTORES') || "stabile.io"; # Used for publishing apps
92 95b003ff Origo
$engineuser = $Stabile::config->get('ENGINEUSER') || "";
93
$imageretention = $Stabile::config->get('Z_IMAGE_RETENTION') || "";
94
$backupretention = $Stabile::config->get('Z_BACKUP_RETENTION') || "";
95
$enginelinked = $Stabile::config->get('ENGINE_LINKED') || "";
96 a2e0bc7e hq
$downloadmasters = $Stabile::config->get('DOWNLOAD_MASTERS') || "";
97 f222b89c hq
$downloadallmasters = $Stabile::config->get('DOWNLOAD_ALL_MASTERS') || "";
98 95b003ff Origo
$disablesnat = $Stabile::config->get('DISABLE_SNAT') || "";
99 d3805c61 hq
our $enforceiolimits = $Stabile::config->get('ENFORCE_IO_LIMITS') || "";
100 e9af6c24 Origo
our $engineid = $Stabile::config->get('ENGINEID') || "";
101 95b003ff Origo
102 a2e0bc7e hq
$Stabile::remoteipprovider = ($Stabile::config->get('REMOTE_IP_PROVIDER')) || "";
103
$Stabile::remoteipenabled = ($Stabile::config->get('REMOTE_IP_ENABLED') && $Stabile::config->get('ENGINE_LINKED')) || "";
104
$Stabile::engineuser = $Stabile::config->get('ENGINEUSER') || "";
105
106 95b003ff Origo
$Stabile::dbopts = {db=>'mysql:steamregister', key=>'uuid', autocommit=>0, CLOBBER=>2, user=>$dbiuser, password=>$dbipasswd};
107
$Stabile::auth_tkt_conf = "/etc/apache2/conf-available/auth_tkt_cgi.conf";
108
109
my $base = "/var/www/stabile";
110
$base = `cat /etc/stabile/basedir` if (-e "/etc/stabile/basedir");
111
chomp $base;
112
$base =~ /(.+)/; $base = $1; #untaint
113
$main::logfile = "/var/log/stabile/steam.log";
114
115
$current_time = time;
116
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($current_time);
117
$year += 1900;
118
$month = substr("0" . ($mon+1), -2);
119
$pretty_time = sprintf "%4d-%02d-%02d@%02d:%02d:%02d",$year,$mon+1,$mday,$hour,$min,$sec;
120
121 d24d9a01 hq
if ($ENV{'HTTP_HOST'} && !($ENV{'HTTP_HOST'} =~ /^10\./) && $ENV{'HTTP_HOST'} ne 'localhost' && !($ENV{'HTTP_HOST'} =~ /^127/)) {
122
    $baseurl = "https://$ENV{'HTTP_HOST'}/stabile";
123
    `echo "$baseurl" > /tmp/baseurl` if ((! -e "/tmp/baseurl") && $baseurl);
124 2a63870a Christian Orellana
} else  {
125
    if (!$baseurl && (-e "/tmp/baseurl" || -e "/etc/stabile/baseurl")) {
126
        if (-e "/etc/stabile/baseurl") {
127
            $baseurl = `cat /etc/stabile/baseurl`;
128
        } else {
129
            $baseurl = `cat /tmp/baseurl`;
130
            chomp $baseurl;
131
            `echo "$baseurl" >/etc/stabile/baseurl` unless (-e "/etc/stabile/baseurl");
132
        }
133
    }
134
}
135
if (!$baseurl) {
136
    my $hostname = `hostname`; chomp $hostname;
137
    $baseurl = "https://$hostname/stabile";
138
}
139 95b003ff Origo
$baseurl = $1 if ($baseurl =~ /(.+)/); #untaint
140
141
$Stabile::basedir = "/var/www/stabile";
142
$Stabile::basedir = `cat /etc/stabile/basedir` if -e "/etc/stabile/basedir";
143
chomp $Stabile::basedir;
144
$Stabile::basedir = $1 if ($Stabile::basedir =~ /(.+)/); #untaint
145
146
$package = substr(lc __PACKAGE__, length "Stabile::");
147
$programname = "Stabile";
148
149
$sshcmd = qq|ssh -l irigo -i /var/www/.ssh/id_rsa_www -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no|;
150
151
$ENV{'REQUEST_METHOD'} = $ENV{'REQUEST_METHOD'} || 'GET';
152
153
preInit();
154
1;
155
156
$main::syslogit = sub {
157
	my ($user, $p, $msg) = @_;
158
	my $priority = ($p eq 'syslog')?'info':$p;
159
160
    $current_time = time;
161
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($current_time);
162
    $year += 1900;
163
    $month = substr("0" . ($mon+1), -2);
164
    my $pretty_time = sprintf "%4d-%02d-%02d@%02d:%02d:%02d",$year,$mon+1,$mday,$hour,$min,$sec;
165
166
    my $loguser = (!$tktuser || $tktuser eq $user)?"$user":"$user ($tktuser)";
167
	if ($msg && $msg ne '') {
168
	    utf8::decode($msg);
169
		unless (open(TEMP3, ">>$main::logfile")) {$posterror .= "Status=Error log file '$main::logfile' could not be written";}
170
        $msg =~ /(.+)/; $msg = $1; #untaint
171
		print TEMP3 $pretty_time, " : $loguser : $msg\n";
172
		close(TEMP3);
173
	}
174
	return 0 unless ($priority =~ /err|debug/);
175
	setlogsock('unix');
176
	# $programname is assumed to be a global.  Also log the PID
177
	# and to CONSole if there's a problem.  Use facility 'user'.
178
	openlog($programname, 'pid,cons', 'user');
179
	syslog($priority, "($loguser) $msg");
180
	closelog();
181
	return 1;
182
};
183
184
185
$main::postToOrigo = sub {
186
    my ($engineid, $postaction, $postcontent, $postkey, $callback) = @_;
187
    my $tktcfg = ConfigReader::Simple->new($Stabile::auth_tkt_conf, [qw(TKTAuthSecret)]);
188
    my $tktkey = $tktcfg->get('TKTAuthSecret') || '';
189
    my $ret;
190
191
    if ($tktkey && $engineid) {
192
        my $browser = LWP::UserAgent->new;
193
        $browser->timeout(15);
194
        $browser->agent('pressurecontrol/1.0b');
195
        $browser->protocols_allowed( [ 'http','https'] );
196
197
        my $postreq;
198
        $postreq->{'engineid'} = $engineid;
199
        $postreq->{'enginetkthash'} = sha512_hex($tktkey) if ($enginelinked);
200
        $postreq->{'appuser'} = $user;
201
        $postreq->{'callback'} .= $callback if ($callback);
202
        $postkey = 'POSTDATA' unless ($postkey);
203
        $postreq->{$postkey} = $postcontent;
204
        my $posturl = "https://www.origo.io/irigo/engine.cgi?action=$postaction";
205
        my $content = $browser->post($posturl, $postreq)->content();
206
        my $ok = ($content =~ /OK: (.*)/i);
207
        $ret .= $content;
208
    } else {
209
        $main::syslogit->('pressurecontrol', 'info', "Unable to get engine tktkey...");
210
        $ret .= "Unable to get engine tktkey...";
211
    }
212
    return $ret;
213
};
214
215 48fcda6b Origo
$main::uploadToOrigo = sub {
216
    my ($engineid, $filepath, $force) = @_;
217
    my $tktcfg = ConfigReader::Simple->new($Stabile::auth_tkt_conf, [qw(TKTAuthSecret)]);
218
    my $tktkey = $tktcfg->get('TKTAuthSecret') || '';
219
    my $ret;
220
221
    if (!$filepath || !(-e $filepath)) {
222
        $ret = "Status=Error Invalid file path\n";
223
    } elsif ($tktkey && $engineid) {
224 2a63870a Christian Orellana
        $HTTP::Request::Common::DYNAMIC_FILE_UPLOAD = 1;
225 48fcda6b Origo
        my $browser = LWP::UserAgent->new;
226
        $browser->timeout(15 * 60); # 15 min
227
        $browser->agent('pressurecontrol/1.0b');
228
        $browser->protocols_allowed( [ 'http','https'] );
229
        my $fname = $1 if ($filepath =~ /.*\/(.+\.qcow2)$/);
230
        return "Status=Error Invalid file\n" unless ($fname);
231
        my $posturl = "https://www.origo.io/irigo/engine.cgi?action=uploadimage";
232 2a63870a Christian Orellana
233
# -- using ->post
234
#         my $postreq = [
235
#             'file'          => [ $filepath ],
236
#             'filename'      => $fname,
237
#             'engineid'      => $engineid,
238
#             'enginetkthash' => sha512_hex($tktkey),
239
#             'appuser'       => $user,
240
#             'force'         => $force
241
#         ];
242
#         my $content = $browser->post($posturl, $postreq, 'Content_Type' => 'form-data')->content;
243
#         $ret .= $content;
244
245
# -- using ->request
246
        my $req = POST $posturl,
247
            Content_Type => 'form-data',
248
            Content => [
249
                'file'          => [ $filepath ],
250
                'filename'      => $fname,
251
                'engineid'      => $engineid,
252
                'enginetkthash' => sha512_hex($tktkey),
253
                'appuser'       => $user,
254
                'force'         => $force
255
            ];
256
        my $total;
257
        my $callback = $req->content;
258
        if (ref($callback) eq "CODE") {
259
            my $size = $req->header('content-length');
260
            my $counter = 0;
261
            my $progress = '';
262
            $req->content(
263
                sub {
264
                    my $chunk = $callback->();
265
                    if ($chunk) {
266
                        my $length = length $chunk;
267
                        $total += $length;
268
                        if ($total / $size * 100 > $counter) {
269
                            $counter = 1+ int $total / $size * 100;
270
                            $progress .= "#";
271
                            `echo "$progress$counter" >> /tmp/upload-$fname`;
272
                        }
273
#                        printf "%+5d = %5.1f%%\n", $length, $total / $size * 100;
274
#                        printf "%5.1f%%\n", $total / $size * 100;
275
276
                    } else {
277
#                        print "Done\n";
278
                    }
279
                    $chunk;
280
                }
281
            );
282
            my $resp = $browser->request($req)->content();
283
            $ret .= $resp;
284
            $ret .= "Status=OK $progress\n";
285
        } else {
286
            $ret .= "Status=Error Did not get a callback";
287
        }
288 48fcda6b Origo
    } else {
289
        $ret .= "Status=Error Unable to get engine tktkey...";
290
    }
291
    return $ret;
292
};
293
294 95b003ff Origo
$main::postAsyncToOrigo = sub {
295
    my ($engineid, $postaction, $json_text) = @_;
296
    my $tktcfg = ConfigReader::Simple->new($Stabile::auth_tkt_conf, [qw(TKTAuthSecret)]);
297
    my $tktkey = $tktcfg->get('TKTAuthSecret') || '';
298
    my $ret;
299
300
    if ($tktkey && $engineid) {
301
        my $browser = LWP::UserAgent->new;
302
        $browser->timeout(15);
303
        $browser->agent('pressurecontrol/1.0b');
304
        $browser->protocols_allowed( [ 'http','https'] );
305
306
        $ret .= "Posting $postaction to origo.io\n";
307
308
        my $postreq;
309
        $postreq->{'engineid'} = $engineid;
310
        $postreq->{'enginetkthash'} = sha512_hex($tktkey);
311
        $postreq->{'POSTDATA'} = $json_text;
312
#        my $content = $browser->post("https://www.origo.io/irigo/engine.cgi?action=$postaction", $postreq)->content();
313
#        my $ok = ($content =~ /OK: (.*)/i);
314
#        $ret .= $content;
315
316
        my $async = HTTP::Async->new;
317
        my $post = POST "https://www.origo.io/irigo/engine.cgi?action=$postaction",
318
            [   engineid => $engineid,
319
                enginetkthash => sha512_hex($tktkey),
320
                POSTDATA => $json_text
321
            ];
322
        $async->add( $post );
323
#        while ( my $response = $async->wait_for_next_response ) {
324
#            $ret .= $response->decoded_content;
325
#        }
326
    } else {
327
        $main::syslogit->('pressurecontrol', 'info', "Unable to get engine tktkey...");
328
        $ret .= "Unable to get engine tktkey...";
329
    }
330
    return $ret;
331
};
332
333
$main::dnsCreate = sub {
334
    my ($engineid, $name, $value, $type, $username) = @_;
335
    my $res;
336 e9af6c24 Origo
    my $dnssubdomain = substr($engineid, 0, 8);
337
    $type = uc $type;
338
    $type || 'CNAME';
339 95b003ff Origo
    $name = $1 if ($name =~ /(.+)\.$dnsdomain/);
340 e9af6c24 Origo
    # $name =$1 if ($name =~ /(.+)\.$dnssubdomain/);
341
    if ($type eq 'A') { # Look for initial registrations and format correctly
342
        if (!$name && $value) { # If no name provided assume we are creating initial A-record
343
            $name = $value;
344
        } elsif ($name =~ /^(\d+\.\d+\.\d+\.\d+)/) { # Looks like an IP address - must be same as value
345
            if ($1 eq $value) { # Keep some order in registrations
346
                $name = "$value.$dnssubdomain"; # The way we format initial registrations
347
            } else {
348
                $name = '';
349
            }
350
        }
351
    }
352 95b003ff Origo
    # Only allow creation of records corresponding to user's own networks when username is supplied
353
    # When username is not supplied, we assume checking has been done
354
    if ($username) {
355
        my $checkval = $value;
356 e9af6c24 Origo
        # Remove any trailing period
357 95b003ff Origo
        $checkval = $1 if ($checkval =~ /(.+)\.$/);
358 6fdc8676 hq
        if ($type eq 'TXT') {
359
            $checkval = '';
360
        } elsif ($type eq 'A') {
361 95b003ff Origo
            $checkval = $value;
362
        } else {
363 e9af6c24 Origo
            $checkval = $1 if ($checkval =~ /(\d+\.\d+\.\d+\.\d+)\.$dnssubdomain\.$dnsdomain$/);
364 95b003ff Origo
            $checkval = $1 if ($checkval =~ /(\d+\.\d+\.\d+\.\d+)\.$dnsdomain$/);
365 e9af6c24 Origo
            $checkval = $1 if ($checkval =~ /(\d+\.\d+\.\d+\.\d+)$/);
366 95b003ff Origo
        }
367
        if ($checkval) {
368
            unless (tie %networkreg,'Tie::DBI', {
369
                    db=>'mysql:steamregister',
370
                    table=>'networks',
371
                    key=>'uuid',
372
                    autocommit=>0,
373
                    CLOBBER=>0,
374
                    user=>$dbiuser,
375
                    password=>$dbipasswd}) {throw Error::Simple("Error Register could not be accessed")};
376
            my @regkeys = (tied %networkreg)->select_where("externalip = '$checkval'");
377
            if (scalar @regkeys == 1) {
378 04c16f26 hq
                if ($register{$regkeys[0]} && $register{$regkeys[0]}->{'user'} eq $username) {
379 95b003ff Origo
                    ; # OK
380
                } else {
381 eb31fb38 hq
                    return qq|{"status": "Error", "message": "Invalid value $checkval, not allowed"}|;
382 95b003ff Origo
                }
383
            } elsif (scalar @regkeys >1) {
384 eb31fb38 hq
                return qq|{"status": "Error", "message": "Invalid value $checkval"}|;
385 95b003ff Origo
            }
386
            untie %networkreg;
387 e9af6c24 Origo
            if ($type eq 'A') {
388 6fdc8676 hq
#                $name = "$checkval.$dnssubdomain"; # Only allow this type of A-records...?
389 e9af6c24 Origo
            } else {
390
                $value = "$checkval.$dnssubdomain";
391
            }
392 95b003ff Origo
        }
393
    }
394
395 6fdc8676 hq
    if ($type ne 'MX' && $type ne 'TXT' && `host $name.$dnsdomain authns1.cabocomm.dk` =~ /has address/) {
396 eb31fb38 hq
        return qq|{"status": "Error", "message": "$name is already registered"}|;
397 e9af6c24 Origo
    };
398
399 95b003ff Origo
    if ($enginelinked && $name && $value) {
400
        require LWP::Simple;
401
        my $browser = LWP::UserAgent->new;
402
        $browser->agent('Stabile/1.0b');
403
        $browser->protocols_allowed( [ 'http','https'] );
404
        $browser->timeout(10);
405
        my $tktcfg = ConfigReader::Simple->new($Stabile::auth_tkt_conf, [qw(TKTAuthSecret)]);
406
        my $tktkey = $tktcfg->get('TKTAuthSecret') || '';
407
        my $tkthash = sha512_hex($tktkey);
408
        my $posturl = "https://www.origo.io/irigo/engine.cgi?action=dnscreate";
409
410
        my $async = HTTP::Async->new;
411
        my $post = POST $posturl,
412 6fdc8676 hq
            [ engineid        => $engineid,
413 95b003ff Origo
                enginetkthash => $tkthash,
414 6fdc8676 hq
                name          => $name,
415
                domain        => $dnsdomain,
416
                value         => $value,
417
                type          => $type,
418
                username      => $username || $user
419 95b003ff Origo
            ];
420
        # We fire this asynchronously and hope for the best. Waiting for an answer is just too erratic for now
421
        $async->add( $post );
422
423
        if ($username) {
424
            my $response;
425
            while ( $response = $async->wait_for_next_response ) {
426
                $ret .= $response->decoded_content;
427
            }
428
            foreach my $line (split /\n/, $ret) {
429
               $res .= $line unless ($line =~ /^\d/);
430
            }
431
        }
432 eb31fb38 hq
    #    $res =~ s/://g;
433 3657de20 Origo
        return "$res\n";
434 95b003ff Origo
435
    } else {
436 eb31fb38 hq
        return qq|{"status": "Error", "message": "Problem creating dns record with data $name, $value.| . ($enginelinked?"":" Engine is not linked!") . qq|"}|;
437 95b003ff Origo
    }
438
};
439
440
$main::dnsDelete = sub {
441 ca937547 hq
    my ($engineid, $name, $value, $type, $username) = @_;
442 e9af6c24 Origo
    my $dnssubdomain = substr($engineid, 0, 8);
443 afc024ef hq
    $name = $1 if ($name =~ /(.+)\.$dnsdomain$/);
444
#    $name =$1 if ($name =~ /(.+)\.$dnssubdomain/);
445 ca937547 hq
    if ($name =~ /^(\d+\.\d+\.\d+\.\d+)$/) {
446
        $name = "$1.$dnssubdomain";
447
        $type = $type || 'A';
448 95b003ff Origo
    }
449
450 ca937547 hq
    $main::syslogit->($user, "info", "Deleting DNS entry $type $name $dnsdomain");
451 95b003ff Origo
    if ($enginelinked && $name) {
452
        require LWP::Simple;
453
        my $browser = LWP::UserAgent->new;
454
        $browser->agent('Stabile/1.0b');
455
        $browser->protocols_allowed( [ 'http','https'] );
456
        my $tktcfg = ConfigReader::Simple->new($Stabile::auth_tkt_conf, [qw(TKTAuthSecret)]);
457
        my $tktkey = $tktcfg->get('TKTAuthSecret') || '';
458
        my $tkthash = sha512_hex($tktkey);
459
        my $posturl = "https://www.origo.io/irigo/engine.cgi?action=dnsdelete";
460
461
        my $postreq = ();
462
        $postreq->{'engineid'} = $engineid;
463
        $postreq->{'enginetkthash'} = $tkthash;
464
        $postreq->{'name'} = $name;
465 ca937547 hq
        $postreq->{'value'} = $value;
466
        $postreq->{'type'} = $type;
467 6fdc8676 hq
        $postreq->{'username'} = $username || $user;
468
        $postreq->{'domain'} = "$dnsdomain";
469 95b003ff Origo
        $content = $browser->post($posturl, $postreq)->content();
470 eb31fb38 hq
    #    $content =~ s/://g;
471 95b003ff Origo
        return $content;
472
    } else {
473
        return "ERROR Invalid data $name." . ($enginelinked?"":" Engine is not linked!") . "\n";
474
    }
475
};
476
477 48fcda6b Origo
$main::dnsUpdate = sub {
478 eb31fb38 hq
    my ($engineid, $name, $value, $type, $oldname, $oldvalue, $username) = @_;
479 48fcda6b Origo
    $name = $1 if ($name =~ /(.+)\.$dnsdomain/);
480 eb31fb38 hq
    $type = uc $type;
481
    $type || 'CNAME';
482 48fcda6b Origo
483
    # Only allow deletion of records corresponding to user's own networks when username is supplied
484
    # When username is not supplied, we assume checking has been done
485 eb31fb38 hq
    # Obsolete
486
    # my $checkval;
487
    # if ($username) {
488
    #     if ($name =~ /\d+\.\d+\.\d+\.\d+/) {
489
    #         $checkval = $name;
490
    #     } else {
491
    #         my $checkname = $name;
492
    #         # Remove trailing period
493
    #         $checkname = $1 if ($checkname =~ /(.+)\.$/);
494
    #         $checkname = "$checkname.$dnsdomain" unless ($checkname =~ /(.+)\.$dnsdomain$/);
495
    #         $checkval = $1 if (`host $checkname authns1.cabocomm.dk` =~ /has address (\d+\.\d+\.\d+\.\d+)/);
496
    #         return "ERROR Invalid value $checkname\n" unless ($checkval);
497
    #     }
498
    #
499
    #     unless (tie %networkreg,'Tie::DBI', {
500
    #         db=>'mysql:steamregister',
501
    #         table=>'networks',
502
    #         key=>'uuid',
503
    #         autocommit=>0,
504
    #         CLOBBER=>0,
505
    #         user=>$dbiuser,
506
    #         password=>$dbipasswd}) {throw Error::Simple("Error Register could not be accessed")};
507
    #     my @regkeys = (tied %networkreg)->select_where("externalip = '$checkval' OR internalip = '$checkval'");
508
    #     if ($isadmin || (scalar @regkeys == 1 && $register{$regkeys[0]}->{'user'} eq $username)) {
509
    #         ; # OK
510
    #     } else {
511
    #         return "ERROR Invalid user for $checkval, not allowed\n";
512
    #     }
513
    #     untie %networkreg;
514
    # }
515 48fcda6b Origo
516
    $main::syslogit->($user, "info", "Updating DNS entries for $name $dnsdomain");
517
    if ($enginelinked && $name) {
518
        require LWP::Simple;
519
        my $browser = LWP::UserAgent->new;
520
        $browser->agent('Stabile/1.0b');
521
        $browser->protocols_allowed( [ 'http','https'] );
522
        my $tktcfg = ConfigReader::Simple->new($Stabile::auth_tkt_conf, [qw(TKTAuthSecret)]);
523
        my $tktkey = $tktcfg->get('TKTAuthSecret') || '';
524
        my $tkthash = sha512_hex($tktkey);
525
        my $posturl = "https://www.origo.io/irigo/engine.cgi?action=dnsupdate";
526
527
        my $postreq = ();
528
        $postreq->{'engineid'} = $engineid;
529
        $postreq->{'enginetkthash'} = $tkthash;
530
        $postreq->{'name'} = $name;
531 eb31fb38 hq
        $postreq->{'value'} = $value;
532
        $postreq->{'type'} = $type;
533
        $postreq->{'oldname'} = $oldname if ($oldname);
534
        $postreq->{'oldvalue'} = $oldvalue if ($oldvalue);
535 6fdc8676 hq
        $postreq->{'username'} = $username || $user;
536 48fcda6b Origo
        $postreq->{'domain'} = $dnsdomain;
537
        $content = $browser->post($posturl, $postreq)->content();
538
        return $content;
539
    } else {
540
        return "ERROR Invalid data $name." . ($enginelinked?"":" Engine is not linked!") . "\n";
541
    }
542
};
543
544 e9af6c24 Origo
$main::dnsList = sub {
545 eb31fb38 hq
    my ($engineid, $username, $domain) = @_;
546 e9af6c24 Origo
    if ($enginelinked) {
547
        require LWP::Simple;
548
        my $browser = LWP::UserAgent->new;
549
        $browser->agent('Stabile/1.0b');
550
        $browser->protocols_allowed( [ 'http','https'] );
551
        my $tktcfg = ConfigReader::Simple->new($Stabile::auth_tkt_conf, [qw(TKTAuthSecret)]);
552
        my $tktkey = $tktcfg->get('TKTAuthSecret') || '';
553
        my $tkthash = sha512_hex($tktkey);
554
        my $posturl = "https://www.origo.io/irigo/engine.cgi?action=dnslist";
555 eb31fb38 hq
        $domain = $domain || $dnsdomain;
556 e9af6c24 Origo
557
        my $postreq = ();
558
        $postreq->{'engineid'} = $engineid;
559
        $postreq->{'enginetkthash'} = $tkthash;
560 eb31fb38 hq
        $postreq->{'domain'} = $domain;
561 6fdc8676 hq
        $postreq->{'username'} = $username || $user;
562 e9af6c24 Origo
        $content = $browser->post($posturl, $postreq)->content();
563 eb31fb38 hq
    #    $content =~ s/://g;
564 e9af6c24 Origo
        return $content;
565
    } else {
566
        return "ERROR Engine is not linked!\n";
567
    }
568
};
569
570
$main::dnsClean = sub {
571
    my ($engineid, $username) = @_;
572
    if ($enginelinked) {
573
        require LWP::Simple;
574
        my $browser = LWP::UserAgent->new;
575
        $browser->agent('Stabile/1.0b');
576
        $browser->protocols_allowed( [ 'http','https'] );
577
        my $tktcfg = ConfigReader::Simple->new($Stabile::auth_tkt_conf, [qw(TKTAuthSecret)]);
578
        my $tktkey = $tktcfg->get('TKTAuthSecret') || '';
579
        my $tkthash = sha512_hex($tktkey);
580
        my $posturl = "https://www.origo.io/irigo/engine.cgi?action=dnsclean";
581
        my $postreq = ();
582
        $postreq->{'engineid'} = $engineid;
583
        $postreq->{'enginetkthash'} = $tkthash;
584
        $postreq->{'domain'} = $dnsdomain;
585
        $content = $browser->post($posturl, $postreq)->content();
586
        $content =~ s/://g;
587
        return $content;
588
    } else {
589
        return "ERROR Engine is not linked!\n";
590
    }
591
};
592
593 95b003ff Origo
$main::xmppSend = sub {
594
    my ($to, $msg, $engineid, $sysuuid) = @_;
595
    $engineid = `cat /etc/stabile/config.cfg | sed -n -e 's/^ENGINEID=//p'` unless ($engineid);
596
    my $doxmpp = `cat /etc/stabile/config.cfg | sed -n -e 's/^DO_XMPP=//p'`;
597
    if (!$doxmpp) {
598
        return "INFO: DO_XMPP not enabled in config\n";
599
600
    } elsif ($to && $msg) {
601
        my $xdom;
602
        $xdom = $1 if ($to =~ /\@(.+)$/);
603
        if ($xdom && `host -t SRV _xmpp-server._tcp.$xdom` !~ /NXDOMAIN/) {
604
            require LWP::Simple;
605
            my $browser = LWP::UserAgent->new;
606
            $browser->agent('Stabile/1.0b');
607
            $browser->protocols_allowed( [ 'http','https'] );
608
            $browser->timeout(10);
609
            my $tktcfg = ConfigReader::Simple->new($Stabile::auth_tkt_conf, [qw(TKTAuthSecret)]);
610
            my $tktkey = $tktcfg->get('TKTAuthSecret') || '';
611
            my $tkthash = sha512_hex($tktkey);
612
            my $posturl = "https://www.origo.io/irigo/engine.cgi?action=xmppsend";
613
614
            my $async = HTTP::Async->new;
615
            my $post = POST $posturl,
616
                [   engineid => $engineid,
617
                    enginetkthash => $tkthash,
618
                    sysuuid => $sysuuid,
619
                    to => $to,
620
                    msg => $msg
621
                ];
622
            $async->add( $post );
623
624
            #my $postreq = ();
625
            #$postreq->{'engineid'} = $engineid;
626
            #$postreq->{'enginetkthash'} = $tkthash;
627
            #$postreq->{'to'} = $to;
628
            #$postreq->{'msg'} = $msg;
629
            #$content = $browser->post($posturl, $postreq)->content();
630
631
            return "Status=OK Sent xmpp message to $to\n";
632
        } else {
633
            return "Status=ERROR XMPP srv records not found for domain \"$xdom\"\n";
634
        }
635
636
    } else {
637
        return "Status=ERROR Invalid xmpp data $to, $msg\n";
638
    }
639
};
640
641 2a63870a Christian Orellana
# Enumerate and return network interfaces
642
$main::getNics = sub {
643
    my $internalnic = $Stabile::config->get('ENGINE_DATA_NIC');
644
    my $externalnic = $Stabile::config->get('EXTERNAL_NIC');
645
    if (!$externalnic) {
646
        my $droute = `ip route show default`;
647
        $externalnic = $1 if ($droute =~ /default via .+ dev (.+) proto/);
648
    }
649
    my @nics = ();
650
    if (!$externalnic || !$internalnic) {
651
        my $niclist = `ifconfig | grep flags= | sed -n -e 's/: .*//p'`;
652
        if (-e "/mnt/stabile/tftp/bionic") { # If a piston root exists, assume we will be providing boot services over secondary NIC even if it has no link
653
            $niclist = `ifconfig -a | grep flags= | sed -n -e 's/: .*//p'`;
654
        }
655
        # my $niclist = `netstat -in`;
656
        push @nics, $externalnic if ($externalnic);
657
        foreach my $line (split("\n", $niclist)) {
658
            if ($line =~ /^(\w+)$/) {
659
                my $nic = $1;
660
                push(@nics, $nic) if ($nic ne 'lo' && $nic ne $externalnic && !($nic=~/^virbr/) && !($nic=~/^docker/) && !($nic=~/^br/) && !($nic=~/^vnet/) && !($nic=~/^Name/) && !($nic=~/^Kernel/) && !($nic=~/^Iface/) && !($nic=~/(\.|\:)/));
661
            }
662
        }
663
    }
664
    $externalnic = $externalnic || $nics[0];
665
    $internalnic = $internalnic || $nics[1] || $externalnic;
666 f222b89c hq
    # We're dealing with a wlan interface, we are probably on a laptop
667
    if ($internalnic =~ /^wl/ && !$Stabile::config->get('EXTERNAL_NIC')) {
668
        $internalnic = $externalnic; # It's very unlikely that we would want to server nfs over wlan
669 f4b82f15 hq
    }
670 2a63870a Christian Orellana
    return ($internalnic, $externalnic);
671
};
672
673 95b003ff Origo
$main::updateUI = sub {
674
    my @parslist = @_;
675
    my $newtasks;
676
    my $tab;
677
    my $duser;
678
    foreach my $pars (@parslist) {
679
        my $type = $pars->{type};
680
        my $duuid = $pars->{uuid};
681
        my $domuuid = $pars->{domuuid};
682
        my $dstatus = $pars->{status};
683
        my $message = $pars->{message};
684 48fcda6b Origo
        $message =~ s/"/\\"/g;
685
        $message =~ s/'/\\'/g;
686 95b003ff Origo
        my $newpath = $pars->{newpath};
687
        my $displayip = $pars->{displayip};
688
        my $displayport = $pars->{displayport};
689
        my $name = $pars->{name};
690
        my $master = $pars->{master};
691
        my $mac = $pars->{mac};
692
        my $macname = $pars->{macname};
693
        my $progress = $pars->{progress};
694
        my $title = $pars->{title};
695
        my $managementlink = $pars->{managementlink};
696
        my $backup = $pars->{backup};
697 2a63870a Christian Orellana
        my $download = $pars->{download};
698
        my $size = $pars->{size};
699 95b003ff Origo
        my $sender = $pars->{sender};
700
        my $path = $pars->{path};
701
        my $snap1 = $pars->{snap1};
702
        my $username = $pars->{username};
703
704
        $tab = $pars->{tab};
705
        $duser = $pars->{user};
706
        $duser = "irigo" if ($duser eq "--");
707
        $tab = $tab || substr(lc __PACKAGE__, 9);
708
        $type = $type || ($message?'message':'update');
709
        $sender = $sender || "stabile:$package";
710
711
        if ($package eq 'users' && $pars->{'uuid'}) {
712
            my %u = %{$register{$pars->{'uuid'}}};
713
            delete $u{'password'};
714
            $u{'user'} = $duser;
715
            $u{'type'} = 'update';
716
            $u{'status'} = ($u{'privileges'} =~ /d/)?'disabled':'enabled';
717
            $u{'tab'} = $package;
718
            $u{'timestamp'} = $current_time;
719
            $newtasks .= to_json(\%u) . ", ";
720
        } else {
721
            $newtasks .= "{\"type\":\"$type\",\"tab\":\"$tab\",\"timestamp\":$current_time" .
722
                ($duuid?",\"uuid\":\"$duuid\"":"") .
723
                ($domuuid?",\"domuuid\":\"$domuuid\"":"") .
724
                ($duser?",\"user\":\"$duser\"":"") .
725
                ($dstatus?",\"status\":\"$dstatus\"":"") .
726
                ($message?",\"message\":\"$message\"":"") .
727
                ($newpath?",\"path\":\"$newpath\"":"") .
728
                ($displayip?",\"displayip\":\"$displayip\"":"") .
729
                ($displayport?",\"displayport\":\"$displayport\"":"") .
730
                ($name?",\"name\":\"$name\"":"") .
731
                ($backup?",\"backup\":\"$backup\"":"") .
732 2a63870a Christian Orellana
                ($download?",\"download\":\"$download\"":"") .
733
                ($size?",\"size\":\"$size\"":"") .
734 95b003ff Origo
                ($mac?",\"mac\":\"$mac\"":"") .
735
                ($macname?",\"macname\":\"$macname\"":"") .
736
                ($progress?",\"progress\":$progress":"") . # This must be a number between 0 and 100
737
                ($title?",\"title\":\"$title\"":"") .
738
                ($managementlink?",\"managementlink\":\"$managementlink\"":"") .
739
                ($master?",\"master\":\"$master\"":"") .
740
                ($snap1?",\"snap1\":\"$snap1\"":"") .
741
                ($username?",\"username\":\"$username\"":"") .
742 48fcda6b Origo
                ($path?",\"path\":\"$path\"":"") .
743
                ",\"sender\":\"$sender\"}, ";
744 95b003ff Origo
        }
745
    }
746
    $newtasks = $1 if ($newtasks =~ /(.+)/); #untaint
747
    my $res;
748
    eval {
749
        opendir my($dh), '/tmp' or die "Couldn't open '/tmp': $!";
750
        my @files;
751
        if ($tab eq 'nodes' || $duser eq 'irigo') {
752
            # write tasks to all admin user's session task pipes
753
            @files = grep { /.*~A-.*\.tasks$/ } readdir $dh;
754
        } else {
755
            # write tasks to all the user's session task pipes
756
            @files = grep { /^$duser~.*\.tasks$/ } readdir $dh;
757
        }
758
        closedir $dh;
759
        my $t = new Proc::ProcessTable;
760
        my @ptable = @{$t->table};
761
        my @pfiles;
762
        my $cmnds;
763
        foreach my $f (@files) {
764
#            my $n = `pgrep -fc "$f"`;
765
#            chomp $n;
766
            foreach my $p ( @ptable ){
767
                my $pcmd = $p->cmndline;
768
                $cmnds .= $pcmd . "\n" if ($pcmd =~ /tmp/);
769
                if ($pcmd =~ /\/tmp\/$f/) { # Only include pipes with active listeners
770
                    push @pfiles, "/tmp/$f";
771
                    last;
772
                }
773
            }
774
        };
775
        my $tasksfiles = join(' ', @pfiles);
776
        $tasksfiles = $1 if ($tasksfiles =~ /(.+)/); #untaint
777
        # Write to users named pipes if user is logged in and session file found
778
        if ($tasksfiles) {
779
            $res = `/bin/echo \'$newtasks\' | /usr/bin/tee  $tasksfiles \&`;
780
        } else {
781
        # If session file not found, append to orphan tasks file wait a sec and reload
782
            $res = `/bin/echo \'$newtasks\' >> /tmp/$duser.tasks`;
783
            $res .= `chown www-data:www-data /tmp/$duser.tasks`;
784
#            sleep 1;
785
            eval {`/usr/bin/pkill -HUP -f ui_update`; 1;} or do {;};
786 ca937547 hq
#            `echo "duh: $duser" >> /tmp/duh`;
787 95b003ff Origo
        }
788
#        eval {`/usr/bin/pkill -HUP -f $duser~ui_update`; 1;} or do {;};
789
    } or do {$e=1; $res .= "ERROR Problem writing to tasks pipe $@\n";};
790
    return 1;
791
};
792
793
sub action {
794
    my ($target, $action, $obj) = @_;
795
    my $res;
796
    my $func = ucfirst $action;
797
    # If a function named $action (with first letter uppercased) exists, call it and return the result
798
    if (defined &{$func}) {
799
        $res .= &{$func}($target, $action, $obj);
800
    }
801
    return $res;
802
}
803
804
sub privileged_action {
805
    my ($target, $action, $obj) = @_;
806
    return "Status=ERROR Your account does not have the necessary privileges\n" if ($isreadonly);
807
    return action($target, $action) if ($help);
808
    my $res;
809
    $obj = {} unless ($obj);
810
    $obj->{'console'} = 1 if ($console || $options{c});
811 2a63870a Christian Orellana
    $obj->{'baseurl'} =  $baseurl if ($baseurl);
812 95b003ff Origo
    my $client = Gearman::Client->new;
813
    $client->job_servers('127.0.0.1:4730');
814
    # Gearman server will try to call a method named "do_gear_$action"
815
    $res = $client->do_task(steamexec => freeze({package=>$package, tktuser=>$tktuser, user=>$user, target=>$target, action=>$action, args=>$obj}));
816
    $res = ${ $res };
817
    return $res;
818
}
819
820
sub privileged_action_async {
821
    my ($target, $action, $obj) = @_;
822
    return "Status=ERROR Your account does not have the necessary privileges\n" if ($isreadonly);
823
    return action($target, $action) if ($help);
824
    my $client = Gearman::Client->new;
825
    $client->job_servers('127.0.0.1:4730');
826
    my $tasks = $client->new_task_set;
827
    $obj = {} unless ($obj);
828
    $obj->{'console'} = 1 if ($console || $options{c});
829
    # Gearman server will try to call a method named "do_gear_$action"
830 a2e0bc7e hq
    if (scalar(keys %{$obj}) > 2) {
831 95b003ff Origo
        my $handle = $tasks->add_task(steamexec => freeze({package=>$package, tktuser=>$tktuser, user=>$user, target=>$target, action=>$action, args=>$obj}));
832
    } else {
833
        my $handle = $tasks->add_task(steamexec => freeze({package=>$package, tktuser=>$tktuser, user=>$user, target=>$target, action=>$action}));
834
    }
835
    my $regtarget = $register{$target};
836
    my $imgregtarget = $imagereg{$target};
837 d24d9a01 hq
    $uistatus = $regtarget->{status} || "$action".'ing';
838 95b003ff Origo
    $uistatus = 'cloning' if ($action eq 'clone');
839
    $uistatus = 'snapshotting' if ($action eq 'snapshot');
840
    $uistatus = 'unsnapping' if ($action eq 'unsnap');
841
    $uistatus = 'mastering' if ($action eq 'master');
842
    $uistatus = 'unmastering' if ($action eq 'unmaster');
843
    $uistatus = 'backingup' if ($action eq 'backup');
844
    $uistatus = 'restoring' if ($action eq 'restore');
845
    $uistatus = 'saving' if ($action eq 'save');
846
    $uistatus = 'venting' if ($action eq 'releasepressure');
847 04c16f26 hq
    $uistatus = 'injecting' if ($action eq 'inject');
848 95b003ff Origo
    my $name = $regtarget->{name} || $imgregtarget->{name};
849
    if ($action eq 'save') {
850
        if ($package eq 'images') {
851
            if ($obj->{status} eq 'new') {
852
                $obj->{status} = 'unused';
853
            }
854
            elsif ($obj->{regstoragepool} ne $obj->{storagepool}) {
855 d24d9a01 hq
                $obj->{'status'} = $uistatus = 'moving';
856 95b003ff Origo
            }
857
        }
858
        $postreply = to_json($obj, {pretty=>1});
859
        $postreply = encode('utf8', $postreply);
860
        $postreply =~ s/""/"--"/g;
861
        $postreply =~ s/null/"--"/g;
862
        $postreply =~ s/"notes" {0,1}: {0,1}"--"/"notes":""/g;
863
        $postreply =~ s/"installable" {0,1}: {0,1}"(true|false)"/"installable":$1/g;
864
        return $postreply;
865
    } else {
866
        return "Status=$uistatus OK $action $name (deferred)\n";
867
    }
868
}
869
870
sub do_gear_action {
871
    my ($target, $action ,$obj) = @_;
872
    $target = encode("iso-8859-1", $target); # MySQL uses Latin1 as default charset
873
    $action = $1 if ($action =~ /gear_(.+)/);
874
    my $res;
875
    return "This only works with elevated privileges\n" if ($>);
876 9d03439e hq
    if ($register{$target}
877
        || $action =~ /all$|save|^monitors|^packages|^changemonitoremail|^buildsystem|^removesystem|^updateaccountinfo|^updateengineinfo|^removeusersystems|^removeuserimages/
878
        || $action =~ /^updateamtinfo|^updatedownloads|^releasepressure|linkmaster$|activate$|engine$|^syncusers|^deletesystem|^getserverbackups|^listserverbackups|^fullstats/
879 14fd7cc5 hq
        || $action =~ /^zbackup|^updateallbtimes|^initializestorage|^liststoragedevices|^getbackupdevice|^getimagesdevice|^listbackupdevices|^listimagesdevices/
880 f222b89c hq
        || $action =~ /^setstoragedevice|^updateui|configurecgroups|backup|sync_backup|^snapshot|^unsnap|downloadmaster/
881 95b003ff Origo
        || ($action eq 'remove' && $package eq 'images' && $target =~ /\.master\.qcow2$/) # We allow removing master images by name only
882 d3805c61 hq
        || ($action eq 'remove' && $package eq 'images' && $target =~ /^(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/) # We allow removing images by uuid also
883 95b003ff Origo
    ) {
884
        my $func = ucfirst $action;
885
        # If a function named $action (with first letter uppercased) exists, call it and return the result
886
        if (defined &{$func}) {
887
            if ($obj) {
888
                $console = $obj->{'console'} if ($obj->{'console'});
889
                $target = $obj->{uuid} if (!$target && $obj->{uuid}); # backwards compat with apps calling removesystem
890
                $res .= &{$func}($target, $action, $obj);
891
            } else {
892
                $res .= &{$func}($target, $action);
893
            }
894
        } else {
895
            $res .= "Status=ERROR Unable to $action $target - function not found in $package\n";
896
        }
897
    } else {
898
        $res .= "Status=ERROR Unable to $action $target - target not found in $package\n";
899
    }
900
    return $res;
901
}
902
903
sub preInit {
904
# Set global vars: $user, $tktuser, $curuuid and if applicable: $curdomuuid, $cursysuuid, $curimg
905
# Identify and validate user, read user prefs from DB
906 48fcda6b Origo
    unless ( tie(%userreg,'Tie::DBI', Hash::Merge::merge({table=>'users', key=>'username'}, $Stabile::dbopts)) ) {throw Error::Simple("Status=Error User register could not be  accessed")};
907 95b003ff Origo
908
    $user = $user || $Stabile::user || $ENV{'REMOTE_USER'};
909
    $user = 'irigo' if ($package eq 'steamexec');
910
    $remoteip = $ENV{'REMOTE_ADDR'};
911
    # If request is coming from a running server from an internal ip, identify user requesting access
912
    if (!$user && $remoteip && $remoteip =~ /^10\.\d+\.\d+\.\d+/) {
913 48fcda6b Origo
        unless ( tie(%networkreg,'Tie::DBI', Hash::Merge::merge({table=>'networks', CLOBBER=>3}, $Stabile::dbopts)) ) {throw Error::Simple("Status=Error Network register could not be accessed")};
914
        unless ( tie(%domreg,'Tie::DBI', Hash::Merge::merge({table=>'domains', CLOBBER=>3}, $Stabile::dbopts)) ) {throw Error::Simple("Status=Error Domain register could not be accessed")};
915 95b003ff Origo
        my @regkeys = (tied %networkreg)->select_where("internalip = '$remoteip'");
916
        foreach my $k (@regkeys) {
917
            my $network = $networkreg{$k};
918
            my @domregkeys = (tied %domreg)->select_where("networkuuid1 = '$network->{uuid}'");
919
            my $dom = $domreg{$network->{'domains'}} || $domreg{$domregkeys[0]}; # Sometimes domains is lost in network - compensate
920
            # Request is coming from a running server from an internal ip - accept
921
            if ($network->{'internalip'} eq $remoteip) {
922
                $user = $network->{'user'};
923
                # my $dom = $domreg{$network->{'domains'}};
924
                if ($package eq 'networks') {
925
                    $curuuid = $network->{'uuid'};
926
                    $curdomuuid = $network->{'domains'};
927
                    $cursysuuid = $dom->{'system'};
928
                } elsif ($package eq 'images') {
929
                    $curimg = $dom->{'image'} unless ($curimg);
930
                } elsif ($package eq 'systems') {
931
                    $curuuid = $dom->{'system'} || $dom->{'uuid'} unless ($curuuid);
932
                    $cursysuuid = $dom->{'system'};
933
                    $curdomuuid = $dom->{'uuid'};
934
                } elsif ($package eq 'servers') {
935
                    $curuuid = $dom->{'uuid'} unless ($curuuid);
936
                    $cursysuuid = $dom->{'system'};
937
                }
938
                if (!$userreg{$user}->{'allowinternalapi'}) {
939
                    $user = ''; # Internal API access is not enabled, disallow access
940
                }
941
                last;
942
            }
943
        }
944
        untie %networkreg;
945
        untie %domreg;
946 705b5366 hq
    } else { # Check authorized referers to mitigate CSRF attacks. If no referer in ENV we let it pass to allow API access.
947
        if (-e "/etc/stabile/basereferers"
948
            && $ENV{HTTP_REFERER}
949
        ) {
950
            my $basereferers = `cat /etc/stabile/basereferers`;
951
            chomp $basereferers;
952
            my @baserefs = split(/\s+/, $basereferers);
953
            my $match = 0;
954
            foreach my $ref (@baserefs) {
955
                if ($ENV{HTTP_REFERER} =~ /$ref/) {
956
                    $match = 1;
957
                    last;
958
                }
959
            }
960
            $user = '' unless ($match);
961
        }
962 95b003ff Origo
    }
963
    $user = $1 if $user =~ /(.+)/; #untaint
964
    $tktuser = $user;
965
    $Stabile::tktuser = $tktuser;
966
967
    # Initalize CGI
968
    $Stabile::q = new CGI;
969
970
    # Load params
971
    %params = $Stabile::q->Vars;
972
    $uripath = URI::Escape::uri_unescape($ENV{'REQUEST_URI'});
973
    if ($options{s}) {
974
        $account = $options{s};
975
    } else {
976
        $account = $Stabile::q->cookie('steamaccount');
977
    }
978
    $user = 'guest' if (!$user && $params{'action'} eq 'help');
979
    die "No active user. Please authenticate or provide user through REMOTE_USER environment variable." unless ($user);
980
981
    my $u = $userreg{$user};
982
    my @accounts = split(/,\s*/, $u->{'accounts'}) if ($u->{'accounts'});
983
    my @accountsprivs = split(/,\s*/, $u->{'accountsprivileges'}) if ($u->{'accountsprivileges'});
984
    for my $i (0 .. $#accounts)
985
        { $ahash{$accounts[$i]} = $accountsprivs[$i] || 'r'; }
986
987
	$privileges = '';
988
    # User is requesting access to another account - check privs
989
    if ($account && $account ne $user) {
990
        if ($ahash{$account}) {
991
            $user = $account;
992
            $main::account = $account;
993
            # Only allow users whose base account is admin to get admin privs
994
            $ahash{$account} =~ s/a// unless ($userreg{$tktuser}->{'privileges'} =~ /a/);
995
            $privileges = $ahash{$account};
996
            $u = $userreg{$account};
997
        }
998
    }
999
1000
    $Stabile::user = $user;
1001
1002
    $defaultmemoryquota = $Stabile::config->get('MEMORY_QUOTA') + 0;
1003
    $defaultstoragequota = $Stabile::config->get('STORAGE_QUOTA') + 0;
1004
    $defaultnodestoragequota = $Stabile::config->get('NODESTORAGE_QUOTA') + 0;
1005
    $defaultvcpuquota = $Stabile::config->get('VCPU_QUOTA') + 0;
1006
    $defaultexternalipquota = $Stabile::config->get('EXTERNAL_IP_QUOTA') + 0;
1007
    $defaultrxquota = $Stabile::config->get('RX_QUOTA') + 0;
1008
    $defaulttxquota = $Stabile::config->get('TX_QUOTA') + 0;
1009
1010
    # Read quotas and privileges from db
1011
    $Stabile::userstoragequota = 0+ $u->{'storagequota'} if ($u->{'storagequota'});
1012
    $Stabile::usernodestoragequota = 0+ $u->{'nodestoragequota'} if ($u->{'storagequota'});
1013 a2e0bc7e hq
    $Stabile::usermemoryquota = 0+ $u->{'memoryquota'} if ($u->{'memoryquota'});
1014
    $Stabile::uservcpuquota = 0+ $u->{'vcpuquota'} if ($u->{'vcpuquota'});
1015 54401133 hq
    $Stabile::userexternalipquota = 0+ $u->{'externalipquota'} if ($u->{'externalipquota'});
1016
    $Stabile::userrxquota = 0+ $u->{'rxquota'} if ( $u->{'rxquota'});
1017
    $Stabile::usertxquota = 0+ $u->{'txquota'} if ($u->{'txquota'});
1018 95b003ff Origo
1019
    $billto = $u->{'billto'};
1020
    $Stabile::userprivileges = $u->{'privileges'};
1021
    $privileges = $Stabile::userprivileges if (!$privileges && $Stabile::userprivileges);
1022
    $isadmin = index($privileges,"a")!=-1;
1023
    $ismanager = index($privileges,"m")!=-1;
1024
    $isreadonly = index($privileges,"r")!=-1;
1025 d3805c61 hq
    $Stabile::preserveimagesonremove = index($privileges,"p")!=-1;
1026 95b003ff Origo
    $fulllist = $options{f} && $isadmin;
1027
    $fullupdate = $options{p} && $isadmin;
1028
1029 71b897d3 hq
    my $bto = $userreg{$billto};
1030
    my @bdnsdomains = split(/, ?/, $bto->{'dnsdomains'});
1031
    my @udnsdomains = split(/, ?/, $u->{'dnsdomains'});
1032 23748604 hq
    $dnsdomain = '' if ($dnsdomain eq '--'); # TODO - ugly
1033
    $udnsdomains[0] = '' if ($udnsdomains[0] eq '--');
1034
    $bdnsdomains[0] = '' if ($bdnsdomains[0] eq '--');
1035 45cc3024 hq
    $dnsdomain = $udnsdomains[0] || $bdnsdomains[0] || $dnsdomain; # override config value
1036
1037
    my $bstoreurl = $bto->{'appstoreurl'};
1038 23748604 hq
    $bstoreurl = '' if ($bstoreurl eq '--');
1039 45cc3024 hq
    my $ustoreurl = $u->{'appstoreurl'};
1040 23748604 hq
    $ustoreurl = '' if ($ustoreurl eq '--');
1041 45cc3024 hq
    $appstoreurl = $bstoreurl || $ustoreurl || $appstoreurl; # override config value
1042 71b897d3 hq
1043 95b003ff Origo
    $Stabile::sshcmd = $sshcmd;
1044
    $Stabile::disablesnat = $disablesnat;
1045
    $Stabile::privileges = $privileges;
1046
    $Stabile::isadmin = $isadmin;
1047
1048
    $storagepools = $u->{'storagepools'}; # Prioritized list of users storage pools as numbers, e.g. "0,2,1"
1049
    my $dbuser = $u->{'username'};
1050
    untie %userreg;
1051
1052
    # If params are passed in URI for a POST og PUT request, we try to parse them out
1053
     if (($ENV{'REQUEST_METHOD'} ne 'GET')  && !$isreadonly) {
1054
         $action = $1 if (!$action && $uripath =~ /action=(\w+)/);
1055
         if ($uripath =~ /$package(\.cgi)?\/(.+)$/ && !$isreadonly) {
1056
             my $uuid = $2;
1057
             if (!(%params) && !$curuuid && $uuid =~ /^\?/) {
1058
                 %params = split /[=&]/, substr($uuid,1);
1059
                 $curuuid = $params{uuid};
1060
             } else {
1061
                 $curuuid = $uuid;
1062
             }
1063
             $curuuid = $1 if ($curuuid =~ /\/(.+)/);
1064
         }
1065
     }
1066
1067
    # Parse out params from g option if called from cmdline
1068
    my $args = $options{g};
1069
    if ($args && !%params) {
1070
        my $obj = from_json( uri_unescape ($args));
1071 d3805c61 hq
        if ( ref($obj) eq 'HASH' && $obj->{items} ) {
1072
            %params = ();
1073
            $params{'POSTDATA'} = $args;
1074
        } elsif (ref($obj) eq 'HASH') {
1075 95b003ff Origo
            %params = %{$obj};
1076
        } else {
1077
            %params = {};
1078
            $params{'POSTDATA'} = $args;
1079
        }
1080
        $console = $obj->{'console'} if ($obj->{'console'});
1081
        $curuuid = $obj->{uuid} if (!$curuuid && $obj->{uuid}); # backwards compat with apps calling removesystem
1082
    }
1083
1084
    # Action may be via on command line switch -a
1085
    if (!$action) {
1086
        $action = $options{a};
1087
        if ($action) { # Set a few options if we are called from command line
1088
            $console = 1 unless ($options{v} && !$options{c});
1089
            $Data::Dumper::Varname = $package;
1090
            $Data::Dumper::Pair = ' : ';
1091
            $Data::Dumper::Terse = 1;
1092
            $Data::Dumper::Useqq = 1;
1093
        }
1094
    }
1095
    # Parse out $action - i.e. find out what action is requested
1096
    $action = $action || $params{'action'}; # $action may have been set above to 'remove' by DELETE request
1097
1098
    # Handling of action given as part of addressable API
1099
    # Special cases for systems, monitors, etc.
1100
    if (!$action && $uripath =~ /$package\/(.+)(\/|\?)/ && !$params{'path'}) {
1101
        $action = $1;
1102
        $action = $1 if ($action =~ /([^\/]+)\/(.*)/);
1103
    }
1104
    $curuuid = $curuuid || $params{'uuid'} || $params{'id'} || $params{'system'} || $params{'serveruuid'};
1105
    # Handling of target given as part of addressable API
1106
    #    if ($uripath =~ /$package(\.cgi)?\/($action\/)?(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})(:\w+)?/) {
1107
    if ($uripath =~ /$package\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})(:\w+)?/) {
1108
        $curuuid = "$1$2";
1109
    } elsif ($package eq 'nodes' && $uripath =~ /$package\/(\w{12})(:\w+)?/) {
1110
        $curuuid = "$1$2";
1111
    }
1112
1113
    $action = lc $action;
1114
    if (!$params && $options{k}) {
1115
        $params{'keywords'} = URI::Escape::uri_unescape($options{k});
1116
        $console = 1 unless ($options{v} && !$options{c});
1117
    }
1118 d3d1a2d4 Origo
    $action = (($action)?$action.'_':'') . 'remove' if ($ENV{'REQUEST_METHOD'} eq 'DELETE' && $action ne 'remove');
1119 95b003ff Origo
    # -f should only set $fulllisting and not trigger any keyword actions
1120
    delete $params{'keywords'} if ($params{'keywords'} eq '-f');
1121
1122
    # Regular read - we send out JSON version of directory list
1123
    if (!$action && (!$ENV{'REQUEST_METHOD'} || $ENV{'REQUEST_METHOD'} eq 'GET')) {
1124
        if (!($package)) {
1125
            ; # If we get called as a library this is were we end - do nothing...
1126
        } elsif ($params{'keywords'}) {
1127
            ; # If param keywords is provided treat as a post
1128
        } else {
1129
            $action = 'list';
1130
        }
1131
    }
1132
1133
    ### Main security check
1134
    unless ($package eq 'pressurecontrol' || $dbuser || ($user eq 'common' && $action =~ /^updatebtime|^list/)) {throw Error::Simple("Status=Error $action: Unknown user $user [$remoteip]")};
1135
    if (index($privileges,"d")!=-1 && $action ne 'help') {throw Error::Simple("Status=Error Disabled user")};
1136
1137
    $curuuid = $curuuid || URI::Escape::uri_unescape($params{'uuid'}); # $curuuid may have been set above for DELETE requests
1138
    $curuuid = "" if ($curuuid eq "--");
1139
    $curuuid = $options{u} unless $curuuid;
1140
    if ($package eq 'images') {
1141
        $curimg = URI::Escape::uri_unescape($params{'image'} || $params{'path'}) unless ($action eq 'listfiles');
1142
        $curimg = "" if ($curimg eq "--");
1143
        $curimg = $1 if ($curimg =~ /(.*)\*$/); # Handle Dojo peculiarity
1144
        $curimg = URI::Escape::uri_unescape($options{i}) unless $curimg;
1145
        unless (tie(%imagereg,'Tie::DBI', Hash::Merge::merge({table=>'images', CLOBBER=>1}, $Stabile::dbopts)) ) {throw Error::Simple("Stroke=Error Image UUID register could not be accessed")};
1146
        if ($curimg && !$curuuid && $curimg =~ /(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})/) {
1147
            $curuuid = $curimg;
1148
            $curimg = $imagereg{$curuuid}->{'path'} if ($imagereg{$curuuid});
1149
#        } elsif ($target && !$curimg && !$curuuid) {
1150
#            if ($target =~ /(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})/) {
1151
#                $curuuid = $1;
1152
#                $curimg = $imagereg{$curuuid}->{'path'};
1153
#            } else {
1154
#                $curimg = $target;
1155
#            }
1156
        } elsif (!$curimg && $curuuid) {
1157
            $curimg = $imagereg{$curuuid}->{'path'} if ($imagereg{$curuuid});
1158
        }
1159
        untie %imagereg;
1160
    }
1161
}
1162
1163
sub process {
1164
    my $target = $params{'target'} || $options{t} ||  $curuuid;
1165
    # We may receive utf8 strings either from browser or command line - convert them to native Perl to avoid double encodings
1166
    utf8::decode($target) if ( $target =~ /[^\x00-\x7f]/ );# true if string contains any non-ascii character
1167
    my $uipath;
1168 d24d9a01 hq
#    my $uistatus;
1169 95b003ff Origo
# Special handling
1170
    if ($package eq 'images') {
1171
        $target = $curimg || $params{'path'} || $params{'image'} || $target unless ($target =~ /^\/.+/);
1172
        $params{'restorepath'} = $params{'path'} if ($action eq 'listfiles');
1173 2a63870a Christian Orellana
        $params{'baseurl'} = "https://$ENV{'HTTP_HOST'}/stabile" if ($action eq 'download' && $ENV{'HTTP_HOST'} && !($baseurl =~ /\./)); # send baseurl if configured value not valid
1174 95b003ff Origo
    } elsif ($package eq 'systems') {
1175
        $target = $params{'id'} || $target if ($action =~ /^monitors_/);
1176
    } elsif ($package eq 'nodes') {
1177
        $target = $target || $params{'mac'};
1178
    } elsif ($package eq 'users') {
1179
        $target = $target || $params{'username'};
1180
    }
1181
    # Named action - we got a request for an action
1182
    my $obj;
1183 d3805c61 hq
    if ($action && (defined &{"do_$action"}) &&
1184
        ($ENV{'REQUEST_METHOD'} ne 'POST' || $action eq 'upload' || $action eq 'restorefiles')
1185
        && !($params{"keywords"} || $params{"POSTDATA"})
1186
    ) {
1187 95b003ff Origo
        # If a function named do_$action (only lowercase allowed) exists, call it and print the result
1188
        if ($action =~ /^monitors/) {
1189
            if ($params{'PUTDATA'}) {
1190
                $obj = $params{'PUTDATA'};
1191
                $action = 'monitors_save' unless ($action =~ /monitors_.+/);
1192
            } else {
1193
                $obj = { action => $action, id => $target };
1194
            }
1195
        } else {
1196
            unless (%params) {
1197
                if ($package eq 'images' && $target =~ /^\//) {
1198
                    %params = ("path", $target);
1199
                    delete $params{"uuid"};
1200
                } else{
1201
                    %params = ("uuid", $target);
1202
                }
1203
            }
1204
            if ($curuuid || $target) {
1205
                $params{uuid} = $curuuid || $target unless ($params{uuid} || $params{path} || ($params{image} && $package eq 'images'));
1206
            }
1207
            $obj = getObj(\%params);
1208
        }
1209
        $obj->{'console'} = $console if ($console);
1210 2a63870a Christian Orellana
        $obj->{'baseurl'} = $params{baseurl} if ($params{baseurl});
1211 95b003ff Origo
    # Perform the action
1212
        $postreply = &{"do_$action"}($target, $action, $obj);
1213
        if (!$postreply) { # We expect some kind of reply
1214 6fdc8676 hq
            $postreply .= header('text/plain', '500 Internal Server Error because no reply') unless ($console);
1215 f222b89c hq
            $main::syslogit->($user, 'info', "Could not $action $target ($package)") unless ($action eq 'uuidlookup' || $action eq 'uuidshow');
1216 95b003ff Origo
        } elsif (! ($postreply =~ /^(Content-type|Status|Location):/i) ) {
1217
            if ($postreply =~ /Content-type:/) {
1218
                ;
1219
            } elsif (!$postreply || $postreply =~ /Status=/ || $postreply =~ /^</ || $postreply =~ /^\w/) {
1220
                $postreply = header('text/plain; charset=UTF8') . $postreply unless ($console);
1221
            } else {
1222
                $postreply = header('application/json; charset=UTF8') . $postreply unless ($console);
1223
            }
1224
        }
1225
        print "$postreply";
1226
1227
    } elsif (($params{'PUTDATA'} || $params{"keywords"} || $params{"POSTDATA"})  && !$isreadonly) {
1228
        # We got a save post with JSON. Look for interesting stuff and perform action or save
1229 2a63870a Christian Orellana
        my @json_array;
1230 95b003ff Origo
		if ($params{'PUTDATA'}) {
1231
		    my $json_text = $params{'PUTDATA'};
1232
            utf8::decode($json_text);
1233
            $json_text =~ s/\x/ /g;
1234
    		$json_text =~ s/\[\]/\"\"/g;
1235
		    @json_array = from_json($json_text);
1236
		} elsif ($params{"keywords"} || $params{"POSTDATA"}) {
1237
            my $json_text = $params{"keywords"} || $params{'POSTDATA'};
1238
            $json_text = uri_unescape($json_text);
1239
            utf8::decode($json_text);
1240
            $json_text =~ s/\x/ /g;
1241
            $json_text =~ s/\[\]/\"\"/g;
1242
            my $json_obj = from_json($json_text);
1243
            if (ref $json_obj eq 'ARRAY') {
1244
                @json_array = @$json_obj;
1245
            } elsif (ref $json_obj eq 'HASH') {
1246
                my %json_hash = %$json_obj;
1247
                my $json_array_ref = [\%json_hash];
1248
                if ($json_hash{"items"}) {
1249
                    $json_array_ref = $json_hash{"items"};
1250
                }
1251
                @json_array = @$json_array_ref;
1252
            }
1253
		}
1254
        foreach (@json_array) {
1255
			my %h = %$_;
1256
			$console = 1 if $h{"console"};
1257
            my $objaction = $h{'action'} || $action;
1258
            $objaction = 'save' if (!$objaction || $objaction eq "--");
1259
            $h{'action'} = $objaction = $action.'_'.$objaction if ($action eq "monitors" || $action eq "packages"); # Allow sending e.g. disable action to monitors by calling monitors_disable
1260 2a63870a Christian Orellana
            $h{'action'} = $objaction if ($objaction && !$h{'action'});
1261 95b003ff Origo
            my $obj = getObj(\%h);
1262
            next unless $obj;
1263
            $obj->{'console'} = $console if ($console);
1264
        # Now build the requested action
1265
            my $objfunc = "do_$objaction";
1266
        # If a function named objfunc exists, call it
1267
            if (defined &$objfunc) {
1268
                $target = $h{'uuid'} || $h{'id'};
1269
                $uiuuid = $target;
1270
                my $targetimg = $imagereg{$target};
1271
        # Special handling
1272
                if ($package eq 'images') {
1273
                    $target = $targetimg->{'path'} || $h{'image'} || $h{'path'} || $target;
1274
                }
1275
        # Perform the action
1276 a2e0bc7e hq
                my $areply = &{$objfunc}($target, $objaction, $obj);
1277
                $postreply .= $areply unless ($postreply eq $areply); # $postreply has been set
1278
1279 95b003ff Origo
        # Special handling
1280
                if ($package eq 'images') {
1281
                    if ($h{'status'} eq 'new') {
1282
#                        $uistatus = 'new';
1283
#                        $uiuuid = ''; # Refresh entire view
1284
                    }
1285
                }
1286
                my $node = $nodereg{$mac};
1287
                my $updateEntry = {
1288
                    tab=>$tab,
1289
                    user=>$user,
1290
                    uuid=>$uiuuid,
1291
                    status=>$uistatus,
1292
                    mac=>$mac,
1293
                    macname=>$node->{'name'},
1294
                    displayip=>$uidisplayip,
1295
                    displayport=>$uidisplayport,
1296
                    type=>$uiupdatetype,
1297
                    message=>$postmsg
1298
                };
1299
                # Special handling
1300
                if ($package eq 'images') {
1301
                    $obj->{'uuid'} = '' if ($uistatus eq 'new');
1302
                    $uipath = $obj->{'path'};
1303
                    $updateEntry->{'path'} = $uipath;
1304
                    $uiname = $obj->{'name'};
1305
                }
1306
                if ($uiname) {
1307
                    $updateEntry->{'name'} = $uiname;
1308
                }
1309
                if ($uiuuid || $postmsg || $uistatus) {
1310
                    push (@updateList, $updateEntry);
1311
                }
1312
            } else {
1313
                $postreply .= "Status=ERROR Unknown $package action: $objaction\n";
1314
            }
1315
		}
1316 a2e0bc7e hq
        if ($postreply && ! ($postreply =~ /^(Content-type|Status|Location):/i) ) {
1317 95b003ff Origo
            if (!$postreply || $postreply =~ /Status=/) {
1318
                $postreply = header('text/plain; charset=UTF8') . $postreply unless ($console);
1319
            } else {
1320
                $postreply = header('application/json; charset=UTF8') . $postreply unless ($console);
1321
            }
1322
        }
1323
        print $postreply;
1324
    } else {
1325
        $postreply .= "Status=Error Unknown $ENV{'REQUEST_METHOD'} $package action: $action\n";
1326
        print header('text/html', '500 Internal Server Error') unless ($console);
1327
        print $postreply;
1328
	}
1329
    # Functions called via aliases to privileged_action or privileged_action_async cannot update $postmsg or $uistatus
1330
    # so updateUI must be called internally in these functions.
1331
    if (@updateList) {
1332
        $main::updateUI->(@updateList);
1333
    }
1334
}
1335
1336
1337
# Print list of available actions
1338
sub Help {
1339
    $help = 1;
1340
    no strict 'refs';
1341
    my %fdescriptions;
1342
    my %fmethods;
1343
    my %fparams;
1344
    my @fnames;
1345
1346
    my $res = header() unless ($console);
1347
    #    my $tempuuid = "484d7852-90d2-43f1-8bd6-e29e234848b0";
1348
    my $tempuuid = "";
1349
    unless ($console) {
1350
        $res .= <<END
1351
    <!DOCTYPE html>
1352
    <html>
1353
        <head>
1354
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
1355
            <!-- script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script -->
1356
            <!-- script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script -->
1357
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
1358
            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
1359
            <style>
1360
                .form-control {display: inline-block; width: auto; margin: 2px; }
1361
                input.form-control {width: 180px;}
1362
				pre {
1363
					overflow-x: auto;
1364
					white-space: pre-wrap;
1365
					white-space: -moz-pre-wrap;
1366
					white-space: -pre-wrap;
1367
					white-space: -o-pre-wrap;
1368
					word-wrap: break-word;
1369
				}
1370
            </style>
1371
        </head>
1372
        <body style="margin:1.25rem;">
1373
        <div>
1374
            <table style="width:100%;"><tr><td>
1375
            <select class="form-control" id="scopeaction" name="scopeaction" placeholder="action" onchange="data.scopeaction=this.value; dofields();" autocomplete="off"></select>
1376
            <span id="scopeinputs">
1377
            <input class="form-control" id="scopeuuid" name="scopeuuid" placeholder="uuid" onchange="data.scopedata.uuid=this.value; update();" value="$tempuuid" autocomplete="off" size="34">
1378
            </span>
1379
            <button class="btn btn-primary" href="#" onclick="doit();">Try it</button>
1380
            <pre>
1381
    \$.ajax({
1382
        url: "<span class='scopeurl'>/stabile/$package?uuid=$tempuuid&action=activate</span>",
1383
        type: "<span class='scopemethod'>GET</span>", <span id="dataspan" style="display:none;"><br />        data: "<span class="scopedata"></span>",</span>
1384
        success: function(result) {\$("#scoperesult").text(result);}
1385
    });
1386
            </pre>
1387
            </td><td width="50%"><textarea id="scoperesult" style="width:100%; height: 200px;"></textarea></td>
1388
            </tr>
1389
            </table>
1390
        </div>
1391
            <script>
1392
                data = {"scopemethod": "GET", "scopeaction": "activate", "scopeuuid": "$tempuuid", "scopeurl": "/stabile/$package?uuid=$tempuuid&action=activate"};
1393
                function doit() {
1394
                    var obj = {
1395
                        url: data.scopeurl,
1396
                        type: data.scopemethod,
1397
                        success: handleResult,
1398
                        error: handleResult
1399
                    }
1400
                    if (data.scopemethod != 'GET') obj.data = JSON.stringify(data.scopedata);
1401
                    \$.ajax(obj);
1402 27512919 Origo
                    \$("#scoperesult").text("");
1403 95b003ff Origo
                    return true;
1404
                    function handleResult(data, textStatus, jqXHR) {
1405
                        if (jqXHR == 'Unauthorized') {
1406
                            \$("#scoperesult").text(jqXHR + ": You must log in before you can call API methods.");
1407
                        } else if (jqXHR.responseText) {
1408
                            \$("#scoperesult").text(jqXHR.responseText);
1409
                        } else {
1410
                            \$("#scoperesult").text("No result received");
1411
                        }
1412
                    }
1413
                }
1414
                function dofields() {
1415
                    if (scopeparams[data.scopeaction].length==0) {
1416
                        \$("#scopeinputs").hide();
1417
                    } else {
1418
                        var fields = "";
1419
                        \$.each(scopeparams[data.scopeaction], function (i, item) {
1420
                            var itemname = "scope" + item;
1421
                            if (\$("#"+itemname).val()) data[itemname] = \$("#"+itemname).val();
1422
                            fields += '<input class="form-control" id="' + itemname + '" placeholder="' + item + '" value="' + ((data[itemname])?data[itemname]:'') + '" size="34" onchange="update();"> ';
1423
                        });
1424
                        \$("#scopeinputs").empty();
1425
                        \$("#scopeinputs").append(fields);
1426
                        \$("#scopeinputs").show();
1427
                    }
1428
                    update();
1429
                }
1430
                function update() {
1431
                    data.scopemethod = scopemethods[data.scopeaction];
1432
                    if (data.scopemethod == "POST") {
1433
                        \$("#dataspan").show();
1434
                        data.scopeurl = "/stabile/$package";
1435
                        data.scopedata = {"items": [{"action":data.scopeaction}]};
1436
                        \$.each(scopeparams[data.scopeaction], function (i, item) {
1437
                            var val = \$("#scope"+item).val();
1438
                            if (val) data.scopedata.items[0][item] = val;
1439
                         });
1440
                    } else if (data.scopemethod == "PUT") {
1441
                        \$("#dataspan").show();
1442
                        data.scopeurl = "/stabile/$package";
1443
                        data.scopedata = [{"action":data.scopeaction}];
1444
                        \$.each(scopeparams[data.scopeaction], function (i, item) {
1445
                            var val = \$("#scope"+item).val();
1446
                            if (val) data.scopedata[0][item] = val;
1447
                         });
1448
                    } else {
1449
                        \$("#dataspan").hide();
1450
                        data.scopeurl = "/stabile/$package?action="+data.scopeaction;
1451
                        \$.each(scopeparams[data.scopeaction], function (i, item) {
1452
                            var val = \$("#scope"+item).val();
1453
                            if (val) data.scopeurl += "&" + item + "=" + val;
1454
                        });
1455
                        data.scopedata = '';
1456
                    }
1457
                    \$(".scopemethod").text(data.scopemethod);
1458
                    \$(".scopeurl").text(data.scopeurl);
1459
                    \$(".scopedata").text(JSON.stringify(data.scopedata, null, ' ').replace(/\\n/g,'').replace(/  /g,''));
1460
                }
1461
                \$( document ).ready(function() {
1462
                    data.scopeaction=\$("#scopeaction").val(); dofields()
1463
                });
1464
END
1465
        ;
1466
        $res .= qq|var scopeparams = {};\n|;
1467
        $res .= qq|var scopemethods = {};\n|;
1468
        $res .= qq|var package="$package"\n|;
1469
    }
1470
    my @entries;
1471
    if ($package eq 'networks') {
1472
        @entries = sort keys %Stabile::Networks::;
1473
    } elsif ($package eq 'images') {
1474
        @entries = sort keys %Stabile::Images::;
1475
    } elsif ($package eq 'servers') {
1476
        @entries = sort keys %Stabile::Servers::;
1477
    } elsif ($package eq 'nodes') {
1478
        @entries = sort keys %Stabile::Nodes::;
1479
    } elsif ($package eq 'users') {
1480
        @entries = sort keys %Stabile::Users::;
1481
    } elsif ($package eq 'systems') {
1482
        @entries = sort keys %Stabile::Systems::;
1483
    }
1484
1485
    foreach my $entry (@entries) {
1486
        if (defined &{"$entry"} && $entry !~ /help/i && $entry =~ /^do_(.+)/) {
1487
            my $fname = $1;
1488
            # Ask function for help - $help is on
1489
            my $helptext = &{"$entry"}(0, $fname);
1490
            my @helplist = split(":", $helptext, 3);
1491
            chomp $helptext;
1492
            unless ($fname =~ /^gear_/) {
1493
                $fmethods{$fname} = $helplist[0];
1494
                $fparams{$fname} = $helplist[1];
1495
                $fdescriptions{$fname} = $helplist[2];
1496
                $fdescriptions{$fname} =~ s/\n// unless ($console);
1497
                $fdescriptions{$fname} =~ s/\n/\n<br>/g unless ($console);
1498
                my @plist = split(/, ?/, $fparams{$fname});
1499
                unless ($console) {
1500
                    $res .= qq|scopeparams["$fname"] = |.to_json(\@plist).";\n";
1501
                    $res .= qq|\$("#scopeaction").append(new Option("$fname", "$fname"));\n|;
1502
                    $res .= qq|scopemethods["$fname"] = "$helplist[0]";\n|;
1503
                }
1504
            }
1505
        }
1506
    }
1507
    @fnames = sort (keys %fdescriptions);
1508
1509
    unless ($console) {
1510
        $res .= "\n</script>\n";
1511
        $res .= <<END
1512
        <div class="table-responsive" style="margin-top:1.5rem; noheight: 65vh; overflow-y: scroll;">
1513
            <table class="table table-striped table-sm">
1514
              <thead>
1515
                <tr>
1516
                  <th>Name</th>
1517
                  <th>Method</th>
1518
                  <th>Parameters</th>
1519
                  <th style="width:60%;">Description</th>
1520
                </tr>
1521
              </thead>
1522
              <tbody>
1523
END
1524
        ;
1525
        foreach my $fname (@fnames) {
1526
            my $fp = ($fparams{$fname}) ? "$fparams{$fname}" : '';
1527
            $res .= <<END
1528
                    <tr>
1529
                      <td><a href="#" onclick="data.scopeaction=this.text; \$('#scopeaction option[value=$fname]').prop('selected', true); dofields();">$fname</a></td>
1530
                      <td>$fmethods{$fname}</td>
1531
                      <td>$fp</td>
1532
                      <td>$fdescriptions{$fname}</td>
1533
                    </tr>
1534
END
1535
            ;
1536
        }
1537
        $res .= <<END
1538
                </tbody>
1539
            </table>
1540
        </div>
1541
END
1542
        ;
1543
        $res .= qq|</body>\n</html>|;
1544
    } else {
1545
        foreach my $fname (@fnames) {
1546
            my $fp = ($fparams{$fname}) ? "[$fparams{$fname}]" : '';
1547
            $res .= <<END
1548
* $fname ($fmethods{$fname}) $fp $fdescriptions{$fname}
1549
END
1550
            ;
1551
        }
1552
    }
1553
1554
    return $res;
1555
}
1556
1557 8d7785ff Origo
sub getBackupSize {
1558
    my ($subdir, $img, $imguser) = @_; # $subdir, if specified, includes leading slash
1559
    $imguser = $imguser || $user;
1560
    my $backupsize = 0;
1561
    my @bdirs = ("$backupdir/$imguser$subdir/$img");
1562
    if ($backupdir =~ /^\/stabile-backup\//) { # ZFS backup is enabled - we need to scan more dirs
1563
        @bdirs = (
1564
            "/stabile-backup/*/$imguser$subdir/" . shell_esc_chars($img),
1565
            "/stabile-backup/*/.zfs/snapshot/*/$imguser$subdir/". shell_esc_chars($img)
1566
        );
1567
    }
1568
    foreach my $bdir (@bdirs) {
1569
        my $bdu = `/usr/bin/du -bs $bdir 2>/dev/null`;
1570
        my @blines = split("\n", $bdu);
1571
        # only count size from last snapshot
1572
        my $bline = pop @blines;
1573
#        foreach my $bline (@blines) {
1574
            $bline =~ /(\d+)\s+/;
1575
            $backupsize += $1;
1576
#        }
1577
    }
1578
    return $backupsize;
1579
}
1580
1581 95b003ff Origo
sub shell_esc_chars {
1582
    my $str = shift;
1583
    $str =~ s/([;<>\*\|`&\$!#\(\)\[\]\{\}:'" ])/\\$1/g;
1584
    return $str;
1585
}