Diff for /loncom/lond between versions 1.178.2.3 and 1.178.2.4

version 1.178.2.3, 2004/02/24 11:22:41 version 1.178.2.4, 2004/02/24 16:51:40
Line 189  sub GetRequest { Line 189  sub GetRequest {
 #     cipher  - This global holds the negotiated encryption key.  #     cipher  - This global holds the negotiated encryption key.
 #  #
 sub Decipher {  sub Decipher {
    my $input  = shift;      my $input  = shift;
    my $output = '';      my $output = '';
         
         
    if($cipher) {      if($cipher) {
       my($enc, $enclength, $encinput) = split(/:/, $input);   my($enc, $enclength, $encinput) = split(/:/, $input);
       for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {   for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
          $output .=       $output .= 
             $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));   $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
       }   }
       return substr($output, 0, $enclength);   return substr($output, 0, $enclength);
    } else {      } else {
       return undef;   return undef;
    }      }
      
 }  }
   
 #  #
Line 234  sub Decipher { Line 233  sub Decipher {
 #        register a duplicate command handler.  #        register a duplicate command handler.
 #  #
 sub RegisterHandler {  sub RegisterHandler {
    my $RequestName    = shift;      my $RequestName    = shift;
    my $Procedure      = shift;      my $Procedure      = shift;
    my $MustEncode     = shift;      my $MustEncode     = shift;
    my $ClientOk       = shift;      my $ClientOk       = shift;
    my $ManagerOk      = shift;      my $ManagerOk      = shift;
         
    #  Don't allow duplication#      #  Don't allow duplication#
      
    if (defined $Dispatcher{$RequestName}) {  
       die "Attempting to define a duplicate request handler for $RequestName\n";  
    }  
    #   Build the client type mask:  
      
    my $ClientTypeMask = 0;  
    if($ClientOk) {  
       $ClientTypeMask  |= $CLIENT_OK;  
    }  
    if($ManagerOk) {  
       $ClientTypeMask  |= $MANAGER_OK;  
    }  
         
    #  Enter the hash:      if (defined $Dispatcher{$RequestName}) {
    die "Attempting to define a duplicate request handler for $RequestName\n";
       }
       #   Build the client type mask:
       
       my $ClientTypeMask = 0;
       if($ClientOk) {
    $ClientTypeMask  |= $CLIENT_OK;
       }
       if($ManagerOk) {
    $ClientTypeMask  |= $MANAGER_OK;
       }
      
       #  Enter the hash:
               
    my @entry = ($Procedure, $MustEncode, $ClientTypeMask);      my @entry = ($Procedure, $MustEncode, $ClientTypeMask);
         
    $Dispatcher{$RequestName} = \@entry;      $Dispatcher{$RequestName} = \@entry;
         
         
 }  }
Line 284  sub RegisterHandler { Line 283  sub RegisterHandler {
 #      Reply information is sent to the client.  #      Reply information is sent to the client.
   
 sub PingHandler {  sub PingHandler {
    my $cmd    = shift;      my $cmd    = shift;
    my $tail   = shift;      my $tail   = shift;
    my $client = shift;      my $client = shift;
         
    Reply( $client,"$currenthostid\n","$cmd:$tail");      Reply( $client,"$currenthostid\n","$cmd:$tail");
         
    return 1;      return 1;
 }  }
 RegisterHandler("ping", \&PingHandler, 0, 1, 1);       # Ping unencoded, client or manager.  RegisterHandler("ping", \&PingHandler, 0, 1, 1);       # Ping unencoded, client or manager.
 #  #
Line 309  RegisterHandler("ping", \&PingHandler, 0 Line 308  RegisterHandler("ping", \&PingHandler, 0
 #      Reply information is sent to the client.  #      Reply information is sent to the client.
   
 sub PongHandler {  sub PongHandler {
    my $cmd     = shift;      my $cmd     = shift;
    my $tail    = shift;      my $tail    = shift;
    my $replyfd = shift;      my $replyfd = shift;
   
    my $reply=&reply("ping",$clientname);      my $reply=&reply("ping",$clientname);
    Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail");       Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
    return 1;      return 1;
 }  }
 RegisterHandler("pong", \&PongHandler, 0, 1, 1);       # Pong unencoded, client or manager  RegisterHandler("pong", \&PongHandler, 0, 1, 1);       # Pong unencoded, client or manager
   
Line 339  RegisterHandler("pong", \&PongHandler, 0 Line 338  RegisterHandler("pong", \&PongHandler, 0
 #      $cipher is set with a reference to a new IDEA encryption object.  #      $cipher is set with a reference to a new IDEA encryption object.
 #  #
 sub EstablishKeyHandler {  sub EstablishKeyHandler {
    my $cmd      = shift;      my $cmd      = shift;
    my $tail     = shift;      my $tail     = shift;
    my $replyfd  = shift;      my $replyfd  = shift;
   
    my $buildkey=time.$$.int(rand 100000);      my $buildkey=time.$$.int(rand 100000);
    $buildkey=~tr/1-6/A-F/;      $buildkey=~tr/1-6/A-F/;
    $buildkey=int(rand 100000).$buildkey.int(rand 100000);      $buildkey=int(rand 100000).$buildkey.int(rand 100000);
    my $key=$currenthostid.$clientname;      my $key=$currenthostid.$clientname;
    $key=~tr/a-z/A-Z/;      $key=~tr/a-z/A-Z/;
    $key=~tr/G-P/0-9/;      $key=~tr/G-P/0-9/;
    $key=~tr/Q-Z/0-9/;      $key=~tr/Q-Z/0-9/;
    $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;      $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
    $key=substr($key,0,32);      $key=substr($key,0,32);
    my $cipherkey=pack("H32",$key);      my $cipherkey=pack("H32",$key);
    $cipher=new IDEA $cipherkey;      $cipher=new IDEA $cipherkey;
    Reply($replyfd, "$buildkey\n", "$cmd:$tail");       Reply($replyfd, "$buildkey\n", "$cmd:$tail"); 
         
    return 1;      return 1;
   
 }  }
 RegisterHandler("ekey", \&EstablishKeyHandler, 0, 1,1);  RegisterHandler("ekey", \&EstablishKeyHandler, 0, 1,1);
Line 379  RegisterHandler("ekey", \&EstablishKeyHa Line 378  RegisterHandler("ekey", \&EstablishKeyHa
 #  Side effects:  #  Side effects:
 #      Reply information is sent to the client.  #      Reply information is sent to the client.
 sub LoadHandler {  sub LoadHandler {
    my $cmd     = shift;      my $cmd     = shift;
    my $tail    = shift;      my $tail    = shift;
    my $replyfd = shift;      my $replyfd = shift;
   
    # Get the load average from /proc/loadavg and calculate it as a percentage of     # Get the load average from /proc/loadavg and calculate it as a percentage of
    # the allowed load limit as set by the perl global variable lonLoadLim     # the allowed load limit as set by the perl global variable lonLoadLim
   
    my $loadavg;      my $loadavg;
    my $loadfile=IO::File->new('/proc/loadavg');      my $loadfile=IO::File->new('/proc/loadavg');
         
    $loadavg=<$loadfile>;      $loadavg=<$loadfile>;
    $loadavg =~ s/\s.*//g;                       # Extract the first field only.      $loadavg =~ s/\s.*//g;                      # Extract the first field only.
         
    my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};      my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
   
    Reply( $replyfd, "$loadpercent\n", "$cmd:$tail");      Reply( $replyfd, "$loadpercent\n", "$cmd:$tail");
         
    return 1;      return 1;
 }  }
 RegisterHandler("load", \&LoadHandler, 0, 1, 0);  RegisterHandler("load", \&LoadHandler, 0, 1, 0);
   
Line 422  RegisterHandler("load", \&LoadHandler, 0 Line 421  RegisterHandler("load", \&LoadHandler, 0
 #     the reply is written to the client.  #     the reply is written to the client.
 #  #
 sub UserLoadHandler {  sub UserLoadHandler {
    my $cmd     = shift;      my $cmd     = shift;
    my $tail    = shift;      my $tail    = shift;
    my $replyfd = shift;      my $replyfd = shift;
   
    my $userloadpercent=&userload();  
    Reply($replyfd, "$userloadpercent\n", "$cmd:$tail");  
   
    return 1;      my $userloadpercent=&userload();
       Reply($replyfd, "$userloadpercent\n", "$cmd:$tail");
       
       return 1;
 }  }
 RegisterHandler("userload", \&UserLoadHandler, 0, 1, 0);  RegisterHandler("userload", \&UserLoadHandler, 0, 1, 0);
   
Line 447  RegisterHandler("userload", \&UserLoadHa Line 446  RegisterHandler("userload", \&UserLoadHa
 #    The user authorization type is written to the client.  #    The user authorization type is written to the client.
 #  #
 sub UserAuthorizationType {  sub UserAuthorizationType {
    my $cmd     = shift;      my $cmd     = shift;
    my $tail    = shift;      my $tail    = shift;
    my $replyfd = shift;      my $replyfd = shift;
         
    my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
         
    #  Pull the domain and username out of the command tail.      #  Pull the domain and username out of the command tail.
    # and call GetAuthType to determine the authentication type.      # and call GetAuthType to determine the authentication type.
         
    my ($udom,$uname)=split(/:/,$tail);      my ($udom,$uname)=split(/:/,$tail);
    my $result = GetAuthType($udom, $uname);      my $result = GetAuthType($udom, $uname);
    if($result eq "nouser") {      if($result eq "nouser") {
       Failure( $replyfd, "unknown_user\n", $userinput);   Failure( $replyfd, "unknown_user\n", $userinput);
    } else {      } else {
       Reply( $replyfd, "$result\n", $userinput);   Reply( $replyfd, "$result\n", $userinput);
    }      }
       
    return 1;      return 1;
 }  }
 RegisterHandler("currentauth", \&UserAuthorizationType, 1, 1, 0);  RegisterHandler("currentauth", \&UserAuthorizationType, 1, 1, 0);
 #  #
Line 483  RegisterHandler("currentauth", \&UserAut Line 482  RegisterHandler("currentauth", \&UserAut
 #    a reply is written to the client.  #    a reply is written to the client.
   
 sub PushFileHandler {  sub PushFileHandler {
    my $cmd    = shift;      my $cmd    = shift;
    my $tail   = shift;      my $tail   = shift;
    my $client = shift;      my $client = shift;
   
    my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
    # At this time we only know that the IP of our partner is a valid manager      # At this time we only know that the IP of our partner is a valid manager
    # the code below is a hook to do further authentication (e.g. to resolve      # the code below is a hook to do further authentication (e.g. to resolve
    # spoofing).      # spoofing).
   
    my $cert = GetCertificate($userinput);      my $cert = GetCertificate($userinput);
    if(ValidManager($cert)) {       if(ValidManager($cert)) { 
   
       # Now presumably we have the bona fides of both the peer host and the   # Now presumably we have the bona fides of both the peer host and the
       # process making the request.   # process making the request.
               
       my $reply = PushFile($userinput);   my $reply = PushFile($userinput);
       Reply($client, "$reply\n", $userinput);   Reply($client, "$reply\n", $userinput);
   
    } else {      } else {
       Failure( $client, "refused\n", $userinput);   Failure( $client, "refused\n", $userinput);
    }       } 
 }  }
 RegisterHandler("pushfile", \&PushFileHandler, 1, 0, 1);  RegisterHandler("pushfile", \&PushFileHandler, 1, 0, 1);
   
Line 525  RegisterHandler("pushfile", \&PushFileHa Line 524  RegisterHandler("pushfile", \&PushFileHa
 #     a reply is sent to the client.  #     a reply is sent to the client.
 #  #
 sub ReinitProcessHandler {  sub ReinitProcessHandler {
    my $cmd    = shift;      my $cmd    = shift;
    my $tail   = shift;      my $tail   = shift;
    my $client = shift;      my $client = shift;
         
    my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
         
    my $cert = GetCertificate($userinput);      my $cert = GetCertificate($userinput);
    if(ValidManager($cert)) {      if(ValidManager($cert)) {
       chomp($userinput);   chomp($userinput);
       my $reply = ReinitProcess($userinput);   my $reply = ReinitProcess($userinput);
       Reply( $client,  "$reply\n", $userinput);   Reply( $client,  "$reply\n", $userinput);
    } else {      } else {
       Failure( $client, "refused\n", $userinput);   Failure( $client, "refused\n", $userinput);
  }      }
    return 1;      return 1;
 }  }
   
 RegisterHandler("reinit", \&ReinitProcessHandler, 1, 0, 1);  RegisterHandler("reinit", \&ReinitProcessHandler, 1, 0, 1);
Line 559  RegisterHandler("reinit", \&ReinitProces Line 558  RegisterHandler("reinit", \&ReinitProces
 #     a reply is sent to the client.  #     a reply is sent to the client.
 #  #
 sub EditTableHandler {  sub EditTableHandler {
    my $command    = shift;      my $command    = shift;
    my $tail       = shift;      my $tail       = shift;
    my $client     = shift;      my $client     = shift;
         
    my $userinput = "$command:$tail";      my $userinput = "$command:$tail";
   
    my $cert = GetCertificate($userinput);      my $cert = GetCertificate($userinput);
    if(ValidManager($cert)) {      if(ValidManager($cert)) {
       my($filetype, $script) = split(/:/, $tail);   my($filetype, $script) = split(/:/, $tail);
       if (($filetype eq "hosts") ||    if (($filetype eq "hosts") || 
           ($filetype eq "domain")) {      ($filetype eq "domain")) {
          if($script ne "") {      if($script ne "") {
             Reply($client,            # BUGBUG - EditFile   Reply($client,              # BUGBUG - EditFile
                   EditFile($userinput), #   could fail.        EditFile($userinput), #   could fail.
                   $userinput);        $userinput);
          } else {      } else {
             Failure($client,"refused\n",$userinput);   Failure($client,"refused\n",$userinput);
          }      }
       } else {   } else {
          Failure($client,"refused\n",$userinput);      Failure($client,"refused\n",$userinput);
       }   }
    } else {      } else {
       Failure($client,"refused\n",$userinput);   Failure($client,"refused\n",$userinput);
    }      }
    return 1;      return 1;
 }  }
 RegisterHandler("edit", \&EditTableHandler, 1, 0, 1);  RegisterHandler("edit", \&EditTableHandler, 1, 0, 1);
   
Line 598  RegisterHandler("edit", \&EditTableHandl Line 597  RegisterHandler("edit", \&EditTableHandl
 #                internal per user password file.  #                internal per user password file.
 #   - kerberos - The user can be authenticated against either a kerb4 or kerb5  #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
 #                ticket granting authority.  #                ticket granting authority.
 #   - user     - The person tailoring LonCAPA can supply a user authentication mechanism  #   - user     - The person tailoring LonCAPA can supply a user authentication
 #                that is per system.  #                mechanism that is per system.
 #  #
 # Parameters:  # Parameters:
 #    $cmd      - The command that got us here.  #    $cmd      - The command that got us here.
Line 613  RegisterHandler("edit", \&EditTableHandl Line 612  RegisterHandler("edit", \&EditTableHandl
 #    input into the authentication process that are described above.  #    input into the authentication process that are described above.
 #  #
 sub AuthenticateHandler {  sub AuthenticateHandler {
    my $cmd        = shift;      my $cmd        = shift;
    my $tail       = shift;      my $tail       = shift;
    my $client     = shift;      my $client     = shift;
         
    #  Regenerate the full input line       #  Regenerate the full input line 
         
    my $userinput  = $cmd.":".$tail;      my $userinput  = $cmd.":".$tail;
   
    #  udom    - User's domain.      #  udom    - User's domain.
    #  uname   - Username.      #  uname   - Username.
    #  upass   - User's password.      #  upass   - User's password.
         
    my ($udom,$uname,$upass)=split(/:/,$tail);      my ($udom,$uname,$upass)=split(/:/,$tail);
    Debug(" Authenticate domain = $udom, user = $uname, password = $upass");      Debug(" Authenticate domain = $udom, user = $uname, password = $upass");
    chomp($upass);      chomp($upass);
    $upass=unescape($upass);      $upass=unescape($upass);
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    my $passfilename="$proname/passwd";      my $passfilename="$proname/passwd";
         
    #   The user's 'personal' loncapa passworrd file describes how to authenticate:      #   The user's 'personal' loncapa passworrd file describes how to authenticate:
         
    if (-e $passfilename) {      if (-e $passfilename) {
      Debug("Located password file: $passfilename");   Debug("Located password file: $passfilename");
   
       my $pf = IO::File->new($passfilename);   my $pf = IO::File->new($passfilename);
       my $realpasswd=<$pf>;   my $realpasswd=<$pf>;
       chomp($realpasswd);   chomp($realpasswd);
       my ($howpwd,$contentpwd)=split(/:/,$realpasswd);   my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
       my $pwdcorrect=0;   my $pwdcorrect=0;
       #   #
       #   Authenticate against password stored in the internal file.   #   Authenticate against password stored in the internal file.
       #   #
      Debug("Authenticating via $howpwd");   Debug("Authenticating via $howpwd");
       if ($howpwd eq 'internal') {   if ($howpwd eq 'internal') {
          &Debug("Internal auth");      &Debug("Internal auth");
          $pwdcorrect= (crypt($upass,$contentpwd) eq $contentpwd);      $pwdcorrect= (crypt($upass,$contentpwd) eq $contentpwd);
       #      #
       #   Authenticate against the unix password file.      #   Authenticate against the unix password file.
       #      #
       } elsif ($howpwd eq 'unix') {   } elsif ($howpwd eq 'unix') {
          &Debug("Unix auth");      &Debug("Unix auth");
          if((getpwnam($uname))[1] eq "") { #no such user!      if((getpwnam($uname))[1] eq "") { #no such user!
             $pwdcorrect = 0;   $pwdcorrect = 0;
          } else {      } else {
             $contentpwd=(getpwnam($uname))[1];   $contentpwd=(getpwnam($uname))[1];
             my $pwauth_path="/usr/local/sbin/pwauth";   my $pwauth_path="/usr/local/sbin/pwauth";
             unless ($contentpwd eq 'x') {   unless ($contentpwd eq 'x') {
                $pwdcorrect= (crypt($upass,$contentpwd) eq $contentpwd);      $pwdcorrect= (crypt($upass,$contentpwd) eq $contentpwd);
             } elsif (-e $pwauth_path) {   } elsif (-e $pwauth_path) {
                open PWAUTH, "|$pwauth_path" or      open PWAUTH, "|$pwauth_path" or
                   die "Cannot invoke authentication";   die "Cannot invoke authentication";
                print PWAUTH "$uname\n$upass\n";      print PWAUTH "$uname\n$upass\n";
                close PWAUTH;      close PWAUTH;
                $pwdcorrect=!$?;      $pwdcorrect=!$?;
             }   }
          }      }
       #      #
       #   Authenticate against a Kerberos 4 server:      #   Authenticate against a Kerberos 4 server:
       #      #
       } elsif ($howpwd eq 'krb4') {   } elsif ($howpwd eq 'krb4') {
          my $null=pack("C",0);      my $null=pack("C",0);
          unless ($upass=~/$null/) {      unless ($upass=~/$null/) {
             my $krb4_error = &Authen::Krb4::get_pw_in_tkt($uname,   my $krb4_error = &Authen::Krb4::get_pw_in_tkt($uname,
                                                           "",        "",
                                                           $contentpwd,        $contentpwd,
                                                           'krbtgt',        'krbtgt',
                                                          $contentpwd,        $contentpwd,
                                                          1,        1,
                                                          $upass);        $upass);
             if (!$krb4_error) {   if (!$krb4_error) {
                $pwdcorrect = 1;      $pwdcorrect = 1;
             } else {    } else { 
                $pwdcorrect=0;       $pwdcorrect=0; 
                # log error if it is not a bad password      # log error if it is not a bad password
                if ($krb4_error != 62) {      if ($krb4_error != 62) {
                   &logthis('krb4:'.$uname.','.$contentpwd.','.   &logthis('krb4:'.$uname.','.$contentpwd.','.
                            &Authen::Krb4::get_err_txt($Authen::Krb4::error));   &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                }      }
             }   }
          }      }
       #      #
       #   Authenticate against a Kerberos 5 server:      #   Authenticate against a Kerberos 5 server:
       #      #
       } elsif ($howpwd eq 'krb5') {   } elsif ($howpwd eq 'krb5') {
          my $null=pack("C",0);      my $null=pack("C",0);
          unless ($upass=~/$null/) {      unless ($upass=~/$null/) {
             my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);   my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
             my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;   my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
             my $krbserver=&Authen::Krb5::parse_name($krbservice);   my $krbserver=&Authen::Krb5::parse_name($krbservice);
             my $credentials=&Authen::Krb5::cc_default();   my $credentials=&Authen::Krb5::cc_default();
             $credentials->initialize($krbclient);   $credentials->initialize($krbclient);
             my $krbreturn = &Authen::Krb5::get_in_tkt_with_password(   my $krbreturn = &Authen::Krb5::get_in_tkt_with_password($krbclient,
                                                                     $krbclient,   $krbserver,
                                                                     $krbserver,   $upass,
                                                                     $upass,   $credentials);
                                                                     $credentials);   $pwdcorrect = ($krbreturn == 1);
             $pwdcorrect = ($krbreturn == 1);      } else { 
          } else {    $pwdcorrect=0; 
             $pwdcorrect=0;       }
          }      #
       #      #  Finally, the user may have written in an authentication module.
       #  Finally, the user may have written in an authentication module.      #  in that case, if requested, authenticate against it.
       #  in that case, if requested, authenticate against it.      #
       #   } elsif ($howpwd eq 'localauth') {
       } elsif ($howpwd eq 'localauth') {      $pwdcorrect=&localauth::localauth($uname,$upass,$contentpwd);
          $pwdcorrect=&localauth::localauth($uname,$upass,$contentpwd);   }
       }   #
       #   #   Successfully authorized.
       #   Successfully authorized.   #
       #   if ($pwdcorrect) {
       if ($pwdcorrect) {      Reply( $client, "authorized\n", $userinput);
          Reply( $client, "authorized\n", $userinput);      #
       #      #  Bad credentials: Failed to authorize
       #  Bad credentials: Failed to authorize      #
       #   } else {
       } else {      Failure( $client, "non_authorized\n", $userinput);
          Failure( $client, "non_authorized\n", $userinput);   }
       }   #
    #   #  User bad... note it may be bad security practice to
    #  User bad... note it may be bad security practice to differntiate to the   #  differntiate to the caller a bad user from a bad
    #  caller a bad user from a  bad passwd... since that supplies covert channel   #  passwd... since that supplies covert channel information
    #  information (you have a good user but bad password e.g.) to guessers.   #  (you have a good user but bad password e.g.) to guessers.
    #   #
    } else {      } else {
       Failure( $client, "unknown_user\n", $userinput);   Failure( $client, "unknown_user\n", $userinput);
    }      }
    return 1;      return 1;
 }  }
 RegisterHandler("auth", \&AuthenticateHandler, 1, 1, 0);  RegisterHandler("auth", \&AuthenticateHandler, 1, 1, 0);
   
Line 765  RegisterHandler("auth", \&AuthenticateHa Line 764  RegisterHandler("auth", \&AuthenticateHa
 #    The authentication systems describe above have their own forms of implicit  #    The authentication systems describe above have their own forms of implicit
 #    input into the authentication process that are described above.  #    input into the authentication process that are described above.
 sub ChangePasswordHandler {  sub ChangePasswordHandler {
    my $cmd     = shift;      my $cmd     = shift;
    my $tail    = shift;      my $tail    = shift;
    my $client  = shift;      my $client  = shift;
         
    my $userinput = $cmd.":".$tail;           # Reconstruct client's string.      my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
   
    #      #
    #  udom  - user's domain.      #  udom  - user's domain.
    #  uname - Username.      #  uname - Username.
    #  upass - Current password.      #  upass - Current password.
    #  npass - New password.      #  npass - New password.
         
    my ($udom,$uname,$upass,$npass)=split(/:/,$tail);      my ($udom,$uname,$upass,$npass)=split(/:/,$tail);
    chomp($npass);      chomp($npass);
    $upass=&unescape($upass);      $upass=&unescape($upass);
    $npass=&unescape($npass);      $npass=&unescape($npass);
    &Debug("Trying to change password for $uname");      &Debug("Trying to change password for $uname");
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    my $passfilename="$proname/passwd";      my $passfilename="$proname/passwd";
    if (-e $passfilename) {      if (-e $passfilename) {
       my $realpasswd;   my $realpasswd;
       {    { 
          my $pf = IO::File->new($passfilename);      my $pf = IO::File->new($passfilename);
          $realpasswd=<$pf>;       $realpasswd=<$pf>; 
       }   }
       chomp($realpasswd);   chomp($realpasswd);
       my ($howpwd,$contentpwd)=split(/:/,$realpasswd);   my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
       if ($howpwd eq 'internal') {   if ($howpwd eq 'internal') {
          &Debug("internal auth");      &Debug("internal auth");
          if (crypt($upass,$contentpwd) eq $contentpwd) {      if (crypt($upass,$contentpwd) eq $contentpwd) {
             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");      my $pf = IO::File->new(">$passfilename");
                   if ($pf) {      if ($pf) {
                      print $pf "internal:$ncpass\n";   print $pf "internal:$ncpass\n";
                      &logthis("Result of password change for "   &logthis("Result of password change for "
                               ."$uname: pwchange_success");   ."$uname: pwchange_success");
                      Reply($client, "ok\n", $userinput);   Reply($client, "ok\n", $userinput);
                   } else {      } else {
                      &logthis("Unable to open $uname passwd "                  &logthis("Unable to open $uname passwd "               
                               ."to change password");   ."to change password");
                      Failure( $client, "non_authorized\n",$userinput);   Failure( $client, "non_authorized\n",$userinput);
                   }      }
                }                }             
          } else {      } else {
             Failure($client, "non_authorized\n", $userinput);   Failure($client, "non_authorized\n", $userinput);
          }      }
       } elsif ($howpwd eq 'unix') {   } elsif ($howpwd eq 'unix') {
          # Unix means we have to access /etc/password      # Unix means we have to access /etc/password
          # one way or another.      # one way or another.
          # First: Make sure the current password is      # First: Make sure the current password is
          #        correct      #        correct
          &Debug("auth is unix");      &Debug("auth is unix");
          $contentpwd=(getpwnam($uname))[1];      $contentpwd=(getpwnam($uname))[1];
          my $pwdcorrect = "0";      my $pwdcorrect = "0";
          my $pwauth_path="/usr/local/sbin/pwauth";      my $pwauth_path="/usr/local/sbin/pwauth";
          unless ($contentpwd eq 'x') {      unless ($contentpwd eq 'x') {
             $pwdcorrect= (crypt($upass,$contentpwd) eq $contentpwd);   $pwdcorrect= (crypt($upass,$contentpwd) eq $contentpwd);
          } elsif (-e $pwauth_path) {      } elsif (-e $pwauth_path) {
             open PWAUTH, "|$pwauth_path" or   open PWAUTH, "|$pwauth_path" or
                die "Cannot invoke authentication";      die "Cannot invoke authentication";
             print PWAUTH "$uname\n$upass\n";   print PWAUTH "$uname\n$upass\n";
             close PWAUTH;   close PWAUTH;
             &Debug("exited pwauth with $? ($uname,$upass) ");   &Debug("exited pwauth with $? ($uname,$upass) ");
             $pwdcorrect=($? == 0);   $pwdcorrect=($? == 0);
          }      }
          if ($pwdcorrect) {      if ($pwdcorrect) {
             my $execdir=$perlvar{'lonDaemons'};   my $execdir=$perlvar{'lonDaemons'};
             &Debug("Opening lcpasswd pipeline");   &Debug("Opening lcpasswd pipeline");
             my $pf = IO::File->new("|$execdir/lcpasswd > "   my $pf = IO::File->new("|$execdir/lcpasswd > "
                                     ."$perlvar{'lonDaemons'}"         ."$perlvar{'lonDaemons'}"
                                     ."/logs/lcpasswd.log");         ."/logs/lcpasswd.log");
             print $pf "$uname\n$npass\n$npass\n";   print $pf "$uname\n$npass\n$npass\n";
             close $pf;   close $pf;
             my $err = $?;   my $err = $?;
             my $result = ($err>0 ? 'pwchange_failure' : 'ok');   my $result = ($err>0 ? 'pwchange_failure' : 'ok');
             &logthis("Result of password change for $uname: ".   &logthis("Result of password change for $uname: ".
             &lcpasswdstrerror($?));   &lcpasswdstrerror($?));
             Reply($client, "$result\n", $userinput);   Reply($client, "$result\n", $userinput);
          } else {      } else {
             Reply($client, "non_authorized\n", $userinput);   Reply($client, "non_authorized\n", $userinput);
          }      }
       } else {   } else {
          Reply( $client, "auth_mode_error\n", $userinput);      Reply( $client, "auth_mode_error\n", $userinput);
       }     }  
    } else {      } else {
             Reply( $client, "unknown_user\n", $userinput);   Reply( $client, "unknown_user\n", $userinput);
    }      }
    return 1;      return 1;
 }  }
 RegisterHandler("passwd", \&ChangePasswordHandler, 1, 1, 0);  RegisterHandler("passwd", \&ChangePasswordHandler, 1, 1, 0);
   
Line 876  RegisterHandler("passwd", \&ChangePasswo Line 875  RegisterHandler("passwd", \&ChangePasswo
 #    The authentication systems describe above have their own forms of implicit  #    The authentication systems describe above have their own forms of implicit
 #    input into the authentication process that are described above.  #    input into the authentication process that are described above.
 sub AddUserHandler {  sub AddUserHandler {
    my $cmd     = shift;      my $cmd     = shift;
    my $tail    = shift;      my $tail    = shift;
    my $client  = shift;      my $client  = shift;
          
    my $userinput = $cmd.":".$tail;         my $userinput = $cmd.":".$tail;   
   
    my $oldumask=umask(0077);      my $oldumask=umask(0077);
    my ($udom,$uname,$umode,$npass)=split(/:/,$tail);      my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
    &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);      &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
    chomp($npass);      chomp($npass);
    $npass=&unescape($npass);      $npass=&unescape($npass);
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    my $passfilename="$proname/passwd";      my $passfilename="$proname/passwd";
    &Debug("Password file created will be:".$passfilename);      &Debug("Password file created will be:".$passfilename);
    if (-e $passfilename) {      if (-e $passfilename) {
       Failure( $client, "already_exists\n", $userinput);   Failure( $client, "already_exists\n", $userinput);
    } elsif ($udom ne $currentdomainid) {      } elsif ($udom ne $currentdomainid) {
       Failure($client, "not_right_domain\n", $userinput);   Failure($client, "not_right_domain\n", $userinput);
    } else {      } else {
       my @fpparts=split(/\//,$proname);   my @fpparts=split(/\//,$proname);
       my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];   my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
       my $fperror='';   my $fperror='';
       for (my $i=3;$i<=$#fpparts;$i++) {   for (my $i=3;$i<=$#fpparts;$i++) {
          $fpnow.='/'.$fpparts[$i];       $fpnow.='/'.$fpparts[$i]; 
          unless (-e $fpnow) {      unless (-e $fpnow) {
             unless (mkdir($fpnow,0777)) {   unless (mkdir($fpnow,0777)) {
                $fperror="error: ".($!+0)." mkdir failed while attempting "      $fperror="error: ".($!+0)." mkdir failed while attempting "
                        ."makeuser";   ."makeuser";
             }   }
          }      }
       }   }
       unless ($fperror) {   unless ($fperror) {
          my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);      my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);
          Reply($client, $result, $userinput);     #BUGBUG - could be fail      Reply($client, $result, $userinput);     #BUGBUG - could be fail
       } else {   } else {
          Failure($client, "$fperror\n", $userinput);      Failure($client, "$fperror\n", $userinput);
       }   }
    }      }
    umask($oldumask);      umask($oldumask);
    return 1;      return 1;
   
 }  }
 RegisterHandler("makeuser", \&AddUserHandler, 1, 1, 0);  RegisterHandler("makeuser", \&AddUserHandler, 1, 1, 0);
Line 943  RegisterHandler("makeuser", \&AddUserHan Line 942  RegisterHandler("makeuser", \&AddUserHan
 #    input into the authentication process that are described above.  #    input into the authentication process that are described above.
 #  #
 sub ChangeAuthenticationHandler {  sub ChangeAuthenticationHandler {
    my $cmd     = shift;      my $cmd     = shift;
    my $tail    = shift;      my $tail    = shift;
    my $client  = shift;      my $client  = shift;
         
    my $userinput  = "$cmd:$tail";              # Reconstruct user input.      my $userinput  = "$cmd:$tail";              # Reconstruct user input.
   
    my ($udom,$uname,$umode,$npass)=split(/:/,$tail);      my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
    chomp($npass);      chomp($npass);
    &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);      &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
    $npass=&unescape($npass);      $npass=&unescape($npass);
    my $proname=&propath($udom,$uname);      my $proname=&propath($udom,$uname);
    my $passfilename="$proname/passwd";      my $passfilename="$proname/passwd";
    if ($udom ne $currentdomainid) {      if ($udom ne $currentdomainid) {
       Failure( $client, "not_right_domain\n", $client);   Failure( $client, "not_right_domain\n", $client);
    } else {      } else {
       my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);   my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);
       Reply($client, $result, $userinput);   Reply($client, $result, $userinput);
    }      }
    return 1;      return 1;
 }  }
 RegisterHandler("changeuserauth", \&ChangeAuthenticationHandler, 1,1, 0);  RegisterHandler("changeuserauth", \&ChangeAuthenticationHandler, 1,1, 0);
   
Line 982  RegisterHandler("changeuserauth", \&Chan Line 981  RegisterHandler("changeuserauth", \&Chan
 #    input into the authentication process that are described above.  #    input into the authentication process that are described above.
 #  #
 sub IsHomeHandler {  sub IsHomeHandler {
    my $cmd     = shift;      my $cmd     = shift;
    my $tail    = shift;      my $tail    = shift;
    my $client  = shift;      my $client  = shift;
         
    my $userinput  = "$cmd:$tail";      my $userinput  = "$cmd:$tail";
         
    my ($udom,$uname)=split(/:/,$tail);      my ($udom,$uname)=split(/:/,$tail);
    chomp($uname);      chomp($uname);
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    if (-e $proname) {      if (-e $proname) {
       Reply( $client, "found\n", $userinput);   Reply( $client, "found\n", $userinput);
    } else {      } else {
       Failure($client, "not_found\n", $userinput);   Failure($client, "not_found\n", $userinput);
    }      }
    return 1;      return 1;
 }  }
 RegisterHandler("home", \&IsHomeHandler, 0,1,0);  RegisterHandler("home", \&IsHomeHandler, 0,1,0);
 #  #
Line 1022  RegisterHandler("home", \&IsHomeHandler, Line 1021  RegisterHandler("home", \&IsHomeHandler,
 #    input into the authentication process that are described above.  #    input into the authentication process that are described above.
 #  #
 sub UpdateResourceHandler {  sub UpdateResourceHandler {
    my $cmd    = shift;      my $cmd    = shift;
    my $tail   = shift;      my $tail   = shift;
    my $client = shift;      my $client = shift;
         
    my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
         
    my $fname=$tail;      my $fname=$tail;
    my $ownership=ishome($fname);      my $ownership=ishome($fname);
    if ($ownership eq 'not_owner') {      if ($ownership eq 'not_owner') {
       if (-e $fname) {   if (-e $fname) {
          my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,      my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
              $atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);   $atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
          my $now=time;      my $now=time;
          my $since=$now-$atime;      my $since=$now-$atime;
          if ($since>$perlvar{'lonExpire'}) {      if ($since>$perlvar{'lonExpire'}) {
             my $reply=&reply("unsub:$fname","$clientname");   my $reply=&reply("unsub:$fname","$clientname");
             unlink("$fname");   unlink("$fname");
          } else {      } else {
             my $transname="$fname.in.transfer";   my $transname="$fname.in.transfer";
             my $remoteurl=&reply("sub:$fname","$clientname");   my $remoteurl=&reply("sub:$fname","$clientname");
             my $response;   my $response;
             alarm(120);   alarm(120);
             {   {
                my $ua=new LWP::UserAgent;      my $ua=new LWP::UserAgent;
                my $request=new HTTP::Request('GET',"$remoteurl");      my $request=new HTTP::Request('GET',"$remoteurl");
                $response=$ua->request($request,$transname);      $response=$ua->request($request,$transname);
             }   }
             alarm(0);   alarm(0);
             if ($response->is_error()) {   if ($response->is_error()) {
                unlink($transname);      unlink($transname);
                my $message=$response->status_line;      my $message=$response->status_line;
                &logthis("LWP GET: $message for $fname ($remoteurl)");      &logthis("LWP GET: $message for $fname ($remoteurl)");
             } else {   } else {
                if ($remoteurl!~/\.meta$/) {      if ($remoteurl!~/\.meta$/) {
                   alarm(120);   alarm(120);
                   {   {
                      my $ua=new LWP::UserAgent;      my $ua=new LWP::UserAgent;
                      my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');      my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                      my $mresponse=$ua->request($mrequest,$fname.'.meta');      my $mresponse=$ua->request($mrequest,$fname.'.meta');
                      if ($mresponse->is_error()) {      if ($mresponse->is_error()) {
                         unlink($fname.'.meta');   unlink($fname.'.meta');
                      }      }
                   }   }
                   alarm(0);   alarm(0);
                }      }
                rename($transname,$fname);      rename($transname,$fname);
             }   }
          }      }
                Reply( $client, "ok\n", $userinput);      Reply( $client, "ok\n", $userinput);
       } else {   } else {
          Failure($client, "not_found\n", $userinput);      Failure($client, "not_found\n", $userinput);
       }   }
    } else {      } else {
       Failure($client, "rejected\n", $userinput);   Failure($client, "rejected\n", $userinput);
    }      }
    return 1;      return 1;
 }  }
 RegisterHandler("update", \&UpdateResourceHandler, 0 ,1, 0);  RegisterHandler("update", \&UpdateResourceHandler, 0 ,1, 0);
   
Line 1092  RegisterHandler("update", \&UpdateResour Line 1091  RegisterHandler("update", \&UpdateResour
 #     1        - Continue processing.  #     1        - Continue processing.
 #  #
 sub FetchUserFileHandler {  sub FetchUserFileHandler {
    my $cmd     = shift;      my $cmd     = shift;
    my $tail    = shift;      my $tail    = shift;
    my $client  = shift;      my $client  = shift;
         
    my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
    my $fname           = $tail;      my $fname           = $tail;
    my ($udom,$uname,$ufile)=split(/\//,$fname);      my ($udom,$uname,$ufile)=split(/\//,$fname);
    my $udir=propath($udom,$uname).'/userfiles';      my $udir=propath($udom,$uname).'/userfiles';
    unless (-e $udir) {      unless (-e $udir) {
       mkdir($udir,0770);    mkdir($udir,0770); 
    }      }
    if (-e $udir) {      if (-e $udir) {
       $ufile=~s/^[\.\~]+//;   $ufile=~s/^[\.\~]+//;
       $ufile=~s/\///g;   $ufile=~s/\///g;
       my $destname=$udir.'/'.$ufile;   my $destname=$udir.'/'.$ufile;
       my $transname=$udir.'/'.$ufile.'.in.transit';   my $transname=$udir.'/'.$ufile.'.in.transit';
       my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;   my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
       my $response;   my $response;
       alarm(120);   alarm(120);
       {   {
          my $ua=new LWP::UserAgent;      my $ua=new LWP::UserAgent;
          my $request=new HTTP::Request('GET',"$remoteurl");      my $request=new HTTP::Request('GET',"$remoteurl");
          $response=$ua->request($request,$transname);      $response=$ua->request($request,$transname);
       }   }
       alarm(0);   alarm(0);
       if ($response->is_error()) {   if ($response->is_error()) {
          unlink($transname);      unlink($transname);
          my $message=$response->status_line;      my $message=$response->status_line;
          &logthis("LWP GET: $message for $fname ($remoteurl)");      &logthis("LWP GET: $message for $fname ($remoteurl)");
          Failure($client, "failed\n", $userinput);      Failure($client, "failed\n", $userinput);
       } else {   } else {
          if (!rename($transname,$destname)) {      if (!rename($transname,$destname)) {
             &logthis("Unable to move $transname to $destname");   &logthis("Unable to move $transname to $destname");
             unlink($transname);   unlink($transname);
             Failure($client, "failed\n", $userinput);   Failure($client, "failed\n", $userinput);
          } else {      } else {
             Reply($client, "ok\n", $userinput);   Reply($client, "ok\n", $userinput);
          }      }
       }      }   
    } else {      } else {
       Failure($client, "not_home\n", $userinput);   Failure($client, "not_home\n", $userinput);
    }      }
    return 1;      return 1;
 }  }
 RegisterHandler("fetchuserfile", \&FetchUserFileHandler, 0, 1, 0);  RegisterHandler("fetchuserfile", \&FetchUserFileHandler, 0, 1, 0);
 #  #
Line 1150  RegisterHandler("fetchuserfile", \&Fetch Line 1149  RegisterHandler("fetchuserfile", \&Fetch
 #     0        - Requested to exit, caller should shut down.  #     0        - Requested to exit, caller should shut down.
 #     1        - Continue processing.  #     1        - Continue processing.
 sub AuthenticateUserFileAccess {  sub AuthenticateUserFileAccess {
    my $cmd   = shift;      my $cmd   = shift;
    my $tail    = shift;      my $tail    = shift;
    my $client = shift;      my $client = shift;
    my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
    my ($fname,$session)=split(/:/,$tail);      my ($fname,$session)=split(/:/,$tail);
    chomp($session);      chomp($session);
    my $reply='non_auth';      my $reply='non_auth';
    if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.$session.'.id')) {      if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.$session.'.id')) {
       while (my $line=<ENVIN>) {   while (my $line=<ENVIN>) {
          if ($line=~/userfile\.$fname\=/) {       if ($line=~/userfile\.$fname\=/) { 
             $reply='ok';    $reply='ok'; 
          }      }
       }   }
       close(ENVIN);   close(ENVIN);
       Reply($client, $reply."\n", $userinput);   Reply($client, $reply."\n", $userinput);
    } else {      } else {
       Failure($client, "invalid_token\n", $userinput);   Failure($client, "invalid_token\n", $userinput);
    }      }
    return 1;      return 1;
         
 }  }
 RegisterHandler("tokenauthuserfile", \&AuthenticateUserFileAccess, 0, 1, 0);  RegisterHandler("tokenauthuserfile", \&AuthenticateUserFileAccess, 0, 1, 0);
Line 1185  RegisterHandler("tokenauthuserfile", \&A Line 1184  RegisterHandler("tokenauthuserfile", \&A
 #     1        - Continue processing.  #     1        - Continue processing.
 #  #
 sub UnsubscribeHandler {  sub UnsubscribeHandler {
    my $cmd      = shift;      my $cmd      = shift;
    my $tail     = shift;      my $tail     = shift;
    my $client   = shift;      my $client   = shift;
    my $userinput= "$cmd:$tail";      my $userinput= "$cmd:$tail";
       
    my $fname = $tail;      my $fname = $tail;
    if (-e $fname) {      if (-e $fname) {
       Reply($client, &unsub($client,$fname,$clientip), $userinput);   Reply($client, &unsub($client,$fname,$clientip), $userinput);
    } else {      } else {
       Failure($client, "not_found\n", $userinput);   Failure($client, "not_found\n", $userinput);
    }      }
    return 1;      return 1;
 }  }
 RegisterHandler("unusb", \&UnsubscribeHandler, 0, 1, 0);  RegisterHandler("unusb", \&UnsubscribeHandler, 0, 1, 0);
   
Line 1211  RegisterHandler("unusb", \&UnsubscribeHa Line 1210  RegisterHandler("unusb", \&UnsubscribeHa
 #     1        - Continue processing.  #     1        - Continue processing.
 #  #
 sub SubscribeHandler {  sub SubscribeHandler {
    my $cmd        = shift;      my $cmd        = shift;
    my $tail       = shift;      my $tail       = shift;
    my $client     = shift;      my $client     = shift;
    my $userinput  = "$cmd:$tail";      my $userinput  = "$cmd:$tail";
   
    Reply( $client, &subscribe($userinput,$clientip), $userinput);      Reply( $client, &subscribe($userinput,$clientip), $userinput);
    
    return 1;      return 1;
 }  }
 RegisterHandler("sub", \&SubscribeHandler, 0, 1, 0);  RegisterHandler("sub", \&SubscribeHandler, 0, 1, 0);
   
Line 1236  RegisterHandler("sub", \&SubscribeHandle Line 1235  RegisterHandler("sub", \&SubscribeHandle
 #     1        - Continue processing.  #     1        - Continue processing.
 #  #
 sub CurrentVersionHandler {  sub CurrentVersionHandler {
    my $cmd      = shift;      my $cmd      = shift;
    my $tail     = shift;      my $tail     = shift;
    my $client   = shift;      my $client   = shift;
    my $userinput= "$cmd:$tail";      my $userinput= "$cmd:$tail";
         
    my $fname   = $tail;      my $fname   = $tail;
    Reply( $client, &currentversion($fname)."\n", $userinput);      Reply( $client, &currentversion($fname)."\n", $userinput);
    return 1;      return 1;
   
 }  }
 RegisterHandler("currentversion", \&CurrentVersionHandler, 0, 1, 0);  RegisterHandler("currentversion", \&CurrentVersionHandler, 0, 1, 0);
Line 1260  RegisterHandler("currentversion", \&Curr Line 1259  RegisterHandler("currentversion", \&Curr
 #     1        - Continue processing.  #     1        - Continue processing.
 #  #
 sub ActivityLogEntryHandler {  sub ActivityLogEntryHandler {
    my $cmd      = shift;      my $cmd      = shift;
    my $tail     = shift;      my $tail     = shift;
    my $client   = shift;      my $client   = shift;
    my $userinput= "$cmd:$tail";      my $userinput= "$cmd:$tail";
   
    my ($udom,$uname,$what)=split(/:/,$tail);      my ($udom,$uname,$what)=split(/:/,$tail);
    chomp($what);      chomp($what);
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    my $now=time;      my $now=time;
    my $hfh;      my $hfh;
    if ($hfh=IO::File->new(">>$proname/activity.log")) {       if ($hfh=IO::File->new(">>$proname/activity.log")) { 
       print $hfh "$now:$clientname:$what\n";   print $hfh "$now:$clientname:$what\n";
       Reply( $client, "ok\n", $userinput);    Reply( $client, "ok\n", $userinput); 
    } else {      } else {
       Reply($client, "error: ".($!+0)." IO::File->new Failed "   Reply($client, "error: ".($!+0)." IO::File->new Failed "
             ."while attempting log\n",         ."while attempting log\n", 
             $userinput);        $userinput);
    }      }
   
    return 1;      return 1;
 }  }
 RegisterHandler("log", \&ActivityLogEntryHandler, 0, 1, 0);  RegisterHandler("log", \&ActivityLogEntryHandler, 0, 1, 0);
 #  #
Line 1297  RegisterHandler("log", \&ActivityLogEntr Line 1296  RegisterHandler("log", \&ActivityLogEntr
 #     1        - Continue processing.  #     1        - Continue processing.
 #  #
 sub PutUserProfileEntry {  sub PutUserProfileEntry {
    my $cmd       = shift;      my $cmd       = shift;
    my $tail      = shift;      my $tail      = shift;
    my $client    = shift;      my $client    = shift;
    my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
    my ($udom,$uname,$namespace,$what) =split(/:/,$tail);      my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
    $namespace=~s/\//\_/g;      $namespace=~s/\//\_/g;
    $namespace=~s/\W//g;      $namespace=~s/\W//g;
    if ($namespace ne 'roles') {      if ($namespace ne 'roles') {
       chomp($what);   chomp($what);
       my $proname=propath($udom,$uname);   my $proname=propath($udom,$uname);
       my $now=time;   my $now=time;
       unless ($namespace=~/^nohist\_/) {   unless ($namespace=~/^nohist\_/) {
          my $hfh;      my $hfh;
          if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {       if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { 
             print $hfh "P:$now:$what\n";    print $hfh "P:$now:$what\n"; 
          }      }
       }   }
       my @pairs=split(/\&/,$what);   my @pairs=split(/\&/,$what);
       my %hash;   my %hash;
       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",   if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
                   &GDBM_WRCREAT(),0640)) {   &GDBM_WRCREAT(),0640)) {
          foreach my $pair (@pairs) {      foreach my $pair (@pairs) {
             my ($key,$value)=split(/=/,$pair);   my ($key,$value)=split(/=/,$pair);
             $hash{$key}=$value;   $hash{$key}=$value;
          }      }
          if (untie(%hash)) {      if (untie(%hash)) {
             Reply( $client, "ok\n", $userinput);   Reply( $client, "ok\n", $userinput);
          } else {      } else {
             Failure($client, "error: ".($!+0)." untie(GDBM) failed ".   Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   "while attempting put\n",    "while attempting put\n", 
                   $userinput);   $userinput);
          }      }
       } else {   } else {
          Failure( $client, "error: ".($!)." tie(GDBM) Failed ".      Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
          "while attempting put\n", $userinput);       "while attempting put\n", $userinput);
       }   }
    } else {      } else {
       Failure( $client, "refused\n", $userinput);   Failure( $client, "refused\n", $userinput);
    }      }
         
    return 1;      return 1;
 }  }
 RegisterHandler("put", \&PutUserProfileEntry, 0, 1, 0);  RegisterHandler("put", \&PutUserProfileEntry, 0, 1, 0);
   
Line 1358  RegisterHandler("put", \&PutUserProfileE Line 1357  RegisterHandler("put", \&PutUserProfileE
 #     1        - Continue processing.  #     1        - Continue processing.
 #  #
 sub IncrementUserValueHandler {  sub IncrementUserValueHandler {
    my $cmd         = shift;      my $cmd         = shift;
    my $tail        = shift;      my $tail        = shift;
    my $client      = shift;      my $client      = shift;
    my $userinput   = shift;      my $userinput   = shift;
   
    my ($udom,$uname,$namespace,$what) =split(/:/,$tail);      my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
    $namespace=~s/\//\_/g;      $namespace=~s/\//\_/g;
    $namespace=~s/\W//g;      $namespace=~s/\W//g;
    if ($namespace ne 'roles') {      if ($namespace ne 'roles') {
       chomp($what);   chomp($what);
       my $proname=propath($udom,$uname);   my $proname=propath($udom,$uname);
       my $now=time;   my $now=time;
       unless ($namespace=~/^nohist\_/) {   unless ($namespace=~/^nohist\_/) {
          my $hfh;      my $hfh;
          if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {       if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { 
             print $hfh "P:$now:$what\n";   print $hfh "P:$now:$what\n";
          }      }
       }   }
       my @pairs=split(/\&/,$what);   my @pairs=split(/\&/,$what);
       my %hash;   my %hash;
       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),   if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),
                0640)) {   0640)) {
          foreach my $pair (@pairs) {      foreach my $pair (@pairs) {
             my ($key,$value)=split(/=/,$pair);   my ($key,$value)=split(/=/,$pair);
             # We could check that we have a number...   # We could check that we have a number...
             if (! defined($value) || $value eq '') {   if (! defined($value) || $value eq '') {
                $value = 1;      $value = 1;
             }   }
             $hash{$key}+=$value;   $hash{$key}+=$value;
          }      }
          if (untie(%hash)) {      if (untie(%hash)) {
             Reply( $client, "ok\n", $userinput);   Reply( $client, "ok\n", $userinput);
          } else {      } else {
             Failure($client, "error: ".($!+0)." untie(GDBM) failed ".   Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                      "while attempting put\n", $userinput);   "while attempting put\n", $userinput);
          }      }
       } else {   } else {
          Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".      Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   "while attempting put\n", $userinput);      "while attempting put\n", $userinput);
       }   }
    } else {      } else {
       Failure($client, "refused\n", $userinput);   Failure($client, "refused\n", $userinput);
    }      }
   
    return 1;      return 1;
 }  }
 RegisterHandler("inc", \&IncrementUserValueHandler, 0, 1, 0);  RegisterHandler("inc", \&IncrementUserValueHandler, 0, 1, 0);
 #  #
Line 1426  RegisterHandler("inc", \&IncrementUserVa Line 1425  RegisterHandler("inc", \&IncrementUserVa
 #  #
 #  #
 sub RolesPutHandler {  sub RolesPutHandler {
    my $cmd        = shift;      my $cmd        = shift;
    my $tail       = shift;      my $tail       = shift;
    my $client     = shift;      my $client     = shift;
    my $userinput  = "$cmd:$tail";      my $userinput  = "$cmd:$tail";
      
    my ($exedom,$exeuser,$udom,$uname,$what)   =split(/:/,$tail);      my ($exedom,$exeuser,$udom,$uname,$what)   =split(/:/,$tail);
    &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.      &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
           "what = ".$what);     "what = ".$what);
    my $namespace='roles';      my $namespace='roles';
    chomp($what);      chomp($what);
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    my $now=time;      my $now=time;
    #      #
    #  Log the attempt to set a role.  The {}'s here ensure that the file       #  Log the attempt to set a role.  The {}'s here ensure that the file 
    #  handle is open for the minimal amount of time.  Since the flush      #  handle is open for the minimal amount of time.  Since the flush
    #  is done on close this improves the chances the log will be an un-      #  is done on close this improves the chances the log will be an un-
    #  corrupted ordered thing.      #  corrupted ordered thing.
    {      {
       my $hfh;   my $hfh;
       if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {    if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { 
          print $hfh "P:$now:$exedom:$exeuser:$what\n";      print $hfh "P:$now:$exedom:$exeuser:$what\n";
       }   }
    }      }
    my @pairs=split(/\&/,$what);      my @pairs=split(/\&/,$what);
    my %hash;      my %hash;
    if (tie(%hash,'GDBM_File',"$proname/$namespace.db", &GDBM_WRCREAT(),0640)) {      if (tie(%hash,'GDBM_File',"$proname/$namespace.db", &GDBM_WRCREAT(),0640)) {
       foreach my $pair (@pairs) {   foreach my $pair (@pairs) {
          my ($key,$value)=split(/=/,$pair);      my ($key,$value)=split(/=/,$pair);
             &ManagePermissions($key, $udom, $uname,              &ManagePermissions($key, $udom, $uname,
                                &GetAuthType( $udom, $uname));                                 &GetAuthType( $udom, $uname));
             $hash{$key}=$value;              $hash{$key}=$value;
       }   }
       if (untie(%hash)) {   if (untie(%hash)) {
          Reply($client, "ok\n", $userinput);      Reply($client, "ok\n", $userinput);
       } else {   } else {
          Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".      Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                          "while attempting rolesput\n", $userinput);       "while attempting rolesput\n", $userinput);
       }   }
    } else {      } else {
       Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".   Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                         "while attempting rolesput\n", $userinput);   "while attempting rolesput\n", $userinput);
    }      }
    return 1;      return 1;
 }  }
 RegisterHandler("rolesput", \&RolesPutHandler, 1,1,0);  # Encoded client only.  RegisterHandler("rolesput", \&RolesPutHandler, 1,1,0);  # Encoded client only.
 #  #
Line 1489  RegisterHandler("rolesput", \&RolesPutHa Line 1488  RegisterHandler("rolesput", \&RolesPutHa
 #     0                    - Exit.  #     0                    - Exit.
 #  #
 sub RolesDeleteHandler {  sub RolesDeleteHandler {
    my $cmd          = shift;      my $cmd          = shift;
    my $tail         = shift;      my $tail         = shift;
    my $client       = shift;      my $client       = shift;
    my $userinput    = "$cmd:$tail";      my $userinput    = "$cmd:$tail";
         
    my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);      my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
    &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.      &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
           "what = ".$what);     "what = ".$what);
    my $namespace='roles';      my $namespace='roles';
    chomp($what);      chomp($what);
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    my $now=time;      my $now=time;
    #      #
    #   Log the attempt. This {}'ing is done to ensure that the      #   Log the attempt. This {}'ing is done to ensure that the
    #   logfile is flushed and closed as quickly as possible.  Hopefully      #   logfile is flushed and closed as quickly as possible.  Hopefully
    #   this preserves both time ordering and reduces the probability that      #   this preserves both time ordering and reduces the probability that
    #   messages will be interleaved.      #   messages will be interleaved.
    #      #
    {      {
       my $hfh;   my $hfh;
       if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {    if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { 
          print $hfh "D:$now:$exedom:$exeuser:$what\n";      print $hfh "D:$now:$exedom:$exeuser:$what\n";
       }   }
    }      }
    my @rolekeys=split(/\&/,$what);      my @rolekeys=split(/\&/,$what);
    my %hash;      my %hash;
    if (tie(%hash,'GDBM_File',"$proname/$namespace.db", &GDBM_WRCREAT(),0640)) {      if (tie(%hash,'GDBM_File',"$proname/$namespace.db", &GDBM_WRCREAT(),0640)) {
       foreach my $key (@rolekeys) {   foreach my $key (@rolekeys) {
          delete $hash{$key};      delete $hash{$key};
       }   }
       if (untie(%hash)) {   if (untie(%hash)) {
          Reply($client, "ok\n", $userinput);      Reply($client, "ok\n", $userinput);
       } else {   } else {
          Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".      Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                            "while attempting rolesdel\n", $userinput);       "while attempting rolesdel\n", $userinput);
       }   }
    } else {      } else {
       Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".   Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                         "while attempting rolesdel\n", $userinput);   "while attempting rolesdel\n", $userinput);
    }      }
       
    return 1;      return 1;
 }  }
 RegisterHandler("rolesdel", \&RolesDeleteHandler, 1,1, 0); # Encoded client only  RegisterHandler("rolesdel", \&RolesDeleteHandler, 1,1, 0); # Encoded client only
   
Line 1554  RegisterHandler("rolesdel", \&RolesDelet Line 1553  RegisterHandler("rolesdel", \&RolesDelet
 #   0       - Exit.  #   0       - Exit.
 #  #
 sub GetProfileEntry {  sub GetProfileEntry {
    my $cmd      = shift;      my $cmd      = shift;
    my $tail     = shift;      my $tail     = shift;
    my $client   = shift;      my $client   = shift;
    my $userinput= "$cmd:$tail";      my $userinput= "$cmd:$tail";
         
    my ($udom,$uname,$namespace,$what) = split(/:/,$tail);      my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
    $namespace=~s/\//\_/g;      $namespace=~s/\//\_/g;
    $namespace=~s/\W//g;      $namespace=~s/\W//g;
    chomp($what);      chomp($what);
    my @queries=split(/\&/,$what);      my @queries=split(/\&/,$what);
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    my $qresult='';      my $qresult='';
    my %hash;      my %hash;
    if (tie(%hash,'GDBM_File',"$proname/$namespace.db", &GDBM_READER(),0640)) {      if (tie(%hash,'GDBM_File',"$proname/$namespace.db", &GDBM_READER(),0640)) {
       for (my $i=0;$i<=$#queries;$i++) {   for (my $i=0;$i<=$#queries;$i++) {
          $qresult.="$hash{$queries[$i]}&";    # Presumably failure gives empty string.      $qresult.="$hash{$queries[$i]}&";    # Presumably failure gives empty string.
       }   }
       if (untie(%hash)) {   if (untie(%hash)) {
          $qresult=~s/\&$//;              # Remove trailing & from last lookup.      $qresult=~s/\&$//;              # Remove trailing & from last lookup.
          Reply($client, "$qresult\n", $userinput);      Reply($client, "$qresult\n", $userinput);
       } else {   } else {
          Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".      Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                           "while attempting get\n", $userinput);      "while attempting get\n", $userinput);
       }   }
    } else {      } else {
       if ($!+0 == 2) {                # +0 coerces errno -> number 2 is ENOENT   if ($!+0 == 2) {               # +0 coerces errno -> number 2 is ENOENT
          Failure($client, "error:No such file or ".      Failure($client, "error:No such file or ".
                           "GDBM reported bad block error\n", $userinput);      "GDBM reported bad block error\n", $userinput);
       } else {                        # Some other undifferentiated err.   } else {                        # Some other undifferentiated err.
          Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".      Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                            "while attempting get\n", $userinput);      "while attempting get\n", $userinput);
       }   }
    }      }
    return 1;      return 1;
 }  }
 RegisterHandler("get", \&GetProfileEntry, 0,1,0);  RegisterHandler("get", \&GetProfileEntry, 0,1,0);
 #  #
Line 1610  RegisterHandler("get", \&GetProfileEntry Line 1609  RegisterHandler("get", \&GetProfileEntry
 #     1      - Continue processing  #     1      - Continue processing
 #     0      - server should exit.  #     0      - server should exit.
 sub GetProfileEntryEncrypted {  sub GetProfileEntryEncrypted {
    my $cmd       = shift;      my $cmd       = shift;
    my $tail      = shift;      my $tail      = shift;
    my $client    = shift;      my $client    = shift;
    my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
         
    my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);      my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
    $namespace=~s/\//\_/g;      $namespace=~s/\//\_/g;
    $namespace=~s/\W//g;      $namespace=~s/\W//g;
    chomp($what);      chomp($what);
    my @queries=split(/\&/,$what);      my @queries=split(/\&/,$what);
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    my $qresult='';      my $qresult='';
    my %hash;      my %hash;
    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {      if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
       for (my $i=0;$i<=$#queries;$i++) {   for (my $i=0;$i<=$#queries;$i++) {
          $qresult.="$hash{$queries[$i]}&";      $qresult.="$hash{$queries[$i]}&";
       }   }
       if (untie(%hash)) {   if (untie(%hash)) {
          $qresult=~s/\&$//;      $qresult=~s/\&$//;
          if ($cipher) {      if ($cipher) {
             my $cmdlength=length($qresult);   my $cmdlength=length($qresult);
             $qresult.="         ";   $qresult.="         ";
             my $encqresult='';   my $encqresult='';
             for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {   for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                $encqresult.= unpack("H16", $cipher->encrypt(substr($qresult,      $encqresult.= unpack("H16", $cipher->encrypt(substr($qresult,
                                                                    $encidx,   $encidx,
                                                                    8)));   8)));
             }   }
             Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);   Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
          } else {      } else {
             Failure( $client, "error:no_key\n", $userinput);   Failure( $client, "error:no_key\n", $userinput);
          }      }
       } else {   } else {
          Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".      Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                               "while attempting eget\n", $userinput);      "while attempting eget\n", $userinput);
       }   }
    } else {      } else {
       Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".   Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                        "while attempting eget\n", $userinput);   "while attempting eget\n", $userinput);
    }      }
                
    return 1;      return 1;
 }  }
 RegisterHandler("eget", \&GetProfileEncrypted, 0, 1, 0);  RegisterHandler("eget", \&GetProfileEncrypted, 0, 1, 0);
   
Line 1674  RegisterHandler("eget", \&GetProfileEncr Line 1673  RegisterHandler("eget", \&GetProfileEncr
 #  #
 #  #
 sub DeletProfileEntry {  sub DeletProfileEntry {
    my $cmd      = shift;      my $cmd      = shift;
    my $tail     = shift;      my $tail     = shift;
    my $client   = shift;      my $client   = shift;
    my $userinput = "cmd:$tail";      my $userinput = "cmd:$tail";
   
    my ($udom,$uname,$namespace,$what) = split(/:/,$tail);      my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
    $namespace=~s/\//\_/g;      $namespace=~s/\//\_/g;
    $namespace=~s/\W//g;      $namespace=~s/\W//g;
    chomp($what);      chomp($what);
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    my $now=time;      my $now=time;
    unless ($namespace=~/^nohist\_/) {      unless ($namespace=~/^nohist\_/) {
       my $hfh;   my $hfh;
       if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {    if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { 
          print $hfh "D:$now:$what\n";       print $hfh "D:$now:$what\n"; 
       }   }
    }      }
    my @keys=split(/\&/,$what);      my @keys=split(/\&/,$what);
    my %hash;      my %hash;
    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {      if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
       foreach my $key (@keys) {   foreach my $key (@keys) {
          delete($hash{$key});      delete($hash{$key});
       }   }
       if (untie(%hash)) {   if (untie(%hash)) {
          Reply($client, "ok\n", $userinput);      Reply($client, "ok\n", $userinput);
       } else {   } else {
          Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".      Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                            "while attempting del\n", $userinput);      "while attempting del\n", $userinput);
       }   }
    } else {      } else {
       Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".   Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                         "while attempting del\n", $userinput);   "while attempting del\n", $userinput);
    }      }
    return 1;      return 1;
 }  }
 RegisterHandler("del", \&DeleteProfileEntry, 0, 1, 0);  RegisterHandler("del", \&DeleteProfileEntry, 0, 1, 0);
 #  #
Line 1726  RegisterHandler("del", \&DeleteProfileEn Line 1725  RegisterHandler("del", \&DeleteProfileEn
 #    0    - Exit the server.  #    0    - Exit the server.
 #  #
 sub GetProfileKeys {  sub GetProfileKeys {
    my $cmd       = shift;      my $cmd       = shift;
    my $tail      = shift;      my $tail      = shift;
    my $client    = shift;      my $client    = shift;
    my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
    my ($udom,$uname,$namespace)=split(/:/,$tail);      my ($udom,$uname,$namespace)=split(/:/,$tail);
    $namespace=~s/\//\_/g;      $namespace=~s/\//\_/g;
    $namespace=~s/\W//g;      $namespace=~s/\W//g;
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    my $qresult='';      my $qresult='';
    my %hash;      my %hash;
    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {      if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
       foreach my $key (keys %hash) {   foreach my $key (keys %hash) {
           $qresult.="$key&";      $qresult.="$key&";
       }   }
       if (untie(%hash)) {   if (untie(%hash)) {
          $qresult=~s/\&$//;      $qresult=~s/\&$//;
          Reply($client, "$qresult\n", $userinput);      Reply($client, "$qresult\n", $userinput);
       } else {   } else {
          Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".      Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                           "while attempting keys\n", $userinput);      "while attempting keys\n", $userinput);
       }   }
    } else {      } else {
       Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".   Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                         "while attempting keys\n", $userinput);   "while attempting keys\n", $userinput);
    }      }
         
    return 1;      return 1;
 }  }
 RegisterHandler("keys", \&GetProfileKeys, 0, 1, 0);  RegisterHandler("keys", \&GetProfileKeys, 0, 1, 0);
 #  #
Line 1776  RegisterHandler("keys", \&GetProfileKeys Line 1775  RegisterHandler("keys", \&GetProfileKeys
 #     0    - Exit the server.  #     0    - Exit the server.
 #  #
 sub DumpProfileDatabase {  sub DumpProfileDatabase {
    my $cmd       = shift;      my $cmd       = shift;
    my $tail      = shift;      my $tail      = shift;
    my $client    = shift;      my $client    = shift;
    my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
         
    my ($udom,$uname,$namespace) = split(/:/,$tail);      my ($udom,$uname,$namespace) = split(/:/,$tail);
    $namespace=~s/\//\_/g;      $namespace=~s/\//\_/g;
    $namespace=~s/\W//g;      $namespace=~s/\W//g;
    my $qresult='';      my $qresult='';
    my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
    my %hash;      my %hash;
    if (tie(%hash,'GDBM_File',"$proname/$namespace.db", &GDBM_READER(),0640)) {      if (tie(%hash,'GDBM_File',"$proname/$namespace.db", &GDBM_READER(),0640)) {
       # Structure of %data:   # Structure of %data:
       # $data{$symb}->{$parameter}=$value;   # $data{$symb}->{$parameter}=$value;
       # $data{$symb}->{'v.'.$parameter}=$version;   # $data{$symb}->{'v.'.$parameter}=$version;
       # since $parameter will be unescaped, we do not   # since $parameter will be unescaped, we do not
       # have to worry about silly parameter names...   # have to worry about silly parameter names...
       my %data = ();                     # A hash of anonymous hashes..   my %data = ();                     # A hash of anonymous hashes..
       while (my ($key,$value) = each(%hash)) {   while (my ($key,$value) = each(%hash)) {
          my ($v,$symb,$param) = split(/:/,$key);      my ($v,$symb,$param) = split(/:/,$key);
          next if ($v eq 'version' || $symb eq 'keys');      next if ($v eq 'version' || $symb eq 'keys');
          next if (exists($data{$symb}) &&       next if (exists($data{$symb}) && 
                   exists($data{$symb}->{$param}) &&       exists($data{$symb}->{$param}) &&
                   $data{$symb}->{'v.'.$param} > $v);       $data{$symb}->{'v.'.$param} > $v);
          $data{$symb}->{$param}=$value;      $data{$symb}->{$param}=$value;
          $data{$symb}->{'v.'.$param}=$v;      $data{$symb}->{'v.'.$param}=$v;
       }   }
       if (untie(%hash)) {   if (untie(%hash)) {
          while (my ($symb,$param_hash) = each(%data)) {      while (my ($symb,$param_hash) = each(%data)) {
             while(my ($param,$value) = each (%$param_hash)){   while(my ($param,$value) = each (%$param_hash)){
                next if ($param =~ /^v\./);       # Ignore versions...      next if ($param =~ /^v\./);       # Ignore versions...
                #      #
                #   Just dump the symb=value pairs separated by &      #   Just dump the symb=value pairs separated by &
                #      #
                $qresult.=$symb.':'.$param.'='.$value.'&';      $qresult.=$symb.':'.$param.'='.$value.'&';
             }   }
          }      }
          chop($qresult);      chop($qresult);
          Reply($client , "$qresult\n", $userinput);      Reply($client , "$qresult\n", $userinput);
       } else {   } else {
          Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".      Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                            "while attempting currentdump\n", $userinput);       "while attempting currentdump\n", $userinput);
       }   }
    } else {      } else {
       Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".   Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                         "while attempting currentdump\n", $userinput);   "while attempting currentdump\n", $userinput);
    }      }
   
    return 1;      return 1;
 }  }
 RegisterHandler("currentdump", \&DumpProfileDatabase, 0, 1, 0);  RegisterHandler("currentdump", \&DumpProfileDatabase, 0, 1, 0);
 #  #
Line 1852  RegisterHandler("currentdump", \&DumpPro Line 1851  RegisterHandler("currentdump", \&DumpPro
 #    response is written to $client.  #    response is written to $client.
 #  #
 sub DumpWithRegexp {  sub DumpWithRegexp {
   my $cmd    = shift;      my $cmd    = shift;
   my $tail   = shift;      my $tail   = shift;
   my $client = shift;      my $client = shift;
   
   my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
   my ($udom,$uname,$namespace,$regexp)=split(/:/,$tail);      my ($udom,$uname,$namespace,$regexp)=split(/:/,$tail);
   $namespace=~s/\//\_/g;      $namespace=~s/\//\_/g;
   $namespace=~s/\W//g;      $namespace=~s/\W//g;
   if (defined($regexp)) {      if (defined($regexp)) {
     $regexp=&unescape($regexp);   $regexp=&unescape($regexp);
   } else {      } else {
     $regexp='.';   $regexp='.';
   }      }
   my $qresult='';      my $qresult='';
   my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
   my %hash;      my %hash;
   if (tie(%hash,'GDBM_File',"$proname/$namespace.db",      if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
   &GDBM_READER(),0640)) {      &GDBM_READER(),0640)) {
     study($regexp);   study($regexp);
     while (my ($key,$value) = each(%hash)) {   while (my ($key,$value) = each(%hash)) {
       if ($regexp eq '.') {      if ($regexp eq '.') {
  $qresult.=$key.'='.$value.'&';   $qresult.=$key.'='.$value.'&';
       } else {      } else {
  my $unescapeKey = &unescape($key);   my $unescapeKey = &unescape($key);
  if (eval('$unescapeKey=~/$regexp/')) {   if (eval('$unescapeKey=~/$regexp/')) {
   $qresult.="$key=$value&";      $qresult.="$key=$value&";
  }   }
       }      }
     }   }
     if (untie(%hash)) {   if (untie(%hash)) {
       chop($qresult);      chop($qresult);
       Reply($client, "$qresult\n", $userinput);      Reply($client, "$qresult\n", $userinput);
     } else {   } else {
       Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".      Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
        "while attempting dump\n", $userinput);       "while attempting dump\n", $userinput);
     }   }
   } else {      } else {
     Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".   Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
     "while attempting dump\n", $userinput);   "while attempting dump\n", $userinput);
   }      }
   
     return 1;      return 1;
 }  }
Line 1917  RegisterHandler("dump", \&DumpWithRegexp Line 1916  RegisterHandler("dump", \&DumpWithRegexp
 #  Side-Effects:  #  Side-Effects:
 #    Writes to the client  #    Writes to the client
 sub StoreHandler {  sub StoreHandler {
   my $cmd    = shift;      my $cmd    = shift;
   my $tail   = shift;      my $tail   = shift;
   my $client = shift;      my $client = shift;
     
   my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
   my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);      my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
   $namespace=~s/\//\_/g;      $namespace=~s/\//\_/g;
   $namespace=~s/\W//g;      $namespace=~s/\W//g;
   if ($namespace ne 'roles') {      if ($namespace ne 'roles') {
     chomp($what);   chomp($what);
     my $proname=propath($udom,$uname);   my $proname=propath($udom,$uname);
     my $now=time;   my $now=time;
     unless ($namespace=~/^nohist\_/) {   unless ($namespace=~/^nohist\_/) {
       my $hfh;      my $hfh;
       if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {      if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
  print $hfh "P:$now:$rid:$what\n";    print $hfh "P:$now:$rid:$what\n"; 
       }      }
    }
    my @pairs=split(/\&/,$what);
    my %hash;
    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
    &GDBM_WRCREAT(),0640)) {
       my @previouskeys=split(/&/,$hash{"keys:$rid"});
       my $key;
       $hash{"version:$rid"}++;
       my $version=$hash{"version:$rid"};
       my $allkeys=''; 
       foreach my $pair (@pairs) {
    my ($key,$value)=split(/=/,$pair);
    $allkeys.=$key.':';
    $hash{"$version:$rid:$key"}=$value;
       }
       $hash{"$version:$rid:timestamp"}=$now;
       $allkeys.='timestamp';
       $hash{"$version:keys:$rid"}=$allkeys;
       if (untie(%hash)) {
    Reply($client, "ok\n", $userinput);
       } else {
    Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
    "while attempting store\n", $userinput);
       }
    } else {
       Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
        "while attempting store\n", $userinput);
    }
       } else {
    Failure($client, "refused\n", $userinput);
     }      }
     my @pairs=split(/\&/,$what);  
     my %hash;  
     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",  
     &GDBM_WRCREAT(),0640)) {  
       my @previouskeys=split(/&/,$hash{"keys:$rid"});  
       my $key;  
       $hash{"version:$rid"}++;  
       my $version=$hash{"version:$rid"};  
       my $allkeys='';   
       foreach my $pair (@pairs) {  
  my ($key,$value)=split(/=/,$pair);  
  $allkeys.=$key.':';  
  $hash{"$version:$rid:$key"}=$value;  
       }  
       $hash{"$version:$rid:timestamp"}=$now;  
       $allkeys.='timestamp';  
       $hash{"$version:keys:$rid"}=$allkeys;  
       if (untie(%hash)) {  
  Reply($client, "ok\n", $userinput);  
       } else {  
  Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".  
  "while attempting store\n", $userinput);  
       }  
     } else {  
       Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".  
        "while attempting store\n", $userinput);  
     }  
   } else {  
     Failure($client, "refused\n", $userinput);  
   }  
   
   return 1;      return 1;
 }  }
 RegisterHandler("store", \&StoreHandler, 0, 1, 0);  RegisterHandler("store", \&StoreHandler, 0, 1, 0);
 #  #
Line 1987  RegisterHandler("store", \&StoreHandler, Line 1986  RegisterHandler("store", \&StoreHandler,
 #   Writes a reply to the client.  #   Writes a reply to the client.
 #  #
 sub RestoreHandler {  sub RestoreHandler {
   my $cmd     = shift;      my $cmd     = shift;
   my $tail    = shift;      my $tail    = shift;
   my $client  = shift;      my $client  = shift;
   
   my $userinput = "$cmd:$tail"; # Only used for logging purposes.      my $userinput = "$cmd:$tail"; # Only used for logging purposes.
   
   my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);      my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
   $namespace=~s/\//\_/g;      $namespace=~s/\//\_/g;
   $namespace=~s/\W//g;      $namespace=~s/\W//g;
   chomp($rid);      chomp($rid);
   my $proname=propath($udom,$uname);      my $proname=propath($udom,$uname);
   my $qresult='';      my $qresult='';
   my %hash;      my %hash;
   if (tie(%hash,'GDBM_File',"$proname/$namespace.db",      if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
   &GDBM_READER(),0640)) {      &GDBM_READER(),0640)) {
     my $version=$hash{"version:$rid"};   my $version=$hash{"version:$rid"};
     $qresult.="version=$version&";   $qresult.="version=$version&";
     my $scope;   my $scope;
     for ($scope=1;$scope<=$version;$scope++) {   for ($scope=1;$scope<=$version;$scope++) {
       my $vkeys=$hash{"$scope:keys:$rid"};      my $vkeys=$hash{"$scope:keys:$rid"};
  my @keys=split(/:/,$vkeys);      my @keys=split(/:/,$vkeys);
       my $key;      my $key;
       $qresult.="$scope:keys=$vkeys&";      $qresult.="$scope:keys=$vkeys&";
       foreach $key (@keys) {      foreach $key (@keys) {
  $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";   $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
       }                                        }                                  
     }   }
      if (untie(%hash)) {   if (untie(%hash)) {
        $qresult=~s/\&$//;      $qresult=~s/\&$//;
        Reply( $client, "$qresult\n", $userinput);      Reply( $client, "$qresult\n", $userinput);
      } else {   } else {
        Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".      Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
        "while attempting restore\n", $userinput);      "while attempting restore\n", $userinput);
      }   }
   } else {      } else {
     Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".   Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
     "while attempting restore\n", $userinput);   "while attempting restore\n", $userinput);
   }      }
       
   return 1;      return 1;
   
   
 }  }
Line 2051  RegisterHandler("restor", \&RestoreHandl Line 2050  RegisterHandler("restor", \&RestoreHandl
 #  #
 #  #
 sub SendChatHandler {  sub SendChatHandler {
   my $cmd     = shift;      my $cmd     = shift;
   my $tail    = shift;      my $tail    = shift;
   my $client  = shift;      my $client  = shift;
       
   my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
   my ($cdom,$cnum,$newpost)=split(/\:/,$tail);      my ($cdom,$cnum,$newpost)=split(/\:/,$tail);
   &chatadd($cdom,$cnum,$newpost);      &chatadd($cdom,$cnum,$newpost);
   Reply($client, "ok\n", $userinput);      Reply($client, "ok\n", $userinput);
   
   return 1;      return 1;
 }  }
 RegisterHandler("chatsend", \&SendChatHandler, 0, 1, 0);  RegisterHandler("chatsend", \&SendChatHandler, 0, 1, 0);
 #  #
Line 2082  RegisterHandler("chatsend", \&SendChatHa Line 2081  RegisterHandler("chatsend", \&SendChatHa
 #    Response is written to the client.  #    Response is written to the client.
 #  #
 sub RetrieveChatHandler {  sub RetrieveChatHandler {
   my $cmd      = shift;      my $cmd      = shift;
   my $tail     = shift;      my $tail     = shift;
   my $client   = shift;      my $client   = shift;
   
   my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
   my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);      my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);
   my $reply='';      my $reply='';
   foreach (&getchat($cdom,$cnum,$udom,$uname)) {      foreach (&getchat($cdom,$cnum,$udom,$uname)) {
     $reply.=&escape($_).':';   $reply.=&escape($_).':';
   }      }
   $reply=~s/\:$//;      $reply=~s/\:$//;
   Reply($client, $reply."\n", $userinput);      Reply($client, $reply."\n", $userinput);
   
   
   return 1;      return 1;
 }  }
 RegisterHandler("chatretr", \&RetrieveChatHandler, 0, 1, 0);  RegisterHandler("chatretr", \&RetrieveChatHandler, 0, 1, 0);
 #  #
Line 2120  RegisterHandler("chatretr", \&RetrieveCh Line 2119  RegisterHandler("chatretr", \&RetrieveCh
 #    a reply is written to $client.  #    a reply is written to $client.
 #  #
 sub SendQueryHandler {  sub SendQueryHandler {
   my $cmd     = shift;      my $cmd     = shift;
   my $tail    = shift;      my $tail    = shift;
   my $client  = shift;      my $client  = shift;
   
   my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
   my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);      my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
   $query=~s/\n*$//g;      $query=~s/\n*$//g;
   Reply($client, "". sqlreply("$clientname\&$query".      Reply($client, "". sqlreply("$clientname\&$query".
       "\&$arg1"."\&$arg2"."\&$arg3")."\n",   "\&$arg1"."\&$arg2"."\&$arg3")."\n",
  $userinput);    $userinput);
       
   return 1;      return 1;
 }  }
 RegisterHandler("querysend", \&SendQueryHandler, 0, 1, 0);  RegisterHandler("querysend", \&SendQueryHandler, 0, 1, 0);
   
Line 2162  RegisterHandler("querysend", \&SendQuery Line 2161  RegisterHandler("querysend", \&SendQuery
 #    ok written to the client.  #    ok written to the client.
 #  #
 sub ReplyQueryHandler {  sub ReplyQueryHandler {
   my $cmd    = shift;      my $cmd    = shift;
   my $tail   = shift;      my $tail   = shift;
   my $client = shift;      my $client = shift;
   
   my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
   my ($cmd,$id,$reply)=split(/:/,$userinput);       my ($cmd,$id,$reply)=split(/:/,$userinput); 
   my $store;      my $store;
   my $execdir=$perlvar{'lonDaemons'};      my $execdir=$perlvar{'lonDaemons'};
   if ($store=IO::File->new(">$execdir/tmp/$id")) {      if ($store=IO::File->new(">$execdir/tmp/$id")) {
     $reply=~s/\&/\n/g;   $reply=~s/\&/\n/g;
          print $store $reply;   print $store $reply;
     close $store;   close $store;
     my $store2=IO::File->new(">$execdir/tmp/$id.end");   my $store2=IO::File->new(">$execdir/tmp/$id.end");
     print $store2 "done\n";   print $store2 "done\n";
     close $store2;   close $store2;
     Reply($client, "ok\n", $userinput);   Reply($client, "ok\n", $userinput);
   }      } else {
   else {   Failure($client, "error: ".($!+0)
     Failure($client, "error: ".($!+0)   ." IO::File->new Failed ".
     ." IO::File->new Failed ".   "while attempting queryreply\n", $userinput);
     "while attempting queryreply\n", $userinput);      }
   }  
     
   
   return 1;      return 1;
 }  }
 RegisterHandler("queryreply", \&ReplyQueryHandler, 0, 1, 0);  RegisterHandler("queryreply", \&ReplyQueryHandler, 0, 1, 0);
 #  #
Line 2209  RegisterHandler("queryreply", \&ReplyQue Line 2207  RegisterHandler("queryreply", \&ReplyQue
 #   reply is written to the client.  #   reply is written to the client.
 #  #
 sub PutCourseIdHandler {  sub PutCourseIdHandler {
   my $cmd    = shift;      my $cmd    = shift;
   my $tail   = shift;      my $tail   = shift;
   my $client = shift;      my $client = shift;
   
   my $userinput = "$cmd:$tail";  
   
   my ($udom,$what)=split(/:/,$tail);  
   chomp($what);  
   $udom=~s/\W//g;  
   my $proname=  
     "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";  
   my $now=time;  
   my @pairs=split(/\&/,$what);  
   my %hash;  
   if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {  
     foreach my $pair (@pairs) {  
       my ($key,$value)=split(/=/,$pair);  
       $hash{$key}=$value.':'.$now;  
     }  
     if (untie(%hash)) {  
       Reply($client, "ok\n", $userinput);  
     } else {  
       Failure( $client, "error: ".($!+0)  
        ." untie(GDBM) Failed ".  
        "while attempting courseidput\n", $userinput);  
     }  
   } else {  
     Failure( $client, "error: ".($!+0)  
      ." tie(GDBM) Failed ".  
      "while attempting courseidput\n", $userinput);  
   }  
   
   return 1;      my $userinput = "$cmd:$tail";
   
       my ($udom,$what)=split(/:/,$tail);
       chomp($what);
       $udom=~s/\W//g;
       my $proname=
    "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
       my $now=time;
       my @pairs=split(/\&/,$what);
       my %hash;
       if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
    foreach my $pair (@pairs) {
       my ($key,$value)=split(/=/,$pair);
       $hash{$key}=$value.':'.$now;
    }
    if (untie(%hash)) {
       Reply($client, "ok\n", $userinput);
    } else {
       Failure( $client, "error: ".($!+0)
        ." untie(GDBM) Failed ".
        "while attempting courseidput\n", $userinput);
    }
       } else {
    Failure( $client, "error: ".($!+0)
    ." tie(GDBM) Failed ".
    "while attempting courseidput\n", $userinput);
       }
   
       return 1;
 }  }
 RegisterHandler("courseidput", \&PutCourseIdHandler, 0, 1, 0);  RegisterHandler("courseidput", \&PutCourseIdHandler, 0, 1, 0);
   
Line 2269  RegisterHandler("courseidput", \&PutCour Line 2267  RegisterHandler("courseidput", \&PutCour
 # Side Effects:  # Side Effects:
 #   a reply is written to $client.  #   a reply is written to $client.
 sub DumpCourseIdHandler {  sub DumpCourseIdHandler {
   my $cmd    = shift;      my $cmd    = shift;
   my $tail   = shift;      my $tail   = shift;
   my $client = shift;      my $client = shift;
   
   my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
   my ($udom,$since,$description) =split(/:/,$tail);      my ($udom,$since,$description) =split(/:/,$tail);
   if (defined($description)) {      if (defined($description)) {
     $description=&unescape($description);   $description=&unescape($description);
   } else {      } else {
     $description='.';   $description='.';
   }      }
   unless (defined($since)) { $since=0; }      unless (defined($since)) { $since=0; }
   my $qresult='';      my $qresult='';
   my $proname = "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";      my $proname = "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
   my %hash;      my %hash;
   if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {      if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
     while (my ($key,$value) = each(%hash)) {   while (my ($key,$value) = each(%hash)) {
       my ($descr,$lasttime)=split(/\:/,$value);      my ($descr,$lasttime)=split(/\:/,$value);
       if ($lasttime<$since) {       if ($lasttime<$since) { 
  next;    next; 
       }      }
       if ($description eq '.') {      if ($description eq '.') {
  $qresult.=$key.'='.$descr.'&';   $qresult.=$key.'='.$descr.'&';
       } else {      } else {
  my $unescapeVal = &unescape($descr);   my $unescapeVal = &unescape($descr);
  if (eval('$unescapeVal=~/$description/i')) {   if (eval('$unescapeVal=~/$description/i')) {
   $qresult.="$key=$descr&";      $qresult.="$key=$descr&";
  }   }
       }      }
     }   }
     if (untie(%hash)) {   if (untie(%hash)) {
       chop($qresult);      chop($qresult);
       Reply($client, "$qresult\n", $userinput);      Reply($client, "$qresult\n", $userinput);
     } else {   } else {
       Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".      Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
       "while attempting courseiddump\n", $userinput);      "while attempting courseiddump\n", $userinput);
     }   }
   } else {      } else {
     Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".   Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
     "while attempting courseiddump\n", $userinput);   "while attempting courseiddump\n", $userinput);
   }      }
   
   
   return 1;      return 1;
 }  }
 RegisterHandler("courseiddump", \&DumpCourseIdHandler, 0, 1, 0);  RegisterHandler("courseiddump", \&DumpCourseIdHandler, 0, 1, 0);
 #  #
Line 2333  RegisterHandler("courseiddump", \&DumpCo Line 2331  RegisterHandler("courseiddump", \&DumpCo
 #     reply is written to $client.  #     reply is written to $client.
 #  #
 sub PutIdHandler {  sub PutIdHandler {
   my $cmd    = shift;      my $cmd    = shift;
   my $tail   = shift;      my $tail   = shift;
   my $client = shift;      my $client = shift;
   
   my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
   my ($udom,$what)=split(/:/,$tail);      my ($udom,$what)=split(/:/,$tail);
   chomp($what);      chomp($what);
   $udom=~s/\W//g;      $udom=~s/\W//g;
   my $proname="$perlvar{'lonUsersDir'}/$udom/ids";      my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
   my $now=time;      my $now=time;
   {      {
     my $hfh;   my $hfh;
     if ($hfh=IO::File->new(">>$proname.hist")) {    if ($hfh=IO::File->new(">>$proname.hist")) { 
       print $hfh "P:$now:$what\n";       print $hfh "P:$now:$what\n"; 
    }
       }
       my @pairs=split(/\&/,$what);
       my %hash;
       if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
    foreach my $pair (@pairs) {
       my ($key,$value)=split(/=/,$pair);
       $hash{$key}=$value;
    }
    if (untie(%hash)) {
       Reply($client, "ok\n", $userinput);
    } else {
       Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
       "while attempting idput\n", $userinput);
    }
       } else {
    Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
    "while attempting idput\n", $userinput);
     }      }
   }  
   my @pairs=split(/\&/,$what);  
   my %hash;  
   if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {  
     foreach my $pair (@pairs) {  
       my ($key,$value)=split(/=/,$pair);  
       $hash{$key}=$value;  
     }  
     if (untie(%hash)) {  
       Reply($client, "ok\n", $userinput);  
     } else {  
       Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".  
       "while attempting idput\n", $userinput);  
     }  
   } else {  
     Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".  
      "while attempting idput\n", $userinput);  
   }  
   
   return 1;      return 1;
 }  }
   
 RegisterHandler("idput", \&PutIdHandler, 0, 1, 0);  RegisterHandler("idput", \&PutIdHandler, 0, 1, 0);
Line 2392  RegisterHandler("idput", \&PutIdHandler, Line 2390  RegisterHandler("idput", \&PutIdHandler,
 #   An & separated list of results is written to $client.  #   An & separated list of results is written to $client.
 #  #
 sub GetIdHandler {  sub GetIdHandler {
   my $cmd    = shift;      my $cmd    = shift;
   my $tail   = shift;      my $tail   = shift;
   my $client = shift;      my $client = shift;
   
   my $userinput = "$client:$tail";      my $userinput = "$client:$tail";
   
   my ($udom,$what)=split(/:/,$tail);      my ($udom,$what)=split(/:/,$tail);
   chomp($what);      chomp($what);
   $udom=~s/\W//g;      $udom=~s/\W//g;
   my $proname="$perlvar{'lonUsersDir'}/$udom/ids";      my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
   my @queries=split(/\&/,$what);      my @queries=split(/\&/,$what);
   my $qresult='';      my $qresult='';
   my %hash;      my %hash;
   if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {      if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
     for (my $i=0;$i<=$#queries;$i++) {   for (my $i=0;$i<=$#queries;$i++) {
       $qresult.="$hash{$queries[$i]}&";      $qresult.="$hash{$queries[$i]}&";
     }   }
     if (untie(%hash)) {   if (untie(%hash)) {
       $qresult=~s/\&$//;      $qresult=~s/\&$//;
       Reply($client, "$qresult\n", $userinput);      Reply($client, "$qresult\n", $userinput);
     } else {   } else {
       Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".      Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
        "while attempting idget\n",$userinput);       "while attempting idget\n",$userinput);
     }   }
   } else {      } else {
     Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".   Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                         "while attempting idget\n",$userinput);   "while attempting idget\n",$userinput);
   }      }
   
   return 1;      return 1;
 }  }
   
 RegisterHandler("idget", \&GetIdHandler, 0, 1, 0);  RegisterHandler("idget", \&GetIdHandler, 0, 1, 0);
Line 2443  RegisterHandler("idget", \&GetIdHandler, Line 2441  RegisterHandler("idget", \&GetIdHandler,
 #   A file is created in the local filesystem.  #   A file is created in the local filesystem.
 #   A reply is sent to the client.  #   A reply is sent to the client.
 sub TmpPutHandler {  sub TmpPutHandler {
   my $cmd       = shift;      my $cmd       = shift;
   my $what      = shift;      my $what      = shift;
   my $client    = shift;      my $client    = shift;
   
   my $userinput = "$cmd:$what"; # Reconstruct for logging.      my $userinput = "$cmd:$what"; # Reconstruct for logging.
   
   
   my $store;      my $store;
   $tmpsnum++;      $tmpsnum++;
   my $id=$$.'_'.$clientip.'_'.$tmpsnum;      my $id=$$.'_'.$clientip.'_'.$tmpsnum;
   $id=~s/\W/\_/g;      $id=~s/\W/\_/g;
   $what=~s/\n//g;      $what=~s/\n//g;
   my $execdir=$perlvar{'lonDaemons'};      my $execdir=$perlvar{'lonDaemons'};
   if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {      if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
     print $store $what;   print $store $what;
     close $store;   close $store;
     Reply($client, "$id\n", $userinput);   Reply($client, "$id\n", $userinput);
   }      } else {
   else {   Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
     Failure( $client, "error: ".($!+0)."IO::File->new Failed ".   "while attempting tmpput\n", $userinput);
      "while attempting tmpput\n", $userinput);      }
   }      return 1;
   return 1;  
       
 }  }
 RegisterHandler("tmpput", \&TmpPutHandler, 0, 1, 0);  RegisterHandler("tmpput", \&TmpPutHandler, 0, 1, 0);
Line 2485  RegisterHandler("tmpput", \&TmpPutHandle Line 2482  RegisterHandler("tmpput", \&TmpPutHandle
   
 #  #
 sub TmpGetHandler {  sub TmpGetHandler {
   my $cmd       = shift;      my $cmd       = shift;
   my $id        = shift;      my $id        = shift;
   my $client    = shift;      my $client    = shift;
   my $userinput = "$cmd:$id";       my $userinput = "$cmd:$id"; 
   
   chomp($id);      chomp($id);
   $id=~s/\W/\_/g;      $id=~s/\W/\_/g;
   my $store;      my $store;
   my $execdir=$perlvar{'lonDaemons'};      my $execdir=$perlvar{'lonDaemons'};
   if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {      if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
     my $reply=<$store>;   my $reply=<$store>;
     Reply( $client, "$reply\n", $userinput);   Reply( $client, "$reply\n", $userinput);
     close $store;   close $store;
   }      } else {
   else {   Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
     Failure( $client, "error: ".($!+0)."IO::File->new Failed ".   "while attempting tmpget\n", $userinput);
      "while attempting tmpget\n", $userinput);      }
   }  
   
   return 1;      return 1;
 }  }
 RegisterHandler("tmpget", \&TmpGetHandler, 0, 1, 0);  RegisterHandler("tmpget", \&TmpGetHandler, 0, 1, 0);
 #  #
Line 2522  RegisterHandler("tmpget", \&TmpGetHandle Line 2518  RegisterHandler("tmpget", \&TmpGetHandle
 #   A file is deleted  #   A file is deleted
 #   A reply is sent to the client.  #   A reply is sent to the client.
 sub TmpDelHandler {  sub TmpDelHandler {
   my $cmd      = shift;      my $cmd      = shift;
   my $id       = shift;      my $id       = shift;
   my $client   = shift;      my $client   = shift;
   
   my $userinput= "$cmd:$id";      my $userinput= "$cmd:$id";
   
   chomp($id);  
   $id=~s/\W/\_/g;  
   my $execdir=$perlvar{'lonDaemons'};  
   if (unlink("$execdir/tmp/$id.tmp")) {  
     Reply($client, "ok\n", $userinput);  
   } else {  
     Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".  
      "while attempting tmpdel\n", $userinput);  
   }  
   
   return 1;      chomp($id);
       $id=~s/\W/\_/g;
       my $execdir=$perlvar{'lonDaemons'};
       if (unlink("$execdir/tmp/$id.tmp")) {
    Reply($client, "ok\n", $userinput);
       } else {
    Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
    "while attempting tmpdel\n", $userinput);
       }
   
       return 1;
   
 }  }
 RegisterHandler("tmpdel", \&TmpDelHandler, 0, 1, 0);  RegisterHandler("tmpdel", \&TmpDelHandler, 0, 1, 0);
Line 2559  RegisterHandler("tmpdel", \&TmpDelHandle Line 2555  RegisterHandler("tmpdel", \&TmpDelHandle
 #   The reply is written to  $client.  #   The reply is written to  $client.
 #  #
 sub LsHandler {  sub LsHandler {
   my $cmd     = shift;      my $cmd     = shift;
   my $ulsdir  = shift;      my $ulsdir  = shift;
   my $client  = shift;      my $client  = shift;
   
   my $userinput = "$cmd:$ulsdir";  
   
   my $ulsout='';  
   my $ulsfn;  
   if (-e $ulsdir) {  
     if(-d $ulsdir) {  
       if (opendir(LSDIR,$ulsdir)) {  
  while ($ulsfn=readdir(LSDIR)) {  
   my @ulsstats=stat($ulsdir.'/'.$ulsfn);  
   $ulsout.=$ulsfn.'&'.  
     join('&',@ulsstats).':';  
  }  
  closedir(LSDIR);  
       }  
     } else {  
       my @ulsstats=stat($ulsdir);  
       $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';  
     }  
   } else {  
     $ulsout='no_such_dir';  
   }  
   if ($ulsout eq '') { $ulsout='empty'; }  
   Reply($client, "$ulsout\n", $userinput);  
   
       my $userinput = "$cmd:$ulsdir";
   
   return 1;      my $ulsout='';
       my $ulsfn;
       if (-e $ulsdir) {
    if(-d $ulsdir) {
       if (opendir(LSDIR,$ulsdir)) {
    while ($ulsfn=readdir(LSDIR)) {
       my @ulsstats=stat($ulsdir.'/'.$ulsfn);
       $ulsout.=$ulsfn.'&'.
    join('&',@ulsstats).':';
    }
    closedir(LSDIR);
       }
    } else {
       my @ulsstats=stat($ulsdir);
       $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
    }
       } else {
    $ulsout='no_such_dir';
       }
       if ($ulsout eq '') { $ulsout='empty'; }
       Reply($client, "$ulsout\n", $userinput);
   
   
       return 1;
 }  }
 RegisterHandler("ls", \&LsHandler, 0, 1, 0);  RegisterHandler("ls", \&LsHandler, 0, 1, 0);
   
Line 2613  RegisterHandler("ls", \&LsHandler, 0, 1, Line 2609  RegisterHandler("ls", \&LsHandler, 0, 1,
 #   A reply is sent to $client.  #   A reply is sent to $client.
 #  #
 sub SetAnnounceHandler {  sub SetAnnounceHandler {
   my $cmd          = shift;      my $cmd          = shift;
   my $announcement = shift;      my $announcement = shift;
   my $client       = shift;      my $client       = shift;
       
   my $userinput    = "$cmd:$announcement";      my $userinput    = "$cmd:$announcement";
   
   chomp($announcement);      chomp($announcement);
   $announcement=&unescape($announcement);      $announcement=&unescape($announcement);
   if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.      if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
       '/announcement.txt')) {   '/announcement.txt')) {
     print $store $announcement;   print $store $announcement;
     close $store;   close $store;
     Reply($client, "ok\n", $userinput);   Reply($client, "ok\n", $userinput);
   } else {      } else {
     Failure($client, "error: ".($!+0)."\n", $userinput);   Failure($client, "error: ".($!+0)."\n", $userinput);
   }      }
   
   return 1;      return 1;
 }  }
 RegisterHandler("setannounce", \&SetAnnounceHandler, 0, 1, 0);  RegisterHandler("setannounce", \&SetAnnounceHandler, 0, 1, 0);
   
Line 2648  RegisterHandler("setannounce", \&SetAnno Line 2644  RegisterHandler("setannounce", \&SetAnno
 # Side Effects:  # Side Effects:
 #   Replies with version to $client.  #   Replies with version to $client.
 sub GetVersionHandler {  sub GetVersionHandler {
   my $client     = shift;      my $client     = shift;
   my $tail       = shift;      my $tail       = shift;
   my $client     = shift;      my $client     = shift;
   my $userinput  = $client;      my $userinput  = $client;
       
   Reply($client, &version($userinput)."\n", $userinput);      Reply($client, &version($userinput)."\n", $userinput);
   
   
   return 1;      return 1;
 }  }
 RegisterHandler("version", \&GetVersionHandler, 0, 1, 0);  RegisterHandler("version", \&GetVersionHandler, 0, 1, 0);
   
Line 2678  RegisterHandler("version", \&GetVersionH Line 2674  RegisterHandler("version", \&GetVersionH
 #     a reply is sent to the client.  #     a reply is sent to the client.
 #  #
 sub SelectHostHandler {  sub SelectHostHandler {
   my $cmd        = shift;      my $cmd        = shift;
   my $tail       = shift;      my $tail       = shift;
   my $socket     = shift;      my $socket     = shift;
       
   my $userinput  ="$cmd:$tail";      my $userinput  ="$cmd:$tail";
   
   Reply($client, &sethost($userinput)."\n", $userinput);      Reply($client, &sethost($userinput)."\n", $userinput);
   
   
   return 1;      return 1;
 }  }
 RegisterHandler("sethost", \&SelectHostHandler, 0, 1, 0);  RegisterHandler("sethost", \&SelectHostHandler, 0, 1, 0);
   
Line 2703  RegisterHandler("sethost", \&SelectHostH Line 2699  RegisterHandler("sethost", \&SelectHostH
 #   0      - Indicating the program should exit!!  #   0      - Indicating the program should exit!!
 #  #
 sub ExitHandler {  sub ExitHandler {
   my $cmd     = shift;      my $cmd     = shift;
   my $tail    = shift;      my $tail    = shift;
   my $client  = shift;      my $client  = shift;
   
   my $userinput = "$cmd:$tail";      my $userinput = "$cmd:$tail";
   
   &logthis("Client $clientip ($clientname) hanging up: $userinput");      &logthis("Client $clientip ($clientname) hanging up: $userinput");
   Reply($client, "bye\n", $userinput);      Reply($client, "bye\n", $userinput);
   $client->shutdown(2);        # shutdown the socket forcibly.      $client->shutdown(2);        # shutdown the socket forcibly.
   $client->close();      $client->close();
   
   return 0;      return 0;
 }  }
 RegisterHandler("exit", \&ExitHandler, 0, 1,1);  RegisterHandler("exit", \&ExitHandler, 0, 1,1);
 RegisterHandler("init", \&ExitHandler, 0, 1,1); # RE-init is like exit.  RegisterHandler("init", \&ExitHandler, 0, 1,1); # RE-init is like exit.
Line 2732  RegisterHandler("quit", \&ExitHandler, 0 Line 2728  RegisterHandler("quit", \&ExitHandler, 0
 #      1            - Accept additional requests from the client.  #      1            - Accept additional requests from the client.
 #  #
 sub ProcessRequest {  sub ProcessRequest {
    my $Request      = shift;      my $Request      = shift;
    my $KeepGoing    = 1; # Assume we're not asked to stop.      my $KeepGoing    = 1; # Assume we're not asked to stop.
           
    my $wasenc=0;      my $wasenc=0;
    my $userinput = $Request;   # for compatibility with oldcode <yeach>      my $userinput = $Request;   # for compatibility with oldcode <yeach>
   
   
 # ------------------------------------------------------------ See if encrypted  # ------------------------------------------------------------ See if encrypted
         
    if($userinput =~ /^enc/) {      if($userinput =~ /^enc/) {
       $wasenc = 1;   $wasenc = 1;
       $userinput = Decipher($userinput);   $userinput = Decipher($userinput);
       if(! $userinput) {   if(! $userinput) {
          Failure($client,"error:Encrypted data without negotiating key");      Failure($client,"error:Encrypted data without negotiating key");
          return 0;                      # Break off with this imposter.      return 0;                      # Break off with this imposter.
       }   }
    }      }
    # Split off the request keyword from the rest of the stuff.      # Split off the request keyword from the rest of the stuff.
         
    my ($command, $tail) = split(/:/, $userinput, 2);      my ($command, $tail) = split(/:/, $userinput, 2);
   
    Debug("Command received: $command, encoded = $wasenc");      Debug("Command received: $command, encoded = $wasenc");
   
         
 # ------------------------------------------------------------- Normal commands  # ------------------------------------------------------------- Normal commands
   
    #       # 
    #   If the command is in the hash, then execute it via the hash dispatch:      #   If the command is in the hash, then execute it via the hash dispatch:
    #      #
    if(defined $Dispatcher{$command}) {      if(defined $Dispatcher{$command}) {
   
       my $DispatchInfo = $Dispatcher{$command};   my $DispatchInfo = $Dispatcher{$command};
       my $Handler      = $$DispatchInfo[0];   my $Handler      = $$DispatchInfo[0];
       my $NeedEncode   = $$DispatchInfo[1];   my $NeedEncode   = $$DispatchInfo[1];
       my $ClientTypes  = $$DispatchInfo[2];   my $ClientTypes  = $$DispatchInfo[2];
       Debug("Matched dispatch hash: mustencode: $NeedEncode ClientType $ClientTypes");   Debug("Matched dispatch hash: mustencode: $NeedEncode ClientType $ClientTypes");
               
       #  Validate the request:   #  Validate the request:
               
       my $ok = 1;   my $ok = 1;
       my $requesterprivs = 0;   my $requesterprivs = 0;
       if(isClient()) {   if(isClient()) {
  $requesterprivs |= $CLIENT_OK;      $requesterprivs |= $CLIENT_OK;
       }   }
       if(isManager()) {   if(isManager()) {
  $requesterprivs |= $MANAGER_OK;      $requesterprivs |= $MANAGER_OK;
       }   }
       if($NeedEncode && (!$wasenc)) {   if($NeedEncode && (!$wasenc)) {
  Debug("Must encode but wasn't: $NeedEncode $wasenc");      Debug("Must encode but wasn't: $NeedEncode $wasenc");
          $ok = 0;      $ok = 0;
       }   }
       if(($ClientTypes & $requesterprivs) == 0) {   if(($ClientTypes & $requesterprivs) == 0) {
  Debug("Client not privileged to do this operation");      Debug("Client not privileged to do this operation");
  $ok = 0;      $ok = 0;
       }   }
   
       if($ok) {   if($ok) {
  Debug("Dispatching to handler $command $tail");      Debug("Dispatching to handler $command $tail");
          $KeepGoing = &$Handler($command, $tail, $client);      $KeepGoing = &$Handler($command, $tail, $client);
       } else {   } else {
  Debug("Refusing to dispatch because ok is false");      Debug("Refusing to dispatch because ok is false");
  Failure($client, "refused", $userinput);      Failure($client, "refused", $userinput);
       }   }
   
   
 # ------------------------------------------------------------- unknown command  # ------------------------------------------------------------- unknown command
   
    } else {      } else {
  # unknown command   # unknown command
       Failure($client, "unknown_cmd\n", $userinput);   Failure($client, "unknown_cmd\n", $userinput);
    }      }
   
     return $KeepGoing;      return $KeepGoing;
 }  }
Line 2839  sub ReadManagerTable { Line 2835  sub ReadManagerTable {
   
     #   Clean out the old table first..      #   Clean out the old table first..
   
    foreach my $key (keys %managers) {      foreach my $key (keys %managers) {
       delete $managers{$key};   delete $managers{$key};
    }      }
   
    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";      my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
    if (!open (MANAGERS, $tablename)) {      if (!open (MANAGERS, $tablename)) {
       logthis('<font color="red">No manager table.  Nobody can manage!!</font>');   logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
       return;   return;
    }      }
    while(my $host = <MANAGERS>) {      while(my $host = <MANAGERS>) {
       chomp($host);   chomp($host);
       if ($host =~ "^#") {                  # Comment line.   if ($host =~ "^#") {                  # Comment line.
          logthis('<font color="green"> Skipping line: '. "$host</font>\n");      logthis('<font color="green"> Skipping line: '. "$host</font>\n");
          next;      next;
       }   }
       if (!defined $hostip{$host}) { # This is a non cluster member   if (!defined $hostip{$host}) { # This is a non cluster member
     #  The entry is of the form:      #  The entry is of the form:
     #    cluname:hostname      #    cluname:hostname
     #  cluname - A 'cluster hostname' is needed in order to negotiate      #  cluname - A 'cluster hostname' is needed in order to negotiate
     #            the host key.      #            the host key.
     #  hostname- The dns name of the host.      #  hostname- The dns name of the host.
     #      #
           my($cluname, $dnsname) = split(/:/, $host);      my($cluname, $dnsname) = split(/:/, $host);
                 
           my $ip = gethostbyname($dnsname);      my $ip = gethostbyname($dnsname);
           if(defined($ip)) {                 # bad names don't deserve entry.      if(defined($ip)) {                 # bad names don't deserve entry.
             my $hostip = inet_ntoa($ip);   my $hostip = inet_ntoa($ip);
             $managers{$hostip} = $cluname;   $managers{$hostip} = $cluname;
             logthis('<font color="green"> registering manager '.   logthis('<font color="green"> registering manager '.
                     "$dnsname as $cluname with $hostip </font>\n");   "$dnsname as $cluname with $hostip </font>\n");
          }      }
       } else {   } else {
          logthis('<font color="green"> existing host'." $host</font>\n");      logthis('<font color="green"> existing host'." $host</font>\n");
          $managers{$hostip{$host}} = $host;  # Use info from cluster tab if clumemeber      $managers{$hostip{$host}} = $host;  # Use info from cluster tab if clumemeber
       }   }
    }      }
 }  }
   
 #  #
Line 2908  sub CopyFile { Line 2904  sub CopyFile {
   
     if(-e $oldfile) {      if(-e $oldfile) {
   
  # Read the old file.   # Read the old file.
   
  my $oldfh = IO::File->new("< $oldfile");   my $oldfh = IO::File->new("< $oldfile");
  if(!$oldfh) {   if(!$oldfh) {
Line 2961  sub AdjustHostContents { Line 2957  sub AdjustHostContents {
     my $adjusted;      my $adjusted;
     my $me        = $perlvar{'lonHostID'};      my $me        = $perlvar{'lonHostID'};
   
  foreach my $line (split(/\n/,$contents)) {      foreach my $line (split(/\n/,$contents)) {
  if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {   if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
     chomp($line);      chomp($line);
     my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);      my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
     if ($id eq $me) {      if ($id eq $me) {
           my $ip = gethostbyname($name);   my $ip = gethostbyname($name);
           my $ipnew = inet_ntoa($ip);   my $ipnew = inet_ntoa($ip);
          $ip = $ipnew;   $ip = $ipnew;
  #  Reconstruct the host line and append to adjusted:   #  Reconstruct the host line and append to adjusted:
   
    my $newline = "$id:$domain:$role:$name:$ip";   my $newline = "$id:$domain:$role:$name:$ip";
    if($maxcon ne "") { # Not all hosts have loncnew tuning params   if($maxcon ne "") { # Not all hosts have loncnew tuning params
      $newline .= ":$maxcon:$idleto:$mincon";      $newline .= ":$maxcon:$idleto:$mincon";
    }   }
    $adjusted .= $newline."\n";   $adjusted .= $newline."\n";
   
       } else { # Not me, pass unmodified.      } else { # Not me, pass unmodified.
    $adjusted .= $line."\n";   $adjusted .= $line."\n";
       }      }
  } else {                  # Blank or comment never re-written.   } else {                  # Blank or comment never re-written.
     $adjusted .= $line."\n"; # Pass blanks and comments as is.      $adjusted .= $line."\n"; # Pass blanks and comments as is.
  }   }
  }      }
  return $adjusted;      return $adjusted;
 }  }
 #  #
 #   InstallFile: Called to install an administrative file:  #   InstallFile: Called to install an administrative file:
Line 3007  sub InstallFile { Line 3003  sub InstallFile {
     my $TempFile = $Filename.".tmp";      my $TempFile = $Filename.".tmp";
   
     #  Open the file for write:      #  Open the file for write:
       
     my $fh = IO::File->new("> $TempFile"); # Write to temp.      my $fh = IO::File->new("> $TempFile"); # Write to temp.
     if(!(defined $fh)) {      if(!(defined $fh)) {
  &logthis('<font color="red"> Unable to create '.$TempFile."</font>");   &logthis('<font color="red"> Unable to create '.$TempFile."</font>");
  return 0;   return 0;
     }      }
     #  write the contents of the file:      #  write the contents of the file:
       
     print $fh ($Contents);       print $fh ($Contents); 
     $fh->close; # In case we ever have a filesystem w. locking      $fh->close; # In case we ever have a filesystem w. locking
   
Line 3097  sub PushFile { Line 3093  sub PushFile {
  return "error:$!";   return "error:$!";
     }      }
     &logthis('<font color="green"> Pushfile: backed up '      &logthis('<font color="green"> Pushfile: backed up '
     .$tablefile." to $backupfile</font>");       .$tablefile." to $backupfile</font>");
           
     #  If the file being pushed is the host file, we adjust the entry for ourself so that the      #  If the file being pushed is the host file, we adjust the entry for ourself so that the
     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible      #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
Line 3113  sub PushFile { Line 3109  sub PushFile {
   
     if(!InstallFile($tablefile, $contents)) {      if(!InstallFile($tablefile, $contents)) {
  &logthis('<font color="red"> Pushfile: unable to install '   &logthis('<font color="red"> Pushfile: unable to install '
  .$tablefile." $! </font>");   .$tablefile." $! </font>");
  return "error:$!";   return "error:$!";
     }      } else {
     else {  
  &logthis('<font color="green"> Installed new '.$tablefile   &logthis('<font color="green"> Installed new '.$tablefile
  ."</font>");   ."</font>");
   
     }      }
   
   
Line 3256  sub ApplyEdit { Line 3251  sub ApplyEdit {
     } elsif ($command eq "delete") {      } elsif ($command eq "delete") {
  $editor->DeleteLine($p1);         # p1 - key p2 null.   $editor->DeleteLine($p1);         # p1 - key p2 null.
     } else {          # Should not get here!!!      } else {          # Should not get here!!!
  die "Invalid command given to ApplyEdit $command"   die "Invalid command given to ApplyEdit $command";
     }      }
 }  }
 #  #
Line 3426  sub catchexception { Line 3421  sub catchexception {
     $SIG{__DIE__}='DEFAULT';      $SIG{__DIE__}='DEFAULT';
     &status("Catching exception");      &status("Catching exception");
     &logthis("<font color=red>CRITICAL: "      &logthis("<font color=red>CRITICAL: "
      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "       ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
      ."a crash with this error msg->[$error]</font>");       ."a crash with this error msg->[$error]</font>");
     &logthis('Famous last words: '.$status.' - '.$lastlog);      &logthis('Famous last words: '.$status.' - '.$lastlog);
     if ($client) { print $client "error: $error\n"; }      if ($client) { print $client "error: $error\n"; }
     $server->close();      $server->close();
Line 3453  undef $perlvarref; Line 3448  undef $perlvarref;
 # ----------------------------- Make sure this process is running from user=www  # ----------------------------- Make sure this process is running from user=www
 my $wwwid=getpwnam('www');  my $wwwid=getpwnam('www');
 if ($wwwid!=$<) {  if ($wwwid!=$<) {
    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";      my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
    my $subj="LON: $currenthostid User ID mismatch";      my $subj="LON: $currenthostid User ID mismatch";
    system("echo 'User ID mismatch.  lond must be run as user www.' |\      system("echo 'User ID mismatch.  lond must be run as user www.' |\
  mailto $emailto -s '$subj' > /dev/null");   mailto $emailto -s '$subj' > /dev/null");
    exit 1;      exit 1;
 }  }
   
 # --------------------------------------------- Check if other instance running  # --------------------------------------------- Check if other instance running
Line 3465  if ($wwwid!=$<) { Line 3460  if ($wwwid!=$<) {
 my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";  my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
   
 if (-e $pidfile) {  if (-e $pidfile) {
    my $lfh=IO::File->new("$pidfile");      my $lfh=IO::File->new("$pidfile");
    my $pide=<$lfh>;      my $pide=<$lfh>;
    chomp($pide);      chomp($pide);
    if (kill 0 => $pide) { die "already running"; }      if (kill 0 => $pide) { die "already running"; }
 }  }
   
 # ------------------------------------------------------------- Read hosts file  # ------------------------------------------------------------- Read hosts file
Line 3481  $server = IO::Socket::INET->new(LocalPor Line 3476  $server = IO::Socket::INET->new(LocalPor
                                 Proto     => 'tcp',                                  Proto     => 'tcp',
                                 Reuse     => 1,                                  Reuse     => 1,
                                 Listen    => 10 )                                  Listen    => 10 )
   or die "making socket: $@\n";      or die "making socket: $@\n";
   
 # --------------------------------------------------------- Do global variables  # --------------------------------------------------------- Do global variables
   
Line 3634  sub checkchildren { Line 3629  sub checkchildren {
     &status("Checking on the children (waiting for reports)");      &status("Checking on the children (waiting for reports)");
     foreach (sort keys %children) {      foreach (sort keys %children) {
         unless (-e "$docdir/lon-status/londchld/$_.txt") {          unless (-e "$docdir/lon-status/londchld/$_.txt") {
           eval {      eval {
             alarm(300);   alarm(300);
     &logthis('Child '.$_.' did not respond');   &logthis('Child '.$_.' did not respond');
     kill 9 => $_;   kill 9 => $_;
     #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";   #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
     #$subj="LON: $currenthostid killed lond process $_";   #$subj="LON: $currenthostid killed lond process $_";
     #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;   #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
     #$execdir=$perlvar{'lonDaemons'};   #$execdir=$perlvar{'lonDaemons'};
     #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;   #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
     alarm(0);   alarm(0);
   }      }
         }          }
     }      }
     $SIG{ALRM} = 'DEFAULT';      $SIG{ALRM} = 'DEFAULT';
Line 3712  sub Reply { Line 3707  sub Reply {
 #    client:  #    client:
 #  #
 sub Failure {  sub Failure {
    my $fd      = shift;      my $fd      = shift;
    my $reply   = shift;      my $reply   = shift;
    my $request = shift;      my $request = shift;
         
    $Failures++;      $Failures++;
    Reply($fd, $reply, $request);      # That's simple eh?      Reply($fd, $reply, $request);      # That's simple eh?
 }  }
 # ------------------------------------------------------------------ Log status  # ------------------------------------------------------------------ Log status
   
 sub logstatus {  sub logstatus {
    &status("Doing logging");      &status("Doing logging");
    my $docdir=$perlvar{'lonDocRoot'};      my $docdir=$perlvar{'lonDocRoot'};
    {      {
       my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");   my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
       print $fh $$."\t".$currenthostid."\t".$status."\t".$lastlog."\n";   print $fh $$."\t".$currenthostid."\t".$status."\t".$lastlog."\n";
       $fh->close();   $fh->close();
    }      }
    &status("Finished londstatus.txt");      &status("Finished londstatus.txt");
    {      {
       my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");   my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
       print $fh $status."\n".$lastlog."\n".time;   print $fh $status."\n".$lastlog."\n".time;
       $fh->close();   $fh->close();
    }      }
    ResetStatistics;      ResetStatistics;
    &status("Finished logging");      &status("Finished logging");
         
 }  }
   
Line 3761  sub status { Line 3756  sub status {
     my $local=localtime($now);      my $local=localtime($now);
     my $status = "lond: $what $local ";      my $status = "lond: $what $local ";
     if($Transactions) {      if($Transactions) {
        $status .= " Transactions: $Transactions Failed; $Failures";   $status .= " Transactions: $Transactions Failed; $Failures";
     }      }
     $0=$status;      $0=$status;
 }  }
Line 3795  sub reconlonc { Line 3790  sub reconlonc {
     &logthis("lonc at pid $loncpid responding, sending USR1");      &logthis("lonc at pid $loncpid responding, sending USR1");
             kill USR1 => $loncpid;              kill USR1 => $loncpid;
         } else {          } else {
     &logthis(      &logthis("<font color=red>CRITICAL: "
               "<font color=red>CRITICAL: "       ."lonc at pid $loncpid not responding, giving up</font>");
              ."lonc at pid $loncpid not responding, giving up</font>");  
         }          }
     } else {      } else {
       &logthis('<font color=red>CRITICAL: lonc not running, giving up</font>');   &logthis('<font color=red>CRITICAL: lonc not running, giving up</font>');
     }      }
 }  }
   
Line 3812  sub subreply { Line 3806  sub subreply {
     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",      my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                                       Type    => SOCK_STREAM,                                        Type    => SOCK_STREAM,
                                       Timeout => 10)                                        Timeout => 10)
        or return "con_lost";   or return "con_lost";
     print $sclient "$cmd\n";      print $sclient "$cmd\n";
     my $answer=<$sclient>;      my $answer=<$sclient>;
     chomp($answer);      chomp($answer);
Line 3821  sub subreply { Line 3815  sub subreply {
 }  }
   
 sub reply {  sub reply {
   my ($cmd,$server)=@_;      my ($cmd,$server)=@_;
   my $answer;      my $answer;
   if ($server ne $currenthostid) {       if ($server ne $currenthostid) { 
     $answer=subreply($cmd,$server);   $answer=subreply($cmd,$server);
     if ($answer eq 'con_lost') {   if ($answer eq 'con_lost') {
  $answer=subreply("ping",$server);      $answer=subreply("ping",$server);
         if ($answer ne $server) {      if ($answer ne $server) {
     &logthis("sub reply: answer != server answer is $answer, server is $server");   &logthis("sub reply: answer != server answer is $answer, server is $server");
            &reconlonc("$perlvar{'lonSockDir'}/$server");   &reconlonc("$perlvar{'lonSockDir'}/$server");
         }      }
         $answer=subreply($cmd,$server);      $answer=subreply($cmd,$server);
     }   }
   } else {      } else {
     $answer='self_reply';   $answer='self_reply';
   }       } 
   return $answer;      return $answer;
 }  }
   
 # -------------------------------------------------------------- Talk to lonsql  # -------------------------------------------------------------- Talk to lonsql
Line 3855  sub subsqlreply { Line 3849  sub subsqlreply {
     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",      my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                                       Type    => SOCK_STREAM,                                        Type    => SOCK_STREAM,
                                       Timeout => 10)                                        Timeout => 10)
        or return "con_lost";   or return "con_lost";
     print $sclient "$cmd\n";      print $sclient "$cmd\n";
     my $answer=<$sclient>;      my $answer=<$sclient>;
     chomp($answer);      chomp($answer);
Line 3948  sub make_new_child { Line 3942  sub make_new_child {
     $sigset = POSIX::SigSet->new(SIGINT);      $sigset = POSIX::SigSet->new(SIGINT);
     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";
       
     die "fork: $!" unless defined ($pid = fork);      die "fork: $!" unless defined ($pid = fork);
   
     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of      $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
Line 3988  sub make_new_child { Line 3982  sub make_new_child {
   
         &Authen::Krb5::init_context();          &Authen::Krb5::init_context();
         &Authen::Krb5::init_ets();          &Authen::Krb5::init_ets();
   
  &status('Accepted connection');   &status('Accepted connection');
 # =============================================================================  # =============================================================================
             # do something with the connection              # do something with the connection
Line 4015  sub make_new_child { Line 4009  sub make_new_child {
     &status("Waiting for init from $clientip $clientname");      &status("Waiting for init from $clientip $clientname");
     &logthis('<font color="yellow">INFO: Connection, '.      &logthis('<font color="yellow">INFO: Connection, '.
      $clientip.       $clientip.
   " ($clientname) connection type = $ConnectionType </font>" );       " ($clientname) connection type = $ConnectionType </font>" );
     &status("Connecting $clientip  ($clientname))");       &status("Connecting $clientip  ($clientname))"); 
     my $remotereq=<$client>;      my $remotereq=<$client>;
     $remotereq=~s/[^\w:]//g;      $remotereq=~s/[^\w:]//g;
Line 4023  sub make_new_child { Line 4017  sub make_new_child {
  &sethost("sethost:$perlvar{'lonHostID'}");   &sethost("sethost:$perlvar{'lonHostID'}");
  my $challenge="$$".time;   my $challenge="$$".time;
  print $client "$challenge\n";   print $client "$challenge\n";
  &status(   &status("Waiting for challenge reply from $clientip ($clientname)"); 
  "Waiting for challenge reply from $clientip ($clientname)");   
  $remotereq=<$client>;   $remotereq=<$client>;
  $remotereq=~s/\W//g;   $remotereq=~s/\W//g;
  if ($challenge eq $remotereq) {   if ($challenge eq $remotereq) {
     $clientok=1;      $clientok=1;
     print $client "ok\n";      print $client "ok\n";
  } else {   } else {
     &logthis(      &logthis("<font color=blue>WARNING: $clientip did not reply challenge</font>");
      "<font color=blue>WARNING: $clientip did not reply challenge</font>");  
     &status('No challenge reply '.$clientip);      &status('No challenge reply '.$clientip);
  }   }
     } else {      } else {
  &logthis(   &logthis("<font color=blue>WARNING: "
  "<font color=blue>WARNING: "  
  ."$clientip failed to initialize: >$remotereq< </font>");   ."$clientip failed to initialize: >$remotereq< </font>");
  &status('No init '.$clientip);   &status('No init '.$clientip);
     }      }
  } else {   } else {
     &logthis(      &logthis("<font color=blue>WARNING: Unknown client $clientip</font>");
      "<font color=blue>WARNING: Unknown client $clientip</font>");  
     &status('Hung up on '.$clientip);      &status('Hung up on '.$clientip);
  }   }
  if ($clientok) {   if ($clientok) {
Line 4104  sub make_new_child { Line 4094  sub make_new_child {
 #    user      - Name of the user for which the role is being put.  #    user      - Name of the user for which the role is being put.
 #    authtype  - The authentication type associated with the user.  #    authtype  - The authentication type associated with the user.
 #  #
 sub ManagePermissions  sub ManagePermissions {
 {  
     my $request = shift;      my $request = shift;
     my $domain  = shift;      my $domain  = shift;
     my $user    = shift;      my $user    = shift;
Line 4125  sub ManagePermissions Line 4114  sub ManagePermissions
   
 #     Returns the authorization type or nouser if there is no such user.  #     Returns the authorization type or nouser if there is no such user.
 #  #
 sub GetAuthType   sub GetAuthType {
 {  
     my $domain = shift;      my $domain = shift;
     my $user   = shift;      my $user   = shift;
   
Line 4146  sub GetAuthType Line 4134  sub GetAuthType
  }   }
   
  return "$authtype:$availinfo";   return "$authtype:$availinfo";
     }      } else {
     else {  
  Debug("Returning nouser");   Debug("Returning nouser");
  return "nouser";   return "nouser";
     }      }
Line 4256  sub currentversion { Line 4243  sub currentversion {
     my $version=-1;      my $version=-1;
     my $ulsdir='';      my $ulsdir='';
     if ($fname=~/^(.+)\/[^\/]+$/) {      if ($fname=~/^(.+)\/[^\/]+$/) {
        $ulsdir=$1;   $ulsdir=$1;
     }      }
     my ($fnamere1,$fnamere2);      my ($fnamere1,$fnamere2);
     # remove version if already specified      # remove version if already specified
Line 4313  sub subscribe { Line 4300  sub subscribe {
                     symlink($root.'.'.$extension,                      symlink($root.'.'.$extension,
                             $root.'.'.$currentversion.'.'.$extension);                              $root.'.'.$currentversion.'.'.$extension);
                     unless ($extension=~/\.meta$/) {                      unless ($extension=~/\.meta$/) {
                        symlink($root.'.'.$extension.'.meta',   symlink($root.'.'.$extension.'.meta',
                             $root.'.'.$currentversion.'.'.$extension.'.meta');   $root.'.'.$currentversion.'.'.$extension.'.meta');
     }      }
                 }                  }
             }              }

Removed from v.1.178.2.3  
changed lines
  Added in v.1.178.2.4


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