-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_stash.cgi
executable file
·3775 lines (2995 loc) · 137 KB
/
simple_stash.cgi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
BEGIN {
require './Config.pl';
}
use strict;
use warnings;
#use Data::Dumper;
#use MIME::Base64;
use CGI;
use Getopt::Long;
use JSON;
use URI::Escape;
#use POSIX;
use File::Temp qw/ tempfile /;
use File::Basename;
use Net::LDAP;
#Download SendMail (and other stuff) like this:
#curl -o perlscr-master.zip https://codeload.github.com/ivanamihalek/perlscr/zip/master
#NOTE: modify line 721 of SendMail.pm to get rid of warning
use lib "/var/www/cgi-bin/domrep/perl_mods/perlscr-master/SendMail-2.09";
use SendMail;
use lib "/var/www/cgi-bin/domrep/perl_mods/installed/lib/perl5";
use Net::OpenSSH;
#process exit codes
use constant EX_SUCC => 0;
use constant EX_FAIL => 1;
use constant EX_WARN => 2;
use constant EX_FTL => 3;
use constant RETRY_SSH_CNT => 1;
my $thisScriptName = basename($0);
my $thisScriptFullUrl = CGI::url();
my $thisScriptDomain = '';
if ($thisScriptFullUrl =~ m/^\s*([a-zA-Z]+\:\/\/[^\/]+)/) { $thisScriptDomain = $1; }
my $stashUIFullUrl = "${thisScriptDomain}/stash_ui_release/stash_ui/index.html";
my $fsSelTxt = "<SELECT style='width:100%' NAME='fs'>\n" . join("\n",map { my $selTxt = ($_ eq 'default') ? 'SELECTED ' : '';
"<OPTION ${selTxt}value='${_}'>${_}</OPTION>"; } keys %$Config::managedFileSystems) .
"</SELECT>\n";
my $allUsersWebAccessGroup = "EVERYONE"; #special web-access only group that signifies all users
#0 if the script is called as a CGI script (e.g. by Apache), 1 otherwise (e.g. command line execution)
my $nocgi = $ENV{HTTP_HOST} ? 0 : 1;
setProxyEnvVars();
my $q = CGI->new();
my $a;
my $fs;
my $stage;
my $mode;
my $dirPath;
my $targetPath;
my $base;
my $eacl;
my $webeacl;
my $filePath;
my $disposition;
my $shareUsers;
my $recursive;
my $directFilePath;
my $stashFileName;
my $newPath;
my $user;
my $no_email;
my $current_user;
my $search_ug_fs_or_web;
my $search_ug_user_or_group;
my $search_ug_search_text;
my $user_sshkey;
my $user_password;
my $callback;
my $singleQuoteInPathsFlag = 0;
setParams();
if (empty($fs)) { $fs = "default"; }
my $fsConfig = $Config::managedFileSystems->{$fs};
if (!defined($fsConfig)) { cgi_die_json("Error: there is no file system '${fs}' being managed"); }
my ($fsRoot, $fsHost, $fsPort, $fsSetCurrentUser, $fsUser, $fsKeyfile) =
($fsConfig->{"root"},$fsConfig->{"host"},$fsConfig->{"port"},$fsConfig->{"set_current_user"},
$fsConfig->{"user"},$fsConfig->{"keyfile"});
if (!defined($fsRoot)) { cgi_die_json("Error: managed file system '${fs}' has no root."); }
if (!empty($fsSetCurrentUser)) { $current_user = $fsSetCurrentUser; }
if (empty($current_user)) {
cgi_die_json("Error: must be authenticated user.");
}
my $fs_users; my $fs_groups;
if (empty($a)) { $a = "show_actions"; }
if (empty($stage)) { $stage = 'form'; }
#admin mode not used now, but could potentially use it somehow if wanted.
if (empty($mode) || (($mode ne 'user') && ($mode ne 'admin'))) { $mode = 'user'; }
if (($mode eq 'admin') && !$Config::adminUsers->{$current_user}) { $mode = 'user'; }
my $actionFuncs = { 'show_actions' => \&show_actions,
'test_ssh_key' => { 'form' => \&TestSshKey_form, 'exec' => \&TestSshKey },
'download_file' => { 'form' => \&DownloadFile_form, 'exec' => \&DownloadFile },
'download_dir' => { 'form' => \&DownloadDir_form, 'exec' => \&DownloadDir },
'stash_file' => { 'form' => \&StashFile_form, 'exec' => \&StashFile },
'create_dir' => { 'form' => \&CreateDir_form, 'exec' => \&CreateDir },
'create_symlink' => { 'form' => \&CreateSymlink_form, 'exec' => \&CreateSymlink },
'directory_contents' => { 'form' => \&DirectoryContents_form, 'exec' => \&DirectoryContents },
'show_eacl' => { 'form' => \&ShowEacl_form, 'exec' => \&ShowEacl },
'modify_eacl' => { 'form' => \&ModifyEacl_form, 'exec' => \&ModifyEacl },
'share' => { 'form' => \&Share_form, 'exec' => \&Share },
'determine_user_access' => { 'form' => \&DetermineUserAccess_form, 'exec' => \&DetermineUserAccess_svc },
'move' => { 'form' => \&Move_form, 'exec' => \&Move },
'delete' => { 'form' => \&Delete_form, 'exec' => \&Delete },
'get_current_user' => \&getCurrentUser_svc,
'check_zip_access' => \&checkZipAccess_svc,
'search_ug' => \&searchUg };
my $curActionFuncs = $actionFuncs->{$a};
if (!defined($curActionFuncs)) {
cgi_die_json("Error: bad action '$a'");
} else {
if (ref $curActionFuncs eq 'HASH') {
my $actualActionFunc = $curActionFuncs->{$stage};
if (!defined($actualActionFunc)) {
cgi_die_json("Error: bad stage '${stage}' for action '${a}'");
}
$actualActionFunc->();
} else {
$curActionFuncs->();
}
}
exit 0;
sub setProxyEnvVars {
$ENV{'https_proxy'} = 'http://proxy-server:8080';
$ENV{'http_proxy'} = 'http://proxy-server:8080';
$ENV{'ftp_proxy'} = 'http://proxy-server:8080';
$ENV{'no_proxy'} = 'bms.com,localhost,169.254.169.254';
$ENV{'HTTPS_PROXY'} = 'http://proxy-server:8080';
$ENV{'HTTP_PROXY'} = 'http://proxy-server:8080';
$ENV{'FTP_PROXY'} = 'http://proxy-server:8080';
}
sub show_actions {
printHeader();
print <<EOF;
<html>
<body>
<center><h3>RR Simple Stash</h3></center>
<ul>
<li><a href='${thisScriptName}?a=test_ssh_key'>TestSshKey</a>
<li><a href='${thisScriptName}?a=download_file'>DownloadFile</a>
<li><a href='${thisScriptName}?a=download_dir'>DownloadDir</a>
<li><a href='${thisScriptName}?a=stash_file'>StashFile</a>
<li><a href='${thisScriptName}?a=create_dir'>CreateDir</a>
<li><a href='${thisScriptName}?a=create_symlink'>CreateSymlink</a>
<li><a href='${thisScriptName}?a=directory_contents'>DirectoryContents</a>
<li><a href='${thisScriptName}?a=show_eacl'>ShowEacl</a>
<li><a href='${thisScriptName}?a=modify_eacl'>ModifyEacl</a>
<li><a href='${thisScriptName}?a=share'>Share</a>
<li><a href='${thisScriptName}?a=determine_user_access'>DetermineUserAccess</a>
<li><a href='${thisScriptName}?a=move'>Move</a>
<li><a href='${thisScriptName}?a=delete'>Delete</a>
</ul>
<hr><a href='${thisScriptName}'>home</a>
</body>
</html>
EOF
}
sub checkZipAccess_svc {
my ($hasZipAccessFlag, $zipErrMsg) = checkZipAccess($dirPath);
printHeader('application/json');
my $retObj = { 'success' => JSON::true,
'has_zip_access' => $hasZipAccessFlag ? JSON::true : JSON::false };
if (!empty($zipErrMsg) && !$hasZipAccessFlag) {
$retObj->{'msg'} = $zipErrMsg;
}
print to_json($retObj);
}
sub getCurrentUser_svc {
printHeader('application/json');
my $retObj = { 'success' => JSON::true,
'current_user' => $current_user };
print to_json($retObj);
}
sub CreateDir_form {
printHeader();
print <<EOF;
<html>
<head><title>CreateDir</title>
<style>
#createdir {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#createdir td, #createdir th {
border: 1px solid #ddd;
padding: 8px;
}
#createdir tr:nth-child(even){background-color: #f2f2f2;}
#createdir tr:hover {background-color: #ddd;}
#createdir th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #004851;
color: #8D9093;
}
</style>
</head>
<body>
<center><h3>CreateDir</h3></center>
Create a new directory path (relative to the root directory) and specify the users and groups who can access the directory as base access (standard Linux user/group/other) and/or extended ACL. Note that 2 versions of extended ACL can be specified, one for web-based access and one for filesystem based access; the web-based extended ACL grants access only through these web services and it is optional. For example create path <i>results/my_project/prod1</i> with base access of <i>u:smitha26:rwx,g:xpress:r,o:OTHER:r</i> (which will set the owner to smitha26 and the group to xpress), filesystem extended ACL of <i>g:bioinfo:r,u:russom:rw</i> and web-based extended ACL of <i>u:john:r</i>. You must have write access (via filesystem ACL; web-based extended ACL is only considered and used for read operations) to the directory path, or you will get an error response. For example, if you specify to create directory <i>results/my_proj/proj_data</i> and <i>results/my_proj</i> exists but you do not have write access to it, then you will receive an error response. If the full path to the directory does not exist it will be created as necessary (i.e. basically a 'mkdir -p PATH' will be done) with each created path segment having base access of the uploading user having 'rwx' access. However, you must have write access to the nearest existing parent directory or you will get an error response. Note that there is also a special web-access only group called EVERYONE that you can use to specify that any user can access, e.g. EVERYONE:r means any user accessing the system has read access to the directory. Choose the Filesystem you want to work with (the system can be configured to manage multiple file systems). An SSH private key or the user's password must be provided in order to have file system extended ACL considered (otherwise only web-access extended ACL will be considered) and is required for any write operations like this service.
<form method='POST' enctype='multipart/form-data' action='${thisScriptName}'>
<table id="createdir"><tr><th>INPUT</th><th>INPUT VALUE</th></tr>
<tr><td>Directory Path:</td><td><input style="width:100%" type=text name=dir_path /></td></tr>
<tr><td>Base ACL (File System):</td><td><input style="width:100%" type=text name=base /></td></tr>
<tr><td>Extended ACL (File System):</td><td><input style="width:100%" type=text name=eacl /></td></tr>
<tr><td>Extended ACL (Web Access):</td><td><input style="width:100%" type=text name=webeacl /></td></tr>
<tr><td>Filesystem:</td><td>${fsSelTxt}</td></tr>
<tr><td>Password:</td><td><input style="width:100%" type=text name=user_password /></td></tr>
<tr><td>SSH Private Key:</td><td><textarea style="width:100%" rows=3 id=user_sshkey name=user_sshkey></textarea></td></tr>
</table><p>
<input type=submit value=Exec />
<input type=hidden name=a value=create_dir />
<input type=hidden name=stage value=exec />
</form>
<hr><a href='${thisScriptName}'>home</a>
</body>
</html>
EOF
}
sub ShowEacl_form {
printHeader();
print <<EOF;
<html>
<head><title>ShowEacl</title>
<style>
#showeacl {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#showeacl td, #showeacl th {
border: 1px solid #ddd;
padding: 8px;
}
#showeacl tr:nth-child(even){background-color: #f2f2f2;}
#showeacl tr:hover {background-color: #ddd;}
#showeacl th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #004851;
color: #8D9093;
}
</style>
</head>
<body>
<center><h3>ShowEacl</h3></center>
Retrieve the current extended ACL (i.e. users and groups who can access, and whether they can 'read', 'write', or 'execute') for a specified relative directory or file path (relative to the root), for example <i>results/my_project/prod1</i>. Both filesystem and web-based access extended ACL will be returned. You must have read access to the parent directory in order to view the extended ACL (except anyone can view for the root). Leave the path blank to show the extended ACL for the root directory. Choose the Filesystem you want to work with (the system can be configured to manage multiple file systems, both local or remote). An SSH private key or the user's password must be provided in order to have file system extended ACL considered (otherwise only web-access extended ACL will be considered) and is required for any write operations.
<form method='POST' enctype='multipart/form-data' action='${thisScriptName}'>
<table id="showeacl"><tr><th>INPUT</th><th>INPUT VALUE</th></tr>
<tr><td>Dir or File Path:</td><td><input style="width:100%" type=text name=dir_path /></td></tr>
<tr><td>Filesystem:</td><td>${fsSelTxt}</td></tr>
<tr><td>Password:</td><td><input style="width:100%" type=text name=user_password /></td></tr>
<tr><td>SSH Private Key:</td><td><textarea style="width:100%" rows=3 id=user_sshkey name=user_sshkey></textarea></td></tr>
</table><p>
<input type=submit value=Exec />
<input type=hidden name=a value=show_eacl />
<input type=hidden name=stage value=exec />
</form>
<hr><a href='${thisScriptName}'>home</a>
</body>
</html>
EOF
}
sub ShowEacl {
if (empty($dirPath)) { #empty means the root directory of simple_stash, normalize to simple empty string
$dirPath = "";
} else {
$dirPath =~ s/\/+$//;
}
if ($dirPath =~ m/^\//) {
cgi_die_json("Error in ShowEacl: The path must be a relative path (not absolute), with no leading \/ character. Files are stashed relative to the stash root of $fsRoot");
}
my $canReadFlag = 0;
my ($pathInfo_full_info, $pathInfo, $pathInfo_fs_user);
if (empty($dirPath)) { #root
$canReadFlag = 1;
($pathInfo_full_info, $pathInfo, $pathInfo_fs_user) = pathInfo([$dirPath],0);
} else {
my ($dirPathPar, $dirPathLastPart) = parentPath($dirPath);
if (!defined($dirPathPar)) {
cgi_die_json("Error in ShowEacl: could not extract parent directory from '${dirPath}'");
}
($pathInfo_full_info, $pathInfo, $pathInfo_fs_user) = pathInfo([$dirPath,$dirPathPar],0);
if ($pathInfo_full_info->{'paths_info'}{$dirPath}{'doesnt_exist'}) {
cgi_die_json("Error in ShowEacl: path '${dirPath}' does not exist.", { 'path_exists' => JSON::false });
}
if (defined($pathInfo) && $pathInfo->{'paths_info'}{$dirPathPar}{'permissions'}{'x'}) { #can view ACL
$canReadFlag = 1;
} else { #check webeacl (i.e. web access rules)
my $webPerms = determineWebPerms($pathInfo_full_info->{'paths_info'}{$dirPathPar}{'webeacl'});
if ($webPerms->{'r'}) {
$canReadFlag = 1;
}
}
}
if (!$canReadFlag) {
cgi_die_json("Error in ShowEacl: access denied to path '${dirPath}'");
}
my $theDirFsAcl = $pathInfo_full_info->{'paths_info'}{$dirPath}{'eacl'};
my $theDirWebAcl = $pathInfo_full_info->{'paths_info'}{$dirPath}{'webeacl'};
my $_eacl_str = eacl_hash_to_str($theDirFsAcl->{'extended_perms'});
my $_webeacl_str = eacl_hash_to_str($theDirWebAcl);
my $base_acl_hash = { 'u' => { $theDirFsAcl->{'owner'} => $theDirFsAcl->{'owner_perms'} },
'g' => { $theDirFsAcl->{'group'} => $theDirFsAcl->{'group_perms'} },
'o' => { 'OTHER' => $theDirFsAcl->{'other_perms'} } };
my $_base_str = eacl_hash_to_str($base_acl_hash);
printHeader('application/json');
my $retObj = { 'success' => JSON::true, 'msg' => "Successfully got eACL of path $dirPath",
'base' => $_base_str,
'eacl' => $_eacl_str,
'webeacl' => $_webeacl_str,
'directory_exists' => JSON::true,
'read_access' => JSON::true };
print to_json($retObj);
}
sub Delete_form {
printHeader();
print <<EOF;
<html>
<head><title>Delete</title>
<style>
#delete {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#delete td, #delete th {
border: 1px solid #ddd;
padding: 8px;
}
#delete tr:nth-child(even){background-color: #f2f2f2;}
#delete tr:hover {background-color: #ddd;}
#delete th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #004851;
color: #8D9093;
}
</style>
</head>
<body>
<center><h3>Delete</h3></center>
Delete a specified relative file or directory path (relative to the root), for example delete file <i>results/my_project/prod1/out_tmp.txt</i>. You must have write access to the specified directory or file path's parent or you will receive an error response. Choose the Filesystem you want to work with (the system can be configured to manage multiple file systems, both local or remote). An SSH private key or the user's password must be provided in order to have file system extended ACL considered (otherwise only web-access extended ACL will be considered) and is required for any write operations like this service.
<form method='POST' enctype='multipart/form-data' action='${thisScriptName}'>
<table id="delete"><tr><th>INPUT</th><th>INPUT VALUE</th></tr>
<tr><td>Dir or File Path:</td><td><input style="width:100%" type=text name=dir_path /></td></tr>
<tr><td>Filesystem:</td><td>${fsSelTxt}</td></tr>
<tr><td>Password:</td><td><input style="width:100%" type=text name=user_password /></td></tr>
<tr><td>SSH Private Key:</td><td><textarea style="width:100%" rows=3 id=user_sshkey name=user_sshkey></textarea></td></tr>
</table><p>
<input type=submit value=Exec />
<input type=hidden name=a value=delete />
<input type=hidden name=stage value=exec />
</form>
<hr><a href='${thisScriptName}'>home</a>
</body>
</html>
EOF
}
sub userProvidedCredentials {
if (empty($user_sshkey) && empty($user_password)) {
return 0;
} else {
return 1;
}
}
sub Delete {
if (!userProvidedCredentials()) {
cgi_die_json("Error in Delete: write operations are only allowed via a user's credentials (SSH private key or password), please provide.");
}
if (empty($dirPath)) { #empty means the root directory of simple_stash, you can't change its eacl
cgi_die_json("Error in Delete: you cannot delete the root directory.", { 'path_exists' => JSON::true, 'write_access' => JSON::false });
}
if ($dirPath =~ m/^\//) {
cgi_die_json("Error in Delete: The path must be a relative path (not absolute), with no leading \/ character. Files are stashed relative to the stash root of $fsRoot");
}
$dirPath =~ s/\/+$//;
my ($dirPathPar, $dirPathLastPart) = parentPath($dirPath);
if (!defined($dirPathPar)) {
cgi_die_json("Error in Delete: could not parse $dirPath");
}
#To delete a file, you need at least 'wx' access to it's parent dir
#and at least 'x' access to all higher level dirs. You do not need any
#permissions on the file itself. To delete a directory, you will need the
#same permissions as just specified for a file, but in addition you'll need
#the correct permissions to delete any underlying files and dirs of the
#directory (i.e. 'wx' on the parent dir and 'x' for all higher level dirs).
my ($pathInfo_full_info, $pathInfo, $pathInfo_fs_user) = pathInfo([$dirPath,$dirPathPar],1);
if ($pathInfo_full_info->{'paths_info'}{$dirPath}{'doesnt_exist'}) {
cgi_die_json("Error in Delete: path '${dirPath}' does not exist.", { 'path_exists' => JSON::false });
}
if (!defined($pathInfo) || !($pathInfo->{'paths_info'}{$dirPathPar}{'permissions'}{'w'} &&
$pathInfo->{'paths_info'}{$dirPathPar}{'permissions'}{'x'})) { #access denied to delete
cgi_die_json("Error in Delete: access denied to path '${dirPath}'");
}
if ($pathInfo_full_info->{'paths_info'}{$dirPath}{'type'} eq 'D') { #need to make sure you have access to delete lower level content
my ($allPathsDown, $errMsg) = allPathsUnder($dirPath);
if (!defined($allPathsDown)) {
return (0,"Error in Delete: couldn't get all paths under '${dirPath}': $errMsg");
}
# my ($pathInfo_full_info, $pathInfo, $pathInfo_fs_user)
my @pathInfoResArr = pathInfo($allPathsDown,0);
my ($hasPerm, $permDownErrMsg) = checkAccessUnder($dirPath,\@pathInfoResArr,undef,{ 'fs' => ['w','x'] });
if (!$hasPerm) { cgi_die_json("Error in Delete: you do not have access to delete '${dirPath}': $permDownErrMsg"); }
}
delPath($dirPath);
printHeader('application/json');
my $retObj = { 'success' => JSON::true, 'msg' => "Successfully deleted path '${dirPath}'",
'path_exists' => JSON::true,
'delete_access' => JSON::true };
print to_json($retObj);
}
sub TestSshKey_form {
printHeader();
print <<EOF;
<html>
<head><title>TestSshKey</title>
<style>
#testsshkey {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#testsshkey td, #testsshkey th {
border: 1px solid #ddd;
padding: 8px;
}
#testsshkey tr:nth-child(even){background-color: #f2f2f2;}
#testsshkey tr:hover {background-color: #ddd;}
#testsshkey th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #004851;
color: #8D9093;
}
</style>
</head>
<body>
<center><h3>Test SSH Key</h3></center>
This service will simply test your provided credentials (SSH private key or password) to see if it works on the host of your chosen file system.
<form method='POST' enctype='multipart/form-data' action='${thisScriptName}'>
<table id="testsshkey"><tr><th>INPUT</th><th>INPUT VALUE</th></tr>
<tr><td>Filesystem:</td><td>${fsSelTxt}</td></tr>
<tr><td>Password:</td><td><input style="width:100%" type=text name=user_password /></td></tr>
<tr><td>SSH Private Key:</td><td><textarea style="width:100%" rows=3 id=user_sshkey name=user_sshkey></textarea></td></tr>
</table><p>
<input type=submit value=Exec />
<input type=hidden name=a value=test_ssh_key />
<input type=hidden name=stage value=exec />
</form>
<hr><a href='${thisScriptName}'>home</a>
</body>
</html>
EOF
}
sub TestSshKey {
if (!userProvidedCredentials()) {
cgi_die_json("Error in TestSshKey: please provide credentials (SSH private key or password) to test.");
}
my $simpleEchoCmd = "echo 'works'";
my $retVal = evalOrDie({"cmd" => $simpleEchoCmd,
"dont_die" => 1,
"parseJsonFlag" => 0,
"msgIfErr" => "Error testing private SSH key."});
my $retRes = rem_ws($retVal->{'res'});
if ($retRes eq 'works') {
my $retObj = { 'success' => JSON::true, 'msg' => "Provided credentials tested successfully and work.",
'ssh_key_works' => JSON::true };
printHeader('application/json');
print to_json($retObj);
} else {
my $dieErrMsg = "Error: your provided credentials did not work, please check and update it and try again.";
cgi_die_json($dieErrMsg, { 'ssh_key_works' => JSON::false, %$retVal });
}
}
sub ModifyEacl_form {
printHeader();
print <<EOF;
<html>
<head><title>ModifyEacl</title>
<style>
#modifyeacl {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#modifyeacl td, #modifyeacl th {
border: 1px solid #ddd;
padding: 8px;
}
#modifyeacl tr:nth-child(even){background-color: #f2f2f2;}
#modifyeacl tr:hover {background-color: #ddd;}
#modifyeacl th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #004851;
color: #8D9093;
}
</style>
</head>
<body>
<center><h3>ModifyEacl</h3></center>
Modify the base access (standard Linux user/group/other), filesystem and/or web-based access extended ACL (i.e. users and groups who can access, and whether they can '<b>r</b>ead', '<b>w</b>rite', or 'e<b>x</b>ecute') for a specified relative file or directory path (relative to the root), for example for path <i>results/my_project/prod1</i> set the base access to <i>u:smitha26:rwx,g:xpress:r,o:OTHER:r</i> (which will set the owner to smitha26 and the group to xpress), the filesystem extended ACL to <i>g:bioinfo:r,u:russom:r</i> and the web-based extended ACL to <i>g:EVERYONE:r</i>. You must be the owner of the specified directory or file path, or you will receive an error response. Note that there is also a special web-access only group called EVERYONE that you can use to specify that any user can access, e.g. EVERYONE:rw means any user accessing the system can read or write the file or directory. Choose the Filesystem you want to work with (the system can be configured to manage multiple file systems, both local or remote). Also, specify whether you want to modify recursively (i.e. the specified path and all its sub paths and sub files) or only modify the specified path; for recursive you will also need to be the owner of all sub paths and sub files or will receive an error response. An SSH private key or the user's password must be provided in order to have file system extended ACL considered (otherwise only web-access extended ACL will be considered) and is required for any write operations like this service.
<form method='POST' enctype='multipart/form-data' action='${thisScriptName}'>
<table id="modifyeacl"><tr><th>INPUT</th><th>INPUT VALUE</th></tr>
<tr><td>Dir or File Path:</td><td><input style="width:100%" type=text name=dir_path /></td></tr>
<tr><td>Base ACL (File System):</td><td><input style="width:100%" type=text name=base /></td></tr>
<tr><td>Extended ACL (File System):</td><td><input style="width:100%" type=text name=eacl /></td></tr>
<tr><td>Extended ACL (Web Access):</td><td><input style="width:100%" type=text name=webeacl /></td></tr>
<tr><td>Filesystem:</td><td>${fsSelTxt}</td></tr>
<tr><td>Recursive?</td><td><select name=recursive>
<option selected value="0">No</option>
<option value="1">Yes</option>
</select></td></tr>
<tr><td>Password:</td><td><input style="width:100%" type=text name=user_password /></td></tr>
<tr><td>SSH Private Key:</td><td><textarea style="width:100%" rows=3 id=user_sshkey name=user_sshkey></textarea></td></tr>
</table><p>
<input type=submit value=Exec />
<input type=hidden name=a value=modify_eacl />
<input type=hidden name=stage value=exec />
</form>
<hr><a href='${thisScriptName}'>home</a>
</body>
</html>
EOF
}
sub resetEaclAndDie {
my ($backupAclTxt, $backupWebAclTxt, $dieErrMsg) = @_;
my $recursTxt = " recursively";
if (!$recursive) { $recursTxt = ""; }
if (empty($dieErrMsg)) {
$dieErrMsg = "There was an error setting filesystem and/or web ACL, and so they have been reset back to their original values.";
}
if (defined($backupWebAclTxt)) {
evalOrDie({"cmd" => "setfattr --restore -",
"stdin_data" => $backupWebAclTxt,
"parseJsonFlag" => 0,
"msgIfErr" => $dieErrMsg . "\n\nError restoring web eacl for $dirPath to original values in resetEaclAndDie${recursTxt}"});
}
if (defined($backupAclTxt)) {
evalOrDie({"cmd" => "setfacl --restore=-",
"stdin_data" => $backupAclTxt,
"parseJsonFlag" => 0,
"msgIfErr" => $dieErrMsg . "\n\nError restoring eacl for $dirPath to original values in resetEaclAndDie${recursTxt}"});
}
cgi_die_json($dieErrMsg);
}
sub ModifyEacl {
my ($justReturnFlag) = @_; #if true, don't print out JSON reply, just return
my $findNotRecurs = " -maxdepth 0";
if ($recursive) { $findNotRecurs = ""; }
my $faclRecurs = " -R";
if (!$recursive) { $faclRecurs = ""; }
my $recursTxt = " recursively";
if (!$recursive) { $recursTxt = ""; }
if (!userProvidedCredentials()) {
cgi_die_json("Error in ModifyEacl: write operations are only allowed via a user's credentials (SSH private key or password), please provide.");
}
if (empty($dirPath)) { #empty means the root directory of simple_stash, you can't change its eacl
cgi_die_json("Error in ModifyEacl: you cannot modify the eACL of the root directory.", { 'path_exists' => JSON::true, 'write_access' => JSON::false });
}
if ($dirPath =~ m/^\//) {
cgi_die_json("Error in ModifyEacl: The path must be a relative path (not absolute), with no leading \/ character. Files are stashed relative to the stash root of $fsRoot");
}
$dirPath =~ s/\/+$//;
my $fullPath = $fsRoot . "/" . $dirPath;
my ($dirPathPar, $dirPathLastPart) = parentPath($dirPath);
if (!defined($dirPathPar)) {
cgi_die_json("Error in ModifyEacl: could not extract parent directory from '${dirPath}'");
}
my ($pathInfo_full_info, $pathInfo, $pathInfo_fs_user) = pathInfo([$dirPath,$dirPathPar],0);
if ($pathInfo_full_info->{'paths_info'}{$dirPath}{'doesnt_exist'}) {
cgi_die_json("Error in ModifyEacl: path '${dirPath}' does not exist.", { 'path_exists' => JSON::false });
}
if (!defined($pathInfo) || !$pathInfo->{'paths_info'}{$dirPathPar}{'permissions'}{'x'}) { #access denied to modify acl
cgi_die_json("Error in ModifyEacl: access denied to path '${dirPath}'");
}
my $base_hash = eacl_str_to_hash($base);
my ($base_is_valid, $base_err_msg) = check_base_access($base_hash);
if (!$base_is_valid) {
cgi_die_json("Error: Base access '${base}' is not valid: $base_err_msg");
}
my $base_for_setfacl = eacl_hash_to_str($base_hash, 1);
my $findCmd = 'find \'' . $fullPath . '\' ' . $findNotRecurs . ' -exec sh -c \'getfacl -p "$1" ; chmod u+rwx "$1"\' sh {} \;';
my $retVal = evalOrDie({"cmd" => $findCmd,
"dont_die" => 1,
"success_exit" => { 0 => 1 },
"parseJsonFlag" => 0,
"msgIfErr" => "Error getting current ACLs and setting to u+rwx for ${dirPath}${recursTxt}"});
my $origSavedAcl = $retVal->{'res'};
my $retErrMsg = $retVal->{'err_msg'};
my $stderr_contents = $retVal->{'stderr'};
if (!empty($stderr_contents)) {
if ($stderr_contents =~ m/No such file or directory/s) {
cgi_die_json("Error in ModifyEacl: path $dirPath does not exist.", { 'path_exists' => JSON::false });
}
}
if (($stderr_contents =~ m/Permission denied/s) ||
($stderr_contents =~ m/Operation not permitted/)) {
cgi_die_json("Error in ModifyEacl: only the owner can modify a file or directory's eACL and you are not the owner of $dirPath and its sub-content and so cannot modify extended ACL${recursTxt}.",
{ 'path_exists' => JSON::true, 'write_access' => JSON::false });
}
giveFsUserAccess($dirPath);
$retVal = evalOrDie({"cmd" => "getfattr${faclRecurs} -d --absolute-names '${fullPath}'",
"parseJsonFlag" => 0,
"msgIfErr" => "Error getting web eacl for $dirPath${recursTxt} in ModifyEacl"});
my $origSavedFattr = $retVal->{'res'};
my $retResFattr;
my $retErrMsgFattr;
my $retStderrFattr;
if (empty($webeacl)) { #remove
my $retVal = evalOrDie({"cmd" => "find '${fullPath}'${findNotRecurs} -exec setfattr -x user.webeacl '{}' \\;",
"dont_die" => 1,
"success_exit" => { 0 => 1 },
"parseJsonFlag" => 0,
"msgIfErr" => "Error removing webeacl for $dirPath in modifyEacl${recursTxt}"});
$retResFattr = $retVal->{'res'};
$retErrMsgFattr = $retVal->{'err_msg'};
$retStderrFattr = $retVal->{'stderr'};
} else {
my $retVal = evalOrDie({"cmd" => "find '${fullPath}'${findNotRecurs} -exec setfattr -n user.webeacl -v '${webeacl}' '{}' \\;",
"dont_die" => 1,
"success_exit" => { 0 => 1 },
"parseJsonFlag" => 0,
"msgIfErr" => "Error doing setfattr for webeacl for $dirPath in modifyEacl${recursTxt}"});
$retResFattr = $retVal->{'res'};
$retErrMsgFattr = $retVal->{'err_msg'};
$retStderrFattr = $retVal->{'stderr'};
}
if (!empty($retErrMsgFattr) || ($retStderrFattr =~ m/Permission denied/)) { #calls to setfattr failed, so set back to original value
my $resetEaclAndDieMsg = "Error setting web ACL for $dirPath in ModifyEacl${recursTxt}, resetting back to original values.";
if ($Config::DEBUG) {
$resetEaclAndDieMsg .= "\nerr_msg:\n${retErrMsgFattr}\nstderr:\n${retStderrFattr}\n";
}
resetEaclAndDie(undef, $origSavedFattr, $resetEaclAndDieMsg);
}
my $eacl_hash = eacl_str_to_hash($eacl);
delete $eacl_hash->{'u'}{$fsUser}; #don't let user modify any extended ACL for $fsUser
#but just add in rx priviliges for $fsUser as extended ACL
$eacl_hash->{'u'}{$fsUser} = { 'r' => 1, 'x' => 1 };
$eacl = eacl_hash_to_str($eacl_hash);
my $base_group_hash = $base_hash->{'g'} || {};
my @base_group_arr = keys %$base_group_hash;
if (@base_group_arr) {
my $base_group = $base_group_arr[0];
evalOrDie({ 'cmd' => "chgrp${faclRecurs} ${base_group} '${fullPath}'",
'parse_json_flag' => 0,
'msgIfErr' => "Error setting base group to '${base_group}' for '${dirPath}'${recursTxt}"});
}
evalOrDie({"cmd" => "setfacl${faclRecurs} -b '$fullPath'",
"parseJsonFlag" => 0,
"msgIfErr" => "Error resetting file system eacl to empty for $dirPath in ModifyEacl${recursTxt}"});
my $set_access_str;
if (!empty($eacl) && !empty($base_for_setfacl)) {
$set_access_str = $eacl . "," . $base_for_setfacl;
} elsif (!empty($eacl)) {
$set_access_str = $eacl;
} elsif (!empty($base_for_setfacl)) {
$set_access_str = $base_for_setfacl;
}
my $setFaclCmd = 'find \'' . $fullPath . '\'' . $findNotRecurs . ' -depth -exec setfacl -m ' . $set_access_str . ' \'{}\' \;'; #need to do bottom up (from leaves up the hierarchy)
my $retValSetfacl = evalOrDie({"cmd" => $setFaclCmd,
"dont_die" => 1,
"success_exit" => { 0 => 1 },
"parseJsonFlag" => 0,
"msgIfErr" => "Error setting file system eacl for $dirPath in ModifyEacl${recursTxt}"});
my $retResSetfacl = $retValSetfacl->{'res'};
my $retErrMsgSetfacl = $retValSetfacl->{'err_msg'};
if (defined($retErrMsgSetfacl)) { #call to setfacl failed, so set back to original value
resetEaclAndDie($origSavedAcl, $origSavedFattr, "Error setting file system eacl for $dirPath in ModifyEacl${recursTxt}, resetting back to original values");
}
my $retObj = { 'success' => JSON::true, 'msg' => "Successfully modified eACL of path ${dirPath}${recursTxt}",
'path_exists' => JSON::true,
'write_access' => JSON::true };
if ($justReturnFlag) {
return($retObj);
} else {
printHeader('application/json');
print to_json($retObj);
}
}
sub Share_form {
printHeader();
print <<EOF;
<html>
<head><title>Share</title>
<style>
#share {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#share td, #share th {
border: 1px solid #ddd;
padding: 8px;
}
#share tr:nth-child(even){background-color: #f2f2f2;}
#share tr:hover {background-color: #ddd;}
#share th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #004851;
color: #8D9093;
}
</style>
</head>
<body>
<center><h3>Share</h3></center>
Share a directory or file (<b>Dir or File Path</b>) with other users (whose LDAP usernames are passed comma separated in <b>Share Users</b>). The users will be given read web access (if they do not already have it) and then an email will be sent to them informing of the directory or file being shared (with links to view or download it). Also, specify whether you want to give read web access recursively (i.e. the specified path and all its sub paths and sub files) or only for the specified path. You must be the owner of the specified directory or file path (and of all sub paths and sub files for directories), or you will receive an error response. An SSH private key or the user's password must be provided in order to have file system extended ACL considered (otherwise only web-access extended ACL will be considered) and is required for any write operations like this service.
<form method='POST' enctype='multipart/form-data' action='${thisScriptName}'>
<table id="share"><tr><th>INPUT</th><th>INPUT VALUE</th></tr>
<tr><td>Dir or File Path:</td><td><input style="width:100%" type=text name=dir_path /></td></tr>
<tr><td>Share Users:</td><td><input style="width:100%" type=text name=share_users /></td></tr>
<tr><td>Filesystem:</td><td>${fsSelTxt}</td></tr>
<tr><td>Recursive?</td><td><select name=recursive>
<option selected value="0">No</option>
<option value="1">Yes</option>
</select></td></tr>
<tr><td>Password:</td><td><input style="width:100%" type=text name=user_password /></td></tr>
<tr><td>SSH Private Key:</td><td><textarea style="width:100%" rows=3 id=user_sshkey name=user_sshkey></textarea></td></tr>
</table><p>
<input type=submit value=Exec />
<input type=hidden name=a value=share />
<input type=hidden name=stage value=exec />
</form>
<hr><a href='${thisScriptName}'>home</a>
</body>
</html>
EOF
}
#Give the file system, e.g. irods, user rx access down the tree and also up the tree, so can
#access files based on web access rules on behalf of users
sub giveFsUserAccess {
my ($dirPath) = @_;
my $fullPath = $fsRoot . "/" . $dirPath;
my $retVal2 =
evalOrDie({"cmd" => "setfacl -R -m u:${fsUser}:rx '$fullPath'",
"parseJsonFlag" => 0,
"msgIfErr" => "Error giving $fsUser file system user access to $dirPath"});
my $parentDir = dirname($fullPath);
while (1) {
last if (($parentDir =~ m/^\/\s*$/) || empty($parentDir));
my $retVal = evalOrDie({"cmd" => "setfacl -m u:${fsUser}:rx '$parentDir'",
"parseJsonFlag" => 0,
"dont_die" => 1,
"msgIfErr" => "Error giving $fsUser file system user access to $dirPath"});
$parentDir = dirname($parentDir);
}
}
sub reverseGetfaclRes {
my ($faclRes) = @_;
my @faclSections = reverse map { rem_ws($_); } split /\n{2,}/, $faclRes;
my $reversed_faclRes = join("\n\n",@faclSections) . "\n\n";
return($reversed_faclRes);
}
sub Share {
my $findNotRecurs = " -maxdepth 0";
if ($recursive) { $findNotRecurs = ""; }
my $faclRecurs = " -R";
if (!$recursive) { $faclRecurs = ""; }
my $recursTxt = " recursively";
if (!$recursive) { $recursTxt = ""; }
if (!userProvidedCredentials()) {
cgi_die_json("Error in Share: write operations are only allowed via a user's credentials (SSH private key or password), please provide.");
}
if (empty($dirPath)) { #empty means the root directory of simple_stash, you can't change its eacl
cgi_die_json("Error in Share: you cannot modify the eACL of the root directory.", { 'path_exists' => JSON::true, 'write_access' => JSON::false });
}
$dirPath =~ s/\/+$//;
my $fullPath = $fsRoot . "/" . $dirPath;
if ($dirPath =~ m/^\//) {
cgi_die_json("Error in Share: The path must be a relative path (not absolute), with no leading \/ character. Files are stashed relative to the stash root of $fsRoot");
}
my ($dirPathPar, $dirPathLastPart) = parentPath($dirPath);
if (!defined($dirPathPar)) {
cgi_die_json("Error in Share: could not extract parent directory from '${dirPath}'");
}
my ($pathInfo_full_info, $pathInfo, $pathInfo_fs_user) = pathInfo([$dirPath,$dirPathPar],0);
if ($pathInfo_full_info->{'paths_info'}{$dirPath}{'doesnt_exist'}) {
cgi_die_json("Error in Share: path '${dirPath}' does not exist.", { 'path_exists' => JSON::false });
}
if (!defined($pathInfo) || !$pathInfo->{'paths_info'}{$dirPathPar}{'permissions'}{'x'}) { #access denied to modify acl
cgi_die_json("Error in ModifyEacl: access denied to path '${dirPath}'");
}
my $allPathsDown;
if ($recursive) {
my $errMsg;
($allPathsDown, $errMsg) = allPathsUnder($dirPath);
if (!defined($allPathsDown)) {
cgi_die_json("Error in Share, couldn't get all paths under '${dirPath}': $errMsg");
}
($pathInfo_full_info, $pathInfo, $pathInfo_fs_user) = pathInfo($allPathsDown,0);
} else {
$allPathsDown = [$dirPath];
}
my @notOwner = grep { my $curPath = $_;