Project

General

Profile

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