Diff for /loncom/lond between versions 1.134 and 1.147

version 1.134, 2003/08/12 03:28:31 version 1.147, 2003/09/23 11:23:31
Line 50 Line 50
 #      population).  Since the time averaged connection rate is close to zero  #      population).  Since the time averaged connection rate is close to zero
 #      because lonc's purpose is to maintain near continuous connnections,  #      because lonc's purpose is to maintain near continuous connnections,
 #      preforking is not really needed.  #      preforking is not really needed.
 ###  # 08/xx/2003 Ron Fox:  Add management requests.  Management requests
   #      will be validated via a call to ValidateManager. At present, this
   #      is done by simple host verification.  In the future we can modify
   #      this function to do a certificate check.
   #      Management functions supported include:
   #       - pushing /home/httpd/lonTabs/hosts.tab
   #       - pushing /home/httpd/lonTabs/domain.tab
   # 09/08/2003 Ron Fox:  Told lond to take care of change logging so we
   #      don't have to remember it:
   # $Log$
   # Revision 1.147  2003/09/23 11:23:31  foxr
   # Comlplete implementation of reinit functionality.  Must still implement
   # the actual initialization functionality, but the process can now
   # receive the request and either invoke the appropriate internal function or
   # signal the correct lonc.
   #
   # Revision 1.146  2003/09/16 10:28:14  foxr
   # ReinitProcess - decode the process selector and produce the associated pid
   # filename.  Note: While it is possible to test that valid process selectors are
   # handled properly I am not able to test that invalid process selectors produce
   # the appropriate error as lonManage also blocks the use of invalid process selectors.
   #
   # Revision 1.145  2003/09/16 10:13:20  foxr
   # Added ReinitProcess function to oversee the parsing and processing of the
   # reinit:<process> client request.
   #
   # Revision 1.144  2003/09/16 09:47:01  foxr
   # Added skeletal support for SIGUSR2 (update hosts.tab)
   #
   # Revision 1.143  2003/09/15 10:03:52  foxr
   # Completed and tested code for pushfile.
   #
   # Revision 1.142  2003/09/09 20:47:46  www
   # Permanently store chatroom entries in chatroom.log
   #
   # Revision 1.141  2003/09/08 10:32:07  foxr
   # Added PushFile sub This sub oversees the push of a new configuration table file
   # Currently supported files are:
   # - hosts.tab   (transaction pushfile:hosts:contents)
   # - domain.tab  (transaction pushfile:domain:contents)
   #
   
   
 use strict;  use strict;
 use lib '/home/httpd/lib/perl/';  use lib '/home/httpd/lib/perl/';
Line 68  use Authen::Krb4; Line 109  use Authen::Krb4;
 use Authen::Krb5;  use Authen::Krb5;
 use lib '/home/httpd/lib/perl/';  use lib '/home/httpd/lib/perl/';
 use localauth;  use localauth;
   use File::Copy;
   
 my $DEBUG = 0;       # Non zero to enable debug log entries.  my $DEBUG = 0;       # Non zero to enable debug log entries.
   
Line 80  my $currenthostid; Line 122  my $currenthostid;
 my $currentdomainid;  my $currentdomainid;
   
 my $client;  my $client;
   my $clientip;
   
 my $server;  my $server;
 my $thisserver;  my $thisserver;
   
 my %hostid;  my %hostid;
 my %hostdom;  my %hostdom;
 my %hostip;  my %hostip;
   my %perlvar; # Will have the apache conf defined perl vars.
   
 #  #
 #  The array below are password error strings."  #  The array below are password error strings."
Line 126  my @adderrors    = ("ok", Line 171  my @adderrors    = ("ok",
   
   
 #  #
   #   GetCertificate: Given a transaction that requires a certificate,
   #   this function will extract the certificate from the transaction
   #   request.  Note that at this point, the only concept of a certificate
   #   is the hostname to which we are connected.
   #
   #   Parameter:
   #      request   - The request sent by our client (this parameterization may
   #                  need to change when we really use a certificate granting
   #                  authority.
   #
   sub GetCertificate {
       my $request = shift;
   
       return $clientip;
   }
   
   
   #
   #  ValidManager: Determines if a given certificate represents a valid manager.
   #                in this primitive implementation, the 'certificate' is
   #                just the connecting loncapa client name.  This is checked
   #                against a valid client list in the configuration.
   #
   #                  
   sub ValidManager {
       my $certificate = shift; 
   
       my $hostentry   = $hostid{$certificate};
       if ($hostentry ne undef) {
    &logthis('<font color="yellow">Authenticating manager'.
    " $hostentry</font>");
    return 1;
       } else {
    &logthis('<font color="red"> Failed manager authentication '.
    "$certificate </font>");
       }
   }
   #
   #  CopyFile:  Called as part of the process of installing a 
   #             new configuration file.  This function copies an existing
   #             file to a backup file.
   # Parameters:
   #     oldfile  - Name of the file to backup.
   #     newfile  - Name of the backup file.
   # Return:
   #     0   - Failure (errno has failure reason).
   #     1   - Success.
   #
   sub CopyFile {
       my $oldfile = shift;
       my $newfile = shift;
   
       #  The file must exist:
   
       if(-e $oldfile) {
   
    # Read the old file.
   
    my $oldfh = IO::File->new("< $oldfile");
    if(!$oldfh) {
       return 0;
    }
    my @contents = <$oldfh>;  # Suck in the entire file.
   
    # write the backup file:
   
    my $newfh = IO::File->new("> $newfile");
    if(!(defined $newfh)){
       return 0;
    }
    my $lines = scalar @contents;
    for (my $i =0; $i < $lines; $i++) {
       print $newfh ($contents[$i]);
    }
   
    $oldfh->close;
    $newfh->close;
   
    chmod(0660, $newfile);
   
    return 1;
       
       } else {
    return 0;
       }
   }
   
   #
   #   InstallFile: Called to install an administrative file:
   #       - The file is created with <name>.tmp
   #       - The <name>.tmp file is then mv'd to <name>
   #   This lugubrious procedure is done to ensure that we are never without
   #   a valid, even if dated, version of the file regardless of who crashes
   #   and when the crash occurs.
   #
   #  Parameters:
   #       Name of the file
   #       File Contents.
   #  Return:
   #      nonzero - success.
   #      0       - failure and $! has an errno.
   #
   sub InstallFile {
       my $Filename = shift;
       my $Contents = shift;
       my $TempFile = $Filename.".tmp";
   
       #  Open the file for write:
   
       my $fh = IO::File->new("> $TempFile"); # Write to temp.
       if(!(defined $fh)) {
    &logthis('<font color="red"> Unable to create '.$TempFile."</font>");
    return 0;
       }
       #  write the contents of the file:
   
       print $fh ($Contents); 
       $fh->close; # In case we ever have a filesystem w. locking
   
       chmod(0660, $TempFile);
   
       # Now we can move install the file in position.
       
       move($TempFile, $Filename);
   
       return 1;
   }
   
   #
   #   PushFile:  Called to do an administrative push of a file.
   #              - Ensure the file being pushed is one we support.
   #              - Backup the old file to <filename.saved>
   #              - Separate the contents of the new file out from the
   #                rest of the request.
   #              - Write the new file.
   #  Parameter:
   #     Request - The entire user request.  This consists of a : separated
   #               string pushfile:tablename:contents.
   #     NOTE:  The contents may have :'s in it as well making things a bit
   #            more interesting... but not much.
   #  Returns:
   #     String to send to client ("ok" or "refused" if bad file).
   #
   sub PushFile {
       my $request = shift;    
       my ($command, $filename, $contents) = split(":", $request, 3);
       
       #  At this point in time, pushes for only the following tables are
       #  supported:
       #   hosts.tab  ($filename eq host).
       #   domain.tab ($filename eq domain).
       # Construct the destination filename or reject the request.
       #
       # lonManage is supposed to ensure this, however this session could be
       # part of some elaborate spoof that managed somehow to authenticate.
       #
   
       my $tablefile = $perlvar{'lonTabDir'}.'/'; # need to precede with dir.
       if ($filename eq "host") {
    $tablefile .= "hosts.tab";
       } elsif ($filename eq "domain") {
    $tablefile .= "domain.tab";
       } else {
    return "refused";
       }
       #
       # >copy< the old table to the backup table
       #        don't rename in case system crashes/reboots etc. in the time
       #        window between a rename and write.
       #
       my $backupfile = $tablefile;
       $backupfile    =~ s/\.tab$/.old/;
       if(!CopyFile($tablefile, $backupfile)) {
    &logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
    return "error:$!";
       }
       &logthis('<font color="green"> Pushfile: backed up '
       .$tablefile." to $backupfile</font>");
       
       #  Install the new file:
   
       if(!InstallFile($tablefile, $contents)) {
    &logthis('<font color="red"> Pushfile: unable to install '
    .$tablefile." $! </font>");
    return "error:$!";
       }
       else {
    &logthis('<font color="green"> Installed new '.$tablefile
    ."</font>");
   
       }
   
   
       #  Indicate success:
    
       return "ok";
   
   }
   
   #
   #  Called to re-init either lonc or lond.
   #
   #  Parameters:
   #    request   - The full request by the client.  This is of the form
   #                reinit:<process>  
   #                where <process> is allowed to be either of 
   #                lonc or lond
   #
   #  Returns:
   #     The string to be sent back to the client either:
   #   ok         - Everything worked just fine.
   #   error:why  - There was a failure and why describes the reason.
   #
   #
   sub ReinitProcess {
       my $request = shift;
   
   
       # separate the request (reinit) from the process identifier and
       # validate it producing the name of the .pid file for the process.
       #
       #
       my ($junk, $process) = split(":", $request);
       my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
       if($process eq 'lonc') {
    $processpidfile = $processpidfile."lonc.pid";
    if (!open(PIDFILE, "< $processpidfile")) {
       return "error:Open failed for $processpidfile";
    }
    my $loncpid = <PIDFILE>;
    close(PIDFILE);
    logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
    ."</font>");
    kill("USR2", $loncpid);
       } elsif ($process eq 'lond') {
    logthis('<font color="red"> Reinitializing self (lond) </font>');
    &UpdateHosts; # Lond is us!!
       } else {
    &logthis('<font color="yellow" Invalid reinit request for '.$process
    ."</font>");
    return "error:Invalid process identifier $process";
       }
       return 'ok';
   }
   
   #
 #  Convert an error return code from lcpasswd to a string value.  #  Convert an error return code from lcpasswd to a string value.
 #  #
 sub lcpasswdstrerror {  sub lcpasswdstrerror {
Line 175  $SIG{__DIE__}=\&catchexception; Line 466  $SIG{__DIE__}=\&catchexception;
 # ---------------------------------- Read loncapa_apache.conf and loncapa.conf  # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 &status("Read loncapa.conf and loncapa_apache.conf");  &status("Read loncapa.conf and loncapa_apache.conf");
 my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');  my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 my %perlvar=%{$perlvarref};  %perlvar=%{$perlvarref};
 undef $perlvarref;  undef $perlvarref;
   
 # ----------------------------- Make sure this process is running from user=www  # ----------------------------- Make sure this process is running from user=www
Line 260  sub HUPSMAN {                      # sig Line 551  sub HUPSMAN {                      # sig
     exec("$execdir/lond");         # here we go again      exec("$execdir/lond");         # here we go again
 }  }
   
   #
   #   Called in response to a USR2 signal.
   #   - Reread hosts.tab
   #   - All children connected to hosts that were removed from hosts.tab
   #     are killed via SIGINT
   #   - All children connected to previously existing hosts are sent SIGUSR1
   #   - Our internal hosts hash is updated to reflect the new contents of
   #     hosts.tab causing connections from hosts added to hosts.tab to
   #     now be honored.
   #
   sub UpdateHosts {
       logthis('<font color="blue"> Updating connections </font>');
   }
   
 sub checkchildren {  sub checkchildren {
     &initnewstatus();      &initnewstatus();
     &logstatus();      &logstatus();
Line 502  $SIG{CHLD} = \&REAPER; Line 807  $SIG{CHLD} = \&REAPER;
 $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 $SIG{HUP}  = \&HUPSMAN;  $SIG{HUP}  = \&HUPSMAN;
 $SIG{USR1} = \&checkchildren;  $SIG{USR1} = \&checkchildren;
   $SIG{USR2} = \&UpdateHosts;
   
   
 # --------------------------------------------------------------  # --------------------------------------------------------------
Line 527  sub make_new_child { Line 832  sub make_new_child {
     sigprocmask(SIG_BLOCK, $sigset)      sigprocmask(SIG_BLOCK, $sigset)
         or die "Can't block SIGINT for fork: $!\n";          or die "Can't block SIGINT for fork: $!\n";
   
     my $clientip;  
     die "fork: $!" unless defined ($pid = fork);      die "fork: $!" unless defined ($pid = fork);
           
     if ($pid) {      if ($pid) {
Line 645  sub make_new_child { Line 949  sub make_new_child {
    if ($userinput =~ /^ping/) {     if ($userinput =~ /^ping/) {
                        print $client "$currenthostid\n";                         print $client "$currenthostid\n";
 # ------------------------------------------------------------------------ pong  # ------------------------------------------------------------------------ pong
    } elsif ($userinput =~ /^pong/) {     }elsif ($userinput =~ /^pong/) {
                        my $reply=&reply("ping",$hostid{$clientip});                         my $reply=&reply("ping",$hostid{$clientip});
                        print $client "$currenthostid:$reply\n";                          print $client "$currenthostid:$reply\n"; 
 # ------------------------------------------------------------------------ ekey  # ------------------------------------------------------------------------ ekey
Line 676  sub make_new_child { Line 980  sub make_new_child {
    } elsif ($userinput =~ /^userload/) {     } elsif ($userinput =~ /^userload/) {
        my $userloadpercent=&userload();         my $userloadpercent=&userload();
        print $client "$userloadpercent\n";         print $client "$userloadpercent\n";
   
   #
   #        Transactions requiring encryption:
   #
 # ----------------------------------------------------------------- currentauth  # ----------------------------------------------------------------- currentauth
    } elsif ($userinput =~ /^currentauth/) {     } elsif ($userinput =~ /^currentauth/) {
      if ($wasenc==1) {       if ($wasenc==1) {
Line 690  sub make_new_child { Line 998  sub make_new_child {
      } else {       } else {
        print $client "refused\n";         print $client "refused\n";
      }       }
   #--------------------------------------------------------------------- pushfile
      } elsif($userinput =~ /^pushfile/) { 
          if($wasenc == 1) {
      my $cert = GetCertificate($userinput);
      if(ValidManager($cert)) {
          my $reply = PushFile($userinput);
          print $client "$reply\n";
      } else {
          print $client "refused\n";
      } 
          } else {
      print $client "refused\n";
          }
   #--------------------------------------------------------------------- reinit
      } elsif($userinput =~ /^reinit/) {
          if ($wasenc == 1) {
      my $cert = GetCertificate($userinput);
      if(ValidManager($cert)) {
          chomp($userinput);
          my $reply = ReinitProcess($userinput);
          print $client  "$reply\n";
      } else {
          print $client "refused\n";
      }
          } else {
      print $client "refused\n";
          }
 # ------------------------------------------------------------------------ auth  # ------------------------------------------------------------------------ auth
                    } elsif ($userinput =~ /^auth/) {                     } elsif ($userinput =~ /^auth/) {
      if ($wasenc==1) {       if ($wasenc==1) {
Line 801  sub make_new_child { Line 1136  sub make_new_child {
      my $salt=time;       my $salt=time;
                              $salt=substr($salt,6,2);                               $salt=substr($salt,6,2);
      my $ncpass=crypt($npass,$salt);       my $ncpass=crypt($npass,$salt);
                              { my $pf = IO::File->new(">$passfilename");                               {
           print $pf "internal:$ncpass\n"; }                my $pf;
      &logthis("Result of password change for $uname: pwchange_success");   if ($pf = IO::File->new(">$passfilename")) {
                              print $client "ok\n";       print $pf "internal:$ncpass\n";
        &logthis("Result of password change for $uname: pwchange_success");
        print $client "ok\n";
    } else {
        &logthis("Unable to open $uname passwd to change password");
        print $client "non_authorized\n";
    }
        }             
        
                            } else {                             } else {
                              print $client "non_authorized\n";                               print $client "non_authorized\n";
                            }                             }
Line 1726  sub make_new_child { Line 2069  sub make_new_child {
                        }                         }
                        if ($ulsout eq '') { $ulsout='empty'; }                         if ($ulsout eq '') { $ulsout='empty'; }
                        print $client "$ulsout\n";                         print $client "$ulsout\n";
   # ----------------------------------------------------------------- setannounce
                      } elsif ($userinput =~ /^setannounce/) {
          my ($cmd,$announcement)=split(/:/,$userinput);
          chomp($announcement);
          $announcement=&unescape($announcement);
                          if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
    '/announcement.txt')) {
      print $store $announcement;
                              close $store;
      print $client "ok\n";
          } else {
      print $client "error: ".($!+0)."\n";
          }
 # ------------------------------------------------------------------ Hanging up  # ------------------------------------------------------------------ Hanging up
                    } elsif (($userinput =~ /^exit/) ||                     } elsif (($userinput =~ /^exit/) ||
                             ($userinput =~ /^init/)) {                              ($userinput =~ /^init/)) {
Line 1880  sub chatadd { Line 2236  sub chatadd {
     my %hash;      my %hash;
     my $proname=&propath($cdom,$cname);      my $proname=&propath($cdom,$cname);
     my @entries=();      my @entries=();
       my $time=time;
     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",      if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
     &GDBM_WRCREAT(),0640)) {      &GDBM_WRCREAT(),0640)) {
  @entries=map { $_.':'.$hash{$_} } sort keys %hash;   @entries=map { $_.':'.$hash{$_} } sort keys %hash;
  my $time=time;  
  my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);   my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
  my ($thentime,$idnum)=split(/\_/,$lastid);   my ($thentime,$idnum)=split(/\_/,$lastid);
  my $newid=$time.'_000000';   my $newid=$time.'_000000';
Line 1903  sub chatadd { Line 2259  sub chatadd {
  }   }
  untie %hash;   untie %hash;
     }      }
       {
    my $hfh;
    if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
       print $hfh "$time:".&unescape($newchat)."\n";
    }
       }
 }  }
   
 sub unsub {  sub unsub {
Line 2098  sub userload { Line 2460  sub userload {
  my $curtime=time;   my $curtime=time;
  while ($filename=readdir(LONIDS)) {   while ($filename=readdir(LONIDS)) {
     if ($filename eq '.' || $filename eq '..') {next;}      if ($filename eq '.' || $filename eq '..') {next;}
     my ($atime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[8];      my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
     if ($curtime-$atime < 3600) { $numusers++; }      if ($curtime-$mtime < 3600) { $numusers++; }
  }   }
  closedir(LONIDS);   closedir(LONIDS);
     }      }
Line 2221  each connection is logged. Line 2583  each connection is logged.
   
 =item *  =item *
   
   SIGUSR2
   
   Parent Signal assignment:
       $SIG{USR2} = \&UpdateHosts
   
   Child signal assignment:
       NONE
   
   
   =item *
   
 SIGCHLD  SIGCHLD
   
 Parent signal assignment:  Parent signal assignment:
Line 2381  Send along temporarily stored informatio Line 2754  Send along temporarily stored informatio
   
 List part of a user's directory.  List part of a user's directory.
   
   =item pushtable
   
   Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
   hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
   must be restored manually in case of a problem with the new table file.
   pushtable requires that the request be encrypted and validated via
   ValidateManager.  The form of the command is:
   enc:pushtable tablename <tablecontents> \n
   where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
   cleartext newline.
   
 =item Hanging up (exit or init)  =item Hanging up (exit or init)
   
 What to do when a client tells the server that they (the client)  What to do when a client tells the server that they (the client)
Line 2391  are leaving the network. Line 2775  are leaving the network.
 If B<lond> is sent an unknown command (not in the list above),  If B<lond> is sent an unknown command (not in the list above),
 it replys to the client "unknown_cmd".  it replys to the client "unknown_cmd".
   
   
 =item UNKNOWN CLIENT  =item UNKNOWN CLIENT
   
 If the anti-spoofing algorithm cannot verify the client,  If the anti-spoofing algorithm cannot verify the client,

Removed from v.1.134  
changed lines
  Added in v.1.147


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