-
Notifications
You must be signed in to change notification settings - Fork 0
/
webmin.py
executable file
·3192 lines (2933 loc) · 105 KB
/
webmin.py
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
# -*- coding: UTF-8 -*-
#
# webmin.py
# Python implementation of web-lib.pl
#
# Written by Peter Åstrand <astrand@cendio.se>
# Copyright (C) 2002-2007 Cendio Systems AB (http://www.cendio.se)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Coding style: Max linewidth 120 chars
#
import socket
import os
import sys
import re
import types
import cgi
import time
import cgi
# added for use in create_user_config_dirs()
import pwd,os.path
#
# Global variables
#
# Make sure to define these as global in funtions, if you want to change them.
#
# main:: variables
session_id = None
read_file_cache = None
tempfilecount = 0
done_webmin_header = 0
whatfailed = None
# A dictionary with lists, like: {"john": ["webmin", "bsdexports"]}
acl_array_cache = {}
# NOTE: I cannot understand what acl_hash_cache is good for in webmin.py. Therefore,
# I'm not using it at all.
done_foreign_require = None
foreign_args = None
no_acl_check = None
no_referers_check = None
locked_file_list = None
locked_file_data = None
locked_file_type = None
locked_file_diff = None
action_id_count = None
done_seed_random = None
# Miscellaneous
text = {}
tconfig = {}
config = {}
gconfig = {}
userconfig = {}
module_name = None
module_config_directory = None
# In web-lib.pl, tb is either "" or "bgcolor=#something". I think this
# is ugly and it makes it hard to use HTMLgen. In webmin.py, tb is
# either None or the color string like "#9999ff". Same goes for cb.
tb = None
cb = None
scriptname = None
remote_user = None
remote_user_info = None
base_remote_user = None
root_directory = None
module_root_directory = None
module_categories = {}
current_lang = "en"
default_lang = "en"
list_languages_cache = []
force_charset = None
user_module_config_directory = None
pragma_no_cache = None
loaded_theme_library = None
module_info = None
indata = None
theme_no_table = 0
anonymous_user = 0
webmin_module = globals()
# ----------------------------------------------------------------
# Themes
#
# A string with the current theme name
current_theme = None
# ----------------------------------------------------------------
# Perl compatibility functions
#
def die(msg):
print >> sys.stderr, msg
sys.exit(1)
# Configuration and spool directories
try:
config_directory = os.environ["WEBMIN_CONFIG"]
except KeyError:
die("WEBMIN_CONFIG not set")
try:
var_directory = os.environ["WEBMIN_VAR"]
except KeyError:
die("WEBMIN_VAR not set")
try:
session_id = os.environ["SESSION_ID"]
del os.environ["SESSION_ID"]
except KeyError:
pass
def read_file(file, dict=None):
"""Return a dictionary with name=value pairs from a file
If an existing dictionary is given, it will be updated
Note: Currently there is not way to check if the read failed or not.
This function should probably raise an exception on error.
"""
if dict == None:
dict = {}
try:
f = open(file)
except:
return dict
for line in f:
# Get rid of \n
line = line.rstrip()
if not line:
continue
if line.startswith("#"):
continue
try:
(name, value) = line.split("=")
except ValueError:
# We fail silently here, because that's the the Perl module does.
continue
name = name.strip()
value = value.strip()
dict[name] = value
return dict
def read_file_cached(file, dict=None):
"""Like read_file, but reads from a cache if the file has already been read
"""
# FIXME
if dict == None:
dict = {}
return read_file(file, dict)
def write_file(file, newdict):
"""Write out the contents of an associative array as name=value lines"""
# FIXME: Maybe preserve order, some day.
dict = read_file(file)
dict.update(newdict)
f = open(file, "w")
for key in dict.keys():
print >> f, "%s=%s" % (key, dict[key])
# FIXME
#if read_file_cached: update...
def html_escape(s):
"""Convert &, < and > codes in text to HTML entities"""
return cgi.escape(s)
## tempname([filename])
def tempname():
raise NotImplementedError
## Returns a mostly random temporary file name
#sub tempname
#{
#local $tmp_dir = -d $remote_user_info[7] ? "$remote_user_info[7]/.tmp" :
# @remote_user_info ? "/tmp/.webmin-$remote_user" :
# "/tmp/.webmin";
#while(1) {
# local @st = lstat($tmp_dir);
# last if ($st[4] == $< && $st[5] == $( && $st[2] & 0x4000 &&
# ($st[2] & 0777) == 0755);
# if (@st) {
# unlink($tmp_dir) || rmdir($tmp_dir) ||
# system("/bin/rm -rf \"$tmp_dir\"");
# }
# mkdir($tmp_dir, 0755) || next;
# chown($<, $(, $tmp_dir);
# chmod(0755, $tmp_dir);
# }
#if (defined($_[0]) && $_[0] !~ /\.\./) {
# return "$tmp_dir/$_[0]";
# }
#else {
# $main::tempfilecount++;
# &seed_random();
# return $tmp_dir."/".int(rand(1000000))."_".
# $main::tempfilecount."_".$scriptname;
# }
#}
#
## trunc
def trunc():
raise NotImplementedError
## Truncation a string to the shortest whole word less than or equal to
## the given width
#sub trunc {
# local($str,$c);
# if (length($_[0]) <= $_[1])
# { return $_[0]; }
# $str = substr($_[0],0,$_[1]);
# do {
# $c = chop($str);
# } while($c !~ /\S/);
# $str =~ s/\s+$//;
# return $str;
#}
#
## indexof
def indexof():
raise NotImplementedError
## Returns the index of some value in an array, or -1
#sub indexof {
# local($i);
# for($i=1; $i <= $#_; $i++) {
# if ($_[$i] eq $_[0]) { return $i - 1; }
# }
# return -1;
# }
#
## unique
def unique():
raise NotImplementedError
## Returns the unique elements of some array
#sub unique
#{
#local(%found, @rv, $e);
#foreach $e (@_) {
# if (!$found{$e}++) { push(@rv, $e); }
# }
#return @rv;
#}
#
## sysprint(handle, [string]+)
def sysprint():
raise NotImplementedError
#sub sysprint
#{
#local($str, $fh);
#$str = join('', @_[1..$#_]);
#$fh = $_[0];
#syswrite $fh, $str, length($str);
#}
#
## check_ipaddress(ip)
def check_ipaddress(ip):
raise NotImplementedError
## Check if some IP address is properly formatted
#sub check_ipaddress
#{
#return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
# $1 >= 0 && $1 <= 255 &&
# $2 >= 0 && $2 <= 255 &&
# $3 >= 0 && $3 <= 255 &&
# $4 >= 0 && $4 <= 255;
#}
#
def generate_icon(image, title, link=None):
if link:
print "<table border><tr><td>"
print "<a href='%s'><img src='%s' alt='' border=0 " % (link, image),
print "width=48 height=48></a></td></tr></table>"
print "<a href='%s'>%s</a>" % (link, title)
else:
print "<table border><tr><td>"
print "<img src='%s' alt='' border=0 width=48 height=48>" % image,
print "</td></tr></table>"
print title
## urlize
def urlize():
raise NotImplementedError
## Convert a string to a form ok for putting in a URL
#sub urlize {
# local $rv = $_[0];
# $rv =~ s/([^A-Za-z0-9])/sprintf("%%%2.2X", ord($1))/ge;
# return $rv;
#
## local($tmp, $tmp2, $c);
## $tmp = $_[0];
## $tmp2 = "";
## while(($c = chop($tmp)) ne "") {
## if ($c !~ /[A-z0-9]/) {
## $c = sprintf("%%%2.2X", ord($c));
## }
## $tmp2 = $c . $tmp2;
## }
## return $tmp2;
#}
#
## un_urlize(string)
def un_urlize():
raise NotImplementedError
## Converts a URL-encoded string to the original
#sub un_urlize
#{
#local $rv = $_[0];
#$rv =~ s/\+/ /g;
#$rv =~ s/%(..)/pack("c",hex($1))/ge;
#return $rv;
#}
#
def include(file):
"""Read and output the named file"""
if os.path.exists(file):
print open(file).read()
## copydata
def copydata():
raise NotImplementedError
## Read from one file handle and write to another
#sub copydata
#{
#local($line, $out, $in);
#$out = $_[1];
#$in = $_[0];
#while($line = <$in>) {
# print $out $line;
# }
#}
#
def ReadParseMime():
raise NotImplementedError
# ReadParseMime
# Read data submitted via a POST request using the multipart/form-data coding
#sub ReadParseMime
#{
#local ($boundary, $line, $foo, $name);
#$ENV{CONTENT_TYPE} =~ /boundary=(.*)$/;
#$boundary = $1;
#<STDIN>; # skip first boundary
#while(1) {
# $name = "";
# # Read section headers
# local $lastheader;
# while(1) {
# $line = <STDIN>;
# $line =~ s/\r|\n//g;
# last if (!$line);
# if ($line =~ /^(\S+):\s*(.*)$/) {
# $header{$lastheader = lc($1)} = $2;
# }
# elsif ($line =~ /^\s+(.*)$/) {
# $header{$lastheader} .= $line;
# }
# }
#
# # Parse out filename and type
# if ($header{'content-disposition'} =~ /^form-data(.*)/) {
# $rest = $1;
# while ($rest =~ /([a-zA-Z]*)=\"([^\"]*)\"(.*)/) {
# if ($1 eq 'name') {
# $name = $2;
# }
# else {
# $foo = $name . "_$1";
# $in{$foo} = $2;
# }
# $rest = $3;
# }
# }
# else {
# &error("Missing Content-Disposition header");
# }
# if ($header{'content-type'} =~ /^([^\s;]+)/) {
# $foo = $name . "_content_type";
# $in{$foo} = $1;
# }
#
# # Read data
# $in{$name} .= "\0" if (defined($in{$name}));
# while(1) {
# $line = <STDIN>;
# if (!$line) { return; }
# if (index($line, $boundary) != -1) { last; }
# $in{$name} .= $line;
# }
# chop($in{$name}); chop($in{$name});
# if (index($line,"$boundary--") != -1) { last; }
# }
#}
#
def ReadParse():
global indata
indata = cgi.FieldStorage()
def _PrintHeader(charset=None):
"""Outputs the HTTP header for HTML"""
if pragma_no_cache and config.get("pragma_no_cache"):
print "Pragma: no-cache"
# FIXME: As far as I know, we should print \r as well.
if charset:
print "Content-type: text/html; Charset=%s\n" % charset
else:
print "Content-type: text/html\n"
# Flush
sys.stdout.flush()
sys.stderr.flush()
# Make sure further errors are visible.
sys.stderr = sys.stdout
def header(title, image=None, help=None, config=None, nomodule=None, nowebmin=None,
rightside="", header=None, body="", below=None):
"""Output a page header with some title and image. The header may also
include a link to help, and a link to the config page.
The header will also have a link to to webmin index, and a link to the
module menu if there is no config link.
"""
if done_webmin_header: return
for l in list_languages():
if l["lang"] == current_lang:
lang = l
if force_charset:
charset = force_charset
elif lang.has_key("charset"):
charset = lang["charset"]
else:
charset = "UTF-8"
_PrintHeader(charset)
_load_theme_library()
if webmin_module.has_key("theme_header"):
theme_header(title, image, help, config, nomodule, nowebmin,
rightside, header, body, below)
return
print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"\n\"http://www.w3.org/TR/REC-html40/loose.dtd\">"
if gconfig.has_key("real_os_type"):
os_type = gconfig["real_os_type"]
else:
os_type = gconfig["os_type"]
if gconfig.has_key("real_os_version"):
os_version = gconfig["real_os_version"]
else:
os_version = gconfig["os_version"]
print "<html>\n<head>"
if (charset):
print "<meta http-equiv=\"Content-Type\" "\
"content=\"text/html; charset=%s\">" % charset
print "<link rel='icon' href='/images/webmin_icon.png' type='image/png'>"
if gconfig.get("sysinfo") == 1:
print "<title>%s : %s on %s (%s %s)</title>" % \
(title, remote_user, get_system_hostname(), os_type, os_version)
else:
print "<title>%s</title>" % title
if header:
print header
if gconfig.get("sysinfo") == 0 and remote_user:
print "<SCRIPT LANGUAGE=\"JavaScript\">"
if os.environ.has_key("SSL_USER"):
userstring = " (SSL certified)"
elif os.environ.has_key("LOCAL_USER"):
userstring = " (Local user)"
else:
userstring = ""
print "defaultStatus=\"%s%s logged into %s %s on %s (%s %s)\";" % \
(remote_user, userstring, text["programname"], get_webmin_version(),
get_system_hostname(), os_type, os_version)
print "</SCRIPT>"
print tconfig.get("headhtml", ""),
if tconfig.has_key("headinclude"):
include(os.path.join(root_directory, current_theme,
tconfig["headinclude"]))
print "</head>"
bgcolor = tconfig.get("cs_page")
if not bgcolor:
bgcolor = gconfig.get("cs_page")
if not bgcolor:
bgcolor = "ffffff"
link = tconfig.get("cs_link")
if not link:
link = gconfig.get("cs_link")
if not link:
link = "0000ee"
text_color = tconfig.get("cs_text")
if not text_color:
text_color = gconfig.get("cs_text")
if not text_color:
text_color = "000000"
if tconfig.has_key("bgimage"):
bgimage = "background=" + tconfig["bgimage"]
else:
bgimage = ""
inbody = tconfig.get("inbody", "")
print "<body bgcolor=#%(bgcolor)s link=#%(link)s vlink=#%(link)s text=#%(text_color)s " \
"%(bgimage)s %(inbody)s %(body)s>" % locals()
hostname = get_system_hostname()
version = get_webmin_version()
prebody = tconfig.get("prebody", "")
if prebody:
prebody.replace("%HOSTNAME%", hostname)
prebody.replace("%VERSION%", version)
prebody.replace("%USER%", remote_user)
prebody.replace("%OS%", os_type + os_version)
print prebody
if tconfig.get("prebodyinclude"):
include(os.path.join(root_directory, current_theme,
tconfig["prebodyinclude"]))
if webmin_module.has_key("theme_prebody"):
theme_prebody(title, image, help, config, nomodule, nowebmin,
rightside, header, body, below)
print "<table width=100%><tr>"
if gconfig.get("sysinfo") == 2 and remote_user:
print "<td colspan=3 align=center>"
print "<tt>%s</tt>%s logged into %s %s on <tt>%s</tt> (%s %s)</td>" % \
(remote_user, userstring, text["programname"], version, os_type, os_version)
print "</tr> <tr>\n";
print "<td width=15% valign=top align=left>"
if os.environ.has_key("HTTP_WEBMIN_SERVERS"):
print "<a href='%s'>" % os.environ["HTTP_WEBMIN_SERVERS"]
print "%s</a><br>" % text["header_servers"]
if not nowebmin and not tconfig.has_key("noindex"):
acl = read_acl()
mc = acl.has_key(base_remote_user)
if gconfig.get("gotoone") and session_id and mc == 1:
print "<a href='%s/session_login.cgi?logout=1'> %s</a><br>" % \
(gconfig.get("webprefix", ""), text["main_logout"])
elif gconfig.get("gotoone") and mc == 1:
print "<a href='%s/switch_user.cgi'> %s</a><br>" % \
(gconfig.get("webprefix", ""), text["main_switch"])
else:
print "<a href='%s/?cat=%s'> %s </a><br>" % \
(gconfig.get("webprefix", ""), module_info.get("category"), text["header_webmin"])
if not nomodule:
print "<a href='%s/%s'> %s </a><br>" % \
(gconfig.get("webprefix", ""), module_name, text["header_module"])
if type(help) == types.ListType:
print hlink(text["header_help"], help[0], help[1]), "<br>"
elif help:
print hlink(text["header_help"], help), "<br>\n"
if config:
access = get_module_acl();
if not access.get("noconfig"):
if user_module_config_directory:
cprog = "uconfig.cgi"
else:
cprog = "config.cgi"
print "<a href='%s/%s?%s'> %s </a><br>" % \
(gconfig.get("webprefix", ""), cprog, module_name, text["header_config"])
print "</td>"
title.replace("ä", "ä")
title.replace("ö", "ö")
title.replace("å", "å")
title.replace("ü", "ü")
title.replace(" ", " ")
if image:
print "<td align=center width=70%> <img alt='%s' src='%s'></td>" % \
(image, image)
elif lang["titles"] and not gconfig.get("texttitles") and not tconfig.get("texttitles"):
print "<td align=center width=70%>"
for char in title:
charnum = ord(char)
if charnum > 127 and lang.get("charset"):
print "<img src='%s/images/letters/%d.%s.gif' alt='%s' align=bottom>" % \
(gconfig.get("webprefix", ""), charnum, lang["charset"], char)
elif char == "":
print "<img src='%s/images/letters/%d.gif' alt=' ' align=bottom>" % \
(gconfig.get("webprefix", ""), charnum)
else:
print "<img src='%s/images/letters/%d.gif' alt='%s' align=bottom>" % \
(gconfig.get("webprefix", ""), charnum, char)
if below:
print "<br>", below
print "</td>"
else:
print "<td align=center width=70%%><h1>%s</h1></td>" % title
print "<td width=15% valign=top align=right>"
print rightside
print "</td></tr></table>"
def footer(links=[], noendbody=None):
"""Output a footer for returning to some page
The links parameter is a list of two-tuples, containing url and name, like:
[('', 'module index'), ('list.cgi', 'users list')]
"""
_load_theme_library()
if webmin_module.has_key("theme_footer"):
theme_footer(links, noendbody)
return
for i in range(len(links)):
(url, name) = links[i]
if url != "/" or not tconfig.get("noindex"):
if url == "/":
url = "/?cat=" + module_info["category"]
elif url == "" and module_name:
url = "/%s/" % module_name
elif url.startswith("?") and module_name:
url = "/%s/" + url
if url.startswith("/"):
url = gconfig.get("webprefix", "") + url
if i == 0:
print "<a href='%s'><img alg='<-' align=middle border=0 "\
"src='%s/images/left.gif'></a>" % (url, gconfig.get("webprefix", ""))
else:
print " |"
print " <a href='%s'> %s</a>" % (url, textsub("main_return", name))
print "<br>\n";
if not noendbody:
postbody = tconfig.get("postbody")
if postbody:
hostname = get_system_hostname()
version = get_webmin_version()
os_type = gconfig.get("real_os_type")
if not os_type:
os_type = gconfig.get("os_type")
os_version = gconfig.get("real_os_version")
if not os_version:
os_version = gconfig.get("os_version")
postbody.replace("%HOSTNAME%", hostname)
postbody.replace("%VERSION%", version)
postbody.replace("%USER%", remote_user)
postbody.replace("%OS%", os_type + os_version)
print postbody
if tconfig.get("postbodyinclude"):
include(os.path.join(root_directory, current_theme,
tconfig['postbodyinclude']))
if webmin_module.has_key("theme_postbody"):
theme_postbody(links, noendbody)
print "</body></html>"
def _load_theme_library():
"""Load theme library"""
if not current_theme or not tconfig.get("functions") or loaded_theme_library:
return
filename = tconfig["functions"]
# HACK!
if filename.endswith(".pl"):
filename = filename[:-3] + ".py"
themefile = os.path.join(root_directory, current_theme, filename)
if not os.path.exists(themefile):
themefile = os.path.join(os.path.split(__file__)[0],
current_theme,
filename)
try:
execfile(themefile, webmin_module, webmin_module)
except IOError:
pass
def redirect(url=""):
"""Output headers to redirect the browser to some page"""
if url==None: url=""
server_port=os.environ.get("SERVER_PORT","")
https=os.environ.get("HTTPS","").upper()
script_name=os.environ.get("SCRIPT_NAME","")
if server_port == "443" and https == "ON":
port=""
elif server_port == "80" and https != "ON":
port=""
else:
port=":"+server_port
prot="http"
if https == "ON":
prot="https"
if gconfig.has_key("webprefixnoredir"):
wp=gconfig["webprefixnoredir"]
else:
wp=gconfig.get("webprefix","")
if re.compile("^(http|https|ftp|gopher):").search(url):
url=url
elif url.startswith("/"):
url="%s://%s%s%s%s" %(prot,os.environ.get("SERVER_NAME",""),port,wp,url)
elif re.compile("^(.*)\/[^\/]*$").search(script_name):
url="%s://%s%s%s/%s%s" %(prot,os.environ.get("SERVER_NAME",""),port,re.compile("^(.*)\/[^\/]*$").search(script_name).group(1),wp,url)
else:
url="%s://%s%s/%s%s" %(prot,os.environ.get("SERVER_NAME",""),port,wp,url)
print "Location: %s\n\n" % url
## kill_byname(name, signal)
def kill_byname(name, signal):
raise NotImplementedError
## Use the command defined in the global config to find and send a signal
## to a process matching some name
#sub kill_byname
#{
#local(@pids);
#@pids = &find_byname($_[0]);
#if (@pids) { kill($_[1], @pids); return scalar(@pids); }
#else { return 0; }
#}
#
## kill_byname_logged(name, signal)
def kill_byname_logged(name, signal):
raise NotImplementedError
## Like kill_byname, but also logs the killing
#sub kill_byname_logged
#{
#local(@pids);
#@pids = &find_byname($_[0]);
#if (@pids) { &kill_logged($_[1], @pids); return scalar(@pids); }
#else { return 0; }
#}
#
## find_byname(name)
def find_byname(name):
raise NotImplementedError
## Finds a process by name, and returns a list of matching PIDs
#sub find_byname
#{
#local($cmd, @pids);
#$cmd = $gconfig{'find_pid_command'};
#$cmd =~ s/NAME/"$_[0]"/g;
#@pids = split(/\n/, `($cmd) </dev/null 2>/dev/null`);
#@pids = grep { $_ != $$ } @pids;
#return @pids;
#}
#
def error(*message):
"""Display an error message and exit. The global variable whatfailed
must be set to the name of the operation that failed."""
_load_theme_library()
if not os.environ.has_key("REQUEST_METHOD"):
# Show text-only error
print >> sys.stderr, text["error"]
print >> sys.stderr, "-----"
if whatfailed:
print >> sys.stderr, whatfailed, " : "
else:
for msg in message:
print >> sys.stderr, msg
print >> sys.stderr, "-----"
elif webmin_module.has_key("theme_error"):
theme_error(*message)
else:
header(text['error'], "");
print "<hr>"
if whatfailed:
print >> sys.stderr, whatfailed, " : "
else:
for msg in message:
print >> sys.stderr, msg
print "<hr>"
footer()
def _error_setup():
# Note: this is probably a public function, although it is not lised on http://www.webmin.com/modules.html
raise NotImplementedError
## error_setup(message)
## Register a message to be prepended to all error strings
#sub error_setup
#{
#$main::whatfailed = $_[0];
#}
#
## wait_for(handle, regexp, regexp, ...)
def wait_for():
raise NotImplementedError
## Read from the input stream until one of the regexps matches..
#sub wait_for
#{
#local($hit, $c, $i, $sw, $rv, $ha); undef($wait_for_input);
##print STDERR "wait_for(",join(",", @_),")\n";
#$ha = $_[0];
#$codes =
#"undef(\$hit);\n".
#"while(1) {\n".
#" if ((\$c = getc($ha)) eq \"\") { return -1; }\n".
#" \$wait_for_input .= \$c;\n";
##" \$wait_for_input .= \$c;\nprint STDERR \$wait_for_input,\"\\n\";";
#for($i=1; $i<@_; $i++) {
# $sw = $i>1 ? "elsif" : "if";
# $codes .= " $sw (\$wait_for_input =~ /$_[$i]/i) { \$hit = $i-1; }\n";
# }
#$codes .=
#" if (defined(\$hit)) {\n".
#" \@matches = (-1, \$1, \$2, \$3, \$4, \$5, \$6, \$7, \$8, \$9);\n".
#" return \$hit;\n".
#" }\n".
#" }\n";
#$rv = eval $codes;
#if ($@) { &error("wait_for error : $@\n"); }
#return $rv;
#}
#
## fast_wait_for(handle, string, string, ...)
def fast_wait_for():
raise NotImplementedError
#sub fast_wait_for
#{
#local($inp, $maxlen, $ha, $i, $c, $inpl);
#for($i=1; $i<@_; $i++) {
# $maxlen = length($_[$i]) > $maxlen ? length($_[$i]) : $maxlen;
# }
#$ha = $_[0];
#while(1) {
# if (($c = getc($ha)) eq "") {
# &error("fast_wait_for read error : $!");
# }
# $inp .= $c;
# if (length($inp) > $maxlen) {
# $inp = substr($inp, length($inp)-$maxlen);
# }
# $inpl = length($inp);
# for($i=1; $i<@_; $i++) {
# if ($_[$i] eq substr($inp, $inpl-length($_[$i]))) {
# return $i-1;
# }
# }
# }
#}
#
def has_command(command):
"""Returns the full path if some command is in the path, None if not"""
for path_dir in os.environ["PATH"].split(os.pathsep):
fullpath = os.path.join(path_dir, command)
if os.path.exists(fullpath):
fstat = os.stat(fullpath)
if fstat[stat.ST_UID] == os.getuid():
# We own this file
if fstat[stat.ST_MODE] & stat.S_IXUSR:
return fullpath
else: continue
elif fstat[stat.ST_GID] == os.getgid():
# Our group
if fstat[stat.ST_MODE] & stat.S_IXGRP:
return fullpath
else: continue
else:
# Other
if fstat[stat.ST_MODE] & stat.S_IXOTH:
return fullpath
else: continue
return None
def make_date(seconds):
"""Converts a Unix date/time in seconds to a human-readable form """
# FIXME: Translation support. Make sure we use same format as web-lib.pl.
return time.ctime(seconds)
def file_chooser_button(input, choosetype, form=0, chroot="/", addmode=0,
ashtml=1):
"""Return HTML for a file chooser button, if the browser supports
Javascript.
@input: The name of the input field in which the filename/directory choosen
in the chooser should appear.
@choosetype: 0 if both file and directories should be selectable. 1 for
directories only.
@form: The form index for the form in which the input field in @input
exists.
@chroot: The path the chooser should begin with.
@addmode: I don't know what this is, but the parameter exists in the
perl implementation, so it's implemented here as well.
@ashtml: If this is set as 0, a hash suitable as argument to a
Input element in HTMLgen will be returned instead of a
string.
"""
ret = {'type':'button'}
ret['onClick'] = "ifield = document.forms[%d].%s; chooser = window.open('%s/chooser.cgi?add=%d&type=%s&chroot=%s&file='+ifield.value, 'chooser', 'toolbar=no,menubar=no,scrollbar=no,width=400,heigh=300'); chooser.ifield = ifield; window.ifield = ifield" % (form, input, gconfig.get('webprefix', ''), addmode, choosetype, chroot)
ret['value'] = '...'
if ashtml:
return "<input type=\"%(type)s\" onClick=%(onClick)s value=%(value)s>\n" % ret
else:
return ret
def read_acl():
"""Reads the acl file and return dictionary"""
global acl_array_cache
if not acl_array_cache:
for line in open(_acl_filename()):
# Get rid of \n
line = line.rstrip()
if not line: continue
match = re.search("^(\S+):\s*(.*)", line)
if match:
user = match.group(1)
modules = match.group(2).split()
acl_array_cache[user] = modules
# Available as global variables, but return anyway...
return acl_array_cache
def _acl_filename():
"""Returns the file containing the webmin ACL"""
return os.path.join(config_directory, "webmin.acl")
## get_miniserv_config(&array)
def _get_miniserv_config():
raise NotImplementedError