File:  [LON-CAPA] / doc / install / linux / install.pl
Revision 1.95: download - view: text, annotated - select for diffs
Mon Aug 5 13:36:59 2024 UTC (7 weeks, 6 days ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- mysql daemon is mariadb for SLES12 SP5 and Debian 10

    1: #!/usr/bin/perl
    2: # The LearningOnline Network 
    3: # Pre-installation script for LON-CAPA
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # http://www.lon-capa.org/
   24: #
   25: 
   26: use strict;
   27: use File::Copy;
   28: use Term::ReadKey;
   29: use Socket;
   30: use Sys::Hostname::FQDN();
   31: use DBI;
   32: use File::Spec;
   33: use Cwd();
   34: use File::Basename();
   35: use lib File::Basename::dirname(Cwd::abs_path($0));
   36: use LCLocalization::localize;
   37: 
   38: # ========================================================= The language handle
   39: 
   40: my %languages = (
   41:                   ar => 'Arabic', 
   42:                   de => 'German',
   43:                   en => 'English',
   44:                   es => 'Spanish (Castellan)',
   45:                   fa => 'Persian',
   46:                   fr => 'French', 
   47:                   he => 'Hebrew', 
   48:                   ja => 'Japanese',
   49:                   pt => 'Portuguese',
   50:                   ru => 'Russian',
   51:                   tr => 'Turkish',
   52:                   zh => 'Chinese Simplified'
   53:                ); 
   54: 
   55: use vars qw($lh $lang);
   56: $lang = 'en';
   57: if (@ARGV > 0) {
   58:     foreach my $poss (keys(%languages)) {
   59:         if ($ARGV[0] eq $poss) {
   60:             $lang = $ARGV[0]; 
   61:         }
   62:     }
   63: }
   64: 
   65: &get_language_handle($lang);
   66: 
   67: # Check user has root privs
   68: if (0 != $<) {
   69:     print &mt('This script must be run as root.')."\n".
   70:           &mt('Stopping execution.')."\n";
   71:     exit;
   72: }
   73: 
   74: 
   75: # Globals: filehandle LOG is global.
   76: if (!open(LOG,">>loncapa_install.log")) {
   77:     print &mt('Unable to open log file.')."\n".
   78:           &mt('Stopping execution.')."\n";
   79:     exit;
   80: } else {
   81:     print LOG '$Id: install.pl,v 1.95 2024/08/05 13:36:59 raeburn Exp $'."\n";
   82: }
   83: 
   84: #
   85: # Helper routines and routines to establish recommended actions
   86: #
   87: 
   88: sub get_language_handle {
   89:     my @languages = @_;
   90:     $lh=LCLocalization::localize->get_handle(@languages);
   91: }
   92: 
   93: sub mt (@) {
   94:     if ($lh) {
   95:         if ($_[0] eq '') {
   96:             if (wantarray) {
   97:                 return @_;
   98:             } else {
   99:                 return $_[0];
  100:             }
  101:         } else {
  102:             return $lh->maketext(@_);
  103:         }
  104:     } else {
  105:         if (wantarray) {
  106:             return @_;
  107:         } else {
  108:             return $_[0];
  109:         }
  110:     }
  111: }
  112: 
  113: sub texthash {
  114:     my (%hash) = @_;
  115:     foreach (keys(%hash)) {
  116:         $hash{$_}=&mt($hash{$_});
  117:     }
  118:     return %hash;
  119: }
  120: 
  121: 
  122: sub skip_if_nonempty {
  123:     my ($string,$error)=@_;
  124:     return if (! defined($error));
  125:     chomp($string);chomp($error);
  126:     if ($string ne '') {
  127:         print_and_log("$error\n".&mt('Stopping execution.')."\n");
  128:         return 1;
  129:     }
  130:     return;
  131: }
  132: 
  133: sub writelog {
  134:     while ($_ = shift) {
  135:         chomp();
  136:         print LOG "$_\n";
  137:     }
  138: }
  139: 
  140: sub print_and_log {
  141:     while ($_=shift) {
  142:         chomp();
  143:         print "$_\n";
  144:         print LOG "$_\n";
  145:     }
  146: }
  147: 
  148: sub get_user_selection {
  149:     my ($defaultrun) = @_;
  150:     my $do_action = 0;
  151:     my $choice = <STDIN>;
  152:     chomp($choice);
  153:     $choice =~ s/(^\s+|\s+$)//g;
  154:     my $yes = &mt('y');
  155:     if ($defaultrun) {
  156:         if (($choice eq '') || ($choice =~ /^\Q$yes\E/i)) {
  157:             $do_action = 1;
  158:         }
  159:     } else {
  160:         if ($choice =~ /^\Q$yes\E/i) {
  161:             $do_action = 1;
  162:         }
  163:     }
  164:     return $do_action;
  165: }
  166: 
  167: sub get_distro {
  168:     my ($distro,$gotprereqs,$updatecmd,$packagecmd,$installnow,$unknown);
  169:     $packagecmd = '/bin/rpm -q LONCAPA-prerequisites ';
  170:     if (-e '/etc/oracle-release') {
  171:         open(IN,'</etc/oracle-release');
  172:         my $versionstring=<IN>;
  173:         chomp($versionstring);
  174:         close(IN);
  175:         if ($versionstring =~ /^Oracle Linux Server release (\d+)/) {
  176:             my $version = $1;
  177:             $distro = 'oracle'.$1;
  178:             $updatecmd = 'yum install LONCAPA-prerequisites';
  179:             $installnow = 'yum -y install LONCAPA-prerequisites';
  180:         }
  181:     } elsif (-e '/etc/redhat-release') {
  182:         open(IN,'</etc/redhat-release');
  183:         my $versionstring=<IN>;
  184:         chomp($versionstring);
  185:         close(IN);
  186:         if ($versionstring =~ /^Red Hat Linux release ([\d\.]+) /) {
  187:             my $version = $1;
  188:             if ($version=~/^7\./) {
  189:                 $distro='redhat7';
  190:             } elsif ($version=~/^8\./) {
  191:                 $distro='redhat8';
  192:             } elsif ($version=~/^9/) {
  193:                 $distro='redhat9';
  194:             }
  195:         } elsif ($versionstring =~ /Fedora( Core)? release ([\d\.]+) /) {
  196:             my $version=$2;
  197:             if ($version - int($version) > .9) {
  198:                 $distro = 'fedora'.(int($version)+1);
  199:             } else {
  200:                 $distro = 'fedora'.int($version);
  201:             }
  202:             $updatecmd = 'yum install LONCAPA-prerequisites';
  203:             $installnow = 'yum -y install LONCAPA-prerequisites';
  204:         } elsif ($versionstring =~ /Red Hat Enterprise Linux [AE]S release ([\d\.]+) /) {
  205:             $distro = 'rhes'.$1;
  206:             $updatecmd = 'up2date -i LONCAPA-prerequisites';
  207:         } elsif ($versionstring =~ /Red Hat Enterprise Linux Server release (\d+)/) {
  208:             $distro = 'rhes'.$1;
  209:             $updatecmd = 'yum install LONCAPA-prerequisites';
  210:             $installnow = 'yum -y install LONCAPA-prerequisites';
  211:         } elsif ($versionstring =~ /Red Hat Enterprise Linux release (\d+)/) {
  212:             $distro = 'rhes'.$1;
  213:             $updatecmd = 'dnf install LONCAPA-prerequisites';
  214:             $installnow = 'dnf -y install LONCAPA-prerequisites';
  215:         } elsif ($versionstring =~ /CentOS(| Linux| Stream) release (\d+)/) {
  216:             $distro = 'centos'.$2;
  217:             if ($1 eq ' Stream') {
  218:                 $distro .= '-stream';
  219:             }
  220:             $updatecmd = 'yum install LONCAPA-prerequisites';
  221:             $installnow = 'yum -y install LONCAPA-prerequisites';
  222:         } elsif ($versionstring =~ /Scientific Linux (?:SL )?release ([\d.]+) /) {
  223:             my $ver = $1;
  224:             $ver =~ s/\.\d+$//;
  225:             $distro = 'scientific'.$ver;
  226:             $updatecmd = 'yum install LONCAPA-prerequisites';
  227:             $installnow = 'yum -y install LONCAPA-prerequisites';
  228:         } elsif ($versionstring =~ /Rocky Linux release ([\d.]+)/) {
  229:             my $ver = $1;
  230:             $ver =~ s/\.\d+$//;
  231:             $distro = 'rocky'.$ver;
  232:             $updatecmd = 'dnf install LONCAPA-prerequisites';
  233:             $installnow = 'dnf -y install LONCAPA-prerequisites';
  234:         } elsif ($versionstring =~ /AlmaLinux release ([\d.]+) /) {
  235:             my $ver = $1;
  236:             $ver =~ s/\.\d+$//;
  237:             $distro = 'alma'.$ver;
  238:             $updatecmd = 'dnf install LONCAPA-prerequisites';
  239:             $installnow = 'dnf -y install LONCAPA-prerequisites';
  240:         } else {
  241:             print &mt('Unable to interpret [_1] to determine system type.',
  242:                       '/etc/redhat-release')."\n";
  243:             $unknown = 1;
  244:         }
  245:     } elsif (-e '/etc/SuSE-release') {
  246:         open(IN,'</etc/SuSE-release');
  247:         my $versionstring=<IN>;
  248:         chomp($versionstring);
  249:         close(IN);
  250:         if ($versionstring =~ /^SUSE LINUX Enterprise Server ([\d\.]+) /i) {
  251:             $distro='sles'.$1;
  252:             if ($1 >= 10) {
  253:                 $updatecmd = 'zypper install LONCAPA-prerequisites';
  254:             } else {
  255:                 $updatecmd = 'yast -i LONCAPA-prerequisites';
  256:             }
  257:         } elsif ($versionstring =~ /^SuSE Linux ([\d\.]+) /i) {
  258:             $distro = 'suse'.$1;
  259:             $updatecmd = 'yast -i LONCAPA-prerequisites';
  260:         } elsif ($versionstring =~ /^openSUSE ([\d\.]+) /i) {
  261:             $distro = 'suse'.$1;
  262:             if ($1 >= 10.3 ) {
  263:                 $updatecmd = 'zypper install LONCAPA-prerequisites';
  264:             } else {
  265:                 $updatecmd = 'yast -i LONCAPA-prerequisites';
  266:             }
  267:         } else {
  268:             print &mt('Unable to interpret [_1] to determine system type.',
  269:                       '/etc/SuSE-release')."\n";
  270:             $unknown = 1;
  271:         }
  272:     } elsif (-e '/etc/issue') {
  273:         open(IN,'</etc/issue');
  274:         my $versionstring=<IN>;
  275:         chomp($versionstring);
  276:         close(IN);
  277:         if ($versionstring =~ /^Ubuntu (\d+)\.\d+/i) {
  278:             $distro = 'ubuntu'.$1;
  279:             $updatecmd = 'sudo apt-get install loncapa-prerequisites';
  280:         } elsif ($versionstring =~ /^Debian\s+GNU\/Linux\s+(\d+)\.\d+/i) {
  281:             $distro = 'debian'.$1;
  282:             $updatecmd = 'apt-get install loncapa-prerequisites';
  283:         } elsif (-e '/etc/debian_version') {
  284:             open(IN,'</etc/debian_version');
  285:             my $version=<IN>;
  286:             chomp($version);
  287:             close(IN);
  288:             if ($version =~ /^(\d+)\.\d+\.?\d*/) {
  289:                 $distro='debian'.$1;
  290:                 $updatecmd = 'apt-get install loncapa-prerequisites';
  291:             } else {
  292:                 print &mt('Unable to interpret [_1] to determine system type.',
  293:                           '/etc/debian_version')."\n";
  294:                 $unknown = 1;
  295:             }
  296:         }
  297:         if ($distro ne '') {
  298:             $packagecmd = '/usr/bin/dpkg -l loncapa-prerequisites ';
  299:         }
  300:     } elsif (-e '/etc/debian_version') {
  301:         open(IN,'</etc/debian_version');
  302:         my $version=<IN>;
  303:         chomp($version);
  304:         close(IN);
  305:         if ($version =~  /^(\d+)\.\d+\.?\d*/) {
  306:             $distro='debian'.$1;
  307:             $packagecmd = '/usr/bin/dpkg -l loncapa-prerequisites ';
  308:             $updatecmd = 'apt-get install loncapa-prerequisites';
  309:         } else {
  310:             print &mt('Unable to interpret [_1] to determine system type.',
  311:                       '/etc/debian_version')."\n";
  312:             $unknown = 1;
  313:         }
  314:     }
  315:     if (($distro eq '') && (!$unknown)) {
  316:         if (-e '/etc/os-release') {
  317:             if (open(IN,'<','/etc/os-release')) {
  318:                 my ($id,$version);
  319:                 while(<IN>) {
  320:                     chomp();
  321:                     if (/^ID="(\w+)"/) {
  322:                         $id=$1;
  323:                     } elsif (/^VERSION_ID="([\d\.]+)"/) {
  324:                         $version=$1;
  325:                     }
  326:                 }
  327:                 close(IN);
  328:                 if ($id eq 'sles') {
  329:                     my ($major,$minor) = split(/\./,$version);
  330:                     if ($major =~ /^\d+$/) {
  331:                         $distro = $id.$major;
  332:                         $updatecmd = 'zypper install LONCAPA-prerequisites';
  333:                     }
  334:                 }
  335:             }
  336:             if ($distro eq '') {
  337:                 print &mt('Unable to interpret [_1] to determine system type.',
  338:                           '/etc/os-release')."\n";
  339:                 $unknown = 1;
  340:             }
  341:         } else {
  342:             print &mt('Unknown installation: expecting a debian, ubuntu, suse, sles, redhat, fedora, scientific linux, or oracle linux system.')."\n";
  343:         }
  344:     }
  345:     return ($distro,$packagecmd,$updatecmd,$installnow);
  346: }
  347: 
  348: #
  349: # get_hostname() prompts the user to provide the server's hostname.
  350: #
  351: # If invalid input is provided, the routine is called recursively 
  352: # until, a valid hostname is provided.
  353: # 
  354: 
  355: sub get_hostname {
  356:     my $hostname;
  357:     print &mt('Enter the hostname of this server, e.g., loncapa.somewhere.edu'."\n");
  358:     my $choice = <STDIN>;
  359:     chomp($choice);
  360:     $choice =~ s/(^\s+|\s+$)//g;
  361:     if ($choice eq '') {
  362:         print &mt("Hostname you entered was either blank or contanied only white space.\n");
  363:     } elsif ($choice =~ /^[\w\.\-]+$/) {
  364:         $hostname = $choice;
  365:     } else {
  366:         print &mt("Hostname you entered was invalid --  a hostname may only contain letters, numbers, - and .\n");
  367:     }
  368:     while ($hostname eq '') {
  369:         $hostname = &get_hostname();
  370:     }
  371:     print "\n";
  372:     return $hostname;
  373: }
  374: 
  375: #
  376: # get_hostip() prompts the user to provide the server's IPv4 IP address
  377: #
  378: # If invalid input is provided, the routine is called recursively 
  379: # until, a valid IPv4 address is provided.
  380: #
  381: 
  382: sub get_hostip {
  383:     my $hostip;
  384:     print &mt('Enter the IP address of this server, e.g., 192.168.10.24'."\n");
  385:     my $choice = <STDIN>;
  386:     chomp($choice);
  387:     $choice =~ s/(^\s+|\s+$)//g;
  388:     my $badformat = 1;
  389:     if ($choice eq '') {
  390:         print &mt("IP address you entered was either blank or contained only white space.\n"); 
  391:     } else {
  392:         if ($choice =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/) {
  393:             if (($1<=255) && ($2<=255) && ($3<=255) && ($4<=255)) {
  394:                 $badformat = 0; 
  395:             }
  396:         }
  397:         if ($badformat) { 
  398:              print &mt('Host IP you entered was invalid -- a host IP has the format d.d.d.d where each d is an integer between 0 and 255')."\n";
  399:         } else {
  400:             $hostip = $choice;
  401:         }
  402:     }
  403:     while ($hostip eq '') {
  404:         $hostip = &get_hostip();
  405:     }
  406:     print "\n";
  407:     return $hostip;
  408: }
  409: 
  410: sub check_prerequisites {
  411:     my ($packagecmd,$distro) = @_;
  412:     my $gotprereqs;
  413:     if ($packagecmd ne '') {
  414:         if (open(PIPE,"$packagecmd|")) {
  415:             if ($distro =~ /^(debian|ubuntu)/) {
  416:                 my @lines = <PIPE>;
  417:                 chomp(@lines);
  418:                 foreach my $line (@lines) {
  419:                     if ($line =~ /^ii\s+loncapa-prerequisites\s+([\w\.]+)/) {
  420:                         $gotprereqs = $1;
  421:                     }
  422:                 }
  423:             } else {
  424:                 my $line = <PIPE>;
  425:                 chomp($line);
  426:                 if ($line =~ /^LONCAPA\-prerequisites\-([\d\-]+)\.(?:[.\w]+)$/) {
  427:                     $gotprereqs = $1;
  428:                 }
  429:             }
  430:             close(PIPE);
  431:         } else {
  432:             print &mt('Error: could not determine if LONCAPA-prerequisites package is installed')."\n";
  433:         }
  434:     }
  435:     return $gotprereqs;
  436: }
  437: 
  438: sub check_locale {
  439:     my ($distro) = @_;
  440:     my ($fh,$langvar,$command,$langcmd,$earlyout,$default);
  441:     $langvar = 'LANG';
  442:     if ($distro =~ /^(ubuntu|debian)/) {
  443:         if (!open($fh,"</etc/default/locale")) {
  444:             print &mt('Failed to open: [_1], default locale not checked.',
  445:                       '/etc/default/locale');
  446:             $earlyout = 1;
  447:         }
  448:     } elsif ($distro =~ /^(suse|sles)(\d+)/) {
  449:         if (($1 eq 'sles') && ($2 >= 15)) {
  450:             if (!open($fh,"</etc/locale.conf")) {
  451:                 print &mt('Failed to open: [_1], default locale not checked.',
  452:                           '/etc/locale.conf');
  453:                 $earlyout = 1;
  454:             }
  455:         } else {
  456:             if (!open($fh,"</etc/sysconfig/language")) {
  457:                 print &mt('Failed to open: [_1], default locale not checked.',
  458:                           '/etc/sysconfig/language');
  459:                 $earlyout = 1;
  460:             }
  461:             $langvar = 'RC_LANG';
  462:         }
  463:     } elsif ($distro =~ /^fedora(\d+)/) {
  464:         if ($1 >= 18) {
  465:             if (!open($fh,"</etc/locale.conf")) {
  466:                 print &mt('Failed to open: [_1], default locale not checked.',
  467:                           '/etc/locale.conf');
  468:                 $earlyout = 1;
  469:             }
  470:         } elsif (!open($fh,"</etc/sysconfig/i18n")) {
  471:             print &mt('Failed to open: [_1], default locale not checked.',
  472:                       '/etc/sysconfig/i18n');
  473:             $earlyout = 1;
  474:         }
  475:     } elsif ($distro =~ /^(?:rhes|centos|scientific|oracle|rocky|alma)(\d+)/) {
  476:         if ($1 >= 7) {
  477:             if (!open($fh,"</etc/locale.conf")) {
  478:                 print &mt('Failed to open: [_1], default locale not checked.',
  479:                           '/etc/locale.conf');
  480:                 $earlyout = 1;
  481:             }
  482:         } elsif (!open($fh,"</etc/sysconfig/i18n")) {
  483:             print &mt('Failed to open: [_1], default locale not checked.',
  484:                       '/etc/sysconfig/i18n');
  485:             $earlyout = 1;
  486:         }
  487:     } else {
  488:         if (!open($fh,"</etc/sysconfig/i18n")) {
  489:             print &mt('Failed to open: [_1], default locale not checked.',
  490:                       '/etc/sysconfig/i18n');
  491:             $earlyout = 1;
  492:         }
  493:     }
  494:     return () if ($earlyout);
  495:     my @data = <$fh>;
  496:     chomp(@data);
  497:     close($fh);
  498:     foreach my $item (@data) {
  499:         if ($item =~ /^\Q$langvar\E=\"?([^\"]*)\"?/) {
  500:             $default = $1;
  501:             if ($default ne 'en_US.UTF-8') {
  502:                 if ($distro =~ /^debian/) {
  503:                     $command = 'locale-gen en_US.UTF-8'."\n".
  504:                                'update-locale LANG=en_US.UTF-8';
  505:                 } elsif ($distro =~ /^ubuntu/) {
  506:                     $command = 'sudo locale-gen en_US.UTF-8'."\n".
  507:                                'sudo update-locale LANG=en_US.UTF-8';
  508:                 } elsif ($distro =~ /^(suse|sles)/) {
  509:                     $command = 'yast language';
  510:                 } elsif (-e '/usr/bin/system-config-language') {
  511:                     $command = 'system-config-language';
  512:                 } elsif (-e '/usr/bin/localectl') {
  513:                     $command = '/usr/bin/localectl set-locale LANG=en_US.UTF-8';
  514:                 } else {
  515:                     $command = 'No standard command found';
  516:                 }
  517:             }
  518:             last;
  519:         }
  520:     }
  521: # Check for locales
  522:     if ($default ne 'en_US.UTF-8') { 
  523:         my ($has_us_english,$has_other_code,$has_other_lang);
  524:         if (open(PIPE,"locale -a 2>/dev/null |")) {
  525:             while (<PIPE>) {
  526:                 chomp();
  527:                 next if (/^(C(|\.utf8)|POSIX)$/i);
  528:                 if (/^en_US\.utf8/i) {
  529:                     $has_us_english = 1;
  530:                 } elsif (/^[A-Za-z]{2}_[A-Za-z]{2}/) {
  531:                     $has_other_code = 1;
  532:                 } elsif (/^[A-Za-z]{3,}/) {
  533:                     $has_other_lang = 1;
  534:                 }
  535:             }
  536:             close(PIPE);
  537:             if (!$has_us_english) {
  538:                 if ($has_other_code || $has_other_lang) {
  539:                     if ($distro =~ /^ubuntu/) {
  540:                         $langcmd = "sudo apt-get install language-pack-en\n";
  541:                     } elsif ($distro =~ /^debian/) {
  542:                         $langcmd = "apt-get install language-pack-en\n";
  543:                     } elsif ($distro =~ /^(suse|sles)/) {
  544:                         $langcmd = &mt('Use yast: System > Language > Primary Language = English')."\n";
  545:                     } elsif ($distro =~ /^fedora(\d+)$/) {
  546:                         if ($1 > 23) {
  547:                             $langcmd = "dnf install glibc-langpack-en\n";
  548:                         } else {
  549:                             $langcmd = "yum install glibc-common\n";
  550:                         }
  551:                     } elsif ($distro =~ /^(?:rhes|centos|scientific|oracle|rocky|alma)(\d+)/) {
  552:                         if ($1 > 7) {
  553:                             $langcmd = "dnf install glibc-langpack-en\n";
  554:                         } else {
  555:                             $langcmd = "yum install glibc-common\n";
  556:                         }
  557:                     }
  558:                 } else {
  559:                     if ($distro =~ /^ubuntu/) {
  560:                         $langcmd = "sudo apt-get install language-pack-en\n";
  561:                     } elsif ($distro =~ /^debian/) {
  562:                         $langcmd = "apt-get install language-pack-en\n";
  563:                     } elsif ($distro =~ /^(suse|sles)/) {
  564:                         $langcmd = &mt('Use yast: System > Language > Primary Language = English')."\n";
  565:                     } elsif ($distro =~ /^fedora(\d+)$/) {
  566:                         if ($1 > 23) {
  567:                             $langcmd = &mt('Either install all languages[_1]or install English only[_2]',
  568:                                            ":\ndnf install glibc-all-langpacks\n\n",
  569:                                            ":\ndnf install glibc-langpack-en\n");
  570:                         } else {
  571:                             $langcmd = "yum install glibc-common\n";
  572:                         }
  573:                     } elsif ($distro =~ /^(?:rhes|centos|scientific|oracle|rocky|alma)(\d+)/) {
  574:                         if ($1 > 7) {
  575:                             $langcmd = &mt('Either install all languages[_1]or install English only[_2]',
  576:                                            ":\ndnf install glibc-all-langpacks\n\n",
  577:                                            ":\ndnf install glibc-langpack-en\n");
  578:                         } else {
  579:                             $langcmd = "yum install glibc-common\n";
  580:                         }
  581:                     }
  582:                 }
  583:             }
  584:         }
  585:     }
  586:     return ($command,$langcmd);
  587: }
  588: 
  589: sub check_required {
  590:     my ($instdir,$dsn) = @_;
  591:     my ($distro,$packagecmd,$updatecmd,$installnow) = &get_distro();
  592:     if ($distro eq '') {
  593:         return;
  594:     }
  595:     my $gotprereqs = &check_prerequisites($packagecmd,$distro); 
  596:     if ($gotprereqs eq '') {
  597:         return ($distro,$gotprereqs,'','',$packagecmd,$updatecmd);
  598:     }
  599:     my ($localecmd,$langcmd) = &check_locale($distro);
  600:     unless ($localecmd eq '') {
  601:         return ($distro,$gotprereqs,$localecmd,$langcmd);
  602:     }
  603:     my ($mysqlon,$mysqlsetup,$mysqlrestart,$dbh,$has_pass,$mysql_unix_socket,$has_lcdb,
  604:         %recommended,$downloadstatus,$filetouse,$production,$testing,$apachefw,
  605:         $tostop,$uses_systemctl,$mysql_has_wwwuser,$hostname,$hostip);
  606:     my $wwwuid = &uid_of_www();
  607:     my $wwwgid = getgrnam('www');
  608:     if (($wwwuid eq '') || ($wwwgid eq '')) {
  609:         $recommended{'wwwuser'} = 1;
  610:     }
  611:     unless( -e "/usr/local/sbin/pwauth") {
  612:         $recommended{'pwauth'} = 1;
  613:     }
  614:     $hostname = Sys::Hostname::FQDN::fqdn();
  615:     if ($hostname eq '') {
  616:         $hostname =&get_hostname();
  617:     } else {
  618:         print &mt("Hostname detected: $hostname. Is that correct? ~[Y/n~]");
  619:         if (!&get_user_selection(1)) {
  620:             $hostname =&get_hostname();
  621:         }
  622:     }
  623:     $hostip = Socket::inet_ntoa(scalar(gethostbyname($hostname)) || 'localhost');
  624:     if ($hostip eq '') {
  625:         $hostip=&get_hostip();
  626:     } else {
  627:         print &mt("Host IP address detected: $hostip. Is that correct? ~[Y/n~]");
  628:         if (!&get_user_selection(1)) {
  629:             $hostip=&get_hostip();
  630:         }
  631:     }
  632:     print_and_log("\n".&mt('Hostname is [_1] and IP address is [_2]',$hostname,$hostip)."\n");
  633:     $mysqlon = &check_mysql_running($distro);
  634:     if ($mysqlon) {
  635:         ($mysqlsetup,$has_pass,$dbh,$mysql_has_wwwuser,$mysql_unix_socket) =
  636:             &check_mysql_setup($instdir,$dsn,$distro);
  637:         if ($mysqlsetup eq 'needsrestart') {
  638:             $mysqlrestart = '';
  639:             if ($distro eq 'ubuntu') {
  640:                 $mysqlrestart = 'sudo ';
  641:             }
  642:             $mysqlrestart .= 'service mysql restart';
  643:             return ($distro,$gotprereqs,$localecmd,$langcmd,$packagecmd,$updatecmd,$installnow,$mysqlrestart);
  644:         } else {
  645:             if ($mysqlsetup eq 'noroot') {
  646:                 $recommended{'mysqlperms'} = 1;
  647:             } else {
  648:                 unless ($mysql_has_wwwuser) {
  649:                     $recommended{'mysqlperms'} = 1;
  650:                 }
  651:             }
  652:             if ($dbh) {
  653:                 $has_lcdb = &check_loncapa_mysqldb($dbh);
  654:             }
  655:             unless ($has_lcdb) {
  656:                 $recommended{'mysql'} = 1;
  657:             }
  658:         }
  659:     }
  660:     my ($sslhostsfilesref,$has_std,$has_int,$rewritenum,$nochgstd,$nochgint);
  661:     ($recommended{'firewall'},$apachefw) = &chkfirewall($distro);
  662:     ($recommended{'runlevels'},$tostop,$uses_systemctl) = &chkconfig($distro,$instdir);
  663:     if ((ref($uses_systemctl) eq 'HASH') && ($uses_systemctl->{'apache'})) {
  664:         $recommended{'systemd'} = &check_systemd_security($distro);
  665:     }
  666:     $recommended{'apache'} = &chkapache($distro,$instdir);
  667:     ($recommended{'apachessl'},$sslhostsfilesref,$has_std,$has_int,$rewritenum,
  668:      $nochgstd,$nochgint) = &chkapachessl($distro,$instdir,$hostname,$hostip);
  669:     $recommended{'stopsrvcs'} = &chksrvcs($distro,$tostop);
  670:     ($recommended{'download'},$downloadstatus,$filetouse,$production,$testing) 
  671:         = &need_download($distro,$instdir);
  672:     return ($distro,$gotprereqs,$localecmd,$langcmd,$packagecmd,$updatecmd,$installnow,
  673:             $mysqlrestart,\%recommended,$dbh,$has_pass,$mysql_unix_socket,
  674:             $has_lcdb,$downloadstatus,$filetouse,$production,$testing,$apachefw,
  675:             $uses_systemctl,$hostname,$hostip,$sslhostsfilesref,$has_std,$has_int,
  676:             $rewritenum,$nochgstd,$nochgint);
  677: }
  678: 
  679: sub check_mysql_running {
  680:     my ($distro) = @_;
  681:     my $use_systemctl;
  682:     my $mysqldaemon ='mysqld';
  683:     if ($distro =~ /^(suse|sles|debian|ubuntu)/) {
  684:         $mysqldaemon = 'mysql';
  685:     }
  686:     my $process = 'mysqld_safe';
  687:     my $proc_owner = 'root';
  688:     if ($distro =~ /^ubuntu(\w+)/) {
  689:         if ($1 >= 10) {
  690:             $process = 'mysqld';
  691:             $proc_owner = 'mysql';
  692:         }
  693:         if ($1 >= 16) {
  694:             $use_systemctl = 1;
  695:         }
  696:     } elsif ($distro =~ /^debian(\w+)/) {
  697:         if ($1 >= 10) {
  698:             $process = 'mysql';
  699:             $proc_owner = 'mysql';
  700:         }
  701:         if ($1 >= 11) {
  702:             $mysqldaemon = 'mariadb';
  703:         }
  704:         if ($1 >= 9) {
  705:             $use_systemctl = 1;
  706:         }
  707:     } elsif ($distro =~ /^fedora(\d+)/) {
  708:         if ($1 >= 16) {
  709:             $process = 'mysqld';
  710:             $proc_owner = 'mysql';
  711:             $use_systemctl = 1;
  712:         }
  713:         if ($1 >= 19) {
  714:             $mysqldaemon ='mariadb';
  715:         }
  716:         if ($1 >= 34) {
  717:             $process = 'mariadb';
  718:         }
  719:     } elsif ($distro =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
  720:         if ($1 >= 7) {
  721:             $mysqldaemon ='mariadb';
  722:             $process = 'mysqld';
  723:             $proc_owner = 'mysql';
  724:             $use_systemctl = 1;
  725:         }
  726:         if ($1 >= 9) {
  727:             $process = 'mariadb';
  728:         }
  729:     } elsif ($distro =~ /^sles(\d+)/) {
  730:         if ($1 >= 12) {
  731:             $use_systemctl = 1;
  732:             $proc_owner = 'mysql';
  733:             $process = 'mysqld';
  734:         }
  735:         if ($1 >= 12) {
  736:             $mysqldaemon ='mariadb';
  737:         }
  738:     } elsif ($distro =~ /^suse(\d+)/) {
  739:         if ($1 >= 13) {
  740:             $use_systemctl = 1;
  741:         }
  742:     }
  743:     if (open(PIPE,"ps -ef |grep $process |grep ^$proc_owner |grep -v grep 2>&1 |")) {
  744:         my $status = <PIPE>;
  745:         close(PIPE);
  746:         chomp($status);
  747:         if ($status =~ /^\Q$proc_owner\E\s+\d+\s+/) {
  748:             print_and_log(&mt('MySQL is running.')."\n");
  749:             return 1;
  750:         } else {
  751:             if ($use_systemctl) {
  752:                 system("/bin/systemctl start $mysqldaemon.service >/dev/null 2>&1 ");
  753:             } else {
  754:                 system("/etc/init.d/$mysqldaemon start >/dev/null 2>&1 ");
  755:             }
  756:             print_and_log(&mt('Waiting for MySQL to start.')."\n");
  757:             sleep 5;
  758:             if (open(PIPE,"ps -ef |grep $process |grep -v grep 2>&1 |")) {
  759:                 $status = <PIPE>;
  760:                 close(PIPE);
  761:                 chomp($status);
  762:                 if ($status =~ /^\Q$proc_owner\E\s+\d+\s+/) {
  763:                     print_and_log(&mt('MySQL is running.')."\n");
  764:                     return 1;
  765:                 } else {
  766:                     print_and_log(&mt('Still waiting for MySQL to start.')."\n");
  767:                     sleep 5;
  768:                     if (open(PIPE,"ps -ef |grep $process |grep -v grep 2>&1 |")) {
  769:                         $status = <PIPE>;
  770:                         close(PIPE);
  771:                         chomp($status);
  772:                         if ($status =~ /^\Q$proc_owner\E\s+\d+\s+/) {
  773:                             print_and_log(&mt('MySQL is running.')."\n");
  774:                             return 1;
  775:                         } else {
  776:                             print_and_log(&mt('Given up waiting for MySQL to start.')."\n"); 
  777:                         }
  778:                     }
  779:                 }
  780:             }
  781:         }
  782:     } else {
  783:         print &mt('Could not determine if MySQL is running.')."\n";
  784:     }
  785:     return;
  786: }
  787: 
  788: sub chkconfig {
  789:     my ($distro,$instdir) = @_;
  790:     my (%needfix,%tostop,%uses_systemctl);
  791:     my $checker_bin = '/sbin/chkconfig';
  792:     my $sysctl_bin = '/bin/systemctl';
  793:     my %daemon = (
  794:                   mysql     => 'mysqld',
  795:                   apache    => 'httpd',
  796:                   cups      => 'cups',
  797:                   ntp       => 'ntpd',
  798:                   memcached => 'memcached',
  799:     );
  800:     my @runlevels = qw/3 4 5/;
  801:     my @norunlevels = qw/0 1 6/;
  802:     if ($distro =~ /^(suse|sles)/) {
  803:         @runlevels = qw/3 5/;
  804:         @norunlevels = qw/0 2 1 6/;
  805:         $daemon{'mysql'} = 'mysql';
  806:         $daemon{'apache'} = 'apache2';
  807:         $daemon{'ntp'}    = 'ntp';
  808:         if ($distro =~ /^(suse|sles)9/) {
  809:             $daemon{'apache'} = 'apache';
  810:         }
  811:         if ($distro =~ /^(suse|sles)([\d\.]+)/) {
  812:             my $name = $1;
  813:             my $num = $2;
  814:             if ($num > 11) {
  815:                 $uses_systemctl{'apache'} = 1;
  816:                 if (($name eq 'sles') || ($name eq 'suse' && $num >= 13.2)) {
  817:                     $uses_systemctl{'mysql'} = 1;
  818:                     $uses_systemctl{'ntp'} = 1;
  819:                     $uses_systemctl{'cups'} = 1;
  820:                     $uses_systemctl{'memcached'} = 1;
  821:                     if ($name eq 'sles') {
  822:                         if ($num >= 12) {
  823:                             $daemon{'mysql'} = 'mariadb';
  824:                         }
  825:                         if ($num >= 15) {
  826:                             $daemon{'ntp'} = 'chronyd';
  827:                         } else {
  828:                             $daemon{'ntp'} = 'ntpd';
  829:                         }
  830:                     } else {
  831:                         $daemon{'ntp'} = 'ntpd';
  832:                     }
  833:                 }
  834:             }
  835:         }
  836:     } elsif ($distro =~ /^(?:debian|ubuntu)(\d+)/) {
  837:         my $version = $1;
  838:         @runlevels = qw/2 3 4 5/;
  839:         @norunlevels = qw/0 1 6/;
  840:         if (($distro =~ /^ubuntu/) && ($version <= 16)) {
  841:             $checker_bin = '/usr/sbin/sysv-rc-conf';
  842:         } else {
  843:             $uses_systemctl{'ntp'} = 1;
  844:             $uses_systemctl{'mysql'} = 1;
  845:             $uses_systemctl{'apache'} = 1;
  846:             $uses_systemctl{'memcached'} = 1;
  847:             $uses_systemctl{'cups'} = 1;
  848:         }
  849:         $daemon{'mysql'}  = 'mysql';
  850:         $daemon{'apache'} = 'apache2';
  851:         $daemon{'ntp'}    = 'ntp';
  852:         if (($distro =~ /^ubuntu/) && ($version <= 8)) {
  853:             $daemon{'cups'} = 'cupsys';
  854:         }
  855:         if ((($distro =~ /^ubuntu/) && ($version >= 18)) ||
  856:             (($distro  =~ /^debian/) && ($version >= 10))) {
  857:             $daemon{'ntp'}    = 'chrony';
  858:         }
  859:         if (($distro  =~ /^debian/) && ($version >= 10)) {
  860:             $daemon{'mysql'} = 'mariadb';
  861:         }
  862:     } elsif ($distro =~ /^fedora(\d+)/) {
  863:         my $version = $1;
  864:         if ($version >= 15) {
  865:             $uses_systemctl{'ntp'} = 1;
  866:         }
  867:         if ($version >= 16) {
  868:             $uses_systemctl{'mysql'} = 1;
  869:             $uses_systemctl{'apache'} = 1;
  870:             $uses_systemctl{'memcached'} = 1;
  871:             $uses_systemctl{'cups'} = 1;
  872:         }
  873:         if ($version >= 19) {
  874:             $daemon{'mysql'} = 'mariadb';
  875:         }
  876:         if ($version >= 26) {
  877:             $daemon{'ntp'} = 'chronyd';
  878:         }
  879:     } elsif ($distro =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
  880:         my $version = $1;
  881:         if ($version >= 7) {
  882:             $uses_systemctl{'ntp'} = 1;
  883:             $uses_systemctl{'mysql'} = 1;
  884:             $uses_systemctl{'apache'} = 1;
  885:             $uses_systemctl{'memcached'} = 1;
  886:             $uses_systemctl{'cups'} = 1;
  887:             $daemon{'mysql'} = 'mariadb';
  888:         }
  889:         if (($version >= 8) || ($distro eq 'oracle7')) {
  890:             $daemon{'ntp'} = 'chronyd';
  891:         }
  892:     }
  893:     my $nocheck;
  894:     if (! -x $checker_bin) {
  895:         if ($uses_systemctl{'mysql'} && $uses_systemctl{'apache'}) {
  896:             if (! -x $sysctl_bin) {
  897:                 $nocheck = 1;       
  898:             }
  899:         } else {
  900:             $nocheck = 1;
  901:         }
  902:     }
  903:     if ($nocheck) {
  904:         print &mt('Could not check runlevel status for MySQL or Apache')."\n";
  905:         return;
  906:     }
  907:     my $rlstr = join('',@runlevels);
  908:     my $nrlstr = join('',@norunlevels);
  909: 
  910:     foreach my $type ('apache','mysql','ntp','cups','memcached') {
  911:         my $service = $daemon{$type};
  912:         if ($uses_systemctl{$type}) {
  913:             if (($type eq 'memcached') || ($type eq 'cups')) {
  914:                 if (-l "/etc/systemd/system/multi-user.target.wants/$service.service") {
  915:                     $tostop{$type} = 1;
  916:                 }
  917:             } else {
  918:                 if (!-l "/etc/systemd/system/multi-user.target.wants/$service.service") {
  919:                     $needfix{$type} = "systemctl enable $service.service";
  920:                 }
  921:             }
  922:         } else {
  923:             my $command = $checker_bin.' --list '.$service.' 2>/dev/null';
  924:             if ($type eq 'cups') {
  925:                 if ($distro =~ /^(?:debian|ubuntu)(\d+)/) {
  926:                     my $version = $1;
  927:                     if (($distro =~ /^ubuntu/) && ($version <= 8)) {
  928:                         $command = $checker_bin.' --list cupsys 2>/dev/null';
  929:                     }
  930:                 }
  931:             }
  932:             my $results = `$command`;
  933:             my $tofix;
  934:             if ($results eq '') {
  935:                 if (($type eq 'apache') || ($type eq 'mysql') || ($type eq 'ntp')) {
  936:                     if ($distro  =~ /^(debian|ubuntu)/) {
  937:                         $tofix = "update-rc.d $type defaults";
  938:                     } else {
  939:                         $tofix = "$checker_bin --add $service\n";
  940:                     }
  941:                 }
  942:             } else {
  943:                 my %curr_runlevels;
  944:                 for (my $rl=0; $rl<=6; $rl++) {
  945:                     if ($results =~ /$rl:on/) { $curr_runlevels{$rl}++; }
  946:                 }
  947:                 if (($type eq 'apache') || ($type eq 'mysql') || ($type eq 'ntp')) {
  948:                     my $warning;
  949:                     foreach my $rl (@runlevels) {
  950:                         if (!exists($curr_runlevels{$rl})) {
  951:                             $warning = 1;
  952:                         }
  953:                     }
  954:                     if ($warning) {
  955:                         $tofix = "$checker_bin --level $rlstr $service on\n";
  956:                     }
  957:                 } elsif (keys(%curr_runlevels) > 0) {
  958:                     $tostop{$type} = 1;
  959:                 }
  960:             }
  961:             if ($tofix) {
  962:                 $needfix{$type} = $tofix;
  963:             }
  964:         }
  965:     }
  966:     if ($distro =~ /^(suse|sles)([\d\.]+)$/) {
  967:         my $name = $1;
  968:         my $version = $2;
  969:         my ($major,$minor);
  970:         if ($name eq 'suse') {
  971:             ($major,$minor) = split(/\./,$version);
  972:         } else {
  973:             $major = $version;
  974:         }
  975:         if (($major > 10) && ($major <= 13)) {
  976:             if (&check_SuSEfirewall2_setup($instdir)) {
  977:                 $needfix{'insserv'} = 1;
  978:             }
  979:         }
  980:     }
  981:     return (\%needfix,\%tostop,\%uses_systemctl);
  982: }
  983: 
  984: sub check_systemd_security {
  985:     my ($distro) = @_;
  986:     my $service = 'httpd.service';
  987:     if ($distro =~ /^(suse|sles|ubuntu|debian)/) {
  988:         $service = 'apache2.service';
  989:     }
  990:     system("systemctl daemon-reload");
  991:     if (open(PIPE,"systemctl show $service --property=ProtectHome 2>/dev/null |")) {
  992:         my $protection = <PIPE>;
  993:         close(PIPE);
  994:         chomp($protection);
  995:         if ($protection =~ /^ProtectHome=(read-only|yes)$/i) {
  996:             return 1;
  997:         }
  998:     } else {
  999:          print &mt('Could not check systemctl configuration for Apache')."\n";
 1000:     }
 1001:     return 0;
 1002: }
 1003: 
 1004: sub uses_firewalld {
 1005:     my ($distro) = @_;
 1006:     my ($inuse,$checkfirewalld,$zone);
 1007:     if ($distro =~ /^(suse|sles)([\d\.]+)$/) {
 1008:         if (($1 eq 'sles') && ($2 >= 15)) {
 1009:             $checkfirewalld = 1;
 1010:         }
 1011:     } elsif ($distro =~ /^fedora(\d+)$/) {
 1012:         if ($1 >= 18) {
 1013:             $checkfirewalld = 1;
 1014:         }
 1015:     } elsif ($distro =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
 1016:         if ($1 >= 7) {
 1017:             $checkfirewalld = 1;
 1018:         }
 1019:     }
 1020:     if ($checkfirewalld) {
 1021:         my ($loaded,$active);
 1022:         if (open(PIPE,"systemctl status firewalld 2>/dev/null |")) {
 1023:             while (<PIPE>) {
 1024:                 chomp();
 1025:                 if (/^\s*Loaded:\s+(\w+)/) {
 1026:                     $loaded = $1;
 1027:                 }
 1028:                 if (/^\s*Active:\s+(\w+)/) {
 1029:                     $active = $1;
 1030:                 }
 1031:             }
 1032:             close(PIPE);
 1033:         }
 1034:         if (($loaded eq 'loaded') || ($active eq 'active')) {
 1035:             $inuse = 1;
 1036:             my $cmd = 'firewall-cmd --get-default-zone';
 1037:             if (open(PIPE,"$cmd |")) {
 1038:                 my $result = <PIPE>;
 1039:                 chomp($result);
 1040:                 close(PIPE);
 1041:                 if ($result =~ /^\w+$/) {
 1042:                     $zone = $result;
 1043:                 }
 1044:             }
 1045:         }
 1046:     }
 1047:     return ($inuse,$zone);
 1048: }
 1049: 
 1050: sub chkfirewall {
 1051:     my ($distro) = @_;
 1052:     my $configfirewall = 1;
 1053:     my %ports = (
 1054:                     http  =>  80,
 1055:                     https => 443,
 1056:                 );
 1057:     my %activefw;
 1058:     my ($firewalld,$zone) = &uses_firewalld($distro);
 1059:     if ($firewalld) {
 1060:         my %current;
 1061:         if (open(PIPE,'firewall-cmd --permanent --zone='.$zone.' --list-services |')) {
 1062:             my $svc = <PIPE>;
 1063:             close(PIPE);
 1064:             chomp($svc);
 1065:             map { $current{$_} = 1; } (split(/\s+/,$svc));
 1066:         }
 1067:         if ($current{'http'} && $current{'https'}) {
 1068:             $configfirewall = 0;
 1069:         }
 1070:     } else {
 1071:         if (&firewall_is_active()) {
 1072:             my $iptables = &get_pathto_iptables();
 1073:             if ($iptables eq '') {
 1074:                 print &mt('Firewall not checked as path to iptables not determined.')."\n";
 1075:             } else {
 1076:                 my @fwchains = &get_fw_chains($iptables,$distro);
 1077:                 if (@fwchains) {
 1078:                     foreach my $service ('http','https') {
 1079:                         foreach my $fwchain (@fwchains) {
 1080:                             if (&firewall_is_port_open($iptables,$fwchain,$ports{$service})) {
 1081:                                 $activefw{$service} = 1;
 1082:                                 last;
 1083:                             }
 1084:                         }
 1085:                     }
 1086:                     if ($activefw{'http'}) {
 1087:                         $configfirewall = 0;
 1088:                     }
 1089:                 } else {
 1090:                     print &mt('Firewall not checked as iptables Chains not identified.')."\n";
 1091:                 }
 1092:             }
 1093:         } else {
 1094:             print &mt('Firewall not enabled.')."\n";
 1095:         }
 1096:     }
 1097:     return ($configfirewall,\%activefw);
 1098: }
 1099: 
 1100: sub chkapache {
 1101:     my ($distro,$instdir) = @_;
 1102:     my $fixapache = 1;
 1103:     if ($distro =~ /^(debian|ubuntu)(\d+)$/) {
 1104:         my $distname = $1;
 1105:         my $version = $2;
 1106:         my ($stdconf,$stdsite);
 1107:         if ((($distname eq 'ubuntu') && ($version > 12)) ||
 1108:             (($distname eq 'debian') && ($version >= 10))) {
 1109:             $stdconf = "$instdir/debian-ubuntu/ubuntu14/loncapa_conf";
 1110:             $stdsite = "$instdir/debian-ubuntu/ubuntu14/loncapa_sites";
 1111:         } else {
 1112:             $stdconf = "$instdir/debian-ubuntu/loncapa"; 
 1113:         }
 1114:         if (!-e $stdconf) {
 1115:             $fixapache = 0;
 1116:             print &mt('Warning: No LON-CAPA Apache configuration file found for installation check.')."\n"; 
 1117:         } else {
 1118:             my ($configfile,$sitefile);
 1119:             if ((($distname eq 'ubuntu') && ($version > 12)) ||
 1120:                 (($distname eq 'debian') && ($version >= 10))) {
 1121:                 $sitefile = '/etc/apache2/sites-available/loncapa.conf';
 1122:                 $configfile = '/etc/apache2/conf-available/loncapa.conf';
 1123:             } else {
 1124:                 $configfile = '/etc/apache2/sites-available/loncapa';
 1125:             }
 1126:             if (($configfile ne '') && (-e $configfile) && (-e $stdconf))  {
 1127:                 if (open(PIPE, "diff --brief $stdconf $configfile |")) {
 1128:                     my $diffres = <PIPE>;
 1129:                     close(PIPE);
 1130:                     chomp($diffres);
 1131:                     unless ($diffres) {
 1132:                         $fixapache = 0;
 1133:                     }
 1134:                 }
 1135:             }
 1136:             if ((!$fixapache) && ((($distname eq 'ubuntu') && ($version > 12)) ||
 1137:                                   (($distname eq 'debian') && ($version >= 10))))  {
 1138:                 if (($sitefile ne '') && (-e $sitefile) && (-e $stdsite)) {
 1139:                     if (open(PIPE, "diff --brief $stdsite $sitefile |")) {
 1140:                         my $diffres = <PIPE>;
 1141:                         close(PIPE);
 1142:                         chomp($diffres);
 1143:                         if ($diffres) {
 1144:                             $fixapache = 1;
 1145:                         } else {
 1146:                             $fixapache = 0;
 1147:                         }
 1148:                     }
 1149:                 }
 1150:             }
 1151:         }
 1152:         if (!$fixapache) {
 1153:             foreach my $module ('headers.load','expires.load') {
 1154:                 unless (-l "/etc/apache2/mods-enabled/$module") {
 1155:                     $fixapache = 1;
 1156:                 }
 1157:             }
 1158:         }
 1159:         if ((!$fixapache) && (($distname eq 'ubuntu') || ($distname eq 'debian'))) {
 1160:             my $sitestatus = "/etc/apache2/mods-available/status.conf";
 1161:             my $stdstatus = "$instdir/debian-ubuntu/status.conf";
 1162:             if ((-e $stdstatus) && (-e $sitestatus)) {
 1163:                 if (open(PIPE, "diff --brief $stdstatus $sitestatus |")) {
 1164:                     my $diffres = <PIPE>;
 1165:                     close(PIPE);
 1166:                     chomp($diffres);
 1167:                     if ($diffres) {
 1168:                         $fixapache = 1;
 1169:                     }
 1170:                 }
 1171:             }
 1172:         }
 1173:     } elsif ($distro =~ /^(suse|sles)([\d\.]+)$/) {
 1174:         my ($name,$version) = ($1,$2);
 1175:         my $apache = 'apache';
 1176:         my $conf_file = "$instdir/sles-suse/default-server.conf";
 1177:         if ($version >= 10) {
 1178:             $apache = 'apache2';
 1179:         }
 1180:         if (($name eq 'sles') && ($version >= 12)) {
 1181:             $conf_file = "$instdir/sles-suse/apache2.4/default-server.conf";
 1182:         }
 1183:         if (!-e $conf_file) {
 1184:             $fixapache = 0;
 1185:             print &mt('Warning: No LON-CAPA Apache configuration file found for installation check.')."\n";
 1186:         } elsif (-e "/etc/$apache/default-server.conf") {
 1187:             if (open(PIPE, "diff --brief $conf_file /etc/$apache/default-server.conf |")) {
 1188:                 my $diffres = <PIPE>;
 1189:                 close(PIPE);
 1190:                 chomp($diffres);
 1191:                 unless ($diffres) {
 1192:                     $fixapache = 0;
 1193:                 }
 1194:             }
 1195:         }
 1196:     } elsif ($distro eq 'rhes4') {
 1197:         if (!-e "$instdir/rhes4/httpd.conf") {
 1198:             $fixapache = 0;
 1199:             print &mt('Warning: No LON-CAPA Apache configuration file found for installation check.')."\n";
 1200:         } elsif ((-e "/etc/httpd/conf/httpd.conf") && (-e "$instdir/rhes4/httpd.conf")) {
 1201:             if (open(PIPE, "diff --brief $instdir/rhes4/httpd.conf /etc/httpd/conf/httpd.conf |")) {
 1202:                 my $diffres = <PIPE>;
 1203:                 close(PIPE);
 1204:                 chomp($diffres);
 1205:                 unless ($diffres) {
 1206:                     $fixapache = 0;
 1207:                 }
 1208:             }
 1209:         }
 1210:     } else {
 1211:         my $configfile = 'httpd.conf';
 1212:         my $mpmfile = 'mpm.conf';
 1213:         if ($distro =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
 1214:             if ($1 >= 7) {
 1215:                 $configfile = 'apache2.4/httpd.conf';
 1216:             } elsif ($1 > 5) {
 1217:                 $configfile = 'new/httpd.conf';
 1218:             }
 1219:         } elsif ($distro =~ /^fedora(\d+)$/) {
 1220:             if ($1 > 17) {
 1221:                 $configfile = 'apache2.4/httpd.conf';
 1222:             } elsif ($1 > 10) {
 1223:                 $configfile = 'new/httpd.conf';
 1224:             }
 1225:         }
 1226:         if (!-e "$instdir/centos-rhes-fedora-sl/$configfile") {
 1227:             $fixapache = 0;
 1228:             print &mt('Warning: No LON-CAPA Apache configuration file found for installation check.')."\n";
 1229:         } elsif ((-e "/etc/httpd/conf/httpd.conf") && (-e "$instdir/centos-rhes-fedora-sl/$configfile")) {
 1230:             if (open(PIPE, "diff --brief $instdir/centos-rhes-fedora-sl/$configfile /etc/httpd/conf/httpd.conf |")) {
 1231:                 my $diffres = <PIPE>;
 1232:                 close(PIPE);
 1233:                 chomp($diffres);
 1234:                 unless ($diffres) {
 1235:                     $fixapache = 0;
 1236:                 }
 1237:             }
 1238:         }
 1239:         if (-e "/etc/httpd/conf.modules.d/00-mpm.conf") {
 1240:             if (!-e "$instdir/centos-rhes-fedora-sl/$mpmfile") {
 1241:                 print &mt('Warning: No LON-CAPA Apache MPM configuration file found for installation check.')."\n";
 1242:             } elsif ((-e "/etc/httpd/conf.modules.d/00-mpm.conf") && (-e "$instdir/centos-rhes-fedora-sl/$mpmfile")) {
 1243:                 if (open(PIPE, "diff --brief $instdir/centos-rhes-fedora-sl/$mpmfile /etc/httpd/conf.modules.d/00-mpm.conf |")) {
 1244:                     my $diffres = <PIPE>;
 1245:                     close(PIPE);
 1246:                     chomp($diffres);
 1247:                     if ($diffres) {
 1248:                         $fixapache = 1;
 1249:                     }
 1250:                 }
 1251:             }
 1252:         }
 1253:     }
 1254:     return $fixapache;
 1255: }
 1256: 
 1257: #
 1258: # chkapachessl() determines whether a server's Apache SSL configuration
 1259: # needs updating to support LON-CAPA.
 1260: #
 1261: # LON-CAPA uses VirtualHosts for port 443, and requires that they are 
 1262: # defined in one Apache configuration file containing two VirtualHost
 1263: # blocks, in order:
 1264: #
 1265: # (1) a block with no ServerName, or with ServerName set to the
 1266: #     server's hostname. This block should contain:
 1267: #
 1268: # <IfModule mod_rewrite.c>
 1269: # LON-CAPA rewrite rules defined in sslrewrite.conf
 1270: # </IfModule>
 1271: #
 1272: # (2) a block with ServerName set to internal-$hostname
 1273: #     (where $hostname is server's hostname).
 1274: #    This block should contain the config and rewrite rules
 1275: #    found in loncapassl.conf.
 1276: #
 1277: # chkapachessl() retrieves the names of .conf files in
 1278: # the directory appropriate for the particular Linux distro,
 1279: # and then checks to see which .conf file is the best candidate as
 1280: # the single file containing VirtualHosts definitions and 
 1281: # <IfModule mod_rewrite.c> </IfModule> rewrite blocks.
 1282: #
 1283: # The best candidate is the one containing a block:
 1284: # <VirtualHost ????? :443> 
 1285: # (where ????? might be _default_ or * or an IP address)
 1286: # <IfModule mod_rewrite.c>
 1287: # </IfModule>
 1288: # </VirtualHost>
 1289: # with the fewest differences between the contents of the 
 1290: # IfModule block and the expected contents (from sslrewrite.conf)
 1291: #
 1292: # If there are no files with rewrite blocks, then a candidate file 
 1293: # is chosen from the .conf files containing VirtualHosts definitions.
 1294: #
 1295: # If the user includes "Configure SSL for Apache web server" as
 1296: # one of the actions to take to prepare the server for LON-CAPA
 1297: # installation, then the output from &chkapachessl() will be
 1298: # used to determined which file will contain VirtualHost configs.  
 1299: #
 1300: # If there are no files containing VirtualHosts definitions, then
 1301: # <VirtualHost *:443> </VirtualHost> blocks will be appended to
 1302: # the standard Apache SSL config for the particular distro:
 1303: # ssl.conf for RHEL/CentOS/Scientific/Fedora, vhost-ssl.conf
 1304: # for SuSE/SLES, and default-ssl.conf for Ubuntu.
 1305: #
 1306: # Once a file is selected, the contents of sslrewrite.conf and 
 1307: # loncapassl.conf are compared with appropriate blocks in the file
 1308: # and the user will be prompted to agree to insertion of missing
 1309: # lines and/or deletion of surplus lines.
 1310: #
 1311: 
 1312: sub chkapachessl {
 1313:     my ($distro,$instdir,$hostname,$hostip) = @_;
 1314:     my $fixapachessl = 1;
 1315:     my $sslintconf = "$instdir/loncapassl.conf";
 1316:     my $sslrewriteconf = "$instdir/sslrewrite.conf";
 1317:     my (%sslfiles,%rewrites,%vhostonly,$has_std,$has_int,$rewritenum,$nochgint,$nochgstd);
 1318:     $nochgstd = 0;
 1319:     $nochgint = 0; 
 1320:     if (!-e $sslintconf) {
 1321:         $fixapachessl = 0;
 1322:         print &mt('Warning: LON-CAPA SSL Apache configuration file [_1] needed for installation check.',$sslintconf)."\n";
 1323:     } elsif (!-e $sslrewriteconf) {
 1324:         $fixapachessl = 0;
 1325:         print &mt('Warning: LON-CAPA SSL Apache configuration file [_1] needed for installation check is missing.',$sslrewriteconf)."\n";
 1326:     } else {
 1327:         my $ssldir;
 1328:         if ($distro =~ /^(debian|ubuntu)(\d+)$/) {
 1329:             $ssldir = '/etc/apache2/sites-available';
 1330:         } elsif ($distro =~ /(suse|sles)/) {
 1331:             $ssldir = '/etc/apache2/vhosts.d';
 1332:         } else {
 1333:             $ssldir = '/etc/httpd/conf.d';
 1334:         }
 1335:         my @rewritessl = ();
 1336:         if (open(my $fh,'<',$sslrewriteconf)) {
 1337:             my $skipnext = 0;
 1338:             while (<$fh>) {
 1339:                 chomp();
 1340:                 s/(^\s+|\s+$)//g;
 1341:                 next if ($_ eq '');
 1342:                 next if ($_ eq '<IfModule mod_rewrite.c>');
 1343:                 next if ($_ eq '</IfModule>');
 1344:                 if ($_ eq 'RewriteCond %{REMOTE_ADDR} {[[[[HostIP]]]]}') {
 1345:                     if (($hostip ne '') && ($hostip ne '127.0.0.1')) {
 1346:                         push(@rewritessl,'RewriteCond %{REMOTE_ADDR} '.$hostip);
 1347:                         next;
 1348:                     } else {
 1349:                         $skipnext = 1;
 1350:                     }
 1351:                 } elsif (($_ eq 'RewriteRule (.*) - [L]') && ($skipnext)) {
 1352:                     $skipnext = 0;
 1353:                     next;
 1354:                 }
 1355:                 push(@rewritessl,$_);
 1356:             }
 1357:         }
 1358:         my @intssl = ();
 1359:         if (open(my $fh,'<',$sslintconf)) {
 1360:             while(<$fh>) {
 1361:                 chomp();
 1362:                 s/(^\s+|\s+$)//g;
 1363:                 next if ($_ eq '');
 1364:                 if ($_ eq 'ServerName internal-{[[[[Hostname]]]]}') {
 1365:                     if ($hostname ne '') {
 1366:                         push(@intssl,'ServerName internal-'.$hostname);
 1367:                         next;
 1368:                     }
 1369:                 }
 1370:                 next if ($_ eq '<VirtualHost *:443>');
 1371:                 next if ($_ eq '</VirtualHost>');
 1372:                 push(@intssl,$_);
 1373:             }
 1374:         }
 1375:         if (-d $ssldir) {
 1376:             my @actualint = ();
 1377:             if (opendir(my $dir,$ssldir)) {
 1378:                 my @sslconf_files;
 1379:                 foreach my $file (grep(!/^\.+/,readdir($dir))) {
 1380:                     next if (($distro =~ /(suse|sles)/) && ($file =~ /\.template$/));
 1381:                     next if ($file =~ /\.rpmnew$/);
 1382:                     if (open(my $fh,'<',"$ssldir/$file")) {
 1383:                         while (<$fh>) {
 1384:                             if (/^\s*<VirtualHost\s+[^:]*\:443>\s*$/) {
 1385:                                 push(@sslconf_files,$file);
 1386:                                 last;
 1387:                             }
 1388:                         }
 1389:                         close($fh);
 1390:                     }
 1391:                 }
 1392:                 closedir($dir);
 1393:                 if (@sslconf_files) {
 1394:                     foreach my $file (@sslconf_files) {
 1395:                         if (open(my $fh,'<',"$ssldir/$file")) {
 1396:                             my ($virtualhost,$rewrite,$num) = (0,0,0);
 1397:                             my ($currname,$has_rewrite);
 1398:                             while (<$fh>) {
 1399:                                 chomp();
 1400:                                 next if (/^\s*$/);
 1401:                                 if ($virtualhost) {
 1402:                                     if (/^\s*<\/VirtualHost>/) {
 1403:                                         if ($currname !~ /^\Qinternal-$hostname\E/) {
 1404:                                             if ($has_rewrite) {
 1405:                                                 delete($vhostonly{$file});
 1406:                                             } else {
 1407:                                                 $vhostonly{$file} = 1;
 1408:                                             }
 1409:                                         }
 1410:                                         $sslfiles{$currname}{$file} = 1;
 1411:                                         $virtualhost = 0;
 1412:                                         $currname = '';
 1413:                                         $has_rewrite = '';
 1414:                                         next;
 1415:                                     } elsif (/^\s*ServerName\s+([^\s]+)\s*$/) {
 1416:                                         $currname = $1;
 1417:                                     }
 1418:                                     if ($currname =~ /^\Qinternal-$hostname\E/) {
 1419:                                         s/(^\s+|\s+$)//g;
 1420:                                         push(@actualint,$_);
 1421:                                         $has_int = $file;
 1422:                                     } else {
 1423:                                         if ($rewrite) {
 1424:                                             if (/^\s*<\/IfModule>/) {
 1425:                                                 $rewrite = 0;
 1426:                                                 $num ++;
 1427:                                             } else {
 1428:                                                 s/(^\s+|\s+$)//g;
 1429:                                                 push(@{$rewrites{$file}[$num]},$_);
 1430:                                             }
 1431:                                         } elsif (/^\s*<IfModule\s+mod_rewrite\.c>/) {
 1432:                                             $rewrite = 1;
 1433:                                             $has_rewrite = 1;
 1434:                                             if ($currname eq '') {
 1435:                                                 $currname = $hostname;
 1436:                                             }
 1437:                                             $rewrites{$file}[$num] = [];
 1438:                                         }
 1439:                                     }
 1440:                                 } elsif (/^\s*<VirtualHost\s+[^:]*\:443>\s*$/) {
 1441:                                     $virtualhost = 1;
 1442:                                 }
 1443:                             }
 1444:                             close($fh);
 1445:                         }
 1446:                     }
 1447:                 }
 1448:                 if (keys(%rewrites)) {
 1449:                     my $mindiffsall;
 1450:                     foreach my $file (sort(keys(%rewrites))) {
 1451:                         if (ref($rewrites{$file}) eq 'ARRAY') {
 1452:                             my $mindiffs;
 1453:                             for (my $i=0; $i<@{$rewrites{$file}}; $i++) {
 1454:                                 if (ref($rewrites{$file}[$i]) eq 'ARRAY') {
 1455:                                     my @diffs = &compare_arrays($rewrites{$file}[$i],\@rewritessl);
 1456:                                     if (@diffs == 0) {
 1457:                                         $fixapachessl = 0;
 1458:                                         $mindiffs = 0;
 1459:                                         $rewritenum = 1+$i;
 1460:                                         last;
 1461:                                     } else {
 1462:                                         if ($mindiffs eq '') {
 1463:                                             $mindiffs = scalar(@diffs);
 1464:                                             $rewritenum = 1+$i; 
 1465:                                         } elsif (scalar(@diffs) <= $mindiffs) {
 1466:                                             $mindiffs = scalar(@diffs);
 1467:                                             $rewritenum = 1+$i;
 1468:                                         }
 1469:                                     }
 1470:                                 }
 1471:                             }
 1472:                             if ($mindiffsall eq '') {
 1473:                                 $mindiffsall = $mindiffs;
 1474:                                 $has_std = $file;
 1475:                             } elsif ($mindiffs <= $mindiffsall) {
 1476:                                 $mindiffsall = $mindiffs;
 1477:                                 $has_std = $file;
 1478:                             }
 1479:                             if ($mindiffsall == 0) {
 1480:                                 $nochgstd = 1;
 1481:                             }
 1482:                         }
 1483:                     }
 1484:                 } elsif (keys(%vhostonly) > 0) {
 1485:                     if (($has_int ne '') && (exists($vhostonly{$has_int}))) {
 1486:                         $has_std = $has_int;
 1487:                     }
 1488:                 }
 1489:                 if (@actualint) {
 1490:                     my @diffs = &compare_arrays(\@actualint,\@intssl);
 1491:                     if (@diffs) {
 1492:                         $fixapachessl = 1;
 1493:                     } else {
 1494:                         $nochgint = 1;
 1495:                     }
 1496:                 } else {
 1497:                     $fixapachessl = 1;
 1498:                 }
 1499:             }
 1500:         }
 1501:         unless ($fixapachessl) {
 1502:             if ($distro =~ /^(debian|ubuntu)(\d+)$/) {
 1503:                 my $enabled_dir = '/etc/apache2/sites-enabled';
 1504:                 if (keys(%sslfiles)) {
 1505:                     foreach my $key (sort(keys(%sslfiles))) {
 1506:                         if (ref($sslfiles{$key}) eq 'HASH') {
 1507:                             foreach my $file (sort(keys(%{$sslfiles{$key}}))) {
 1508:                                 unless ((-l "$enabled_dir/$file") &&
 1509:                                         (readlink("$enabled_dir/$file") eq "$ssldir/$file")) {
 1510:                                     if ($distro =~ /^debian(\d+)$/) {
 1511:                                         print_and_log(&mt("Warning, use: 'a2ensite $file' to activate LON-CAPA SSL Apache config\n"));
 1512:                                     } elsif ($distro =~ /^ubuntu(\d+)$/) {
 1513:                                         print_and_log(&mt("Warning, use: 'sudo a2ensite $file' to activate LON-CAPA SSL Apache config\n"));
 1514:                                     }
 1515:                                 }
 1516:                             }
 1517:                         }
 1518:                     }
 1519:                 }
 1520:             }
 1521:         }
 1522:     }
 1523:     return ($fixapachessl,\%sslfiles,$has_std,$has_int,$rewritenum,$nochgstd,$nochgint);
 1524: }
 1525: 
 1526: #
 1527: # compare_arrays() expects two refs to arrays as args.
 1528: #
 1529: # The contents of the two arrays are compared, and if they
 1530: # are different, and array of the differences is returned.
 1531: #
 1532: 
 1533: sub compare_arrays {
 1534:     my ($arrayref1,$arrayref2) = @_;
 1535:     my (@difference,%count);
 1536:     @difference = ();
 1537:     %count = ();
 1538:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
 1539:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
 1540:         foreach my $element (keys(%count)) {
 1541:             if ($count{$element} == 1) {
 1542:                 push(@difference,$element);
 1543:             }
 1544:         }
 1545:     }
 1546:     return @difference;
 1547: }
 1548: 
 1549: sub chksrvcs {
 1550:     my ($distro,$tostop) = @_;
 1551:     my %stopsrvcs;
 1552:     if (ref($tostop) eq 'HASH') {
 1553:         %stopsrvcs = %{$tostop};
 1554:     }
 1555:     foreach my $service ('cups','memcached') {
 1556:         next if (exists($stopsrvcs{$service}));
 1557:         my $daemon = $service;
 1558:         if ($service eq 'cups') {
 1559:             $daemon = 'cupsd';
 1560:         }
 1561:         my $cmd = "ps -ef |grep '$daemon' |grep -v grep";
 1562:         if (open(PIPE,'-|',$cmd)) {
 1563:             my $daemonrunning = <PIPE>;
 1564:             chomp($daemonrunning);
 1565:             close(PIPE);
 1566:             if ($daemonrunning) {
 1567:                 if ($service eq 'memcached') {
 1568:                     my $cmd = '/usr/bin/memcached';
 1569:                     if ($distro =~ /^(suse|sles)/) {
 1570:                         $cmd = '/usr/sbin/memcached';
 1571:                     }
 1572:                     unless ($daemonrunning =~ m{^www[^/]+\Q$cmd -m 400 -v\E$}) {
 1573:                         $stopsrvcs{$service} = 1;
 1574:                     }
 1575:                 } else {
 1576:                     $stopsrvcs{$service} = 1;
 1577:                 }
 1578:             }
 1579:         }
 1580:     }
 1581:     return \%stopsrvcs;
 1582: }
 1583: 
 1584: sub need_download {
 1585:     my ($distro,$instdir) = @_;
 1586:     my $needs_download = 1;
 1587:     my ($production,$testing,$stdsizes) = &download_versionslist();
 1588:     my ($localcurrent,$localtesting,%tarball,%localsize,%bymodtime,
 1589:         %bysize,$filetouse,$downloadstatus);
 1590:     if (opendir(my $dir,$instdir)) {
 1591:         my (@lcdownloads,$version);
 1592:         foreach my $file (readdir($dir)) {
 1593:             if ($file =~ /^loncapa\-([\w\-.]+)\.tar\.gz$/) {
 1594:                 $version = $1;
 1595:             } else {
 1596:                 next;
 1597:             }
 1598:             if (ref($stdsizes) eq 'HASH') {
 1599:                 if ($version eq 'current') {
 1600:                     my @stats = stat("$instdir/$file");
 1601:                     $localcurrent = $stats[7];
 1602:                     if ($localcurrent == $stdsizes->{$production}) {
 1603:                         $needs_download = 0;
 1604:                         $filetouse = $file;
 1605:                     }
 1606:                 } elsif ($version eq 'testing') {
 1607:                     my @stats = stat("$instdir/$file");
 1608:                     $localtesting = $stats[7];
 1609:                     if ($localtesting == $stdsizes->{$testing}) {
 1610:                         $needs_download = 0;
 1611:                         $filetouse = $file;
 1612:                     }
 1613:                 }
 1614:             }
 1615:             $tarball{$version} = $file;
 1616:             push(@lcdownloads,$version);
 1617:         }
 1618:         if ($needs_download) {
 1619:             if (@lcdownloads > 0) {
 1620:                 foreach my $version (@lcdownloads) {
 1621:                     my @stats = stat("$instdir/$tarball{$version}");
 1622:                     my $mtime = $stats[9];
 1623:                     $localsize{$version} = $stats[7];
 1624:                     if ($mtime) {
 1625:                         push(@{$bymodtime{$mtime}},$version);
 1626:                     }
 1627:                     if ($localsize{$version}) {
 1628:                         push(@{$bysize{$localsize{$version}}},$version);
 1629:                     }
 1630:                 }
 1631:                 if ($testing) {
 1632:                     if (exists($localsize{$testing})) {
 1633:                         if ($stdsizes->{$testing} == $localsize{$testing}) {
 1634:                             $needs_download = 0;
 1635:                             $filetouse = 'loncapa-'.$testing.'.tar.gz';
 1636:                         }
 1637:                     }
 1638:                 }
 1639:                 if ($needs_download) { 
 1640:                     if ($production) {
 1641:                         if (exists($localsize{$production})) {
 1642:                             if ($stdsizes->{$production} == $localsize{$production}) {
 1643:                                 $needs_download = 0;
 1644:                                 $filetouse = 'loncapa-'.$production.'.tar.gz';
 1645:                             }
 1646:                         }
 1647:                     }
 1648:                 }
 1649:                 if ($needs_download) {
 1650:                     my @sorted = sort { $b <=> $a } keys(%bymodtime);
 1651:                     my $newest = $sorted[0];
 1652:                     if (ref($bymodtime{$newest}) eq 'ARRAY') {
 1653:                         $downloadstatus = 
 1654:                               "Latest LON-CAPA source download in $instdir is: ".
 1655:                               join(',',@{$bymodtime{$newest}})." (downloaded ".
 1656:                               localtime($newest).")\n";
 1657:                     }
 1658:                 } else {
 1659:                     $downloadstatus = 
 1660:                         "The $instdir directory already contains the latest LON-CAPA version:".
 1661:                         "\n".$filetouse."\n"."which can be used for installation.\n";
 1662:                 }
 1663:             } else {
 1664:                 $downloadstatus = "The $instdir directory does not appear to contain any downloaded LON-CAPA source code files which can be used for installation.\n";
 1665:             }
 1666:         }
 1667:     } else {
 1668:         $downloadstatus = "Could not open $instdir directory to look for existing downloads of LON-CAPA source code.\n";
 1669:     }
 1670:     return ($needs_download,$downloadstatus,$filetouse,$production,$testing);
 1671: }
 1672: 
 1673: sub check_mysql_setup {
 1674:     my ($instdir,$dsn,$distro) = @_;
 1675:     my ($mysqlsetup,$has_pass,$mysql_unix_socket,$mysql_has_wwwuser);
 1676:     my $dbh = DBI->connect($dsn,'root','',{'PrintError'=>0});
 1677:     my ($mysqlversion,$mysqlminorversion,$mysqlsubver,$mysqlname) = &get_mysql_version();
 1678:     if (($mysqlname =~ /^MariaDB/i) && (($mysqlversion == 10 && $mysqlminorversion >= 4) || ($mysqlversion >= 11))) {
 1679:         if ($dbh) {
 1680:             my $sth = $dbh->prepare("SELECT Priv FROM mysql.global_priv WHERE (User = 'root' AND Host ='localhost')");
 1681:             $sth->execute();
 1682:             while (my $priv = $sth->fetchrow_array) {
 1683:                 if ($priv =~ /unix_socket/) {
 1684:                     $mysql_unix_socket = 1;
 1685:                     last;
 1686:                 }
 1687:             }
 1688:             $sth->finish();
 1689:             if ($mysql_unix_socket) {
 1690:                 print_and_log(&mt('MariaDB using unix_socket for root access from localhost.')."\n");
 1691:                 $mysqlsetup = 'rootok';
 1692:                 $mysql_has_wwwuser = &check_mysql_wwwuser($dbh);
 1693:                 return ($mysqlsetup,$has_pass,$dbh,$mysql_has_wwwuser,$mysql_unix_socket);
 1694:             }
 1695:         }
 1696:     }
 1697:     if ($dbh) {
 1698:         $mysqlsetup = 'noroot';
 1699:         if (($mysqlname !~ /^MariaDB/i) && (($mysqlversion == 5 && $mysqlminorversion >= 7) || ($mysqlversion >= 6))) {
 1700:             my $sth = $dbh->prepare("SELECT plugin from mysql.user where User='root'");
 1701:             $sth->execute();
 1702:             while (my $priv = $sth->fetchrow_array) {
 1703:                 if ($priv =~ /auth_socket/) {
 1704:                     $mysql_unix_socket = 1;
 1705:                     last;
 1706:                 }
 1707:             }
 1708:             $sth->finish();
 1709:             if ($mysql_unix_socket) {
 1710:                 print_and_log(&mt('MySQL using unix_socket for root access from localhost.')."\n");
 1711:                 $mysqlsetup = 'rootok';
 1712:                 $mysql_has_wwwuser = &check_mysql_wwwuser($dbh);
 1713:                 return ($mysqlsetup,$has_pass,$dbh,$mysql_has_wwwuser,$mysql_unix_socket);
 1714:             }
 1715:         }
 1716:     } elsif ($DBI::err =~ /1045/) {
 1717:         $has_pass = 1;
 1718:     } elsif ($distro =~ /^ubuntu(\d+)$/) {
 1719:         my $version = $1;
 1720:         if ($1 > 12) {
 1721:             print_and_log(&mt('Restarting mysql, please be patient')."\n");
 1722:             if (open (PIPE, "service mysql restart 2>&1 |")) {
 1723:                 while (<PIPE>) {
 1724:                     print $_;
 1725:                 }
 1726:                 close(PIPE);
 1727:             }
 1728:             $dbh = DBI->connect($dsn,'root','',{'PrintError'=>0});
 1729:             if ($dbh) {
 1730:                 $mysqlsetup = 'noroot';
 1731:                 $mysql_has_wwwuser = &check_mysql_wwwuser($dbh);
 1732:             } elsif ($DBI::err =~ /1045/) {
 1733:                 $has_pass = 1;
 1734:             } else {
 1735:                 $mysqlsetup = 'needsrestart';
 1736:                 $mysql_has_wwwuser = &check_mysql_wwwuser();
 1737:                 return ($mysqlsetup,$has_pass,$dbh,$mysql_has_wwwuser);
 1738:             }
 1739:         }
 1740:     }
 1741:     if ($has_pass) {
 1742:         print &mt('You have already set a root password for the MySQL database.')."\n";
 1743:         my $currpass = &get_mysql_password(&mt('Please enter the password now'));
 1744:         $dbh = DBI->connect($dsn,'root',$currpass,{'PrintError'=>0});
 1745:         if ($dbh) {
 1746:             $mysqlsetup = 'rootok';
 1747:             print_and_log(&mt('Password accepted.')."\n");
 1748:             $mysql_has_wwwuser = &check_mysql_wwwuser($dbh);
 1749:         } else {
 1750:             $mysqlsetup = 'rootfail';
 1751:             print_and_log(&mt('Problem accessing MySQL.')."\n");
 1752:             if ($DBI::err =~ /1045/) {
 1753:                 print_and_log(&mt('Perhaps the password was incorrect?')."\n");
 1754:                 print &mt('Try again?').' ';
 1755:                 $currpass = &get_mysql_password(&mt('Re-enter password now')); 
 1756:                 $dbh = DBI->connect($dsn,'root',$currpass,{'PrintError'=>0});
 1757:                 if ($dbh) {
 1758:                     $mysqlsetup = 'rootok';
 1759:                     print_and_log(&mt('Password accepted.')."\n");
 1760:                     $mysql_has_wwwuser = &check_mysql_wwwuser($dbh);
 1761:                 } else {
 1762:                     if ($DBI::err =~ /1045/) {
 1763:                         print_and_log(&mt('Incorrect password.')."\n");
 1764:                     }
 1765:                     $mysql_has_wwwuser = &check_mysql_wwwuser();
 1766:                 }
 1767:             }
 1768:         }
 1769:     } elsif ($mysqlsetup ne 'noroot') {
 1770:         print_and_log(&mt('Problem accessing MySQL.')."\n");
 1771:         $mysqlsetup = 'rootfail';
 1772:         $mysql_has_wwwuser = &check_mysql_wwwuser();
 1773:     }
 1774:     return ($mysqlsetup,$has_pass,$dbh,$mysql_has_wwwuser);
 1775: }
 1776: 
 1777: sub check_mysql_wwwuser {
 1778:     my ($dbh) = @_;
 1779:     my $mysql_wwwuser;
 1780:     if ($dbh) {
 1781:         $mysql_wwwuser = $dbh->selectrow_array("SELECT COUNT(User) FROM mysql.user WHERE (User = 'www' AND Host ='localhost')");
 1782:     } else {
 1783:         my $dbhn = DBI->connect("DBI:mysql:database=information_schema",'www','localhostkey',
 1784:                                 {PrintError => +0}) || return;
 1785:         if ($dbhn) {
 1786:             $mysql_wwwuser = 1;
 1787:             $dbhn->disconnect;
 1788:         }
 1789:     }
 1790:     return $mysql_wwwuser;
 1791: }
 1792: 
 1793: sub check_loncapa_mysqldb {
 1794:     my ($dbh) = @_;
 1795:     my $has_lcdb;
 1796:     if (ref($dbh)) {
 1797:         my $sth = $dbh->prepare("SHOW DATABASES");
 1798:         $sth->execute();
 1799:         while (my $dbname = $sth->fetchrow_array) {
 1800:             if ($dbname eq 'loncapa') {
 1801:                 $has_lcdb = 1;
 1802:                 last;
 1803:             }
 1804:         }
 1805:         $sth->finish();
 1806:     }
 1807:     return $has_lcdb;
 1808: }
 1809: 
 1810: sub get_pathto_iptables {
 1811:     my $iptables;
 1812:     if (-e '/sbin/iptables') {
 1813:         $iptables = '/sbin/iptables';
 1814:     } elsif (-e '/usr/sbin/iptables') {
 1815:         $iptables = '/usr/sbin/iptables';
 1816:     } else {
 1817:         print &mt('Unable to find iptables command.')."\n";
 1818:     }
 1819:     return $iptables;
 1820: }
 1821: 
 1822: sub firewall_is_active {
 1823:     if (-e '/proc/net/ip_tables_names') {
 1824:         my $status;
 1825:         if (open(PIPE,'cat /proc/net/ip_tables_names |grep filter |')) {
 1826:             $status = <PIPE>;
 1827:             close(PIPE);
 1828:             chomp($status);
 1829:             if ($status eq 'filter') {
 1830:                 return 1;
 1831:             }
 1832:         }
 1833:         unless ($status) {
 1834:             if (open(PIPE,'nft list tables |')) {
 1835:                 while(<PIPE>) {
 1836:                     chomp();
 1837:                     if (/filter$/) {
 1838:                         $status = 1;
 1839:                         last;
 1840:                     }
 1841:                 }
 1842:                 close(PIPE);
 1843:                 if ($status) {
 1844:                     return 1;
 1845:                 }
 1846:             }
 1847:         }
 1848:     }
 1849:     return 0;
 1850: }
 1851: 
 1852: sub get_fw_chains {
 1853:     my ($iptables,$distro) = @_;
 1854:     my @fw_chains;
 1855:     my $suse_config = "/etc/sysconfig/SuSEfirewall2";
 1856:     my $ubuntu_config = "/etc/ufw/ufw.conf";
 1857:     if (-e $suse_config) {
 1858:         push(@fw_chains,'input_ext');
 1859:     } else {
 1860:         my @posschains;
 1861:         if (-e $ubuntu_config) {
 1862:             @posschains = ('ufw-user-input','INPUT');
 1863:         } elsif ($distro =~ /^debian5/) {
 1864:             @posschains = ('INPUT');
 1865:         } elsif ($distro =~ /^(suse|sles)(\d+)/) {
 1866:             @posschains = ('IN_public');
 1867:         } else {
 1868:             @posschains = ('RH-Firewall-1-INPUT','INPUT');
 1869:             if (!-e '/etc/sysconfig/iptables') {
 1870:                 if (!-e '/var/lib/iptables') {
 1871:                     print &mt('Unable to find iptables file containing static definitions.')."\n";
 1872:                 }
 1873:                 push(@fw_chains,'RH-Firewall-1-INPUT');
 1874:             }
 1875:         }
 1876:         if ($iptables eq '') {
 1877:             $iptables = &get_pathto_iptables();
 1878:         }
 1879:         my %counts;
 1880:         if (open(PIPE,"$iptables -L -n |")) {
 1881:             while(<PIPE>) {
 1882:                 foreach my $chain (@posschains) {
 1883:                     if (/(\Q$chain\E)/) {
 1884:                         $counts{$1} ++;
 1885:                     }
 1886:                 }
 1887:             }
 1888:             close(PIPE);
 1889:         }
 1890:         foreach my $fw_chain (@posschains) {
 1891:             if ($counts{$fw_chain}) {
 1892:                 unless(grep(/^\Q$fw_chain\E$/,@fw_chains)) {
 1893:                     push(@fw_chains,$fw_chain);
 1894:                 }
 1895:             }
 1896:         }
 1897:     }
 1898:     return @fw_chains;
 1899: }
 1900: 
 1901: sub firewall_is_port_open {
 1902:     my ($iptables,$fw_chain,$port) = @_;
 1903:     # returns 1 if the firewall port is open, 0 if not.
 1904:     #
 1905:     # check if firewall is active or installed
 1906:     return if (! &firewall_is_active());
 1907:     my $count = 0;
 1908:     if (open(PIPE,"$iptables -L $fw_chain -n |")) {
 1909:         while(<PIPE>) {
 1910:             if (/tcp dpt\:\Q$port\E/) {
 1911:                 $count ++;
 1912:                 last;
 1913:             }
 1914:         }
 1915:         close(PIPE);
 1916:     } else {
 1917:         print &mt('Firewall status not checked: unable to run [_1].','iptables -L')."\n";
 1918:     }
 1919:     return $count;
 1920: }
 1921: 
 1922: sub get_mysql_password {
 1923:     my ($prompt) = @_;
 1924:     local $| = 1;
 1925:     print $prompt.': ';
 1926:     my $newpasswd = '';
 1927:     ReadMode 'raw';
 1928:     my $key;
 1929:     while(ord($key = ReadKey(0)) != 10) {
 1930:         if(ord($key) == 127 || ord($key) == 8) {
 1931:             chop($newpasswd);
 1932:             print "\b \b";
 1933:         } elsif(!ord($key) < 32) {
 1934:             $newpasswd .= $key;
 1935:             print '*';
 1936:         }
 1937:     }
 1938:     ReadMode 'normal';
 1939:     print "\n";
 1940:     return $newpasswd;
 1941: }
 1942: 
 1943: sub check_SuSEfirewall2_setup {
 1944:     my ($instdir) = @_;
 1945:     my $need_override = 1;
 1946:     if ((-e "/etc/insserv/overrides/SuSEfirewall2_setup") && (-e "$instdir/sles-suse/SuSEfirewall2_setup")) {
 1947:         if (open(PIPE, "diff --brief $instdir/sles-suse/SuSEfirewall2_setup /etc/insserv/overrides/SuSEfirewall2_setup  |")) {
 1948:             my $diffres = <PIPE>;
 1949:             close(PIPE);
 1950:             chomp($diffres);
 1951:             unless ($diffres) {
 1952:                 $need_override = 0;
 1953:             }
 1954:         }
 1955:     }
 1956:     return $need_override;
 1957: }
 1958: 
 1959: sub download_versionslist {
 1960:     my ($production,$testing,%sizes);
 1961:     if (-e "latest.txt") {
 1962:          unlink("latest.txt");
 1963:     }
 1964:     my $rtncode = system("wget http://install.loncapa.org/versions/latest.txt ".
 1965:                          "> /dev/null 2>&1");
 1966:     if (!$rtncode) {
 1967:         if (open(my $fh,"<latest.txt")) {
 1968:             my @info = <$fh>;
 1969:             close($fh);
 1970:             foreach my $line (@info) {
 1971:                 chomp();
 1972:                 if ($line =~ /^\QLATEST-IS: \E([\w\-.]+):(\d+)$/) {
 1973:                      $production = $1;
 1974:                      $sizes{$1} = $2;
 1975:                 } elsif ($line =~ /^LATEST-TESTING-IS: \E([\w\-.]+):(\d+)$/) {
 1976:                      $testing = $1;
 1977:                      $sizes{$1} = $2;
 1978:                 }
 1979:             }
 1980:         }
 1981:     }
 1982:     return ($production,$testing,\%sizes);
 1983: }
 1984: 
 1985: #
 1986: # End helper routines.
 1987: # Main script starts here
 1988: #
 1989: 
 1990: print "
 1991: ********************************************************************
 1992: 
 1993:                     ".&mt('Welcome to LON-CAPA')."
 1994: 
 1995: ".&mt('This script will configure your system for installation of LON-CAPA.')."
 1996: 
 1997: ********************************************************************
 1998: 
 1999: ".&mt('The following actions are available:')."
 2000: 
 2001: ".&mt('1.')." ".&mt('Create the www user/group.')."
 2002:    ".&mt('This is the user/group ownership under which Apache child processes run.')."
 2003:    ".&mt('It also owns most directories within the /home/httpd directory.')." 
 2004:    ".&mt('This directory is where most LON-CAPA files and directories are stored.')."
 2005: ".&mt('2.')." ".&mt('Install the package LON-CAPA uses to authenticate users.')."
 2006: ".&mt('3.')." ".&mt('Set-up the MySQL database.')."
 2007: ".&mt('4.')." ".&mt('Set-up MySQL permissions.')."
 2008: ".&mt('5.')." ".&mt('Configure Apache web server.')."
 2009: ".&mt('6.')." ".&mt('Configure systemd security settings for Apache web server.')."
 2010: ".&mt('7.')." ".&mt('Configure SSL for Apache web server.')."
 2011: ".&mt('8.')." ".&mt('Configure start-up of services.')."
 2012: ".&mt('9.')." ".&mt('Check firewall settings.')."
 2013: ".&mt('10.')." ".&mt('Stop services not used by LON-CAPA,')."
 2014:    ".&mt('i.e., services for a print server: [_1] daemon.',"'cups'")."
 2015: ".&mt('11.')." ".&mt('Download LON-CAPA source code in readiness for installation.')."
 2016: 
 2017: ".&mt('Typically, you will run this script only once, when you first install LON-CAPA.')." 
 2018: 
 2019: ".&mt('The script will analyze your system to determine which actions are recommended.')."
 2020: ".&mt('The script will then prompt you to choose the actions you would like taken.')."
 2021: 
 2022: ".&mt('For each the recommended action will be selected if you hit Enter/Return.')."
 2023: ".&mt('To override the default, type the lower case option from the two options listed.')."
 2024: ".&mt('So, if the default is "yes", ~[Y/n~] will be shown -- type n to override.')."
 2025: ".&mt('Whereas if the default is "no", ~[y/N~] will be shown -- type y to override.')." 
 2026: 
 2027: ".&mt('To accept the default, simply hit Enter/Return on your keyboard.')."
 2028: ".&mt('Otherwise type: y or n then hit the Enter/Return key.')."
 2029: 
 2030: ".&mt('Once a choice has been entered for all nine actions, required changes will be made.')."
 2031: ".&mt('Feedback will be displayed on screen, and also stored in: [_1].','loncapa_install.log')."
 2032: 
 2033: ".&mt('Continue? ~[Y/n~] ');
 2034: 
 2035: my $go_on = &get_user_selection(1);
 2036: if (!$go_on) {
 2037:     exit;
 2038: }
 2039: 
 2040: my $instdir = `pwd`;
 2041: chomp($instdir);
 2042: 
 2043: my %callsub;
 2044: my @actions = ('wwwuser','pwauth','mysql','mysqlperms','apache','systemd',
 2045:                'apachessl','runlevels','firewall','stopsrvcs','download');
 2046: my %prompts = &texthash( 
 2047:     wwwuser    => "Create the 'www' user?",
 2048:     pwauth     => 'Install the package LON-CAPA uses to authenticate users?',
 2049:     mysql      => 'Set-up the MySQL database?',
 2050:     mysqlperms => 'Set-up MySQL permissions?',
 2051:     apache     => 'Configure Apache web server?',
 2052:     systemd    => 'Configure systemd security settings for Apache web server?',
 2053:     apachessl  => 'Configure SSL for Apache web server?',
 2054:     runlevels  => 'Set overrides for start-up order of services?',
 2055:     firewall   => 'Configure firewall settings for Apache',
 2056:     stopsrvcs  => 'Stop extra services not required on a LON-CAPA server?',
 2057:     download   => 'Download LON-CAPA source code in readiness for installation?',
 2058: );
 2059: 
 2060: print "\n".&mt('Checking system status ...')."\n\n";
 2061: 
 2062: my $dsn = "DBI:mysql:database=mysql";
 2063: my ($distro,$gotprereqs,$localecmd,$langcmd,$packagecmd,$updatecmd,$installnow,$mysqlrestart,
 2064:     $recommended,$dbh,$has_pass,$mysql_unix_socket,$has_lcdb,$downloadstatus,
 2065:     $filetouse,$production,$testing,$apachefw,$uses_systemctl,$hostname,$hostip,
 2066:     $sslhostsfiles,$has_std,$has_int,$rewritenum,$nochgstd,$nochgint) =
 2067:     &check_required($instdir,$dsn);
 2068: if ($distro eq '') {
 2069:     print "\n".&mt('Linux distribution could not be verified as a supported distribution.')."\n".
 2070:           &mt('The following are supported: [_1].',
 2071:               'CentOS, RedHat Enterprise, Fedora, Scientific Linux, '.
 2072:               'Oracle Linux, openSuSE, SLES, Ubuntu LTS, Debian')."\n\n".
 2073:           &mt('Stopping execution.')."\n";
 2074:     exit;
 2075: }
 2076: if ($mysqlrestart) {
 2077:     print "\n".&mt('The mysql daemon needs to be restarted using the following command:')."\n".
 2078:           $mysqlrestart."\n\n".
 2079:           &mt('Stopping execution of install.pl script.')."\n".
 2080:           &mt('Please run the install.pl script again, once you have restarted mysql.')."\n";
 2081:     exit;
 2082: }
 2083: if ($localecmd ne '') {
 2084:     print "\n".&mt('Although the LON-CAPA application itself is localized for a number of different languages,[_1]the default locale language for the Linux OS on which it runs should be US English.',"\n")."\n\n";
 2085:     if ($langcmd ne '') {
 2086:         print &mt('Use the following command(s) or action(s) to install a required language package.')."\n\n".
 2087:               "$langcmd\n";
 2088:     }
 2089:     print &mt('Run the following command from the command line to set the default language for your OS,[_1]and then run this LON-CAPA installation set-up script again.',"\n")."\n\n".
 2090:     $localecmd."\n\n".
 2091:     &mt('Stopping execution.')."\n";
 2092:     exit;
 2093: }
 2094: if (!$gotprereqs) {
 2095:     print "\n".&mt('The LONCAPA-prerequisites package is not installed.')."\n".
 2096:           &mt('The following command can be used to install the package (and dependencies):')."\n\n".
 2097:           $updatecmd."\n\n";
 2098:     if ($installnow eq '') {
 2099:         print &mt('Stopping execution.')."\n";
 2100:         exit;
 2101:     } else {
 2102:         print &mt('Run command? ~[Y/n~]');
 2103:         my $install_prereq = &get_user_selection(1);
 2104:         if ($install_prereq) {
 2105:             if (open(PIPE,'|-',$installnow)) {
 2106:                 close(PIPE);
 2107:                 $gotprereqs = &check_prerequisites($packagecmd,$distro);
 2108:                 if (!$gotprereqs) {
 2109:                     print &mt('The LONCAPA-prerequisites package is not installed.')."\n".
 2110:                           &mt('Stopping execution.')."\n";
 2111:                     exit;
 2112:                 } else {
 2113:                     ($distro,$gotprereqs,$localecmd,$langcmd,$packagecmd,$updatecmd,$installnow,
 2114:                      $mysqlrestart,$recommended,$dbh,$has_pass,$mysql_unix_socket,
 2115:                      $has_lcdb,$downloadstatus,$filetouse,$production,$testing,$apachefw,
 2116:                      $uses_systemctl,$hostname,$hostip,$sslhostsfiles,$has_std,$has_int,
 2117:                      $rewritenum,$nochgstd,$nochgint) = &check_required($instdir,$dsn);
 2118:                 }
 2119:             } else {
 2120:                 print &mt('Failed to run command to install LONCAPA-prerequisites')."\n";
 2121:                 exit;
 2122:             }
 2123:         } else {
 2124:             print &mt('Stopping execution.')."\n";
 2125:             exit;
 2126:         }
 2127:     }
 2128: }
 2129: unless (ref($recommended) eq 'HASH') {
 2130:     print "\n".&mt('An error occurred determining which actions are recommended.')."\n\n".
 2131:           &mt('Stopping execution.')."\n";
 2132:     exit;
 2133: }
 2134: 
 2135: print "\n";
 2136: my $num = 0;
 2137: foreach my $action (@actions) {
 2138:     $num ++;
 2139:     my ($yesno,$defaultrun);
 2140:     if (ref($recommended) eq 'HASH') {
 2141:         if (($action eq 'runlevels') || ($action eq 'stopsrvcs')) {
 2142:             $yesno = '[y/N]';
 2143:             if (ref($recommended->{$action}) eq 'HASH') {
 2144:                 if (keys(%{$recommended->{$action}}) > 0) {
 2145:                     $yesno = &mt('~[Y/n~]');
 2146:                     $defaultrun = 1;
 2147:                 }
 2148:             }
 2149:         } else {
 2150:             if ($action eq 'download') {
 2151:                 if ($downloadstatus) {
 2152:                     print "\n$downloadstatus\n";
 2153:                 }
 2154:             }
 2155:             if ($recommended->{$action}) {
 2156:                 $yesno = mt('~[Y/n~]');
 2157:                 $defaultrun = 1;
 2158:             } else {
 2159:                 $yesno = &mt('~[y/N~]');
 2160:             }
 2161:         }
 2162:         print $num.'. '.$prompts{$action}." $yesno ";
 2163:         $callsub{$action} = &get_user_selection($defaultrun);
 2164:     }
 2165: }
 2166: 
 2167: my $lctarball = 'loncapa-current.tar.gz';
 2168: my $sourcetarball = $lctarball;
 2169: if ($callsub{'download'}) {
 2170:     my ($production,$testing,$sizes) = &download_versionslist();
 2171:     my $homedir = '/root';
 2172:     if ($distro =~ /^ubuntu/) {
 2173:         if ($instdir ne $homedir) {
 2174:             ($homedir) = ($instdir =~ m{^(.*)/[^/]+$});
 2175:         }
 2176:     }
 2177:     if ($production && $testing) {
 2178:         if ($production ne $testing) {
 2179:             print &mt('Two recent LON-CAPA releases are available: ')."\n".
 2180:                   &mt('1.').' '.&mt('A production release - version: [_1].',$production)."\n".
 2181:                   &mt('2.').' '.&mt('A testing release - version: [_1].',$testing)."\n\n".
 2182:                   &mt("After download, the tar.gz file will be extracted into $homedir")."\n\n".
 2183:                   &mt("Download the production release into $instdir? ~[Y/n~]");
 2184:             if (&get_user_selection(1)) {
 2185:                 $sourcetarball = 'loncapa-'.$production.'.tar.gz';
 2186:                 print "$sourcetarball will be downloaded into $instdir\n";
 2187:             } else {
 2188:                 print "\n".&mt('Download the testing release? ~[Y/n~]');
 2189:                 if (&get_user_selection(1)) {
 2190:                     $sourcetarball = 'loncapa-'.$testing.'.tar.gz';
 2191:                     print "$sourcetarball will be downloaded into $instdir\n";
 2192:                 } else {
 2193:                     $callsub{'download'} = 0;
 2194:                 }
 2195:             }
 2196:         }
 2197:     } elsif ($production) {
 2198:         print &mt('The most recent LON-CAPA release is version: [_1].',$production)."\n".
 2199:               &mt("After download, the tar.gz file will be extracted into $homedir")."\n\n".
 2200:               &mt("Download the production release into $instdir? ~[Y/n~]");
 2201:         if (&get_user_selection(1)) {
 2202:             $sourcetarball = 'loncapa-'.$production.'.tar.gz';
 2203:             print "$sourcetarball will be downloaded into $instdir\n";
 2204:         } else {
 2205:             $callsub{'download'} = 0;
 2206:         }
 2207:     }
 2208: } elsif ($filetouse ne '') {
 2209:     $sourcetarball = $filetouse;
 2210: }
 2211: 
 2212: print_and_log("\n");
 2213: 
 2214: # Each action: report if skipping, or perform action and provide feedback. 
 2215: if ($callsub{'wwwuser'}) {
 2216:     &setup_www();
 2217: } else {
 2218:     &print_and_log(&mt('Skipping creation of user [_1].',"'www'")."\n");
 2219: }
 2220: 
 2221: if ($callsub{'pwauth'}) {
 2222:     &build_and_install_mod_auth_external($instdir);
 2223: } else {
 2224:     &print_and_log(&mt('Skipping [_1] installation.',"'pwauth'")."\n");
 2225: }
 2226: 
 2227: if ($callsub{'mysql'}) {
 2228:     if ($dbh) {
 2229:         &setup_mysql($callsub{'mysqlperms'},$dbh,$has_pass,
 2230:                      $mysql_unix_socket,$has_lcdb,$distro);
 2231:     } else {
 2232:         print &mt('Unable to configure MySQL because access is denied.')."\n";
 2233:     }
 2234: } else {
 2235:     &print_and_log(&mt('Skipping configuration of MySQL.')."\n");
 2236:     if ($callsub{'mysqlperms'}) {
 2237:         if ($dbh) {
 2238:             &setup_mysql_permissions($dbh,$has_pass,$mysql_unix_socket);
 2239:         } else {
 2240:             print &mt('Unable to configure MySQL because access is denied.')."\n";  
 2241:         }
 2242:     } else {
 2243:         &print_and_log(&mt('Skipping MySQL permissions setup.')."\n");
 2244:     }
 2245: }
 2246: 
 2247: if ($dbh) {
 2248:     if (!$dbh->disconnect) {
 2249:         &print_and_log(&mt('Failed to disconnect from MySQL:')."\n".
 2250:                        $dbh->errstr);
 2251:     }
 2252: }
 2253: 
 2254: if ($callsub{'apache'}) {
 2255:     if ($distro =~ /^(suse|sles)/) {
 2256:         &copy_apache2_suseconf($instdir,$hostname,$distro);
 2257:     } elsif ($distro =~ /^(debian|ubuntu)/) {
 2258:         &copy_apache2_debconf($instdir,$distro,$hostname);
 2259:     } else {
 2260:         &copy_httpd_conf($instdir,$distro,$hostname);
 2261:         &copy_mpm_conf($instdir,$distro);
 2262:     }
 2263: } else {
 2264:     print_and_log(&mt('Skipping configuration of Apache web server.')."\n");
 2265: }
 2266: 
 2267: if ($callsub{'systemd'}) {
 2268:     &check_systemd_update($distro); 
 2269: } else {
 2270:     print_and_log('Skipping systemd configuration update for web server');
 2271: }
 2272: 
 2273: if ($callsub{'apachessl'}) {
 2274:     my $targetdir = '/etc/httpd/conf.d';
 2275:     if ($distro =~ /^(suse|sles)/) {
 2276:         $targetdir = '/etc/apache2/vhosts.d';
 2277:     } elsif ($distro =~ /^(debian|ubuntu)/) {
 2278:         $targetdir = '/etc/apache2/sites-available';
 2279:     }
 2280:     my ($new_rewrite,$new_int) = 
 2281:         &copy_apache_sslconf_files($distro,$hostname,$hostip,$instdir,$targetdir,$sslhostsfiles,
 2282:                                    $has_std,$has_int,$rewritenum,$nochgstd,$nochgint); 
 2283:     if ($distro =~ /^(debian|ubuntu)/) {
 2284:         my $apache2_sites_enabled_dir = '/etc/apache2/sites-enabled';
 2285:         if (-d $apache2_sites_enabled_dir) {  
 2286:             if ($has_std ne '') {
 2287:                 unless ((-l "$apache2_sites_enabled_dir/$has_std") && (readlink(("$apache2_sites_enabled_dir/$has_std") eq "$targetdir/$has_std"))) {
 2288:                     my $made_symlink =  eval { symlink("$targetdir/$has_std","$apache2_sites_enabled_dir/$has_std"); 1};
 2289:                     if ($made_symlink) {
 2290:                         print_and_log(&mt('Enabling "[_1]" Apache SSL configuration.',$has_std)."\n");
 2291:                     }
 2292:                 }
 2293:             }
 2294:             if (($has_int ne '') && ($has_int ne $has_std)) {
 2295:                 unless ((-l "$apache2_sites_enabled_dir/$has_int") && (readlink("$apache2_sites_enabled_dir/$has_int") eq "$targetdir/$has_int")) {
 2296:                     my $made_symlink =  eval { symlink("$targetdir/$has_int","$apache2_sites_enabled_dir/$has_int"); 1 };
 2297:                     if ($made_symlink) {
 2298:                         print_and_log(&mt('Enabling "[_1]" Apache SSL configuration.',$has_int)."\n");
 2299:                     }
 2300:                 }
 2301:             }
 2302:         }
 2303:     }
 2304:     print_and_log("\n");
 2305: } else {
 2306:     print_and_log(&mt('Skipping configuration of SSL for Apache web server.')."\n");
 2307: }
 2308: 
 2309: if ($callsub{'runlevels'}) {
 2310:     my $count = 0;
 2311:     if (ref($recommended) eq 'HASH') {
 2312:         if (ref($recommended->{'runlevels'}) eq 'HASH') {
 2313:             foreach my $type (keys(%{$recommended->{'runlevels'}})) {
 2314:                 next if ($type eq 'insserv');
 2315:                 $count ++;
 2316:                 my $command = $recommended->{'runlevels'}{$type};
 2317:                 if ($command ne '') {
 2318:                     print_and_log(&mt('Runlevel update command run: [_1].',$command)."\n");
 2319:                     system($command);
 2320:                 }
 2321:             }
 2322:             if (!$count) {
 2323:                 print_and_log(&mt('No runlevel updates required.')."\n");
 2324:             }  
 2325:         }
 2326:     }
 2327:     if ($distro =~ /^(suse|sles)(\d+)/) {
 2328:         unless(($1 eq 'sles') && ($2 >= 15)) {
 2329:             &update_SuSEfirewall2_setup($instdir);
 2330:         }
 2331:     }
 2332: } else {
 2333:     &print_and_log(&mt('Skipping setting override for start-up order of services.')."\n");
 2334: }
 2335: 
 2336: if ($callsub{'firewall'}) {
 2337:     my ($firewalld,$zone) = &uses_firewalld($distro);
 2338:     if ($firewalld) {
 2339:         my (%current,%added);
 2340:         if (open(PIPE,"firewall-cmd --permanent --zone=$zone --list-services |")) {
 2341:             my $svc = <PIPE>;
 2342:             close(PIPE);
 2343:             chomp($svc);
 2344:             map { $current{$_} = 1; } (split(/\s+/,$svc));
 2345:         }
 2346:         foreach my $service ('http','https') {
 2347:             unless ($current{$service}) {
 2348:                 if (open(PIPE,"firewall-cmd --permanent --zone=$zone --add-service=$service |")) {
 2349:                     my $result = <PIPE>;
 2350:                     if ($result =~ /^success/) {
 2351:                         $added{$service} = 1;
 2352:                     }
 2353:                 }
 2354:             }
 2355:         }
 2356:         if (keys(%added) > 0) {
 2357:             print &mt('Firewall configured to allow access for: [_1].',
 2358:                       join(', ',sort(keys(%added))))."\n";
 2359:             system('firewall-cmd --reload');
 2360:         }
 2361:         if ($current{'http'} || $current{'https'}) {
 2362:             print &mt('Firewall already configured to allow access for:[_1].',
 2363:                       (($current{'http'})? ' http':'').(($current{'https'})? ' https':''))."\n";
 2364:         }
 2365:         unless ($current{'ssh'}) {
 2366:             print &mt('If you would like to allow access to ssh from outside, use the commands:')."\n".
 2367:                   "firewall-cmd --permanent --zone=$zone --add-service=ssh\n".
 2368:                   "firewall-cmd --reload\n";
 2369:         }
 2370:     } elsif ($distro =~ /^(suse|sles)/) {
 2371:         print &mt('Use [_1] to configure the firewall to allow access for [_2].',
 2372:                   'yast -- Security and Users -> Firewall -> Interfaces',
 2373:                   'ssh, http, https')."\n";
 2374:     } elsif ($distro =~ /^(debian|ubuntu)(\d+)/) {
 2375:         if (($1 eq 'ubuntu') || ($2 > 5)) {
 2376:             print &mt('Use [_1] to configure the firewall to allow access for [_2].',
 2377:                       'ufw','ssh, http, https')."\n";
 2378:         } else {
 2379:             my $fwadded = &get_iptables_rules($distro,$instdir,$apachefw);
 2380:             if ($fwadded) {
 2381:                 print &mt('Enable firewall? ~[Y/n~]');
 2382:                 my $enable_iptables = &get_user_selection(1);
 2383:                 if ($enable_iptables) {
 2384:                     system('/etc/network/if-pre-up.d/iptables');
 2385:                     print &mt('Firewall enabled using rules defined in [_1].',
 2386:                               '/etc/iptables.loncapa.rules'); 
 2387:                 }
 2388:             }
 2389:         }
 2390:     } elsif ($distro =~ /^(scientific|oracle)/) {
 2391:         print &mt('Use [_1] to configure the firewall to allow access for [_2].',
 2392:                   'system-config-firewall-tui -- Customize',
 2393:                   'ssh, http')."\n";
 2394:     } else {
 2395:         my $version;
 2396:         if ($distro =~ /^(redhat|centos|rocky|alma)(\d+)/) {
 2397:             $version = $1;
 2398:         }
 2399:         if ($version > 5) {
 2400:             print &mt('Use [_1] to configure the firewall to allow access for [_2].',
 2401:                   'system-config-firewall-tui -- Customize',
 2402:                   'ssh, http')."\n";
 2403:         } else {
 2404:             print &mt('Use [_1] to configure the firewall to allow access for [_2].',
 2405:                       'setup -- Firewall configuration -> Customize',
 2406:                       'ssh, http, https')."\n";
 2407:         }
 2408:     }
 2409: } else {
 2410:     &print_and_log(&mt('Skipping Firewall configuration.')."\n");
 2411: }
 2412: 
 2413: if ($callsub{'stopsrvcs'}) {
 2414:     &kill_extra_services($distro,$recommended->{'stopsrvcs'},$uses_systemctl);
 2415: } else {
 2416:     &print_and_log(&mt('Skipping stopping unnecessary service ([_1] daemons).',"'cups','memcached'")."\n");
 2417: }
 2418: 
 2419: my ($have_tarball,$updateshown);
 2420: if ($callsub{'download'}) {
 2421:     ($have_tarball,$updateshown) = &download_loncapa($instdir,$sourcetarball);
 2422: } else {
 2423:     print_and_log(&mt('Skipping download of LON-CAPA tar file.')."\n\n");
 2424:     print &mt('LON-CAPA is available for download from: [_1]',
 2425:               'http://install.loncapa.org/')."\n";
 2426:     if (!-e '/etc/loncapa-release') {
 2427:         &print_and_log(&mt('LON-CAPA is not yet installed on your system.')."\n\n");
 2428:         unless ($filetouse) {
 2429:             &print_and_log(&mt('You may retrieve the source for LON-CAPA by executing:')."\n".
 2430:                            "wget http://install.loncapa.org/versions/$lctarball\n");
 2431:         }
 2432:     } else {
 2433:         my $currentversion;
 2434:         if (open(my $fh,"</etc/loncapa-release")) {
 2435:             my $version = <$fh>;
 2436:             chomp($version);
 2437:             if ($version =~ /^\QLON-CAPA release \E([\w\-.]+)$/) {
 2438:                 $currentversion = $1;
 2439:             }
 2440:         }
 2441:         if ($currentversion ne '') {
 2442:             print &mt('Version of LON-CAPA currently installed on this server is: [_1].',
 2443:                       $currentversion),"\n";
 2444:             if ($production) {
 2445:                 print &mt('The latest production release of LON-CAPA is [_1].',$production)."\n";
 2446:             }
 2447:             if ($testing) {
 2448:                 print &mt('The latest testing release of LON-CAPA is [_1].',$testing)."\n";
 2449:             }
 2450:         }
 2451:     }
 2452:     if ($filetouse ne '') {
 2453:         $have_tarball = 1;
 2454:     }
 2455: }
 2456: 
 2457: print "\n".&mt('Requested configuration complete.')."\n\n";
 2458: if ($have_tarball && !$updateshown) {
 2459:     my ($lcdir) = ($sourcetarball =~ /^([\w.\-]+)\.tar.gz$/);
 2460:     if ($lcdir eq 'loncapa-current') {
 2461:         $lcdir = "loncapa-X.Y.Z (X.Y.Z should correspond to a version number like '2.11.3')";
 2462:     }
 2463:     my ($apachename,$lc_uses_systemctl,$uses_sudo);
 2464:     if ($distro =~ /^(suse|sles|debian|ubuntu)([\d.]+)/) {
 2465:         if (($1 eq 'suse') && ($2 < 10)) {
 2466:             $apachename = 'apache';
 2467:         } else {
 2468:             $apachename = 'apache2';
 2469:         }
 2470:     } else {
 2471:         $apachename = 'httpd';
 2472:     }
 2473:     if ($distro =~ /^oracle(\d+)$/) {
 2474:         if ($1 > 6) {
 2475:             $lc_uses_systemctl = 1;
 2476:         }
 2477:     } elsif ($distro =~ /^(?:rhes|centos|rocky|alma)(\d+)/) {
 2478:         if ($1 > 7) {
 2479:             $lc_uses_systemctl = 1;
 2480:         }
 2481:     } elsif ($distro =~ /^ubuntu(\d+)$/) {
 2482:         if ($1 > 16) {
 2483:             $lc_uses_systemctl = 1;
 2484:         }
 2485:         $uses_sudo = 1;
 2486:     } elsif ($distro =~ /^debian(\d+)$/) {
 2487:         if ($1 >= 10) {
 2488:             $lc_uses_systemctl = 1;
 2489:         }
 2490:     } elsif ($distro =~ /^sles(\d+)$/) {
 2491:         if ($1 > 12) {
 2492:             $lc_uses_systemctl = 1;
 2493:         }
 2494:     } elsif ($distro =~ /^fedora(\d+)$/) {
 2495:         if ($1 > 25) {
 2496:             $lc_uses_systemctl = 1;
 2497:         }
 2498:     }
 2499:     if (!-e '/etc/loncapa-release') {
 2500:         print &mt('If you are now ready to install LON-CAPA, enter the following commands:')."\n\n";
 2501:     } else {
 2502:         my $lcstop = '/etc/init.d/loncontrol stop';
 2503:         if ($lc_uses_systemctl) {
 2504:             $lcstop = 'systemctl stop loncontrol';
 2505:         }
 2506:         my $apachestop = "/etc/init.d/$apachename stop";
 2507:         if ($uses_systemctl) {
 2508:             $apachestop = "systemctl stop $apachename";
 2509:         }
 2510:         if ($uses_sudo) {
 2511:             $lcstop = 'sudo '.$lcstop;
 2512:             $apachestop = 'sudo '.$apachestop;
 2513:         }
 2514:         print &mt('If you are now ready to update LON-CAPA, enter the following commands:').
 2515:               "\n\n$lcstop\n$apachestop\n";
 2516:     }
 2517:     my ($extract,$update);
 2518:     my $homedir = '/root';
 2519:     if ($uses_sudo) {
 2520:         $extract = 'sudo ';
 2521:         $update = 'sudo ';
 2522:         if ($instdir ne $homedir) {
 2523:             ($homedir) = ($instdir =~ m{^(.*)/[^/]+$});
 2524:         }
 2525:     }
 2526:     $extract .= "tar zxf $sourcetarball --directory $homedir";
 2527:     $update .= './UPDATE';
 2528:     print "$extract\n".
 2529:           "cd $homedir/$lcdir\n".
 2530:           "$update\n";
 2531:     if (-e '/etc/loncapa-release') {
 2532:         my $lcstart = '/etc/init.d/loncontrol start';
 2533:         if ($lc_uses_systemctl) {
 2534:             $lcstart = '/home/httpd/perl/loncontrol start';
 2535:         }
 2536:         my $apachestart = "/etc/init.d/$apachename start";
 2537:         if ($uses_systemctl) {
 2538:             $apachestart = "systemctl start $apachename";
 2539:         }
 2540:         if ($uses_sudo) {
 2541:             $lcstart = 'sudo '.$lcstart;
 2542:             $apachestart = 'sudo '.$apachestart;
 2543:         }
 2544:         print "$lcstart\n";
 2545:         print "$apachestart\n";
 2546:     }
 2547: }
 2548: exit;
 2549: 
 2550: #
 2551: # End main script
 2552: #
 2553: 
 2554: #
 2555: # Routines for the actions
 2556: #
 2557:  
 2558: sub setup_www {
 2559:     ##
 2560:     ## Set up www
 2561:     ##
 2562:     print_and_log(&mt('Creating user [_1]',"'www'")."\n");
 2563:     # -- Add group
 2564: 
 2565:     my $status = `/usr/sbin/groupadd www`;
 2566:     if ($status =~ /\QGroup `www' already exists.\E/) {
 2567:         print &mt('Group [_1] already exists.',"'www'")."\n";
 2568:     } elsif ($status ne '') {
 2569:         print &mt('Unable to add group [_1].',"'www'")."\n";
 2570:     }
 2571:    
 2572:     my $gid = getgrnam('www');
 2573: 
 2574:     if (open (PIPE, "/usr/sbin/useradd -c LONCAPA -g $gid www 2>&1 |")) {
 2575:         $status = <PIPE>;
 2576:         close(PIPE);
 2577:         chomp($status);
 2578:         if ($status =~ /\QAccount `www' already exists.\E/) {
 2579:             print &mt('Account [_1] already exists.',"'www'")."\n";
 2580:         } elsif ($status ne '') {
 2581:             print &mt('Unable to add user [_1].',"'www'")."\n";
 2582:         }
 2583:     }  else {
 2584:         print &mt('Unable to run command to add user [_1].',"'www'")."\n";
 2585:     }
 2586: 
 2587:     my $uid = &uid_of_www();
 2588:     if (($gid ne '') && ($uid ne '')) {
 2589:         if (!-e '/home/www') {
 2590:             mkdir('/home/www',0755);
 2591:             system('chown www:www /home/www');
 2592:         }
 2593:     }
 2594:     writelog ($status);
 2595: }
 2596: 
 2597: sub uid_of_www {
 2598:     my ($num) = (getpwnam('www'))[2];
 2599:     return $num;
 2600: }
 2601: 
 2602: sub build_and_install_mod_auth_external {
 2603:     my ($instdir) = @_;
 2604:     my $num = &uid_of_www();
 2605:     # Patch pwauth
 2606:     print_and_log(&mt('Building authentication system for LON-CAPA users.')."\n");
 2607:     my $patch = <<"ENDPATCH";
 2608: 148c148
 2609: < #define SERVER_UIDS 99		/* user "nobody" */
 2610: ---
 2611: > #define SERVER_UIDS $num		/* user "www" */
 2612: ENDPATCH
 2613: 
 2614:     my $patch_code = <<"ENDPATCH";
 2615: 127a128
 2616: > #include <string.h>
 2617: 214a216
 2618: > #include <time.h>
 2619: 566c568
 2620: < check_fails()
 2621: ---
 2622: > int check_fails()
 2623: 589c591
 2624: < log_failure()
 2625: ---
 2626: > void log_failure()
 2627: 629c631
 2628: < snooze(int seconds)
 2629: ---
 2630: > void snooze(int seconds)
 2631: 653c655
 2632: < main(int argc, char **argv)
 2633: ---
 2634: > int main(int argc, char **argv)
 2635: ENDPATCH
 2636: 
 2637:     if (! -e "/usr/bin/patch") {
 2638: 	print_and_log(&mt('You must install the software development tools package: [_1], when installing Linux.',"'patch'")."\n");
 2639:         print_and_log(&mt('Authentication installation not completed.')."\n");
 2640:         return;
 2641:     }
 2642:     if (&skip_if_nonempty(`cd /tmp; tar zxf $instdir/pwauth-2.2.8.tar.gz`,
 2643: 		     &mt('Unable to extract pwauth')."\n")) {
 2644:         return;
 2645:     }
 2646:     my $dir = "/tmp/pwauth-2.2.8";
 2647:     my $patchedok;
 2648:     if (open(PATCH,"| patch $dir/config.h")) {
 2649:         print PATCH $patch;
 2650:         close(PATCH);
 2651:         if (open(PATCH,"| patch $dir/pwauth.c")) {
 2652:             print PATCH $patch_code;
 2653:             close(PATCH);
 2654:             $patchedok = 1;
 2655:         }
 2656:     }
 2657:     if ($patchedok) {
 2658:         print_and_log("\n");
 2659:         ##
 2660:         ## Compile patched pwauth
 2661:         ##
 2662:         print_and_log(&mt('Compiling pwauth')."\n");
 2663:         my $result = `cd $dir/; make 2>/dev/null `;
 2664:         my $expected = <<"END";
 2665: gcc -g    -c -o pwauth.o pwauth.c
 2666: gcc -o pwauth -g  pwauth.o -lcrypt
 2667: END
 2668:         if ($result eq $expected) {
 2669:             print_and_log(&mt('Apparent success compiling pwauth:').
 2670:                           "\n".$result );
 2671:             # Install patched pwauth
 2672:             print_and_log(&mt('Copying pwauth to [_1]',' /usr/local/sbin')."\n");
 2673:             if (copy "$dir/pwauth","/usr/local/sbin/pwauth") {
 2674:                 if (chmod(06755, "/usr/local/sbin/pwauth")) {
 2675:                     print_and_log(&mt('[_1] copied successfully',"'pwauth'").
 2676:                                   "\n");
 2677:                 } else {
 2678:                     print &mt('Unable to set permissions on [_1].'.
 2679:                               "/usr/local/sbin/pwauth")."\n";
 2680:                 }
 2681:             } else {
 2682:                 print &mt('Unable to copy [_1] to [_2]',
 2683:                           "'$dir/pwauth'","/usr/local/sbin/pwauth")."\n$!\n";
 2684:             }
 2685:         } else {
 2686:             print &mt('Unable to compile patched [_1].'."'pwauth'")."\n";
 2687:         }
 2688:     } else {
 2689:         print &mt('Unable to start patch for [_1]',"'pwauth'")."\n";
 2690:     }
 2691:     print_and_log("\n");
 2692: }
 2693: 
 2694: sub kill_extra_services {
 2695:     my ($distro,$stopsrvcs,$uses_systemctl) = @_;
 2696:     if (ref($stopsrvcs) eq 'HASH') {
 2697:         my @stopping = sort(keys(%{$stopsrvcs}));
 2698:         if (@stopping) {
 2699:             my $kill_list = join("', '",@stopping);
 2700:             if ($kill_list) {
 2701:                 $kill_list = "'".$kill_list."'";
 2702:                 &print_and_log("\n".&mt('Killing unnecessary services ([_1] daemon(s)).',$kill_list)."\n");
 2703:                 foreach my $service (@stopping) {
 2704:                     my $daemon = $service;
 2705:                     if ($service eq 'cups') {
 2706:                         $daemon = 'cupsd';
 2707:                         if ($distro =~ /^(?:debian|ubuntu)(\d+)/) {
 2708:                             my $version = $1;
 2709:                             if (($distro =~ /^ubuntu/) && ($version <= 8)) {
 2710:                                 $daemon = 'cupsys';
 2711:                             }
 2712:                         } else {
 2713:                             $daemon = 'cups';
 2714:                         }
 2715:                     }
 2716:                     my $cmd = "ps -ef |grep '$daemon' |grep -v grep";
 2717:                     if (open(PIPE,'-|',$cmd)) {
 2718:                         my $daemonrunning = <PIPE>;
 2719:                         chomp($daemonrunning);
 2720:                         close(PIPE);
 2721:                         if ($daemonrunning) {
 2722:                             &print_and_log(`/etc/init.d/$daemon stop`);
 2723:                         }
 2724:                     }
 2725: 	            &print_and_log(&mt('Removing [_1] from startup.',$service)."\n");
 2726:                     if ($distro =~ /^(?:debian|ubuntu)(\d+)/) {
 2727:                         my $version = $1;
 2728:                         if ((($distro =~ /^ubuntu/) && ($version > 16)) ||
 2729:                             (($distro =~ /^debian/) && ($version >= 10))) {
 2730:                             if (ref($uses_systemctl) eq 'HASH') {
 2731:                                 if ($uses_systemctl->{$service}) {
 2732:                                     if (`systemctl is-enabled $service`) {
 2733:                                         &print_and_log(`systemctl disable $service`);
 2734:                                     }
 2735:                                 }
 2736:                             }
 2737:                         } else {
 2738:                             &print_and_log(`update-rc.d -f $daemon remove`);
 2739:                         }
 2740:                     } else {
 2741:                         if (ref($uses_systemctl) eq 'HASH') {
 2742:                             if ($uses_systemctl->{$service}) {
 2743:                                 if (`systemctl is-enabled $service`) {                          
 2744:                                     &print_and_log(`systemctl disable $service`);
 2745:                                 }
 2746:                             } else {
 2747:                                 &print_and_log(`/sbin/chkconfig --del $service`);
 2748:                             }
 2749:                         } else {
 2750: 	                    &print_and_log(`/sbin/chkconfig --del $service`);
 2751:                         } 
 2752:                     }
 2753:                 }
 2754:             }
 2755:         }
 2756:     }
 2757:     return;
 2758: }
 2759: 
 2760: sub setup_mysql {
 2761:     my ($setup_mysql_permissions,$dbh,$has_pass,$mysql_unix_socket,$has_lcdb,$distro) = @_;
 2762:     my @mysql_lc_commands;
 2763:     unless ($has_lcdb) {
 2764:         my $createcmd = 'CREATE DATABASE loncapa';
 2765:         if ($distro =~ /^sles(\d+)/) {
 2766:             if ($1 > 11) {
 2767:                 $createcmd .= ' CHARACTER SET utf8 COLLATE utf8_general_ci';
 2768:             }
 2769:         } elsif ($distro =~ /^ubuntu(\d+)/) {
 2770:             if ($1 > 16) {
 2771:                 $createcmd .= ' CHARACTER SET latin1 COLLATE latin1_swedish_ci';
 2772:             }
 2773:         }
 2774:         push(@mysql_lc_commands,$createcmd);
 2775:     }
 2776:     push(@mysql_lc_commands,"USE loncapa");
 2777:     push(@mysql_lc_commands,qq{
 2778: CREATE TABLE IF NOT EXISTS metadata (title TEXT, author TEXT, subject TEXT, url TEXT, keywords TEXT, version TEXT, notes TEXT, abstract TEXT, mime TEXT, language TEXT, creationdate DATETIME, lastrevisiondate DATETIME, owner TEXT, copyright TEXT, domain TEXT, dependencies TEXT, modifyinguser TEXT, authorspace TEXT, lowestgradelevel TEXT, highestgradelevel TEXT, standards TEXT, count INT, course INT, course_list TEXT, goto INT, goto_list TEXT, comefrom INT, comefrom_list TEXT, sequsage INT, sequsage_list TEXT, stdno INT, stdno_list TEXT, avetries FLOAT, avetries_list TEXT, difficulty FLOAT, difficulty_list TEXT, disc FLOAT, disc_list TEXT, clear FLOAT, technical FLOAT, correct FLOAT, helpful FLOAT, depth FLOAT, hostname TEXT, FULLTEXT idx_title (title), FULLTEXT idx_author (author), FULLTEXT idx_subject (subject), FULLTEXT idx_url (url), FULLTEXT idx_keywords (keywords), FULLTEXT idx_version (version), FULLTEXT idx_notes (notes), FULLTEXT idx_abstract (abstract), FULLTEXT idx_mime (mime), FULLTEXT idx_language (language), FULLTEXT idx_owner (owner), FULLTEXT idx_copyright (copyright)) ENGINE=MYISAM
 2779: });
 2780:     if ($setup_mysql_permissions) {
 2781:         &setup_mysql_permissions($dbh,$has_pass,$mysql_unix_socket,@mysql_lc_commands);
 2782:     } else {
 2783:         print_and_log(&mt('Skipping MySQL permissions setup.')."\n");
 2784:         if ($dbh) {
 2785:             if (@mysql_lc_commands) {
 2786:                 foreach my $lccmd (@mysql_lc_commands) { 
 2787:                     $dbh->do($lccmd) || print $dbh->errstr."\n";
 2788:                 }
 2789:             }
 2790:             print_and_log(&mt('MySQL database set up complete.')."\n");
 2791:         } else {
 2792:             print_and_log(&mt('Problem accessing MySQL.')."\n");
 2793:         }
 2794:     }
 2795: }
 2796: 
 2797: sub setup_mysql_permissions {
 2798:     my ($dbh,$has_pass,$mysql_unix_socket,@mysql_lc_commands) = @_;
 2799:     my ($mysqlversion,$mysqlminorversion,$mysqlsubver,$mysqlname) = &get_mysql_version();
 2800:     my ($usescreate,$usesauth,$is_mariadb,$hasauthcol,@mysql_commands);
 2801:     if ($mysqlname =~ /^MariaDB/i) {
 2802:         $is_mariadb = 1;
 2803:         if ((($mysqlversion == 10) && ($mysqlminorversion >= 4)) || ($mysqlversion >= 11)) {
 2804:             $usescreate = 1;
 2805:         } elsif (($mysqlversion == 10) && ($mysqlminorversion >= 2)) {
 2806:             $usesauth = 1;
 2807:         } elsif (($mysqlversion == 5) && ($mysqlminorversion >= 5)) {
 2808:             $hasauthcol = 1;
 2809:         }
 2810:     } else {
 2811:         if (($mysqlversion > 5) || (($mysqlminorversion == 5) && ($mysqlminorversion > 7)) ||
 2812:             (($mysqlversion == 5) && ($mysqlminorversion == 7) && ($mysqlsubver > 5))) {
 2813:             $usesauth = 1;
 2814:         } elsif (($mysqlversion == 5) &&
 2815:                  (($mysqlminorversion >= 6) || (($mysqlminorversion == 5) && ($mysqlsubver >= 7)))) {
 2816:             $hasauthcol = 1;
 2817:         }
 2818:     }
 2819:     if ($usescreate) {
 2820:         @mysql_commands = ("CREATE USER 'www'\@'localhost' IDENTIFIED BY 'localhostkey'");
 2821:     } elsif ($usesauth) {
 2822:         @mysql_commands = ("INSERT user (Host, User, ssl_cipher, x509_issuer, x509_subject, authentication_string) VALUES('localhost','www','','','','')",
 2823:                            "FLUSH PRIVILEGES");
 2824:         if ($is_mariadb) {
 2825:             push(@mysql_commands,"ALTER USER 'www'\@'localhost' IDENTIFIED BY 'localhostkey'");
 2826:         } else {
 2827:             push(@mysql_commands,"ALTER USER 'www'\@'localhost' IDENTIFIED WITH mysql_native_password BY 'localhostkey'");
 2828:         }
 2829:     } elsif ($hasauthcol) {
 2830:         @mysql_commands = ("INSERT user (Host, User, Password, ssl_cipher, x509_issuer, x509_subject, authentication_string) VALUES('localhost','www',password('localhostkey'),'','','','');");
 2831:     } else {
 2832:         @mysql_commands = ("INSERT user (Host, User, Password, ssl_cipher, x509_issuer, x509_subject) VALUES('localhost','www',password('localhostkey'),'','','');");
 2833:     }
 2834:     if ($mysqlversion < 4) {
 2835:         push (@mysql_commands,"
 2836: INSERT db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Grant_priv,References_priv,Index_priv,Alter_priv) VALUES('localhost','loncapa','www','Y','Y','Y','Y','Y','Y','N','Y','Y','Y')");
 2837:     } else {
 2838:         push (@mysql_commands,"
 2839: INSERT db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Grant_priv,References_priv,Index_priv,Alter_priv,Create_tmp_table_priv,Lock_tables_priv) VALUES('localhost','loncapa','www','Y','Y','Y','Y','Y','Y','N','Y','Y','Y','Y','Y')");
 2840:     }
 2841:     push(@mysql_commands,"DELETE FROM user WHERE host<>'localhost'");
 2842:     if (($has_pass) || ($mysql_unix_socket)) {
 2843:         if ($dbh) {
 2844:             push(@mysql_commands,"FLUSH PRIVILEGES");
 2845:             if (@mysql_commands) {
 2846:                 foreach my $cmd (@mysql_commands) {
 2847:                     $dbh->do($cmd) || print $dbh->errstr."\n";
 2848:                 }
 2849:             }
 2850:             if (@mysql_lc_commands) {
 2851:                 foreach my $lccmd (@mysql_lc_commands) {
 2852:                     $dbh->do($lccmd) || print $dbh->errstr."\n";
 2853:                 }
 2854:             }
 2855:             print_and_log(&mt('Permissions set for LON-CAPA MySQL user: [_1]',"'www'")."\n");
 2856:         } else {
 2857:             print_and_log(&mt('Problem accessing MySQL.')."\n".
 2858:                           &mt('Permissions not set.')."\n");
 2859:         }
 2860:     } else {
 2861:         my ($firstpass,$secondpass,$got_passwd,$newmysqlpass);
 2862:         print &mt('Please enter a root password for the mysql database.')."\n".
 2863:               &mt('It does not have to match your root account password, but you will need to remember it.')."\n";
 2864:         my $maxtries = 10;
 2865:         my $trial = 0;
 2866:         while ((!$got_passwd) && ($trial < $maxtries)) {
 2867:             $firstpass = &get_mysql_password(&mt('Enter password'));
 2868:             if (length($firstpass) > 5) { 
 2869:                 $secondpass = &get_mysql_password(&mt('Enter password a second time'));
 2870:                 if ($firstpass eq $secondpass) {
 2871:                     $got_passwd = 1;
 2872:                     $newmysqlpass = $firstpass;
 2873:                 } else {
 2874:                     print(&mt('Passwords did not match. Please try again.')."\n");
 2875:                 }
 2876:                 $trial ++;
 2877:             } else {
 2878:                 print(&mt('Password too short.')."\n".
 2879:                       &mt('Please choose a password with at least six characters.')."\n");
 2880:             }
 2881:         }
 2882:         if ($got_passwd) {
 2883:             my (@newpass_cmds) = &new_mysql_rootpasswd($newmysqlpass,$usesauth,$is_mariadb);
 2884:             push(@mysql_commands,@newpass_cmds);
 2885:         } else {
 2886:             print_and_log(&mt('Failed to get MySQL root password from user input.')."\n");
 2887:         }
 2888:         if ($dbh) {
 2889:             if (@mysql_commands) {
 2890:                 foreach my $cmd (@mysql_commands) {
 2891:                     $dbh->do($cmd) || print $dbh->errstr."\n";
 2892:                 }
 2893:             }
 2894:             if (@mysql_lc_commands) {
 2895:                 foreach my $lccmd (@mysql_lc_commands) {
 2896:                     $dbh->do($lccmd) || print $dbh->errstr."\n";
 2897:                 }
 2898:             }
 2899:             if ($got_passwd) {
 2900:                 print_and_log(&mt('MySQL root password stored.')."\n".
 2901:                               &mt('Permissions set for LON-CAPA MySQL user: [_1].',"'www'")."\n");
 2902:             } else {
 2903:                 print_and_log(&mt('Permissions set for LON-CAPA MySQL user: [_1].',"'www'")."\n");
 2904:             }
 2905:         } else {
 2906:             print_and_log(&mt('Problem accessing MySQL.')."\n".
 2907:                           &mt('Permissions not set.')."\n");
 2908:         }
 2909:     }
 2910: }
 2911: 
 2912: sub new_mysql_rootpasswd {
 2913:     my ($currmysqlpass,$usesauth,$is_mariadb) = @_;
 2914:     if ($usesauth) {
 2915:         if ($is_mariadb) {
 2916:             return ("ALTER USER 'root'\@'localhost' IDENTIFIED BY '$currmysqlpass'",
 2917:                     "FLUSH PRIVILEGES;");
 2918:         } else {
 2919:             return ("ALTER USER 'root'\@'localhost' IDENTIFIED WITH mysql_native_password BY '$currmysqlpass'",
 2920:                     "FLUSH PRIVILEGES;");
 2921:         }
 2922:     } else {
 2923:         return ("SET PASSWORD FOR 'root'\@'localhost'=PASSWORD('$currmysqlpass')",
 2924:                 "FLUSH PRIVILEGES;");
 2925:     }
 2926: }
 2927: 
 2928: sub get_mysql_version {
 2929:     my ($version,$minorversion,$subversion,$name);
 2930:     if (open(PIPE," mysql -V |")) {
 2931:         my $info = <PIPE>;
 2932:         chomp($info);
 2933:         close(PIPE);
 2934:         ($version,$minorversion,$subversion,$name) = ($info =~ /(\d+)\.(\d+)\.(\d+)(?:\-?(\w*),|)/);
 2935:     } else {
 2936:         print &mt('Could not determine which version of MySQL is installed.').
 2937:               "\n";
 2938:     }
 2939:     return ($version,$minorversion,$subversion,$name);
 2940: }
 2941: 
 2942: sub check_systemd_update {
 2943:     my ($distro) = @_;
 2944:     my ($use_systemctl,$service);
 2945:     $service = 'apache2.service';
 2946:     if ($distro =~ /^ubuntu(\w+)/) {
 2947:         if ($1 >= 16) {
 2948:             $use_systemctl = 1;
 2949:         }
 2950:     } elsif ($distro =~ /^debian(\w+)/) {
 2951:         if ($1 >= 9) {
 2952:             $use_systemctl = 1;
 2953:         }
 2954:     } elsif ($distro =~ /^fedora(\d+)/) {
 2955:         $service = 'httpd.service';
 2956:         if ($1 >= 16) {
 2957:             $use_systemctl = 1;
 2958:         }
 2959:     } elsif ($distro =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
 2960:         $service = 'httpd.service';
 2961:         if ($1 >= 7) {
 2962:             $use_systemctl = 1;
 2963:         }
 2964:     } elsif ($distro =~ /^sles(\d+)/) {
 2965:         if ($1 >= 12) {
 2966:             $use_systemctl = 1;
 2967:         }
 2968:     } elsif ($distro =~ /^suse(\d+)/) {
 2969:         if ($1 >= 13) {
 2970:             $use_systemctl = 1;
 2971:         }
 2972:     }
 2973:     if ($use_systemctl) {
 2974:         my $needsupdate = &check_systemd_security($distro);
 2975:         if ($needsupdate) {
 2976:             if (!-d '/etc/systemd/system/'.$service.'.d') {
 2977:                 mkdir '/etc/systemd/system/'.$service.'.d', 0755;
 2978:             }
 2979:             if (-d '/etc/systemd/system/'.$service.'.d') {
 2980:                 if (-e '/etc/systemd/system/'.$service.'.d/override.conf') {
 2981:                     if (open(my $fh,'<','/etc/systemd/system/'.$service.'.d/override.conf')) {
 2982:                         my ($inservice,$addservice,$protectoff,$linenum,$change,@lines);
 2983:                         while (my $entry = <$fh>) {
 2984:                             $linenum ++;
 2985:                             chomp($entry);
 2986:                             if ($entry eq '[Service]') {
 2987:                                 if (!$protectoff) {
 2988:                                     $inservice = $linenum;
 2989:                                     push(@lines,$entry);
 2990:                                 } else {
 2991:                                     $addservice = 1;
 2992:                                     next;
 2993:                                 }
 2994:                             }
 2995:                             if ($entry =~ /^ProtectHome\s*=\s*([\w-]+)\s*$/) {
 2996:                                 my $value = $1;
 2997:                                 if ($protectoff) {
 2998:                                     next;
 2999:                                     if (lc($value) eq 'no') {
 3000:                                         $protectoff = $linenum;
 3001:                                         push(@lines,$entry);
 3002:                                     } else {
 3003:                                         if ($protectoff) {
 3004:                                             next;
 3005:                                         } else {
 3006:                                             push(@lines,'ProtectHome=no');
 3007:                                             $protectoff = $linenum;
 3008:                                             $change = $linenum;
 3009:                                         }
 3010:                                     }
 3011:                                 }
 3012:                             }
 3013:                         }
 3014:                         close($fh);
 3015:                         if ($addservice || $change || !$protectoff) {
 3016:                             if (open(my $fh,'>','/etc/systemd/system/'.$service.'.d/override.conf')) {
 3017:                                 if ($addservice) {
 3018:                                     print $fh "[Service]\n";
 3019:                                 }
 3020:                                 foreach my $entry (@lines) {
 3021:                                     print $fh "$entry\n";
 3022:                                 }
 3023:                                 close($fh);
 3024:                                 print_and_log('Updated /etc/systemd/system/'.$service.'.d/override.conf');
 3025:                                 system('systemctl daemon-reload');
 3026:                             } else {
 3027:                                 print_and_log('Could not open /etc/systemd/system/'.$service.'.d/override.conf for writing.');
 3028:                             }
 3029:                         } else {
 3030:                             print_and_log('No change needed in /etc/systemd/system/'.$service.'.d/override.conf');
 3031:                         }
 3032:                     } else {
 3033:                         print_and_log('Could not open /etc/systemd/system/'.$service.'.d/override.conf for reading.');
 3034:                     }
 3035:                 } else {
 3036:                     if (open(my $fh,'>','/etc/systemd/system/'.$service.'.d/override.conf')) {
 3037:                         print $fh '[Service]'."\n".'ProtectHome=no'."\n";
 3038:                         close($fh);
 3039:                         print_and_log('Created /etc/systemd/system/'.$service.'.d/override.conf');
 3040:                         system('systemctl daemon-reload');
 3041:                     }
 3042:                 }
 3043:             } else {
 3044:                 print_and_log('No /etc/systemd/system/'.$service.'.d directory exists and creating one failed,');
 3045:             }
 3046:         } else {
 3047:             print_and_log('No update needed to systemd security settings for Apache web server.');
 3048:         }
 3049:     } else {
 3050:         print_and_log('No update needed to systemd, as this Linux distro does not use systemctl');
 3051:     }
 3052: }
 3053: 
 3054: ###########################################################
 3055: ##
 3056: ## RHEL/CentOS/Fedora/Scientific Linux
 3057: ## Copy LON-CAPA httpd.conf to /etc/httpd/conf
 3058: ##
 3059: ###########################################################
 3060: 
 3061: sub copy_httpd_conf {
 3062:     my ($instdir,$distro,$hostname) = @_;
 3063:     my $configfile = 'httpd.conf';
 3064:     if ($distro =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
 3065:         if ($1 >= 7) {
 3066:             $configfile = 'apache2.4/httpd.conf';
 3067:         } elsif ($1 > 5) {
 3068:             $configfile = 'new/httpd.conf';
 3069:         }
 3070:     } elsif ($distro =~ /^fedora(\d+)$/) {
 3071:         if ($1 > 17) {
 3072:             $configfile = 'apache2.4/httpd.conf';
 3073:         } elsif ($1 > 10) {
 3074:             $configfile = 'new/httpd.conf';
 3075:         }
 3076:     }
 3077:     print_and_log(&mt('Copying the LON-CAPA [_1] to [_2].',"'httpd.conf'",
 3078:                   "'/etc/httpd/conf/httpd.conf'")."\n");
 3079:     copy "/etc/httpd/conf/httpd.conf","/etc/httpd/conf/httpd.conf.original";
 3080:     copy "$instdir/centos-rhes-fedora-sl/$configfile","/etc/httpd/conf/httpd.conf";
 3081:     chmod(0444,"/etc/httpd/conf/httpd.conf");
 3082:     print_and_log("\n");
 3083: }
 3084: 
 3085: ###########################################################
 3086: ##
 3087: ## RHEL/CentOS/Fedora/Scientific Linux
 3088: ## Copy LON-CAPA mpm.conf to /etc/httpd/conf.modules.d/00-mpm.conf
 3089: ##
 3090: ## The LON-CAPA mpm.conf enables the prefork MPM module in
 3091: ## Apache. This is also the default for RHEL/CentOS/Oracle
 3092: ## Linux 7 and earlier, and Fedora 26 and earlier. For more
 3093: ## recent versions of those distros, the event MPM is enabled
 3094: ## by default. After &copy_mpm_conf() is run, the prefork MPM
 3095: ## module will be enabled instead of the event MPM module.
 3096: ##
 3097: ###########################################################
 3098: 
 3099: sub copy_mpm_conf {
 3100:     my ($instdir,$distro) = @_;
 3101:     my $mpmfile = 'mpm.conf';
 3102:     if ((-e "/etc/httpd/conf.modules.d/00-mpm.conf") &&
 3103:         (-e "$instdir/centos-rhes-fedora-sl/$mpmfile")) {
 3104:         print_and_log(&mt('Copying the LON-CAPA [_1] to [_2].',"'mpm.conf'",
 3105:                       "'/etc/httpd/conf.modules.d/00-mpm.conf'")."\n");
 3106:         copy "$instdir/centos-rhes-fedora-sl/$mpmfile","/etc/httpd/conf.modules.d/00-mpm.conf";
 3107:         chmod(0644,"/etc/httpd/conf.modules.d/00-mpm.conf");
 3108:         print_and_log("\n");
 3109:     } else {
 3110:         my $logfail;
 3111:         if ($distro =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
 3112:             if ($1 > 7) {
 3113:                 $logfail = 1;
 3114:             }
 3115:         } elsif ($distro =~ /^fedora(\d+)$/) {
 3116:             if ($1 > 26) {
 3117:                 $logfail = 1;
 3118:             }
 3119:         }
 3120:         if ($logfail) {
 3121:             print_and_log(&mt('Warning: copying the LON-CAPA [_1] failed because [_2] and/or [_3] are missing.',
 3122:                               $mpmfile,"'$instdir/centos-rhes-fedora-sl/$mpmfile'",
 3123:                               "'/etc/httpd/conf.modules.d/00-mpm.conf'"));
 3124:             print_and_log("\n");
 3125:         }
 3126:     }
 3127: }
 3128: 
 3129: ###############################################
 3130: ##
 3131: ## Copy loncapassl.conf and sslrewrite.conf
 3132: ##
 3133: ###############################################
 3134: 
 3135: #
 3136: # The Apache SSL configuration used by LON-CAPA is contained in
 3137: # two files: sslrewrite.conf and loncapassl.conf.
 3138: #
 3139: # Starting with LON-CAPA 2.12, name-based virtual hosts are used
 3140: # with port 443. The default virtual host (i.e., the one listed
 3141: # first) is for the server's standard hostname, and that is the one 
 3142: # which will respond to client browser requests for https:// pages. 
 3143: #
 3144: # Accordingly, a system administrator will need to edit the config
 3145: # config file to include paths to a signed SSL certificate (public), 
 3146: # chain (public) and key (private) pem files. The certificate should
 3147: # have been signed by a recognized certificate authority ((e.g., 
 3148: # InCommon or Let's Encrypt).
 3149: #  
 3150: # The sslrewrite.conf file contains the rewrite configuration for
 3151: # the default virtual host. The rewrite rules defined are used to 
 3152: # allow internal HEAD requests to /cgi-bin/mimetex.cgi to be served
 3153: # http://, in order to support vertical alignment of mimetex images
 3154: # (one of the options for rendering Math content); (b) allow requests
 3155: # for certain URLs (external resource, and syllabus, if external URL
 3156: # used) to be served http:// to accommodate the use of iframes which 
 3157: # would otherwise result in browser blocking of mixed active content.
 3158: #
 3159: # The loncapassl.conf file contains the configuration for the  
 3160: # "internal" virtual host, which will respond to requests for https://
 3161: # pages from other LON-CAPA servers in the network to which the node
 3162: # belongs. The ServerName is internal-<hostname> where <hostname>
 3163: # is the server's hostname. There is no need to create a DNS entry 
 3164: # for internal-<hostname>, as LON-CAPA 2.12 automatically performs
 3165: # the required hostname to IP mapping.
 3166: # 
 3167: # Requests to /raw on the "internal" virtual host require a valid
 3168: # SSL client certificate, signed by the certificate authority
 3169: # for the LON-CAPA network to which the node belongs.
 3170: # 
 3171: # The configuration file to which the contents of sslrewrite.conf
 3172: # and loncapassl.conf will be written will have either been identified
 3173: # when &chkapachessl() was run, or if no files were found with
 3174: # existing rewrite blocks, then a candidate file will be chosen
 3175: # from the .conf files containing VirtualHosts definitions.
 3176: # If there is more than one suitable candidate file, the system
 3177: # administrator will be prompted to select from the available files.
 3178: #
 3179: # If there are no files containing VirtualHosts definitions, then
 3180: # <VirtualHost *:443> </VirtualHost> blocks will be appended to
 3181: # the standard Apache SSL config for the particular distro:
 3182: # ssl.conf for RHEL/CentOS/Scientific/Fedora, vhost-ssl.conf
 3183: # for SuSE/SLES, and default-ssl.conf for Ubuntu.
 3184: #
 3185: # Once a file is selected, the contents of sslrewrite.conf and
 3186: # loncapassl.conf are compared with appropriate blocks in the file
 3187: # and the user will be prompted to agree to insertion of missing lines
 3188: # and/or deletion of surplus lines.
 3189: #
 3190: 
 3191: sub copy_apache_sslconf_files {
 3192:     my ($distro,$hostname,$hostip,$instdir,$targetdir,$targetfilesref,
 3193:         $has_std,$has_int,$rewritenum,$nochgstd,$nochgint) = @_;
 3194:     my ($new_std,$new_int);
 3195:     my (@internal,@standard,%int_by_linenum,%int_by_linetext,
 3196:         %rule_by_linenum,%rule_by_linetext,%foundint);
 3197:     if (-e "$instdir/loncapassl.conf") {
 3198:         if (open(my $fh,'<',"$instdir/loncapassl.conf")) {
 3199:             my $num = 1;
 3200:             while (<$fh>) {
 3201:                 chomp();
 3202:                 if (/^ServerName/) {
 3203:                     s/(\Qinternal-{[[[[Hostname]]]]}\E)/internal-$hostname/;
 3204:                 }
 3205:                 push(@internal,$_);
 3206:                 $int_by_linenum{$num} = $_;
 3207:                 s/(^\s+|\s+$)//g;
 3208:                 push(@{$int_by_linetext{$_}},$num);
 3209:                 $num ++;
 3210:             }
 3211:             close($fh);
 3212:         }
 3213:     }
 3214:     if (-e "$instdir/sslrewrite.conf") {
 3215:         if (open(my $fh,'<',"$instdir/sslrewrite.conf")) {
 3216:             my $num = 1;
 3217:             while (<$fh>) {
 3218:                 chomp();
 3219:                 if (/\Q{[[[[HostIP]]]]}\E/) {
 3220:                     s/(\QRewriteCond %{REMOTE_ADDR} {[[[[HostIP]]]]}\E)/RewriteCond %{REMOTE_ADDR} $hostip/;
 3221:                 }
 3222:                 push(@standard,$_);
 3223:                 $rule_by_linenum{$num} = $_;
 3224:                 s/(^\s+|\s+$)//g;
 3225:                 push(@{$rule_by_linetext{$_}},$num);
 3226:                 $num ++;
 3227:             }
 3228:             close($fh);
 3229:         }
 3230:     }
 3231:     if (!$nochgstd) {
 3232:         if ($has_std eq '') {
 3233:             my $file;
 3234:             if ($has_int ne '') {
 3235:                 if (open(my $fh,'<',"$targetdir/$has_int")) {
 3236:                     my @saved = <$fh>;
 3237:                     close($fh);
 3238:                     if (open(my $fhout, '>',"$targetdir/$has_int")) {
 3239:                         print $fhout "<VirtualHost *:443>\n".
 3240:                                      "ServerName $hostname\n".
 3241:                                      join("\n",@standard)."\n".
 3242:                                      "</VirtualHost>\n\n".
 3243:                                      join('',@saved);
 3244:                         close($fhout);
 3245:                         $new_int = $has_int; 
 3246:                     }
 3247:                 }
 3248:             }
 3249:         } else {
 3250:             if ($rewritenum eq '') {
 3251:                 &append_to_vhost($targetdir,$has_std,$hostname,\%rule_by_linenum,'std');
 3252:                 $new_std = $has_std;
 3253:             } else {
 3254:                 $new_std = &modify_ssl_config($targetdir,$has_std,$hostname,$rewritenum,
 3255:                                               \%rule_by_linetext,\%rule_by_linenum,'std');
 3256:             }
 3257:         }
 3258:     }
 3259:     if (!$nochgint) {
 3260:         if ($has_int eq '') {
 3261:             if ($has_std ne '') {
 3262:                 if (open(my $fhout,'>>',"$targetdir/$has_std")) {
 3263:                     print $fhout "\n".join("\n",@internal)."\n";
 3264:                     close($fhout);
 3265:                     $new_int = $has_std;
 3266:                 }
 3267:             }
 3268:         } else {
 3269:             $new_int = &modify_ssl_config($targetdir,$has_int,$hostname,$rewritenum,\%int_by_linetext,\%int_by_linenum,'int');
 3270:         }
 3271:     }
 3272:     if (($has_std eq '') && ($has_int eq '')) {
 3273:         my ($file,$numfiles) = &get_sslconf_filename($distro,$targetdir,$targetfilesref);
 3274:         if ($numfiles == 0) { 
 3275:             if (open(my $fhout, '>>', "$targetdir/$file")) {
 3276:                 print $fhout "<VirtualHost *:443>\n".
 3277:                              "ServerName $hostname\n".
 3278:                              join("\n",@standard)."\n".
 3279:                              "</VirtualHost>\n\n".
 3280:                              join("\n",@internal)."\n";
 3281:                 close($fhout);
 3282:                 $new_std = $file;
 3283:                 $new_int = $file;
 3284:             }
 3285:         } elsif ($numfiles == 1) {
 3286:             &append_to_vhost($targetdir,$file,$hostname,\%rule_by_linenum,'std');
 3287:             if (open(my $fhout, '>>', "$targetdir/$file")) {
 3288:                 print $fhout "\n".join("\n",@internal)."\n";
 3289:                 close($fhout);
 3290:                 $new_std = $file;
 3291:                 $new_int = $file;
 3292:             }
 3293:         } elsif ($numfiles == -1) {
 3294:             print_and_log(&mt('Failed to copy contents of [_1] or [_2] to a file in [_3]',
 3295:                               "'loncapassl.conf'","'sslrewrite.conf'","'$targetdir'")."\n");
 3296:         }
 3297:     }
 3298:     if ($nochgstd) {
 3299:         print_and_log(&mt('No change required to file: [_1] in [_2], (no difference between [_3] and rewrite block.)',
 3300:                           "'$has_std'","'$targetdir'","'sslrewrite.conf'"));
 3301:     }
 3302:     if ($nochgint) {
 3303:         print_and_log(&mt('No change required to file: [_1] in [_2], (no difference between [_3] and virtualhost block.)',
 3304:                           "'$has_int'","'$targetdir'","'loncapassl.conf'"));
 3305:     }
 3306:     if ($new_int) {
 3307:         print_and_log(&mt('Successfully copied contents of [_1] to [_2].',"'loncapassl.conf'","'$targetdir/$new_int'")."\n");
 3308:         chmod(0444,"$targetdir/loncapassl.conf");
 3309:     }
 3310:     if ($new_std) {
 3311:         print_and_log(&mt('Successfully copied contents of [_1] to [_2].',"'sslrewrite.conf'","'$targetdir/$new_std'")."\n");
 3312:         chmod(0444,"$targetdir/loncapassl.conf");
 3313:     }
 3314:     return ($new_int,$new_std);
 3315: }
 3316: 
 3317: #
 3318: # append_to_vhost() is called to add rewrite rules (in a 
 3319: # <IfModule +mod_rewrite.c> </IfModule> block), provided
 3320: # in the sslrewrite.conf configuration file, to an Apache
 3321: # SSL configuration file within a VirtualHost for port 443
 3322: # (for server's public-facing hostname).
 3323: #
 3324: sub append_to_vhost {
 3325:     my ($targetdir,$filename,$hostname,$by_linenum,$type) = @_;
 3326:     return unless (ref($by_linenum) eq 'HASH');
 3327:     my ($startvhost,$endvhost);
 3328:     if (-e "$targetdir/$filename") {
 3329:         my (@lines,$currname,$virtualhost,$hasname);
 3330:         if (open(my $fh,'<',"$targetdir/$filename")) {
 3331:             my $currline = 0;
 3332:             while (<$fh>) {
 3333:                 $currline ++;
 3334:                 push(@lines,$_);
 3335:                 chomp();
 3336:                 s/(^\s+|\s+$)//g;
 3337:                 if (/^<VirtualHost\s+[^:]*\:443>/) {
 3338:                     $virtualhost = 1;
 3339:                     unless ($endvhost) {
 3340:                         $startvhost = $currline;
 3341:                     }
 3342:                 }
 3343:                 if ($virtualhost) {
 3344:                     if (/^ServerName\s+([^\s]+)\s*$/) {
 3345:                         $currname = $1;
 3346:                         unless ($endvhost) {
 3347:                             if ((($currname eq '') || ($currname eq $hostname)) && ($type eq 'std')) {
 3348:                                 $hasname = 1;
 3349:                             }
 3350:                         }
 3351:                     }
 3352:                     if (/^<\/VirtualHost>/) {
 3353:                         $virtualhost = 0;
 3354:                         unless ($endvhost) {
 3355:                             if (((($currname eq '') || ($currname eq $hostname)) && ($type eq 'std')) ||
 3356:                                 (($currname eq 'internal-'.$hostname) && ($type eq 'int'))) { 
 3357:                                 $endvhost = $currline;
 3358:                             } else {
 3359:                                 undef($startvhost);  
 3360:                             }
 3361:                         }
 3362:                     }
 3363:                 }
 3364:             }
 3365:             close($fh);
 3366:         }
 3367:         if ($endvhost) {
 3368:             if (open(my $fout,'>',"$targetdir/$filename")) {
 3369:                 for (my $i=0; $i<@lines; $i++) {
 3370:                     if ($i == $startvhost) {
 3371:                         unless (($hasname) && ($type eq 'std')) {
 3372:                             print $fout "ServerName $hostname\n";
 3373:                         }
 3374:                     }
 3375:                     if ($i == $endvhost-1) {
 3376:                         foreach my $item (sort { $a <=> $b } keys(%{$by_linenum})) {
 3377:                             print $fout $by_linenum->{$item}."\n";
 3378:                         }
 3379:                     }
 3380:                     print $fout $lines[$i];
 3381:                 }
 3382:                 close($fout);
 3383:             }
 3384:         }
 3385:     }
 3386:     return $endvhost;
 3387: }
 3388: 
 3389: #
 3390: # get_sslconf_filename() is called when the Apache SSL configuration
 3391: # option has been selected and there are no files containing
 3392: # VirtualHost definitions containing rewrite blocks,
 3393: # 
 3394: # In this case get_sslconf_filename() is used to chose from the 
 3395: # available .conf files containing VirtualHosts definitions. If
 3396: # there is ambiguity about which file to use, &apacheconf_choice()
 3397: # will be called to prompt the user to choose one of the possible
 3398: # files.
 3399: #
 3400: 
 3401: sub get_sslconf_filename {
 3402:     my ($distro,$targetdir,$targetfilesref) = @_;
 3403:     my ($configfile,$numfiles,@possfiles);
 3404:     if (ref($targetfilesref) eq 'HASH') {
 3405:         if (keys(%{$targetfilesref}) > 0) {
 3406:             foreach my $name (sort(keys(%{$targetfilesref}))) {
 3407:                 if (ref($targetfilesref->{$name}) eq 'HASH') {
 3408:                     foreach my $file (sort(keys(%{$targetfilesref->{$name}}))) {
 3409:                         next if ($file eq '');
 3410:                         next if (!-e "$targetdir/$file");
 3411:                         unless (grep(/^\Q$file\E$/,@possfiles)) {
 3412:                             push(@possfiles,$file);
 3413:                         }
 3414:                     }
 3415:                 }
 3416:             }
 3417:         }
 3418:         if (@possfiles == 0) {
 3419:             $configfile = 'ssl.conf';
 3420:             if ($distro =~ /^(suse|sles)/) {
 3421:                 $configfile = 'vhost-ssl.conf';
 3422:             } elsif ($distro =~ /^(debian|ubuntu)/) {
 3423:                 $configfile = 'default-ssl.conf';
 3424:             }
 3425:             $numfiles = 0;
 3426:             print &mt('No configuration files in [_1] contain a <VirtualHost *:443> </VirtualHost> block which can be used to house Apache rewrite rules from https to http.',$targetdir)."\n\n".
 3427:                   &mt('Accordingly, the contents of sslrewrite.conf will be included in a <VirtualHost *:443> </VirtualHost> block which will be added to a file named: [_1].',$configfile)."\n\n";
 3428:         } elsif (@possfiles == 1) {
 3429:             $configfile = $possfiles[0];
 3430:             $numfiles = 1;
 3431:             print &mt('A single configuration file in [_1] contains a <VirtualHost *:443> </VirtualHost> block.',$targetdir)."\n".
 3432:                   &mt('The contents of sslrewrite.conf will be added to this block.')."\n\n";
 3433:         } else {
 3434:             print &mt('More than one Apache config file contains a <VirtualHost *:443> </VirtualHost> block.')."\n\n".&mt('The possible files are:')."\n";
 3435:             my $counter = 1;
 3436:             my $max = scalar(@possfiles);
 3437:             foreach my $file (@possfiles) {
 3438:                 print "$counter. $file\n";
 3439:                 $counter ++;
 3440:             }
 3441:             print "\n".&mt('Enter a number between 1 and [_1] to indicate which file should be modified to include the contents of sslrewrite.conf.',$max)."\n";
 3442:             my $choice = &apacheconf_choice($max);
 3443:             if (($choice =~ /^\d+$/) && ($choice >= 1) && ($choice <= $max)) {
 3444:                 $configfile = $possfiles[$choice-1];
 3445:                 $numfiles = 1; 
 3446:             } else {
 3447:                 $numfiles = -1;
 3448:             }
 3449:         }
 3450:     }
 3451:     return ($configfile,$numfiles);
 3452: }
 3453: 
 3454: #
 3455: # &apacheconf_choice() prompts a user to choose an integer between 1 and the  
 3456: # maximum number of available of possible Apache SSL config files found
 3457: # at the distros standard location for Apache config files containing
 3458: # VirtualHost definitions.
 3459: #
 3460: # This routine is called recursively until the user enters a valid integer.
 3461: #
 3462: 
 3463: sub apacheconf_choice {
 3464:     my ($max) = @_;
 3465:     my $choice = <STDIN>;
 3466:     chomp($choice);
 3467:     $choice =~ s/(^\s+|\s+$)//g;
 3468:     my $configfile;
 3469:     if (($choice =~ /^\d+$/) && ($choice >= 1) && ($choice <= $max)) {
 3470:         $configfile = $choice;
 3471:     } 
 3472:     while ($configfile eq '') {
 3473:         print &mt('Invalid choice.  Please enter a number between 1 and [_1].',$max)."\n";
 3474:         $configfile = &apacheconf_choice($max);
 3475:     }
 3476:     print "\n";
 3477:     return $configfile;
 3478: }
 3479: 
 3480: #
 3481: # &modify_ssl_config() is called to modify the contents of an Apache SSL config
 3482: # file so that it has two <VirtualHost *:443> </VirtualHost> blocks containing
 3483: # (a) the default VirtualHost with the <IfModule mod_rewrite.c> </IfModule> block 
 3484: # provided in sslrewrites.conf, and (b) an "internal" VirtualHost with the 
 3485: # content provided in loncapassl.conf.
 3486: #
 3487: # This routine will prompted you to agree to insertion of lines present in the
 3488: # shipped conf file, but missing from the local config file, and also for
 3489: # deletion of lines present in the local config file, but not required in
 3490: # the shipped conf file.
 3491: # 
 3492:  
 3493: sub modify_ssl_config {
 3494:     my ($targetdir,$filename,$hostname,$rewritenum,$by_linetext,$by_linenum,$type) = @_;
 3495:     return unless ((ref($by_linetext) eq 'HASH') && (ref($by_linenum) eq 'HASH'));
 3496:     if (-e "$targetdir/$filename") {
 3497:         my (@lines,$virtualhost,$currname,$rewrite);
 3498:         if (open(my $fh,'<',"$targetdir/$filename")) {
 3499:             my %found;
 3500:             my %possible;
 3501:             my $currline = 0;
 3502:             my $rewritecount = 0;
 3503:             while (<$fh>) {
 3504:                 $currline ++;
 3505:                 push(@lines,$_);
 3506:                 chomp();
 3507:                 s/(^\s+|\s+$)//g;
 3508:                 if (/^\s*<VirtualHost\s+[^:]*\:443>\s*$/) {
 3509:                     $virtualhost = 1;
 3510:                 }
 3511:                 if ($virtualhost) {
 3512:                     if ((exists($by_linetext->{$_})) && (ref($by_linetext->{$_}) eq 'ARRAY') &&
 3513:                         (@{$by_linetext->{$_}} > 0)) {
 3514:                         $possible{$currline} = shift(@{$by_linetext->{$_}});
 3515:                     } 
 3516:                     if (/^\s*<\/VirtualHost>/) {
 3517:                         if ((($currname eq 'internal-'.$hostname) && ($type eq 'int')) ||
 3518:                             ((($currname eq $hostname) || ($currname eq '')) && ($type eq 'std') &&
 3519:                               ($rewritecount == $rewritenum))) {
 3520:                             %found = (%found,%possible);
 3521:                         } else {
 3522:                             foreach my $line (sort {$b <=> $a } keys(%possible)) {
 3523:                                 my $num = $possible{$line};
 3524:                                 if (ref($by_linetext->{$by_linenum->{$num}}) eq 'ARRAY') { 
 3525:                                     unshift(@{$by_linetext->{$by_linenum->{$num}}},$num);
 3526:                                 }
 3527:                             } 
 3528:                         }
 3529:                         undef(%possible);
 3530:                         $virtualhost = 0;
 3531:                         $currname = '';
 3532:                     } elsif (/^\s*ServerName\s+([^\s]+)\s*$/) {
 3533:                         $currname = $1;
 3534:                     } elsif (/^\s*<IfModule\s+mod_rewrite\.c>/) {
 3535:                         $rewrite = 1;
 3536:                     } elsif (/^\s*<\/IfModule>/) {
 3537:                         $rewritecount ++;
 3538:                         $rewrite = 0;
 3539:                     }
 3540:                 }
 3541:             }
 3542:             close($fh);
 3543:             if (open(my $fout,'>',"$targetdir/$filename")) {
 3544:                 my $currline = 0;
 3545:                 my ($lastfound,$done);
 3546:                 my $numfound = 0;
 3547:                 foreach my $line (@lines) {
 3548:                     $currline ++;
 3549:                     if ($done) {
 3550:                         print $fout $line;
 3551:                     } elsif ($lastfound) {
 3552:                         if ($found{$currline}) {
 3553:                             for (my $i=$lastfound+1; $i<$found{$currline}; $i++) {
 3554:                                 print &mt('The following line is missing from the current <VirtualHost *:443> </VirtualHost> block:')."\n".
 3555:                                       $by_linenum->{$i}."\n".
 3556:                                       &mt('Add this line? ~[Y/n~]');
 3557:                                 if (&get_user_selection(1)) {
 3558:                                     print $fout $by_linenum->{$i}."\n";
 3559:                                 }
 3560:                             }
 3561:                             $numfound ++;
 3562:                             $lastfound = $found{$currline};
 3563:                             print $fout $line;
 3564:                             if ($numfound == scalar(keys(%found))) {
 3565:                                 $done = 1;
 3566:                                 for (my $i=$found{$currline}+1; $i<=scalar(keys(%{$by_linenum})); $i++) {
 3567:                                     print &mt('The following line is missing from the current <VirtualHost *:443> </VirtualHost> block:')."\n".
 3568:                                           $by_linenum->{$i}."\n".
 3569:                                           &mt('Add this line? ~[Y/n~]');
 3570:                                     if (&get_user_selection(1)) {
 3571:                                         print $fout $by_linenum->{$i}."\n";
 3572:                                     }
 3573:                                 }
 3574:                             }
 3575:                         } else {
 3576:                             print &mt('The following line found within a <VirtualHost *:443> </VirtualHost> block does not match that expected by LON-CAPA:')."\n".
 3577:                                   $line.
 3578:                                   &mt('Delete this line? ~[Y/n~]');
 3579:                             if (!&get_user_selection(1)) {
 3580:                                 print $fout $line;
 3581:                             }
 3582:                         }
 3583:                     } elsif ($found{$currline}) {
 3584:                         $numfound ++;
 3585:                         $lastfound = $found{$currline};
 3586:                         for (my $i=1; $i<$found{$currline}; $i++) {
 3587:                             print &mt('The following line is missing from the current <VirtualHost *:443> </VirtualHost> block:')."\n".
 3588:                                   $by_linenum->{$i}."\n".
 3589:                                   &mt('Add this line? ~[Y/n~]');
 3590:                             if (&get_user_selection(1)) {
 3591:                                 print $fout $by_linenum->{$i}."\n";
 3592:                             }
 3593:                         }
 3594:                         print $fout $line;
 3595:                     } else {
 3596:                         print $fout $line;
 3597:                     }
 3598:                 }
 3599:                 close($fout);
 3600:             }
 3601:         }
 3602:     }
 3603:     return $filename;
 3604: }
 3605: 
 3606: #########################################################
 3607: ##
 3608: ## Ubuntu/Debian -- copy our loncapa configuration file to
 3609: ## sites-available and set the symlink from sites-enabled.
 3610: ##
 3611: #########################################################
 3612: 
 3613: sub copy_apache2_debconf {
 3614:     my ($instdir,$distro,$hostname) = @_;
 3615:     my $apache2_mods_enabled_dir = '/etc/apache2/mods-enabled';
 3616:     my $apache2_mods_available_dir = '/etc/apache2/mods-available';
 3617:     foreach my $module ('headers.load','expires.load') {
 3618:         unless (-l "$apache2_mods_enabled_dir/$module") {
 3619:             symlink("$apache2_mods_available_dir/$module","$apache2_mods_enabled_dir/$module");
 3620:             print_and_log(&mt('Enabling "[_1]" Apache module.',$module)."\n");
 3621:         }
 3622:     }
 3623:     my $apache2_sites_enabled_dir = '/etc/apache2/sites-enabled';
 3624:     my $apache2_sites_available_dir = '/etc/apache2/sites-available';
 3625:     my $defaultconfig = "$apache2_sites_enabled_dir/000-default";
 3626:     my $defaultsite = "$apache2_sites_enabled_dir/loncapa.conf";
 3627:     my ($distname,$version);
 3628:     if ($distro =~ /^(debian|ubuntu)(\d+)$/) {
 3629:         $distname = $1;
 3630:         $version = $2;
 3631:     }
 3632:     if ((($distname eq 'ubuntu') && ($version > 12)) ||
 3633:         (($distname eq 'debian') && ($version >= 10))) {
 3634:         $defaultconfig = "$apache2_sites_enabled_dir/000-default.conf";
 3635:     }
 3636:     my ($skipconf,$skipsite,$skipstatus);
 3637:     if ((($distname eq 'ubuntu') && ($version > 12)) ||
 3638:         (($distname eq 'debian') && ($version >= 10))) {
 3639:         my $apache2_conf_enabled_dir = '/etc/apache2/conf-enabled';
 3640:         my $apache2_conf_available_dir = '/etc/apache2/conf-available';
 3641:         my $defaultconf = $apache2_conf_enabled_dir.'/loncapa.conf';
 3642:         if ((-e "$apache2_conf_available_dir/loncapa") && (-e "$instdir/debian-ubuntu/ubuntu14/loncapa_conf")) {
 3643:             if (open(PIPE, "diff --brief $apache2_conf_available_dir/loncapa $instdir/debian-ubuntu/ubuntu14/loncapa_conf |")) {
 3644:                 my $diffres = <PIPE>;
 3645:                 close(PIPE);
 3646:                 chomp($diffres);
 3647:                 if ($diffres) {
 3648:                     copy("$apache2_conf_available_dir/loncapa","$apache2_conf_available_dir/loncapa.conf.original");
 3649:                 } else {
 3650:                     copy("$apache2_conf_available_dir/loncapa","$apache2_conf_available_dir/loncapa.conf");
 3651:                     chdir($apache2_conf_enabled_dir);
 3652:                     symlink('../conf-available/loncapa.conf','loncapa.conf');
 3653:                     chdir($instdir);
 3654:                 }
 3655:                 if (-l $defaultconf) {
 3656:                     my $linkfname = readlink($defaultconf);
 3657:                     if ($linkfname ne '') {
 3658:                         $linkfname = Cwd::abs_path(File::Spec->rel2abs($linkfname,$apache2_conf_enabled_dir));
 3659:                     }
 3660:                     if ($linkfname eq "$apache2_conf_available_dir/loncapa") {
 3661:                         unlink($defaultconf);
 3662:                     }
 3663:                 }
 3664:                 unlink("$apache2_conf_available_dir/loncapa");
 3665:             }
 3666:         }
 3667:         if ((-e "$apache2_conf_available_dir/loncapa.conf") && (-e "$instdir/debian-ubuntu/ubuntu14/loncapa_conf")) {
 3668:             if (open(PIPE, "diff --brief $apache2_conf_available_dir/loncapa.conf $instdir/debian-ubuntu/ubuntu14/loncapa_conf |")) {
 3669:                 my $diffres = <PIPE>;
 3670:                 close(PIPE);
 3671:                 chomp($diffres);
 3672:                 if ($diffres) {
 3673:                     copy("$apache2_conf_available_dir/loncapa.conf","$apache2_conf_available_dir/loncapa.conf.original");
 3674:                 }
 3675:                 if (-l $defaultconf) {
 3676:                     my $linkfname = readlink($defaultconf);
 3677:                     if ($linkfname ne '') {
 3678:                         $linkfname = Cwd::abs_path(File::Spec->rel2abs($linkfname,$apache2_conf_enabled_dir));
 3679:                     }
 3680:                     if ($linkfname eq "$apache2_conf_available_dir/loncapa.conf") {
 3681:                         unless ($diffres) {
 3682:                             $skipconf = 1;
 3683:                         }
 3684:                     }
 3685:                 }
 3686:             }
 3687:         }
 3688:         unless ($skipconf) {
 3689:             print_and_log(&mt('Copying loncapa [_1] config file to [_2] and pointing [_3] to it from conf-enabled.',"'apache2'","'/etc/apache2/conf-available'","'loncapa.conf symlink'")."\n");
 3690:             copy("$instdir/debian-ubuntu/ubuntu14/loncapa_conf","$apache2_conf_available_dir/loncapa.conf");
 3691:             chmod(0444,"$apache2_conf_available_dir/loncapa.conf");
 3692:             if (-l $defaultconf) {
 3693:                 unlink($defaultconf);
 3694:             }
 3695:             chdir($apache2_conf_enabled_dir);
 3696:             symlink('../conf-available/loncapa.conf','loncapa.conf');
 3697:             chdir($instdir);
 3698:         }
 3699:         my $stdsite = "$instdir/debian-ubuntu/ubuntu14/loncapa_site";
 3700:         if ((-e $stdsite) && (-e "$apache2_sites_available_dir/loncapa")) {
 3701:             if (open(PIPE, "diff --brief $stdsite $apache2_sites_available_dir/loncapa |")) {
 3702:                 my $diffres = <PIPE>;
 3703:                 close(PIPE);
 3704:                 chomp($diffres);
 3705:                 if ($diffres) {
 3706:                     copy("$apache2_sites_available_dir/loncapa","$apache2_sites_available_dir/loncapa.conf.original");
 3707:                 } else {
 3708:                     copy("$apache2_sites_available_dir/loncapa","$apache2_sites_available_dir/loncapa.conf");
 3709:                 }
 3710:                 if (-l $defaultconfig) {
 3711:                     my $linkfname = readlink($defaultconfig);
 3712:                     if ($linkfname ne '') {
 3713:                         $linkfname = Cwd::abs_path(File::Spec->rel2abs($linkfname,$apache2_sites_enabled_dir));
 3714:                     }
 3715:                     if ($linkfname eq "$apache2_sites_available_dir/loncapa") {
 3716:                         unlink($defaultconfig);
 3717:                     }
 3718:                 }
 3719:                 unlink("$apache2_sites_available_dir/loncapa");
 3720:             }
 3721:         }
 3722:         if ((-e $stdsite) && (-e "$apache2_sites_available_dir/loncapa.conf")) {
 3723:             if (open(PIPE, "diff --brief $stdsite $apache2_sites_available_dir/loncapa.conf |")) {
 3724:                 my $diffres = <PIPE>;
 3725:                 close(PIPE);
 3726:                 chomp($diffres);
 3727:                 if ($diffres) {
 3728:                     copy("$apache2_sites_available_dir/loncapa.conf","$apache2_sites_available_dir/loncapa.conf.original");
 3729:                 }
 3730:                 if (-l $defaultsite) {
 3731:                     my $linkfname = readlink($defaultsite);
 3732:                     if ($linkfname ne '') {
 3733:                         $linkfname = Cwd::abs_path(File::Spec->rel2abs($linkfname,$apache2_sites_enabled_dir));
 3734:                     }
 3735:                     if ($linkfname eq "$apache2_sites_available_dir/loncapa.conf") {
 3736:                         unless ($diffres) {
 3737:                             $skipsite = 1;
 3738:                         }
 3739:                     }
 3740:                 }
 3741:             }
 3742:         }
 3743:         unless ($skipsite) {
 3744:             print_and_log(&mt('Copying loncapa [_1] site file to [_2] and pointing [_3] to it from sites-enabled.',"'apache2'","'/etc/apache2/sites-available'","'loncapa.conf symlink'")."\n");
 3745:             copy("$instdir/debian-ubuntu/ubuntu14/loncapa_site","$apache2_sites_available_dir/loncapa.conf");
 3746:             chmod(0444,"$apache2_sites_available_dir/loncapa.conf");
 3747:             chdir($apache2_sites_enabled_dir);
 3748:             symlink('../sites-available/loncapa.conf','loncapa.conf');
 3749:             chdir($instdir);
 3750:         }
 3751:         if (-l $defaultconfig) {
 3752:             my $linkfname = readlink($defaultconfig);
 3753:             if ($linkfname ne '') {
 3754:                 $linkfname = Cwd::abs_path(File::Spec->rel2abs($linkfname,$apache2_sites_enabled_dir));
 3755:             }
 3756:             if ($linkfname eq "$apache2_sites_available_dir/000-default.conf") {
 3757:                 unlink($defaultconfig);
 3758:             }
 3759:         }
 3760:     } else {
 3761:         if ((-e "$instdir/debian-ubuntu/loncapa") && (-e "$apache2_sites_available_dir/loncapa")) {
 3762:             if (open(PIPE, "diff --brief $instdir/debian-ubuntu/loncapa $apache2_sites_available_dir/loncapa |")) {
 3763:                 my $diffres = <PIPE>;
 3764:                 close(PIPE);
 3765:                 chomp($diffres);
 3766:                 if ($diffres) {
 3767:                     copy("$apache2_sites_available_dir/loncapa","$apache2_sites_available_dir/loncapa.original");
 3768:                 }
 3769:                 if (-l $defaultconfig) {
 3770:                     my $linkfname = readlink($defaultconfig);
 3771:                     if ($linkfname eq "$apache2_sites_available_dir/loncapa") {
 3772:                         unless ($diffres) {
 3773:                             $skipsite = 1;
 3774:                         }
 3775:                     }
 3776:                 }
 3777:             }
 3778:         }
 3779:         unless ($skipsite) {
 3780:             if (-l $defaultconfig) {
 3781:                 unlink($defaultconfig);
 3782:             }
 3783:             print_and_log(&mt('Copying loncapa [_1] config file to [_2] and pointing [_3] to it from sites-enabled.',"'apache2'","'/etc/apache2/sites-available'","'000-default symlink'")."\n");
 3784:             if (-e "$instdir/debian-ubuntu/loncapa") {
 3785:                 copy("$instdir/debian-ubuntu/loncapa","$apache2_sites_available_dir/loncapa");
 3786:                 chmod(0444,"$apache2_sites_available_dir/loncapa");
 3787:                 symlink("$apache2_sites_available_dir/loncapa","$apache2_sites_enabled_dir/000-default");
 3788:             }
 3789:         }
 3790:     }
 3791:     if (($distname eq 'ubuntu') || ($distname eq 'debian')) {
 3792:         my $sitestatus = "$apache2_mods_available_dir/status.conf";
 3793:         my $stdstatus = "$instdir/debian-ubuntu/status.conf";
 3794:         if ((-e $sitestatus) && (-e $stdstatus)) {
 3795:             if (open(PIPE, "diff --brief $stdstatus $sitestatus |")) {
 3796:                 my $diffres = <PIPE>;
 3797:                 close(PIPE);
 3798:                 chomp($diffres);
 3799:                 if ($diffres) {
 3800:                     copy("$apache2_mods_available_dir/status.conf","$apache2_mods_available_dir/status.conf.original");
 3801:                 } else {
 3802:                     $skipstatus = 1;
 3803:                 }
 3804:             }
 3805:         }
 3806:         unless ($skipstatus) {
 3807:             if (-e $stdstatus) {
 3808:                 print_and_log(&mt('Copying loncapa [_1] file to [_2],',"'status.conf'","'/etc/apache2/mods-available/status.conf'")."\n");
 3809:                 copy($stdstatus,$sitestatus);
 3810:                 chmod(0644,$sitestatus);
 3811:             }
 3812:         }
 3813:     }
 3814:     print_and_log("\n");
 3815: }
 3816: 
 3817: ###########################################################
 3818: ##
 3819: ## openSuSE/SLES Copy apache2 config files:
 3820: ##   default-server.conf, uid.conf, /etc/sysconfig/apache2 
 3821: ##   and create symlink from /srv/www/conf to /etc/apache2 
 3822: ##
 3823: ###########################################################
 3824: 
 3825: sub copy_apache2_suseconf {
 3826:     my ($instdir,$hostname,$distro) = @_;
 3827:     my ($name,$version) = ($distro =~ /^(suse|sles)([\d\.]+)$/);
 3828:     my $conf_file = "$instdir/sles-suse/default-server.conf";
 3829:     if (($name eq 'sles') && ($version >= 12)) {
 3830:         $conf_file = "$instdir/sles-suse/apache2.4/default-server.conf";
 3831:     }
 3832:     print_and_log(&mt('Copying the LON-CAPA [_1] to [_2].',
 3833:                   "'default-server.conf'",
 3834:                   "'/etc/apache2/default-server.conf'")."\n");
 3835:     if (!-e "/etc/apache2/default-server.conf.original") {
 3836:         copy "/etc/apache2/default-server.conf","/etc/apache2/default-server.conf.original";
 3837:     }
 3838:     copy $conf_file,"/etc/apache2/default-server.conf";
 3839:     chmod(0444,"/etc/apache2/default-server.conf");
 3840:     # Make symlink for conf directory (included in loncapa_apache.conf)
 3841:     my $can_symlink = (eval { symlink('/etc/apache2','/srv/www/conf'); }, $@ eq '');
 3842:     if ($can_symlink) {
 3843:         &print_and_log(&mt('Symlink created for [_1] to [_2].',
 3844:                        "'/srv/www/conf'","'/etc/apache2'")."\n");
 3845:     } else {
 3846:         &print_and_log(&mt('Symlink creation failed for [_1] to [_2]. You will need to perform this action from the command line.',"'/srv/www/conf'","'/etc/apache2'")."\n");
 3847:     }
 3848:     &copy_apache2_conf_files($instdir);
 3849:     &copy_sysconfig_apache2_file($instdir,$name,$version); 
 3850:     print_and_log("\n");
 3851: }
 3852: 
 3853: ###############################################
 3854: ##
 3855: ## Modify uid.conf
 3856: ##
 3857: ###############################################
 3858: sub copy_apache2_conf_files {
 3859:     my ($instdir) = @_;
 3860:     print_and_log(&mt('Copying the LON-CAPA [_1] to [_2].',
 3861:                   "'uid.conf'","'/etc/apache2/uid.conf'")."\n");
 3862:     if (!-e "/etc/apache2/uid.conf.original") {
 3863:         copy "/etc/apache2/uid.conf","/etc/apache2/uid.conf.original";
 3864:     }
 3865:     copy "$instdir/sles-suse/uid.conf","/etc/apache2/uid.conf";
 3866:     chmod(0444,"/etc/apache2/uid.conf");
 3867: }
 3868: 
 3869: ###############################################
 3870: ##
 3871: ## Modify /etc/sysconfig/apache2  
 3872: ##
 3873: ###############################################
 3874: sub copy_sysconfig_apache2_file {
 3875:     my ($instdir,$name,$version) = @_;
 3876:     print_and_log(&mt('Copying the LON-CAPA [_1] to [_2].',"'sysconfig/apache2'","'/etc/sysconfig/apache2'")."\n");
 3877:     if (!-e "/etc/sysconfig/apache2.original") {
 3878:         copy "/etc/sysconfig/apache2","/etc/sysconfig/apache2.original";
 3879:     }
 3880:     my $sysconf_file = "$instdir/sles-suse/sysconfig_apache2";
 3881:     if (($name eq 'sles') && ($version >= 12)) {
 3882:        $sysconf_file = "$instdir/sles-suse/apache2.4/sysconfig_apache2";
 3883:     }
 3884:     copy $sysconf_file,"/etc/sysconfig/apache2";
 3885:     chmod(0444,"/etc/sysconfig/apache2");
 3886: }
 3887: 
 3888: ###############################################
 3889: ##
 3890: ## Add/Modify /etc/insserv/overrides
 3891: ##
 3892: ###############################################
 3893: 
 3894: sub update_SuSEfirewall2_setup {
 3895:     my ($instdir) = @_;
 3896:     print_and_log(&mt('Copying the LON-CAPA [_1] to [_2].',"'SuSEfirewall2_setup'","'/etc/insserv/overrides/SuSEfirewall2_setup'")."\n");
 3897:     if (!-e "/etc/insserv/overrides/SuSEfirewall2_setup") {
 3898:         if (!-d "/etc/insserv") {
 3899:             mkdir("/etc/insserv",0755); 
 3900:         }
 3901:         if (!-d "/etc/insserv/overrides") {
 3902:             mkdir("/etc/insserv/overrides",0755);
 3903:         }
 3904:     } elsif (!-e  "/etc/insserv/overrides/SuSEfirewall2_setup.original") {
 3905:         copy "/etc/insserv/overrides/SuSEfirewall2_setup","/etc/insserv/overrides/SuSEfirewall2_setup.original"
 3906:     }
 3907:     copy "$instdir/sles-suse/SuSEfirewall2_setup","/etc/insserv/overrides/SuSEfirewall2_setup";
 3908:     chmod(0444,"/etc/insserv/overrides/SuSEfirewall2_setup");
 3909: }
 3910: 
 3911: sub get_iptables_rules {
 3912:     my ($distro,$instdir,$apachefw) = @_;
 3913:     my (@fwchains,@ports);
 3914:     if (&firewall_is_active()) {
 3915:         my $iptables = &get_pathto_iptables();
 3916:         if ($iptables ne '') {
 3917:             @fwchains = &get_fw_chains($iptables,$distro);
 3918:         }
 3919:     }
 3920:     if (ref($apachefw) eq 'HASH') {
 3921:         foreach my $service ('http','https') {
 3922:             unless ($apachefw->{$service}) {
 3923:                 push (@ports,$service); 
 3924:             }
 3925:         }
 3926:     } else {
 3927:         @ports = ('http','https');
 3928:     }
 3929:     if (@ports == 0) {
 3930:         return;
 3931:     }
 3932:     my $ask_to_enable;
 3933:     if (-e "/etc/iptables.loncapa.rules") {
 3934:         if (open(PIPE, "diff --brief $instdir/debian-ubuntu/iptables.loncapa.rules /etc/iptables.loncapa.rules |")) {
 3935:             my $diffres = <PIPE>;
 3936:             close(PIPE);
 3937:             chomp($diffres);
 3938:             if ($diffres) {
 3939:                 print &mt('Warning: [_1] exists but differs from LON-CAPA supplied file.','/etc/iptables.loncapa.rules')."\n";
 3940:             }
 3941:         } else {
 3942:             print &mt('Error: unable to open [_1] to compare contents with LON-CAPA supplied file.','/etc/iptables.loncapa.rules')."\n";
 3943:         }
 3944:     } else {
 3945:         if (-e "$instdir/debian-ubuntu/iptables.loncapa.rules") {
 3946:             copy "$instdir/debian-ubuntu/iptables.loncapa.rules","/etc/iptables.loncapa.rules";
 3947:             chmod(0600,"/etc/iptables.loncapa.rules");
 3948:         }
 3949:     }
 3950:     if (-e "/etc/iptables.loncapa.rules") {
 3951:         if (-e "/etc/network/if-pre-up.d/iptables") {
 3952:             if (open(PIPE, "diff --brief $instdir/debian-ubuntu/iptables /etc/network/if-pre-up/iptables |")) {
 3953:                 my $diffres = <PIPE>;
 3954:                 close(PIPE);
 3955:                 chomp($diffres);
 3956:                 if ($diffres) {
 3957:                     print &mt('Warning: [_1] exists but differs from LON-CAPA supplied file.','/etc/network/if-pre-up.d/iptables')."\n";
 3958:                 }
 3959:             } else {
 3960:                 print &mt('Error: unable to open [_1] to compare contents with LON-CAPA supplied file.','/etc/network/if-pre-up.d/iptables')."\n";
 3961:             }
 3962:         } else {
 3963:             copy "$instdir/debian-ubuntu/iptables","/etc/network/if-pre-up.d/iptables";
 3964:             chmod(0755,"/etc/network/if-pre-up.d/iptables");
 3965:             print_and_log(&mt('Installed script "[_1]" to add iptables rules to block all ports except 22, 80, and 443 when network is enabled during boot.','/etc/network/if-pre-up.d/iptables'));
 3966:             $ask_to_enable = 1;
 3967:         }
 3968:     }
 3969:     return $ask_to_enable;
 3970: }
 3971: 
 3972: sub download_loncapa {
 3973:     my ($instdir,$lctarball) = @_;
 3974:     my ($have_tarball,$updateshown);
 3975:     if (! -e "$instdir/$lctarball") {
 3976: 	print_and_log(&mt('Retrieving LON-CAPA source files from: [_1]',
 3977: 		      'http://install.loncapa.org')."\n");
 3978: 	system("wget http://install.loncapa.org/versions/$lctarball ".
 3979: 	       "2>/dev/null 1>/dev/null");
 3980: 	if (! -e "./$lctarball") {
 3981: 	    print &mt('Unable to retrieve LON-CAPA source files from: [_1].', 
 3982: 		     "http://install.loncapa.org/versions/$lctarball")."\n";
 3983: 	} else {
 3984:             $have_tarball = 1;
 3985:         }
 3986: 	print_and_log("\n");
 3987:     } else {
 3988:         $have_tarball = 1;
 3989: 	print_and_log("
 3990: ------------------------------------------------------------------------
 3991: 
 3992: ".&mt('You seem to have a version of [_1] in [_2]',$lctarball,$instdir)."\n".
 3993: &mt('This copy will be used and a new version will NOT be downloaded.')."\n".
 3994: &mt('If you wish, you may download a new version by executing:')."
 3995: 
 3996: wget http://install.loncapa.org/versions/$lctarball
 3997: 
 3998: ------------------------------------------------------------------------
 3999: ");
 4000:     }
 4001: 
 4002:     ##
 4003:     ## untar loncapa-X.Y.Z.tar.gz
 4004:     ##
 4005:     if ($have_tarball) {
 4006:         my $homedir = '/root';
 4007:         my ($targetdir,$chdircmd,$updatecmd);
 4008:         if (($distro =~ /^ubuntu/) && ($instdir ne $homedir)) {
 4009:             ($homedir) = ($instdir =~ m{^(.*)/[^/]+$});
 4010:             $updatecmd = 'sudo ./UPDATE';
 4011:         } else {
 4012:             $updatecmd = './UPDATE';
 4013:         }
 4014:         print_and_log(&mt('Extracting LON-CAPA source files')."\n");
 4015:         if (-e $homedir) {
 4016:             writelog(`tar zxf $instdir/$lctarball --directory $homedir`);
 4017:             $targetdir = $homedir;
 4018:         } else {
 4019:             writelog(`tar zxf $instdir/$lctarball`);
 4020:             $targetdir = $instdir;
 4021:         }
 4022:         if ($lctarball =~ /^loncapa\-(\d+\.\d+\.\d+(?:|[^.]+))\.tar\.gz$/) {
 4023:             $chdircmd = "cd $targetdir/loncapa-".$1;
 4024:         } else {
 4025:             $chdircmd = "cd $targetdir/loncapa-X.Y.Z  (X.Y.Z should correspond to a version number like '2.11.3')";
 4026:         }
 4027:         print_and_log("\n");
 4028:         print &mt('LON-CAPA source files extracted.')."\n".
 4029:               &mt('It remains for you to execute the following commands:').
 4030:               "\n$chdircmd\n$updatecmd\n".
 4031:               &mt('If you have any trouble, please see [_1] and [_2]',
 4032:                   'http://install.loncapa.org/','http://help.loncapa.org/')."\n";
 4033:         $updateshown = 1;
 4034:     }
 4035:     return ($have_tarball,$updateshown);
 4036: }
 4037: 
 4038: close LOG;

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>