PageRenderTime 31ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/src/atom/http_core.py

https://code.google.com/p/gdata-python-client/
Python | 601 lines | 528 code | 20 blank | 53 comment | 7 complexity | 178c2ec31ca84fc8f7120136c74fb094 MD5 | raw file
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2009 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # This module is used for version 2 of the Google Data APIs.
  17. # TODO: add proxy handling.
  18. __author__ = 'j.s@google.com (Jeff Scudder)'
  19. import os
  20. import StringIO
  21. import urlparse
  22. import urllib
  23. import httplib
  24. ssl = None
  25. try:
  26. import ssl
  27. except ImportError:
  28. pass
  29. class Error(Exception):
  30. pass
  31. class UnknownSize(Error):
  32. pass
  33. class ProxyError(Error):
  34. pass
  35. MIME_BOUNDARY = 'END_OF_PART'
  36. def get_headers(http_response):
  37. """Retrieves all HTTP headers from an HTTP response from the server.
  38. This method is provided for backwards compatibility for Python2.2 and 2.3.
  39. The httplib.HTTPResponse object in 2.2 and 2.3 does not have a getheaders
  40. method so this function will use getheaders if available, but if not it
  41. will retrieve a few using getheader.
  42. """
  43. if hasattr(http_response, 'getheaders'):
  44. return http_response.getheaders()
  45. else:
  46. headers = []
  47. for header in (
  48. 'location', 'content-type', 'content-length', 'age', 'allow',
  49. 'cache-control', 'content-location', 'content-encoding', 'date',
  50. 'etag', 'expires', 'last-modified', 'pragma', 'server',
  51. 'set-cookie', 'transfer-encoding', 'vary', 'via', 'warning',
  52. 'www-authenticate', 'gdata-version'):
  53. value = http_response.getheader(header, None)
  54. if value is not None:
  55. headers.append((header, value))
  56. return headers
  57. class HttpRequest(object):
  58. """Contains all of the parameters for an HTTP 1.1 request.
  59. The HTTP headers are represented by a dictionary, and it is the
  60. responsibility of the user to ensure that duplicate field names are combined
  61. into one header value according to the rules in section 4.2 of RFC 2616.
  62. """
  63. method = None
  64. uri = None
  65. def __init__(self, uri=None, method=None, headers=None):
  66. """Construct an HTTP request.
  67. Args:
  68. uri: The full path or partial path as a Uri object or a string.
  69. method: The HTTP method for the request, examples include 'GET', 'POST',
  70. etc.
  71. headers: dict of strings The HTTP headers to include in the request.
  72. """
  73. self.headers = headers or {}
  74. self._body_parts = []
  75. if method is not None:
  76. self.method = method
  77. if isinstance(uri, (str, unicode)):
  78. uri = Uri.parse_uri(uri)
  79. self.uri = uri or Uri()
  80. def add_body_part(self, data, mime_type, size=None):
  81. """Adds data to the HTTP request body.
  82. If more than one part is added, this is assumed to be a mime-multipart
  83. request. This method is designed to create MIME 1.0 requests as specified
  84. in RFC 1341.
  85. Args:
  86. data: str or a file-like object containing a part of the request body.
  87. mime_type: str The MIME type describing the data
  88. size: int Required if the data is a file like object. If the data is a
  89. string, the size is calculated so this parameter is ignored.
  90. """
  91. if isinstance(data, str):
  92. size = len(data)
  93. if size is None:
  94. # TODO: support chunked transfer if some of the body is of unknown size.
  95. raise UnknownSize('Each part of the body must have a known size.')
  96. if 'Content-Length' in self.headers:
  97. content_length = int(self.headers['Content-Length'])
  98. else:
  99. content_length = 0
  100. # If this is the first part added to the body, then this is not a multipart
  101. # request.
  102. if len(self._body_parts) == 0:
  103. self.headers['Content-Type'] = mime_type
  104. content_length = size
  105. self._body_parts.append(data)
  106. elif len(self._body_parts) == 1:
  107. # This is the first member in a mime-multipart request, so change the
  108. # _body_parts list to indicate a multipart payload.
  109. self._body_parts.insert(0, 'Media multipart posting')
  110. boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,)
  111. content_length += len(boundary_string) + size
  112. self._body_parts.insert(1, boundary_string)
  113. content_length += len('Media multipart posting')
  114. # Put the content type of the first part of the body into the multipart
  115. # payload.
  116. original_type_string = 'Content-Type: %s\r\n\r\n' % (
  117. self.headers['Content-Type'],)
  118. self._body_parts.insert(2, original_type_string)
  119. content_length += len(original_type_string)
  120. boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,)
  121. self._body_parts.append(boundary_string)
  122. content_length += len(boundary_string)
  123. # Change the headers to indicate this is now a mime multipart request.
  124. self.headers['Content-Type'] = 'multipart/related; boundary="%s"' % (
  125. MIME_BOUNDARY,)
  126. self.headers['MIME-version'] = '1.0'
  127. # Include the mime type of this part.
  128. type_string = 'Content-Type: %s\r\n\r\n' % (mime_type)
  129. self._body_parts.append(type_string)
  130. content_length += len(type_string)
  131. self._body_parts.append(data)
  132. ending_boundary_string = '\r\n--%s--' % (MIME_BOUNDARY,)
  133. self._body_parts.append(ending_boundary_string)
  134. content_length += len(ending_boundary_string)
  135. else:
  136. # This is a mime multipart request.
  137. boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,)
  138. self._body_parts.insert(-1, boundary_string)
  139. content_length += len(boundary_string) + size
  140. # Include the mime type of this part.
  141. type_string = 'Content-Type: %s\r\n\r\n' % (mime_type)
  142. self._body_parts.insert(-1, type_string)
  143. content_length += len(type_string)
  144. self._body_parts.insert(-1, data)
  145. self.headers['Content-Length'] = str(content_length)
  146. # I could add an "append_to_body_part" method as well.
  147. AddBodyPart = add_body_part
  148. def add_form_inputs(self, form_data,
  149. mime_type='application/x-www-form-urlencoded'):
  150. """Form-encodes and adds data to the request body.
  151. Args:
  152. form_data: dict or sequnce or two member tuples which contains the
  153. form keys and values.
  154. mime_type: str The MIME type of the form data being sent. Defaults
  155. to 'application/x-www-form-urlencoded'.
  156. """
  157. body = urllib.urlencode(form_data)
  158. self.add_body_part(body, mime_type)
  159. AddFormInputs = add_form_inputs
  160. def _copy(self):
  161. """Creates a deep copy of this request."""
  162. copied_uri = Uri(self.uri.scheme, self.uri.host, self.uri.port,
  163. self.uri.path, self.uri.query.copy())
  164. new_request = HttpRequest(uri=copied_uri, method=self.method,
  165. headers=self.headers.copy())
  166. new_request._body_parts = self._body_parts[:]
  167. return new_request
  168. def _dump(self):
  169. """Converts to a printable string for debugging purposes.
  170. In order to preserve the request, it does not read from file-like objects
  171. in the body.
  172. """
  173. output = 'HTTP Request\n method: %s\n url: %s\n headers:\n' % (
  174. self.method, str(self.uri))
  175. for header, value in self.headers.iteritems():
  176. output += ' %s: %s\n' % (header, value)
  177. output += ' body sections:\n'
  178. i = 0
  179. for part in self._body_parts:
  180. if isinstance(part, (str, unicode)):
  181. output += ' %s: %s\n' % (i, part)
  182. else:
  183. output += ' %s: <file like object>\n' % i
  184. i += 1
  185. return output
  186. def _apply_defaults(http_request):
  187. if http_request.uri.scheme is None:
  188. if http_request.uri.port == 443:
  189. http_request.uri.scheme = 'https'
  190. else:
  191. http_request.uri.scheme = 'http'
  192. class Uri(object):
  193. """A URI as used in HTTP 1.1"""
  194. scheme = None
  195. host = None
  196. port = None
  197. path = None
  198. def __init__(self, scheme=None, host=None, port=None, path=None, query=None):
  199. """Constructor for a URI.
  200. Args:
  201. scheme: str This is usually 'http' or 'https'.
  202. host: str The host name or IP address of the desired server.
  203. post: int The server's port number.
  204. path: str The path of the resource following the host. This begins with
  205. a /, example: '/calendar/feeds/default/allcalendars/full'
  206. query: dict of strings The URL query parameters. The keys and values are
  207. both escaped so this dict should contain the unescaped values.
  208. For example {'my key': 'val', 'second': '!!!'} will become
  209. '?my+key=val&second=%21%21%21' which is appended to the path.
  210. """
  211. self.query = query or {}
  212. if scheme is not None:
  213. self.scheme = scheme
  214. if host is not None:
  215. self.host = host
  216. if port is not None:
  217. self.port = port
  218. if path:
  219. self.path = path
  220. def _get_query_string(self):
  221. param_pairs = []
  222. for key, value in self.query.iteritems():
  223. quoted_key = urllib.quote_plus(str(key))
  224. if value is None:
  225. param_pairs.append(quoted_key)
  226. else:
  227. quoted_value = urllib.quote_plus(str(value))
  228. param_pairs.append('%s=%s' % (quoted_key, quoted_value))
  229. return '&'.join(param_pairs)
  230. def _get_relative_path(self):
  231. """Returns the path with the query parameters escaped and appended."""
  232. param_string = self._get_query_string()
  233. if self.path is None:
  234. path = '/'
  235. else:
  236. path = self.path
  237. if param_string:
  238. return '?'.join([path, param_string])
  239. else:
  240. return path
  241. def _to_string(self):
  242. if self.scheme is None and self.port == 443:
  243. scheme = 'https'
  244. elif self.scheme is None:
  245. scheme = 'http'
  246. else:
  247. scheme = self.scheme
  248. if self.path is None:
  249. path = '/'
  250. else:
  251. path = self.path
  252. if self.port is None:
  253. return '%s://%s%s' % (scheme, self.host, self._get_relative_path())
  254. else:
  255. return '%s://%s:%s%s' % (scheme, self.host, str(self.port),
  256. self._get_relative_path())
  257. def __str__(self):
  258. return self._to_string()
  259. def modify_request(self, http_request=None):
  260. """Sets HTTP request components based on the URI."""
  261. if http_request is None:
  262. http_request = HttpRequest()
  263. if http_request.uri is None:
  264. http_request.uri = Uri()
  265. # Determine the correct scheme.
  266. if self.scheme:
  267. http_request.uri.scheme = self.scheme
  268. if self.port:
  269. http_request.uri.port = self.port
  270. if self.host:
  271. http_request.uri.host = self.host
  272. # Set the relative uri path
  273. if self.path:
  274. http_request.uri.path = self.path
  275. if self.query:
  276. http_request.uri.query = self.query.copy()
  277. return http_request
  278. ModifyRequest = modify_request
  279. def parse_uri(uri_string):
  280. """Creates a Uri object which corresponds to the URI string.
  281. This method can accept partial URIs, but it will leave missing
  282. members of the Uri unset.
  283. """
  284. parts = urlparse.urlparse(uri_string)
  285. uri = Uri()
  286. if parts[0]:
  287. uri.scheme = parts[0]
  288. if parts[1]:
  289. host_parts = parts[1].split(':')
  290. if host_parts[0]:
  291. uri.host = host_parts[0]
  292. if len(host_parts) > 1:
  293. uri.port = int(host_parts[1])
  294. if parts[2]:
  295. uri.path = parts[2]
  296. if parts[4]:
  297. param_pairs = parts[4].split('&')
  298. for pair in param_pairs:
  299. pair_parts = pair.split('=')
  300. if len(pair_parts) > 1:
  301. uri.query[urllib.unquote_plus(pair_parts[0])] = (
  302. urllib.unquote_plus(pair_parts[1]))
  303. elif len(pair_parts) == 1:
  304. uri.query[urllib.unquote_plus(pair_parts[0])] = None
  305. return uri
  306. parse_uri = staticmethod(parse_uri)
  307. ParseUri = parse_uri
  308. parse_uri = Uri.parse_uri
  309. ParseUri = Uri.parse_uri
  310. class HttpResponse(object):
  311. status = None
  312. reason = None
  313. _body = None
  314. def __init__(self, status=None, reason=None, headers=None, body=None):
  315. self._headers = headers or {}
  316. if status is not None:
  317. self.status = status
  318. if reason is not None:
  319. self.reason = reason
  320. if body is not None:
  321. if hasattr(body, 'read'):
  322. self._body = body
  323. else:
  324. self._body = StringIO.StringIO(body)
  325. def getheader(self, name, default=None):
  326. if name in self._headers:
  327. return self._headers[name]
  328. else:
  329. return default
  330. def getheaders(self):
  331. return self._headers
  332. def read(self, amt=None):
  333. if self._body is None:
  334. return None
  335. if not amt:
  336. return self._body.read()
  337. else:
  338. return self._body.read(amt)
  339. def _dump_response(http_response):
  340. """Converts to a string for printing debug messages.
  341. Does not read the body since that may consume the content.
  342. """
  343. output = 'HttpResponse\n status: %s\n reason: %s\n headers:' % (
  344. http_response.status, http_response.reason)
  345. headers = get_headers(http_response)
  346. if isinstance(headers, dict):
  347. for header, value in headers.iteritems():
  348. output += ' %s: %s\n' % (header, value)
  349. else:
  350. for pair in headers:
  351. output += ' %s: %s\n' % (pair[0], pair[1])
  352. return output
  353. class HttpClient(object):
  354. """Performs HTTP requests using httplib."""
  355. debug = None
  356. def request(self, http_request):
  357. return self._http_request(http_request.method, http_request.uri,
  358. http_request.headers, http_request._body_parts)
  359. Request = request
  360. def _get_connection(self, uri, headers=None):
  361. """Opens a socket connection to the server to set up an HTTP request.
  362. Args:
  363. uri: The full URL for the request as a Uri object.
  364. headers: A dict of string pairs containing the HTTP headers for the
  365. request.
  366. """
  367. connection = None
  368. if uri.scheme == 'https':
  369. if not uri.port:
  370. connection = httplib.HTTPSConnection(uri.host)
  371. else:
  372. connection = httplib.HTTPSConnection(uri.host, int(uri.port))
  373. else:
  374. if not uri.port:
  375. connection = httplib.HTTPConnection(uri.host)
  376. else:
  377. connection = httplib.HTTPConnection(uri.host, int(uri.port))
  378. return connection
  379. def _http_request(self, method, uri, headers=None, body_parts=None):
  380. """Makes an HTTP request using httplib.
  381. Args:
  382. method: str example: 'GET', 'POST', 'PUT', 'DELETE', etc.
  383. uri: str or atom.http_core.Uri
  384. headers: dict of strings mapping to strings which will be sent as HTTP
  385. headers in the request.
  386. body_parts: list of strings, objects with a read method, or objects
  387. which can be converted to strings using str. Each of these
  388. will be sent in order as the body of the HTTP request.
  389. """
  390. if isinstance(uri, (str, unicode)):
  391. uri = Uri.parse_uri(uri)
  392. connection = self._get_connection(uri, headers=headers)
  393. if self.debug:
  394. connection.debuglevel = 1
  395. if connection.host != uri.host:
  396. connection.putrequest(method, str(uri))
  397. else:
  398. connection.putrequest(method, uri._get_relative_path())
  399. # Overcome a bug in Python 2.4 and 2.5
  400. # httplib.HTTPConnection.putrequest adding
  401. # HTTP request header 'Host: www.google.com:443' instead of
  402. # 'Host: www.google.com', and thus resulting the error message
  403. # 'Token invalid - AuthSub token has wrong scope' in the HTTP response.
  404. if (uri.scheme == 'https' and int(uri.port or 443) == 443 and
  405. hasattr(connection, '_buffer') and
  406. isinstance(connection._buffer, list)):
  407. header_line = 'Host: %s:443' % uri.host
  408. replacement_header_line = 'Host: %s' % uri.host
  409. try:
  410. connection._buffer[connection._buffer.index(header_line)] = (
  411. replacement_header_line)
  412. except ValueError: # header_line missing from connection._buffer
  413. pass
  414. # Send the HTTP headers.
  415. for header_name, value in headers.iteritems():
  416. connection.putheader(header_name, value)
  417. connection.endheaders()
  418. # If there is data, send it in the request.
  419. if body_parts and filter(lambda x: x != '', body_parts):
  420. for part in body_parts:
  421. _send_data_part(part, connection)
  422. # Return the HTTP Response from the server.
  423. return connection.getresponse()
  424. def _send_data_part(data, connection):
  425. if isinstance(data, (str, unicode)):
  426. # I might want to just allow str, not unicode.
  427. connection.send(data)
  428. return
  429. # Check to see if data is a file-like object that has a read method.
  430. elif hasattr(data, 'read'):
  431. # Read the file and send it a chunk at a time.
  432. while 1:
  433. binarydata = data.read(100000)
  434. if binarydata == '': break
  435. connection.send(binarydata)
  436. return
  437. else:
  438. # The data object was not a file.
  439. # Try to convert to a string and send the data.
  440. connection.send(str(data))
  441. return
  442. class ProxiedHttpClient(HttpClient):
  443. def _get_connection(self, uri, headers=None):
  444. # Check to see if there are proxy settings required for this request.
  445. proxy = None
  446. if uri.scheme == 'https':
  447. proxy = os.environ.get('https_proxy')
  448. elif uri.scheme == 'http':
  449. proxy = os.environ.get('http_proxy')
  450. if not proxy:
  451. return HttpClient._get_connection(self, uri, headers=headers)
  452. # Now we have the URL of the appropriate proxy server.
  453. # Get a username and password for the proxy if required.
  454. proxy_auth = _get_proxy_auth()
  455. if uri.scheme == 'https':
  456. import socket
  457. if proxy_auth:
  458. proxy_auth = 'Proxy-authorization: %s' % proxy_auth
  459. # Construct the proxy connect command.
  460. port = uri.port
  461. if not port:
  462. port = 443
  463. proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (uri.host, port)
  464. # Set the user agent to send to the proxy
  465. user_agent = ''
  466. if headers and 'User-Agent' in headers:
  467. user_agent = 'User-Agent: %s\r\n' % (headers['User-Agent'])
  468. proxy_pieces = '%s%s%s\r\n' % (proxy_connect, proxy_auth, user_agent)
  469. # Find the proxy host and port.
  470. proxy_uri = Uri.parse_uri(proxy)
  471. if not proxy_uri.port:
  472. proxy_uri.port = '80'
  473. # Connect to the proxy server, very simple recv and error checking
  474. p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  475. p_sock.connect((proxy_uri.host, int(proxy_uri.port)))
  476. p_sock.sendall(proxy_pieces)
  477. response = ''
  478. # Wait for the full response.
  479. while response.find("\r\n\r\n") == -1:
  480. response += p_sock.recv(8192)
  481. p_status = response.split()[1]
  482. if p_status != str(200):
  483. raise ProxyError('Error status=%s' % str(p_status))
  484. # Trivial setup for ssl socket.
  485. sslobj = None
  486. if ssl is not None:
  487. sslobj = ssl.wrap_socket(p_sock, None, None)
  488. else:
  489. sock_ssl = socket.ssl(p_sock, None, Nonesock_)
  490. sslobj = httplib.FakeSocket(p_sock, sock_ssl)
  491. # Initalize httplib and replace with the proxy socket.
  492. connection = httplib.HTTPConnection(proxy_uri.host)
  493. connection.sock = sslobj
  494. return connection
  495. elif uri.scheme == 'http':
  496. proxy_uri = Uri.parse_uri(proxy)
  497. if not proxy_uri.port:
  498. proxy_uri.port = '80'
  499. if proxy_auth:
  500. headers['Proxy-Authorization'] = proxy_auth.strip()
  501. return httplib.HTTPConnection(proxy_uri.host, int(proxy_uri.port))
  502. return None
  503. def _get_proxy_auth():
  504. import base64
  505. proxy_username = os.environ.get('proxy-username')
  506. if not proxy_username:
  507. proxy_username = os.environ.get('proxy_username')
  508. proxy_password = os.environ.get('proxy-password')
  509. if not proxy_password:
  510. proxy_password = os.environ.get('proxy_password')
  511. if proxy_username:
  512. user_auth = base64.b64encode('%s:%s' % (proxy_username,
  513. proxy_password))
  514. return 'Basic %s\r\n' % (user_auth.strip())
  515. else:
  516. return ''