gP[c @sfddlmZddlmZmZddlmZddlmZm Z ddl m Z m Z ddlZyddlmZmZWnEek reZyddlmZWqek reZqXnXyXdZeZddlZdd lmZmZmZdd lmZdd lmZWnek r;nXddlZd d lmZmZmZe Z!dZ"de fdYZ#deddddddddgfdYZ$dZ%dZ&dZ'dddddZ(dZ)dZ*d Z+d!Z,d"Z-edk rGddddddd#Z.nddddddd$Z.dS(%i(t b64encode(thexlifyt unhexlify(t namedtuple(tmd5tsha1(terrort_GLOBAL_DEFAULT_TIMEOUTN(tpolltPOLLIN(tselect(t wrap_sockett CERT_NONEtPROTOCOL_SSLv23(t SSLContext(tHAS_SNIi(tLocationParseErrortSSLErrortTimeoutStateErrorcCs tjS(sQ Retrieve the current time, this function is mocked out in unit testing. (ttime(((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyt current_time,stTimeoutcBseZdZeZeed dZdZe dZ e dZ dZ dZ dZedZed ZRS( s Utility object for storing timeout values. Example usage: .. code-block:: python timeout = urllib3.util.Timeout(connect=2.0, read=7.0) pool = HTTPConnectionPool('www.google.com', 80, timeout=timeout) pool.request(...) # Etc, etc :param connect: The maximum amount of time to wait for a connection attempt to a server to succeed. Omitting the parameter will default the connect timeout to the system default, probably `the global default timeout in socket.py `_. None will set an infinite timeout for connection attempts. :type connect: integer, float, or None :param read: The maximum amount of time to wait between consecutive read operations for a response from the server. Omitting the parameter will default the read timeout to the system default, probably `the global default timeout in socket.py `_. None will set an infinite timeout. :type read: integer, float, or None :param total: The maximum amount of time to wait for an HTTP request to connect and return. This combines the connect and read timeouts into one. In the event that both a connect timeout and a total are specified, or a read timeout and a total are specified, the shorter timeout will be applied. Defaults to None. :type total: integer, float, or None .. note:: Many factors can affect the total amount of time for urllib3 to return an HTTP response. Specifically, Python's DNS resolver does not obey the timeout specified on the socket. Other factors that can affect total request time include high CPU load, high swap, the program running at a low priority level, or other behaviors. The observed running time for urllib3 to return a response may be greater than the value passed to `total`. In addition, the read and total timeouts only measure the time between read operations on the socket connecting the client and the server, not the total amount of time for the request to return a complete response. As an example, you may want a request to return within 7 seconds or fail, so you set the ``total`` timeout to 7 seconds. If the server sends one byte to you every 5 seconds, the request will **not** trigger time out. This case is admittedly rare. cCsL|j|d|_|j|d|_|j|d|_d|_dS(Ntconnecttreadttotal(t_validate_timeoutt_connectt_readRtNonet_start_connect(tselfRRR((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyt__init__sscCs&dt|j|j|j|jfS(Ns!%s(connect=%r, read=%r, total=%r)(ttypet__name__RRR(R((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyt__str__yscCs|tkr|jS|dks.||jkr2|Syt|Wn-ttfk rotd||fnXy)|dkrtd||fnWn'tk rtd||fnX|S(st Check that a timeout attribute is valid :param value: The timeout value to validate :param name: The name of the timeout attribute to validate. This is used for clear error messages :return: the value :raises ValueError: if the type is not an integer or a float, or if it is a numeric value less than zero s8Timeout value %s was %s, but it must be an int or float.isXAttempted to set %s timeout to %s, but the timeout cannot be set to a value less than 0.N(t_DefaulttDEFAULT_TIMEOUTRtfloatt TypeErrort ValueError(tclstvaluetname((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyR~s"   cCstd|d|S(s Create a new Timeout from a legacy timeout value. The timeout value used by httplib.py sets the same timeout on the connect(), and recv() socket requests. This creates a :class:`Timeout` object that sets the individual timeouts to the ``timeout`` value passed to this function. :param timeout: The legacy timeout value :type timeout: integer, float, sentinel default object, or None :return: a Timeout object :rtype: :class:`Timeout` RR(R(R(ttimeout((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyt from_floatscCs"td|jd|jd|jS(s Create a copy of the timeout object Timeout properties are stored per-pool but each request needs a fresh Timeout object to ensure each one has its own start/stop configured. :return: a copy of the timeout object :rtype: :class:`Timeout` RRR(RRRR(R((s0/usr/lib/python2.7/dist-packages/urllib3/util.pytclones cCs1|jdk rtdnt|_|jS(s Start the timeout clock, used during a connect() attempt :raises urllib3.exceptions.TimeoutStateError: if you attempt to start a timer that has been started already. s'Timeout timer has already been started.N(RRRR(R((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyt start_connects cCs,|jdkrtdnt|jS(s Gets the time elapsed since the call to :meth:`start_connect`. :return: the elapsed time :rtype: float :raises urllib3.exceptions.TimeoutStateError: if you attempt to get duration for a timer that hasn't been started. s:Can't get connect duration for timer that has not started.N(RRRR(R((s0/usr/lib/python2.7/dist-packages/urllib3/util.pytget_connect_durationscCsQ|jdkr|jS|jdks7|j|jkr>|jSt|j|jS(s% Get the value to use when setting a connection timeout. This will be a positive float or integer, the value None (never timeout), or the default system timeout. :return: the connect timeout :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None N(RRRR$tmin(R((s0/usr/lib/python2.7/dist-packages/urllib3/util.pytconnect_timeouts !cCs|jdk r~|j|jk r~|jdk r~|j|jk r~|jdkrX|jStdt|j|j|jS|jdk r|j|jk rtd|j|jS|jSdS(s Get the value for the read timeout. This assumes some time has elapsed in the connection timeout and computes the read timeout appropriately. If self.total is set, the read timeout is dependent on the amount of time taken by the connect timeout. If the connection time has not been established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be raised. :return: the value to use for the read timeout :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` has not yet been called on this object. iN(RRR$RRtmaxR0R/(R((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyt read_timeouts !N(R!t __module__t__doc__RR$R#RRR"t classmethodRR,R-R.R/tpropertyR1R3(((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyR3s; "  tUrltschemetauththosttporttpathtquerytfragmentcBs_eZdZdZddddddddZedZedZedZ RS(sg Datastructure for representing an HTTP URL. Used as a return value for :func:`parse_url`. c Cs+tt|j||||||||S(N(tsuperR8t__new__(R(R9R:R;R<R=R>R?((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyRAscCs|jS(s@For backwards-compatibility with urlparse. We're nice like that.(R;(R((s0/usr/lib/python2.7/dist-packages/urllib3/util.pythostnamescCs6|jp d}|jdk r2|d|j7}n|S(s)Absolute path including the query string.t/t?N(R=R>R(Rturi((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyt request_uriscCs$|jrd|j|jfS|jS(s(Network location including host and ports%s:%d(R<R;(R((s0/usr/lib/python2.7/dist-packages/urllib3/util.pytnetloc"s (N( R!R4R5tslotsRRAR7RBRFRG(((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyR8 s  cCsd}d}xV|D]N}|j|}|dkr:qn|dksR||kr|}|}qqW|dks}|dkr|ddfS|| ||d|fS(s Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example: :: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123') ('foo/bar?baz', '', None) Scales linearly with number of delims. Not ideal for large number of delims. itiN(Rtfind(tstdelimstmin_idxt min_delimtdtidx((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyt split_first*s    c Csd }d }d }d }d }d }d }d|krQ|jdd\}}nt|dddg\}}} | r| |}nd|kr|jdd\}}n|r|ddkr|jd d\}}|d 7}nd |krH|jd d\} }|s| }n|js9td |nt|}n| r^|r^|}n|st|||||||Sd|kr|jdd\}}nd|kr|jdd\}}nt|||||||S( s7 Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. Partly backwards-compatible with :mod:`urlparse`. Example: :: >>> parse_url('http://google.com/mail/') Url(scheme='http', host='google.com', port=None, path='/', ...) >>> parse_url('google.com:80') Url(scheme=None, host='google.com', port=80, path=None, ...) >>> parse_url('/foo?bar') Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) s://iRCRDt#t@it[t]t:sFailed to parse: %sN(RtsplitRQtisdigitRtintR8( turlR9R:R;R<R=R?R>tpath_tdelimt_host((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyt parse_urlKsB !          cCs(t|}|jpd|j|jfS(s5 Deprecated. Use :func:`.parse_url` instead. thttp(R^R9RBR<(RZtp((s0/usr/lib/python2.7/dist-packages/urllib3/util.pytget_hosts cCsi}|rRt|trn't|tr?dj|}nd}||d>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'} t,s gzip,deflatesaccept-encodings user-agents keep-alivet connectionsBasic sutf-8t authorization(t isinstancetstrtlisttjoinRtsixtbtdecode(t keep_alivetaccept_encodingt user_agentt basic_auththeaders((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyt make_headerss    &cCst|dt}|tkr"tS|dkr2tStsxtsBtSyt|gggddSWqxtk rttSXnt}|j|tx3|jdD]"\}}||j krtSqWdS(s  Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us. tsockgiN( tgetattrtFalseRtTrueRR t SocketErrortregisterR tfileno(tconnRrR`tfnotev((s0/usr/lib/python2.7/dist-packages/urllib3/util.pytis_connection_droppeds"     cCs[|dkrtSt|trWtt|d}|dkrSttd|}n|S|S(s Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_NONE`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbrevation. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. If it's neither `None` nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket. tCERT_N(RR ReRfRstssl(t candidatetres((s0/usr/lib/python2.7/dist-packages/urllib3/util.pytresolve_cert_reqss  cCs[|dkrtSt|trWtt|d}|dkrSttd|}n|S|S(s like resolve_cert_reqs t PROTOCOL_N(RR ReRfRsR~(RR((s0/usr/lib/python2.7/dist-packages/urllib3/util.pytresolve_ssl_versions  cCsitd6td6}|jddj}tt|d\}}|sY||krhtdnt|j}||}||j }||kstdj t |t |ndS( s Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. iiRVRIis!Fingerprint is of invalid length.s6Fingerprints did not match. Expected "{0}", got "{1}".N( RRtreplacetlowertdivmodtlenRRtencodetdigesttformatR(tcertt fingerprintt hashfunc_mapt digest_lengthtresttfingerprint_bytesthashfunct cert_digest((s0/usr/lib/python2.7/dist-packages/urllib3/util.pytassert_fingerprint s      cCs#t|dr|jdkS|jS(st Checks whether a given file-like object is closed. :param obj: The file-like object to check. tfpN(thasattrRRtclosed(tobj((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyt is_fp_closedDs c Cst|}||_|rQy|j|WqQtk rM}t|qQXn|rj|j||ntr|j|d|S|j|S(s All arguments except `server_hostname` have the same meaning as for :func:`ssl.wrap_socket` :param server_hostname: Hostname of the expected certificate tserver_hostname(Rt verify_modetload_verify_locationst ExceptionRtload_cert_chainRR ( Rrtkeyfiletcertfilet cert_reqstca_certsRt ssl_versiontcontextte((s0/usr/lib/python2.7/dist-packages/urllib3/util.pytssl_wrap_socketTs  c Cs(t|d|d|d|d|d|S(NRRRRR(R (RrRRRRRR((s0/usr/lib/python2.7/dist-packages/urllib3/util.pyRos (/tbase64RtbinasciiRRt collectionsRthashlibRRtsocketRRvRRR RR t ImportErrorRtRRRR~R R R Rit exceptionsRRRtobjectR#RRR8RQR^RaRqR|RRRRR(((s0/usr/lib/python2.7/dist-packages/urllib3/util.pytsZ        4! ! P   3 "   $