Debian Codegraph @

mechanize/_http.py

raw symbols SCIP
1 """HTTP related handlers.
2
3 Note that some other HTTP handlers live in more specific modules: _auth.py,
4 _gzip.py, etc.
5
6
7 Copyright 2002-2006 John J Lee <[email protected]>
8
9 This code is free software; you can redistribute it and/or modify it
10 under the terms of the BSD or ZPL 2.1 licenses (see the file
11 LICENSE included with the distribution).
12
13 """
14
15 from __future__ import absolute_import
16
17 import logging
18 import socket
19 import time
20 from io import BytesIO
21
22 from . import _rfc3986, _sockettimeout
23 from ._headersutil import is_html
24 from ._request import Request
25 from ._response import response_seek_wrapper
26 from ._urllib2_fork import BaseHandler, HTTPError
27 from ._equiv import HTTPEquivParser
28 from .polyglot import create_response_info, RobotFileParser, is_py2, as_unicode
29
30 debug = logging.getLogger("mechanize").debug
31 debug_robots = logging.getLogger("mechanize.robots").debug
32
33
34 def parse_head(fileobj):
35 """Return a list of key, value pairs."""
36 p = HTTPEquivParser(fileobj.read(4096))
37 return p()
38
39
40 class HTTPEquivProcessor(BaseHandler):
41 """Append META HTTP-EQUIV headers to regular HTTP headers."""
42
43 handler_order = 300 # before handlers that look at HTTP headers
44
45 def http_response(self, request, response):
46 if not hasattr(response, "seek"):
47 response = response_seek_wrapper(response)
48 http_message = response.info()
49 url = response.geturl()
50 ct_hdrs = http_message.getheaders("content-type")
51 if is_html(ct_hdrs, url, True):
52 try:
53 try:
54 html_headers = parse_head(response)
55 finally:
56 response.seek(0)
57 except Exception:
58 pass
59 else:
60 for hdr, val in html_headers:
61 if is_py2:
62 # add a header
63 http_message.dict[hdr.lower()] = val
64 text = hdr + b": " + val
65 for line in text.split(b"\n"):
66 http_message.headers.append(line + b"\n")
67 else:
68 hdr = hdr.decode('iso-8859-1')
69 http_message[hdr] = val.decode('iso-8859-1')
70 return response
71
72 https_response = http_response
73
74
75 class MechanizeRobotFileParser(RobotFileParser):
76
77 def __init__(self, url='', opener=None):
78 RobotFileParser.__init__(self, url)
79 self._opener = opener
80 self._timeout = _sockettimeout._GLOBAL_DEFAULT_TIMEOUT
81
82 def set_opener(self, opener=None):
83 from . import _opener
84 if opener is None:
85 opener = _opener.OpenerDirector()
86 self._opener = opener
87
88 def set_timeout(self, timeout):
89 self._timeout = timeout
90
91 def read(self):
92 """Reads the robots.txt URL and feeds it to the parser."""
93 if self._opener is None:
94 self.set_opener()
95 req = Request(self.url, unverifiable=True, visit=False,
96 timeout=self._timeout)
97 try:
98 f = self._opener.open(req)
99 except HTTPError as err:
100 f = err
101 except (IOError, socket.error, OSError) as exc:
102 debug_robots("ignoring error opening %r: %s" %
103 (self.url, exc))
104 return
105 lines = []
106 line = f.readline()
107 while line:
108 lines.append(line.strip())
109 line = f.readline()
110 status = f.code
111 if status == 401 or status == 403:
112 self.disallow_all = True
113 debug_robots("disallow all")
114 elif status >= 400:
115 self.allow_all = True
116 debug_robots("allow all")
117 elif status == 200 and lines:
118 debug_robots("parse lines")
119 if is_py2:
120 self.parse(lines)
121 else:
122 # As per: https://developers.google.com/search/docs/advanced/robots/robots_txt
123 # robots.txt must be utf-8 encoded and invalid encoding causes
124 # bytes to be ignored to be ignored
125 self.parse((as_unicode(x, errors='ignore') for x in lines))
126
127
128 class RobotExclusionError(HTTPError):
129
130 def __init__(self, request, *args):
131 HTTPError.__init__(self, *args)
132 self.request = request
133
134
135 class HTTPRobotRulesProcessor(BaseHandler):
136 # before redirections, after everything else
137 handler_order = 800
138 http_response_class = None
139
140 def __init__(self, rfp_class=MechanizeRobotFileParser):
141 self.rfp_class = rfp_class
142 self.rfp = None
143 self._host = None
144
145 def __copy__(self):
146 return self.__class__(self.rfp_class)
147
148 def http_request(self, request):
149 scheme = request.get_type()
150 if scheme not in ["http", "https"]:
151 # robots exclusion only applies to HTTP
152 return request
153
154 if request.get_selector() == "/robots.txt":
155 # /robots.txt is always OK to fetch
156 return request
157
158 host = request.get_host()
159
160 # robots.txt requests don't need to be allowed by robots.txt :-)
161 origin_req = getattr(request, "_origin_req", None)
162 if (origin_req is not None and
163 origin_req.get_selector() == "/robots.txt" and
164 origin_req.get_host() == host):
165 return request
166
167 if host != self._host:
168 self.rfp = self.rfp_class()
169 try:
170 self.rfp.set_opener(self.parent)
171 except AttributeError:
172 debug("%r instance does not support set_opener" %
173 self.rfp.__class__)
174 self.rfp.set_url(scheme + "://" + host + "/robots.txt")
175 self.rfp.set_timeout(request.timeout)
176 self.rfp.read()
177 self._host = host
178
179 ua = request.get_header("User-agent", "")
180 if self.rfp.can_fetch(ua, request.get_full_url()):
181 return request
182 else:
183 # XXX This should really have raised URLError. Too late now...
184 factory = self.http_response_class or create_response_info
185 msg = b"request disallowed by robots.txt"
186 raise RobotExclusionError(
187 request,
188 request.get_full_url(),
189 403, msg,
190 factory(BytesIO()), BytesIO(msg))
191
192 https_request = http_request
193
194
195 class HTTPRefererProcessor(BaseHandler):
196 """Add Referer header to requests.
197
198 This only makes sense if you use each RefererProcessor for a single
199 chain of requests only (so, for example, if you use a single
200 HTTPRefererProcessor to fetch a series of URLs extracted from a single
201 page, this will break).
202
203 There's a proper implementation of this in mechanize.Browser.
204
205 """
206
207 def __init__(self):
208 self.referer = None
209
210 def http_request(self, request):
211 if ((self.referer is not None) and
212 not request.has_header("Referer")):
213 request.add_unredirected_header("Referer", self.referer)
214 return request
215
216 def http_response(self, request, response):
217 self.referer = response.geturl()
218 return response
219
220 https_request = http_request
221 https_response = http_response
222
223
224 def clean_refresh_url(url):
225 # e.g. Firefox 1.5 does (something like) this
226 if ((url.startswith('"') and url.endswith('"')) or
227 (url.startswith("'") and url.endswith("'"))):
228 url = url[1:-1]
229 return _rfc3986.clean_url(url, 'utf-8') # XXX encoding
230
231
232 def parse_refresh_header(refresh):
233 """
234 >>> parse_refresh_header("1; url=http://example.com/")
235 (1.0, 'http://example.com/')
236 >>> parse_refresh_header("1; url='http://example.com/'")
237 (1.0, 'http://example.com/')
238 >>> parse_refresh_header("1")
239 (1.0, None)
240 >>> parse_refresh_header("blah") # doctest: +IGNORE_EXCEPTION_DETAIL
241 Traceback (most recent call last):
242 ValueError: invalid literal for float(): blah
243
244 """
245
246 ii = refresh.find(";")
247 if ii != -1:
248 pause, newurl_spec = float(refresh[:ii]), refresh[ii + 1:]
249 jj = newurl_spec.find("=")
250 key = None
251 if jj != -1:
252 key, newurl = newurl_spec[:jj], newurl_spec[jj + 1:]
253 newurl = clean_refresh_url(newurl)
254 if key is None or key.strip().lower() != "url":
255 raise ValueError()
256 else:
257 pause, newurl = float(refresh), None
258 return pause, newurl
259
260
261 class HTTPRefreshProcessor(BaseHandler):
262 """Perform HTTP Refresh redirections.
263
264 Note that if a non-200 HTTP code has occurred (for example, a 30x
265 redirect), this processor will do nothing.
266
267 By default, only zero-time Refresh headers are redirected. Use the
268 max_time attribute / constructor argument to allow Refresh with longer
269 pauses. Use the honor_time attribute / constructor argument to control
270 whether the requested pause is honoured (with a time.sleep()) or
271 skipped in favour of immediate redirection.
272
273 Public attributes:
274
275 max_time: see above
276 honor_time: see above
277
278 """
279 handler_order = 1000
280
281 def __init__(self, max_time=0, honor_time=True):
282 self.max_time = max_time
283 self.honor_time = honor_time
284 self._sleep = time.sleep
285
286 def __copy__(self):
287 return self.__class__(self.max_time, self.honor_time)
288
289 def http_response(self, request, response):
290 code, msg, hdrs = response.code, response.msg, response.info()
291
292 if code == 200 and 'refresh' in hdrs:
293 refresh = hdrs.getheaders("refresh")[0]
294 try:
295 pause, newurl = parse_refresh_header(refresh)
296 except ValueError:
297 debug("bad Refresh header: %r" % refresh)
298 return response
299
300 if newurl is None:
301 newurl = response.geturl()
302 if (self.max_time is None) or (pause <= self.max_time):
303 if pause > 1E-3 and self.honor_time:
304 self._sleep(pause)
305 hdrs["location"] = newurl
306 # hardcoded http is NOT a bug
307 response = self.parent.error(
308 "http", request, response,
309 "refresh", msg, hdrs)
310 else:
311 debug("Refresh header ignored: %r" % refresh)
312
313 return response
314
315 https_response = http_response