
    BfiS=                     H   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
kD  r=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mZ ddl m!Z" ddl#m$Z% n6d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j`                  e1      Z2 G d de      Z3 G d de4      Z5d#dZ6d#dZ7d#dZ8d#dZ9d$dZ:d Z; G d d e<      Z=d! Z>e1d"k(  r ej~                           e>        yy)%z`Utilities using NDG HTTPS Client, including a main module that can be used to
fetch from a URL.
zR B Wilkinsonz09/12/11z2(C) 2011 Science and Technology Facilities Councilz-BSD - see LICENSE file in top-level directoryzPhilip.Kershaw@stfc.ac.ukz$Id$    N)OptionParser   )Request)HTTPHandler)HTTPCookieProcessor)HTTPBasicAuthHandler)HTTPPasswordMgrWithDefaultRealm)ProxyHandler)	HTTPError)build_opener)HTTPSContextHandler)ssl_context_utilc                       e Zd ZdZd ZeZy)AccumulatingHTTPCookieProcessorztCookie processor that adds new cookies (instead of replacing the existing
    ones as HTTPCookieProcessor does)
    c                    d}t        |j                         |j                  i |j                  |j                        }| j
                  j                  |       |j                  |      }|r[|j                  |      r8|j                  |      }dj                  ||g      }|j                  ||       |S |j                  ||       |S )zProcesses cookies for a HTTP request.
        @param request: request to process
        @type request: urllib2.Request
        @return: request
        @rtype: urllib2.Request
        Cookiez; )Request_get_full_urldataorigin_req_hostunverifiable	cookiejaradd_cookie_header
get_header
has_headerjoinadd_unredirected_header)selfrequestCOOKIE_HEADER_NAMEtmp_requestnew_cookiesold_cookiesmerged_cookiess          g/var/www/html/BankruptcyAI-uat/bankruptcy-ai/venv/lib/python3.12/site-packages/ndg/httpsclient/utils.pyhttp_requestz,AccumulatingHTTPCookieProcessor.http_request3   s     &w335w||R&-&=&=&-&:&:< 	((5!,,-?@!!"45%001CD!%K+E!F//0B0>@
  //0BKP    N)__name__
__module____qualname____doc__r&   https_request r'   r%   r   r   /   s    6 !Mr'   r   c                       e Zd ZdZy)URLFetchErrorzError fetching content from URLN)r(   r)   r*   r+   r-   r'   r%   r/   r/   Q   s    )r'   r/   c                     t        | |||      \  }}}|r5|t        j                  k(  r"|j                         }|j	                          |S t        |      )zReturns 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   handlers)open_urlhttp_client_OKreadcloser/   )urlconfigr   r2   return_codereturn_messageresponsereturn_datas           r%   fetch_from_urlr>   U   sS     -5S&t>F-H)K{loo5mmoN++r'   c                    t        | |||      \  }}}|t        j                  k(  rM|j                         }|j	                          t        |d      }	|	j                  |       |	j	                          |||t        j                  k(  fS )a  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)
    r1   w)r3   r4   r5   r6   r7   openwrite)
r8   r9   output_filer   r2   r:   r;   r<   r=   outfiles
             r%   fetch_from_url_to_filerE   f   sw     -5S&t>F-H)Kloo%mmo{C(k"|(FFFr'   c                 l    t        | |||      \  }}}|r|t        j                  k(  r|S t        |      )a  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
    r1   )r3   r4   r5   r/   )r8   r9   r   r2   r:   r;   r<   s          r%   fetch_stream_from_urlrG      s=     -5S&t>F-H)K{loo5N++r'   c                 p   |j                   rdnd}|j                  r|j                  }nt        j                         }t	        |      }|sg }|j                  |       |j                   r6t        |      }t        |j                  |      }|j                  ||g       |j                  rSt        t                     }	|	j                  d| |j                  d   |j                  d          |j                  |	       t        | |j                        s0|j                  t!        i              t"        j                  d       nR|j$                  rF|j                  t!        |j$                               t"        j                  d|j$                  z         t'        |d|j                  i}
|j(                  }|i }t+        | ||      }d}d	}d}	 |
j-                  |      }|j.                  }|j0                  }t"        j3                  t4        j6                        r*t9        |      D ]  \  }}t"        j                  d
||        |||fS # t:        $ rs}|j0                  }d|j.                  z  }t"        j3                  t4        j6                        r+t"        j                  d|j0                  |j.                         Y d}~|d}~wt<        $ rg}d|j?                         z  }t"        j3                  t4        j6                        r'ddl }t"        j                  |jC                                Y d}~d}~ww xY w)a  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)
       r   )
debuglevelN)realmuriuserpasswdzNot using proxyzConfiguring proxies: %sssl_context z	%s  :  %sz	Error: %sz%s %s)"debugcookie
cookiejar_	CookieJarr   appendHTTPHandler_r   rO   extendhttp_basicauthHTTPBasicAuthHandler_ HTTPPasswordMgrWithDefaultRealm_add_password_should_use_proxyno_proxyProxyHandler_logproxiesr   headersr   rA   msgcodeisEnabledForloggingDEBUG	enumerate
HTTPError_	Exception__str__	traceback
format_exc)r8   r9   r   r2   rJ   cjcookie_handlerhttp_handlerhttps_handlerauth_handleropenerra   r   r:   r;   r<   indexrR   excrk   s                       r%   r3   r3      s    llJ }}]]!!# 5R8NOON#||#z:+F,>,>7AC}56,-M-OP!!#'-'<'<Q'?)/)>)>q)A 	" 	C 	% S&//2b)*		#$	fnn56		+fnn<=8D1C1CDFnnGsD'*G KNH.;;w'!mmGMM*!*2 6v		+uf56 22  2hh$sww.GMM*IIgsxx1 .$s{{}4GMM*IIi**,-	.s'   A6I 	L5A)KL5AL00L5c                    |!t         j                  j                  dd      }n|}t        j                  t        |             }|j                  d      D cg c]  }|j                          c}D ]  }|j                  |k(  s y yc c}w )zDetermines 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
    r]   rP   ,FT)	osenvironget	urlparse_urlparse_url_as_stringsplitstriphostname)r8   r]   no_proxy_effectiveurlObjhnps         r%   r\   r\      s     ZZ^^J;%s 34F"4":":3"?@Qqwwy@ ??b  	 As   Bc                     t        | t              r| j                         S t        | t              r| S t	        dt        dt              )zReturns 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
    zExpected type z or )
isinstancer   r   str	TypeError)r8   s    r%   r|   r|     sC     #x !!	C	
h( ) 	)r'   c                       e Zd ZdZ	 	 ddZy)ConfigurationzConnection configuration.
    Nc                 f    || _         || _        || _        || _        || _        || _        || _        y)a  
        @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)rO   rQ   r`   r]   rR   rX   ra   )r   rO   rQ   r`   r]   rR   rX   ra   s           r%   __init__zConfiguration.__init__  s7    $ '
 ,r'   )FNNNNN)r(   r)   r*   r+   r   r-   r'   r%   r   r     s    HL;?r'   r   c            	      f   t        d      } | j                  ddddt        j                  j	                  d      d	       | j                  d
ddddd	       | j                  dddddd	       | j                  dddddd       | j                  dddddd	       | j                  dd d!ddd"	       | j                  d#d$dd%dd&       | j                  d'd(d)d*dd+	       | j                  d,d-d.d/d01       | j                         \  }}t        |      d2k7  r| j                  d3       |d4   }|j                  r1t        j                         j                  t        j                         |j                  r6t        j                  j                  |j                        r|j                  }nd}|j                  r6t        j                  j                  |j                        r|j                  }nd}|j                   r6t        j                  j                  |j                         r|j                   }nd}|j"                   }|j$                  r_t        j                  j                  |j$                        r6t'        |j$                        }|j)                         }	|j+                          nd}	|j,                  r|j,                  j/                  d5d2      }
nd}
i }|j0                  rG|j0                  D ]8  }|j/                  d5d2      \  }}|j3                         ||j5                         <   : t7        j8                  ||d|||      }t;        ||j                  |
|6      }|j<                  r*t?        |||j<                  |	      dd7 \  }}tA        ||      tC        ||      }	tE        |	       y)8zHUtility to fetch data using HTTP or HTTPS GET from a specified URL.
    z%prog [options] url)usagez-cz--certificate	cert_fileFILEz~/credentials.pemz4Certificate file - defaults to $HOME/credentials.pem)destmetavardefaulthelpz-kz--private-keykey_fileNz3Private key file - defaults to the certificate filez-tz--ca-certificate-dirca_dirPATHz%Trusted CA certificate file directoryz-dz--debug
store_truerQ   FzPrint debug information.)actionr   r   r   z-pz--post-data-file	data_filezPOST data filez-fz--fetchrC   zOutput filez-nz--no-verify-peerno_verify_peerz&Skip verification of peer certificate.z-az--basicauth	basicauthzUSER:PASSWDzHTTP authentication credentialsz--headerrU   ra   zHEADER: VALUEzAdd HTTP header to request)r   r   r   r   rI   zIncorrect number of argumentsr   :)rX   ra   r   )#r   
add_optionrw   path
expanduser
parse_argslenerrorrQ   re   	getLoggersetLevelrf   r   existsr   r   r   r   rA   r6   r7   r   r}   ra   lstripr~   r   make_ssl_contextr   rC   rE   
SystemExitr>   print)parseroptionsargsr8   r   r   r   verify_peerr   r   rX   ra   r   keyvalrO   r9   r:   r;   s                      r%   mainr   4  s     56F
dO+v gg001DEQ  S dO*f"P  R d2$"B  D dIl#5  7 d.[$d+  - dIM6"  8
d.|+UC  E dM+"<  > j	-7  9 '')OWd
4yA~45
q'C}}$$W]]3BGGNN7+;+;<##RWW^^G,=,=>%%		~~"''..8,,,KRWW^^G,=,=>**+	~~ **00a8G 	0AwwsAHC#&::<GCIIK 	0 #33H4=484:4?479K ;"==*8#*,F &<696<6=6I6I6:	'< =?Q	'@#^
 n55c6*dr'   __main__)NN)N)@r+   
__author____date____copyright____license____contact____revision__re   optparser   rw   sysversion_infohttp.cookiejarr   rS   http.clientclientr4   urllib.requestr   r   r   rV   r   HTTPCookieProcessor_r   rY   r	   rZ   r
   r^   urllib.errorr   rh   urllib.parseparserz   	cookielibhttpliburllib2r{   $ndg.httpsclient.urllib2_build_openerr   ndg.httpsclient.httpsr   ndg.httpsclientr   r   r(   r_   r   ri   r/   r>   rE   rG   r3   r\   r|   objectr   r   basicConfigr-   r'   r%   <module>r      s   
D=)  ! 	 
A'&2:JLM<4$""+3CEM5/  = 5 ,g!!&: !D*I *,"G2,*\3~$)"F <bJ ZGF r'   