pyweblib-1.3.9/0000755000076400001440000000000011745325171014134 5ustar michaelusers00000000000000pyweblib-1.3.9/htdocs/0000755000076400001440000000000011745325171015420 5ustar michaelusers00000000000000pyweblib-1.3.9/htdocs/index.html0000644000076400001440000000376211577431511017424 0ustar michaelusers00000000000000 PyWebLib

PyWebLib

CVS Id: $Id: index.html,v 1.7 2011/06/19 17:35:05 michael Exp $

Welcome to PyWebLib - yet another web programming framework for Python.

Content

The module package pyweblib consists of several submodules:
pyweblib.forms
class library for handling <FORM> input
pyweblib.session
server-side web session handling
pyweblib.helper
misc. stuff useful in CGI-BINs
pyweblib.sslenv
retrieves SSL-related env vars
pyweblib.httphelper
very basic HTTP functions/classes

License

© by Michael Ströder <michael@stroeder.com>

This software is Open Source and given away under:

GPL (GNU GENERAL PUBLIC LICENSE) Version 2
The author refuses to give any warranty of any kind.

Download

Stable release: pyweblib-1.3.8.tar.gz

Installation

This module package requires Python 2.0+!
Install via DistUtils by typing the command python setup.py install.

Documentation

Documentation is sparse!

Applications

More complex programming examples. ;-)

pyweblib-1.3.9/htdocs/pydoc/0000755000076400001440000000000011745325171016536 5ustar michaelusers00000000000000pyweblib-1.3.9/htdocs/pydoc/pyweblib.html0000755000076400001440000000630710112613726021243 0ustar michaelusers00000000000000 Python: package pyweblib
 
 
pyweblib (version 1.3.3)
index
/usr/lib/python2.3/site-packages/pyweblib/__init__.py

pyweblib - several modules for web programming tasks
(C) 2001 by Michael Stroeder <michael@stroeder.com>
 
This module including sub-modules is distributed under the terms
of the GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)
 
Compability note:
requires Python 2.0+
 
Sub modules:
pyweblib.forms             class library for handling <FORM> input
pyweblib.session           server-side web session handling
pyweblib.helper            misc. stuff useful in CGI-BINs
pyweblib.sslenv            retrieves SSL-related env vars
pyweblib.httphelper        very basic HTTP functions
 
$Id: pyweblib.html,v 1.15 2004/08/24 10:26:30 michael Exp $

 
Package Contents
       
forms
helper
httphelper
session
sslenv

 
Data
        __version__ = '1.3.3'
pyweblib-1.3.9/htdocs/pydoc/pyweblib.httphelper.html0000755000076400001440000001217210112613726023416 0ustar michaelusers00000000000000 Python: module pyweblib.httphelper
 
 
pyweblib.httphelper (version 0.0.4)
index
/usr/lib/python2.3/site-packages/pyweblib/httphelper.py

httphelper.py - basic HTTP-related functions
(c) by Michael Stroeder <michael@stroeder.com>
 
This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)
 
$Id: pyweblib.httphelper.html,v 1.12 2004/08/24 10:26:30 michael Exp $

 
Modules
       
sys
time

 
Functions
       
DateTimeRFC1123(secs=0)
Return seconds as RFC1123 date/time format preferred
for HTTP 1.1 (see RFC2616)
SendHeader(outf=<open file '<stdout>', mode 'w'>, contenttype='text/html', charset='ISO-8859-1', contentlength=None, expires_offset=0, current_datetime=None, additional_header=None)
Generate HTTP header
 
outf
    File object used for sending to client.
contenttype
    MIME type of object in HTTP body. Default is 'text/html'.
charset
    Character set used. Default is 'ISO-8859-1'.
contentlength
    Content-Length if known and gzip-encoding is not used.
    Default is None indicating unknown length.
expires_offset=0,
    Expiry time from current time in seconds. Default is 0.
current_datetime
    Last modification time in seconds.
    If zero (default) 'Last-modified' header will be omitted.
additional_header
    Dictionary containing arbitrary additional HTTP header fields
    as key/value-pairs.
SimpleMsg(outf, msg)
Output HTML text.
URLRedirect(outf, url, refreshtime=0, msg='Redirecting...')
Output HTML text with redirecting <head> section.

 
Data
        HTTP_LINESEP = '\r\n'
__version__ = '0.0.4'
pyweblib-1.3.9/htdocs/pydoc/pyweblib.forms.html0000755000076400001440000020135710112613726022372 0ustar michaelusers00000000000000 Python: module pyweblib.forms
 
 
pyweblib.forms (version 0.15.0)
index
/usr/lib/python2.3/site-packages/pyweblib/forms.py

pyweblib.forms - class library for handling <FORM> input
(c) by Michael Stroeder <michael@stroeder.com>
 
This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)
 
Python compability note:
This module only works with Python 2.0 since all string parameters
are assumed to be Unicode objects and string methods are used instead
string module.
 
$Id: pyweblib.forms.html,v 1.17 2004/08/24 10:26:30 michael Exp $

 
Modules
       
pyweblib.helper
re
sys
types
urllib

 
Classes
       
exceptions.Exception
FormException
ContentLengthExceeded
InvalidFormEncoding
InvalidRequestMethod
InvalidValueFormat
InvalidValueLen
ParamsMissing
TooManyValues
UndeclaredFieldName
Field
Checkbox
Input
File
HiddenInput
Password
Keygen
Radio
Select
Textarea
Form

 
class Checkbox(Field)
    Check boxes:
<INPUT TYPE=CHECKBOX>
 
  Methods defined here:
__init__(self, name, text, maxValues=1, required=0, accessKey='', default=None, checked=0)
pattern and maxLen are determined by default
inputHTML(self, default=None, id_value=None, title=None, checked=None)

Methods inherited from Field:
getValue(self)
Returns self.value in case of multi-valued input or
self.value[0] if only one value is allowed.
idAttrStr(self, id_value)
labelHTML(self, labelText=None, for_value=None)
setCharset(self, charset)
Define the character set of the user's input.
setDefault(self, default)
Set the default of a field.
 
Mainly this is used by the application if self.default shall
be changed after initializing the field object.
setRegex(self, pattern)
Set the regex pattern for validating this field.
 
Mainly this is used if self._re shall be changed after
the field object was initialized.
 
pattern
    Either a string containing a regex pattern,
    a tuple (pattern string, pattern options) or None.
    If None regex checking in _validateFormat is switched off
    (not recommended).
setValue(self, value)
Store the user's value into the field object.
 
This method can be used to modify the user's value
before storing it into self.value.
valueHTML(self)
HTML output of self.value using the HTML template string
in self.valueHTMLTemplate.

 
class ContentLengthExceeded(FormException)
    Overall length of input data too large.
 
Attributes:
contentLength         received content length
maxContentLength      maximum valid content length
 
 
Method resolution order:
ContentLengthExceeded
FormException
exceptions.Exception

Methods defined here:
__init__(self, contentLength, maxContentLength)
__str__(self)

Methods inherited from FormException:
html(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class Field
    Base class for all kind of single input fields.
 
In most cases this class is not used directly
since derivate classes for most types of input fields exist.
 
  Methods defined here:
__init__(self, name, text, maxLen, maxValues, pattern, required=0, default=None, accessKey='')
name
    Field name used in <INPUT NAME="..">
text
    User-friendly text describing this field
maxLen
    maximum length of a single input value [Bytes]
maxValues
    maximum amount of input values
default
    default value to be used in method inputfield()
required
    flag which marks field as mandantory input field
accessKey
    key for accessing this field to be displayed by method inputHTML()
pattern
    regex pattern of valid values either as string
    or tuple (pattern,options)
getValue(self)
Returns self.value in case of multi-valued input or
self.value[0] if only one value is allowed.
idAttrStr(self, id_value)
labelHTML(self, labelText=None, for_value=None)
setCharset(self, charset)
Define the character set of the user's input.
setDefault(self, default)
Set the default of a field.
 
Mainly this is used by the application if self.default shall
be changed after initializing the field object.
setRegex(self, pattern)
Set the regex pattern for validating this field.
 
Mainly this is used if self._re shall be changed after
the field object was initialized.
 
pattern
    Either a string containing a regex pattern,
    a tuple (pattern string, pattern options) or None.
    If None regex checking in _validateFormat is switched off
    (not recommended).
setValue(self, value)
Store the user's value into the field object.
 
This method can be used to modify the user's value
before storing it into self.value.
valueHTML(self)
HTML output of self.value using the HTML template string
in self.valueHTMLTemplate.

 
class File(Input)
    File upload field
<input type="file">
 
 
Method resolution order:
File
Input
Field

Methods defined here:
inputHTML(self, default=None, id_value=None, title=None, mimeType=None)

Data and other attributes defined here:
mimeType = 'application/octet-stream'

Methods inherited from Input:
__init__(self, name, text, maxLen, maxValues, pattern, required=0, default=None, accessKey='', size=None)

Methods inherited from Field:
getValue(self)
Returns self.value in case of multi-valued input or
self.value[0] if only one value is allowed.
idAttrStr(self, id_value)
labelHTML(self, labelText=None, for_value=None)
setCharset(self, charset)
Define the character set of the user's input.
setDefault(self, default)
Set the default of a field.
 
Mainly this is used by the application if self.default shall
be changed after initializing the field object.
setRegex(self, pattern)
Set the regex pattern for validating this field.
 
Mainly this is used if self._re shall be changed after
the field object was initialized.
 
pattern
    Either a string containing a regex pattern,
    a tuple (pattern string, pattern options) or None.
    If None regex checking in _validateFormat is switched off
    (not recommended).
setValue(self, value)
Store the user's value into the field object.
 
This method can be used to modify the user's value
before storing it into self.value.
valueHTML(self)
HTML output of self.value using the HTML template string
in self.valueHTMLTemplate.

 
class Form
    Class for declaring and processing a whole <form>
 
  Methods defined here:
__init__(self, inf, env)
Initialize a Form
inf                 Read from this file object if method is POST.
env                 Dictionary holding the environment vars.
addField(self, f)
Add a input field object f to the form.
checkRequestMethod(self)
Checks whether the HTTP request method is accepted
getContentType(self)
Determine the HTTP content type of HTTP request
getInputFields(self, ignoreEmptyFields=0, ignoreUndeclaredFields=0, stripValues=1, unquotePlus=0)
Process user's <form> input and store the values in each
field instance's content attribute.
 
When a processing error occurs FormException (or derivatives)
are raised.
 
ignoreEmptyFields=0         Ignore fields with empty input.
ignoreUndeclaredFields=0    Ignore fields with names not declared.
                            Normally UndeclaredFieldName is raised.
stripValues=1               If true leading and trailing whitespaces
                            are stripped from all input values.
unquotePlus=0
   If non-zero urllib.unquote_plus() is used instead of urllib.unquote().
getInputValue(self, name, default=[])
Return input value of a field defined by name if presented
in form input. Return default else.
hiddenInputFields(self, outf=<open file '<stdout>', mode 'w'>, ignoreFieldNames=[])
Output all parameters as hidden fields.
 
outf
    File object for output.
ignoreFieldNames
    Names of parameters to be excluded.

 
class FormException(exceptions.Exception)
    Base exception class to indicate form processing errors.
 
Attributes:
args          unstructured List of parameters
 
  Methods defined here:
__init__(self, *args, **kwargs)
html(self)

Methods inherited from exceptions.Exception:
__getitem__(...)
__str__(...)

 
class HiddenInput(Input)
    Hidden input field:
<input type="hidden">
 
 
Method resolution order:
HiddenInput
Input
Field

Methods defined here:
__init__(self, name, text, maxLen, maxValues, pattern, required=0, default=None, accessKey='')
inputHTML(self, default=None, id_value=None, title=None, show=0)

Methods inherited from Field:
getValue(self)
Returns self.value in case of multi-valued input or
self.value[0] if only one value is allowed.
idAttrStr(self, id_value)
labelHTML(self, labelText=None, for_value=None)
setCharset(self, charset)
Define the character set of the user's input.
setDefault(self, default)
Set the default of a field.
 
Mainly this is used by the application if self.default shall
be changed after initializing the field object.
setRegex(self, pattern)
Set the regex pattern for validating this field.
 
Mainly this is used if self._re shall be changed after
the field object was initialized.
 
pattern
    Either a string containing a regex pattern,
    a tuple (pattern string, pattern options) or None.
    If None regex checking in _validateFormat is switched off
    (not recommended).
setValue(self, value)
Store the user's value into the field object.
 
This method can be used to modify the user's value
before storing it into self.value.
valueHTML(self)
HTML output of self.value using the HTML template string
in self.valueHTMLTemplate.

 
class Input(Field)
    Normal one-line input field:
<input>
 
  Methods defined here:
__init__(self, name, text, maxLen, maxValues, pattern, required=0, default=None, accessKey='', size=None)
inputHTML(self, default=None, id_value=None, title=None)

Methods inherited from Field:
getValue(self)
Returns self.value in case of multi-valued input or
self.value[0] if only one value is allowed.
idAttrStr(self, id_value)
labelHTML(self, labelText=None, for_value=None)
setCharset(self, charset)
Define the character set of the user's input.
setDefault(self, default)
Set the default of a field.
 
Mainly this is used by the application if self.default shall
be changed after initializing the field object.
setRegex(self, pattern)
Set the regex pattern for validating this field.
 
Mainly this is used if self._re shall be changed after
the field object was initialized.
 
pattern
    Either a string containing a regex pattern,
    a tuple (pattern string, pattern options) or None.
    If None regex checking in _validateFormat is switched off
    (not recommended).
setValue(self, value)
Store the user's value into the field object.
 
This method can be used to modify the user's value
before storing it into self.value.
valueHTML(self)
HTML output of self.value using the HTML template string
in self.valueHTMLTemplate.

 
class InvalidFormEncoding(FormException)
    The form data is malformed.
 
Attributes:
param         name/value causing the exception
 
 
Method resolution order:
InvalidFormEncoding
FormException
exceptions.Exception

Methods defined here:
__init__(self, param)
__str__(self)

Methods inherited from FormException:
html(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class InvalidRequestMethod(FormException)
    Exception raised when HTTP request method was invalid.
 
Attributes:
method        string containing method used
 
 
Method resolution order:
InvalidRequestMethod
FormException
exceptions.Exception

Methods defined here:
__init__(self, method)
__str__(self)

Methods inherited from FormException:
html(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class InvalidValueFormat(FormException)
    The user's input does not match the required format.
 
Attributes:
name          name of input field (Field.name)
text          textual description of input field (Field.text)
value         input value received
 
 
Method resolution order:
InvalidValueFormat
FormException
exceptions.Exception

Methods defined here:
__init__(self, name, text, value)
__str__(self)

Methods inherited from FormException:
html(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class InvalidValueLen(FormException)
    Length of user input value invalid.
 
Attributes:
name          name of input field (Field.name)
text          textual description of input field (Field.text)
valueLen      integer number of received value length
maxValueLen   integer number of maximum value length
 
 
Method resolution order:
InvalidValueLen
FormException
exceptions.Exception

Methods defined here:
__init__(self, name, text, valueLen, maxValueLen)
__str__(self)

Methods inherited from FormException:
html(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class Keygen(Field)
    Select field for client-side key generation with
Netscape/Mozilla/Opera browser:
<KEYGEN>
 
  Methods defined here:
__init__(self, name, text, maxLen, maxValues, required=0, minKeyLength=512)
inputHTML(self, challenge, id_value=None, title=None)
valueHTML(self)

Methods inherited from Field:
getValue(self)
Returns self.value in case of multi-valued input or
self.value[0] if only one value is allowed.
idAttrStr(self, id_value)
labelHTML(self, labelText=None, for_value=None)
setCharset(self, charset)
Define the character set of the user's input.
setDefault(self, default)
Set the default of a field.
 
Mainly this is used by the application if self.default shall
be changed after initializing the field object.
setRegex(self, pattern)
Set the regex pattern for validating this field.
 
Mainly this is used if self._re shall be changed after
the field object was initialized.
 
pattern
    Either a string containing a regex pattern,
    a tuple (pattern string, pattern options) or None.
    If None regex checking in _validateFormat is switched off
    (not recommended).
setValue(self, value)
Store the user's value into the field object.
 
This method can be used to modify the user's value
before storing it into self.value.

 
class ParamsMissing(FormException)
    Required parameters are missing.
 
Attributes:
missingParamNames     list of strings containing all names of missing
                      input fields.
 
 
Method resolution order:
ParamsMissing
FormException
exceptions.Exception

Methods defined here:
__init__(self, missingParamNames)
__str__(self)

Methods inherited from FormException:
html(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class Password(Input)
    Password input field:
<input type=password>
 
 
Method resolution order:
Password
Input
Field

Methods defined here:
inputHTML(self, default=None, id_value=None, title=None)
valueHTML(self)
For security reasons only stars are printed

Methods inherited from Input:
__init__(self, name, text, maxLen, maxValues, pattern, required=0, default=None, accessKey='', size=None)

Methods inherited from Field:
getValue(self)
Returns self.value in case of multi-valued input or
self.value[0] if only one value is allowed.
idAttrStr(self, id_value)
labelHTML(self, labelText=None, for_value=None)
setCharset(self, charset)
Define the character set of the user's input.
setDefault(self, default)
Set the default of a field.
 
Mainly this is used by the application if self.default shall
be changed after initializing the field object.
setRegex(self, pattern)
Set the regex pattern for validating this field.
 
Mainly this is used if self._re shall be changed after
the field object was initialized.
 
pattern
    Either a string containing a regex pattern,
    a tuple (pattern string, pattern options) or None.
    If None regex checking in _validateFormat is switched off
    (not recommended).
setValue(self, value)
Store the user's value into the field object.
 
This method can be used to modify the user's value
before storing it into self.value.

 
class Radio(Field)
    Radio buttons:
<INPUT TYPE=RADIO>
 
  Methods defined here:
__init__(self, name, text, maxValues=1, required=0, default=None, accessKey='', options=None)
pattern and maxLen are determined from __init__ params
Additional parameters:
options=[]
  List of options. Either just a list of strings
  ['value1','value2',..] for simple options
  or a list of tuples of string pairs
  [('value1','description1),('value2','description2),..]
  for options with different option value and description.
inputHTML(self, default=None, id_value=None, title=None)
setDefault(self, default)
Set the default of a default field.
 
Mainly this is used if self.default shall be changed after
initializing the field object.
setOptions(self, options)

Methods inherited from Field:
getValue(self)
Returns self.value in case of multi-valued input or
self.value[0] if only one value is allowed.
idAttrStr(self, id_value)
labelHTML(self, labelText=None, for_value=None)
setCharset(self, charset)
Define the character set of the user's input.
setRegex(self, pattern)
Set the regex pattern for validating this field.
 
Mainly this is used if self._re shall be changed after
the field object was initialized.
 
pattern
    Either a string containing a regex pattern,
    a tuple (pattern string, pattern options) or None.
    If None regex checking in _validateFormat is switched off
    (not recommended).
setValue(self, value)
Store the user's value into the field object.
 
This method can be used to modify the user's value
before storing it into self.value.
valueHTML(self)
HTML output of self.value using the HTML template string
in self.valueHTMLTemplate.

 
class Select(Radio)
    Select field:
<select multiple>
  <option value="value">description</option>
</select>
 
 
Method resolution order:
Select
Radio
Field

Methods defined here:
__init__(self, name, text, maxValues, required=0, default=None, accessKey='', options=None, size=1, ignoreCase=0, multiSelect=0)
Additional parameters:
size
  Integer for the size of displayed select field.
ignorecase
  Integer flag. If non-zero the case of input strings is ignored
  when checking input values.
multiSelect
  Integer flag. If non-zero the select field has HTML attribute
  "multiple" set.
inputHTML(self, default=None, id_value=None, title=None)

Methods inherited from Radio:
setDefault(self, default)
Set the default of a default field.
 
Mainly this is used if self.default shall be changed after
initializing the field object.
setOptions(self, options)

Methods inherited from Field:
getValue(self)
Returns self.value in case of multi-valued input or
self.value[0] if only one value is allowed.
idAttrStr(self, id_value)
labelHTML(self, labelText=None, for_value=None)
setCharset(self, charset)
Define the character set of the user's input.
setRegex(self, pattern)
Set the regex pattern for validating this field.
 
Mainly this is used if self._re shall be changed after
the field object was initialized.
 
pattern
    Either a string containing a regex pattern,
    a tuple (pattern string, pattern options) or None.
    If None regex checking in _validateFormat is switched off
    (not recommended).
setValue(self, value)
Store the user's value into the field object.
 
This method can be used to modify the user's value
before storing it into self.value.
valueHTML(self)
HTML output of self.value using the HTML template string
in self.valueHTMLTemplate.

 
class Textarea(Field)
    Multi-line input field:
<textarea>
 
  Methods defined here:
__init__(self, name, text, maxLen, maxValues, pattern, required=0, default=None, accessKey='', rows=10, cols=60)
inputHTML(self, default=None, id_value=None, title=None)
Returns string with HTML input field.
setRegex(self, pattern)
Like Field.setRegex() but pattern options re.S and re.M are
automatically added.
valueHTML(self)
HTML output of self.value using the HTML template string
in self.valueHTMLTemplate.

Methods inherited from Field:
getValue(self)
Returns self.value in case of multi-valued input or
self.value[0] if only one value is allowed.
idAttrStr(self, id_value)
labelHTML(self, labelText=None, for_value=None)
setCharset(self, charset)
Define the character set of the user's input.
setDefault(self, default)
Set the default of a field.
 
Mainly this is used by the application if self.default shall
be changed after initializing the field object.
setValue(self, value)
Store the user's value into the field object.
 
This method can be used to modify the user's value
before storing it into self.value.

 
class TooManyValues(FormException)
    User's input contained too many values for same parameter.
 
Attributes:
name                  name of input field (Field.name)
text                  textual description of input field (Field.text)
valueCount            integer number of values counted with name
maxValueCount         integer number of maximum values with name allowed
 
 
Method resolution order:
TooManyValues
FormException
exceptions.Exception

Methods defined here:
__init__(self, name, text, valueCount, maxValueCount)
__str__(self)

Methods inherited from FormException:
html(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class UndeclaredFieldName(FormException)
    Parameter with undeclared name attribute received.
 
Attributes:
name          name of undeclared field
 
 
Method resolution order:
UndeclaredFieldName
FormException
exceptions.Exception

Methods defined here:
__init__(self, name)
__str__(self)

Methods inherited from FormException:
html(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
Functions
       
escapeHTML(s)
Escape all characters with a special meaning in HTML
to appropriate character tags

 
Data
        __version__ = '0.15.0'
pyweblib-1.3.9/htdocs/pydoc/pyweblib.sslenv.html0000755000076400001440000001072310112613726022551 0ustar michaelusers00000000000000 Python: module pyweblib.sslenv
 
 
pyweblib.sslenv (version 0.6.1)
index
/usr/lib/python2.3/site-packages/pyweblib/sslenv.py

pyweblib.sslenv.py - retrieve SSL data from environment vars
(C) by Michael Stroeder
 
This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)
 
$Id: pyweblib.sslenv.html,v 1.13 2004/08/24 10:26:30 michael Exp $

 
Modules
       
os
re
string
sys

 
Functions
       
GetAllSSLEnviron(env=None)
Get all SSL-related environment vars and return mod_ssl
compatible dictionary.
 
mod_ssl compatible names are preferred. ApacheSSL names
are used as fallback.
PrintSecInfo(env, acceptedciphers, valid_dn_regex='', valid_idn_regex='', f=<open file '<stdout>', mode 'w'>)
Print the SSL data in HTML format
SecLevel(env, acceptedciphers, valid_dn_regex='', valid_idn_regex='')
Determine Security Level of SSL session.
 
Returns:
0     no SSL at all
1     SSL-connection and cipher used is in acceptedciphers
2     like 1 but client also has sent client certificate
      matching valid_dn_regex and valid_idn_regex.
asn12html4(s)
Convert BMPString to HTML-4 character representation
t612html4(s)
Convert T.61 character representation to HTML-4 character representation

 
Data
        __version__ = '0.6.1'
pyweblib-1.3.9/htdocs/pydoc/pyweblib.helper.html0000755000076400001440000003442010112613726022516 0ustar michaelusers00000000000000 Python: module pyweblib.helper
 
 
pyweblib.helper (version 0.3.0)
index
/usr/lib/python2.3/site-packages/pyweblib/helper.py

pyweblib.helper - Misc. stuff useful in CGI-BINs
(c) by Michael Stroeder <michael@stroeder.com>
 
This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)
 
$Id: pyweblib.helper.html,v 1.12 2004/08/24 10:26:30 michael Exp $

 
Modules
       
UserDict
os
re

 
Classes
       
UserDict.UserDict
AcceptHeaderDict
AcceptCharsetDict

 
class AcceptCharsetDict(AcceptHeaderDict)
    Special class for Accept-Charset header
 
 
Method resolution order:
AcceptCharsetDict
AcceptHeaderDict
UserDict.UserDict

Methods defined here:
__init__(self, envKey='HTTP_ACCEPT_CHARSET', env=None, defaultValue='utf-8')
preferred(self)
Return the value name with highest capability weigth

Methods inherited from AcceptHeaderDict:
__getitem__(self, value)
value
    String representing the value for which to return
    the floating point capability weight.
items(self)
Return the accepted values as tuples (value,weigth)
in descending order of capability weight
keys(self)
Return the accepted values in descending order of capability weight

Methods inherited from UserDict.UserDict:
__cmp__(self, dict)
__contains__(self, key)
__delitem__(self, key)
__len__(self)
__repr__(self)
__setitem__(self, key, item)
clear(self)
copy(self)
get(self, key, failobj=None)
has_key(self, key)
iteritems(self)
iterkeys(self)
itervalues(self)
pop(self, key, *args)
popitem(self)
setdefault(self, key, failobj=None)
update(self, dict)
values(self)

Class methods inherited from UserDict.UserDict:
fromkeys(cls, iterable, value=None) from __builtin__.classobj

 
class AcceptHeaderDict(UserDict.UserDict)
    This dictionary class is used to parse
Accept-header lines with quality weights.
 
It's a base class for all Accept-* headers described
in sections 14.1 to 14.5 of RFC2616.
 
  Methods defined here:
__getitem__(self, value)
value
    String representing the value for which to return
    the floating point capability weight.
__init__(self, envKey, env=None, defaultValue=None)
Parse the Accept-* header line.
 
httpHeader
    string with value of Accept-* header line
items(self)
Return the accepted values as tuples (value,weigth)
in descending order of capability weight
keys(self)
Return the accepted values in descending order of capability weight

Methods inherited from UserDict.UserDict:
__cmp__(self, dict)
__contains__(self, key)
__delitem__(self, key)
__len__(self)
__repr__(self)
__setitem__(self, key, item)
clear(self)
copy(self)
get(self, key, failobj=None)
has_key(self, key)
iteritems(self)
iterkeys(self)
itervalues(self)
pop(self, key, *args)
popitem(self)
setdefault(self, key, failobj=None)
update(self, dict)
values(self)

Class methods inherited from UserDict.UserDict:
fromkeys(cls, iterable, value=None) from __builtin__.classobj

 
Functions
       
BrowserType(http_user_agent)
Parse the HTTP_USER_AGENT environment variable and return the
tuple (Browser,Version).
 
Not sure if this succeeds in every situation since most
browsers have very obscure HTTP_USER_AGENT entries for compability reasons.
The following browsers are known by name:
Netscape      Netscape Navigator, Netscape Communicator)
MSIE          MS Internet Explorer
Opera         Opera browser from http://www.operasoftware.com/
StarOffice    built-in browser of Star Office
Lynx          the text-based browser Lynx
NetPositive   Net Positive (BeOS)
guessClientAddr(env=None)
Guesses the host name or IP address of the HTTP client by looking
at various HTTP headers mapped to CGI-BIN environment.
 
env
      dictionary containing environment vars (default os.env)

 
Data
        __version__ = '0.3.0'
b = 'NetPositive'
compatible_browsers = ['Opera', 'StarOffice', 'Lynx', 'NCSA_Mosaic', 'MSIE', 'NetPositive']
compatible_browsers_re = <_sre.SRE_Pattern object>
known_browsers = {'Lynx': 'Lynx', 'MSIE': 'Microsoft Internet Explorer', 'Mozilla': 'Netscape Navigator', 'NCSA_Mosaic': 'NCSA Mosaic', 'NetPositive': 'Net Positive', 'Opera': 'Opera', 'StarOffice': 'StarOffice'}
known_browsers_rev = {'Lynx': 'Lynx', 'Microsoft Internet Explorer': 'MSIE', 'NCSA Mosaic': 'NCSA_Mosaic', 'Net Positive': 'NetPositive', 'Netscape Navigator': 'Mozilla', 'Opera': 'Opera', 'StarOffice': 'StarOffice'}
mozilla_re = <_sre.SRE_Pattern object>
pyweblib-1.3.9/htdocs/pydoc/pyweblib.session.html0000755000076400001440000005444110112613726022727 0ustar michaelusers00000000000000 Python: module pyweblib.session
 
 
pyweblib.session (version 0.3.4)
index
/usr/lib/python2.3/site-packages/pyweblib/session.py

pyweblib.session - server-side web session handling
(C) 2001 by Michael Stroeder <michael@stroeder.com>
 
This module implements server side session handling stored in
arbitrary string-keyed dictionary objects
 
This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)
 
$Id: pyweblib.session.html,v 1.13 2004/08/24 10:26:30 michael Exp $

 
Modules
       
pickle
random
re
string
threading
time

 
Classes
       
exceptions.Exception
SessionException
BadSessionId
CorruptData
GenerateIDError
InvalidSessionId
MaxSessionCountExceeded
SessionExpired
SessionHijacked
threading.Thread(threading._Verbose)
CleanUpThread
WebSession

 
class BadSessionId(SessionException)
    Raised if session ID not found in session dictionary.
 
 
Method resolution order:
BadSessionId
SessionException
exceptions.Exception

Methods defined here:
__init__(self, session_id)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class CleanUpThread(threading.Thread)
    Thread class for clean-up thread
 
 
Method resolution order:
CleanUpThread
threading.Thread
threading._Verbose
__builtin__.object

Methods defined here:
__init__(self, sessionInstance, interval=60)
__repr__(self)
join(self, timeout=0.0)
run(self)
Thread function for cleaning up session database

Methods inherited from threading.Thread:
getName(self)
isAlive(self)
isDaemon(self)
setDaemon(self, daemonic)
setName(self, name)
start(self)

Data and other attributes inherited from threading._Verbose:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of '_Verbose' objects>
list of weak references to the object (if defined)

 
class CorruptData(SessionException)
    Raised if data was corrupt, e.g. UnpicklingError occured
 
 
Method resolution order:
CorruptData
SessionException
exceptions.Exception

Methods defined here:
__str__(self)

Methods inherited from SessionException:
__init__(self, *args)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class GenerateIDError(SessionException)
    Raised if generation of unique session ID failed.
 
 
Method resolution order:
GenerateIDError
SessionException
exceptions.Exception

Methods defined here:
__init__(self, maxtry)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class InvalidSessionId(SessionException)
    Raised if session ID not found in session dictionary.
 
 
Method resolution order:
InvalidSessionId
SessionException
exceptions.Exception

Methods defined here:
__init__(self, session_id)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class MaxSessionCountExceeded(SessionException)
    Raised if maximum number of sessions is exceeded.
 
 
Method resolution order:
MaxSessionCountExceeded
SessionException
exceptions.Exception

Methods defined here:
__init__(self, max_session_count)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class SessionException(exceptions.Exception)
    Raised if
 
  Methods defined here:
__init__(self, *args)

Methods inherited from exceptions.Exception:
__getitem__(...)
__str__(...)

 
class SessionExpired(SessionException)
    Raised if session is expired.
 
 
Method resolution order:
SessionExpired
SessionException
exceptions.Exception

Methods defined here:
__init__(self, timestamp, session_data)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class SessionHijacked(SessionException)
    Raised if hijacking of session was detected.
 
 
Method resolution order:
SessionHijacked
SessionException
exceptions.Exception

Methods defined here:
__init__(self, failed_vars)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class WebSession
    The session class which handles storing and retrieving of session data
in a dictionary-like sessiondict object.
 
  Methods defined here:
__init__(self, dictobj=None, expireDeactivate=0, expireRemove=0, crossCheckVars=None, maxSessionCount=None)
dictobj
    has to be a instance of a dictionary-like object
    (e.g. derived from UserDict or shelve)
expireDeactivate    
    amount of time (secs) after which a session
    expires and a SessionExpired exception is
    raised which contains the session data.
expireRemove
    Amount of time (secs) after which a session
    expires and the session data is silently deleted.
    A InvalidSessionId exception is raised in this case if
    the application trys to access the session ID again.
crossCheckVars
    List of keys of variables cross-checked for each
    retrieval of session data in retrieveSession(). If None
    SESSION_CROSSCHECKVARS is used.
maxSessionCount
    Maximum number of valid sessions. This affects
    behaviour of retrieveSession() which raises.
    None means unlimited number of sessions.
cleanUp(self)
Search for expired session entries and delete them.
 
Returns integer counter of deleted sessions as result.
close(self)
Call close() if self.sessiondict has .close() method
deleteSession(self, session_id)
Delete session_data referenced by session_id.
newSession(self, env={})
Store session data under session id
retrieveSession(self, session_id, env={})
Retrieve session data
storeSession(self, session_id, session_data)
Store session_data under session_id.
sync(self)
Call sync if self.sessiondict has .sync() method

 
Functions
       
ThreadingLock = allocate_lock(...)
allocate_lock() -> lock object
(allocate() is an obsolete synonym)
 
Create a new lock object.  See LockType.__doc__ for information about locks.

 
Data
        SESSION_CROSSCHECKVARS = ('\n List of environment variables assumed to be c...gh a network of web proxy siblings.\n REMOTE_ADDR', 'REMOTE_HOST', 'REMOTE_IDENT', 'REMOTE_USER', 'FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'HTTP_USER_AGENT', 'HTTP_ACCEPT_CHARSET', 'SSL_SESSION_ID', 'SSL_CLIENT_V_START', 'SSL_CLIENT_V_END', 'SSL_CLIENT_I_DN', 'SSL_CLIENT_IDN', 'SSL_CLIENT_S_DN', 'SSL_CLIENT_SDN', 'SSL_CLIENT_M_SERIAL', 'SSL_CLIENT_CERT_SERIAL')
SESSION_ID_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
__version__ = '0.3.4'
pyweblib-1.3.9/MANIFEST.in0000755000076400001440000000017310070510404015657 0ustar michaelusers00000000000000include CHANGES MANIFEST.in recursive-include pyweblib *.py recursive-include htdocs *.html recursive-include cgi-bin *.py pyweblib-1.3.9/pyweblib/0000755000076400001440000000000011745325171015751 5ustar michaelusers00000000000000pyweblib-1.3.9/pyweblib/__init__.py0000644000076400001440000000130011610333565020051 0ustar michaelusers00000000000000""" pyweblib - several modules for web programming tasks (C) 2001 by Michael Stroeder This module including sub-modules is distributed under the terms of the GPL (GNU GENERAL PUBLIC LICENSE) Version 2 (see http://www.gnu.org/copyleft/gpl.html) Compability note: requires Python 2.0+ Sub modules: pyweblib.forms class library for handling

input pyweblib.session server-side web session handling pyweblib.helper misc. stuff useful in CGI-BINs pyweblib.sslenv retrieves SSL-related env vars pyweblib.httphelper very basic HTTP functions $Id: __init__.py,v 1.33 2011/07/16 16:08:21 michael Exp $ """ __version__ = '1.3.9' pyweblib-1.3.9/pyweblib/helper.py0000644000076400001440000001165411540364750017610 0ustar michaelusers00000000000000""" pyweblib.helper - Misc. stuff useful in CGI-BINs (c) by Michael Stroeder This module is distributed under the terms of the GPL (GNU GENERAL PUBLIC LICENSE) Version 2 (see http://www.gnu.org/copyleft/gpl.html) $Id: helper.py,v 1.15 2011/01/16 09:04:10 michael Exp $ """ __version__ = '0.3.1' import os,re,UserDict known_browsers = { 'MSIE':'Microsoft Internet Explorer', 'Mozilla':'Netscape Navigator', 'Lynx':'Lynx', 'Opera':'Opera', 'StarOffice':'StarOffice', 'NCSA_Mosaic':'NCSA Mosaic', 'NetPositive':'Net Positive', 'Mozilla':'Firefox', 'Mozilla':'Seamonkey', } known_browsers_rev = {} for b in known_browsers.keys(): known_browsers_rev[known_browsers[b]]=b compatible_browsers = known_browsers.keys() compatible_browsers.remove('Mozilla') compatible_browsers_re = re.compile('(%s)[/ ]+([0-9.]*)' % '|'.join(compatible_browsers)) mozilla_re = re.compile('(Mozilla)[/ ]+([0-9.]*)') def BrowserType(http_user_agent): """ Parse the HTTP_USER_AGENT environment variable and return the tuple (Browser,Version). Not sure if this succeeds in every situation since most browsers have very obscure HTTP_USER_AGENT entries for compability reasons. The following browsers are known by name: Netscape Netscape Navigator, Netscape Communicator) MSIE MS Internet Explorer Opera Opera browser from http://www.operasoftware.com/ StarOffice built-in browser of Star Office Lynx the text-based browser Lynx NetPositive Net Positive (BeOS) """ if not http_user_agent: return ('','') else: browserrm = compatible_browsers_re.search(http_user_agent) if browserrm: return browserrm.groups() else: browserrm = mozilla_re.search(http_user_agent) if browserrm: return browserrm.groups() else: return ('','') def guessClientAddr(env=None): """ Guesses the host name or IP address of the HTTP client by looking at various HTTP headers mapped to CGI-BIN environment. env dictionary containing environment vars (default os.env) """ env = env or os.environ return env.get('FORWARDED_FOR', env.get('HTTP_X_FORWARDED_FOR', env.get('REMOTE_HOST', env.get('REMOTE_ADDR',None)))) class AcceptHeaderDict(UserDict.UserDict): """ This dictionary class is used to parse Accept-header lines with quality weights. It's a base class for all Accept-* headers described in sections 14.1 to 14.5 of RFC2616. """ def __init__(self,envKey,env=None,defaultValue=None): """ Parse the Accept-* header line. httpHeader string with value of Accept-* header line """ env = env or os.environ UserDict.UserDict.__init__(self) self.defaultValue = defaultValue self.preferred_value = [] try: http_accept_value = [ s for s in env[envKey].strip().split(',') if len(s) ] except KeyError: self.data = {'*':1.0} else: if not http_accept_value: self.data = {'*':1.0} else: self.data = {} for i in http_accept_value: try: c,w=i.split(';') except ValueError: c,w = i,'' # Normalize charset name c=c.strip().lower() try: q,qvalue_str=w.split('=',1) qvalue = float(qvalue_str) except ValueError: qvalue = 1.0 # Add to capability dictionary if c: self.data[c] = qvalue return # AcceptHeaderDict.__init__() def __getitem__(self,value): """ value String representing the value for which to return the floating point capability weight. """ return self.data.get( value.lower(), self.data.get('*',0) ) def items(self): """ Return the accepted values as tuples (value,weigth) in descending order of capability weight """ l = self.data.items() l.sort(lambda x,y:cmp(y[1],x[1])) return l def keys(self): """ Return the accepted values in descending order of capability weight """ l = self.items() return [ k for k,v in l ] class AcceptCharsetDict(AcceptHeaderDict): """ Special class for Accept-Charset header """ def __init__(self,envKey='HTTP_ACCEPT_CHARSET',env=None,defaultValue='utf-8'): AcceptHeaderDict.__init__(self,envKey,env,defaultValue) # Special treating of ISO-8859-1 charset to be compliant to RFC2616 self.data['iso-8859-1'] = self.data.get('iso-8859-1',self.data.get('*',1.0)) return # AcceptCharsetDict.__init__() def preferred(self): """ Return the value name with highest capability weigth """ l = self.items() while l and l[0][0]!='*': try: u''.encode(l[0][0]) except LookupError: l.pop(0) else: break if l: if self.defaultValue and l[0][0]=='*': return self.defaultValue else: return l[0][0] else: return self.defaultValue pyweblib-1.3.9/pyweblib/forms.py0000644000076400001440000007112211730635634017456 0ustar michaelusers00000000000000""" pyweblib.forms - class library for handling input (c) by Michael Stroeder This module is distributed under the terms of the GPL (GNU GENERAL PUBLIC LICENSE) Version 2 (see http://www.gnu.org/copyleft/gpl.html) Python compability note: This module only works with Python 2.0 since all string parameters are assumed to be Unicode objects and string methods are used instead string module. $Id: forms.py,v 1.47 2012/03/16 13:09:48 michael Exp $ """ __version__ = '0.16.0' import sys,types,re,urllib import helper def escapeHTML(s): """ Escape all characters with a special meaning in HTML to appropriate character tags """ s = s.replace('&','&') s = s.replace('<','<') s = s.replace('>','>') s = s.replace("'",''') s = s.replace('"','"') s = s.replace(':',':') s = s.replace('=','=') s = s.replace('{','{') s = s.replace('}','}') s = s.replace('(','(') s = s.replace(')',')') s = s.replace('`','`') return s class Field: """ Base class for all kind of single input fields. In most cases this class is not used directly since derivate classes for most types of input fields exist. """ def __init__( self,name,text,maxLen,maxValues,pattern,required=0,default=None,accessKey='', ): """ name Field name used in text User-friendly text describing this field maxLen maximum length of a single input value [Bytes] maxValues maximum amount of input values default default value to be used in method inputfield() required flag which marks field as mandantory input field accessKey key for accessing this field to be displayed by method inputHTML() pattern regex pattern of valid values either as string or tuple (pattern,options) """ self.value = [] self.name = name self.text = text self.maxLen = maxLen self.maxValues = maxValues self.required = required self.accessKey = accessKey self.inputHTMLTemplate = r'%s' self.valueHTMLTemplate = r'%s' # Charset is the preferred character set of the browser. # This is set by Form.add() the something meaningful. self.charset = 'iso-8859-1' self.setDefault(default) self.setRegex(pattern) def _accessKeyAttr(self): if self.accessKey: return 'accesskey="%s"' % (self.accessKey) else: return '' def idAttrStr(self,id_value): if id_value is None: return '' else: return 'id="%s" ' % (id_value) def labelHTML(self,labelText=None,for_value=None): labelText = (labelText or self.text).encode(self.charset) return '' % (for_value or self.name,labelText) def getValue(self): """ Returns self.value in case of multi-valued input or self.value[0] if only one value is allowed. """ if self.maxValues>1: return self.value else: return self.value[0] def setDefault(self,default): """ Set the default of a field. Mainly this is used by the application if self.default shall be changed after initializing the field object. """ if type(default)==types.ListType: self.default = [i for i in default if i!=None] else: self.default = default or '' def _patternAndOptions(self,pattern): """ The result is a tuple (pattern string,pattern options). pattern Either a string containing a regex pattern, a tuple (pattern string, pattern options) or None. """ if type(pattern) is types.TupleType: return pattern else: return pattern, 0 def setRegex(self,pattern): """ Set the regex pattern for validating this field. Mainly this is used if self._re shall be changed after the field object was initialized. pattern Either a string containing a regex pattern, a tuple (pattern string, pattern options) or None. If None regex checking in _validateFormat is switched off (not recommended). """ patternstring,patternoptions = self._patternAndOptions(pattern) if patternstring is None: # Regex checking is completely switched off self._re = None else: # This is a Unicode input field patternoptions = patternoptions | re.U self._re = re.compile('%s$' % patternstring,patternoptions) def _validateLen(self,value): """Check length of the user's value for this field.""" if len(value)>self.maxLen: raise InvalidValueLen(self.name,self.text,len(value),self.maxLen) def _validateFormat(self,value): """ Check format of the user's value for this field. Empty input (zero-length string) are valid in any case. You might override this method to change this behaviour. """ if (not self._re is None) and value: rm = self._re.match(value) if rm is None: raise InvalidValueFormat( self.name, self.text.encode(self.charset), value.encode(self.charset) ) def _validateMaxValue(self): if len(self.value)>=self.maxValues: raise TooManyValues(self.name,self.text,len(self.value),self.maxValues) def _encodeValue(self,value): """ Return Unicode object or string to be stored in self.value """ try: value = unicode(value,self.charset) except UnicodeError: # Work around buggy browsers... value = unicode(value,'iso-8859-1') return value def setValue(self,value): """ Store the user's value into the field object. This method can be used to modify the user's value before storing it into self.value. """ value = self._encodeValue(value) # Check if input is valid # Length valid? self._validateLen(value) # Format valid? self._validateFormat(value) self._validateMaxValue() self.value.append(value) def setCharset(self,charset): """Define the character set of the user's input.""" self.charset = charset def _defaultValue(self,default): """returns default value""" return default or self.__dict__.get('default','') def titleHTML(self,title): """HTML output of default.""" return escapeHTML(title or self.text).encode(self.charset) def _defaultHTML(self,default): """HTML output of default.""" return escapeHTML(self._defaultValue(default)).encode(self.charset) def valueHTML(self): """ HTML output of self.value using the HTML template string in self.valueHTMLTemplate. """ return [ self.valueHTMLTemplate % v for v in self.value ] class Textarea(Field): """ Multi-line input field: ' % ( self.idAttrStr(id_value), self.titleHTML(title), self.name, self._accessKeyAttr(), self.rows,self.cols, self._defaultHTML(default) ) ) def valueHTML(self): """ HTML output of self.value using the HTML template string in self.valueHTMLTemplate. """ return [ self.valueHTMLTemplate % '
%s
' % v for v in self.value ] class Input(Field): """ Normal one-line input field: """ def __init__( self,name,text,maxLen,maxValues,pattern,required=0,default=None,accessKey='', size=None ): self.size = size or maxLen Field.__init__( self,name,text,maxLen,maxValues,pattern,required,default,accessKey, ) def inputHTML(self,default=None,id_value=None,title=None): return self.inputHTMLTemplate % ( '' % ( self.idAttrStr(id_value), self.titleHTML(title), self.name, self._accessKeyAttr(), self.maxLen, self.size, self._defaultHTML(default) ) ) class HiddenInput(Input): """ Hidden input field: """ def __init__( self,name,text,maxLen,maxValues,pattern,required=0,default=None,accessKey='' ): Input.__init__( self,name,text,maxLen,maxValues,pattern,required,default,accessKey, ) def inputHTML(self,default=None,id_value=None,title=None,show=0): default_html = self._defaultHTML(default) if show: default_str = default_html else: default_str = '' return self.inputHTMLTemplate % ( '%s' % ( self.idAttrStr(id_value), self.titleHTML(title), self.name, self._accessKeyAttr(), default_html, default_str ) ) class File(Input): """ File upload field """ mimeType='application/octet-stream' def _validateFormat(self,value): """Binary data is assumed to be valid all the time""" return def _encodeValue(self,value): """ Return Unicode object or string to be stored in self.value """ return value def inputHTML(self,default=None,id_value=None,title=None,mimeType=None): return self.inputHTMLTemplate % ( '' % ( self.idAttrStr(id_value), self.titleHTML(title), self.name, self._accessKeyAttr(), mimeType or self.mimeType ) ) class Password(Input): """ Password input field: """ def inputHTML(self,default=None,id_value=None,title=None): return self.inputHTMLTemplate % ( '' % ( self.idAttrStr(id_value), self.titleHTML(title), self.name, self._accessKeyAttr(), self.maxLen, self.size, default or '' ) ) def valueHTML(self): """For security reasons only stars are printed""" return [ self.valueHTMLTemplate % (len(v)*'*') for v in self.value ] class Radio(Field): """ Radio buttons: """ def __init__( self,name,text,maxValues=1,required=0,default=None,accessKey='', options=None ): """ pattern and maxLen are determined from __init__ params Additional parameters: options=[] List of options. Either just a list of strings ['value1','value2',..] for simple options or a list of tuples of string pairs [('value1','description1),('value2','description2),..] for options with different option value and description. """ self.setOptions(options) self.setDefault(default) Field.__init__( self,name,text,self.maxLen,maxValues,'',required,default,accessKey ) def _validateFormat(self,value): """ Check format of the user's value for this field. Empty input (zero-length string) are valid in any case. You might override this method to change this behaviour. """ if value and (not value in self.optionValues): raise InvalidValueFormat( self.name, self.text.encode(self.charset), value.encode(self.charset) ) def setOptions(self,options): self.optionValues = {} self.maxLen = 0 if options: optionValues = [] for i in options: if type(i) is types.TupleType: optionValue = i[0] else: optionValue = i self.optionValues[optionValue] = None self.maxLen = max(map(len,self.optionValues.keys())) self.options = options def inputHTML(self,default=None,id_value=None,title=None): s = [] default_value = self._defaultValue(default) for i in self.options: if type(i) is types.TupleType: optionValue,optionText = i else: optionValue = optionText = i s.append(""" %s
""" % ( self.idAttrStr(id_value), self.titleHTML(title), self.name.encode(self.charset), self._accessKeyAttr(), optionValue, ' checked'*(optionValue==default_value), optionText ) ) return self.inputHTMLTemplate % '\n'.join(s) def setDefault(self,default): """ Set the default of a default field. Mainly this is used if self.default shall be changed after initializing the field object. """ optionValues = [] for i in self.options: if type(i) is types.TupleType: optionValues.append(i[0]) else: optionValues.append(i) if type(default)==types.StringType and not default in optionValues: # Append option to list of options if singleton self.options.append(default) elif type(default)==types.ListType: # Extend list of options with items in default which are not in options self.options.extend(filter(lambda x,o=optionValues:not x in o,default)) self.default = default class Select(Radio): """ Select field: """ def __init__( self,name,text,maxValues,required=0,default=None,accessKey='', options=None,size=1,ignoreCase=0,multiSelect=0, ): """ Additional parameters: size Integer for the size of displayed select field. ignorecase Integer flag. If non-zero the case of input strings is ignored when checking input values. multiSelect Integer flag. If non-zero the select field has HTML attribute "multiple" set. """ self.size = size self.multiSelect = multiSelect self.ignoreCase = ignoreCase Radio.__init__( self,name,text,maxValues,required,default,accessKey,options, ) def inputHTML(self,default=None,id_value=None,title=None): s = ['') return self.inputHTMLTemplate % '\n'.join(s) class Checkbox(Field): """ Check boxes: """ def __init__( self,name,text,maxValues=1,required=0,accessKey='', default=None,checked=0 ): """ pattern and maxLen are determined by default """ pattern = default maxLen = len(default or '') self.checked = checked Field.__init__( self,name,text,maxLen,maxValues,pattern,required,default,accessKey ) def inputHTML(self,default=None,id_value=None,title=None,checked=None): if checked is None: checked = self.checked return self.inputHTMLTemplate % ( '' % ( self.idAttrStr(id_value), self.titleHTML(title), self.name, self._accessKeyAttr(), self._defaultValue(default),' checked'*(checked) ) ) class Keygen(Field): """ Select field for client-side key generation with Netscape/Mozilla/Opera browser: """ def __init__( self,name,text,maxLen,maxValues,required=0, minKeyLength=512 ): Field.__init__( self,name,text,maxLen,maxValues,(r'[ -z\r\n]*',re.M+re.S),required ) self.minKeyLength = minKeyLength def _encodeValue(self,value): return value.replace('\n','').replace('\r','') def inputHTML(self,challenge,id_value=None,title=None,): return self.inputHTMLTemplate % ( '' % ( self.idAttrStr(id_value), self.titleHTML(title), self.name, self._accessKeyAttr(), challenge ) ) def valueHTML(self): return self.valueHTMLTemplate % ('%d Bytes' % (len(self.value))) class FormException(Exception): """ Base exception class to indicate form processing errors. Attributes: args unstructured List of parameters """ def __init__(self,*args,**kwargs): self.args = args for key,value in kwargs.items(): setattr(self,key,value) def html(self): return escapeHTML(str(self)) class InvalidRequestMethod(FormException): """ Exception raised when HTTP request method was invalid. Attributes: method string containing method used """ def __init__(self,method): self.method = method def __str__(self): return 'Invalid request method %s.' % (self.method) class InvalidFormEncoding(FormException): """ The form data is malformed. Attributes: param name/value causing the exception """ def __init__(self,param): self.param = param def __str__(self): return 'The form data is malformed.' class ContentLengthExceeded(FormException): """ Overall length of input data too large. Attributes: contentLength received content length maxContentLength maximum valid content length """ def __init__(self,contentLength,maxContentLength): self.contentLength = contentLength self.maxContentLength = maxContentLength def __str__(self): return 'Input length of %d bytes exceeded the maximum of %d bytes.' % ( self.contentLength,self.maxContentLength ) class UndeclaredFieldName(FormException): """ Parameter with undeclared name attribute received. Attributes: name name of undeclared field """ def __init__(self,name): self.name = name def __str__(self): return 'Unknown parameter %s.' % (self.name) class ParamsMissing(FormException): """ Required parameters are missing. Attributes: missingParamNames list of strings containing all names of missing input fields. """ def __init__(self,missingParamNames): self.missingParamNames = missingParamNames def __str__(self): return 'Required fields missing: %s' % ( ', '.join( map( lambda i:'%s (%s)' % (i[1],i[0]), self.missingParamNames ) ) ) class InvalidValueFormat(FormException): """ The user's input does not match the required format. Attributes: name name of input field (Field.name) text textual description of input field (Field.text) value input value received """ def __init__(self,name,text,value): self.name = name self.text = text self.value = value def __str__(self): return 'Input value "%s" for field %s (%s) has invalid format.' % ( self.value,self.text,self.name ) class InvalidValueLen(FormException): """ Length of user input value invalid. Attributes: name name of input field (Field.name) text textual description of input field (Field.text) valueLen integer number of received value length maxValueLen integer number of maximum value length """ def __init__(self,name,text,valueLen,maxValueLen): self.name = name self.text = text self.valueLen = valueLen self.maxValueLen = maxValueLen def __str__(self): return 'Content too long. Field %s (%s) has %d characters but is limited to %d.' % ( self.text,self.name,self.valueLen,self.maxValueLen ) class TooManyValues(FormException): """ User's input contained too many values for same parameter. Attributes: name name of input field (Field.name) text textual description of input field (Field.text) valueCount integer number of values counted with name maxValueCount integer number of maximum values with name allowed """ def __init__(self,name,text,valueCount,maxValueCount): self.name = name self.text = text self.valueCount = valueCount self.maxValueCount = maxValueCount def __str__(self): return '%d values for field %s (%s). Limited to %d input values.' % ( self.valueCount,self.text,self.name,self.maxValueCount ) class Form: """ Class for declaring and processing a whole """ def __init__(self,inf,env): """ Initialize a Form inf Read from this file object if method is POST. env Dictionary holding the environment vars. """ # Dictionary of Field objects self.field = {} # Ordered list of input field names self.declaredFieldNames = [] # List of parameters names received self.inputFieldNames = [] # Save the environment vars self.env = env # input file object self.inf = inf or sys.stdin # Save request method self.request_method = env['REQUEST_METHOD'] self.script_name = env['SCRIPT_NAME'] # Initialize the AcceptHeaderDict objects self.http_accept_charset = helper.AcceptCharsetDict('HTTP_ACCEPT_CHARSET',env) self.http_accept_language = helper.AcceptHeaderDict('HTTP_ACCEPT_LANGUAGE',env) self.accept_language = self.http_accept_language.keys() self.http_accept_encoding = helper.AcceptHeaderDict('HTTP_ACCEPT_ENCODING',env) # Set the preferred character set self.accept_charset = self.http_accept_charset.preferred() # Determine query string and content length dependent on request method self.checkRequestMethod() return # Form.__init__() def checkRequestMethod(self): """ Checks whether the HTTP request method is accepted """ if not self.request_method in ['POST','GET']: raise InvalidRequestMethod(self.request_method) def getContentType(self): """ Determine the HTTP content type of HTTP request """ if self.request_method=='POST': return self.env.get('CONTENT_TYPE','application/x-www-form-urlencoded').lower() or None elif self.request_method=='GET': return 'application/x-www-form-urlencoded' def addField(self,f): """ Add a input field object f to the form. """ f.setCharset(self.accept_charset) self.field[f.name] = f if not f.name in self.declaredFieldNames: self.declaredFieldNames.append(f.name) return # Form.addField() def getInputValue(self,name,default=[]): """ Return input value of a field defined by name if presented in form input. Return default else. """ if name in self.inputFieldNames: return self.field[name].value else: return default def hiddenInputFields(self,outf=sys.stdout,ignoreFieldNames=None): """ Output all parameters as hidden fields. outf File object for output. ignoreFieldNames Names of parameters to be excluded. """ ignoreFieldNames=ignoreFieldNames or [] for f in [ self.field[p] for p in self.declaredFieldNames if (p in self.inputFieldNames) and not (p in ignoreFieldNames) ]: for v in f.value: outf.write( '\n\r' % ( f.name.encode(f.charset),escapeHTML(v.encode(f.charset)) ) ) return # Form.hiddenInputFields() def _parseFormUrlEncoded(self,maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote): if self.request_method=='POST': query_string = self.inf.read(int(self.env['CONTENT_LENGTH'])) elif self.request_method=='GET': query_string = self.env.get('QUERY_STRING','') self.inf.close() inputlist = query_string.split('&') contentLength = 0 # Loop over all name attributes declared for param in inputlist: if param: # Einzelne Parametername/-daten-Paare auseinandernehmen try: name,value = param.split('=',1) except ValueError: raise InvalidFormEncoding(param) name = unquote(name).strip() if not name in self.declaredFieldNames: if ignoreUndeclaredFields: continue else: raise UndeclaredFieldName(name) value = unquote(value) if stripValues: value = value.strip() contentLength += len(value) # Gesamtlaenge der Daten noch zulaessig? if contentLength > maxContentLength: raise ContentLengthExceeded(contentLength,maxContentLength) f = self.field[name] # input is empty string? if value or (not ignoreEmptyFields): # Input is stored in field instance f.setValue(value) # Add name of field to list of input keys if not name in self.inputFieldNames: self.inputFieldNames.append(name) return #_parseFormUrlEncoded() def _parseMultipartFormData(self,maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote): import cgi ctype, pdict = cgi.parse_header(self.env['CONTENT_TYPE']) parts = cgi.parse_multipart(self.inf,pdict) contentLength = 0 for name in parts.keys(): if not name in self.declaredFieldNames: if ignoreUndeclaredFields: continue else: raise UndeclaredFieldName(name) for value in parts[name]: # if stripValues: # value = value.strip() contentLength += len(value) # Gesamtlaenge der Daten noch zulaessig? if contentLength > maxContentLength: raise ContentLengthExceeded(contentLength,maxContentLength) f = self.field[name] # input is empty string? if value or (not ignoreEmptyFields): # Input is stored in field instance f.setValue(value) # Add name of field to list of input keys if not name in self.inputFieldNames: self.inputFieldNames.append(name) return # _parseMultipartFormData() def getInputFields( self, ignoreEmptyFields=0, ignoreUndeclaredFields=0, stripValues=1, unquotePlus=0, ): """ Process user's input and store the values in each field instance's content attribute. When a processing error occurs FormException (or derivatives) are raised. ignoreEmptyFields=0 Ignore fields with empty input. ignoreUndeclaredFields=0 Ignore fields with names not declared. Normally UndeclaredFieldName is raised. stripValues=1 If true leading and trailing whitespaces are stripped from all input values. unquotePlus=0 If non-zero urllib.unquote_plus() is used instead of urllib.unquote(). """ unquote = {0:urllib.unquote_plus,1:urllib.unquote_plus}[unquotePlus] # Calculate maxContentLength maxContentLength = 0 for name,f in self.field.items(): maxContentLength += f.maxValues*f.maxLen content_type = self.getContentType() if content_type.startswith('application/x-www-form-urlencoded'): # Parse user's input self._parseFormUrlEncoded(maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote) elif content_type.startswith('multipart/form-data'): self._parseMultipartFormData(maxContentLength,ignoreEmptyFields,ignoreUndeclaredFields,stripValues,unquote) else: raise FormException('Invalid content type %s received' % (repr(content_type))) # Are all required parameters present? missing_params = [] for n,f in self.field.items(): if f.required and not (f.name in self.inputFieldNames): missing_params.append((f.name,f.text)) if missing_params: raise ParamsMissing(missing_params) return # Form.getInputFields() pyweblib-1.3.9/pyweblib/httphelper.py0000644000076400001440000000632311461761136020506 0ustar michaelusers00000000000000""" httphelper.py - basic HTTP-related functions (c) by Michael Stroeder This module is distributed under the terms of the GPL (GNU GENERAL PUBLIC LICENSE) Version 2 (see http://www.gnu.org/copyleft/gpl.html) $Id: httphelper.py,v 1.13 2010/10/27 08:27:10 michael Exp $ """ __version__ = '0.0.5' import sys,time HTTP_LINESEP = '\r\n' def DateTimeRFC1123(secs=0): """ Return seconds as RFC1123 date/time format preferred for HTTP 1.1 (see RFC2616) """ return time.strftime( '%a, %d %b %Y %H:%M:%S GMT', time.gmtime(secs) ) # Write HTTP-Header def SendHeader( outf=sys.stdout, contenttype='text/html', charset='ISO-8859-1', contentlength=None, expires_offset=0, current_datetime=None, additional_header=None ): """ Generate HTTP header outf File object used for sending to client. contenttype MIME type of object in HTTP body. Default is 'text/html'. charset Character set used. Default is 'ISO-8859-1'. contentlength Content-Length if known and gzip-encoding is not used. Default is None indicating unknown length. expires_offset=0, Expiry time from current time in seconds. Default is 0. current_datetime Last modification time in seconds. If zero (default) 'Last-modified' header will be omitted. additional_header Dictionary containing arbitrary additional HTTP header fields as key/value-pairs. """ additional_header = additional_header or {} gzip = hasattr(outf,'fileobj') # Get current time as GMT (seconds since epoch) gmt = time.time() # Determine times for HTTP header if current_datetime is None: current_datetime = DateTimeRFC1123(gmt) expires = DateTimeRFC1123(gmt+expires_offset) # Build list of header lines header_lines = [] # Write header if not (contenttype is None): if contenttype.lower().startswith('text/'): header_lines.append('Content-Type: %s;charset=%s' % (contenttype,charset)) else: header_lines.append('Content-Type: %s' % (contenttype)) if not (contentlength is None): header_lines.append('Content-Length: %d' % (contentlength)) if gzip: header_lines.append('Content-Encoding: gzip') header_lines.append('Vary: Accept-Encoding') header_lines.append('Date: %s' % (current_datetime)) header_lines.append('Last-Modified: %s' % (current_datetime)) header_lines.append('Expires: %s' % (expires)) for h,v in additional_header.items(): header_lines.append('%s: %s' % (h,v)) # Write empty end-of-header line header_lines.extend(['','']) if gzip: outf.fileobj.write(HTTP_LINESEP.join(header_lines)) outf.fileobj.flush() else: outf.write(HTTP_LINESEP.join(header_lines)) return def SimpleMsg(outf,msg): """ Output HTML text. """ SendHeader(outf) outf.write(""" Note %s """ % (msg) ) def URLRedirect(outf,url,refreshtime=0,msg='Redirecting...'): """ Output HTML text with redirecting section. """ SendHeader(outf) outf.write(""" %s Redirecting... """ % (refreshtime,url,msg,url) ) pyweblib-1.3.9/pyweblib/sslenv.py0000644000076400001440000002146211552320105017626 0ustar michaelusers00000000000000""" pyweblib.sslenv.py - retrieve SSL data from environment vars (C) by Michael Stroeder This module is distributed under the terms of the GPL (GNU GENERAL PUBLIC LICENSE) Version 2 (see http://www.gnu.org/copyleft/gpl.html) $Id: sslenv.py,v 1.11 2011/04/16 13:57:25 michael Exp $ """ __version__ = '0.6.3' from forms import escapeHTML import sys,os,re,string def GetAllSSLEnviron(env=None): """ Get all SSL-related environment vars and return mod_ssl compatible dictionary. mod_ssl compatible names are preferred. ApacheSSL names are used as fallback. """ env = env or os.environ if env.get('HTTPS','off')!='on': return {} SSLEnv = {} SSLEnv['SSL_CIPHER_ALGKEYSIZE'] = \ env.get('SSL_CIPHER_ALGKEYSIZE', env.get('HTTPS_KEYSIZE', env.get('SSL_KEYSIZE', env.get('SSL_SERVER_KEY_SIZE', None)))) SSLEnv['SSL_CIPHER_EXPORT'] = \ env.get('SSL_CIPHER_EXPORT', env.get('HTTPS_EXPORT', env.get('SSL_EXPORT', None))) SSLEnv['SSL_CIPHER'] = \ env.get('SSL_CIPHER', env.get('HTTPS_CIPHER', None)) SSLEnv['SSL_CIPHER_USEKEYSIZE'] = \ env.get('SSL_CIPHER_USEKEYSIZE', env.get('HTTPS_SECRETKEYSIZE', env.get('SSL_SECKEYSIZE', None))) SSLEnv['SSL_CLIENT_A_SIG'] = \ env.get('SSL_CLIENT_A_SIG', env.get('SSL_CLIENT_SIGNATURE_ALGORITHM', None)) SSLEnv['SSL_CLIENT_CERT'] = \ env.get('SSL_CLIENT_CERT', env.get('SSL_CLIENT_CERTIFICATE', None)) SSLEnv['SSL_CLIENT_I_DN'] = \ env.get('SSL_CLIENT_I_DN', env.get('SSL_CLIENT_IDN', None)) SSLEnv['SSL_CLIENT_I_DN_CN'] = \ env.get('SSL_CLIENT_I_DN_CN', env.get('SSL_CLIENT_ICN', None)) SSLEnv['SSL_CLIENT_I_DN_C'] = \ env.get('SSL_CLIENT_I_DN_C', env.get('SSL_CLIENT_IC', None)) SSLEnv['SSL_CLIENT_I_DN_Email'] = \ env.get('SSL_CLIENT_I_DN_Email', env.get('SSL_CLIENT_IEMAIL', None)) SSLEnv['SSL_CLIENT_I_DN_L'] = \ env.get('SSL_CLIENT_I_DN_L', env.get('SSL_CLIENT_IL', None)) SSLEnv['SSL_CLIENT_I_DN_O'] = \ env.get('SSL_CLIENT_I_DN_O', env.get('SSL_CLIENT_IO', None)) SSLEnv['SSL_CLIENT_I_DN_OU'] = \ env.get('SSL_CLIENT_I_DN_OU', env.get('SSL_CLIENT_IOU', None)) SSLEnv['SSL_CLIENT_I_DN_SP'] = \ env.get('SSL_CLIENT_I_DN_SP', env.get('SSL_CLIENT_ISP', None)) SSLEnv['SSL_CLIENT_M_SERIAL'] = \ env.get('SSL_CLIENT_M_SERIAL', env.get('SSL_CLIENT_CERT_SERIAL', None)) SSLEnv['SSL_CLIENT_S_DN'] = \ env.get('SSL_CLIENT_S_DN', env.get('SSL_CLIENT_DN', None)) SSLEnv['SSL_CLIENT_S_DN_CN'] = \ env.get('SSL_CLIENT_S_DN_CN', env.get('SSL_CLIENT_CN', None)) SSLEnv['SSL_CLIENT_S_DN_C'] = \ env.get('SSL_CLIENT_S_DN_C', env.get('SSL_CLIENT_C', None)) SSLEnv['SSL_CLIENT_S_DN_Email'] = \ env.get('SSL_CLIENT_S_DN_Email', env.get('SSL_CLIENT_EMAIL', None)) SSLEnv['SSL_CLIENT_S_DN_L'] = \ env.get('SSL_CLIENT_S_DN_L', env.get('SSL_CLIENT_L', None)) SSLEnv['SSL_CLIENT_S_DN_O'] = \ env.get('SSL_CLIENT_S_DN_O', env.get('SSL_CLIENT_O', None)) SSLEnv['SSL_CLIENT_S_DN_OU'] = \ env.get('SSL_CLIENT_S_DN_OU', env.get('SSL_CLIENT_OU', None)) SSLEnv['SSL_CLIENT_S_DN_SP'] = \ env.get('SSL_CLIENT_S_DN_SP', env.get('SSL_CLIENT_SP', None)) SSLEnv['SSL_CLIENT_V_END'] = \ env.get('SSL_CLIENT_V_END', env.get('SSL_CLIENT_CERT_END', None)) SSLEnv['SSL_CLIENT_V_START'] = \ env.get('SSL_CLIENT_V_START', env.get('SSL_CLIENT_CERT_START', None)) SSLEnv['SSL_PROTOCOL'] = \ env.get('SSL_PROTOCOL', env.get('SSL_PROTOCOL_VERSION', None)) SSLEnv['SSL_SERVER_A_SIG'] = \ env.get('SSL_SERVER_A_SIG', env.get('SSL_SERVER_SIGNATURE_ALGORITHM', None)) SSLEnv['SSL_SERVER_CERT'] = \ env.get('SSL_SERVER_CERT', env.get('SSL_SERVER_CERTIFICATE', None)) SSLEnv['SSL_SERVER_I_DN_CN'] = \ env.get('SSL_SERVER_I_DN_CN', env.get('SSL_SERVER_ICN', None)) SSLEnv['SSL_SERVER_I_DN_C'] = \ env.get('SSL_SERVER_I_DN_C', env.get('SSL_SERVER_IC', None)) SSLEnv['SSL_SERVER_I_DN_Email'] = \ env.get('SSL_SERVER_I_DN_Email', env.get('SSL_SERVER_IEMAIL', None)) SSLEnv['SSL_SERVER_I_DN_L'] = \ env.get('SSL_SERVER_I_DN_L', env.get('SSL_SERVER_IL', None)) SSLEnv['SSL_SERVER_I_DN_O'] = \ env.get('SSL_SERVER_I_DN_O', env.get('SSL_SERVER_IO', None)) SSLEnv['SSL_SERVER_I_DN'] = \ env.get('SSL_SERVER_I_DN', env.get('SSL_SERVER_IDN', None)) SSLEnv['SSL_SERVER_I_DN_OU'] = \ env.get('SSL_SERVER_I_DN_OU', env.get('SSL_SERVER_IOU', None)) SSLEnv['SSL_SERVER_I_DN_SP'] = \ env.get('SSL_SERVER_I_DN_SP', env.get('SSL_SERVER_ISP', None)) SSLEnv['SSL_SERVER_M_SERIAL'] = \ env.get('SSL_SERVER_M_SERIAL', env.get('SSL_SERVER_CERT_SERIAL', None)) SSLEnv['SSL_SERVER_S_DN'] = \ env.get('SSL_SERVER_S_DN', env.get('SSL_SERVER_DN', None)) SSLEnv['SSL_SERVER_S_DN_CN'] = \ env.get('SSL_SERVER_S_DN_CN', env.get('SSL_SERVER_CN', None)) SSLEnv['SSL_SERVER_S_DN_C'] = \ env.get('SSL_SERVER_S_DN_C', env.get('SSL_SERVER_C', None)) SSLEnv['SSL_SERVER_S_DN_Email'] = \ env.get('SSL_SERVER_S_DN_Email', env.get('SSL_SERVER_EMAIL', None)) SSLEnv['SSL_SERVER_S_DN_L'] = \ env.get('SSL_SERVER_S_DN_L', env.get('SSL_SERVER_L', None)) SSLEnv['SSL_SERVER_S_DN_O'] = \ env.get('SSL_SERVER_S_DN_O', env.get('SSL_SERVER_O', None)) SSLEnv['SSL_SERVER_S_DN_OU'] = \ env.get('SSL_SERVER_S_DN_OU', env.get('SSL_SERVER_OU', None)) SSLEnv['SSL_SERVER_S_DN_SP'] = \ env.get('SSL_SERVER_S_DN_SP', env.get('SSL_SERVER_SP', None)) SSLEnv['SSL_SERVER_V_END'] = \ env.get('SSL_SERVER_V_END', env.get('SSL_SERVER_CERT_END', None)) SSLEnv['SSL_SERVER_V_START'] = \ env.get('SSL_SERVER_V_START', env.get('SSL_SERVER_CERT_START', None)) SSLEnv['SSL_VERSION_LIBRARY'] = \ env.get('SSL_VERSION_LIBRARY', env.get('SSL_SSLEAY_VERSION', None)) return SSLEnv def SecLevel(env,acceptedciphers,valid_dn_regex='',valid_idn_regex=''): """ Determine Security Level of SSL session. Returns: 0 no SSL at all 1 SSL-connection and cipher used is in acceptedciphers 2 like 1 but client also has sent client certificate matching valid_dn_regex and valid_idn_regex. """ https_env = GetAllSSLEnviron(env) if https_env and https_env.get('SSL_CIPHER','') in acceptedciphers: ssl_client_s_dn = https_env.get('SSL_CLIENT_S_DN','') if ssl_client_s_dn: ssl_client_i_dn = https_env.get('SSL_CLIENT_I_DN','') dn_rm = re.compile(valid_dn_regex).match(ssl_client_s_dn) idn_rm = re.compile(valid_idn_regex).match(ssl_client_i_dn) if (dn_rm) and (idn_rm): return 2 else: return 1 else: return 1 else: return 0 def PrintSecInfo(env,acceptedciphers,valid_dn_regex='',valid_idn_regex='',f=sys.stdout): """ Print the SSL data in HTML format """ seclevel = SecLevel(env,acceptedciphers,valid_dn_regex,valid_idn_regex) https_env = GetAllSSLEnviron(env) f.write("""

Security level

Current security level is: %d

0 no encryption at all
1 Session is encrypted with SSL and cipher is accepted
2 Client presented valid certificate, the DN of the certified object matches "%s" and the DN of the certifier matches "%s"
""" % (seclevel,valid_dn_regex,valid_idn_regex)) if seclevel>=1: SSL_PROTOCOL = https_env.get('SSL_PROTOCOL') SSL_CIPHER_ALGKEYSIZE = https_env.get('SSL_CIPHER_ALGKEYSIZE') SSL_CIPHER = https_env.get('SSL_CIPHER') SSL_CIPHER_USEKEYSIZE = https_env.get('SSL_CIPHER_USEKEYSIZE') SSL_SERVER_S_DN = https_env.get('SSL_SERVER_S_DN') SSL_SERVER_I_DN = https_env.get('SSL_SERVER_I_DN') f.write("""

%s connection with cipher %s, key size %s Bit, actually used key size %s Bit.

Server certificate

Subject-DN:
%s
Issuer-DN:
%s
""" % ( SSL_PROTOCOL, SSL_CIPHER, SSL_CIPHER_ALGKEYSIZE, SSL_CIPHER_USEKEYSIZE, escapeHTML(SSL_SERVER_S_DN), escapeHTML(SSL_SERVER_I_DN), )) if seclevel>=2: SSL_CLIENT_I_DN = https_env.get('SSL_CLIENT_I_DN',https_env.get('SSL_CLIENT_IDN','') ) SSL_CLIENT_S_DN = https_env.get('SSL_CLIENT_S_DN',https_env.get('SSL_CLIENT_DN','')) f.write("""

Your client certificate

Subject-DN:
%s
Issuer-DN:
%s
""" % ( escapeHTML(SSL_CLIENT_S_DN), escapeHTML(SSL_CLIENT_I_DN), )) pyweblib-1.3.9/pyweblib/session.py0000644000076400001440000003064211461761136020013 0ustar michaelusers00000000000000""" pyweblib.session - server-side web session handling (C) 2001 by Michael Stroeder This module implements server side session handling stored in arbitrary string-keyed dictionary objects This module is distributed under the terms of the GPL (GNU GENERAL PUBLIC LICENSE) Version 2 (see http://www.gnu.org/copyleft/gpl.html) $Id: session.py,v 1.28 2010/10/27 08:27:10 michael Exp $ """ __version__ = '0.3.5' import string,re,random,time,pickle SESSION_ID_CHARS=string.letters+string.digits+'-._' SESSION_CROSSCHECKVARS = ( """ List of environment variables assumed to be constant throughout web sessions with the same ID if existent. These env vars are cross-checked each time when restoring an web session to reduce the risk of session-hijacking. Note: REMOTE_ADDR and REMOTE_HOST might not be constant if the client access comes through a network of web proxy siblings. """ # REMOTE_ADDR and REMOTE_HOST might not be constant if the client # access comes through a network of web proxy siblings. 'REMOTE_ADDR','REMOTE_HOST', 'REMOTE_IDENT','REMOTE_USER', # If the proxy sets them but can be easily spoofed 'FORWARDED_FOR','HTTP_X_FORWARDED_FOR', # These two are not really secure 'HTTP_USER_AGENT','HTTP_ACCEPT_CHARSET', # SSL session ID if running on SSL server capable # of reusing SSL sessions 'SSL_SESSION_ID', # env vars of client certs used for SSL strong authentication 'SSL_CLIENT_V_START','SSL_CLIENT_V_END', 'SSL_CLIENT_I_DN','SSL_CLIENT_IDN', 'SSL_CLIENT_S_DN','SSL_CLIENT_SDN', 'SSL_CLIENT_M_SERIAL','SSL_CLIENT_CERT_SERIAL', ) ############################################################################## # Exception classes ############################################################################## class SessionException(Exception): """Raised if """ def __init__(self, *args): self.args = args class CorruptData(SessionException): """Raised if data was corrupt, e.g. UnpicklingError occured""" def __str__(self): return "Error during retrieving corrupted session data. Session deleted." class GenerateIDError(SessionException): """Raised if generation of unique session ID failed.""" def __init__(self, maxtry): self.maxtry = maxtry def __str__(self): return "Could not create new session id. Tried %d times." % (self.maxtry) class SessionExpired(SessionException): """Raised if session is expired.""" def __init__(self, timestamp, session_data): self.timestamp = timestamp self.session_data = session_data def __str__(self): return "Session expired %s." % (time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime(self.timestamp))) class SessionHijacked(SessionException): """Raised if hijacking of session was detected.""" def __init__(self, failed_vars): self.failed_vars = failed_vars def __str__(self): return "Crosschecking of the following env vars failed: %s." % ( self.failed_vars ) class MaxSessionCountExceeded(SessionException): """Raised if maximum number of sessions is exceeded.""" def __init__(self, max_session_count): self.max_session_count = max_session_count def __str__(self): return "Maximum number of sessions exceeded. Limit is %d." % ( self.max_session_count ) class BadSessionId(SessionException): """Raised if session ID not found in session dictionary.""" def __init__(self, session_id): self.session_id = session_id def __str__(self): return "No session with key %s." % (self.session_id) class InvalidSessionId(SessionException): """Raised if session ID not found in session dictionary.""" def __init__(self, session_id): self.session_id = session_id def __str__(self): return "No session with key %s." % (self.session_id) try: import threading from threading import Lock as ThreadingLock except ImportError: # Python installation has no thread support class ThreadingLock: """ mimikri for threading.Lock() """ def acquire(self): pass def release(self): pass else: class CleanUpThread(threading.Thread): """ Thread class for clean-up thread """ def __init__(self,sessionInstance,interval=60): self._sessionInstance = sessionInstance self._interval = interval self._stop_event = threading.Event() self._removed = 0 threading.Thread.__init__(self,name=self.__class__.__module__+self.__class__.__name__) def run(self): """Thread function for cleaning up session database""" while not self._stop_event.isSet(): self._removed += self._sessionInstance.cleanUp() self._stop_event.wait(self._interval) def __repr__(self): return '%s: %d sessions removed' % ( self.getName(),self._removed ) def join(self,timeout=0.0): self._stop_event.set() threading.Thread.join(self,timeout) class WebSession: """ The session class which handles storing and retrieving of session data in a dictionary-like sessiondict object. """ def __init__( self, dictobj=None, expireDeactivate=0, expireRemove=0, crossCheckVars=None, maxSessionCount=None, sessionIDLength=12, sessionIDChars=None, ): """ dictobj has to be a instance of a dictionary-like object (e.g. derived from UserDict or shelve) expireDeactivate amount of time (secs) after which a session expires and a SessionExpired exception is raised which contains the session data. expireRemove Amount of time (secs) after which a session expires and the session data is silently deleted. A InvalidSessionId exception is raised in this case if the application trys to access the session ID again. crossCheckVars List of keys of variables cross-checked for each retrieval of session data in retrieveSession(). If None SESSION_CROSSCHECKVARS is used. maxSessionCount Maximum number of valid sessions. This affects behaviour of retrieveSession() which raises. None means unlimited number of sessions. sessionIDLength Exact integer length of the session ID generated sessionIDChars String containing the valid chars for session IDs (if this is zero-value the default is SESSION_ID_CHARS) """ if dictobj is None: self.sessiondict = {} else: self.sessiondict = dictobj self.expireDeactivate = expireDeactivate self.expireRemove = expireRemove self._session_lock = ThreadingLock() if crossCheckVars is None: crossCheckVars = SESSION_CROSSCHECKVARS self.crossCheckVars = crossCheckVars self.maxSessionCount = maxSessionCount self.sessionCounter = 0 self.session_id_len = sessionIDLength self.session_id_chars = sessionIDChars or SESSION_ID_CHARS self.session_id_re = re.compile('^[%s]+$' % (re.escape(self.session_id_chars))) return # __init__() def sync(self): """ Call sync if self.sessiondict has .sync() method """ if hasattr(self.sessiondict,'sync'): self.sessiondict.sync() def close(self): """ Call close() if self.sessiondict has .close() method """ if hasattr(self.sessiondict,'close'): # Close e.g. a database self.sessiondict.close() else: # Make sessiondict inaccessible self.sessiondict = None def _validateSessionIdFormat(self,session_id): """ Validate the format of session_id. Implementation has to match IDs produced in method _generateSessionID() """ if len(session_id)!=self.session_id_len or self.session_id_re.match(session_id) is None: raise BadSessionId(session_id) return def _crosscheckSessionEnv(self,stored_env,current_env): """ Returns a list of keys of items which differ in stored_env and current_env. """ return [ k for k in stored_env.keys() if stored_env[k]!=current_env.get(k,None) ] def _generateCrosscheckEnv(self,current_env): """ Generate a dictionary of env vars for session cross-checking """ crosscheckenv = {} for k in self.crossCheckVars: if current_env.has_key(k): crosscheckenv[k] = current_env[k] return crosscheckenv def _generateSessionID(self,maxtry=1): """ Generate a new random and unique session id string """ def choice_id(): return ''.join([ random.choice(SESSION_ID_CHARS) for i in range(self.session_id_len) ]) newid = choice_id() tried = 0 while self.sessiondict.has_key(newid) and (not maxtry or tried=maxtry: raise GenerateIDError(maxtry) else: return newid def storeSession(self,session_id,session_data): """ Store session_data under session_id. """ self._session_lock.acquire() try: # Store session data with timestamp self.sessiondict[session_id] = (time.time(),session_data) self.sync() finally: self._session_lock.release() return session_id def deleteSession(self,session_id): """ Delete session_data referenced by session_id. """ # Delete the session data self._session_lock.acquire() try: if self.sessiondict.has_key(session_id): del self.sessiondict[session_id] if self.sessiondict.has_key('__session_checkvars__'+session_id): del self.sessiondict['__session_checkvars__'+session_id] self.sync() finally: self._session_lock.release() return session_id def retrieveSession(self,session_id,env={}): """ Retrieve session data """ self._validateSessionIdFormat(session_id) session_vars_key = '__session_checkvars__'+session_id # Check if session id exists if not ( self.sessiondict.has_key(session_id) and \ self.sessiondict.has_key(session_vars_key) ): raise InvalidSessionId(session_id) # Read the timestamped session data try: self._session_lock.acquire() try: session_checkvars = self.sessiondict[session_vars_key] timestamp,session_data = self.sessiondict[session_id] finally: self._session_lock.release() except pickle.UnpicklingError: self.deleteSession(session_id) raise CorruptData current_time = time.time() # Check if session data is already expired if self.expireDeactivate and \ (current_time>timestamp+self.expireDeactivate): # Remove session entry self.deleteSession(session_id) # Check if application should be able to allow relogin if self.expireRemove and \ (current_time>timestamp+self.expireRemove): raise InvalidSessionId(session_id) else: raise SessionExpired(timestamp,session_data) failed_vars = self._crosscheckSessionEnv(session_checkvars,env) if failed_vars: # Remove session entry raise SessionHijacked(failed_vars) # Everything's ok => return the session data return session_data def newSession(self,env={}): """ Store session data under session id """ if self.maxSessionCount and len(self.sessiondict)/2+1>self.maxSessionCount: raise MaxSessionCountExceeded(self.maxSessionCount) self._session_lock.acquire() try: # generate completely new session data entry session_id=self._generateSessionID(maxtry=3) # Store session data with timestamp if session ID # was created successfully self.sessiondict[session_id] = ( # Current time time.time(), # Store a dummy string first '_created_', ) self.sessiondict['__session_checkvars__'+session_id] = self._generateCrosscheckEnv(env) self.sync() self.sessionCounter += 1 finally: self._session_lock.release() return session_id def cleanUp(self): """ Search for expired session entries and delete them. Returns integer counter of deleted sessions as result. """ current_time = time.time() result = 0 for session_id in self.sessiondict.keys(): if not session_id.startswith('__'): try: session_timestamp = self.sessiondict[session_id][0] except InvalidSessionId: # Avoid race condition. The session might have been # deleted in the meantime. But make sure everything is deleted. self.deleteSession(session_id) else: # Check expiration time if session_timestamp+self.expireRemove input pyweblib.session server-side web session handling pyweblib.helper misc. stuff useful in CGI-BINs pyweblib.sslenv retrieves SSL-related env vars pyweblib.httphelper very basic HTTP functions """, author = 'Michael Stroeder', author_email = 'michael@stroeder.com', maintainer = 'Michael Stroeder', maintainer_email = 'michael@stroeder.com', url = 'http://www.stroeder.com/pylib/PyWebLib/', packages = ['pyweblib'], # keywords = ['web programming','CGI-BIN','session handling','form handling'] ) pyweblib-1.3.9/cgi-bin/0000755000076400001440000000000011745325171015444 5ustar michaelusers00000000000000pyweblib-1.3.9/cgi-bin/test-forms.py0000755000076400001440000000536107741757116020142 0ustar michaelusers00000000000000#!/usr/bin/python2.3 import sys,os,types # Where to find own modules sys.path.append('/home/michael/Proj/python/pyweblib') import pyweblib from pyweblib import forms def ErrorExit(Msg): print """Content-type: text/html Error

Error

%s

""" % Msg def PrintEmptyInputForm(form,Msg=''): print """Content-type: text/html Give me some data!

Give me some data!

""" % (os.environ['SCRIPT_NAME']) for name in form.declaredFieldNames: f = form.field[name] print '' % ( f.labelHTML(),f.required*'
required',f.inputHTML() ) print """
%s%s%s
""" def PrintInputData(form): # Anzeige der eingegebenen Daten print """Content-type: text/html Your input data

Your input data

""" for i in form.inputFieldNames: contentlist = [] f = form.field[i] if f.value != None: if type(f.value) is types.ListType: contentlist.extend(f.valueHTML()) else: contentlist.append(f.valueHTML()) else: contentlist.append(' ') print '' % (i,'
'.join(contentlist)) print """
%s%s
""" form = forms.Form(sys.stdin,os.environ) form.addField( forms.Input( 'param_input','Input',255,1,'abc.*',accessKey='1', size=25 ) ) form.addField( forms.HiddenInput( 'param_hidden','HiddenInput',255,1,'.*',default='Hidden Value', show=1 ) ) form.addField( forms.Password( 'param_password','Password',16,1,'.*',accessKey='3' ) ) form.addField( forms.Select( 'param_select','Select',3, options=[('value1','Option 1'),'value2',('value3','Option 3')], default=['value2','value3'], size=3,multiSelect=1 ) ) form.addField( forms.Radio('param_radio','Radio',default='value2', options=[('value1','Option 1'),'value2',('value3','Option 3')], ) ) form.addField( forms.Textarea( 'param_textarea', 'Additional Comments', 1000,1,'Longer text:.*',default='Longer text:\nWrite here...', rows=5,cols=50 ) ) form.addField( forms.Checkbox( 'param_checkbox','Checkbox',default='Checked value' ) ) form.addField( forms.File( 'param_file','File upload',100000,1,None,default='/etc/passwd',size=30 ) ) try: form.getInputFields() except forms.FormException,e: ErrorExit(e.html()) if not form.inputFieldNames: PrintEmptyInputForm(form,'') else: PrintInputData(form) sys.exit(0) pyweblib-1.3.9/cgi-bin/test-session.py0000755000076400001440000000273207325510622020461 0ustar michaelusers00000000000000#!/usr/bin/python import sys, os, string, types, dbm, gdbm, shelve, cgi # Where to find own modules sys.path.append('/home/michael/Proj/python/pyweblib') import pyweblib.session sessiondict = shelve.open('/tmp/test-pyweblib.session','c') webSession = pyweblib.session.WebSession( sessiondict,expireDeactivate=30,expireRemove=60 ) form = cgi.FieldStorage() if form.has_key('sessionid'): sessionid = form['sessionid'].value try: oldtext = webSession.retrieveSession(sessionid) except pyweblib.session.SessionException,e: sessionid = webSession.newSession() oldtext = '*** %s' % (str(e)) else: sessionid = webSession.newSession() oldtext = '*** Created new session.' if form.has_key('text'): newtext = form['text'].value webSession.storeSession(sessionid,newtext) else: newtext = '' # Anzeige der eingegebenen Daten print """Content-type: text/html Pragma: no-cache

sessionid = %(sessionid)s

Old text restored from session cache:

      %(oldtext)s
    

New text stored currently stored into session cache:

      %(newtext)s
    
""" % vars() sessiondict.close() sys.exit(0) pyweblib-1.3.9/CHANGES0000644000076400001440000001654711745325137015146 0ustar michaelusers000000000000002012-04-23 PyWebLib 1.3.9 - Radio.inputHTML(): Fixed double output of attribute name id= - File.inputHTML(): Various attributes are not allowed for 2011-06-19 PyWebLib 1.3.8 - sslenv.PrintSecInfo(): Simplified output of issuer and subject DNs - Class Radio: Regex-checking is not used anymore since this fails on larger option lists 2011-02-19 PyWebLib 1.3.7 - sslenv.PrintSecInfo(): Also SSL_PROTOCOL is displayed - fixed inconsistent use of tabs and spaces (python -tt) - Single quotes and backticks are now escaped in pyweblib.forms.escapeHTML() - pyweblib.forms.Form.hiddenInputFields(): Treat default value for key-word argument ignoreFieldNames more robustely - forms.Select now also supports 3-tuples as option and the third value will be added as attribute text to HTML tag