Websh Reference 3.6.0b5
$Id$
IntroductionGeneral remarks
Websh 3.6 (pronounced "web shell") embeds a Tcl interpreter,
(version 8.3 or higher) and all Tcl commands are available.
Typically, Websh commands have the following syntax:
web::acommandoptionssubcommandsarguments
Options start with a dash ("-"). As usual, dash-dash
("--") indicates the
"end-of-options". Thus,
web::acommand -o1 a1 -- -o2
takes "-o2" as the first argument.
Instead of the normal Tcl behaviour, Websh configuration
commands normally return the previous value when a new value
is set.
In addition to the examples given here, you might find http://tcl.apache.org/websh/examples.ws3
a useful source of information.
About this document
The original version of this document can always be found at
http://tcl.apache.org/websh/download/.
We try to keep this quick reference up-to-date and hope that
it will be useful. We do not guarantee that it is suitable for
any particular purpose whatsoever. The authors accept no
liability with regards to this information or its use.
Configurationweb::configweb::configkeyvalue
If is
ommitted, the current value of
is returned. Note that
unlike the set command
web::config always returns the value
for the given key before the new value is set.
This allows to keep the old value and set it back later.
Sets or gets the maximum number of bytes that will be saved, when
files are uploaded in a multipart form. Default: 0.
Sets or gets name of the command parameter in
the URL used to dispatch to web::command
using web::dispatch. Default: "cmd".
Sets or gets name of the timestamp parameter in the URL. Default:
"t".
Defines whether the timestamp should be included in URLs
generated by web::cmdurl. Default: 1 (yes)
Turns substitution of log messages on (1) or off (0). Default:
0 (off).
Makes web::log "safe" if set to 1
(i.e. it never throws an error even if corresponding I/O to
file, channel or command etc. fails). Default: 1 (on).
Sets or gets the markup characters for sections to be eval'd in
web::putx and web::putxfile
commands to either curly braces ({ ... }) or special tags (<?
... ?>). Default: "brace".
Sets or gets the list of commands that should be tried, in
sequence, to encrypt a message.
Default: "web::encryptd".
Sets or gets the list of commands that should be tried, in
sequence, to decrypt a message.
Default: "web::decryptd".
Sets or gets the file permissions of files that Websh creates.
This affects the creation of log files, filecounters, session
files, and temporary files created when files are uploaded in
multipart forms (see web::formvar). Default:
0644.
The following special subcommand is used to reset all configuration
options to their default values:
Resets all values to their defaults.
The following two subcommands are read-only and just return their
predefined values:
Returns the version info string.
Returns a copyright message string.
The following subcommands are also read-only. They return the
current request environment within mod_websh (and if applicable
in CGI mode):
Returns the path to the currently requestes Websh script.
Returns the Apache ServerRoot configuration path.
Returns the Apache DocumentRoot configuration path.
Returns the interpclass the current request was mapped to
(see web::interpmap command).
web::config
% web::config decryptchain
web::encryptd
% web::config filepermissions 0666
0644
% web::config filepermissions
0666
% web::config putxmarkup tag
brace
% web::config reset
% web::config filepermissions
0644
% web::config putxmarkup
brace
% Command dispatching and session management
Websh provides a command dispatching mechanism to produce,
for example, different HTML pages within one "application",
which is most likely one file on the file system. The name of
the command to be used for a particular page is encoded in the
querystring (see web::cmdurl for details on
how to produce such querystrings). Command dispatching is
initiated with the command web::dispatch.
Commands are defined with web::command.
web::commandweb::commandcmdNamecmdBody
Registers as
. If is
omitted, "default" is used.
Simple command dispatching
proc page {title code} {
web::put "<html><title>[web::htmlify $title]</title><body>"
web::put "<h1>[web::htmlify $title]</h1>"
uplevel 1 $code
web::put {</body></html>}
}
web::command default {
page "Home" {
web::put "<a href=\"[web::cmdurl page1]\">Link to Page 1</a>"
web::put "<br/>"
web::put "<a href=\"[web::cmdurl page2]\">Link to Page 2</a>"
}
}
web::command page1 {
page "Page 1" {
web::put "<a href=\"[web::cmdurl default]\">Home</a>"
}
}
web::command page2 {
page "Page 2" {
web::put "<a href=\"[web::cmdurl default]\">Home</a>"
}
}
web::dispatchweb::getcommandweb::getcommandcmdName
Retrieves the body of the command
or of the command "default" if
is omitted.
web::cmdurlweb::cmdurloptionscmdNamekey-value-listweb::cmdurloptionscmdNamek1 v1 ... kN vN
Options are: , and
Generate URLs including querystring. By default, URLs are
self-referencing, but the exact output is subject to
configuration. The querystring is encrypted, using the
encryption method specified by configuration (see
web::config). If
is "", no command parameter is produced in the query
string.
Tells Websh not to add a timestamp to URLs.
Specifies which items will be used to format just this
URL. Default: {scriptname pathinfo
querystring}.
Note: Use web::cmdurlcfg to define the
url format for all URLs produced by
web::cmdurl in one request.
Includes the protocol, only "http"
and "https" are currently supported.
Includes the host name,
e.g. "websh.com".
Includes the port,
e.g. "80" Trying to set
this item without host will throw an error.
Includes scriptname,
e.g. "/cgi-bin/orderbooks".
Includes pathinfo,
e.g. "/merchants/shop1".
Includes the querystring,
e.g. "select=download".
Note that there are two more commands that control
the output of web::cmdurl:
web::config
and
web::config .
web::cmdurl
% web::cmdurl -notimestamp -urlformat [list scheme host scriptname pathinfo querystring] "test"
http://websh.com/bin/returnmail/member?XDZuRD2rnsfHjFH
% web::cmdurlcfgweb::cmdurlcfgoptionkeyvalue
Command options are exactly like those of
web::param.
web::cmdurlcfgoptionvalue
Options are ,
, ,
,
,
,
If
is omitted, the current value is
returned. Otherwise, the is stored.
Configuration for web::cmdurl.
This command serves two purposes:
Management of static parametersConfiguration for
web::cmdurl
By "static parameters", we mean those which are set for every
page, instead of set on a per-page basis.
Management of static parameters
In addition to the easy way of tracking parameters using
web::dispatch -track ..., specific values
for parameters can be set using web::cmdurlcfg:
In order to explicitly set, retrieve, append or unset static
parameters, use the syntax of the web::param
command, for example:
web::cmdurlcfg -set
Adds the static parameter .
web::cmdurlcfg -names
Returns a list of all known static parameters.
Important: web::cmdurl
compares every key from the static parameters (see
web::cmdurlcfg) against the keys from the
command line. The static parameter is only used if there is no
parameter of the same name given on the command line.
Configuration for web::cmdurl
Sets or gets protocol to be used. Defaults to the scheme used
to access the page, which is overridden if the user
sets a value.
Sets or gets server name to be used. Default: taken from
request.
Sets or gets port number to be used. Default: taken from
request, 80 if not available.
Sets or gets name of CGI executable. Default: taken from
request.
Sets or gets path info (path after scriptname). Default:
taken from request.
Sets or gets the urlformat permanently. See
web::cmdurl for the description of
this option.
In all these cases, "web::cmdurlcfg -option
" sets the value of the given
option and returns the value that was used before the change,
while "web::cmdurlcfg -option" returns
the current value. If no value has been set using
web::cmdurlcfg, but is
requested for the URL generation, the value from the request
will be used. This value, however, can not be retrieved using
web::cmdurlcfg.
Resets the web::cmdurlcfg configuration.
Note however, that static parameters will not be reset by this
option. To get rid of static parameters configured with the
-set option, use -unset
with (for a specific parameter) or without (for all parameters)
key.
Note that setting a value to an empty string
is the same as using -unset.
Also note: web::cmdurl
compares every key from the static parameters against
the keys from the command line. The static parameter is only
used if there is no such parameter on the command line.
web::cmdurl and web::cmdurlcfg
% web::cmdurl ""
?XDqPtk34XvyPh41gUBo
% web::cmdurlcfg -scriptname bin/test_script
% web::cmdurl ""
bin/test_script?XDqPtk34XvyPh41gUBo
% web::cmdurlcfg -scriptname ""
% web::cmdurl ""
?XDqPtk34XvyPh41gUBo
% web::cmdurlcfg -urlformat {scheme host port querystring}
scriptname pathinfo querystring
% # for clearer view on what happens: disable querystring encryption
% web::config encryptchain {}
web::encryptd
% web::cmdurlcfg -set foo bar
bar
% web::cmdurlcfg -host tcl.apache.org
% web::cmdurl zoo
http://tcl.apache.org:80?foo=bar&cmd=zoo&t=1141776460
% web::cmdurlcfg -reset
% web::cmdurl zoo
?foo=bar&cmd=zoo&t=1141776496
% web::config cmdurltimestamp 0
1
% web::config cmdparam page
cmd
% web::cmdurl zoo
?foo=bar&page=zoo
% web::dispatchweb::dispatchoptions
Options are: ,
, ,
and .
Parse information and call a command.
Switches to command . If
is an empty string, no
command is called. By default,
is taken from the
querystring.
Parses as the querystring. If
is an empty string,
querystring parsing is turned off. By default,
querystring is taken from the request data (CGI
environment or apache module request object).
Do not parse any post data.
Parse channel (or variable
named if is
given) as POST data input with length
and type
.
can be application/x-www-form-urlencoded
or multipart/form-data;
boundary=xxx.
In the case of multipat form data,
must specify the
boundary as well. By default, POST data is taken from
the request data. Default for
is application/x-www-form-urlencoded.
Default for is to read a
channel up to EOF or the full content of the variable.
Use the keyword end for
to indicate that
Websh should read all content.
Supported content types are:
multipart/form-data; boundary=xxxxapplication/x-www-form-urlencoded (default)
Track a parameter: register it as "static"
for the generation of URLs with
web::cmdurl. Thus,
each parameter with the key in
will be repeated in
every URL generated with web::cmdurl.
See the documentation of web::cmdurl for
details.
Causes web::dispatch to eval
just before the command (from any source) is
evaluated. When is evaluated,
the full request information has been parsed. That
is, web::param,
web::formvar etc. will have up-to-date
information when is evaluated.
Note: If no command is passed to
web::dispatch either in the querystring or with the
option, web::dispatch will
call the command "default".
web::command and web::dispatch
% set tst {puts "On the hook"}
puts "On the hook"
% web::command acmd {puts "this is acmd"}
% web::dispatch -cmd acmd -querystring "" -postdata ""
this is acmd
% web::dispatch -cmd acmd -querystring "" -postdata "" -hook $tst
On the hook
this is acmd
% set data "a=b&c=d"
a=b&c=d
% web::dispatch -cmd "" -querystring "" -postdata #data
% web::formvar a
b
% web::formvar c
d
% Session management
Websh session management consits of two parts:
Session id trackingSession context management
Session context managers are described in detail below
(web::filecontext,
web::cookiecontext). Session id tracking is
managed by web::dispatch -track. The two
parts are connected with the option
of the session context manager. The control is as follows:
A user uses the Websh script for the first
time.web::dispatch -track will not
see any session id, and, consequently, not set the
static parameter id.
Within the application, the session is initialized using
mgr::init. init
will find no static parameter id (which has been specified at
creation time of the session manager using the
option). Now, it tries to
create a new session id. This will be possible if a
session id generator has been specified when the manager
was created using the option.
From now, on the session id will be a static parameter,
and will therefore be present in every URL generated
with web::cmdurl.
The next time the user visits the Websh application
using one of these URLs,
web::dispatch will detect the
session id, and mgr::init will directly load
the corresponding session context without generating a
new session id.
Examples
See http://tcl.apache.org/websh/examples.ws3
for several sample application demonstrating Websh's
session management facilities.
Request data handlingweb::requestweb::requestoptionskeyvalueweb::requestkeydefault
Options are: , ,
, ,
, and
web::request is an accessor to request
specific information: either CGI related (stand alone
Websh) or Apache related (mod_websh).
web::request
Returns a list of all known keys.
web::request
Returns the value for . Can be a
list. In case that does not
exist, return , if it is
given, or an empty string.
web::request
Returns number of items in list for
; returns 0 if
does not exist.
web::request
Does the same as web::request
.
web::request
Adds the parameter to the
web::request data. Any existing parameters
with are overwritten.
web::request
Appends parameters with the same
to the web::request data. In this case
the existing is not overwritten.
web::request
Deletes all parameters from the web::request data.
web::request
Deletes a parameter from the web::request data.
web::request
Deletes all parameters from the web::request
data (like 'web::request -unset'),
removes all static parameters (like
'web::cmdurlcfg -unset'), all form
variables (like 'web::formvar -unset'),
all query string parameters (like
'web::param -unset'), and all
temporary files created by HTTP form upload.
web::request
Returns the preset default channel for the current request.
(Note that this is not necessarily the currently selected
channel.)
Special case for handling Basic Auth:
web::request
Returns the username provided by the user when Basic Auth is
requested and Apache does not handle it (i.e. if Apache does
not provide REMOTE_USER).
web::request
Returns the password provided by the user when Basic Auth is
requested and Apache does not handle it (i.e. if Apache does
not provide REMOTE_USER).
The following example provides a basic app that requires Basic Auth and
completely bypasses Apache's auth mechanisms.
web::request AUTH_USER and web::request AUTH_PW
# returns 1 if user/pass provided is websh/websh
proc isAuthenticated {} {
if {[web::request -count AUTH_USER]} {
set user [web::request AUTH_USER]
set pass [web::request AUTH_PW]
if {[string eq $user "websh"] && [string eq $pass "websh"]} {
return 1
}
}
return 0
}
# the default command requests Basic Auth unless provided correctly
web::command default {
if {![isAuthenticated]} {
web::response -set Status {401 Authorization Required}
web::response -set WWW-Authenticate {Basic realm="Websh auth"}
web::put "Sorry, you're out"
} else {
web::put "You're in"
}
}
# command dispath
web::dispatch
Note: CGI usually does not expose the Basic Auth
Authorization header for security reasons. The following configuration
for Apache (as of version 2.0.51) will allow Websh to also provide the
same functionality when running in CGI (requires mod_setenvif):
Apache configuration for AUTH_USER and AUTH_PW to work under CGI
SetEnvIf Authorization "^(Basic .+)$" AUTH_BASIC=$1
Important security consideration: This
configuration will also expose the authentication information to
Websh when Apache does handle the authentication. Although Websh
hides the information in that case, it is always available in the
CGI environment. Use this configuration carefully!
web::paramweb::paramoptionkeyvalue...
Options are: , ,
, , and
web::param is an accessor to state information
from the querystring. Suppose the querystring is "lang=EN".
After web::dispatch has parsed the querystring,
web::param will
report EN. Additionaly,
web::param can manage this data and add, append,
and delete parameters as needed.
web::param
Returns a list of all known keys.
web::param
Returns the value for . Can be a
list. In case that does not
exist, return , if it is
given, or an empty string.
web::param
Returns number of items in list of
.
web::param
Does the same as web::param
.
web::param
Adds the parameter to the
web::param data. Any existing
parameters with are overwritten.
web::param
Appends parameters with the same
to the web::param data.
In this case the existing is not
overwritten.
web::param
Deletes all parameters from the web::param
data.
web::param
Deletes a parameter from the web::param
data.
web::formvarweb::formvaroptionskeyvalue
Exactly like web::param.
web::formvar is an accessor to HTML FORM
data. After web::dispatch has parsed the
POST data, you can access all form fields using
web::formvar.
In addition to this, web::formvar can also
handle files uploaded
via Netscape 2.0 file upload mechanism. In this case, the result of
web::formvar is a list with four elements:
The first element contains the name of the locally saved file;
the second element contains the remote file name; the third element
is set to 0 if the upload was successful, -1 if upload is disabled
(see web::config uploadfilesize) and n > 0 if n
Bytes have been truncated, because the file was too big. The last
element contains the mime type of the file.
Note that the temporary files are created with the permissions
configured by web::config filepermissions,
which defaults to 0644.
web::param
% web::request CONTENT_LENGTH
% web::dispatch -querystring "cmd=default&t=100" -postdata "" -cmd ""
% web::param -names
t cmd
% web::param cmd
default
% web::param -set k v
v
% web::param -names
t cmd k
% Response data handling
Websh can send output to any Tcl channel and to global
variables (web::put). Optionally, data is
scanned for Tcl code before it is output to a channel
(web::putx). Websh manages
response objects that are related to Tcl
channels and are identified using the name of the corresponding
Tcl channel. Configuration is achieved with
web::response.
web::responseweb::responseweb::responseoptionweb::responsesubcommandargs
Subcommands are ,
, ,
, ,
, , and
Options are
, ,
and .
Selects the default response object and sets and accesses
properties of the response object, and returns the name of the
response object.
web::response
Returns the name of the currently selected response object.
web::responsechannelName
Selects
as new response object. If the
is
prepended by a , it refers to a global
variable named
.
web::response
Sets property to
, or returns current value if
is omitted. The
are names of HTTP header fields
(do not include ':' at the end of the header field
name) and the corresponding
value of the field (like Content-Type) and their
values (like text/html).
Example:web::response -set Content-Type text/plain.
web::response
Returns the list of known keys.
web::response
Returns number of items in list of .
web::response
Deletes the value of , if
is given, or all keys.
web::response
Sets or gets the sendheader flag which indicates and controls
whether the HTTP headers have been or should be sent.
It is initially set to 1 and set to 0 after the first
call of web::put or
web::putx. If
is omitted, returns the
current value.
web::response
Sets or gets the HTTP response like "HTTP/1.0 200
OK" for the given (or default) channel. If no
given, returns the the current
HTTP response set. In the case of the Apache module
mod_websh, Apache replaces the protocol
"HTTP/??" in the reponse with
"HTTP/1.1".
Note: Depending on the CGI
implementation of your web
server, this does not always work. A working alternative
for newer versions of Apache is to set a Status header
in the response as follows:
web::response -set Status "400 Bad Request".
web::response
Returns the number of bytes that have already been sent to this
channel.
web::response
Resets the 'sendheader' flag for the channel to true,
the HTTP response to the default "HTTP/?? 200
OK", removes any HTTP headers set, and resets the
names of the query string parameters for the timestamp
and the command to their default values ("t"
and "cmd", respectively).
web::response
Performs a web::response -reset on all
registered channels.
web::response
% web::response
stdout
% web::response -select stderr
stdout
% web::response
stderr
% web::response -sendheader
1
% web::response -names
Content-Type Generator
% web::response Content-Type
text/html
% web::response -bytessent
0
% web::response -set Set-Cookie "my cookie that contains data"
% web::put "Hello, world\n"
Content-Type: text/html
Set-Cookie: my cookie that contains data
Generator: websh3.6.0
Hello, world
% web::putweb::put#channeltext
Sends output to a Tcl channel. No newline is added to
output. If
is ommitted, output is sent to the current default
channel. The default channel can be changed with
web::response
.
The optional hash ("#") denotes that output should be
sent to a global variable named
instead of
a Tcl channel.
web::putxweb::putx#channeltext
Writes to the specified channel. Code in
curly brackets is eval'd, unless the brackets are escaped by
"\". These markup characters '{...}' can be changed
to '<? ... ?>' with
'web::config putxmarkup tag'. The optional hash
("#") denotes that output should be sent to a global
variable named
instead of a Tcl channel.
web::putxfileweb::putxfile#channelfilemsg
Like web::putx, but takes input from a file.
Returns 0 on success, 1 otherwise. If an error occurs, an
error message is written to . If only two
arguments are passed, then takes
precedence. The optional hash ("#") denotes that output
should be sent to a global variable named
instead
of a Tcl channel.
Logging
Logging consists of two parts. web::log
issues a logging message, while
web::loglevel and
web::logdest determine where to send a
message. Websh uses a two-step filtering. First, Websh
determines whether it should handle a message, or not, using the
levels configured with web::loglevel. Then,
Websh determines which message is to be sent where, using the
the additional filters and destinations configured with
web::logdest. There is no logging per default.
Setting levels with web::loglevel is mandatory.
A filter consists of a tag and a level, separated by a
".". The tag is free text. Typically, it is the name
of the application, say "foo". Example:
"ws3.debug". Levels are, in order:
alerterrorwarninginfodebugweb::logdestweb::logdestsubcommandoptionsargs
Subcommands are: ,
, , and
.
web::logdest
Options are: , and
.
-maxchar n truncates the message to a
maximum of n characters.
The format string consists of time format specifications for
strftime() plus: $p (process id), $t (thread id), $l (log level), $n (numerical log level), $f (log facility), $m (the message), and $$ (dollar sign).
Default format: "%x %X [\$p] \$f.\$l: \$m\n"
Known plug-ins are: ,
(Unix only), ,
, and
(mod_websh only).
Note: plug-ins may have indiviudal options
(such as ), see documentation below.
web::logdest add -maxchar 25 -format "%x %X \$l \$m\n" *.-debug command logTestweb::logdest
Removes destination from list, or
removes all destinations if is omitted.
(The special case -requests
to delete all destinations except the one defined from
within web::initializer code is only
used internally.)
web::logdest
Returns a list of all destination ids that have been set.
web::loglevel
Lists all destination ids and their actual log levels in a
readable format
web::loglevelweb::loglevelsubcommandargs
Subcommands are: ,
, ,
and .
Levels defined using web::loglevel act as a
filter for log messages sent by Websh. Only messages that pass
at least one level defined using this command are passed to the
log destinations configured using web::logdestweb::loglevel
Adds a level to the list.
web::loglevel
Removes level from list, or removes all
levels if is omitted.
(The special case -requests
to delete all levels except the one defined from within
web::initializer code is only used
internally.)
web::loglevel
Returns a list of all level ids that have been set.
web::loglevel
Lists all level ids and their actual log levels in a
readable format.
web::logweb::loglevelmsg
Issues a log message. It is possible, should the user so
desire, to have the web::log run
subst on its arguments. This behaviour is
turned off by default, and can be turned on by doing:
web::config logsubst 1.
Log plug-insFileweb::logdestadddestination.-levelfileoptionsfilename
Option is:
Log messages are sent to the file ,
which is opened in append mode at the time of this call and
stays open until this destination is deleted. This is either
at the end of the request (mod_websh) or when the interpreter
is deleted.
The file opened using the permissions configured with
web::config filepermissions. Default: 0644.
Syslogweb::logdestadd*.-debugsysloglevel
See the man page for syslog for levels on your system. Typical: 10.
Available under Unix only.
Commandweb::logdestadd*.-debugcommandcmdName
The log message is sent to a Tcl command taking the message
as an argument. E.g.
% proc logCommand {msg} {
puts "---- here comes the message ----"
puts -nonewline $msg
puts "----- that was the message -----"
}
%
% web::loglevel add *.-debug
loglevel0
% web::logdest add *.-debug command logCommand
logdest0
% web::log debug "a log message"
---- here comes the message ----
10/28/05 13:44:26 [20596] user.debug: a log message
----- that was the message -----
% Channelweb::logdestadd*.-debugchanneloptionschannel
Option is:
Writes the message to the Tcl channel .
Apacheweb::logdestadd*.-debugapache
Sends the message to the Apache ErrorLog file. Available within
mod_websh only.
web::log, web::loglevel, and web::logdest
% web::loglevel add *.-debug
loglevel0
% web::logdest add *.-debug channel stdout
logdest0
% web::log info {Websh is cool}
03/01/00 00:00:00 [111] user.info: Websh is cool
% web::logdest delete
% web::logdest add -format "--> \$m\n" *.-debug channel stdout
logdest0
% web::log info {Websh is cool}
--> Websh is cool
% web::logdest delete
% web::logdest add -maxchar 5 *.-debug channel stdout
% web::log info {Websh is cool}
03/01/00 00:00:00 [111] user.info: Websh
% Context handlingweb::context
Creation
web::contextname
Creates a namespace with the following
commands:
name::subcommandargs
Subcommands are: ,
, ,
, ,
, ,
, ,
and .
Manages data of the context. The subcommands behave like the
Tcl commands with similar names.
name::cset
Set to .
name::cappend
Appends to existing value for
.
name::clappend
Appends to existing list of
values for .
name::cget
Accesses the value for key , or
returns if
does not exist in the context. If
is omitted, an empty string
is returned if is unknown.
name::cexists
Returns true (1) if exists in
context, false (0) otherwise.
name::cunset
Removes from context.
name::carray
Array manipulation as known from the Tcl command
array.
name::cnames
Lists existing keys of context matching
.
name::delete
Deletes the context (same as namespace delete
name)
name::dump
Serializes context in a "source"-able format.
web::context
% web::context sc
% sc::cset lang FR
FR
% # ... some code ...
% set lang [sc::cget lang EN]
FR
% web::filecontext
Creation:
web::filecontextnameoptions
Options are: , ,
, , and
.
Creates a namespace to manage file-based
context data:
name::subcommandargs
Subcommands are: ,
, ,
, ,
, ,
, ,
, ,
, and .
Manages file-based context data. The subcommands have their
familiar behaviour of the Tcl commands with similar
names. Please refer to the section context management for a
description of the commands ,
, ,
, ,
, , and
.
name::init
Loads an existing session context with id
, or creates a new one, if
possible. Automation depends on the settings of the
actual context manager settings, see
below. If you specify an
, you must decide when to create a
new file and when to use the old one, if any, by
yourself.
name::new
Creates a new session context. Automation depends on
the settings of the actual context manager settings,
see below.
name::commit
Makes session context persistent.
name::id
Returns id of session.
name::invalidate
Deletes session in memory and on file system.
Options:
web::filecontextname-permperm
Sets the file permissions of the session context files
is an unix-like octal value like 0644.
If not specified, files are created with the permissions defined
in web::config filepermissions,
which again defaults to 0644.
web::filecontext
Specifies where to store session context files and how
to name them. Suppose that the session id is 99.
-path [file join .. data s%d.dat]
would then cause filecontext to save the session
context as ../data/s99.dat.
web::filecontext
Sets crypting of session context on or off.
Default: on.
web::filecontext
Sets command to find a new
session id. See doc of
web::filecounter below for an
implementation provided by Websh.
is used in case that no
argument has been passed to
or .
web::filecontext
Causes name::init
to initialize with the id given in the querystring parameter
. (This is one important reason why
the querystring should be encrypted). After
web::dispatch has
parsed the querystring, web::param
will report the current session id in
, if any. Note
that you can maintain several sessions in parallel,
and attach every session to its own
.
Using
web::dispatch -track
further automates the passing of session ids from
request to request.
Note: Whenever you create a new
file-based context, the context is initialized and you loose
whatever information that you might have stored in the context
before you initialized it as a file-based session context.
web::cookiecontext
Creation:
web::cookiecontextnameoptions
Options are: ,
, ,
, , and
.
Creates a namespace to manage
cookie-based context data:
name::subcommand
Subcommands are: ,
, ,
, ,
, ,
, ,
, ,
, and .
name::init
Loads an existing session context (cookie must have
been sent by the client).
name::new
Creates a new session context.
name::commit
Sends a cookie (if no output to the page has been sent yet).
name::id
Returns id of session.
name::invalidate
Deletes session in memory and on client side.
Options:
web::cookiecontext
Sets the expiration date of the cookie. Possible values
for are
seconds (time in seconds since
1970-01-01) or date-string (any
time string that Tcl can scan. Note that therefore many
relative times, such as 24 hours,
week, 2 weeks,
tomorrow, etc.
are possible. Default is now + 24 hours
(i.e. cookie expires in 24 hours. (Please note that the
behavior of some of these relative time specifiers changed
from Tcl8.4 to Tcl8.5.) Use
-expires "" to
send a cookie without an expires parameter.
web::cookiecontext
Sets the property of the cookie.
web::cookiecontext
Sets the property of the cookie.
web::cookiecontext
Sets the property of the cookie.
web::cookiecontext
Sets crypting of cookie context on or off.
Default: on.
web::cookiecontext
Sets the response object to send the cookie to (see also
web::response).
Because cookies are client-based, in principle no id is
needed. Websh uses to name the cookie,
however, and the new,
init, and load commands
still require the argument. (fixme: any
changes?) Please note that property settings of a cookie
context can only be changed before
anything is output on the respective channel.
web::filecounter
This is a numeric sequence-number generator which stores its
state in a file. Basic usage:
Creation:web::filecounter
Options are: ,
, ,
, ,
Uses to store the current
value (no default).
Uses this value as a minimum at start and after wrap,
if wrap is true. Default: 0.
Uses this value as a maximum, if wrap is true. Default: 2147483647.
Usea this value as a starting point if persistent file does
not exist yet. Default: 0.
Uses this value as an increment for each 'nextval'.
Default: 1.
Sets the permissions on the newly created files.
Default is configured in web::config filepermissions, which defaults to 0644.
Indicates whether this counter should wrap around its
values (back to min from max). Default: false.
After creation, a new command is
registered with the following subcommands:
config
Returns a flat list of key value pairs with the
filecounter's configuration.
nextval
Returns the next value.
curval
Returns the current value, that is, the value that the
last call to "nextval" or "getval"
reported (as opposed to the current value in the file).
getval
Returns the current value in the file. (Does not increment
file as in "nextval".)
web::filecounter
% web::filecounter fc1 -filename test.dat
fc1
% fc1 config
file test.dat handle fc1 seed 0 min 0 max 2147483647 incr 1 perms 0644 wrap false curr {not valid}
% fc1 curval
web::filecounter: no current value available
% fc1 nextval
0
% fc1 config
file test.dat handle fc1 seed 0 min 0 max 2147483647 incr 1 perms 0644 wrap false curr 0
% fc1 nextval
1
% web::filecounter fc2 -filename test.dat
fc2
% fc2 curval
web::filecounter: no current value available
% fc2 getval
1
% fc2 nextval
2
% fc2 curval
2
% fc1 curval
1
% fc1 nextval
3
% fc2 getval
3
% web::filecounter fc3 -filename othertest.dat -min 1 -max 10 -seed 1 -incr 2 -wrap 1
fc3
% fc3 config
file othertest.dat handle fc3 seed 1 min 1 max 10 incr 2 perms 0644 wrap true curr {not valid}
% fc3 nextval
1
% fc3 nextval
3
% File handling and file I/Oweb::includeweb::includefileNamemsg
If the file exists, it is sourced (must be a
script). Otherwise if the library fileName+"shared lib
extension" exists, it is loaded (must be a shared library).
Returns 0 on success, 1 otherwise. If an error occurs, an error
message is written to .
web::readfileweb::readfilefilevarNamemsg
Reads and writes it to
. Returns 0 on success, 1
otherwise. If an error occurs, an error message is written to
the variable .
web::lockfile and web::unlockfileweb::lockfilefhweb::unlockfilefh
Interfaces lockf(). lockf()
works best on local filesystems.
Please read the documentation of lockf() on your
system to learn about the problems and limitations of file locking.
Note that
web::lockfile also performs a
seek() and
resets the file cursor to the beginning of the file.
Note that the file needs to be open for
writing.
web::truncatefileweb::truncatefilefh
Interfaces truncate(). Truncates a file based on
the file handle, while Tcl's file commands are based on file
names. This is used to truncate a file while holding the lock.
web::lockfile
set fh [open [web::tempfile] w]
web::lockfile $fh
puts $fh foo
web::unlockfile $fh
close $fh Data encryption
Encrypts (web::encrypt) and decrypts
(web::decrypt) data. By default, the
built-in, weak encryption is used. Encryption is extensible by
plug-ins. The encryption module tries all plug-ins from a list
until the first plug-in was able to en-/decrypt the input. See
web::config for the configuration of the
plug-ins to be used.
web::encryptweb::encryptdata
Returns encrypted data.
web::decryptweb::decryptdata
Returns decrypted data.
web::encrypt
% web::encrypt "Hello, world!"
XDIVAhkgkxRjcfA7UTwpD7
% web::decrypt [web::encrypt "Hello, world!"]
Hello, world!
% Encryption plug-in Dweb::encryptd
By default, Websh uses this plug-in for (very) weak data
encryption (web::encryptd)
and decryption (web::decryptd). The
encryption key is managed with
web::crpytdkey.
web::encryptddata
Returns encrypted .
web::decryptdweb::decryptddata
Returns decrypted .
web::cryptdkeyweb::cryptdkeykey
Sets a new key for encryption. If no argument is given,
resets to the default key. This command does not return the
currently active key, in difference to other configuration
commands of Websh.
Encryption plug-in interfaceFor plug-in developers only
The encryption plug-in is required to implement the interface
described below (note that to activate your plug-in, use
web::config encryptchain and
web::config decryptchain respectively):
web::yourencrypt accepts one argument
web::yourencrypt takes a string as
input and generates a string which must be URI compliant.
web::yourdecrypt accepts one argument
web::yourdecrypt takes a string as input
and returns a string.
Symmetry: $in ==
[web::yourdecrypt [web::yourencrypt
$in]]
Error messaging: TCL_OK for
success. TCL_ERROR for any error
during en-/decryption. TCL_CONTINUE
for unknown encryption type (pass on to next method).
Uri-/html- en-/decodingweb::htmlifyweb::htmlify-optionstext
Options: .
Returns HTML-compliant with HTML
encoded entities in mnemonic form (e.g. ä) or in numeric
form (e.g. ä) if the option
is specified. Multibyte characters are encoded as
&#<numeric>;.
web::dehtmlifyweb::dehtmlifytext
Removes all HTML-tags from and translates
all HTML entities to their corresponding characters (also
handles encoded multibyte characters encoded with
&#<numeric>;).
web::uriencodeweb::uriencodetext
Returns URI-compliant .
web::uridecodeweb::uridecodetextDecodes URI-compliant .
web::htmlify
% web::htmlify <
<
% web::htmlify -numeric <
<
% web::dehtmlify "< <"
< <
% web::uriencode "Hello, world!"
Hello%2c+world%21
% web::uridecode "Hello%2c+world%21"
Hello, world!
% Inter-process/-system communication
Sends to and receives from sockets.
web::sendweb::sendchannelcmdNrmessageflags
Sends the command
and the
message to
channel
using
the flags
. The command
numbers are application specific. If
is used,
flags is the numeric (integer) representation of the flags is
to be set. If the # is omitted,
is a list of
symbolic flags. Currently, there is only one flag:
or with the
same meaning, indicating that there is more to follow and no
automatic flush on the channel should be done.
web::recvweb::recvchannelcmdVarNamemsgVarNameflagVarName
Receives a message from . The
other arguments are the names of the corresponding variables
which will contain the message. The flags are returned
numeric. (To handle these flags, use the
web::msgflag function).
web::msgflagweb::msgflagflagstestflags
Sets or tests flags.
web::msgflag
Returns a list of all known message flags.
web::msgflag
Returns the integer representation of the flags listed
in .
web::msgflag
Returns 1, if the flags in
are set in .
Apache module specific commands
Note that these commands are implemented as dummies in the CGI
version of Websh only. They don't do anything except for
web::initializer and
web::finalizer, which just evaluate the
code provided in the argument.
web::initializerweb::initializercode
This code is executed only when a new interpreter is created.
Note that the "main" Websh script can
source several modules which each call
their initialization code.
Also note that this code eval'd when it is first requested and
read in its normal script sequence, and not prior to any other
code in the script.
Calling web::loglevel and
web::logdest in any
web::initializer will tag these log levels
and destinations as not to be deleted, after the request ends.
This log condifguration will therefore also be available in
the finalizer code, which is only eval'd after the last request
in the interpreter has been cleaned up.
logging in web::initializer
> cat test.ws3
web::initializer {
web::logdest add user.-debug file -unbuffered /tmp/test.log
web::logfilter add *.-debug
web::log info "initializing interp"
}
web::command default {
web::log info "command default call number [web::interpcfg numreq]"
web::putxfile /tmp/dummypage.html
}
web::finalizer {
web::log info "shutting down interp"
}
web::dispatch
> # requesting test.ws3 three times over mod_websh:
> more /tmp/test.log
10/28/05 14:13:45 [20639] user.info: initializing interp
10/28/05 14:13:45 [20639] user.info: command default call number 0
10/28/05 14:13:46 [20639] user.info: command default call number 1
10/28/05 14:13:47 [20639] user.info: command default call number 2
10/28/05 14:13:47 [20639] user.info: shutting down interp
Note that in the above example the lifetime of the interpreter class is set to 3 requests. (See command web::interpclasscfg.)
web::finalizerweb::finalizercode
Registers code to be exectuted when the interpreter for this
Websh script is deleted. web::finalize
will then call each block that has been
registered, starting with the most recently added
.
web::finalizeweb::finalize
Executes finalizer code that has been registered using
web::finalizer, starting with the most
recently added . Note that this command
is executed automatically and does not have to be called
manually. However, it can be used as a hook, when the
interpreter is deleted:
web::finalize hook
rename web::finalize web::finalize.orig
proc web::myFinalize {} {
# code to eval before finalize.orig
finalize.orig
# code to eval after finalize.orig
} web::mainevalweb::mainevalcode
Executes code in the "main" interpreter of mod_websh. (Note
that this is synchronized, i.e. the main interpreter is locked for
exclusive access by the current thread within the process. However,
running Apache in a prefork setting sets up a main interpreter per
child, so the exclusive access does not refer to server wide
exclusivity, but only to child process wide exclusiveity.)
web::interpclasscfgweb::interpclasscfgclassidpropertyvalue
Properties are: ,
,
Sets or accesses properties of the interpreter class
.
web::interpclasscfg
Sets or gets the maximum number of requests
interpreters of this class should handle. If
is 0, handle an unlimited
number of requests. Default: 1.
web::interpclasscfg
Sets or gets the maximum number of seconds
interpreters of this class should live. If
is 0, it lives
forever. Default: 0.
web::interpclasscfg
Sets or gets the maximum number of seconds
interpreters of this class should live beeing idle. If
is 0, no idle timeout is
assumed. Default: 0.
web::interpcfgweb::interpcfgpropertyvalue
Properties are: ,
, ,
Sets or accesses properties of the current interpreter.
web::interpcfg
Returns of current
interpreter.
web::interpcfg
Returns the number of requests handled by this
interpreter.
web::interpcfg
Sets or gets the flag indicating this interpreter
should be removed after handling the current request.
web::interpcfg
Returns the time in seconds since the epoch, this
interpreter was started.
web::interpcfg
Returns the time in seconds since the epoch, this
interpreter was last used (starttime in case of first
request).
web::interpmapweb::interpmapfilename
Hook to define interpreter classes depending on the requested file.
Note that this hook must be defined in the Websh configuration file
(WebshConfig directive of mod_websh).
When a request is directed to mod_websh, Websh needs to determine the
interpreter class for that reqest. It does that by calling
web::interpmap with the requested file as argument.
The return value of that command is the name of the interpreter class
and at the same time the filename of the script for this interpreter
class.
web::interpmap
proc web::interpmap {filename} {
if {[string match "/path/to/myApp" $filename]} {
# this is my special app
return /real/path/to/myApp
}
if {[string match "*.ws3"]} {
# scripts have their own interp class
return $filename
}
# default: all templates are handled by my handler
return /my/special/template/handler
}
The default implementation of web::interpmap is
proc web::interpmap {filename} {return $filename}
This sets up a separate interpreter class for every requested URL
and takes the file itself as script.
Miscellaneous commandsweb::matchweb::matchresultlistToBeSearchedsearchFor
In case exists in
,
web::match returns
, otherwise an empty string.
web::match treats listToBeSearched as a list.
Thus, web::match "ok" {tv dvd vcr} dvd
will return ok.
web::tempfileweb::tempfileoptions
Options are ,
, and .
web::tempfile-path
path-prefix
prefix
Returns a unique name of a temporary file in the default
temp directory or the directory given with
path.
The name can be prefixed with prefix.
The maximum of guaranteed unique names per application is system
dependent. This command just returns the name of a file. It is the
programmers job to handle the file, for example to open
it. Note that Websh keeps an internal list of all file
names generated with web::tempfile and will
attempt to delete all files when the interpreter dies.
web::tempfile-remove
Attempts to clean up all temporary
files previously created using web::tempfile and
resets the internal list of these file names.