ó
 ½ƒWc           @   s¤  d  Z  d Z d Z d Z d Z d Z d Z d d l Z d d	 l m	 Z	 d d l
 Z
 d d l Z e j d
 d k rd d l j Z d d l j Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l m Z d d l  m! Z" d d l# j$ Z% n” d d l& Z d d l' Z d d l( m Z d d l( m Z d d l( m Z d d l( m Z d d l( m Z d d l( m Z d d l( m! Z" d d l) Z% d d l* m+ Z+ d d l, m- Z- d d l. m/ Z/ e j0 e1 ƒ Z2 d e f d „  ƒ  YZ3 d e4 f d „  ƒ  YZ5 d d d „ Z7 d d d „ Z8 d d d „ Z9 d d d „ Z: d d „ Z; d „  Z< d  e= f d! „  ƒ  YZ> d" „  Z? e1 d# k r e j@ ƒ  e? ƒ  n  d S($   s`   Utilities using NDG HTTPS Client, including a main module that can be used to
fetch from a URL.
s   R B Wilkinsons   09/12/11s2   (C) 2011 Science and Technology Facilities Councils-   BSD - see LICENSE file in top-level directorys   Philip.Kershaw@stfc.ac.uks   $Id$iÿÿÿÿN(   t   OptionParseri    i   (   t   Request(   t   HTTPHandler(   t   HTTPCookieProcessor(   t   HTTPBasicAuthHandler(   t   HTTPPasswordMgrWithDefaultRealm(   t   ProxyHandler(   t	   HTTPError(   t   build_opener(   t   HTTPSContextHandler(   t   ssl_context_utilt   AccumulatingHTTPCookieProcessorc           B   s   e  Z d  Z d „  Z e Z RS(   st   Cookie processor that adds new cookies (instead of replacing the existing
    ones as HTTPCookieProcessor does)
    c         C   s¯   d } t  | j ƒ  | j i  | j | j ƒ } |  j j | ƒ | j | ƒ } | r« | j | ƒ r˜ | j | ƒ } d j	 | | g ƒ } | j
 | | ƒ q« | j
 | | ƒ n  | S(   s¹   Processes cookies for a HTTP request.
        @param request: request to process
        @type request: urllib2.Request
        @return: request
        @rtype: urllib2.Request
        t   Cookies   ; (   t   Request_t   get_full_urlt   datat   origin_req_hostt   unverifiablet	   cookiejart   add_cookie_headert
   get_headert
   has_headert   joint   add_unredirected_header(   t   selft   requestt   COOKIE_HEADER_NAMEt   tmp_requestt   new_cookiest   old_cookiest   merged_cookies(    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyt   http_request3   s    	
(   t   __name__t
   __module__t   __doc__R   t   https_request(    (    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyR   /   s   	t   URLFetchErrorc           B   s   e  Z d  Z RS(   s   Error fetching content from URL(   R    R!   R"   (    (    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyR$   Q   s   c         C   sc   t  |  | d | d | ƒ\ } } } | rS | t j k rS | j ƒ  } | j ƒ  | St | ƒ ‚ d S(   sá   Returns data retrieved from a URL.
    @param url: URL to attempt to open
    @type url: basestring
    @param config: SSL context configuration
    @type config: Configuration
    @return data retrieved from URL or None
    R   t   handlersN(   t   open_urlt   http_client_t   OKt   readt   closeR$   (   t   urlt   configR   R%   t   return_codet   return_messaget   responset   return_data(    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyt   fetch_from_urlU   s    
c   
      C   sˆ   t  |  | d | d | ƒ\ } } } | t j k rr | j ƒ  } | j ƒ  t | d ƒ }	 |	 j | ƒ |	 j ƒ  n  | | | t j k f S(   s¨  Writes data retrieved from a URL to a file.
    @param url: URL to attempt to open
    @type url: basestring
    @param config: SSL context configuration
    @type config: Configuration
    @param output_file: output file
    @type output_file: basestring
    @return: tuple (
        returned HTTP status code or 0 if an error occurred
        returned message
        boolean indicating whether access was successful)
    R   R%   t   w(   R&   R'   R(   R)   R*   t   opent   write(
   R+   R,   t   output_fileR   R%   R-   R.   R/   R0   t   outfile(    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyt   fetch_from_url_to_filef   s    
c         C   sM   t  |  | d | d | ƒ\ } } } | r= | t j k r= | St | ƒ ‚ d S(   sœ  Returns data retrieved from a URL.
    @param url: URL to attempt to open
    @type url: basestring
    @param config: SSL context configuration
    @type config: Configuration
    @param data: HTTP POST data
    @type data: str
    @param handlers: list of custom urllib2 handlers to add to the request
    @type handlers: iterable
    @return: data retrieved from URL or None
    @rtype: file derived type
    R   R%   N(   R&   R'   R(   R$   (   R+   R,   R   R%   R-   R.   R/   (    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyt   fetch_stream_from_url   s
    c      
   C   sâ  | j  r d n d } | j r* | j } n t j ƒ  } t | ƒ } | sQ g  } n  | j | ƒ | j  r¡ t d | ƒ } t | j d | ƒ} | j	 | | g ƒ n  | j
 rù t t ƒ  ƒ }	 |	 j d d d |  d | j
 d d | j
 d ƒ | j |	 ƒ n  t |  | j ƒ s.| j t i  ƒ ƒ t j  d ƒ n6 | j rd| j t | j ƒ ƒ t j  d	 | j ƒ n  t d
 | j | Œ }
 | j } | d k r—i  } n  t |  | | ƒ } d } d } d } yj |
 j | ƒ } | j } | j } t j t j ƒ r$x0 t | ƒ D] \ } } t j  d | | ƒ qþWn  Wn­ t k
 r~} | j } d | j } t j t j ƒ rÕt j  d | j | j ƒ qÕnW t k
 rÔ} d | j  ƒ  } t j t j ƒ rÕd d l! } t j  | j" ƒ  ƒ qÕn X| | | f S(   sÞ  Attempts to open a connection to a specified URL.
    @param url: URL to attempt to open
    @param config: SSL context configuration
    @type config: Configuration
    @param data: HTTP POST data
    @type data: str
    @param handlers: list of custom urllib2 handlers to add to the request
    @type handlers: iterable
    @return: tuple (
        returned HTTP status code or 0 if an error occurred
        returned message or error description
        response object)
    i   i    t
   debuglevelt   realmt   urit   usert   passwds   Not using proxys   Configuring proxies: %st   ssl_contextt    s	   %s  :  %ss	   Error: %ss   %s %siÿÿÿÿN(#   t   debugt   cookiet
   cookiejar_t	   CookieJarR   t   appendt   HTTPHandler_R	   R>   t   extendt   http_basicautht   HTTPBasicAuthHandler_t    HTTPPasswordMgrWithDefaultRealm_t   add_passwordt   Nonet   _should_use_proxyt   no_proxyt   ProxyHandler_t   logt   proxiesR   t   headersR   R3   t   msgt   codet   isEnabledFort   loggingt   DEBUGt	   enumeratet
   HTTPError_t	   Exceptiont   __str__t	   tracebackt
   format_exc(   R+   R,   R   R%   R9   t   cjt   cookie_handlert   http_handlert   https_handlert   auth_handlert   openerRQ   R   R-   R.   R/   t   indexRA   t   excR[   (    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyR&   ”   sf    											c         C   s‰   | d k r$ t j j d d ƒ } n | } t j t |  ƒ ƒ } xC g  | j d ƒ D] } | j ƒ  ^ qR D] } | j	 | k rh t
 Sqh Wt S(   sØ   Determines whether a proxy should be used to open a connection to the 
    specified URL, based on the value of the no_proxy environment variable.
    @param url: URL
    @type url: basestring or urllib2.Request
    RM   R?   t   ,N(   RK   t   ost   environt   gett	   urlparse_t   urlparset   _url_as_stringt   splitt   stript   hostnamet   Falset   True(   R+   RM   t   no_proxy_effectivet   urlObjt   ht   np(    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyRL   ó   s    /c         C   sF   t  |  t ƒ r |  j ƒ  St  |  t ƒ r, |  St d t t f ƒ ‚ d S(   sÍ   Returns the URL string from a URL value that is either a string or
    urllib2.Request..
    @param url: URL
    @type url: basestring or urllib2.Request
    @return: URL string
    @rtype: basestring
    s   Expected type %r or %rN(   t
   isinstanceR   R   t   strt	   TypeError(   R+   (    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyRk     s    
t   Configurationc           B   s)   e  Z d  Z e d d d d d d „ Z RS(   s   Connection configuration.
    c         C   sC   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ d S(   sÔ  
        @param ssl_context: SSL context to use with this configuration
        @type ssl_context: OpenSSL.SSL.Context
        @param debug: if True, output debugging information
        @type debug: bool
        @param proxies: proxies to use for 
        @type proxies: dict with basestring keys and values
        @param no_proxy: hosts for which a proxy should not be used
        @type no_proxy: basestring
        @param cookie: cookies to set for request
        @type cookie: cookielib.CookieJar (python 3 - http.cookiejar)
        @param http_basicauth: http authentication, or None
        @type http_basicauth: tuple of (username,password)
        @param headers: http headers
        @type headers: dict
        N(   R>   R@   RP   RM   RA   RG   RQ   (   R   R>   R@   RP   RM   RA   RG   RQ   (    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyt   __init__  s    						N(   R    R!   R"   Ro   RK   Ry   (    (    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyRx     s   	c          C   sÒ  t  d d ƒ }  |  j d d d d d d d	 t j j d
 ƒ d d ƒ|  j d d d d d d d	 d8 d d ƒ|  j d d d d d d d	 d8 d d ƒ|  j d d d d d d d	 t d d ƒ|  j d d d d d d d	 d8 d d ƒ|  j d  d! d d" d d d	 d8 d d# ƒ|  j d$ d% d d d d& d	 t d d' ƒ|  j d( d) d d* d d+ d	 d8 d d, ƒ|  j d- d d. d d/ d d0 d d1 ƒ|  j ƒ  \ } } t | ƒ d2 k r´|  j	 d3 ƒ n  | d4 } | j
 ràt j ƒ  j t j ƒ n  | j r
t j j | j ƒ r
| j } n d8 } | j r:t j j | j ƒ r:| j } n d8 } | j rjt j j | j ƒ rj| j } n d8 } | j } | j rÀt j j | j ƒ rÀt | j ƒ } | j ƒ  }	 | j ƒ  n d8 }	 | j rç| j j d5 d2 ƒ }
 n d8 }
 i  } | j rAxB | j D]4 } | j d5 d2 ƒ \ } } | j ƒ  | | j ƒ  <qWn  t j | | d8 | | | ƒ } t | | j
 d6 |
 d/ | ƒ} | j  rºt! | | | j  |	 ƒ d7  \ } } t" | | ƒ ‚ n t# | | ƒ }	 |	 GHd8 S(9   sH   Utility to fetch data using HTTP or HTTPS GET from a specified URL.
    t   usages   %prog [options] urls   -cs   --certificatet   destt	   cert_filet   metavart   FILEt   defaults   ~/credentials.pemt   helps4   Certificate file - defaults to $HOME/credentials.pems   -ks   --private-keyt   key_files3   Private key file - defaults to the certificate files   -ts   --ca-certificate-dirt   ca_dirt   PATHs%   Trusted CA certificate file directorys   -ds   --debugt   actiont
   store_trueR@   s   Print debug information.s   -ps   --post-data-filet	   data_files   POST data files   -fs   --fetchR5   s   Output files   -ns   --no-verify-peert   no_verify_peers&   Skip verification of peer certificate.s   -as   --basicautht	   basicauths   USER:PASSWDs   HTTP authentication credentialss   --headerRD   RQ   s   HEADER: VALUEs   Add HTTP header to requesti   s   Incorrect number of argumentsi    t   :RG   i   N($   R    t
   add_optionRf   t   patht
   expanduserRK   Ro   t
   parse_argst   lent   errorR@   RU   t	   getLoggert   setLevelRV   R   t   existsR|   R‚   R‡   R†   R3   R)   R*   Rˆ   Rl   RQ   t   lstripRm   R
   t   make_ssl_contextRx   R5   R7   t
   SystemExitR1   (   t   parsert   optionst   argsR+   R   R|   R‚   t   verify_peerR†   R   RG   RQ   Rs   t   keyt   valR>   R,   R-   R.   (    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyt   main4  sš    
	
							t   __main__(A   R"   t
   __author__t   __date__t   __copyright__t   __license__t   __contact__t   __revision__RU   t   optparseR    Rf   t   syst   version_infot   http.cookiejarR   RB   t   http.clientt   clientR'   t   urllib.requestR   R   R   RE   R   t   HTTPCookieProcessor_R   RH   R   RI   R   RN   t   urllib.errorR   RX   t   urllib.parset   parseRi   t	   cookielibt   httplibt   urllib2Rj   t$   ndg.httpsclient.urllib2_build_openerR   t   ndg.httpsclient.httpsR	   t   ndg.httpsclientR
   R   R    RO   R   RY   R$   RK   R1   R7   R8   R&   RL   Rk   t   objectRx   Rœ   t   basicConfig(    (    (    s9   /usr/lib/python2.7/dist-packages/ndg/httpsclient/utils.pyt   <module>   s`   "_		e
