Package rhn :: Module connections
[hide private]
[frames] | no frames]

Source Code for Module rhn.connections

  1  # 
  2  # Connection objects 
  3  # 
  4  # Copyright (c) 2002--2020 Red Hat, Inc. 
  5  # 
  6  # Author: Mihai Ibanescu <misa@redhat.com> 
  7   
  8   
  9   
 10  import base64 
 11  import encodings.idna 
 12  import socket 
 13  from platform import python_version 
 14  from rhn import SSL 
 15  from rhn import nonblocking 
 16  from rhn import i18n 
 17   
 18  try: # python2 
 19      import httplib 
 20      # Import into the local namespace some httplib-related names 
 21      from httplib import _CS_REQ_SENT, _CS_IDLE, ResponseNotReady 
 22   
 23      import xmlrpclib 
 24  except ImportError: # python3 
 25      import http.client as httplib 
 26      # Import into the local namespace some httplib-related names 
 27      from http.client import _CS_REQ_SENT, _CS_IDLE, ResponseNotReady 
 28   
 29      import xmlrpc.client as xmlrpclib 
 30   
31 -class HTTPResponse(httplib.HTTPResponse):
32 - def set_callback(self, rs, ws, ex, user_data, callback):
33 if not isinstance(self.fp, nonblocking.NonBlockingFile): 34 self.fp = nonblocking.NonBlockingFile(self.fp) 35 self.fp.set_callback(rs, ws, ex, user_data, callback)
36
37 -class HTTPConnection(httplib.HTTPConnection):
38 response_class = HTTPResponse 39
40 - def __init__(self, host, port=None, timeout=SSL.DEFAULT_TIMEOUT):
41 if python_version() >= '2.6.1': 42 httplib.HTTPConnection.__init__(self, host, port, timeout=timeout) 43 else: 44 httplib.HTTPConnection.__init__(self, host, port) 45 self._cb_rs = [] 46 self._cb_ws = [] 47 self._cb_ex = [] 48 self._cb_user_data = None 49 self._cb_callback = None 50 self._user_agent = "rhn.connections $Revision$ (python)" 51 self.timeout = timeout
52
53 - def set_callback(self, rs, ws, ex, user_data, callback):
54 # XXX check the params 55 self._cb_rs = rs 56 self._cb_ws = ws 57 self._cb_ex = ex 58 self._cb_user_data = user_data 59 self._cb_callback = callback
60
61 - def set_user_agent(self, user_agent):
62 self._user_agent = user_agent
63 64 # XXX Had to copy the function from httplib.py, because the nonblocking 65 # framework had to be initialized
66 - def getresponse(self):
67 "Get the response from the server." 68 69 # check if a prior response has been completed 70 if self.__response and self.__response.isclosed(): 71 self.__response = None 72 73 # 74 # if a prior response exists, then it must be completed (otherwise, we 75 # cannot read this response's header to determine the connection-close 76 # behavior) 77 # 78 # note: if a prior response existed, but was connection-close, then the 79 # socket and response were made independent of this HTTPConnection 80 # object since a new request requires that we open a whole new 81 # connection 82 # 83 # this means the prior response had one of two states: 84 # 1) will_close: this connection was reset and the prior socket and 85 # response operate independently 86 # 2) persistent: the response was retained and we await its 87 # isclosed() status to become true. 88 # 89 if self.__state != _CS_REQ_SENT or self.__response: 90 raise ResponseNotReady() 91 92 if self.debuglevel > 0: 93 response = self.response_class(self.sock, self.debuglevel) 94 else: 95 response = self.response_class(self.sock) 96 97 # The only modification compared to the stock HTTPConnection 98 if self._cb_callback: 99 response.set_callback(self._cb_rs, self._cb_ws, self._cb_ex, 100 self._cb_user_data, self._cb_callback) 101 102 response.begin() 103 assert response.will_close != httplib._UNKNOWN 104 self.__state = _CS_IDLE 105 106 if response.will_close: 107 # this effectively passes the connection to the response 108 self.close() 109 else: 110 # remember this, so we can tell when it is complete 111 self.__response = response 112 113 return response
114
115 - def connect(self):
116 httplib.HTTPConnection.connect(self) 117 self.sock.settimeout(self.timeout)
118 119
120 -class HTTPProxyConnection(HTTPConnection):
121 - def __init__(self, proxy, host, port=None, username=None, password=None, 122 timeout=SSL.DEFAULT_TIMEOUT):
123 # The connection goes through the proxy 124 HTTPConnection.__init__(self, proxy, timeout=timeout) 125 # save the proxy values 126 self.__proxy, self.__proxy_port = self.host, self.port 127 # self.host and self.port will point to the real host 128 self._set_hostport(host, port) 129 # save the host and port 130 self._host, self._port = self.host, self.port 131 # Authenticated proxies support 132 self.__username = username 133 self.__password = password
134
135 - def connect(self):
136 # We are actually connecting to the proxy 137 self._set_hostport(self.__proxy, self.__proxy_port) 138 HTTPConnection.connect(self) 139 # Restore the real host and port 140 self._set_hostport(self._host, self._port)
141
142 - def putrequest(self, method, url, skip_host=0):
143 # The URL has to include the real host 144 hostname = self._host 145 if self._port != self.default_port: 146 hostname = hostname + ':' + str(self._port) 147 newurl = "http://%s%s" % (hostname, url) 148 # Piggyback on the parent class 149 HTTPConnection.putrequest(self, method, newurl, skip_host=skip_host) 150 # Add proxy-specific headers 151 self._add_proxy_headers()
152
153 - def _add_proxy_headers(self):
154 if not self.__username: 155 return 156 # Authenticated proxy 157 userpass = "%s:%s" % (self.__username, self.__password) 158 enc_userpass = base64.encodestring(i18n.bstr(userpass)).replace(i18n.bstr("\n"), i18n.bstr("")) 159 self.putheader("Proxy-Authorization", "Basic %s" % i18n.sstr(enc_userpass))
160
161 - def _set_hostport(self, host, port):
162 (self.host, self.port) = self._get_hostport(host, port)
163
164 -class HTTPSConnection(HTTPConnection):
165 response_class = HTTPResponse 166 default_port = httplib.HTTPSConnection.default_port 167
168 - def __init__(self, host, port=None, trusted_certs=None, 169 timeout=SSL.DEFAULT_TIMEOUT):
170 HTTPConnection.__init__(self, host, port, timeout=timeout) 171 trusted_certs = trusted_certs or [] 172 self.trusted_certs = trusted_certs
173
174 - def connect(self):
175 "Connect to a host on a given (SSL) port" 176 results = socket.getaddrinfo(self.host, self.port, 177 socket.AF_UNSPEC, socket.SOCK_STREAM) 178 179 for r in results: 180 af, socktype, proto, canonname, sa = r 181 try: 182 sock = socket.socket(af, socktype, proto) 183 except socket.error: 184 sock = None 185 continue 186 187 try: 188 sock.connect((self.host, self.port)) 189 sock.settimeout(self.timeout) 190 except socket.error: 191 sock.close() 192 sock = None 193 continue 194 break 195 196 if sock is None: 197 raise socket.error("Unable to connect to the host and port specified") 198 199 self.sock = SSL.SSLSocket(sock, self.trusted_certs) 200 self.sock.init_ssl(self.host)
201
202 -class HTTPSProxyResponse(HTTPResponse):
203 - def begin(self):
204 HTTPResponse.begin(self) 205 self.will_close = 0
206
207 -class HTTPSProxyConnection(HTTPProxyConnection):
208 default_port = HTTPSConnection.default_port 209
210 - def __init__(self, proxy, host, port=None, username=None, password=None, 211 trusted_certs=None, timeout=SSL.DEFAULT_TIMEOUT):
212 HTTPProxyConnection.__init__(self, proxy, host, port, username, 213 password, timeout=timeout) 214 trusted_certs = trusted_certs or [] 215 self.trusted_certs = trusted_certs
216
217 - def connect(self):
218 # Set the connection with the proxy 219 HTTPProxyConnection.connect(self) 220 # Use the stock HTTPConnection putrequest 221 host = "%s:%s" % (self._host, self._port) 222 HTTPConnection.putrequest(self, "CONNECT", host) 223 # Add proxy-specific stuff 224 self._add_proxy_headers() 225 # And send the request 226 HTTPConnection.endheaders(self) 227 # Save the response class 228 response_class = self.response_class 229 # And replace the response class with our own one, which does not 230 # close the connection after 231 self.response_class = HTTPSProxyResponse 232 response = HTTPConnection.getresponse(self) 233 # Restore the response class 234 self.response_class = response_class 235 # Close the response object manually 236 response.close() 237 if response.status != 200: 238 # Close the connection manually 239 self.close() 240 raise xmlrpclib.ProtocolError(host, 241 response.status, response.reason, response.msg) 242 self.sock = SSL.SSLSocket(self.sock, self.trusted_certs) 243 self.sock.init_ssl()
244
245 - def putrequest(self, method, url, skip_host=0):
246 return HTTPConnection.putrequest(self, method, url, skip_host=skip_host)
247
248 - def _add_proxy_headers(self):
249 HTTPProxyConnection._add_proxy_headers(self) 250 # Add a User-Agent header 251 self.putheader("User-Agent", self._user_agent)
252
253 -def idn_puny_to_unicode(hostname):
254 """ Convert Internationalized domain name from Punycode (RFC3492) to Unicode """ 255 if hostname is None: 256 return None 257 else: 258 hostname = i18n.bstr(hostname) 259 return hostname.decode('idna')
260
261 -def idn_ascii_to_puny(hostname):
262 """ Convert domain name to Punycode (RFC3492). Hostname can be instance of string or Unicode """ 263 if hostname is None: 264 return None 265 else: 266 hostname = i18n.ustr(hostname) 267 return i18n.ustr(hostname.encode('idna'))
268