home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 February / maximum-cd-2011-02.iso / DiscContents / digsby_setup85.exe / lib / ZSI / client.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-11-24  |  16.1 KB  |  472 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. from ZSI import _copyright, _seqtypes, ParsedSoap, SoapWriter, TC, ZSI_SCHEMA_URI, EvaluateException, FaultFromFaultMessage, _child_elements, _attrs, _find_arraytype, _find_type, _get_idstr, _get_postvalue_from_absoluteURI, FaultException, WSActionException, UNICODE_ENCODING
  5. from ZSI.auth import AUTH
  6. from ZSI.TC import AnyElement, AnyType, String, TypeCode, _get_global_element_declaration, _get_type_definition
  7. from ZSI.TCcompound import Struct
  8. import base64
  9. import httplib
  10. import Cookie
  11. import types
  12. import time
  13. import urlparse
  14. from ZSI.address import Address
  15. from ZSI.wstools.logging import getLogger as _GetLogger
  16. _b64_encode = base64.encodestring
  17.  
  18. class _AuthHeader:
  19.     
  20.     def __init__(self, name = None, password = None):
  21.         self.Name = name
  22.         self.Password = password
  23.  
  24.  
  25. _AuthHeader.typecode = Struct(_AuthHeader, ofwhat = (String((ZSI_SCHEMA_URI, 'Name'), typed = False), String((ZSI_SCHEMA_URI, 'Password'), typed = False)), pname = (ZSI_SCHEMA_URI, 'BasicAuth'), typed = False)
  26.  
  27. class _Caller:
  28.     
  29.     def __init__(self, binding, name, namespace = None):
  30.         self.binding = binding
  31.         self.name = name
  32.         self.namespace = namespace
  33.  
  34.     
  35.     def __call__(self, *args):
  36.         nsuri = self.namespace
  37.         if nsuri is None:
  38.             return self.binding.RPC(None, self.name, args, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', replytype = TC.Any(self.name + 'Response'))
  39.         return self.binding.RPC(None, (nsuri, self.name), args, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', replytype = TC.Any((nsuri, self.name + 'Response')))
  40.  
  41.  
  42.  
  43. class _NamedParamCaller:
  44.     
  45.     def __init__(self, binding, name, namespace = None):
  46.         self.binding = binding
  47.         self.name = name
  48.         self.namespace = namespace
  49.  
  50.     
  51.     def __call__(self, **params):
  52.         kw = { }
  53.         for key in [
  54.             'auth_header',
  55.             'nsdict',
  56.             'requesttypecode',
  57.             'soapaction']:
  58.             if params.has_key(key):
  59.                 kw[key] = params[key]
  60.                 del params[key]
  61.                 continue
  62.         
  63.         nsuri = self.namespace
  64.         if nsuri is None:
  65.             return self.binding.RPC(None, self.name, None, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', _args = params, replytype = TC.Any(self.name + 'Response', aslist = False), **kw)
  66.         return self.binding.RPC(None, (nsuri, self.name), None, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', _args = params, replytype = TC.Any((nsuri, self.name + 'Response'), aslist = False), **kw)
  67.  
  68.  
  69.  
  70. class _Binding(object):
  71.     defaultHttpTransport = httplib.HTTPConnection
  72.     defaultHttpsTransport = httplib.HTTPSConnection
  73.     logger = _GetLogger('ZSI.client.Binding')
  74.     
  75.     def __init__(self, nsdict = None, transport = None, url = None, tracefile = None, readerclass = None, writerclass = None, soapaction = '', wsAddressURI = None, sig_handler = None, transdict = None, **kw):
  76.         self.data = None
  77.         self.ps = None
  78.         self.user_headers = []
  79.         if not nsdict:
  80.             pass
  81.         self.nsdict = { }
  82.         self.transport = transport
  83.         if not transdict:
  84.             pass
  85.         self.transdict = { }
  86.         self.url = url
  87.         self.trace = tracefile
  88.         self.readerclass = readerclass
  89.         self.writerclass = writerclass
  90.         self.soapaction = soapaction
  91.         self.wsAddressURI = wsAddressURI
  92.         self.sig_handler = sig_handler
  93.         self.address = None
  94.         self.endPointReference = kw.get('endPointReference', None)
  95.         self.cookies = Cookie.SimpleCookie()
  96.         self.http_callbacks = { }
  97.         if kw.has_key('auth'):
  98.             self.SetAuth(*kw['auth'])
  99.         else:
  100.             self.SetAuth(AUTH.none)
  101.  
  102.     
  103.     def SetAuth(self, style, user = None, password = None):
  104.         self.auth_style = style
  105.         self.auth_user = user
  106.         self.auth_pass = password
  107.         return self
  108.  
  109.     
  110.     def SetURL(self, url):
  111.         self.url = url
  112.         return self
  113.  
  114.     
  115.     def ResetHeaders(self):
  116.         self.user_headers = []
  117.         return self
  118.  
  119.     
  120.     def ResetCookies(self):
  121.         self.cookies = Cookie.SimpleCookie()
  122.  
  123.     
  124.     def AddHeader(self, header, value):
  125.         self.user_headers.append((header, value))
  126.         return self
  127.  
  128.     
  129.     def _Binding__addcookies(self):
  130.         for cname, morsel in self.cookies.items():
  131.             attrs = []
  132.             value = morsel.get('version', '')
  133.             if value != '' and value != '0':
  134.                 attrs.append('$Version=%s' % value)
  135.             
  136.             attrs.append('%s=%s' % (cname, morsel.coded_value))
  137.             value = morsel.get('path')
  138.             if value:
  139.                 attrs.append('$Path=%s' % value)
  140.             
  141.             value = morsel.get('domain')
  142.             if value:
  143.                 attrs.append('$Domain=%s' % value)
  144.             
  145.             self.h.putheader('Cookie', '; '.join(attrs))
  146.         
  147.  
  148.     
  149.     def RPC(self, url, opname, obj, replytype = None, **kw):
  150.         self.Send(url, opname, obj, **kw)
  151.         return self.Receive(replytype, **kw)
  152.  
  153.     
  154.     def Send(self, url, opname, obj, nsdict = { }, soapaction = None, wsaction = None, endPointReference = None, soapheaders = (), **kw):
  155.         if not url:
  156.             pass
  157.         url = self.url
  158.         if not endPointReference:
  159.             pass
  160.         endPointReference = self.endPointReference
  161.         d = { }
  162.         d.update(self.nsdict)
  163.         d.update(nsdict)
  164.         if not self.writerclass:
  165.             pass
  166.         SWC = kw.get('writerclass', SoapWriter)
  167.         sw = SWC(nsdict = d, header = True, outputclass = self.writerclass, encodingStyle = kw.get('encodingStyle'))
  168.         requesttypecode = kw.get('requesttypecode')
  169.         if kw.has_key('_args'):
  170.             if not requesttypecode:
  171.                 pass
  172.             tc = TC.Any(pname = opname, aslist = False)
  173.             sw.serialize(kw['_args'], tc)
  174.         elif not requesttypecode:
  175.             if not getattr(obj, 'typecode', None):
  176.                 pass
  177.             tc = TC.Any(pname = opname, aslist = False)
  178.             
  179.             try:
  180.                 if type(obj) in _seqtypes:
  181.                     obj = dict(map((lambda i: (i.typecode.pname, i)), obj))
  182.             except AttributeError:
  183.                 tc = TC.Any(pname = opname, aslist = True)
  184.  
  185.             tc = TC.Any(pname = opname, aslist = False)
  186.             sw.serialize(obj, tc)
  187.         else:
  188.             sw.serialize(obj, requesttypecode)
  189.         for i in soapheaders:
  190.             sw.serialize_header(i)
  191.         
  192.         if self.auth_style & AUTH.zsibasic:
  193.             sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass), _AuthHeader.typecode)
  194.         
  195.         if self.wsAddressURI is not None:
  196.             if self.soapaction and wsaction.strip('\'"') != self.soapaction:
  197.                 raise WSActionException, 'soapAction(%s) and WS-Action(%s) must match' % (self.soapaction, wsaction)
  198.             wsaction.strip('\'"') != self.soapaction
  199.             self.address = Address(url, self.wsAddressURI)
  200.             self.address.setRequest(endPointReference, wsaction)
  201.             self.address.serialize(sw)
  202.         
  203.         if self.sig_handler is not None:
  204.             self.sig_handler.sign(sw)
  205.         
  206.         (scheme, netloc, path, nil, nil, nil) = urlparse.urlparse(url)
  207.         transport = self.transport
  208.         if transport is None and url is not None:
  209.             if scheme == 'https':
  210.                 transport = self.defaultHttpsTransport
  211.             elif scheme == 'http':
  212.                 transport = self.defaultHttpTransport
  213.             else:
  214.                 raise RuntimeError, 'must specify transport or url startswith https/http'
  215.         scheme == 'https'
  216.         if issubclass(transport, httplib.HTTPConnection) is False:
  217.             raise TypeError, 'transport must be a HTTPConnection'
  218.         issubclass(transport, httplib.HTTPConnection) is False
  219.         soapdata = str(sw)
  220.         self.h = transport(netloc, None, **self.transdict)
  221.         self.h.connect()
  222.         self.SendSOAPData(soapdata, url, soapaction, **kw)
  223.  
  224.     
  225.     def SendSOAPData(self, soapdata, url, soapaction, headers = { }, **kw):
  226.         if self.trace:
  227.             print >>self.trace, '_' * 33, time.ctime(time.time()), 'REQUEST:'
  228.             print >>self.trace, soapdata
  229.         
  230.         if not url:
  231.             pass
  232.         url = self.url
  233.         request_uri = _get_postvalue_from_absoluteURI(url)
  234.         self.h.putrequest('POST', request_uri)
  235.         self.h.putheader('Content-Length', '%d' % len(soapdata))
  236.         self.h.putheader('Content-Type', 'text/xml; charset="%s"' % UNICODE_ENCODING)
  237.         self._Binding__addcookies()
  238.         for header, value in headers.items():
  239.             self.h.putheader(header, value)
  240.         
  241.         if not soapaction:
  242.             pass
  243.         SOAPActionValue = '"%s"' % self.soapaction
  244.         self.h.putheader('SOAPAction', SOAPActionValue)
  245.         if self.auth_style & AUTH.httpbasic:
  246.             val = _b64_encode(self.auth_user + ':' + self.auth_pass).replace('\n', '')
  247.             self.h.putheader('Authorization', 'Basic ' + val)
  248.         elif self.auth_style == AUTH.httpdigest and not headers.has_key('Authorization') and not headers.has_key('Expect'):
  249.             
  250.             def digest_auth_cb(response):
  251.                 self.SendSOAPDataHTTPDigestAuth(response, soapdata, url, request_uri, soapaction, **kw)
  252.                 self.http_callbacks[401] = None
  253.  
  254.             self.http_callbacks[401] = digest_auth_cb
  255.         
  256.         for header, value in self.user_headers:
  257.             self.h.putheader(header, value)
  258.         
  259.         self.h.endheaders()
  260.         self.h.send(soapdata)
  261.         (self.data, self.ps) = (None, None)
  262.  
  263.     
  264.     def SendSOAPDataHTTPDigestAuth(self, response, soapdata, url, request_uri, soapaction, **kw):
  265.         if self.trace:
  266.             print >>self.trace, '------ Digest Auth Header'
  267.         
  268.         if not url:
  269.             pass
  270.         url = self.url
  271.         if response.status != 401:
  272.             raise RuntimeError, 'Expecting HTTP 401 response.'
  273.         response.status != 401
  274.         if self.auth_style != AUTH.httpdigest:
  275.             raise RuntimeError, 'Auth style(%d) does not support requested digest authorization.' % self.auth_style
  276.         self.auth_style != AUTH.httpdigest
  277.         fetch_challenge = fetch_challenge
  278.         generate_response = generate_response
  279.         build_authorization_arg = build_authorization_arg
  280.         dict_fetch = dict_fetch
  281.         import ZSI.digest_auth
  282.         chaldict = fetch_challenge(response.getheader('www-authenticate'))
  283.         if dict_fetch(chaldict, 'challenge', '').lower() == 'digest' and dict_fetch(chaldict, 'nonce', None) and dict_fetch(chaldict, 'realm', None) and dict_fetch(chaldict, 'qop', None):
  284.             authdict = generate_response(chaldict, request_uri, self.auth_user, self.auth_pass, method = 'POST')
  285.             headers = {
  286.                 'Authorization': build_authorization_arg(authdict),
  287.                 'Expect': '100-continue' }
  288.             self.SendSOAPData(soapdata, url, soapaction, headers, **kw)
  289.             return None
  290.         raise RuntimeError, 'Client expecting digest authorization challenge.'
  291.  
  292.     
  293.     def ReceiveRaw(self, **kw):
  294.         if self.data:
  295.             return self.data
  296.         trace = self.trace
  297.         while None:
  298.             response = self.h.getresponse()
  299.             (self.reply_code, self.reply_msg, self.reply_headers, self.data) = (response.status, response.reason, response.msg, response.read())
  300.             saved = None
  301.             for d in response.msg.getallmatchingheaders('set-cookie'):
  302.                 if d[0] in (' ', '\t'):
  303.                     saved += d.strip()
  304.                     continue
  305.                 None if trace else self.data
  306.                 if saved:
  307.                     self.cookies.load(saved)
  308.                 
  309.                 saved = d.strip()
  310.             
  311.             if saved:
  312.                 self.cookies.load(saved)
  313.             
  314.             if response.status == 401:
  315.                 if not callable(self.http_callbacks.get(response.status, None)):
  316.                     raise RuntimeError, 'HTTP Digest Authorization Failed'
  317.                 callable(self.http_callbacks.get(response.status, None))
  318.                 self.http_callbacks[response.status](response)
  319.                 continue
  320.             
  321.             if response.status != 100:
  322.                 break
  323.             
  324.             self.h._HTTPConnection__state = httplib._CS_REQ_SENT
  325.             self.h._HTTPConnection__response = None
  326.             continue
  327.             return self.data
  328.  
  329.     
  330.     def IsSOAP(self):
  331.         if self.ps:
  332.             return 1
  333.         self.ReceiveRaw()
  334.         mimetype = self.reply_headers.type
  335.         return mimetype == 'text/xml'
  336.  
  337.     
  338.     def ReceiveSOAP(self, readerclass = None, **kw):
  339.         if self.ps:
  340.             return self.ps
  341.         if not self.IsSOAP():
  342.             raise TypeError('Response is "%s", not "text/xml"' % self.reply_headers.type)
  343.         self.IsSOAP()
  344.         if len(self.data) == 0:
  345.             raise TypeError('Received empty response')
  346.         len(self.data) == 0
  347.         if not readerclass:
  348.             pass
  349.         self.ps = ParsedSoap(self.data, readerclass = self.readerclass, encodingStyle = kw.get('encodingStyle'))
  350.         if self.sig_handler is not None:
  351.             self.sig_handler.verify(self.ps)
  352.         
  353.         return self.ps
  354.  
  355.     
  356.     def IsAFault(self):
  357.         self.ReceiveSOAP()
  358.         return self.ps.IsAFault()
  359.  
  360.     
  361.     def ReceiveFault(self, **kw):
  362.         self.ReceiveSOAP(**kw)
  363.         if not self.ps.IsAFault():
  364.             raise TypeError('Expected SOAP Fault not found')
  365.         self.ps.IsAFault()
  366.         return FaultFromFaultMessage(self.ps)
  367.  
  368.     
  369.     def Receive(self, replytype, **kw):
  370.         self.ReceiveSOAP(**kw)
  371.         if self.ps.IsAFault():
  372.             msg = FaultFromFaultMessage(self.ps)
  373.             raise FaultException(msg)
  374.         self.ps.IsAFault()
  375.         tc = replytype
  376.         if hasattr(replytype, 'typecode'):
  377.             tc = replytype.typecode
  378.         
  379.         reply = self.ps.Parse(tc)
  380.         if self.address is not None:
  381.             self.address.checkResponse(self.ps, kw.get('wsaction'))
  382.         
  383.         return reply
  384.  
  385.     
  386.     def __repr__(self):
  387.         return '<%s instance %s>' % (self.__class__.__name__, _get_idstr(self))
  388.  
  389.  
  390.  
  391. class Binding(_Binding):
  392.     gettypecode = staticmethod((lambda mod, e: getattr(mod, str(e.localName)).typecode))
  393.     logger = _GetLogger('ZSI.client.Binding')
  394.     
  395.     def __init__(self, url, namespace = None, typesmodule = None, **kw):
  396.         self.typesmodule = typesmodule
  397.         self.namespace = namespace
  398.         _Binding.__init__(self, url = url, **kw)
  399.  
  400.     
  401.     def __getattr__(self, name):
  402.         if name[:2] == '__' and len(name) > 5 and name[-2:] == '__':
  403.             if hasattr(self, name):
  404.                 return getattr(self, name)
  405.             return getattr(self.__class__, name)
  406.         return _Caller(self, name, self.namespace)
  407.  
  408.     
  409.     def __parse_child(self, node):
  410.         
  411.         try:
  412.             tc = self.gettypecode(self.typesmodule, node)
  413.         except:
  414.             self.logger.debug('didnt find typecode for "%s" in typesmodule: %s', node.localName, self.typesmodule)
  415.             tc = TC.Any(aslist = 1)
  416.             return tc.parse(node, self.ps)
  417.  
  418.         self.logger.debug('parse child with typecode : %s', tc)
  419.         
  420.         try:
  421.             return tc.parse(node, self.ps)
  422.         except Exception:
  423.             self.logger.debug('parse failed try Any : %s', tc)
  424.  
  425.         tc = TC.Any(aslist = 1)
  426.         return tc.parse(node, self.ps)
  427.  
  428.     
  429.     def Receive(self, replytype, **kw):
  430.         self.ReceiveSOAP(**kw)
  431.         ps = self.ps
  432.         tp = _find_type(ps.body_root)
  433.         if not type(tp) in (tuple, list) or tp[1] == 'Array':
  434.             pass
  435.         isarray = _find_arraytype(ps.body_root)
  436.         if self.typesmodule is None or isarray:
  437.             return _Binding.Receive(self, replytype, **kw)
  438.         if ps.IsAFault():
  439.             msg = FaultFromFaultMessage(ps)
  440.             raise FaultException(msg)
  441.         ps.IsAFault()
  442.         tc = replytype
  443.         if hasattr(replytype, 'typecode'):
  444.             tc = replytype.typecode
  445.         
  446.         reply = { }
  447.         for elt in _child_elements(ps.body_root):
  448.             name = str(elt.localName)
  449.             reply[name] = self._Binding__parse_child(elt)
  450.         
  451.         if self.address is not None:
  452.             self.address.checkResponse(ps, kw.get('wsaction'))
  453.         
  454.         return reply
  455.  
  456.  
  457.  
  458. class NamedParamBinding(Binding):
  459.     logger = _GetLogger('ZSI.client.Binding')
  460.     
  461.     def __getattr__(self, name):
  462.         if name[:2] == '__' and len(name) > 5 and name[-2:] == '__':
  463.             if hasattr(self, name):
  464.                 return getattr(self, name)
  465.             return getattr(self.__class__, name)
  466.         return _NamedParamCaller(self, name, self.namespace)
  467.  
  468.  
  469. if __name__ == '__main__':
  470.     print _copyright
  471.  
  472.