home *** CD-ROM | disk | FTP | other *** search
/ PCNET 2006 September - Disc 1 / PCNET_CD_2006_09.iso / linux / puppy-barebones-2.01r2.iso / pup_201.sfs / usr / lib / tcl8.5 / safe.tcl < prev    next >
Encoding:
Text File  |  2006-06-17  |  26.3 KB  |  910 lines

  1. # safe.tcl --
  2. #
  3. # This file provide a safe loading/sourcing mechanism for safe interpreters.
  4. # It implements a virtual path mecanism to hide the real pathnames from the
  5. # slave. It runs in a master interpreter and sets up data structure and
  6. # aliases that will be invoked when used from a slave interpreter.
  7. # See the safe.n man page for details.
  8. #
  9. # Copyright (c) 1996-1997 Sun Microsystems, Inc.
  10. #
  11. # See the file "license.terms" for information on usage and redistribution
  12. # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
  13. #
  14. # RCS: @(#) $Id: safe.tcl,v 1.15 2005/07/23 04:12:49 dgp Exp $
  15.  
  16. #
  17. # The implementation is based on namespaces. These naming conventions
  18. # are followed:
  19. # Private procs starts with uppercase.
  20. # Public  procs are exported and starts with lowercase
  21. #
  22.  
  23. # Needed utilities package
  24. package require opt 0.4.1;
  25.  
  26. # Create the safe namespace
  27. namespace eval ::safe {
  28.  
  29.     # Exported API:
  30.     namespace export interpCreate interpInit interpConfigure interpDelete \
  31.         interpAddToAccessPath interpFindInAccessPath setLogCmd
  32.  
  33.     ####
  34.     #
  35.     # Setup the arguments parsing
  36.     #
  37.     ####
  38.  
  39.     # Make sure that our temporary variable is local to this
  40.     # namespace.  [Bug 981733]
  41.     variable temp
  42.  
  43.     # Share the descriptions
  44.     set temp [::tcl::OptKeyRegister {
  45.     {-accessPath -list {} "access path for the slave"}
  46.     {-noStatics "prevent loading of statically linked pkgs"}
  47.     {-statics true "loading of statically linked pkgs"}
  48.     {-nestedLoadOk "allow nested loading"}
  49.     {-nested false "nested loading"}
  50.     {-deleteHook -script {} "delete hook"}
  51.     }]
  52.  
  53.     # create case (slave is optional)
  54.     ::tcl::OptKeyRegister {
  55.     {?slave? -name {} "name of the slave (optional)"}
  56.     } ::safe::interpCreate
  57.     # adding the flags sub programs to the command program
  58.     # (relying on Opt's internal implementation details)
  59.     lappend ::tcl::OptDesc(::safe::interpCreate) $::tcl::OptDesc($temp)
  60.  
  61.     # init and configure (slave is needed)
  62.     ::tcl::OptKeyRegister {
  63.     {slave -name {} "name of the slave"}
  64.     } ::safe::interpIC
  65.     # adding the flags sub programs to the command program
  66.     # (relying on Opt's internal implementation details)
  67.     lappend ::tcl::OptDesc(::safe::interpIC) $::tcl::OptDesc($temp)
  68.     # temp not needed anymore
  69.     ::tcl::OptKeyDelete $temp
  70.  
  71.  
  72.     # Helper function to resolve the dual way of specifying staticsok
  73.     # (either by -noStatics or -statics 0)
  74.     proc InterpStatics {} {
  75.     foreach v {Args statics noStatics} {
  76.         upvar $v $v
  77.     }
  78.     set flag [::tcl::OptProcArgGiven -noStatics];
  79.     if {$flag && (!$noStatics == !$statics) 
  80.               && ([::tcl::OptProcArgGiven -statics])} {
  81.         return -code error\
  82.             "conflicting values given for -statics and -noStatics"
  83.     }
  84.     if {$flag} {
  85.         return [expr {!$noStatics}]
  86.     } else {
  87.         return $statics
  88.     }
  89.     }
  90.  
  91.     # Helper function to resolve the dual way of specifying nested loading
  92.     # (either by -nestedLoadOk or -nested 1)
  93.     proc InterpNested {} {
  94.     foreach v {Args nested nestedLoadOk} {
  95.         upvar $v $v
  96.     }
  97.     set flag [::tcl::OptProcArgGiven -nestedLoadOk];
  98.     # note that the test here is the opposite of the "InterpStatics"
  99.     # one (it is not -noNested... because of the wanted default value)
  100.     if {$flag && (!$nestedLoadOk != !$nested) 
  101.               && ([::tcl::OptProcArgGiven -nested])} {
  102.         return -code error\
  103.             "conflicting values given for -nested and -nestedLoadOk"
  104.     }
  105.     if {$flag} {
  106.         # another difference with "InterpStatics"
  107.         return $nestedLoadOk
  108.     } else {
  109.         return $nested
  110.     }
  111.     }
  112.  
  113.     ####
  114.     #
  115.     #  API entry points that needs argument parsing :
  116.     #
  117.     ####
  118.  
  119.  
  120.     # Interface/entry point function and front end for "Create"
  121.     proc interpCreate {args} {
  122.     set Args [::tcl::OptKeyParse ::safe::interpCreate $args]
  123.     InterpCreate $slave $accessPath \
  124.         [InterpStatics] [InterpNested] $deleteHook
  125.     }
  126.  
  127.     proc interpInit {args} {
  128.     set Args [::tcl::OptKeyParse ::safe::interpIC $args]
  129.     if {![::interp exists $slave]} {
  130.         return -code error "\"$slave\" is not an interpreter"
  131.     }
  132.     InterpInit $slave $accessPath \
  133.         [InterpStatics] [InterpNested] $deleteHook;
  134.     }
  135.  
  136.     proc CheckInterp {slave} {
  137.     if {![IsInterp $slave]} {
  138.         return -code error \
  139.             "\"$slave\" is not an interpreter managed by ::safe::"
  140.     }
  141.     }
  142.  
  143.     # Interface/entry point function and front end for "Configure"
  144.     # This code is awfully pedestrian because it would need
  145.     # more coupling and support between the way we store the
  146.     # configuration values in safe::interp's and the Opt package
  147.     # Obviously we would like an OptConfigure
  148.     # to avoid duplicating all this code everywhere. -> TODO
  149.     # (the app should share or access easily the program/value
  150.     #  stored by opt)
  151.     # This is even more complicated by the boolean flags with no values
  152.     # that we had the bad idea to support for the sake of user simplicity
  153.     # in create/init but which makes life hard in configure...
  154.     # So this will be hopefully written and some integrated with opt1.0
  155.     # (hopefully for tcl8.1 ?)
  156.     proc interpConfigure {args} {
  157.     switch [llength $args] {
  158.         1 {
  159.         # If we have exactly 1 argument
  160.         # the semantic is to return all the current configuration
  161.         # We still call OptKeyParse though we know that "slave"
  162.         # is our given argument because it also checks
  163.         # for the "-help" option.
  164.         set Args [::tcl::OptKeyParse ::safe::interpIC $args]
  165.         CheckInterp $slave
  166.         set res {}
  167.         lappend res [list -accessPath [Set [PathListName $slave]]]
  168.         lappend res [list -statics    [Set [StaticsOkName $slave]]]
  169.         lappend res [list -nested     [Set [NestedOkName $slave]]]
  170.         lappend res [list -deleteHook [Set [DeleteHookName $slave]]]
  171.         join $res
  172.         }
  173.         2 {
  174.         # If we have exactly 2 arguments
  175.         # the semantic is a "configure get"
  176.         ::tcl::Lassign $args slave arg
  177.         # get the flag sub program (we 'know' about Opt's internal
  178.         # representation of data)
  179.         set desc [lindex [::tcl::OptKeyGetDesc ::safe::interpIC] 2]
  180.         set hits [::tcl::OptHits desc $arg]
  181.                 if {$hits > 1} {
  182.                     return -code error [::tcl::OptAmbigous $desc $arg]
  183.                 } elseif {$hits == 0} {
  184.                     return -code error [::tcl::OptFlagUsage $desc $arg]
  185.                 }
  186.         CheckInterp $slave
  187.         set item [::tcl::OptCurDesc $desc]
  188.         set name [::tcl::OptName $item]
  189.         switch -exact -- $name {
  190.             -accessPath {
  191.             return [list -accessPath [Set [PathListName $slave]]]
  192.             }
  193.             -statics {
  194.             return [list -statics    [Set [StaticsOkName $slave]]]
  195.             }
  196.             -nested {
  197.             return [list -nested     [Set [NestedOkName $slave]]]
  198.             }
  199.             -deleteHook {
  200.             return [list -deleteHook [Set [DeleteHookName $slave]]]
  201.             }
  202.             -noStatics {
  203.             # it is most probably a set in fact
  204.             # but we would need then to jump to the set part
  205.             # and it is not *sure* that it is a set action
  206.             # that the user want, so force it to use the
  207.             # unambigous -statics ?value? instead:
  208.             return -code error\
  209.                 "ambigous query (get or set -noStatics ?)\
  210.                 use -statics instead"
  211.             }
  212.             -nestedLoadOk {
  213.             return -code error\
  214.                 "ambigous query (get or set -nestedLoadOk ?)\
  215.                 use -nested instead"
  216.             }
  217.             default {
  218.             return -code error "unknown flag $name (bug)"
  219.             }
  220.         }
  221.         }
  222.         default {
  223.         # Otherwise we want to parse the arguments like init and create
  224.         # did
  225.         set Args [::tcl::OptKeyParse ::safe::interpIC $args]
  226.         CheckInterp $slave
  227.         # Get the current (and not the default) values of
  228.         # whatever has not been given:
  229.         if {![::tcl::OptProcArgGiven -accessPath]} {
  230.             set doreset 1
  231.             set accessPath [Set [PathListName $slave]]
  232.         } else {
  233.             set doreset 0
  234.         }
  235.         if {(![::tcl::OptProcArgGiven -statics]) \
  236.             && (![::tcl::OptProcArgGiven -noStatics]) } {
  237.             set statics    [Set [StaticsOkName $slave]]
  238.         } else {
  239.             set statics    [InterpStatics]
  240.         }
  241.         if {([::tcl::OptProcArgGiven -nested]) \
  242.             || ([::tcl::OptProcArgGiven -nestedLoadOk]) } {
  243.             set nested     [InterpNested]
  244.         } else {
  245.             set nested     [Set [NestedOkName $slave]]
  246.         }
  247.         if {![::tcl::OptProcArgGiven -deleteHook]} {
  248.             set deleteHook [Set [DeleteHookName $slave]]
  249.         }
  250.         # we can now reconfigure :
  251.         InterpSetConfig $slave $accessPath $statics $nested $deleteHook
  252.         # auto_reset the slave (to completly synch the new access_path)
  253.         if {$doreset} {
  254.             if {[catch {::interp eval $slave {auto_reset}} msg]} {
  255.             Log $slave "auto_reset failed: $msg"
  256.             } else {
  257.             Log $slave "successful auto_reset" NOTICE
  258.             }
  259.         }
  260.         }
  261.     }
  262.     }
  263.  
  264.  
  265.     ####
  266.     #
  267.     #  Functions that actually implements the exported APIs
  268.     #
  269.     ####
  270.  
  271.  
  272.     #
  273.     # safe::InterpCreate : doing the real job
  274.     #
  275.     # This procedure creates a safe slave and initializes it with the
  276.     # safe base aliases.
  277.     # NB: slave name must be simple alphanumeric string, no spaces,
  278.     # no (), no {},...  {because the state array is stored as part of the name}
  279.     #
  280.     # Returns the slave name.
  281.     #
  282.     # Optional Arguments : 
  283.     # + slave name : if empty, generated name will be used
  284.     # + access_path: path list controlling where load/source can occur,
  285.     #                if empty: the master auto_path will be used.
  286.     # + staticsok  : flag, if 0 :no static package can be loaded (load {} Xxx)
  287.     #                      if 1 :static packages are ok.
  288.     # + nestedok: flag, if 0 :no loading to sub-sub interps (load xx xx sub)
  289.     #                      if 1 : multiple levels are ok.
  290.     
  291.     # use the full name and no indent so auto_mkIndex can find us
  292.     proc ::safe::InterpCreate {
  293.     slave 
  294.     access_path
  295.     staticsok
  296.     nestedok
  297.     deletehook
  298.     } {
  299.     # Create the slave.
  300.     if {$slave ne ""} {
  301.         ::interp create -safe $slave
  302.     } else {
  303.         # empty argument: generate slave name
  304.         set slave [::interp create -safe]
  305.     }
  306.     Log $slave "Created" NOTICE
  307.  
  308.     # Initialize it. (returns slave name)
  309.     InterpInit $slave $access_path $staticsok $nestedok $deletehook
  310.     }
  311.  
  312.  
  313.     #
  314.     # InterpSetConfig (was setAccessPath) :
  315.     #    Sets up slave virtual auto_path and corresponding structure
  316.     #    within the master. Also sets the tcl_library in the slave
  317.     #    to be the first directory in the path.
  318.     #    Nb: If you change the path after the slave has been initialized
  319.     #    you probably need to call "auto_reset" in the slave in order that it
  320.     #    gets the right auto_index() array values.
  321.  
  322.     proc ::safe::InterpSetConfig {slave access_path staticsok\
  323.         nestedok deletehook} {
  324.  
  325.     # determine and store the access path if empty
  326.     if {$access_path eq ""} {
  327.         set access_path [uplevel \#0 set auto_path]
  328.         # Make sure that tcl_library is in auto_path
  329.         # and at the first position (needed by setAccessPath)
  330.         set where [lsearch -exact $access_path [info library]]
  331.         if {$where == -1} {
  332.         # not found, add it.
  333.         set access_path [concat [list [info library]] $access_path]
  334.         Log $slave "tcl_library was not in auto_path,\
  335.             added it to slave's access_path" NOTICE
  336.         } elseif {$where != 0} {
  337.         # not first, move it first
  338.         set access_path [concat [list [info library]]\
  339.             [lreplace $access_path $where $where]]
  340.         Log $slave "tcl_libray was not in first in auto_path,\
  341.             moved it to front of slave's access_path" NOTICE
  342.         
  343.         }
  344.  
  345.         # Add 1st level sub dirs (will searched by auto loading from tcl
  346.         # code in the slave using glob and thus fail, so we add them
  347.         # here so by default it works the same).
  348.         set access_path [AddSubDirs $access_path]
  349.     }
  350.  
  351.     Log $slave "Setting accessPath=($access_path) staticsok=$staticsok\
  352.         nestedok=$nestedok deletehook=($deletehook)" NOTICE
  353.  
  354.     # clear old autopath if it existed
  355.     set nname [PathNumberName $slave]
  356.     if {[Exists $nname]} {
  357.         set n [Set $nname]
  358.         for {set i 0} {$i<$n} {incr i} {
  359.         Unset [PathToken $i $slave]
  360.         }
  361.     }
  362.  
  363.     # build new one
  364.     set slave_auto_path {}
  365.     set i 0
  366.     foreach dir $access_path {
  367.         Set [PathToken $i $slave] $dir
  368.         lappend slave_auto_path "\$[PathToken $i]"
  369.         incr i
  370.     }
  371.     Set $nname $i
  372.     Set [PathListName $slave] $access_path
  373.     Set [VirtualPathListName $slave] $slave_auto_path
  374.  
  375.     Set [StaticsOkName $slave] $staticsok
  376.     Set [NestedOkName $slave] $nestedok
  377.     Set [DeleteHookName $slave] $deletehook
  378.  
  379.     SyncAccessPath $slave
  380.     }
  381.  
  382.     #
  383.     #
  384.     # FindInAccessPath:
  385.     #    Search for a real directory and returns its virtual Id
  386.     #    (including the "$")
  387. proc ::safe::interpFindInAccessPath {slave path} {
  388.     set access_path [GetAccessPath $slave]
  389.     set where [lsearch -exact $access_path $path]
  390.     if {$where == -1} {
  391.         return -code error "$path not found in access path $access_path"
  392.     }
  393.     return "\$[PathToken $where]"
  394.     }
  395.  
  396.     #
  397.     # addToAccessPath:
  398.     #    add (if needed) a real directory to access path
  399.     #    and return its virtual token (including the "$").
  400. proc ::safe::interpAddToAccessPath {slave path} {
  401.     # first check if the directory is already in there
  402.     if {![catch {interpFindInAccessPath $slave $path} res]} {
  403.         return $res
  404.     }
  405.     # new one, add it:
  406.     set nname [PathNumberName $slave]
  407.     set n [Set $nname]
  408.     Set [PathToken $n $slave] $path
  409.  
  410.     set token "\$[PathToken $n]"
  411.  
  412.     Lappend [VirtualPathListName $slave] $token
  413.     Lappend [PathListName $slave] $path
  414.     Set $nname [expr {$n+1}]
  415.  
  416.     SyncAccessPath $slave
  417.  
  418.     return $token
  419.     }
  420.  
  421.     # This procedure applies the initializations to an already existing
  422.     # interpreter. It is useful when you want to install the safe base
  423.     # aliases into a preexisting safe interpreter.
  424.     proc ::safe::InterpInit {
  425.     slave 
  426.     access_path
  427.     staticsok
  428.     nestedok
  429.     deletehook
  430.     } {
  431.  
  432.     # Configure will generate an access_path when access_path is
  433.     # empty.
  434.     InterpSetConfig $slave $access_path $staticsok $nestedok $deletehook
  435.  
  436.     # These aliases let the slave load files to define new commands
  437.  
  438.     # NB we need to add [namespace current], aliases are always
  439.     # absolute paths.
  440.     ::interp alias $slave source {} [namespace current]::AliasSource $slave
  441.     ::interp alias $slave load {} [namespace current]::AliasLoad $slave
  442.  
  443.     # This alias lets the slave use the encoding names, convertfrom,
  444.     # convertto, and system, but not "encoding system <name>" to set
  445.     # the system encoding.
  446.  
  447.     ::interp alias $slave encoding {} [namespace current]::AliasEncoding \
  448.         $slave
  449.  
  450.     # This alias lets the slave have access to a subset of the 'file'
  451.     # command functionality.
  452.  
  453.     AliasSubset $slave file file dir.* join root.* ext.* tail \
  454.         path.* split
  455.  
  456.     # This alias interposes on the 'exit' command and cleanly terminates
  457.     # the slave.
  458.  
  459.     ::interp alias $slave exit {} [namespace current]::interpDelete $slave
  460.  
  461.     # The allowed slave variables already have been set
  462.     # by Tcl_MakeSafe(3)
  463.  
  464.  
  465.     # Source init.tcl into the slave, to get auto_load and other
  466.     # procedures defined:
  467.  
  468.     if {[catch {::interp eval $slave\
  469.         {source [file join $tcl_library init.tcl]}} msg]} {
  470.         Log $slave "can't source init.tcl ($msg)"
  471.         error "can't source init.tcl into slave $slave ($msg)"
  472.     }
  473.  
  474.     return $slave
  475.     }
  476.  
  477.  
  478.     # Add (only if needed, avoid duplicates) 1 level of
  479.     # sub directories to an existing path list.
  480.     # Also removes non directories from the returned list.
  481.     proc AddSubDirs {pathList} {
  482.     set res {}
  483.     foreach dir $pathList {
  484.         if {[file isdirectory $dir]} {
  485.         # check that we don't have it yet as a children
  486.         # of a previous dir
  487.         if {[lsearch -exact $res $dir]<0} {
  488.             lappend res $dir
  489.         }
  490.         foreach sub [glob -directory $dir -nocomplain *] {
  491.             if {([file isdirectory $sub]) \
  492.                 && ([lsearch -exact $res $sub]<0) } {
  493.             # new sub dir, add it !
  494.                     lappend res $sub
  495.                 }
  496.         }
  497.         }
  498.     }
  499.     return $res
  500.     }
  501.  
  502.     # This procedure deletes a safe slave managed by Safe Tcl and
  503.     # cleans up associated state:
  504.  
  505. proc ::safe::interpDelete {slave} {
  506.  
  507.         Log $slave "About to delete" NOTICE
  508.  
  509.     # If the slave has a cleanup hook registered, call it.
  510.     # check the existance because we might be called to delete an interp
  511.     # which has not been registered with us at all
  512.     set hookname [DeleteHookName $slave]
  513.     if {[Exists $hookname]} {
  514.         set hook [Set $hookname]
  515.         if {![::tcl::Lempty $hook]} {
  516.         # remove the hook now, otherwise if the hook
  517.         # calls us somehow, we'll loop
  518.         Unset $hookname
  519.         if {[catch {{expand}$hook $slave} err]} {
  520.             Log $slave "Delete hook error ($err)"
  521.         }
  522.         }
  523.     }
  524.  
  525.     # Discard the global array of state associated with the slave, and
  526.     # delete the interpreter.
  527.  
  528.     set statename [InterpStateName $slave]
  529.     if {[Exists $statename]} {
  530.         Unset $statename
  531.     }
  532.  
  533.     # if we have been called twice, the interp might have been deleted
  534.     # already
  535.     if {[::interp exists $slave]} {
  536.         ::interp delete $slave
  537.         Log $slave "Deleted" NOTICE
  538.     }
  539.  
  540.     return
  541.     }
  542.  
  543.     # Set (or get) the loging mecanism 
  544.  
  545. proc ::safe::setLogCmd {args} {
  546.     variable Log
  547.     if {[llength $args] == 0} {
  548.     return $Log
  549.     } else {
  550.     if {[llength $args] == 1} {
  551.         set Log [lindex $args 0]
  552.     } else {
  553.         set Log $args
  554.     }
  555.     }
  556. }
  557.  
  558.     # internal variable
  559.     variable Log {}
  560.  
  561.     # ------------------- END OF PUBLIC METHODS ------------
  562.  
  563.  
  564.     #
  565.     # sets the slave auto_path to the master recorded value.
  566.     # also sets tcl_library to the first token of the virtual path.
  567.     #
  568.     proc SyncAccessPath {slave} {
  569.     set slave_auto_path [Set [VirtualPathListName $slave]]
  570.     ::interp eval $slave [list set auto_path $slave_auto_path]
  571.     Log $slave "auto_path in $slave has been set to $slave_auto_path"\
  572.         NOTICE
  573.     ::interp eval $slave [list set tcl_library [lindex $slave_auto_path 0]]
  574.     }
  575.  
  576.     # base name for storing all the slave states
  577.     # the array variable name for slave foo is thus "Sfoo"
  578.     # and for sub slave {foo bar} "Sfoo bar" (spaces are handled
  579.     # ok everywhere (or should))
  580.     # We add the S prefix to avoid that a slave interp called "Log"
  581.     # would smash our "Log" variable.
  582.     proc InterpStateName {slave} {
  583.     return "S$slave"
  584.     }
  585.  
  586.     # Check that the given slave is "one of us"
  587.     proc IsInterp {slave} {
  588.     expr {[Exists [InterpStateName $slave]] && [::interp exists $slave]}
  589.     }
  590.  
  591.     # returns the virtual token for directory number N
  592.     # if the slave argument is given, 
  593.     # it will return the corresponding master global variable name
  594.     proc PathToken {n {slave ""}} {
  595.     if {$slave ne ""} {
  596.         return "[InterpStateName $slave](access_path,$n)"
  597.     } else {
  598.         # We need to have a ":" in the token string so
  599.         # [file join] on the mac won't turn it into a relative
  600.         # path.
  601.         return "p(:$n:)"
  602.     }
  603.     }
  604.     # returns the variable name of the complete path list
  605.     proc PathListName {slave} {
  606.     return "[InterpStateName $slave](access_path)"
  607.     }
  608.     # returns the variable name of the complete path list
  609.     proc VirtualPathListName {slave} {
  610.     return "[InterpStateName $slave](access_path_slave)"
  611.     }
  612.     # returns the variable name of the number of items
  613.     proc PathNumberName {slave} {
  614.     return "[InterpStateName $slave](access_path,n)"
  615.     }
  616.     # returns the staticsok flag var name
  617.     proc StaticsOkName {slave} {
  618.     return "[InterpStateName $slave](staticsok)"
  619.     }
  620.     # returns the nestedok flag var name
  621.     proc NestedOkName {slave} {
  622.     return "[InterpStateName $slave](nestedok)"
  623.     }
  624.     # Run some code at the namespace toplevel
  625.     proc Toplevel {args} {
  626.     namespace eval [namespace current] $args
  627.     }
  628.     # set/get values
  629.     proc Set {args} {
  630.     Toplevel set {expand}$args
  631.     }
  632.     # lappend on toplevel vars
  633.     proc Lappend {args} {
  634.     Toplevel lappend {expand}$args
  635.     }
  636.     # unset a var/token (currently just an global level eval)
  637.     proc Unset {args} {
  638.     Toplevel unset {expand}$args
  639.     }
  640.     # test existance 
  641.     proc Exists {varname} {
  642.     Toplevel info exists $varname
  643.     }
  644.     # short cut for access path getting
  645.     proc GetAccessPath {slave} {
  646.     Set [PathListName $slave]
  647.     }
  648.     # short cut for statics ok flag getting
  649.     proc StaticsOk {slave} {
  650.     Set [StaticsOkName $slave]
  651.     }
  652.     # short cut for getting the multiples interps sub loading ok flag
  653.     proc NestedOk {slave} {
  654.     Set [NestedOkName $slave]
  655.     }
  656.     # interp deletion storing hook name
  657.     proc DeleteHookName {slave} {
  658.     return [InterpStateName $slave](cleanupHook)
  659.     }
  660.  
  661.     #
  662.     # translate virtual path into real path
  663.     #
  664.     proc TranslatePath {slave path} {
  665.     # somehow strip the namespaces 'functionality' out (the danger
  666.     # is that we would strip valid macintosh "../" queries... :
  667.     if {[string match "*::*" $path] || [string match "*..*" $path]} {
  668.         error "invalid characters in path $path"
  669.     }
  670.     set n [expr {[Set [PathNumberName $slave]]-1}]
  671.     for {} {$n>=0} {incr n -1} {
  672.         # fill the token virtual names with their real value
  673.         set [PathToken $n] [Set [PathToken $n $slave]]
  674.     }
  675.     # replaces the token by their value
  676.     subst -nobackslashes -nocommands $path
  677.     }
  678.  
  679.  
  680.     # Log eventually log an error
  681.     # to enable error logging, set Log to {puts stderr} for instance
  682.     proc Log {slave msg {type ERROR}} {
  683.     variable Log
  684.     if {[info exists Log] && [llength $Log]} {
  685.         {expand}$Log "$type for slave $slave : $msg"
  686.     }
  687.     }
  688.  
  689.  
  690.     # file name control (limit access to files/ressources that should be
  691.     # a valid tcl source file)
  692.     proc CheckFileName {slave file} {
  693.     # This used to limit what can be sourced to ".tcl" and forbid files
  694.     # with more than 1 dot and longer than 14 chars, but I changed that
  695.     # for 8.4 as a safe interp has enough internal protection already
  696.     # to allow sourcing anything. - hobbs
  697.  
  698.     if {![file exists $file]} {
  699.         # don't tell the file path
  700.         error "no such file or directory"
  701.     }
  702.  
  703.     if {![file readable $file]} {
  704.         # don't tell the file path
  705.         error "not readable"
  706.     }
  707.     }
  708.  
  709.  
  710.     # AliasSource is the target of the "source" alias in safe interpreters.
  711.  
  712.     proc AliasSource {slave args} {
  713.  
  714.     set argc [llength $args]
  715.     # Allow only "source filename"
  716.     if {$argc != 1} {
  717.         set msg "wrong # args: should be \"source fileName\""
  718.         Log $slave "$msg ($args)"
  719.         return -code error $msg
  720.     }
  721.     set file [lindex $args 0]
  722.     
  723.     # get the real path from the virtual one.
  724.     if {[catch {set file [TranslatePath $slave $file]} msg]} {
  725.         Log $slave $msg
  726.         return -code error "permission denied"
  727.     }
  728.     
  729.     # check that the path is in the access path of that slave
  730.     if {[catch {FileInAccessPath $slave $file} msg]} {
  731.         Log $slave $msg
  732.         return -code error "permission denied"
  733.     }
  734.  
  735.     # do the checks on the filename :
  736.     if {[catch {CheckFileName $slave $file} msg]} {
  737.         Log $slave "$file:$msg"
  738.         return -code error $msg
  739.     }
  740.  
  741.     # passed all the tests , lets source it:
  742.     if {[catch {::interp invokehidden $slave source $file} msg]} {
  743.         Log $slave $msg
  744.         return -code error "script error"
  745.     }
  746.     return $msg
  747.     }
  748.  
  749.     # AliasLoad is the target of the "load" alias in safe interpreters.
  750.  
  751.     proc AliasLoad {slave file args} {
  752.  
  753.     set argc [llength $args]
  754.     if {$argc > 2} {
  755.         set msg "load error: too many arguments"
  756.         Log $slave "$msg ($argc) {$file $args}"
  757.         return -code error $msg
  758.     }
  759.  
  760.     # package name (can be empty if file is not).
  761.     set package [lindex $args 0]
  762.  
  763.     # Determine where to load. load use a relative interp path
  764.     # and {} means self, so we can directly and safely use passed arg.
  765.     set target [lindex $args 1]
  766.     if {$target ne ""} {
  767.         # we will try to load into a sub sub interp
  768.         # check that we want to authorize that.
  769.         if {![NestedOk $slave]} {
  770.         Log $slave "loading to a sub interp (nestedok)\
  771.             disabled (trying to load $package to $target)"
  772.         return -code error "permission denied (nested load)"
  773.         }
  774.         
  775.     }
  776.  
  777.     # Determine what kind of load is requested
  778.     if {$file eq ""} {
  779.         # static package loading
  780.         if {$package eq ""} {
  781.         set msg "load error: empty filename and no package name"
  782.         Log $slave $msg
  783.         return -code error $msg
  784.         }
  785.         if {![StaticsOk $slave]} {
  786.         Log $slave "static packages loading disabled\
  787.             (trying to load $package to $target)"
  788.         return -code error "permission denied (static package)"
  789.         }
  790.     } else {
  791.         # file loading
  792.  
  793.         # get the real path from the virtual one.
  794.         if {[catch {set file [TranslatePath $slave $file]} msg]} {
  795.         Log $slave $msg
  796.         return -code error "permission denied"
  797.         }
  798.  
  799.         # check the translated path
  800.         if {[catch {FileInAccessPath $slave $file} msg]} {
  801.         Log $slave $msg
  802.         return -code error "permission denied (path)"
  803.         }
  804.     }
  805.  
  806.     if {[catch {::interp invokehidden\
  807.         $slave load $file $package $target} msg]} {
  808.         Log $slave $msg
  809.         return -code error $msg
  810.     }
  811.  
  812.     return $msg
  813.     }
  814.  
  815.     # FileInAccessPath raises an error if the file is not found in
  816.     # the list of directories contained in the (master side recorded) slave's
  817.     # access path.
  818.  
  819.     # the security here relies on "file dirname" answering the proper
  820.     # result.... needs checking ?
  821.     proc FileInAccessPath {slave file} {
  822.  
  823.     set access_path [GetAccessPath $slave]
  824.  
  825.     if {[file isdirectory $file]} {
  826.         error "\"$file\": is a directory"
  827.     }
  828.     set parent [file dirname $file]
  829.  
  830.     # Normalize paths for comparison since lsearch knows nothing of
  831.     # potential pathname anomalies.
  832.     set norm_parent [file normalize $parent]
  833.     foreach path $access_path {
  834.         lappend norm_access_path [file normalize $path]
  835.     }
  836.  
  837.     if {[lsearch -exact $norm_access_path $norm_parent] == -1} {
  838.         error "\"$file\": not in access_path"
  839.     }
  840.     }
  841.  
  842.     # This procedure enables access from a safe interpreter to only a subset of
  843.     # the subcommands of a command:
  844.  
  845.     proc Subset {slave command okpat args} {
  846.     set subcommand [lindex $args 0]
  847.     if {[regexp $okpat $subcommand]} {
  848.         return [$command {expand}$args]
  849.     }
  850.     set msg "not allowed to invoke subcommand $subcommand of $command"
  851.     Log $slave $msg
  852.     error $msg
  853.     }
  854.  
  855.     # This procedure installs an alias in a slave that invokes "safesubset"
  856.     # in the master to execute allowed subcommands. It precomputes the pattern
  857.     # of allowed subcommands; you can use wildcards in the pattern if you wish
  858.     # to allow subcommand abbreviation.
  859.     #
  860.     # Syntax is: AliasSubset slave alias target subcommand1 subcommand2...
  861.  
  862.     proc AliasSubset {slave alias target args} {
  863.     set pat ^(; set sep ""
  864.     foreach sub $args {
  865.         append pat $sep$sub
  866.         set sep |
  867.     }
  868.     append pat )\$
  869.     ::interp alias $slave $alias {}\
  870.         [namespace current]::Subset $slave $target $pat
  871.     }
  872.  
  873.     # AliasEncoding is the target of the "encoding" alias in safe interpreters.
  874.  
  875.     proc AliasEncoding {slave args} {
  876.  
  877.     set argc [llength $args]
  878.  
  879.     set okpat "^(name.*|convert.*)\$"
  880.     set subcommand [lindex $args 0]
  881.  
  882.     if {[regexp $okpat $subcommand]} {
  883.         return [::interp invokehidden $slave encoding {expand}$args]
  884.     }
  885.  
  886.     if {[string first $subcommand system] == 0} {
  887.         if {$argc == 1} {
  888.         # passed all the tests , lets source it:
  889.         if {[catch {::interp invokehidden \
  890.             $slave encoding system} msg]} {
  891.             Log $slave $msg
  892.             return -code error "script error"
  893.         }
  894.         } else {
  895.         set msg "wrong # args: should be \"encoding system\""
  896.         Log $slave $msg
  897.         error $msg
  898.         }
  899.     } else {
  900.         set msg "wrong # args: should be \"encoding option ?arg ...?\""
  901.         Log $slave $msg
  902.         error $msg
  903.     }
  904.  
  905.     return $msg
  906.     }
  907.  
  908. }
  909.