home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 January / maximum-cd-2011-01.iso / DiscContents / xbmc-9.11.exe / system / python / spyce / Cookie.py < prev    next >
Encoding:
Python Source  |  2009-12-23  |  20.2 KB  |  558 lines

  1. ##################################################
  2. # SPYCE - Python-based HTML Scripting
  3. # Copyright (c) 2002 Rimon Barr.
  4. #
  5. # Refer to spyce.py
  6. # CVS: $Id: Cookie.py 20864 2009-06-02 06:16:47Z ceros7 $
  7. ##################################################
  8.  
  9. # Cookie.py taken from Python 2.2, and modified it to work in Python 1.5 -- RB
  10.  
  11. __doc__ = 'Cookie parsing functionality'
  12.  
  13. ####
  14. # Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>
  15. #
  16. #                All Rights Reserved
  17. #
  18. # Permission to use, copy, modify, and distribute this software
  19. # and its documentation for any purpose and without fee is hereby
  20. # granted, provided that the above copyright notice appear in all
  21. # copies and that both that copyright notice and this permission
  22. # notice appear in supporting documentation, and that the name of
  23. # Timothy O'Malley  not be used in advertising or publicity
  24. # pertaining to distribution of the software without specific, written
  25. # prior permission.
  26. #
  27. # Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
  28. # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  29. # AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
  30. # ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  31. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  32. # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  33. # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  34. # PERFORMANCE OF THIS SOFTWARE.
  35. #
  36.  
  37. import string
  38. from UserDict import UserDict
  39.  
  40. try:
  41.     from cPickle import dumps, loads
  42. except ImportError:
  43.     from pickle import dumps, loads
  44.  
  45. try:
  46.     import re
  47. except ImportError:
  48.     raise ImportError, "Cookie.py requires 're' from Python 1.5 or later"
  49.  
  50. __all__ = ["CookieError","BaseCookie","SimpleCookie","SerialCookie",
  51.            "SmartCookie","Cookie"]
  52.  
  53. #
  54. # Define an exception visible to External modules
  55. #
  56. class CookieError(Exception):
  57.     pass
  58.  
  59.  
  60. # These quoting routines conform to the RFC2109 specification, which in
  61. # turn references the character definitions from RFC2068.  They provide
  62. # a two-way quoting algorithm.  Any non-text character is translated
  63. # into a 4 character sequence: a forward-slash followed by the
  64. # three-digit octal equivalent of the character.  Any '\' or '"' is
  65. # quoted with a preceeding '\' slash.
  66. #
  67. # These are taken from RFC2068 and RFC2109.
  68. #       _LegalChars       is the list of chars which don't require "'s
  69. #       _Translator       hash-table for fast quoting
  70. #
  71.  
  72. ascii_lowercase = string.join(map(lambda c: chr(ord('a')+c), range(ord('z')-ord('a')+1)),'')
  73. ascii_uppercase = string.join(map(lambda c: chr(ord('A')+c), range(ord('z')-ord('a')+1)),'')
  74.  
  75. _LegalChars       = ascii_lowercase + ascii_uppercase + string.digits + "!#$%&'*+-.^_`|~"
  76. _Translator       = {
  77.     '\000' : '\\000',  '\001' : '\\001',  '\002' : '\\002',
  78.     '\003' : '\\003',  '\004' : '\\004',  '\005' : '\\005',
  79.     '\006' : '\\006',  '\007' : '\\007',  '\010' : '\\010',
  80.     '\011' : '\\011',  '\012' : '\\012',  '\013' : '\\013',
  81.     '\014' : '\\014',  '\015' : '\\015',  '\016' : '\\016',
  82.     '\017' : '\\017',  '\020' : '\\020',  '\021' : '\\021',
  83.     '\022' : '\\022',  '\023' : '\\023',  '\024' : '\\024',
  84.     '\025' : '\\025',  '\026' : '\\026',  '\027' : '\\027',
  85.     '\030' : '\\030',  '\031' : '\\031',  '\032' : '\\032',
  86.     '\033' : '\\033',  '\034' : '\\034',  '\035' : '\\035',
  87.     '\036' : '\\036',  '\037' : '\\037',
  88.  
  89.     '"' : '\\"',       '\\' : '\\\\',
  90.  
  91.     '\177' : '\\177',  '\200' : '\\200',  '\201' : '\\201',
  92.     '\202' : '\\202',  '\203' : '\\203',  '\204' : '\\204',
  93.     '\205' : '\\205',  '\206' : '\\206',  '\207' : '\\207',
  94.     '\210' : '\\210',  '\211' : '\\211',  '\212' : '\\212',
  95.     '\213' : '\\213',  '\214' : '\\214',  '\215' : '\\215',
  96.     '\216' : '\\216',  '\217' : '\\217',  '\220' : '\\220',
  97.     '\221' : '\\221',  '\222' : '\\222',  '\223' : '\\223',
  98.     '\224' : '\\224',  '\225' : '\\225',  '\226' : '\\226',
  99.     '\227' : '\\227',  '\230' : '\\230',  '\231' : '\\231',
  100.     '\232' : '\\232',  '\233' : '\\233',  '\234' : '\\234',
  101.     '\235' : '\\235',  '\236' : '\\236',  '\237' : '\\237',
  102.     '\240' : '\\240',  '\241' : '\\241',  '\242' : '\\242',
  103.     '\243' : '\\243',  '\244' : '\\244',  '\245' : '\\245',
  104.     '\246' : '\\246',  '\247' : '\\247',  '\250' : '\\250',
  105.     '\251' : '\\251',  '\252' : '\\252',  '\253' : '\\253',
  106.     '\254' : '\\254',  '\255' : '\\255',  '\256' : '\\256',
  107.     '\257' : '\\257',  '\260' : '\\260',  '\261' : '\\261',
  108.     '\262' : '\\262',  '\263' : '\\263',  '\264' : '\\264',
  109.     '\265' : '\\265',  '\266' : '\\266',  '\267' : '\\267',
  110.     '\270' : '\\270',  '\271' : '\\271',  '\272' : '\\272',
  111.     '\273' : '\\273',  '\274' : '\\274',  '\275' : '\\275',
  112.     '\276' : '\\276',  '\277' : '\\277',  '\300' : '\\300',
  113.     '\301' : '\\301',  '\302' : '\\302',  '\303' : '\\303',
  114.     '\304' : '\\304',  '\305' : '\\305',  '\306' : '\\306',
  115.     '\307' : '\\307',  '\310' : '\\310',  '\311' : '\\311',
  116.     '\312' : '\\312',  '\313' : '\\313',  '\314' : '\\314',
  117.     '\315' : '\\315',  '\316' : '\\316',  '\317' : '\\317',
  118.     '\320' : '\\320',  '\321' : '\\321',  '\322' : '\\322',
  119.     '\323' : '\\323',  '\324' : '\\324',  '\325' : '\\325',
  120.     '\326' : '\\326',  '\327' : '\\327',  '\330' : '\\330',
  121.     '\331' : '\\331',  '\332' : '\\332',  '\333' : '\\333',
  122.     '\334' : '\\334',  '\335' : '\\335',  '\336' : '\\336',
  123.     '\337' : '\\337',  '\340' : '\\340',  '\341' : '\\341',
  124.     '\342' : '\\342',  '\343' : '\\343',  '\344' : '\\344',
  125.     '\345' : '\\345',  '\346' : '\\346',  '\347' : '\\347',
  126.     '\350' : '\\350',  '\351' : '\\351',  '\352' : '\\352',
  127.     '\353' : '\\353',  '\354' : '\\354',  '\355' : '\\355',
  128.     '\356' : '\\356',  '\357' : '\\357',  '\360' : '\\360',
  129.     '\361' : '\\361',  '\362' : '\\362',  '\363' : '\\363',
  130.     '\364' : '\\364',  '\365' : '\\365',  '\366' : '\\366',
  131.     '\367' : '\\367',  '\370' : '\\370',  '\371' : '\\371',
  132.     '\372' : '\\372',  '\373' : '\\373',  '\374' : '\\374',
  133.     '\375' : '\\375',  '\376' : '\\376',  '\377' : '\\377'
  134.     }
  135.  
  136. def _quote(str, LegalChars=_LegalChars,
  137.     join=string.join, idmap=string._idmap, translate=string.translate):
  138.     #
  139.     # If the string does not need to be double-quoted,
  140.     # then just return the string.  Otherwise, surround
  141.     # the string in doublequotes and precede quote (with a \)
  142.     # special characters.
  143.     #
  144.     if "" == translate(str, idmap, LegalChars):
  145.         return str
  146.     else:
  147.         return '"' + join( map(_Translator.get, str, str), "" ) + '"'
  148. # end _quote
  149.  
  150.  
  151. _OctalPatt = re.compile(r"\\[0-3][0-7][0-7]")
  152. _QuotePatt = re.compile(r"[\\].")
  153.  
  154. def _unquote(str, join=string.join, atoi=string.atoi):
  155.     # If there aren't any doublequotes,
  156.     # then there can't be any special characters.  See RFC 2109.
  157.     if  len(str) < 2:
  158.         return str
  159.     if str[0] != '"' or str[-1] != '"':
  160.         return str
  161.  
  162.     # We have to assume that we must decode this string.
  163.     # Down to work.
  164.  
  165.     # Remove the "s
  166.     str = str[1:-1]
  167.  
  168.     # Check for special sequences.  Examples:
  169.     #    \012 --> \n
  170.     #    \"   --> "
  171.     #
  172.     i = 0
  173.     n = len(str)
  174.     res = []
  175.     while 0 <= i < n:
  176.         Omatch = _OctalPatt.search(str, i)
  177.         Qmatch = _QuotePatt.search(str, i)
  178.         if not Omatch and not Qmatch:              # Neither matched
  179.             res.append(str[i:])
  180.             break
  181.         # else:
  182.         j = k = -1
  183.         if Omatch: j = Omatch.start(0)
  184.         if Qmatch: k = Qmatch.start(0)
  185.         if Qmatch and ( not Omatch or k < j ):     # QuotePatt matched
  186.             res.append(str[i:k])
  187.             res.append(str[k+1])
  188.             i = k+2
  189.         else:                                      # OctalPatt matched
  190.             res.append(str[i:j])
  191.             res.append( chr( atoi(str[j+1:j+4], 8) ) )
  192.             i = j+4
  193.     return join(res, "")
  194. # end _unquote
  195.  
  196. # The _getdate() routine is used to set the expiration time in
  197. # the cookie's HTTP header.      By default, _getdate() returns the
  198. # current time in the appropriate "expires" format for a
  199. # Set-Cookie header.     The one optional argument is an offset from
  200. # now, in seconds.      For example, an offset of -3600 means "one hour ago".
  201. # The offset may be a floating point number.
  202. #
  203.  
  204. _weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  205.  
  206. _monthname = [None,
  207.               'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  208.               'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  209.  
  210. def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname):
  211.     from time import gmtime, time
  212.     now = time()
  213.     year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future)
  214.     return "%s, %02d-%3s-%4d %02d:%02d:%02d GMT" % \
  215.            (weekdayname[wd], day, monthname[month], year, hh, mm, ss)
  216.  
  217.  
  218. #
  219. # A class to hold ONE key,value pair.
  220. # In a cookie, each such pair may have several attributes.
  221. #       so this class is used to keep the attributes associated
  222. #       with the appropriate key,value pair.
  223. # This class also includes a coded_value attribute, which
  224. #       is used to hold the network representation of the
  225. #       value.  This is most useful when Python objects are
  226. #       pickled for network transit.
  227. #
  228.  
  229. class Morsel(UserDict):
  230.     # RFC 2109 lists these attributes as reserved:
  231.     #   path       comment         domain
  232.     #   max-age    secure      version
  233.     #
  234.     # For historical reasons, these attributes are also reserved:
  235.     #   expires
  236.     #
  237.     # This dictionary provides a mapping from the lowercase
  238.     # variant on the left to the appropriate traditional
  239.     # formatting on the right.
  240.     _reserved = { "expires" : "expires",
  241.                    "path"        : "Path",
  242.                    "comment" : "Comment",
  243.                    "domain"      : "Domain",
  244.                    "max-age" : "Max-Age",
  245.                    "secure"      : "secure",
  246.                    "version" : "Version",
  247.                    }
  248.     _reserved_keys = _reserved.keys()
  249.  
  250.     def __init__(self):
  251.         # Set defaults
  252.         self.key = self.value = self.coded_value = None
  253.         UserDict.__init__(self)
  254.  
  255.         # Set default attributes
  256.         for K in self._reserved_keys:
  257.             UserDict.__setitem__(self, K, "")
  258.     # end __init__
  259.  
  260.     def __setitem__(self, K, V):
  261.         K = string.lower(K)
  262.         if not K in self._reserved_keys:
  263.             raise CookieError("Invalid Attribute %s" % K)
  264.         UserDict.__setitem__(self, K, V)
  265.     # end __setitem__
  266.  
  267.     def isReservedKey(self, K):
  268.         return string.lower(K) in self._reserved_keys
  269.     # end isReservedKey
  270.  
  271.     def set(self, key, val, coded_val,
  272.             LegalChars=_LegalChars,
  273.             idmap=string._idmap, translate=string.translate ):
  274.         # First we verify that the key isn't a reserved word
  275.         # Second we make sure it only contains legal characters
  276.         if string.lower(key) in self._reserved_keys:
  277.             raise CookieError("Attempt to set a reserved key: %s" % key)
  278.         if "" != translate(key, idmap, LegalChars):
  279.             raise CookieError("Illegal key value: %s" % key)
  280.  
  281.         # It's a good key, so save it.
  282.         self.key                 = key
  283.         self.value               = val
  284.         self.coded_value         = coded_val
  285.     # end set
  286.  
  287.     def output(self, attrs=None, header = "Set-Cookie:"):
  288.         return "%s %s" % ( header, self.OutputString(attrs) )
  289.  
  290.     __str__ = output
  291.  
  292.     def __repr__(self):
  293.         return '<%s: %s=%s>' % (self.__class__.__name__,
  294.                                 self.key, repr(self.value) )
  295.  
  296.     def js_output(self, attrs=None):
  297.         # Print javascript
  298.         return """
  299.         <SCRIPT LANGUAGE="JavaScript">
  300.         <!-- begin hiding
  301.         document.cookie = \"%s\"
  302.         // end hiding -->
  303.         </script>
  304.         """ % ( self.OutputString(attrs), )
  305.     # end js_output()
  306.  
  307.     def OutputString(self, attrs=None):
  308.         # Build up our result
  309.         #
  310.         result = []
  311.         RA = result.append
  312.  
  313.         # First, the key=value pair
  314.         RA("%s=%s;" % (self.key, self.coded_value))
  315.  
  316.         # Now add any defined attributes
  317.         if attrs is None:
  318.             attrs = self._reserved_keys
  319.         items = self.items()
  320.         items.sort()
  321.         for K,V in items:
  322.             if V == "": continue
  323.             if K not in attrs: continue
  324.             if K == "expires" and type(V) == type(1):
  325.                 RA("%s=%s;" % (self._reserved[K], _getdate(V)))
  326.             elif K == "max-age" and type(V) == type(1):
  327.                 RA("%s=%d;" % (self._reserved[K], V))
  328.             elif K == "secure":
  329.                 RA("%s;" % self._reserved[K])
  330.             else:
  331.                 RA("%s=%s;" % (self._reserved[K], V))
  332.  
  333.         # Return the result
  334.         return string.join(result, " ")
  335.     # end OutputString
  336. # end Morsel class
  337.  
  338.  
  339.  
  340. #
  341. # Pattern for finding cookie
  342. #
  343. # This used to be strict parsing based on the RFC2109 and RFC2068
  344. # specifications.  I have since discovered that MSIE 3.0x doesn't
  345. # follow the character rules outlined in those specs.  As a
  346. # result, the parsing rules here are less strict.
  347. #
  348.  
  349. _LegalCharsPatt  = r"[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=]"
  350. _CookiePattern = re.compile(
  351.     r"(?x)"                       # This is a Verbose pattern
  352.     r"(?P<key>"                   # Start of group 'key'
  353.     ""+ _LegalCharsPatt +"+?"     # Any word of at least one letter, nongreedy
  354.     r")"                          # End of group 'key'
  355.     r"\s*=\s*"                    # Equal Sign
  356.     r"(?P<val>"                   # Start of group 'val'
  357.     r'"(?:[^\\"]|\\.)*"'            # Any doublequoted string
  358.     r"|"                            # or
  359.     ""+ _LegalCharsPatt +"*"        # Any word or empty string
  360.     r")"                          # End of group 'val'
  361.     r"\s*;?"                      # Probably ending in a semi-colon
  362.     )
  363.  
  364.  
  365. # At long last, here is the cookie class.
  366. #   Using this class is almost just like using a dictionary.
  367. # See this module's docstring for example usage.
  368. #
  369. class BaseCookie(UserDict):
  370.     # A container class for a set of Morsels
  371.     #
  372.  
  373.     def value_decode(self, val):
  374.         """real_value, coded_value = value_decode(STRING)
  375.         Called prior to setting a cookie's value from the network
  376.         representation.  The VALUE is the value read from HTTP
  377.         header.
  378.         Override this function to modify the behavior of cookies.
  379.         """
  380.         return val, val
  381.     # end value_encode
  382.  
  383.     def value_encode(self, val):
  384.         """real_value, coded_value = value_encode(VALUE)
  385.         Called prior to setting a cookie's value from the dictionary
  386.         representation.  The VALUE is the value being assigned.
  387.         Override this function to modify the behavior of cookies.
  388.         """
  389.         strval = str(val)
  390.         return strval, strval
  391.     # end value_encode
  392.  
  393.     def __init__(self, input=None):
  394.         UserDict.__init__(self)
  395.         if input: self.load(input)
  396.     # end __init__
  397.  
  398.     def __set(self, key, real_value, coded_value):
  399.         """Private method for setting a cookie's value"""
  400.         M = self.get(key, Morsel())
  401.         M.set(key, real_value, coded_value)
  402.         UserDict.__setitem__(self, key, M)
  403.     # end __set
  404.  
  405.     def __setitem__(self, key, value):
  406.         """Dictionary style assignment."""
  407.         rval, cval = self.value_encode(value)
  408.         self.__set(key, rval, cval)
  409.     # end __setitem__
  410.  
  411.     def output(self, attrs=None, header="Set-Cookie:", sep="\n"):
  412.         """Return a string suitable for HTTP."""
  413.         result = []
  414.         items = self.items()
  415.         items.sort()
  416.         for K,V in items:
  417.             result.append( V.output(attrs, header) )
  418.         return string.join(result, sep)
  419.     # end output
  420.  
  421.     __str__ = output
  422.  
  423.     def __repr__(self):
  424.         L = []
  425.         items = self.items()
  426.         items.sort()
  427.         for K,V in items:
  428.             L.append( '%s=%s' % (K,repr(V.value) ) )
  429.         return '<%s: %s>' % (self.__class__.__name__, string.join(L))
  430.  
  431.     def js_output(self, attrs=None):
  432.         """Return a string suitable for JavaScript."""
  433.         result = []
  434.         items = self.items()
  435.         items.sort()
  436.         for K,V in items:
  437.             result.append( V.js_output(attrs) )
  438.         return string.join(result, "")
  439.     # end js_output
  440.  
  441.     def load(self, rawdata):
  442.         """Load cookies from a string (presumably HTTP_COOKIE) or
  443.         from a dictionary.  Loading cookies from a dictionary 'd'
  444.         is equivalent to calling:
  445.             map(Cookie.__setitem__, d.keys(), d.values())
  446.         """
  447.         if type(rawdata) == type(""):
  448.             self.__ParseString(rawdata)
  449.         else:
  450.             self.update(rawdata)
  451.         return
  452.     # end load()
  453.  
  454.     def __ParseString(self, str, patt=_CookiePattern):
  455.         i = 0            # Our starting point
  456.         n = len(str)     # Length of string
  457.         M = None         # current morsel
  458.  
  459.         while 0 <= i < n:
  460.             # Start looking for a cookie
  461.             match = patt.search(str, i)
  462.             if not match: break          # No more cookies
  463.  
  464.             K,V = match.group("key"), match.group("val")
  465.             i = match.end(0)
  466.  
  467.             # Parse the key, value in case it's metainfo
  468.             if K[0] == "$":
  469.                 # We ignore attributes which pertain to the cookie
  470.                 # mechanism as a whole.  See RFC 2109.
  471.                 # (Does anyone care?)
  472.                 if M:
  473.                     M[ K[1:] ] = V
  474.             elif string.lower(K) in Morsel._reserved_keys:
  475.                 if M:
  476.                     M[ K ] = _unquote(V)
  477.             else:
  478.                 rval, cval = self.value_decode(V)
  479.                 self.__set(K, rval, cval)
  480.                 M = self[K]
  481.     # end __ParseString
  482. # end BaseCookie class
  483.  
  484. class SimpleCookie(BaseCookie):
  485.     """SimpleCookie
  486.     SimpleCookie supports strings as cookie values.  When setting
  487.     the value using the dictionary assignment notation, SimpleCookie
  488.     calls the builtin str() to convert the value to a string.  Values
  489.     received from HTTP are kept as strings.
  490.     """
  491.     def value_decode(self, val):
  492.         return _unquote( val ), val
  493.     def value_encode(self, val):
  494.         strval = str(val)
  495.         return strval, _quote( strval )
  496. # end SimpleCookie
  497.  
  498. class SerialCookie(BaseCookie):
  499.     """SerialCookie
  500.     SerialCookie supports arbitrary objects as cookie values. All
  501.     values are serialized (using cPickle) before being sent to the
  502.     client.  All incoming values are assumed to be valid Pickle
  503.     representations.  IF AN INCOMING VALUE IS NOT IN A VALID PICKLE
  504.     FORMAT, THEN AN EXCEPTION WILL BE RAISED.
  505.  
  506.     Note: Large cookie values add overhead because they must be
  507.     retransmitted on every HTTP transaction.
  508.  
  509.     Note: HTTP has a 2k limit on the size of a cookie.  This class
  510.     does not check for this limit, so be careful!!!
  511.     """
  512.     def value_decode(self, val):
  513.         # This could raise an exception!
  514.         return loads( _unquote(val) ), val
  515.     def value_encode(self, val):
  516.         return val, _quote( dumps(val) )
  517. # end SerialCookie
  518.  
  519. class SmartCookie(BaseCookie):
  520.     """SmartCookie
  521.     SmartCookie supports arbitrary objects as cookie values.  If the
  522.     object is a string, then it is quoted.  If the object is not a
  523.     string, however, then SmartCookie will use cPickle to serialize
  524.     the object into a string representation.
  525.  
  526.     Note: Large cookie values add overhead because they must be
  527.     retransmitted on every HTTP transaction.
  528.  
  529.     Note: HTTP has a 2k limit on the size of a cookie.  This class
  530.     does not check for this limit, so be careful!!!
  531.     """
  532.     def value_decode(self, val):
  533.         strval = _unquote(val)
  534.         try:
  535.             return loads(strval), val
  536.         except:
  537.             return strval, val
  538.     def value_encode(self, val):
  539.         if type(val) == type(""):
  540.             return val, _quote(val)
  541.         else:
  542.             return val, _quote( dumps(val) )
  543. # end SmartCookie
  544.  
  545.  
  546. ###########################################################
  547. # Backwards Compatibility:  Don't break any existing code!
  548.  
  549. # We provide Cookie() as an alias for SmartCookie()
  550. Cookie = SmartCookie
  551.  
  552. #
  553. ###########################################################
  554.  
  555. #Local Variables:
  556. #tab-width: 4
  557. #end:
  558.