home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 November / CPNL0711.ISO / beeld / teken / scribus-1.3.3.9-win32-install.exe / tcl / tcl8.4 / safe.tcl < prev    next >
Text File  |  2004-07-02  |  28KB  |  925 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.9.2.2 2004/06/29 09:39:01 dkf 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 {[string equal "" $access_path]} {
  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.     # We don't try to use the -rsrc on the mac because it would get
  469.     # confusing if you would want to customize init.tcl
  470.     # for a given set of safe slaves, on all the platforms
  471.     # you just need to give a specific access_path and
  472.     # the mac should be no exception. As there is no
  473.     # obvious full "safe ressources" design nor implementation
  474.     # for the mac, safe interps there will just don't
  475.     # have that ability. (A specific app can still reenable
  476.     # that using custom aliases if they want to).
  477.     # It would also make the security analysis and the Safe Tcl security
  478.     # model platform dependant and thus more error prone.
  479.  
  480.     if {[catch {::interp eval $slave\
  481.         {source [file join $tcl_library init.tcl]}} msg]} {
  482.         Log $slave "can't source init.tcl ($msg)"
  483.         error "can't source init.tcl into slave $slave ($msg)"
  484.     }
  485.  
  486.     return $slave
  487.     }
  488.  
  489.  
  490.     # Add (only if needed, avoid duplicates) 1 level of
  491.     # sub directories to an existing path list.
  492.     # Also removes non directories from the returned list.
  493.     proc AddSubDirs {pathList} {
  494.     set res {}
  495.     foreach dir $pathList {
  496.         if {[file isdirectory $dir]} {
  497.         # check that we don't have it yet as a children
  498.         # of a previous dir
  499.         if {[lsearch -exact $res $dir]<0} {
  500.             lappend res $dir
  501.         }
  502.         foreach sub [glob -directory $dir -nocomplain *] {
  503.             if {([file isdirectory $sub]) \
  504.                 && ([lsearch -exact $res $sub]<0) } {
  505.             # new sub dir, add it !
  506.                     lappend res $sub
  507.                 }
  508.         }
  509.         }
  510.     }
  511.     return $res
  512.     }
  513.  
  514.     # This procedure deletes a safe slave managed by Safe Tcl and
  515.     # cleans up associated state:
  516.  
  517. proc ::safe::interpDelete {slave} {
  518.  
  519.         Log $slave "About to delete" NOTICE
  520.  
  521.     # If the slave has a cleanup hook registered, call it.
  522.     # check the existance because we might be called to delete an interp
  523.     # which has not been registered with us at all
  524.     set hookname [DeleteHookName $slave]
  525.     if {[Exists $hookname]} {
  526.         set hook [Set $hookname]
  527.         if {![::tcl::Lempty $hook]} {
  528.         # remove the hook now, otherwise if the hook
  529.         # calls us somehow, we'll loop
  530.         Unset $hookname
  531.         if {[catch {eval $hook [list $slave]} err]} {
  532.             Log $slave "Delete hook error ($err)"
  533.         }
  534.         }
  535.     }
  536.  
  537.     # Discard the global array of state associated with the slave, and
  538.     # delete the interpreter.
  539.  
  540.     set statename [InterpStateName $slave]
  541.     if {[Exists $statename]} {
  542.         Unset $statename
  543.     }
  544.  
  545.     # if we have been called twice, the interp might have been deleted
  546.     # already
  547.     if {[::interp exists $slave]} {
  548.         ::interp delete $slave
  549.         Log $slave "Deleted" NOTICE
  550.     }
  551.  
  552.     return
  553.     }
  554.  
  555.     # Set (or get) the loging mecanism 
  556.  
  557. proc ::safe::setLogCmd {args} {
  558.     variable Log
  559.     if {[llength $args] == 0} {
  560.     return $Log
  561.     } else {
  562.     if {[llength $args] == 1} {
  563.         set Log [lindex $args 0]
  564.     } else {
  565.         set Log $args
  566.     }
  567.     }
  568. }
  569.  
  570.     # internal variable
  571.     variable Log {}
  572.  
  573.     # ------------------- END OF PUBLIC METHODS ------------
  574.  
  575.  
  576.     #
  577.     # sets the slave auto_path to the master recorded value.
  578.     # also sets tcl_library to the first token of the virtual path.
  579.     #
  580.     proc SyncAccessPath {slave} {
  581.     set slave_auto_path [Set [VirtualPathListName $slave]]
  582.     ::interp eval $slave [list set auto_path $slave_auto_path]
  583.     Log $slave "auto_path in $slave has been set to $slave_auto_path"\
  584.         NOTICE
  585.     ::interp eval $slave [list set tcl_library [lindex $slave_auto_path 0]]
  586.     }
  587.  
  588.     # base name for storing all the slave states
  589.     # the array variable name for slave foo is thus "Sfoo"
  590.     # and for sub slave {foo bar} "Sfoo bar" (spaces are handled
  591.     # ok everywhere (or should))
  592.     # We add the S prefix to avoid that a slave interp called "Log"
  593.     # would smash our "Log" variable.
  594.     proc InterpStateName {slave} {
  595.     return "S$slave"
  596.     }
  597.  
  598.     # Check that the given slave is "one of us"
  599.     proc IsInterp {slave} {
  600.     expr {[Exists [InterpStateName $slave]] && [::interp exists $slave]}
  601.     }
  602.  
  603.     # returns the virtual token for directory number N
  604.     # if the slave argument is given, 
  605.     # it will return the corresponding master global variable name
  606.     proc PathToken {n {slave ""}} {
  607.     if {$slave ne ""} {
  608.         return "[InterpStateName $slave](access_path,$n)"
  609.     } else {
  610.         # We need to have a ":" in the token string so
  611.         # [file join] on the mac won't turn it into a relative
  612.         # path.
  613.         return "p(:$n:)"
  614.     }
  615.     }
  616.     # returns the variable name of the complete path list
  617.     proc PathListName {slave} {
  618.     return "[InterpStateName $slave](access_path)"
  619.     }
  620.     # returns the variable name of the complete path list
  621.     proc VirtualPathListName {slave} {
  622.     return "[InterpStateName $slave](access_path_slave)"
  623.     }
  624.     # returns the variable name of the number of items
  625.     proc PathNumberName {slave} {
  626.     return "[InterpStateName $slave](access_path,n)"
  627.     }
  628.     # returns the staticsok flag var name
  629.     proc StaticsOkName {slave} {
  630.     return "[InterpStateName $slave](staticsok)"
  631.     }
  632.     # returns the nestedok flag var name
  633.     proc NestedOkName {slave} {
  634.     return "[InterpStateName $slave](nestedok)"
  635.     }
  636.     # Run some code at the namespace toplevel
  637.     proc Toplevel {args} {
  638.     namespace eval [namespace current] $args
  639.     }
  640.     # set/get values
  641.     proc Set {args} {
  642.     eval [list Toplevel set] $args
  643.     }
  644.     # lappend on toplevel vars
  645.     proc Lappend {args} {
  646.     eval [list Toplevel lappend] $args
  647.     }
  648.     # unset a var/token (currently just an global level eval)
  649.     proc Unset {args} {
  650.     eval [list Toplevel unset] $args
  651.     }
  652.     # test existance 
  653.     proc Exists {varname} {
  654.     Toplevel info exists $varname
  655.     }
  656.     # short cut for access path getting
  657.     proc GetAccessPath {slave} {
  658.     Set [PathListName $slave]
  659.     }
  660.     # short cut for statics ok flag getting
  661.     proc StaticsOk {slave} {
  662.     Set [StaticsOkName $slave]
  663.     }
  664.     # short cut for getting the multiples interps sub loading ok flag
  665.     proc NestedOk {slave} {
  666.     Set [NestedOkName $slave]
  667.     }
  668.     # interp deletion storing hook name
  669.     proc DeleteHookName {slave} {
  670.     return [InterpStateName $slave](cleanupHook)
  671.     }
  672.  
  673.     #
  674.     # translate virtual path into real path
  675.     #
  676.     proc TranslatePath {slave path} {
  677.     # somehow strip the namespaces 'functionality' out (the danger
  678.     # is that we would strip valid macintosh "../" queries... :
  679.     if {[regexp {(::)|(\.\.)} $path]} {
  680.         error "invalid characters in path $path"
  681.     }
  682.     set n [expr {[Set [PathNumberName $slave]]-1}]
  683.     for {} {$n>=0} {incr n -1} {
  684.         # fill the token virtual names with their real value
  685.         set [PathToken $n] [Set [PathToken $n $slave]]
  686.     }
  687.     # replaces the token by their value
  688.     subst -nobackslashes -nocommands $path
  689.     }
  690.  
  691.  
  692.     # Log eventually log an error
  693.     # to enable error logging, set Log to {puts stderr} for instance
  694.     proc Log {slave msg {type ERROR}} {
  695.     variable Log
  696.     if {[info exists Log] && [llength $Log]} {
  697.         eval $Log [list "$type for slave $slave : $msg"]
  698.     }
  699.     }
  700.  
  701.  
  702.     # file name control (limit access to files/ressources that should be
  703.     # a valid tcl source file)
  704.     proc CheckFileName {slave file} {
  705.     # This used to limit what can be sourced to ".tcl" and forbid files
  706.     # with more than 1 dot and longer than 14 chars, but I changed that
  707.     # for 8.4 as a safe interp has enough internal protection already
  708.     # to allow sourcing anything. - hobbs
  709.  
  710.     if {![file exists $file]} {
  711.         # don't tell the file path
  712.         error "no such file or directory"
  713.     }
  714.  
  715.     if {![file readable $file]} {
  716.         # don't tell the file path
  717.         error "not readable"
  718.     }
  719.     }
  720.  
  721.  
  722.     # AliasSource is the target of the "source" alias in safe interpreters.
  723.  
  724.     proc AliasSource {slave args} {
  725.  
  726.     set argc [llength $args]
  727.     # Allow only "source filename"
  728.     # (and not mac specific -rsrc for instance - see comment in ::init
  729.     # for current rationale)
  730.     if {$argc != 1} {
  731.         set msg "wrong # args: should be \"source fileName\""
  732.         Log $slave "$msg ($args)"
  733.         return -code error $msg
  734.     }
  735.     set file [lindex $args 0]
  736.     
  737.     # get the real path from the virtual one.
  738.     if {[catch {set file [TranslatePath $slave $file]} msg]} {
  739.         Log $slave $msg
  740.         return -code error "permission denied"
  741.     }
  742.     
  743.     # check that the path is in the access path of that slave
  744.     if {[catch {FileInAccessPath $slave $file} msg]} {
  745.         Log $slave $msg
  746.         return -code error "permission denied"
  747.     }
  748.  
  749.     # do the checks on the filename :
  750.     if {[catch {CheckFileName $slave $file} msg]} {
  751.         Log $slave "$file:$msg"
  752.         return -code error $msg
  753.     }
  754.  
  755.     # passed all the tests , lets source it:
  756.     if {[catch {::interp invokehidden $slave source $file} msg]} {
  757.         Log $slave $msg
  758.         return -code error "script error"
  759.     }
  760.     return $msg
  761.     }
  762.  
  763.     # AliasLoad is the target of the "load" alias in safe interpreters.
  764.  
  765.     proc AliasLoad {slave file args} {
  766.  
  767.     set argc [llength $args]
  768.     if {$argc > 2} {
  769.         set msg "load error: too many arguments"
  770.         Log $slave "$msg ($argc) {$file $args}"
  771.         return -code error $msg
  772.     }
  773.  
  774.     # package name (can be empty if file is not).
  775.     set package [lindex $args 0]
  776.  
  777.     # Determine where to load. load use a relative interp path
  778.     # and {} means self, so we can directly and safely use passed arg.
  779.     set target [lindex $args 1]
  780.     if {[string length $target]} {
  781.         # we will try to load into a sub sub interp
  782.         # check that we want to authorize that.
  783.         if {![NestedOk $slave]} {
  784.         Log $slave "loading to a sub interp (nestedok)\
  785.             disabled (trying to load $package to $target)"
  786.         return -code error "permission denied (nested load)"
  787.         }
  788.         
  789.     }
  790.  
  791.     # Determine what kind of load is requested
  792.     if {[string length $file] == 0} {
  793.         # static package loading
  794.         if {[string length $package] == 0} {
  795.         set msg "load error: empty filename and no package name"
  796.         Log $slave $msg
  797.         return -code error $msg
  798.         }
  799.         if {![StaticsOk $slave]} {
  800.         Log $slave "static packages loading disabled\
  801.             (trying to load $package to $target)"
  802.         return -code error "permission denied (static package)"
  803.         }
  804.     } else {
  805.         # file loading
  806.  
  807.         # get the real path from the virtual one.
  808.         if {[catch {set file [TranslatePath $slave $file]} msg]} {
  809.         Log $slave $msg
  810.         return -code error "permission denied"
  811.         }
  812.  
  813.         # check the translated path
  814.         if {[catch {FileInAccessPath $slave $file} msg]} {
  815.         Log $slave $msg
  816.         return -code error "permission denied (path)"
  817.         }
  818.     }
  819.  
  820.     if {[catch {::interp invokehidden\
  821.         $slave load $file $package $target} msg]} {
  822.         Log $slave $msg
  823.         return -code error $msg
  824.     }
  825.  
  826.     return $msg
  827.     }
  828.  
  829.     # FileInAccessPath raises an error if the file is not found in
  830.     # the list of directories contained in the (master side recorded) slave's
  831.     # access path.
  832.  
  833.     # the security here relies on "file dirname" answering the proper
  834.     # result.... needs checking ?
  835.     proc FileInAccessPath {slave file} {
  836.  
  837.     set access_path [GetAccessPath $slave]
  838.  
  839.     if {[file isdirectory $file]} {
  840.         error "\"$file\": is a directory"
  841.     }
  842.     set parent [file dirname $file]
  843.  
  844.     # Normalize paths for comparison since lsearch knows nothing of
  845.     # potential pathname anomalies.
  846.     set norm_parent [file normalize $parent]
  847.     foreach path $access_path {
  848.         lappend norm_access_path [file normalize $path]
  849.     }
  850.  
  851.     if {[lsearch -exact $norm_access_path $norm_parent] == -1} {
  852.         error "\"$file\": not in access_path"
  853.     }
  854.     }
  855.  
  856.     # This procedure enables access from a safe interpreter to only a subset of
  857.     # the subcommands of a command:
  858.  
  859.     proc Subset {slave command okpat args} {
  860.     set subcommand [lindex $args 0]
  861.     if {[regexp $okpat $subcommand]} {
  862.         return [eval [list $command $subcommand] [lrange $args 1 end]]
  863.     }
  864.     set msg "not allowed to invoke subcommand $subcommand of $command"
  865.     Log $slave $msg
  866.     error $msg
  867.     }
  868.  
  869.     # This procedure installs an alias in a slave that invokes "safesubset"
  870.     # in the master to execute allowed subcommands. It precomputes the pattern
  871.     # of allowed subcommands; you can use wildcards in the pattern if you wish
  872.     # to allow subcommand abbreviation.
  873.     #
  874.     # Syntax is: AliasSubset slave alias target subcommand1 subcommand2...
  875.  
  876.     proc AliasSubset {slave alias target args} {
  877.     set pat ^(; set sep ""
  878.     foreach sub $args {
  879.         append pat $sep$sub
  880.         set sep |
  881.     }
  882.     append pat )\$
  883.     ::interp alias $slave $alias {}\
  884.         [namespace current]::Subset $slave $target $pat
  885.     }
  886.  
  887.     # AliasEncoding is the target of the "encoding" alias in safe interpreters.
  888.  
  889.     proc AliasEncoding {slave args} {
  890.  
  891.     set argc [llength $args]
  892.  
  893.     set okpat "^(name.*|convert.*)\$"
  894.     set subcommand [lindex $args 0]
  895.  
  896.     if {[regexp $okpat $subcommand]} {
  897.         return [eval ::interp invokehidden $slave encoding $subcommand \
  898.             [lrange $args 1 end]]
  899.     }
  900.  
  901.     if {[string match $subcommand system]} {
  902.         if {$argc == 1} {
  903.         # passed all the tests , lets source it:
  904.         if {[catch {::interp invokehidden \
  905.             $slave encoding system} msg]} {
  906.             Log $slave $msg
  907.             return -code error "script error"
  908.         }
  909.         } else {
  910.         set msg "wrong # args: should be \"encoding system\""
  911.         Log $slave $msg
  912.         error $msg
  913.         }
  914.     } else {
  915.         set msg "wrong # args: should be \"encoding option ?arg ...?\""
  916.         Log $slave $msg
  917.         error $msg
  918.     }
  919.  
  920.     return $msg
  921.     }
  922.  
  923. }
  924.