forked from cPanelPeter/easyapachebuddy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasyapachebuddy.pl
executable file
·2952 lines (2645 loc) · 120 KB
/
easyapachebuddy.pl
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/local/cpanel/3rdparty/bin/perl
# Version 1.1
# This is a fork of apache2buddy.pl but modified for use on cPanel servers only checking EasyApache 4 settings
# (MultiPHP, DefaultPHP, PHP-FPM settings). users can be passed using the --user flag, and individual php-fpm settings will be displayed.
use Getopt::Long qw(:config no_ignore_case bundling pass_through);
use POSIX;
use Cpanel::SafeRun::Timed();
use Cpanel::JSON;
use JSON::MaybeXS qw(encode_json decode_json);
use strict;
use Time::Local;
use Time::Piece;
use Time::Seconds;
use File::Find;
#
# Version 1.3
#
############################################################################################################
#
# ___ __ _ ___ _ _ __ _ _ __ __ _ ___| |__ ___| |__ _ _ __| | __| |_ _
# / _ \/ _` / __| | | |/ _` | '_ \ / _` |/ __| '_ \ / _ \ '_ \| | | |/ _` |/ _` | | | |
# | __/ (_| \__ \ |_| | (_| | |_) | (_| | (__| | | | __/ |_) | |_| | (_| | (_| | |_| |
# \___|\__,_|___/\__, |\__,_| .__/ \__,_|\___|_| |_|\___|_.__/ \__,_|\__,_|\__,_|\__, |
# |___/ |_| |___/
#
# For cPanel Servers Only! - This will not run without cPanel
# Modified by Peter Elsner
# A fork of...
#
# __ ___ __ __ __ __
# ____ ____ ____ ______/ /_ ___ |__ \ / /_ __ ______/ /___/ /_ __ ____ / /
# / __ `/ __ \/ __ `/ ___/ __ \/ _ \__/ // __ \/ / / / __ / __ / / / / / __ \/ /
# / /_/ / /_/ / /_/ / /__/ / / / __/ __// /_/ / /_/ / /_/ / /_/ / /_/ / / /_/ / /
# \__,_/ .___/\__,_/\___/_/ /_/\___/____/_.___/\__,_/\__,_/\__,_/\__, (_) .___/_/
# /_/ /____/ /_/
#
#
#
############################################################################################################
# author: richard forth
# description: apache2buddy, a fork of apachebuddy that caters for apache2, obviously.
#
# Github Page: https://github.com/richardforth/apache2buddy
# Please only make pull requests from staging branch.
#
# [ INFO ] apache2buddy.pl is a fork of apachebuddy.pl.
# [ INFO ] MD5SUMs now availiable at https://raw.githubusercontent.com/richardforth/apache2buddy/master/md5sums.txt
# [ INFO ] SHA256SUMs now availiable at https://raw.githubusercontent.com/richardforth/apache2buddy/master/sha256sums.txt
# [ INFO ] apache2buddy.pl is now released under the Apache 2.0 License. See https://raw.githubusercontent.com/richardforth/apache2buddy/master/LICENSE
# [ INFO ] apache2buddy.pl is now hosted from github. See https://github.com/richardforth/apache2buddy
# [ INFO ] Changelogs and updates in github. See https://raw.githubusercontent.com/richardforth/apache2buddy/master/changelog
#
###########################################################################################################
#
# L I C E N S E
#
###########################################################################################################
#
# Copyright 2016 Richard Forth
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# The copyright line reads as my name, because I did a lot of work in making
# this fork a whole new beast, and the previous project was never distributed
# under any official license, I did get the blessing from Gus Maskowitz to
# publish it under the Apache License 2.0.
#
# The purpose of the license is to ensure that free software remains free, not
# as in "free beer" but in "freedom". The freedom to derive new software from
# this and to keep that software "free" too.
#
# But it is important to acknowldege too, that this is a derivative work from
# apachebuddy.pl. Even though it is not being maintained any more, I would like
# to acknowledge the talents of a few people:
#
# Major Hayden - for his inspiring work on MySQLTuner.pl
# Jacob Walcik - who is the credited author of apache2buddy.pl (see the first
# few lines of the original script code at http:// apachebuddy.pl)
# Gus Maskowitz - for his work on the script, though it is no longer maintained
# Will Parsons - for hosting the original script at http://apachebuddy.pl
#
# Here I note that I also do not maintain the old project, this is a complete
# fork and revamp of the original code, and is maintained separately.
#
# Please keep any and all credits in the source code, and if you derive a new
# software from it, by all means add your own credits.
#
#
############################################################################################################
# D I S C L A I M E R
############################################################################################################
#
# PLEASE NOTE THAT THIS IS DESIGNED AS A REPORTING TOOL ONLY
# ==============================================================
#
# There are no plans to make this script automatically change any apache configuration settings, as this
# could prove disasterous in production environments.
#
# Needless to say this script comes without any warranty or fitness for a particular use and you run it
# at your own risk.
#
# * * * * USE THIS SCRIPT AT YOUR OWN RISK * * * *
#
# Every care has been taken to make sure this does nothing bad, it should only be reading configuration
# files, and doing a bit of maths, and printing out a shiny report.
#
# Nothing more nothing less.
#
# Please pay special attention and review the source code before deciding whether you should run this on
# your systems.
#
# I am not responsible for any damage caused to your data, systems or hardware, loss of business, your
# marriage breaking down, getting your car or house reposessed, or ending up in prison or losing your job
# and drug habits developing , insolvency, bankruptcy, personal hygiene issues, disease or death that may
# stem as a direct result of running this script.
#
# YOU HAVE BEEN WARNED!
#
#
###########################################################################################################
#
# Note:
#
# If you really want to read all of the source code, I suggest that you start from the comment:
#
# ########################
# # BEGIN MAIN EXECUTION #
# ########################
#
# Because everything from this point to that, is just a bunch of subroutines that the script needs in order
# to be able to run, and it won't flow or make any sense until you start from the "start".
#
##########################################################################################################
## print usage
sub usage {
our $usage_output = <<'END_USAGE';
Usage: easyapachebuddy.pl [OPTIONS]
If no options are specified, the basic tests will be run.
-h, --help Print this help message
-p, --port=PORT Specify an alternate port to check (default: 80)
--pid=PID Specify a PID to bypass the "Multiple PIDS listening on port 80" error.
-v, --verbose Use verbose output (this is very noisy, only useful for debugging)
-n, --nocolor Use default terminal color, dont try to be all fancy!
-H, --noheader Do not show header title bar.
-N, --noinfo Do not show informational messages.
-K, --no-ok Do not show OK messages.
-W, --nowarn Do not show warning messages.
-L, --light-term Show colours for a light background terminal.
-r, --report Implies -HNWK or --noinfo --nowarn --no-ok --noheader --skip-maxclients --skip-php-fatal --skip-updates
--user username Used during PHP-FPM detection. You can pass multiple users by adding extra --user flags.
-P, --no-check-pid DON'T Check the Parent Pid File Size (only use if desperate for more info, results may be skewed).
--skip-maxclients Skip checking in maxclients was hit recently, can be slow, especialy if you have large log files.
--skip-php-fatal Skip checking for PHP FATAL errors, can be slow, especialy if you have large log files.
--skip-updates Skip checking for package updates, can be slow or problematic, causing the script to hang.
-O, --skip-os-version-check Skips past the OS version check.
Allows one to bypass EOL version showstopper but be mindful:
skipping the os version check is not recommended as features may be
deprecated or removed and easyapachebuddy is not backward compatible
with end of life operating systems, this may cause errors and unpredictable
behaviour.
Key:
[ -- ] = Information
[ @@ ] = Advisory
[ >> ] = Warning
[ !! ] = Critical
END_USAGE
print $usage_output;
}
########################
# GATHER CMD LINE ARGS #
########################
# if help is not asked for, we do not give it
my $help = "";
# by default, assume the terminal has dark background, eg putty
my $LIGHTBG = 0;
# if no port is specified, we default to 80
# on cPanel servers this should default to 443
my $port = 443;
# if no pid is specified, we default to 0
our $pid = 0;
our $major_redhat_version = "";
# by default, do not use verbose output
our $VERBOSE = "";
# by default, use color output
our $NOCOLOR = 0;
# by default, show news messages
our $NONEWS = 0;
# by default, show informational messages
our $NOINFO = 0;
# by default, show ok messages
our $NOOK = 0;
# by default, show warnings
our $NOWARN = 0;
# by default, show full output
our $REPORT = 0;
# by default, show header
our $NOHEADER = 0;
# by default, check pid size
our $NOCHKPID = 0;
# by default, check OS support
our $NOCHKOS = 0;
# add 'skip section' options...
# by default, do not skip maxclients check
our $SKIPMAXCLIENTS = 0;
# by default, do not skip php fatal errors check
our $SKIPPHPFATAL = 0;
# by default, do not skip updates check
our $SKIPUPDATES = 0;
# by default, undef @PHPFPMUSERS
our @PHPFPMUSERS = undef;
######################
# MORE OUR VARIABLES #
######################
# "cache" for os platrofm information: ( distro, version, codename )
our @os_platform;
# grab the command line arguments
GetOptions(
'help|h' => \$help,
'port|p:i' => \$port,
'pid:i' => \$pid,
'verbose|v' => \$VERBOSE,
'nocolor|n' => \$main::NOCOLOR,
'noinfo|N' => \$NOINFO,
'nowarn|W' => \$NOWARN,
'report|r' => \$REPORT,
'light-term|L' => \$LIGHTBG,
'no-ok|K' => \$NOOK,
'noheader|H' => \$NOHEADER,
'no-check-pid|P' => \$NOCHKPID,
'skip-maxclients' => \$SKIPMAXCLIENTS,
'skip-php-fatal' => \$SKIPPHPFATAL,
'skip-updates' => \$SKIPUPDATES,
'user=s' => \@PHPFPMUSERS,
'skip-os-version-check|O' => \$NOCHKOS,
'nonews' => \$NONEWS
);
if ( $REPORT ) {
$NOHEADER = 1;
$NOINFO = 1;
$NONEWS = 1;
$NOWARN = 1;
$NOOK = 1;
$SKIPMAXCLIENTS = 1;
$SKIPPHPFATAL = 1;
$SKIPUPDATES = 1;
}
# Declare constants such as ANSI COLOR schemes.
# TO SAVE CODE and thus also massively cut down on the file size, Ive decided to handle NOCOLOR here,
# instead of on every single line where I need to print something. it seems much simpler and cleaner
# to print an empty string rather than an escape sequence, rather than doubling up on print() statements.
our $RED;
our $GREEN;
our $YELLOW;
our $BLUE;
our $PURPLE;
our $CYAN;
our $ENDC;
our $BOLD;
our $UNDERLINE;
if ( ! $NOCOLOR ) {
if ( ! $LIGHTBG ) {
$RED = "\033[91m";
$GREEN = "\033[92m"; # Like a light green color, not good for light terminals, but perfect for dark, eg PuTTY, terminals.
$YELLOW = "\033[93m"; # Like a yellow color, not good for light terminals, but perfect for dark, eg PuTTY, terminals.
$BLUE = "\033[94m";
$PURPLE = "\033[95m"; # technically its Magento...
$CYAN = "\033[96m"; # Like a light blue color, not good for light terminals, but perfect for dark, eg PuTTY, terminals.
} else {
$RED = "\033[1m"; # bold all the things!
$GREEN = "\033[1m"; # bold all the things!
$YELLOW = "\033[1m"; # bold all the things!
$BLUE = "\033[1m"; # bold all the things!
$PURPLE = "\033[1m"; # bold all the things!
$CYAN = "\033[1m"; # bold all the things!
}
$ENDC = "\033[0m"; # reset the terminal color
$BOLD = "\033[1m"; # what it says on the tin, you can double up eg make a bold red: ${BOLD}${RED}Something${ENDC}
$UNDERLINE = "\033[4m"; # again you can double this one up.
} else {
$RED = ""; # SUPPRESS COLORS
$GREEN = ""; # SUPPRESS COLORS
$YELLOW = ""; # SUPPRESS COLORS
$BLUE = ""; # SUPPRESS COLORS
$PURPLE = ""; # SUPPRESS COLORS
$CYAN = ""; # SUPPRESS COLORS
$ENDC = ""; # SUPPRESS COLORS
$BOLD = ""; # SUPPRESS COLORS
$UNDERLINE = ""; # SUPPRESS COLORS
}
if ( ! -d '/usr/local/cpanel' ) {
show_crit_box();
print "${RED}cPanel Software Not Installed - easyapachebuddy.pl won't work here!\n${ENDC}";
exit;
}
sub get_os_platform {
return @main::os_platform if @main::os_platform; # we already know everything
my @py_scripts = (
# platform.linux_distribution() - This function is deprecated since Python 3.5
# and removed in Python 3.8. See alternative like the distro package.
"try:
import platform
print(platform.linux_distribution())
except AttributeError as e:
pass",
# platform.dist() - Deprecated since version 2.6.
"try:
import platform
print(platform.dist())
except AttributeError as e:
pass",
# distro.linux_distribution() - 'distro' is not default installed package
"try:
import distro
print(distro.linux_distribution())
except AttributeError as e:
pass
except ModuleNotFoundError as e:
pass"); # Note the pass is required because perl needs an empty result for error handling internally switching from python back to perl.
# We just want python to die quietly in a corner for aestehetic reasons.
# Check for python (new in Debian 9 as it doesnt come with it out of the box)
my $py_exists = 0;
for my $pyname ( qw / python3 python python2 / ) {
my $python = `which $pyname`;
chomp( $python );
unless ( $python ) {
show_crit_box();
print "Unable to locate the '$pyname' binary.\n";
next;
}
$py_exists = 1;
if ( ! $NOOK ) { show_ok_box(); print "The '$pyname' binary exists and is available for use: ${CYAN}$python${ENDC}\n" }
print "VERBOSE: Check OS platform\n" if $VERBOSE;
for my $pyscript (@py_scripts) {
print "VERBOSE: $python -c '$pyscript'\n" if $VERBOSE;
my $raw_platform = `$python -c \"$pyscript\"`;
# ('CentOS Linux', '7.3.1611', 'Core')
chomp($raw_platform);
next unless $raw_platform;
$raw_platform =~ s/[()']//g;
my ( $distro, $version, $codename ) = split( '\s*,\s+', $raw_platform);
next unless $distro;
@main::os_platform = ( $distro, $version, $codename );
return ( $distro, $version, $codename );
}
}
# we can't determine OS and Version
if ( $py_exists ) {
show_crit_box(); print "Python scripting failed. Python requires package 'distro' or 'platform' to determine the Operating System and Version.\n";
} else {
show_crit_box(); print "Unable to locate the any 'python' binary. This script requires python to determine the Operating System and Version.\n";
show_info_box(); print "${YELLOW}To fix this make sure the python2 or python3 package is installed.${ENDC}\n";
}
exit;
# XXX instead of calling exit() we can:
# @main::os_platform = ( 'Unknown Distro', '0.0', '' );
# return @main::os_platform;
}
sub check_os_support {
my ($distro, $version, $codename) = @_;
# Please dont make pull requests to add your distro to this list, that doesnt make it supported.
# The following distros are what I use to test and deploy easyapachebuddy and only these distro's are supported.
my @supported_os_list = ('Ubuntu',
'ubuntu',
'Red Hat Enterprise Linux',
'Red Hat Enterprise Linux Server',
'redhat',
'CentOS Linux',
'CentOS',
'centos',
'CloudLinux Server',
'CloudLinux',
'cloudlinux',
'AlmaLinux Linux',
'AlmaLinux',
'almalinux');
my %sol = map { $_ => 1 } @supported_os_list;
my @ubuntu_os_list = ('Ubuntu', 'ubuntu');
my %uol = map { $_ => 1 } @ubuntu_os_list;
my @redhat_os_list = ('Red Hat Enterprise Linux', 'redhat', 'CentOS Linux', 'AlmaLinux', 'Cloudlinux', 'CloudLinux', 'CloudLinux Server');
my %rol = map { $_ => 1 } @redhat_os_list;
# https://www.ubuntu.com/info/release-end-of-life
my @ubuntu_supported_versions = ('20.04');
my %usv = map { $_ => 1 } @ubuntu_supported_versions;
if (exists($sol{$distro})) {
if ( ! $NOOK ) { show_ok_box(); print "This distro is supported by easyapachebuddy.pl.\n" }
# If the OS is deemed unsupported, we still run, but you may get errors, however any github issues raised will not
# be entertained for unsupported or EOL OS releaases.
} if (exists($uol{$distro})) {
if (exists($usv{$version})) {
if ( ! $NOOK ) { show_ok_box(); print "This distro version is supported by easyapachebuddy.pl.\n" }
} else {
show_crit_box(); print "${RED}This distro version (${CYAN}$version${ENDC}${RED}) is not supported by easyapachebuddy.pl.${ENDC}\n";
# list supported Ubuntu versions
if ( ! $NOINFO ) { show_advisory_box(); print "${YELLOW}Supported Ubuntu (LTS ONLY) versions:${ENDC} '${CYAN}" . join("${ENDC}', '${CYAN}", @ubuntu_supported_versions) . "${ENDC}'. To run anyway (at your own risk), try -O or --skip-os-version-check.\n"}
exit;
}
} elsif (exists($rol{$distro})) {
# for red hat versions is not so clinical regarding the specific versions, however we need to be mindful of EOL versions eg RHEL 3, 4, 5, 6
# get major version from version string. note that redhatm centos and scientifc are al rebuilds of the same sources, variables therefore
# use the generic 'redhat' reference.
if ( $VERBOSE ) { print "VERBOSE -> RedHat Version: ". $version . "\n"}
my @redhat_version = split('\.', $version);
if ( $VERBOSE ) {
foreach my $item (@redhat_version) {
print "VERBOSE: ". $item . "\n";
}
}
$major_redhat_version = $redhat_version[0];
if ( $VERBOSE ) { print "VERBOSE -> Major RedHat Version Detected ". $major_redhat_version . "\n"}
if ($major_redhat_version lt 6 ) {
show_crit_box(); print "${RED}This distro version (${CYAN}$version${ENDC}${RED}) is not supported by easyapachebuddy.pl.${ENDC}\n";
exit;
}
} else {
show_crit_box(); print "${RED}This distro is not supported by easyapachebuddy.pl.${ENDC}\n";
# list supported OS distros
if ( ! $NOINFO ) { show_advisory_box(); print "${YELLOW}Supported Distro's:${ENDC} '${CYAN}" . join("${ENDC}', '${CYAN}", @supported_os_list) . "${ENDC}'. To run anyway (at your own risk), try -O or --skip-os-version-check.\n"}
exit;
}
}
sub systemcheck_large_logs {
my ($logdir) = @_;
if ( -d $logdir ) {
my @logs;
my $logfiles_raw = find(sub {push @logs, $File::Find::name if -s >= 1024000000;}, $logdir);
foreach my $log (@logs) {
chomp($log);
# Issue 255 skip reporting already gzipped logs, as they have already been rotated
if ( ! $log =~ m/\.gz$/ ) {
my $size = -s $log;
my $humansize = sprintf "%.2f", $size/1024/1024/1024;
show_crit_box(); print $log . " --> " . $humansize . "GB\b\n";
}
}
if (@logs == 0) {
if ( ! $NOOK ) { show_ok_box(); print "${GREEN}No large log files were found in ${CYAN}$logdir${ENDC}.\n"; }
} else {
show_advisory_box(); print "${YELLOW}Consider setting up a log rotation policy.${ENDC}\n";
show_advisory_box(); print "${YELLOW}Note: Log rotation should already be set up under normal circumstances, so very${ENDC}\n";
show_advisory_box(); print "${YELLOW}Large error logs can indicate a fundmental issue with the website / web application.${ENDC}\n";
}
}
# silently proceed if the folder doesnt exist
}
sub files_in_array_that_exist_and_are_readable {
# takes an array of filenames as argument, filters out files that may cause an exception later on.
# see issue #347
my @in_array = @_;
# Lets programatically rip through the array and work out which
# ones exist and put those in a new array.
my @out_array;
foreach my $file(@in_array) {
chomp($file);
# if the file exists, and we have permission to read it ( and we should, we are root after all if we got this far)
if ( -f $file && -r $file) {
push(@out_array,$file)
}
}
return @out_array;
}
# here we're going to build a list of the files included by the Apache
# configuration
sub build_list_of_files {
my ($base_apache_config,$apache_root) = @_;
# these to arrays will contain lists of Apache configuration files
# this is going to be the ultimate list of files that will be parsed
# searching for arguments
my @master_list;
# this will be a "scratch" space to store a list of files that
# currently need to be searched for more "include" lines
my @find_includes_in;
# put the main configuration file into the list of files we're going
# to include
push(@master_list,$base_apache_config);
# put the main configuration file into the list of files we need to
# search for include lines
push(@find_includes_in,$base_apache_config);
#get the Include lines from the main apache config
@master_list = find_included_files(\@master_list,\@find_includes_in,$apache_root);
}
# here we're going to build an array holding the content of all of the
# available configuration files
sub build_config_array {
my ($base_apache_config,$apache_root) = @_;
# these to arrays will contain lists of Apache configuration files
# this is going to be the ultimate list of files that will be parsed
# searching for arguments
my @master_list;
# this will be a "scratch" space to store a list of files that
# currently need to be searched for more "include" lines
my @find_includes_in;
# put the main configuration file into the list of files we're going
# to include
push(@master_list,$base_apache_config);
# put the main configuration file into the list of files we need to
# search for include lines
push(@find_includes_in,$base_apache_config);
#get the Include lines from the main apache config
@master_list = find_included_files(\@master_list,\@find_includes_in,$apache_root);
}
# this will find all of the files that need to be included
sub find_included_files {
my ($master_list, $find_includes_in, $apache_root) = @_;
# get the number of elements in the array
my $count = @$find_includes_in;
# this array will eventually hold the entire apache configuration
my @master_config_array;
# while there are still entries in this array, keep processing
while ( $count > 0 ) {
my $file = $$find_includes_in[0];
print "VERBOSE: Processing ".$file."\n" if $main::VERBOSE;
if(-d $file && $file !~ /\*$/) {
print "VERBOSE: Adding glob to ".$file.", is a directory\n" if $main::VERBOSE;
$file .= "/" if($file !~ /\/$/);
$file .= "*";
}
# open the file
open(FILE,$file) || die("Unable to open file: ".$file."\n");
# push the file into an array
my @file = <FILE>;
# put the file in the master configuration array
push(@master_config_array,@file);
# close the file
close(FILE);
# search the file for includes
foreach (@file) {
# this will be used to store a list of any new include
# lines found
# my @new_includes;
# if the line looks like an include, then we want to examine it
if ( $_ =~ m/^\s*include\s+/i ) {
# grab the included file name or file glob
$_ =~ s/\s*include\s+(.+)\s*/$1/i;
# strip out any quoting
$_ =~ s/['"]+//g;
# prepend the Apache root for files or
# globs that are relative
if ( $_ !~ m/^\// ) {
$_ = $apache_root."/".$_;
}
# check for file globbing
if(-d $_ && $_ !~ /\*$/) {
print "VERBOSE: Adding glob to ".$_.", is a directory\n" if $main::VERBOSE;
$_ .= "/" if($_ !~ /\/$/);
$_ .= "*";
}
if ( $_ =~ m/.*\*.*/ ) {
my $glob = $_;
my @include_files;
chomp($glob);
# if the include is a file glob,
# expand it and add the files
# to the list
my @new_includes = expand_included_files(\@include_files, $glob, $apache_root);
my @sane_includes = files_in_array_that_exist_and_are_readable(@new_includes);
push(@$master_list,@sane_includes);
push(@$find_includes_in,@sane_includes);
}
else {
# if it is not a glob, push the
# line into the configuration
# array
push(@$master_list,$_);
@$master_list = files_in_array_that_exist_and_are_readable(@$master_list);
push(@$find_includes_in,$_);
@$find_includes_in = files_in_array_that_exist_and_are_readable(@$find_includes_in);
}
}
# This extra bit of code is required for apache 2.4's new directive "IncludeOptional"
if ( $_ =~ m/^\s*includeoptional\s+/i ) {
# grab the included file name or file glob
$_ =~ s/\s*includeoptional\s+(.+)\s*/$1/i;
# strip out any quoting
$_ =~ s/['"]+//g;
# prepend the Apache root for files or
# globs that are relative
if ( $_ !~ m/^\// ) {
$_ = $apache_root."/".$_;
}
# check for file globbing
if(-d $_ && $_ !~ /\*$/) {
print "VERBOSE: Adding glob to ".$_.", is a directory\n" if $main::VERBOSE;
$_ .= "/" if($_ !~ /\/$/);
$_ .= "*";
}
if ( $_ =~ m/.*\*.*/ ) {
my $glob = $_;
my @include_files;
chomp($glob);
# if the include is a file glob,
# expand it and add the files
# to the list
my @new_includes = expand_included_files(\@include_files, $glob, $apache_root);
my @sane_includes = files_in_array_that_exist_and_are_readable(@new_includes);
push(@$master_list,@sane_includes);
push(@$find_includes_in,@sane_includes);
}
else {
# if it is not a glob, push the
# line into the configuration
# array
push(@$master_list,$_);
@$master_list = files_in_array_that_exist_and_are_readable(@$master_list);
push(@$find_includes_in,$_);
@$find_includes_in = files_in_array_that_exist_and_are_readable(@$find_includes_in);
}
}
}
# trim the first entry off the array now that we have
# processed it
shift(@$find_includes_in);
# get the new count of files left to look at
$count = @$find_includes_in;
}
# return the config array with the included files attached
return @master_config_array;
}
# this will expand a glob into a list of individual files
sub expand_included_files {
my ($include_files, $glob, $apache_root) = @_;
# use a call to ls to get a list of the files from the glob
my @files = `ls $glob 2> /dev/null`;
# add the files from the glob to the array we're going to pass back
foreach(@files) {
chomp($_);
if ( -f $_ ) {
push(@$include_files,$_);
print "VERBOSE: Adding ".$_." to list of files for processing\n" if $main::VERBOSE;
} else {
print "VERBOSE: Skipping ".$_." as it is a directory\n" if $main::VERBOSE;
}
}
# return the include_files array with the files from the glob attached
return @$include_files;
}
# search the configuration array for a defined value that is not inside of a
# virtual host
sub find_master_value {
my ($config_array, $model, $config_element) = @_;
# store our results in an array
my @results;
# used to control whether or not we are currently ignoring elements
# while searching the array
my $ignore = 0;
my $ignore_by_model = 0;
my $ifmodule_count = 0;
# apache has four available models - prefork, worker, event, and itk. only one can be
# in use at a time. we have already determined which model is being used. We also only
# support PreFork, any any one time three MPM's will need to be ignored.
my $ignore_model1;
my $ignore_model2;
my $ignore_model3; # always ignore MPM ITK
if ( $model =~ m/.*worker.*/i ) {
$ignore_model1 = "prefork";
$ignore_model2 = "event";
$ignore_model3 = "itk";
} elsif ( $model =~ m/.*event.*/i ) {
$ignore_model1 = "worker";
$ignore_model2 = "prefork";
$ignore_model3 = "itk";
} else {
# default to prefork
$ignore_model1 = "worker";
$ignore_model2 = "event";
$ignore_model3 = "itk";
}
print "VERBOSE: Searching Apache configuration for the ".$config_element." directive\n" if $main::VERBOSE;
# search for the string in the configuration array
foreach (@$config_array) {
# ignore lines that are comments
if ( $_ !~ m/^\s*#/ ) {
chomp($_);
# we ignore lines that are within a Directory, Location,
# File, or Virtualhost block
# check to see if we have an opening tag for one of the
# block types listed above
if ( $_ =~ m/^\s*<(directory|location|files|virtualhost|ifmodule\s.*$ignore_model1|ifmodule\s.*$ignore_model2|ifmodule\s.*$ignore_model3)/i ) {
#print "Starting to ignore lines: ".$_."\n";
$ignore = 1;
}
# check for a closing block to stop ignoring lines
if ( $_ =~ m/^\s*<\/(directory|location|files|virtualhost|ifmodule)/i ) {
#print "Starting to watch lines: ".$_."\n";
$ignore = 0;
}
# if we're not ignoring lines, check and see if we've
# found the configuration element we're looking for
if ( $ignore != 1 ) {
# if we find a match
if ( $_ =~ m/^\s*$config_element\s+.*/i ) {
chomp($_);
$_ =~ s/^\s*$config_element\s+(.*)/$1/i;
$_ =~ s/\r//g;
push(@results,$_);
}
}
}
}
# if we find multiple definitions for the same element, we should
# return the last one
my $result;
if ( @results > 1 ) {
$result = $results[@results - 1];
}
else {
$result = $results[0];
}
#Result not found
if (@results == 0) {
$result = "CONFIG NOT FOUND";
}
print "VERBOSE: $result \n" if $main::VERBOSE;
# Ubuntu does not store the Apache user, group, or pidfile definitions
# in the apache2.conf file. instead, variables are in the configuration
# file and the real values are in /etc/apache2/envvars. this is a
# workaround for that behavior.
if ( $config_element =~ m/[users|group|pidfile]/i && $result =~ m/^\$/i ) {
if ( -e "/etc/debian_version" && -e "/etc/apache2/envvars") {
print "VERBOSE: Using Ubuntu workaround for: ".$config_element."\n" if $main::VERBOSE;
print "VERBOSE: Processing /etc/apache2/envvars\n" if $main::VERBOSE;
open(ENVVARS,"/etc/apache2/envvars") || die "Could not open file: /etc/apache2/envvars\n";
my @envvars = <ENVVARS>;
close(ENVVARS);
# change "pidfile" to match Ubuntu's "pid_file"
# definition
if ( $config_element =~ m/pidfile/i ) {
$config_element = "pid_file";
}
foreach (@envvars) {
if ( $_ =~ m/.*$config_element.*/i ) {
chomp($_);
$_ =~ s/^.*=(.*)\s*$/$1/i;
$result = $_;
}
}
}
}
# return the value to the main program
return $result;
}
# this will examine the memory usage of the apache processes and return one of
# three different outputs: average usage across all processes, the memory usage
# by the largest process, or the memory usage by the smallest process
sub get_memory_usage {
my ($process_name, $apache_user_running, $search_type) = @_;
my (@proc_mem_usages, $result);
print "VERBOSE: Get '".$search_type."' memory usage\n" if $main::VERBOSE;
# get a list of the pid's for apache running as the appropriate user
my @pids = `ps aux | grep $process_name | grep "^$apache_user_running\\s" | awk \'{ print \$2 }\'`;
# if length of @pids is still zero then die with an error.
if (@pids == 0) {
show_crit_box(); print ("Error getting a list of PIDs\n");
print ("DEBUG -> Process Name: ".$process_name."\nDEBUG -> Apache_user: ".$apache_user_running."\nDEBUG -> Search Type: ".$search_type."\n\n");
exit 1;
}
# figure out how much memory each process is using
foreach (@pids) {
chomp($_);
# pmap -d is used to determine the memory usage for the
# individual processes
my ($distro, $version, $codename) = get_os_platform();
#output of 'pmap' is different depending on distro!
my $pid_mem_usage;
$pid_mem_usage = `LANGUAGE=en_GB.UTF-8 pmap -d $_ | egrep "writeable/private" | awk \'{ print \$4 }\'`;
$pid_mem_usage =~ s/K//;
chomp($pid_mem_usage);
print "VERBOSE: Memory usage by PID ".$_." is ".$pid_mem_usage."K\n" if $main::VERBOSE;
# on a busy system, the grep output will return the pid for the
# grep process itself, which will be gone by the time we get
# around to running pmap
if ( $pid_mem_usage ne "" ) {
push(@proc_mem_usages, $pid_mem_usage);
}
}
# examine the array
if ( $search_type eq "high" ) {
# to find the largest process, sort the values from largest to
# smallest and take the first one
@proc_mem_usages = sort { $b <=> $a } @proc_mem_usages;
$result = $proc_mem_usages[0] / 1024;
}
if ( $search_type eq "low" ) {
# to find the smallest process, sort the values from smallest to
# largest and take the first one
@proc_mem_usages = sort { $a <=> $b } @proc_mem_usages;
$result = $proc_mem_usages[0] / 1024;
}
if ( $search_type eq "average" ) {
# to get the average, add up the total amount of memory used by
# each process, and then divide by the number of processes
my $sum = 0;
my $count;
foreach (@proc_mem_usages) {
$sum = $sum + $_;
$count++;
}
# our result is in kilobytes, convert it to megabytes before
# returning it
$result = $sum / $count / 1024;
}
# round off the result
$result = round($result);
return $result;
}
# this function accepts the path to a file and then tests to see whether the
# item at that path is an Apache binary
sub test_process {
my ($process_name) = @_;
# THIS SUBROUTINE WORKS FINE WITH httpd4u EXECUTABLES TOO.
# Reduce to only aphanumerics, to deal with "nginx: master process" or any newlnes
$process_name = `echo -n $process_name | sed 's/://g'`;
# the first line of output from "httpd -V" should tell us whether or
# not this is Apache
our @output;
if ( $process_name eq '/usr/sbin/httpd' ) {
@output = `LANGUAGE=en_GB.UTF-8 $process_name -V 2>&1 | grep "Server version"`;
print "VERBOSE: First line of output from \"$process_name -V\": $output[0]\n" if $main::VERBOSE;
} elsif ( $process_name eq '/usr/sbin/httpd.worker' ) {
# Handle Worker processes better
# BUGFIX, first identified by C. Piper Balta
@output = `LANGUAGE=en_GB.UTF-8 $process_name -V 2>&1 | grep "Server version"`;
print "VERBOSE: First line of output from \"$process_name -V\": $output[0]\n" if $main::VERBOSE;
} elsif ( $process_name eq '/usr/sbin/apache2' ) {
@output = `LANGUAGE=en_GB.UTF-8 /usr/sbin/apache2ctl -V 2>&1 | grep "Server version"`;
print "VERBOSE: First line of output from \"/usr/sbin/apache2ctl -V\": $output[0]\n" if $main::VERBOSE;
} elsif ( $process_name eq '/usr/local/apache/bin/httpd' ) {
if ( ! $NOWARN ) { show_warn_box(); print "${RED}Apache seems to have been installed from source, its technically unsupported, we may get errors${ENDC}\n" }
@output = `LANGUAGE=en_GB.UTF-8 $process_name -V 2>&1 | grep "Server version"`;
print "VERBOSE: First line of output from \"/usr/local/apache/bin/httpd -V\": $output[0]\n" if $main::VERBOSE;
} elsif ( $process_name eq '/opt/apache2/bin/httpd' ) {
if ( ! $NOWARN ) { show_warn_box(); print "${RED}Apache seems to have been installed from a self build package, its technically unsupported, we may get errors${ENDC}\n" }
@output = `LANGUAGE=en_GB.UTF-8 $process_name -V 2>&1 | grep "Server version"`;
print "VERBOSE: First line of output from \"/opt/apache2/bin/httpd -V\": $output[0]\n" if $main::VERBOSE;
} else {
# this catchall should cover all other possibilities, such as
# nginx, varnish, etc.
# BUGFIX, first identified by C. Piper Balta.
my $return_val = 0;
return $return_val;
}
my $return_val = 0;
#if ( $output eq '' ) {
# $return_val = 0;
#}
# check for valid variable
if ( ! $output[0] ) {
show_crit_box();
print "${RED}Something went wrong, and I suspect you have a syntax error in your apache configuration.${ENDC}\n";
show_crit_box();
print "${YELLOW}See \"${CYAN}systemctl status httpd.service${ENDC}\" ${YELLOW}and \"${CYAN}journalctl -xe${ENDC}\" ${YELLOW}for details.${ENDC}\n";
exit;
} else {
# check for output matching Apache'
if ( $output[0] =~ m/^Server version.*Apache\/[0-9].*/ ) {
$return_val = 1;
}
elsif ( $output[0] =~ m/^Server version.*Server\/[0-9].*/ ) {
print "${YELLOW}Apache server was build with version string \"${CYAN}Server version: Server/....${YELLOW}\" and not as usual \"${CYAN}Server version: Apache/....${YELLOW}\"${ENDC}\n";