
gP[c        
   @   sf  d  d l  m Z d  d l m Z m Z d  d l m Z d  d l m Z m	 Z	 d  d l
 m Z m Z d  d l Z y d  d l m Z m Z WnE e k
 r e Z y d  d l m Z Wq e k
 r e Z q Xn XyX d Z e Z d  d l Z d  d	 l m Z m Z m Z d  d
 l m Z d  d l m Z Wn e k
 r;n Xd  d l Z d d l m Z m Z m Z e    Z! d   Z" d e  f d     YZ# d e d d d d d d d d g  f d     YZ$ d   Z% d   Z& d   Z' d d d d d  Z( d   Z) d   Z* d    Z+ d!   Z, d"   Z- e d k	 rGd d d d d d d#  Z. n d d d d d d d$  Z. d S(%   i(   t	   b64encode(   t   hexlifyt	   unhexlify(   t
   namedtuple(   t   md5t   sha1(   t   errort   _GLOBAL_DEFAULT_TIMEOUTN(   t   pollt   POLLIN(   t   select(   t   wrap_sockett	   CERT_NONEt   PROTOCOL_SSLv23(   t
   SSLContext(   t   HAS_SNIi   (   t   LocationParseErrort   SSLErrort   TimeoutStateErrorc           C   s
   t  j    S(   sQ   
    Retrieve the current time, this function is mocked out in unit testing.
    (   t   time(    (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   current_time,   s    t   Timeoutc           B   s   e  Z d  Z e Z e e d
 d  Z d   Z e	 d    Z
 e	 d    Z d   Z d   Z d   Z e d    Z e d	    Z RS(   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
        <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.
        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
        <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.
        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.
    c         C   sL   |  j  | d  |  _ |  j  | d  |  _ |  j  | d  |  _ d  |  _ d  S(   Nt   connectt   readt   total(   t   _validate_timeoutt   _connectt   _readR   t   Nonet   _start_connect(   t   selfR   R   R   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   __init__s   s    c         C   s&   d t  |   j |  j |  j |  j f S(   Ns!   %s(connect=%r, read=%r, total=%r)(   t   typet   __name__R   R   R   (   R   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   __str__y   s    c         C   s   | t  k r |  j S| d k s. | |  j k r2 | Sy t |  Wn- t t f k
 ro t d | | f   n Xy) | d k  r t d | | f   n  Wn' t k
 r t d | | f   n X| 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
        s8   Timeout value %s was %s, but it must be an int or float.i    sX   Attempted to set %s timeout to %s, but the timeout cannot be set to a value less than 0.N(   t   _Defaultt   DEFAULT_TIMEOUTR   t   floatt	   TypeErrort
   ValueError(   t   clst   valuet   name(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyR   ~   s"    c         C   s   t  d | 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`
        R   R   (   R   (   R(   t   timeout(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt
   from_float   s    c         C   s"   t  d |  j d |  j d |  j  S(   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`
        R   R   R   (   R   R   R   R   (   R   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   clone   s    c         C   s1   |  j  d k	 r t d   n  t   |  _  |  j  S(   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(   R   R   R   R   (   R   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   start_connect   s    c         C   s,   |  j  d k r t d   n  t   |  j  S(   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(   R   R   R   R   (   R   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   get_connect_duration   s    c         C   sQ   |  j  d k r |  j S|  j d k s7 |  j |  j k r> |  j  St |  j |  j   S(   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(   R   R   R   R$   t   min(   R   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   connect_timeout   s
    
!c         C   s   |  j  d k	 r~ |  j  |  j k	 r~ |  j d k	 r~ |  j |  j k	 r~ |  j d k rX |  j St d t |  j  |  j   |  j   S|  j  d k	 r |  j  |  j k	 r t d |  j  |  j    S|  j Sd S(   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.
        i    N(   R   R   R$   R   R   t   maxR0   R/   (   R   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   read_timeout   s    !N(   R!   t
   __module__t   __doc__R   R$   R#   R   R   R"   t   classmethodR   R,   R-   R.   R/   t   propertyR1   R3   (    (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyR   3   s   ;	"			t   Urlt   schemet   autht   hostt   portt   patht   queryt   fragmentc           B   s_   e  Z d  Z d Z d d d d d d d d  Z e d    Z e d    Z e d    Z	 RS(   sg   
    Datastructure for representing an HTTP URL. Used as a return value for
    :func:`parse_url`.
    c      	   C   s+   t  t |   j |  | | | | | | |  S(   N(   t   superR8   t   __new__(   R(   R9   R:   R;   R<   R=   R>   R?   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyRA     s    c         C   s   |  j  S(   s@   For backwards-compatibility with urlparse. We're nice like that.(   R;   (   R   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   hostname  s    c         C   s6   |  j  p d } |  j d k	 r2 | d |  j 7} n  | S(   s)   Absolute path including the query string.t   /t   ?N(   R=   R>   R   (   R   t   uri(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   request_uri  s    c         C   s$   |  j  r d |  j |  j  f S|  j S(   s(   Network location including host and ports   %s:%d(   R<   R;   (   R   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   netloc"  s    	(    N(
   R!   R4   R5   t   slotsR   RA   R7   RB   RF   RG   (    (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyR8   	  s   
c         C   s   d } d } xV | D]N } |  j |  } | d k  r: q n  | d k sR | | k  r | } | } q q W| d k s} | d k  r |  d d f S|  |  |  | d | f S(   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.
    i    t    i   N(   R   t   find(   t   st   delimst   min_idxt	   min_delimt   dt   idx(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   split_first*  s    c      
   C   s  d } d } d } d } d } d } d } d |  k rQ |  j d d  \ } }  n  t |  d d d g  \ }  } }	 |	 r |	 | } n  d |  k r |  j d d  \ } }  n  |  r |  d d k r |  j d	 d  \ } }  | d	 7} n  d
 |  k rH|  j d
 d  \ }
 } | s|
 } n  | j   s9t d |    n  t |  } n | r^|  r^|  } n  | st | | | | | | |  Sd | k r| j d d  \ } } n  d | k r| j d d  \ } } n  t | | | | | | |  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   ://i   RC   RD   t   #t   @i    t   [t   ]t   :s   Failed to parse: %sN(   R   t   splitRQ   t   isdigitR   t   intR8   (   t   urlR9   R:   R;   R<   R=   R?   R>   t   path_t   delimt   _host(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt	   parse_urlK  sB    !		c         C   s(   t  |   } | j p d | j | j f S(   s5   
    Deprecated. Use :func:`.parse_url` instead.
    t   http(   R^   R9   RB   R<   (   RZ   t   p(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   get_host  s    c         C   s   i  } | rR t  | t  r n' t  | t  r? d j |  } n d } | | d <n  | re | | d <n  |  rx d | d <n  | r d t t j |   j d  | d	 <n  | S(
   s-  
    Shortcuts for generating request headers.

    :param keep_alive:
        If ``True``, adds 'connection: keep-alive' header.

    :param accept_encoding:
        Can be a boolean, list, or string.
        ``True`` translates to 'gzip,deflate'.
        List will get joined by comma.
        String will be used as provided.

    :param user_agent:
        String representing the user-agent you want, such as
        "python-urllib3/0.6"

    :param basic_auth:
        Colon-separated username:password string for 'authorization: basic ...'
        auth header.

    Example: ::

        >>> 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,deflates   accept-encodings
   user-agents
   keep-alivet
   connections   Basic s   utf-8t   authorization(   t
   isinstancet   strt   listt   joinR    t   sixt   bt   decode(   t
   keep_alivet   accept_encodingt
   user_agentt
   basic_autht   headers(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   make_headers  s     &c         C   s   t  |  d t  } | t k r" t S| d k r2 t St sx t sB t Sy t | g g  g  d  d SWqx t k
 rt t SXn  t   } | j | t  x3 | j d  D]" \ } } | | j	   k r t Sq Wd S(   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.
    t   sockg        i    N(
   t   getattrt   FalseR   t   TrueR   R
   t   SocketErrort   registerR	   t   fileno(   t   connRr   R`   t   fnot   ev(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   is_connection_dropped  s"    
	c         C   s[   |  d k r t St |  t  rW t t |  d  } | d k rS t t d |   } 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.
    t   CERT_N(   R   R   Re   Rf   Rs   t   ssl(   t	   candidatet   res(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   resolve_cert_reqs  s    c         C   s[   |  d k r t St |  t  rW t t |  d  } | d k rS t t d |   } n  | S|  S(   s    
    like resolve_cert_reqs
    t	   PROTOCOL_N(   R   R   Re   Rf   Rs   R~   (   R   R   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   resolve_ssl_version  s    c         C   s   i t  d 6t d 6} | j d d  j   } t t |  d  \ } } | sY | | k rh t d   n  t | j    } | | } | |   j	   } | | k s t d j
 t |  t |     n  d S(	   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.
    i   i   RV   RI   i   s!   Fingerprint is of invalid length.s6   Fingerprints did not match. Expected "{0}", got "{1}".N(   R   R   t   replacet   lowert   divmodt   lenR   R   t   encodet   digestt   formatR   (   t   certt   fingerprintt   hashfunc_mapt   digest_lengtht   restt   fingerprint_bytest   hashfunct   cert_digest(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   assert_fingerprint   s    

		c         C   s#   t  |  d  r |  j d k S|  j S(   st   
    Checks whether a given file-like object is closed.

    :param obj:
        The file-like object to check.
    t   fpN(   t   hasattrR   R   t   closed(   t   obj(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   is_fp_closedD  s    c   	      C   s   t  |  } | | _ | rQ y | j |  WqQ t k
 rM } t |   qQ Xn  | rj | j | |  n  t r | 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
        t   server_hostname(   R   t   verify_modet   load_verify_locationst	   ExceptionR   t   load_cert_chainR   R   (	   Rr   t   keyfilet   certfilet	   cert_reqst   ca_certsR   t   ssl_versiont   contextt   e(    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   ssl_wrap_socketT  s    
	c         C   s(   t  |  d | d | d | d | d | S(   NR   R   R   R   R   (   R   (   Rr   R   R   R   R   R   R   (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyR   o  s    (/   t   base64R    t   binasciiR   R   t   collectionsR   t   hashlibR   R   t   socketR   Rv   R   R   R
   R   R	   t   ImportErrorRt   R   R   R   R~   R   R   R   Ri   t
   exceptionsR   R   R   t   objectR#   R   R   R8   RQ   R^   Ra   Rq   R|   R   R   R   R   R   (    (    (    s0   /usr/lib/python2.7/dist-packages/urllib3/util.pyt   <module>   sZ   		4!	!	P		3	"			$			