ArcherSysOS 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. checksums.yaml +7 -0
  2. data/-interactive +0 -0
  3. data/.302.html.swp +0 -0
  4. data/.AerodiaServer.rb.swp +0 -0
  5. data/.README.md.swp +0 -0
  6. data/.archersys_os_peace.py.swp +0 -0
  7. data/.authorize.php.swp +0 -0
  8. data/.buildinfo +4 -0
  9. data/.git.cmd.swp +0 -0
  10. data/.gitconfig +1 -0
  11. data/.gitignore +9 -0
  12. data/.htaccess +12 -0
  13. data/.index.php.swl +0 -0
  14. data/.index.php.swm +0 -0
  15. data/.index.php.swn +0 -0
  16. data/.index.php.swo +0 -0
  17. data/.index.php.swp +0 -0
  18. data/.irb.cmd.swp +0 -0
  19. data/.irb_history +436 -0
  20. data/.irbrc +24 -0
  21. data/.irbrc~ +24 -0
  22. data/.livesearch.php.swp +0 -0
  23. data/.login.php.swl +0 -0
  24. data/.login.php.swm +0 -0
  25. data/.login.php.swn +0 -0
  26. data/.login.php.swo +0 -0
  27. data/.login.php.swp +0 -0
  28. data/.logout.php.swp +0 -0
  29. data/.npmrc +96 -0
  30. data/.os-desktop.php.swp +0 -0
  31. data/.pythonrc.py +11 -0
  32. data/.railsrc +1 -0
  33. data/.travis.yml +3 -0
  34. data/.vimstarter.bat.swp +0 -0
  35. data/302.html +8 -0
  36. data/401.html +43 -0
  37. data/403.html +9 -0
  38. data/404.html +43 -0
  39. data/7imperialisminjapan2.ppt +0 -0
  40. data/8_imperialism_by_the_united_states2.ppt +0 -0
  41. data/AbstractArrbyKlass.rb +16 -0
  42. data/AbstractImplementation.rb +10 -0
  43. data/Aerodia2.scn +0 -0
  44. data/AerodiaServer.rb +130 -0
  45. data/AerodiaServer.rb~ +129 -0
  46. data/AerodiaServer.txt +53 -0
  47. data/ArcherCGI.txt +8 -0
  48. data/ArcherDBM.rb +30 -0
  49. data/ArcherSysOS.gemspec +33 -0
  50. data/ArcherSysOS.rb +13 -0
  51. data/ArcherSysOS.rb.txt +13 -0
  52. data/ArcherSysOSDate.rb +10 -0
  53. data/ArcherSysOSOptionsParser.rb +108 -0
  54. data/ArcherSysOSOptionsParser.rb~ +108 -0
  55. data/ArcherVMCashewDelegator.rb +17 -0
  56. data/ArcherVMCashewLogger.rb +55 -0
  57. data/ArcherVMCashewLogger.rb~ +55 -0
  58. data/ArcherVMCashewTimeServer.rb +23 -0
  59. data/ArcherVMCashewTimeServer.rb~ +23 -0
  60. data/ArcherVMException.rb +13 -0
  61. data/CHANGELOG.md +4 -0
  62. data/CONTRIBUTING.md +8 -0
  63. data/CodeIgniter_2.2.0.zip +0 -0
  64. data/ConfigTest.php +11 -0
  65. data/F16MUDCockpitServlet.rb +14 -0
  66. data/F16MUDTape.rb +7 -0
  67. data/F16Shell.rb +42 -0
  68. data/Gemfile +4 -0
  69. data/LICENSE +19 -0
  70. data/Listing.rb +31 -0
  71. data/Middleware.rb +12 -0
  72. data/Middleware.txt +12 -0
  73. data/Movie.rb +8 -0
  74. data/MovieLibrary.rb +10 -0
  75. data/MySQLDumper1.24.4.zip +0 -0
  76. data/NotakerPro.aia +0 -0
  77. data/Num.rb +17 -0
  78. data/OSStartScreen.py +31 -0
  79. data/Product.rb +26 -0
  80. data/QAERODIACORP.sav +0 -0
  81. data/Queue.rb +16 -0
  82. data/Queue.rb~ +15 -0
  83. data/README.md +39 -0
  84. data/README.md~ +46 -0
  85. data/Rakefile +1 -0
  86. data/StockTickerServlet.rb +19 -0
  87. data/StockTickerServlet.rb~ +19 -0
  88. data/Symfony_cookbook_2.5.pdf +35637 -39
  89. data/Taxgator.rb +9 -0
  90. data/Tetris +2 -0
  91. data/Ticker.rb +63 -0
  92. data/Ticker.rb~ +63 -0
  93. data/WeakHash.rb +10 -0
  94. data/WikiPage.rb +27 -0
  95. data/WikiPage.rb~ +27 -0
  96. data/ZlibEngine.rb +20 -0
  97. data/_.swm +0 -0
  98. data/_.swn +0 -0
  99. data/_.swo +0 -0
  100. data/_.swp +0 -0
  101. data/acoserver_acoserver (2).sql +15131 -0
  102. data/acoserver_acoserver.sql +34707 -0
  103. data/acoserver_admin.sql +571 -0
  104. data/acoserver_games.sql +6344 -0
  105. data/acoserver_moodle.sql +16013 -0
  106. data/activate_docs_gen.bat +1 -0
  107. data/activate_docs_gen.txt +1 -0
  108. data/ager.py +6 -0
  109. data/alarmpy.py +6 -0
  110. data/american_imperialism2.ppt +0 -0
  111. data/apple-touch-icon.png +0 -0
  112. data/apps.php +35 -0
  113. data/apps.php.txt +7 -0
  114. data/arbylog.rb +16 -0
  115. data/archergit.py +6 -0
  116. data/archergit.py.txt +6 -0
  117. data/archergit.txt +6 -0
  118. data/archerlua.lua +3 -0
  119. data/archersys-logo.png +0 -0
  120. data/archersys.gemspec +32 -0
  121. data/archersys_os_peace.py +7 -0
  122. data/archersys_os_peace.py~ +5 -0
  123. data/autoexec.bat +3 -0
  124. data/bootstrap-tour.css +65 -0
  125. data/bootstrap-tour.js +698 -0
  126. data/bootstrap-tour.min.css +19 -0
  127. data/bootstrap-tour.min.js +19 -0
  128. data/bootstrap.css +7098 -0
  129. data/bootstrap.js +2002 -0
  130. data/bucketwise-master.zip +0 -0
  131. data/cargo.bat +1 -0
  132. data/cargo.cmd +1 -0
  133. data/changelog.txt +769 -0
  134. data/client_secrets.json +4 -0
  135. data/cockpitguess.py +12 -0
  136. data/collaborant-0.1.0.gem +0 -0
  137. data/composer.json +40 -0
  138. data/composer.lock +1484 -0
  139. data/composer.phar +0 -0
  140. data/conchtack_id.dat +0 -0
  141. data/config.json +4 -0
  142. data/config.php +17 -0
  143. data/config.ru +5 -0
  144. data/config.yml +16 -0
  145. data/console.html +8 -0
  146. data/console.php +42 -0
  147. data/contact.db +0 -0
  148. data/contacts.db +0 -0
  149. data/contrib-update.cmd +6 -0
  150. data/contrib-update.cmd~ +6 -0
  151. data/crossdomain.xml +9 -0
  152. data/cse.xml +25 -0
  153. data/depression_dbq.pdf +0 -0
  154. data/desktop-w10.php +6 -0
  155. data/desktop.html +33 -0
  156. data/desktop.php +310 -0
  157. data/dialogue.txt +13 -0
  158. data/dict.rb +15 -0
  159. data/dictionary_of_words.db +0 -0
  160. data/doc-create.html +5 -0
  161. data/doc-create.php +12 -0
  162. data/dokuwiki-d9556fbc2c1c07a0baaf81c07d4165f6.tgz +0 -0
  163. data/drive-appfolder.php +19 -0
  164. data/drive.php +49 -0
  165. data/dropbox-login.php +13 -0
  166. data/drupal-7.34.zip +0 -0
  167. data/dtop.php +131 -0
  168. data/f18mud.rb +2 -0
  169. data/favicon.ico +0 -0
  170. data/favicon.png +0 -0
  171. data/footer.html +5 -0
  172. data/forum.php +5 -0
  173. data/game1.py +171 -0
  174. data/genindex.html +164 -0
  175. data/git.cmd~ +2 -0
  176. data/github-ci.rb +6 -0
  177. data/histogram.py +36 -0
  178. data/htdocs.gemspec~ +31 -0
  179. data/https___summerjobs.dc.gov_(S(ryzytlym5hqgi255zgb4ojjk))_parental_consent_form.pdf +0 -0
  180. data/ieconfig.xml +12 -0
  181. data/imperialism_dbq_questions2.doc +0 -0
  182. data/imperialism_graphic_organizer2.docx +0 -0
  183. data/index-desktop.php +42 -0
  184. data/index-desktop.php.txt +14 -0
  185. data/index.html +175 -0
  186. data/index.php +302 -0
  187. data/index.php~ +315 -0
  188. data/info.php +3 -0
  189. data/iostarter.py +88 -0
  190. data/irb.cmd +3 -0
  191. data/irb.cmd~ +2 -0
  192. data/jquery-mobile-theme-105213-0.zip +0 -0
  193. data/jquery-ui-1.11.1.custom.zip +0 -0
  194. data/laravel-master.zip +0 -0
  195. data/laravel.phar +0 -0
  196. data/latest_specs.4.8 +0 -0
  197. data/latest_specs.4.8.gz +0 -0
  198. data/login.php +266 -0
  199. data/login.php~ +265 -0
  200. data/logout.php +13 -0
  201. data/logout.php~ +13 -0
  202. data/lua.bat +1 -0
  203. data/main.php +22 -0
  204. data/manage.py +10 -0
  205. data/manifest.appcache +22 -0
  206. data/manifest.json +19 -0
  207. data/manifest.webapp +14 -0
  208. data/meter.js +19 -0
  209. data/meter.php +17 -0
  210. data/mime.types +0 -0
  211. data/moodle.sqk +12123 -0
  212. data/moodle.sql +12123 -0
  213. data/movielibrary.rhtml +16 -0
  214. data/mud_login.rb +38 -0
  215. data/news.py +18 -0
  216. data/node.exe +0 -0
  217. data/node_etw_provider.man +153 -0
  218. data/node_perfctr_provider.man +107 -0
  219. data/nodejs-portable.bat +194 -0
  220. data/nodevars.bat +24 -0
  221. data/notifications-gateway.php +5 -0
  222. data/now.bat +3 -0
  223. data/npm +14 -0
  224. data/npm-debug.log +40 -0
  225. data/npm.cmd +6 -0
  226. data/objects.inv +0 -0
  227. data/ocular.phar +0 -0
  228. data/opensearch.xml +12 -0
  229. data/os-desktop.php +211 -0
  230. data/os-mobile.php +127 -0
  231. data/package.json +5 -0
  232. data/parse-js-blank-1.3.0.zip +0 -0
  233. data/partii.appcache +2 -0
  234. data/pear.conf +2 -0
  235. data/phpldapadmin-1.2.3.zip +0 -0
  236. data/phpliteAdmin_v1-9-5.zip +0 -0
  237. data/phpunit.cmd +1 -0
  238. data/phpunit.dist.xml +8 -0
  239. data/phpunit.phar +77428 -2
  240. data/phpunit.xml +8 -0
  241. data/pik.bat +3 -0
  242. data/pik.ps1 +3 -0
  243. data/pik_runner.exe +0 -0
  244. data/pip-selfcheck.json +1 -0
  245. data/prerelease_specs.4.8 +0 -0
  246. data/prerelease_specs.4.8.gz +0 -0
  247. data/producktivshellwin +0 -0
  248. data/profile.php +7 -0
  249. data/prototype.php +7 -0
  250. data/pyconsole.cmd +3 -0
  251. data/pyconsole.py +8 -0
  252. data/pygubu-asos.py +19 -0
  253. data/pythonray.py +62 -0
  254. data/pythonray.py~ +62 -0
  255. data/pyvenv.cfg +3 -0
  256. data/radius.py +12 -0
  257. data/react-0.11.2.zip +0 -0
  258. data/readme.txt +8 -0
  259. data/register.php +130 -0
  260. data/register.php~ +126 -0
  261. data/rockpaperscissors.py +68 -0
  262. data/rockpaperscissors.py~ +28 -0
  263. data/run_f16.rb +2 -0
  264. data/rustc.cmd +1 -0
  265. data/scrollbar.css +6 -0
  266. data/scrollbar.css~ +4 -0
  267. data/scrutinizer.yml +5 -0
  268. data/search.html +177 -0
  269. data/searchindex.js +1 -0
  270. data/setup-owncloud.php +300 -0
  271. data/setup.py +9 -0
  272. data/sinatra-1.4.5.gem +0 -0
  273. data/smartsheet.html +1 -0
  274. data/span.html +5 -0
  275. data/specs.4.8 +0 -0
  276. data/specs.4.8.gz +0 -0
  277. data/starter-kit-1.8.1.zip +0 -0
  278. data/startscreen.php +11 -0
  279. data/startscreen.py +33 -0
  280. data/startup.png +0 -0
  281. data/svg-edit-2.6.zip +0 -0
  282. data/symfony.com_pdf_Symfony_book_2.5.pdf +0 -0
  283. data/telnet-client.py +18 -0
  284. data/tess.py +26 -0
  285. data/time.css +279 -0
  286. data/time.html +2 -0
  287. data/time.php +56 -0
  288. data/tinymce_spellchecker_php_2_0_6_1.zip +0 -0
  289. data/urllib2.py +1371 -0
  290. data/uru.bat +12 -0
  291. data/uru.bat.bak +12 -0
  292. data/uru.ps1 +11 -0
  293. data/uru.ps1.bak +11 -0
  294. data/uru_rt.exe +0 -0
  295. data/vimstarter.bat +3 -0
  296. metadata +338 -0
@@ -0,0 +1,1371 @@
1
+ """An extensible library for opening URLs using a variety of protocols
2
+
3
+ The simplest way to use this module is to call the urlopen function,
4
+ which accepts a string containing a URL or a Request object (described
5
+ below). It opens the URL and returns the results as file-like
6
+ object; the returned object has some extra methods described below.
7
+
8
+ The OpenerDirector manages a collection of Handler objects that do
9
+ all the actual work. Each Handler implements a particular protocol or
10
+ option. The OpenerDirector is a composite object that invokes the
11
+ Handlers needed to open the requested URL. For example, the
12
+ HTTPHandler performs HTTP GET and POST requests and deals with
13
+ non-error returns. The HTTPRedirectHandler automatically deals with
14
+ HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
15
+ deals with digest authentication.
16
+
17
+ urlopen(url, data=None) -- basic usage is the same as original
18
+ urllib. pass the url and optionally data to post to an HTTP URL, and
19
+ get a file-like object back. One difference is that you can also pass
20
+ a Request instance instead of URL. Raises a URLError (subclass of
21
+ IOError); for HTTP errors, raises an HTTPError, which can also be
22
+ treated as a valid response.
23
+
24
+ build_opener -- function that creates a new OpenerDirector instance.
25
+ will install the default handlers. accepts one or more Handlers as
26
+ arguments, either instances or Handler classes that it will
27
+ instantiate. if one of the argument is a subclass of the default
28
+ handler, the argument will be installed instead of the default.
29
+
30
+ install_opener -- installs a new opener as the default opener.
31
+
32
+ objects of interest:
33
+ OpenerDirector --
34
+
35
+ Request -- an object that encapsulates the state of a request. the
36
+ state can be a simple as the URL. it can also include extra HTTP
37
+ headers, e.g. a User-Agent.
38
+
39
+ BaseHandler --
40
+
41
+ exceptions:
42
+ URLError-- a subclass of IOError, individual protocols have their own
43
+ specific subclass
44
+
45
+ HTTPError-- also a valid HTTP response, so you can treat an HTTP error
46
+ as an exceptional event or valid response
47
+
48
+ internals:
49
+ BaseHandler and parent
50
+ _call_chain conventions
51
+
52
+ Example usage:
53
+
54
+ import urllib2
55
+
56
+ # set up authentication info
57
+ authinfo = urllib2.HTTPBasicAuthHandler()
58
+ authinfo.add_password(realm='PDQ Application',
59
+ uri='https://mahler:8092/site-updates.py',
60
+ user='klem',
61
+ passwd='geheim$parole')
62
+
63
+ proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
64
+
65
+ # build a new opener that adds authentication and caching FTP handlers
66
+ opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)
67
+
68
+ # install it
69
+ urllib2.install_opener(opener)
70
+
71
+ f = urllib2.urlopen('http://www.python.org/')
72
+
73
+
74
+ """
75
+
76
+ # XXX issues:
77
+ # If an authentication error handler that tries to perform
78
+ # authentication for some reason but fails, how should the error be
79
+ # signalled? The client needs to know the HTTP error code. But if
80
+ # the handler knows that the problem was, e.g., that it didn't know
81
+ # that hash algo that requested in the challenge, it would be good to
82
+ # pass that information along to the client, too.
83
+ # ftp errors aren't handled cleanly
84
+ # check digest against correct (i.e. non-apache) implementation
85
+
86
+ # Possible extensions:
87
+ # complex proxies XXX not sure what exactly was meant by this
88
+ # abstract factory for opener
89
+
90
+ import base64
91
+ import hashlib
92
+ import httplib
93
+ import mimetools
94
+ import os
95
+ import posixpath
96
+ import random
97
+ import re
98
+ import socket
99
+ import sys
100
+ import time
101
+ import urlparse
102
+ import bisect
103
+
104
+ try:
105
+ from cStringIO import StringIO
106
+ except ImportError:
107
+ from StringIO import StringIO
108
+
109
+ from urllib import (unwrap, unquote, splittype, splithost, quote,
110
+ addinfourl, splitport, splitgophertype, splitquery,
111
+ splitattr, ftpwrapper, noheaders, splituser, splitpasswd, splitvalue)
112
+
113
+ # support for FileHandler, proxies via environment variables
114
+ from urllib import localhost, url2pathname, getproxies
115
+
116
+ # used in User-Agent header sent
117
+ __version__ = sys.version[:3]
118
+
119
+ _opener = None
120
+ def urlopen(url, data=None):
121
+ global _opener
122
+ if _opener is None:
123
+ _opener = build_opener()
124
+ return _opener.open(url, data)
125
+
126
+ def install_opener(opener):
127
+ global _opener
128
+ _opener = opener
129
+
130
+ # do these error classes make sense?
131
+ # make sure all of the IOError stuff is overridden. we just want to be
132
+ # subtypes.
133
+
134
+ class URLError(IOError):
135
+ # URLError is a sub-type of IOError, but it doesn't share any of
136
+ # the implementation. need to override __init__ and __str__.
137
+ # It sets self.args for compatibility with other EnvironmentError
138
+ # subclasses, but args doesn't have the typical format with errno in
139
+ # slot 0 and strerror in slot 1. This may be better than nothing.
140
+ def __init__(self, reason):
141
+ self.args = reason,
142
+ self.reason = reason
143
+
144
+ def __str__(self):
145
+ return '<urlopen error %s>' % self.reason
146
+
147
+ class HTTPError(URLError, addinfourl):
148
+ """Raised when HTTP error occurs, but also acts like non-error return"""
149
+ __super_init = addinfourl.__init__
150
+
151
+ def __init__(self, url, code, msg, hdrs, fp):
152
+ self.code = code
153
+ self.msg = msg
154
+ self.hdrs = hdrs
155
+ self.fp = fp
156
+ self.filename = url
157
+ # The addinfourl classes depend on fp being a valid file
158
+ # object. In some cases, the HTTPError may not have a valid
159
+ # file object. If this happens, the simplest workaround is to
160
+ # not initialize the base classes.
161
+ if fp is not None:
162
+ self.__super_init(fp, hdrs, url)
163
+
164
+ def __str__(self):
165
+ return 'HTTP Error %s: %s' % (self.code, self.msg)
166
+
167
+ class GopherError(URLError):
168
+ pass
169
+
170
+ # copied from cookielib.py
171
+ _cut_port_re = re.compile(r":\d+$")
172
+ def request_host(request):
173
+ """Return request-host, as defined by RFC 2965.
174
+
175
+ Variation from RFC: returned value is lowercased, for convenient
176
+ comparison.
177
+
178
+ """
179
+ url = request.get_full_url()
180
+ host = urlparse.urlparse(url)[1]
181
+ if host == "":
182
+ host = request.get_header("Host", "")
183
+
184
+ # remove port, if present
185
+ host = _cut_port_re.sub("", host, 1)
186
+ return host.lower()
187
+
188
+ class Request:
189
+
190
+ def __init__(self, url, data=None, headers={},
191
+ origin_req_host=None, unverifiable=False):
192
+ # unwrap('<URL:type://host/path>') --> 'type://host/path'
193
+ self.__original = unwrap(url)
194
+ self.type = None
195
+ # self.__r_type is what's left after doing the splittype
196
+ self.host = None
197
+ self.port = None
198
+ self.data = data
199
+ self.headers = {}
200
+ for key, value in headers.items():
201
+ self.add_header(key, value)
202
+ self.unredirected_hdrs = {}
203
+ if origin_req_host is None:
204
+ origin_req_host = request_host(self)
205
+ self.origin_req_host = origin_req_host
206
+ self.unverifiable = unverifiable
207
+
208
+ def __getattr__(self, attr):
209
+ # XXX this is a fallback mechanism to guard against these
210
+ # methods getting called in a non-standard order. this may be
211
+ # too complicated and/or unnecessary.
212
+ # XXX should the __r_XXX attributes be public?
213
+ if attr[:12] == '_Request__r_':
214
+ name = attr[12:]
215
+ if hasattr(Request, 'get_' + name):
216
+ getattr(self, 'get_' + name)()
217
+ return getattr(self, attr)
218
+ raise AttributeError, attr
219
+
220
+ def get_method(self):
221
+ if self.has_data():
222
+ return "POST"
223
+ else:
224
+ return "GET"
225
+
226
+ # XXX these helper methods are lame
227
+
228
+ def add_data(self, data):
229
+ self.data = data
230
+
231
+ def has_data(self):
232
+ return self.data is not None
233
+
234
+ def get_data(self):
235
+ return self.data
236
+
237
+ def get_full_url(self):
238
+ return self.__original
239
+
240
+ def get_type(self):
241
+ if self.type is None:
242
+ self.type, self.__r_type = splittype(self.__original)
243
+ if self.type is None:
244
+ raise ValueError, "unknown url type: %s" % self.__original
245
+ return self.type
246
+
247
+ def get_host(self):
248
+ if self.host is None:
249
+ self.host, self.__r_host = splithost(self.__r_type)
250
+ if self.host:
251
+ self.host = unquote(self.host)
252
+ return self.host
253
+
254
+ def get_selector(self):
255
+ return self.__r_host
256
+
257
+ def set_proxy(self, host, type):
258
+ self.host, self.type = host, type
259
+ self.__r_host = self.__original
260
+
261
+ def get_origin_req_host(self):
262
+ return self.origin_req_host
263
+
264
+ def is_unverifiable(self):
265
+ return self.unverifiable
266
+
267
+ def add_header(self, key, val):
268
+ # useful for something like authentication
269
+ self.headers[key.capitalize()] = val
270
+
271
+ def add_unredirected_header(self, key, val):
272
+ # will not be added to a redirected request
273
+ self.unredirected_hdrs[key.capitalize()] = val
274
+
275
+ def has_header(self, header_name):
276
+ return (header_name in self.headers or
277
+ header_name in self.unredirected_hdrs)
278
+
279
+ def get_header(self, header_name, default=None):
280
+ return self.headers.get(
281
+ header_name,
282
+ self.unredirected_hdrs.get(header_name, default))
283
+
284
+ def header_items(self):
285
+ hdrs = self.unredirected_hdrs.copy()
286
+ hdrs.update(self.headers)
287
+ return hdrs.items()
288
+
289
+ class OpenerDirector:
290
+ def __init__(self):
291
+ client_version = "Python-urllib/%s" % __version__
292
+ self.addheaders = [('User-agent', client_version)]
293
+ # manage the individual handlers
294
+ self.handlers = []
295
+ self.handle_open = {}
296
+ self.handle_error = {}
297
+ self.process_response = {}
298
+ self.process_request = {}
299
+
300
+ def add_handler(self, handler):
301
+ if not hasattr(handler, "add_parent"):
302
+ raise TypeError("expected BaseHandler instance, got %r" %
303
+ type(handler))
304
+
305
+ added = False
306
+ for meth in dir(handler):
307
+ if meth in ["redirect_request", "do_open", "proxy_open"]:
308
+ # oops, coincidental match
309
+ continue
310
+
311
+ i = meth.find("_")
312
+ protocol = meth[:i]
313
+ condition = meth[i+1:]
314
+
315
+ if condition.startswith("error"):
316
+ j = condition.find("_") + i + 1
317
+ kind = meth[j+1:]
318
+ try:
319
+ kind = int(kind)
320
+ except ValueError:
321
+ pass
322
+ lookup = self.handle_error.get(protocol, {})
323
+ self.handle_error[protocol] = lookup
324
+ elif condition == "open":
325
+ kind = protocol
326
+ lookup = self.handle_open
327
+ elif condition == "response":
328
+ kind = protocol
329
+ lookup = self.process_response
330
+ elif condition == "request":
331
+ kind = protocol
332
+ lookup = self.process_request
333
+ else:
334
+ continue
335
+
336
+ handlers = lookup.setdefault(kind, [])
337
+ if handlers:
338
+ bisect.insort(handlers, handler)
339
+ else:
340
+ handlers.append(handler)
341
+ added = True
342
+
343
+ if added:
344
+ # XXX why does self.handlers need to be sorted?
345
+ bisect.insort(self.handlers, handler)
346
+ handler.add_parent(self)
347
+
348
+ def close(self):
349
+ # Only exists for backwards compatibility.
350
+ pass
351
+
352
+ def _call_chain(self, chain, kind, meth_name, *args):
353
+ # Handlers raise an exception if no one else should try to handle
354
+ # the request, or return None if they can't but another handler
355
+ # could. Otherwise, they return the response.
356
+ handlers = chain.get(kind, ())
357
+ for handler in handlers:
358
+ func = getattr(handler, meth_name)
359
+
360
+ result = func(*args)
361
+ if result is not None:
362
+ return result
363
+
364
+ def open(self, fullurl, data=None):
365
+ # accept a URL or a Request object
366
+ if isinstance(fullurl, basestring):
367
+ req = Request(fullurl, data)
368
+ else:
369
+ req = fullurl
370
+ if data is not None:
371
+ req.add_data(data)
372
+
373
+ protocol = req.get_type()
374
+
375
+ # pre-process request
376
+ meth_name = protocol+"_request"
377
+ for processor in self.process_request.get(protocol, []):
378
+ meth = getattr(processor, meth_name)
379
+ req = meth(req)
380
+
381
+ response = self._open(req, data)
382
+
383
+ # post-process response
384
+ meth_name = protocol+"_response"
385
+ for processor in self.process_response.get(protocol, []):
386
+ meth = getattr(processor, meth_name)
387
+ response = meth(req, response)
388
+
389
+ return response
390
+
391
+ def _open(self, req, data=None):
392
+ result = self._call_chain(self.handle_open, 'default',
393
+ 'default_open', req)
394
+ if result:
395
+ return result
396
+
397
+ protocol = req.get_type()
398
+ result = self._call_chain(self.handle_open, protocol, protocol +
399
+ '_open', req)
400
+ if result:
401
+ return result
402
+
403
+ return self._call_chain(self.handle_open, 'unknown',
404
+ 'unknown_open', req)
405
+
406
+ def error(self, proto, *args):
407
+ if proto in ('http', 'https'):
408
+ # XXX http[s] protocols are special-cased
409
+ dict = self.handle_error['http'] # https is not different than http
410
+ proto = args[2] # YUCK!
411
+ meth_name = 'http_error_%s' % proto
412
+ http_err = 1
413
+ orig_args = args
414
+ else:
415
+ dict = self.handle_error
416
+ meth_name = proto + '_error'
417
+ http_err = 0
418
+ args = (dict, proto, meth_name) + args
419
+ result = self._call_chain(*args)
420
+ if result:
421
+ return result
422
+
423
+ if http_err:
424
+ args = (dict, 'default', 'http_error_default') + orig_args
425
+ return self._call_chain(*args)
426
+
427
+ # XXX probably also want an abstract factory that knows when it makes
428
+ # sense to skip a superclass in favor of a subclass and when it might
429
+ # make sense to include both
430
+
431
+ def build_opener(*handlers):
432
+ """Create an opener object from a list of handlers.
433
+
434
+ The opener will use several default handlers, including support
435
+ for HTTP and FTP.
436
+
437
+ If any of the handlers passed as arguments are subclasses of the
438
+ default handlers, the default handlers will not be used.
439
+ """
440
+ import types
441
+ def isclass(obj):
442
+ return isinstance(obj, types.ClassType) or hasattr(obj, "__bases__")
443
+
444
+ opener = OpenerDirector()
445
+ default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
446
+ HTTPDefaultErrorHandler, HTTPRedirectHandler,
447
+ FTPHandler, FileHandler, HTTPErrorProcessor]
448
+ if hasattr(httplib, 'HTTPS'):
449
+ default_classes.append(HTTPSHandler)
450
+ skip = set()
451
+ for klass in default_classes:
452
+ for check in handlers:
453
+ if isclass(check):
454
+ if issubclass(check, klass):
455
+ skip.add(klass)
456
+ elif isinstance(check, klass):
457
+ skip.add(klass)
458
+ for klass in skip:
459
+ default_classes.remove(klass)
460
+
461
+ for klass in default_classes:
462
+ opener.add_handler(klass())
463
+
464
+ for h in handlers:
465
+ if isclass(h):
466
+ h = h()
467
+ opener.add_handler(h)
468
+ return opener
469
+
470
+ class BaseHandler:
471
+ handler_order = 500
472
+
473
+ def add_parent(self, parent):
474
+ self.parent = parent
475
+
476
+ def close(self):
477
+ # Only exists for backwards compatibility
478
+ pass
479
+
480
+ def __lt__(self, other):
481
+ if not hasattr(other, "handler_order"):
482
+ # Try to preserve the old behavior of having custom classes
483
+ # inserted after default ones (works only for custom user
484
+ # classes which are not aware of handler_order).
485
+ return True
486
+ return self.handler_order < other.handler_order
487
+
488
+
489
+ class HTTPErrorProcessor(BaseHandler):
490
+ """Process HTTP error responses."""
491
+ handler_order = 1000 # after all other processing
492
+
493
+ def http_response(self, request, response):
494
+ code, msg, hdrs = response.code, response.msg, response.info()
495
+
496
+ if code not in (200, 206):
497
+ response = self.parent.error(
498
+ 'http', request, response, code, msg, hdrs)
499
+
500
+ return response
501
+
502
+ https_response = http_response
503
+
504
+ class HTTPDefaultErrorHandler(BaseHandler):
505
+ def http_error_default(self, req, fp, code, msg, hdrs):
506
+ raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
507
+
508
+ class HTTPRedirectHandler(BaseHandler):
509
+ # maximum number of redirections to any single URL
510
+ # this is needed because of the state that cookies introduce
511
+ max_repeats = 4
512
+ # maximum total number of redirections (regardless of URL) before
513
+ # assuming we're in a loop
514
+ max_redirections = 10
515
+
516
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
517
+ """Return a Request or None in response to a redirect.
518
+
519
+ This is called by the http_error_30x methods when a
520
+ redirection response is received. If a redirection should
521
+ take place, return a new Request to allow http_error_30x to
522
+ perform the redirect. Otherwise, raise HTTPError if no-one
523
+ else should try to handle this url. Return None if you can't
524
+ but another Handler might.
525
+ """
526
+ m = req.get_method()
527
+ if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
528
+ or code in (301, 302, 303) and m == "POST"):
529
+ # Strictly (according to RFC 2616), 301 or 302 in response
530
+ # to a POST MUST NOT cause a redirection without confirmation
531
+ # from the user (of urllib2, in this case). In practice,
532
+ # essentially all clients do redirect in this case, so we
533
+ # do the same.
534
+ # be conciliant with URIs containing a space
535
+ newurl = newurl.replace(' ', '%20')
536
+ return Request(newurl,
537
+ headers=req.headers,
538
+ origin_req_host=req.get_origin_req_host(),
539
+ unverifiable=True)
540
+ else:
541
+ raise HTTPError(req.get_full_url(), code, msg, headers, fp)
542
+
543
+ # Implementation note: To avoid the server sending us into an
544
+ # infinite loop, the request object needs to track what URLs we
545
+ # have already seen. Do this by adding a handler-specific
546
+ # attribute to the Request object.
547
+ def http_error_302(self, req, fp, code, msg, headers):
548
+ # Some servers (incorrectly) return multiple Location headers
549
+ # (so probably same goes for URI). Use first header.
550
+ if 'location' in headers:
551
+ newurl = headers.getheaders('location')[0]
552
+ elif 'uri' in headers:
553
+ newurl = headers.getheaders('uri')[0]
554
+ else:
555
+ return
556
+ newurl = urlparse.urljoin(req.get_full_url(), newurl)
557
+
558
+ # For security reasons we do not allow redirects to protocols
559
+ # other than HTTP, HTTPS or FTP.
560
+ newurl_lower = newurl.lower()
561
+ if not (newurl_lower.startswith('http://') or
562
+ newurl_lower.startswith('https://') or
563
+ newurl_lower.startswith('ftp://')):
564
+ raise HTTPError(newurl, code,
565
+ msg + " - Redirection to url '%s' is not allowed" %
566
+ newurl,
567
+ headers, fp)
568
+
569
+ # XXX Probably want to forget about the state of the current
570
+ # request, although that might interact poorly with other
571
+ # handlers that also use handler-specific request attributes
572
+ new = self.redirect_request(req, fp, code, msg, headers, newurl)
573
+ if new is None:
574
+ return
575
+
576
+ # loop detection
577
+ # .redirect_dict has a key url if url was previously visited.
578
+ if hasattr(req, 'redirect_dict'):
579
+ visited = new.redirect_dict = req.redirect_dict
580
+ if (visited.get(newurl, 0) >= self.max_repeats or
581
+ len(visited) >= self.max_redirections):
582
+ raise HTTPError(req.get_full_url(), code,
583
+ self.inf_msg + msg, headers, fp)
584
+ else:
585
+ visited = new.redirect_dict = req.redirect_dict = {}
586
+ visited[newurl] = visited.get(newurl, 0) + 1
587
+
588
+ # Don't close the fp until we are sure that we won't use it
589
+ # with HTTPError.
590
+ fp.read()
591
+ fp.close()
592
+
593
+ return self.parent.open(new)
594
+
595
+ http_error_301 = http_error_303 = http_error_307 = http_error_302
596
+
597
+ inf_msg = "The HTTP server returned a redirect error that would " \
598
+ "lead to an infinite loop.\n" \
599
+ "The last 30x error message was:\n"
600
+
601
+
602
+ def _parse_proxy(proxy):
603
+ """Return (scheme, user, password, host/port) given a URL or an authority.
604
+
605
+ If a URL is supplied, it must have an authority (host:port) component.
606
+ According to RFC 3986, having an authority component means the URL must
607
+ have two slashes after the scheme:
608
+
609
+ >>> _parse_proxy('file:/ftp.example.com/')
610
+ Traceback (most recent call last):
611
+ ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
612
+
613
+ The first three items of the returned tuple may be None.
614
+
615
+ Examples of authority parsing:
616
+
617
+ >>> _parse_proxy('proxy.example.com')
618
+ (None, None, None, 'proxy.example.com')
619
+ >>> _parse_proxy('proxy.example.com:3128')
620
+ (None, None, None, 'proxy.example.com:3128')
621
+
622
+ The authority component may optionally include userinfo (assumed to be
623
+ username:password):
624
+
625
+ >>> _parse_proxy('joe:password@proxy.example.com')
626
+ (None, 'joe', 'password', 'proxy.example.com')
627
+ >>> _parse_proxy('joe:password@proxy.example.com:3128')
628
+ (None, 'joe', 'password', 'proxy.example.com:3128')
629
+
630
+ Same examples, but with URLs instead:
631
+
632
+ >>> _parse_proxy('http://proxy.example.com/')
633
+ ('http', None, None, 'proxy.example.com')
634
+ >>> _parse_proxy('http://proxy.example.com:3128/')
635
+ ('http', None, None, 'proxy.example.com:3128')
636
+ >>> _parse_proxy('http://joe:password@proxy.example.com/')
637
+ ('http', 'joe', 'password', 'proxy.example.com')
638
+ >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
639
+ ('http', 'joe', 'password', 'proxy.example.com:3128')
640
+
641
+ Everything after the authority is ignored:
642
+
643
+ >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
644
+ ('ftp', 'joe', 'password', 'proxy.example.com')
645
+
646
+ Test for no trailing '/' case:
647
+
648
+ >>> _parse_proxy('http://joe:password@proxy.example.com')
649
+ ('http', 'joe', 'password', 'proxy.example.com')
650
+
651
+ """
652
+ scheme, r_scheme = splittype(proxy)
653
+ if not r_scheme.startswith("/"):
654
+ # authority
655
+ scheme = None
656
+ authority = proxy
657
+ else:
658
+ # URL
659
+ if not r_scheme.startswith("//"):
660
+ raise ValueError("proxy URL with no authority: %r" % proxy)
661
+ # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
662
+ # and 3.3.), path is empty or starts with '/'
663
+ end = r_scheme.find("/", 2)
664
+ if end == -1:
665
+ end = None
666
+ authority = r_scheme[2:end]
667
+ userinfo, hostport = splituser(authority)
668
+ if userinfo is not None:
669
+ user, password = splitpasswd(userinfo)
670
+ else:
671
+ user = password = None
672
+ return scheme, user, password, hostport
673
+
674
+ class ProxyHandler(BaseHandler):
675
+ # Proxies must be in front
676
+ handler_order = 100
677
+
678
+ def __init__(self, proxies=None):
679
+ if proxies is None:
680
+ proxies = getproxies()
681
+ assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
682
+ self.proxies = proxies
683
+ for type, url in proxies.items():
684
+ setattr(self, '%s_open' % type,
685
+ lambda r, proxy=url, type=type, meth=self.proxy_open: \
686
+ meth(r, proxy, type))
687
+
688
+ def proxy_open(self, req, proxy, type):
689
+ orig_type = req.get_type()
690
+ proxy_type, user, password, hostport = _parse_proxy(proxy)
691
+ if proxy_type is None:
692
+ proxy_type = orig_type
693
+ if user and password:
694
+ user_pass = '%s:%s' % (unquote(user), unquote(password))
695
+ creds = base64.b64encode(user_pass).strip()
696
+ req.add_header('Proxy-authorization', 'Basic ' + creds)
697
+ hostport = unquote(hostport)
698
+ req.set_proxy(hostport, proxy_type)
699
+ if orig_type == proxy_type:
700
+ # let other handlers take care of it
701
+ return None
702
+ else:
703
+ # need to start over, because the other handlers don't
704
+ # grok the proxy's URL type
705
+ # e.g. if we have a constructor arg proxies like so:
706
+ # {'http': 'ftp://proxy.example.com'}, we may end up turning
707
+ # a request for http://acme.example.com/a into one for
708
+ # ftp://proxy.example.com/a
709
+ return self.parent.open(req)
710
+
711
+ class HTTPPasswordMgr:
712
+
713
+ def __init__(self):
714
+ self.passwd = {}
715
+
716
+ def add_password(self, realm, uri, user, passwd):
717
+ # uri could be a single URI or a sequence
718
+ if isinstance(uri, basestring):
719
+ uri = [uri]
720
+ if not realm in self.passwd:
721
+ self.passwd[realm] = {}
722
+ for default_port in True, False:
723
+ reduced_uri = tuple(
724
+ [self.reduce_uri(u, default_port) for u in uri])
725
+ self.passwd[realm][reduced_uri] = (user, passwd)
726
+
727
+ def find_user_password(self, realm, authuri):
728
+ domains = self.passwd.get(realm, {})
729
+ for default_port in True, False:
730
+ reduced_authuri = self.reduce_uri(authuri, default_port)
731
+ for uris, authinfo in domains.iteritems():
732
+ for uri in uris:
733
+ if self.is_suburi(uri, reduced_authuri):
734
+ return authinfo
735
+ return None, None
736
+
737
+ def reduce_uri(self, uri, default_port=True):
738
+ """Accept authority or URI and extract only the authority and path."""
739
+ # note HTTP URLs do not have a userinfo component
740
+ parts = urlparse.urlsplit(uri)
741
+ if parts[1]:
742
+ # URI
743
+ scheme = parts[0]
744
+ authority = parts[1]
745
+ path = parts[2] or '/'
746
+ else:
747
+ # host or host:port
748
+ scheme = None
749
+ authority = uri
750
+ path = '/'
751
+ host, port = splitport(authority)
752
+ if default_port and port is None and scheme is not None:
753
+ dport = {"http": 80,
754
+ "https": 443,
755
+ }.get(scheme)
756
+ if dport is not None:
757
+ authority = "%s:%d" % (host, dport)
758
+ return authority, path
759
+
760
+ def is_suburi(self, base, test):
761
+ """Check if test is below base in a URI tree
762
+
763
+ Both args must be URIs in reduced form.
764
+ """
765
+ if base == test:
766
+ return True
767
+ if base[0] != test[0]:
768
+ return False
769
+ common = posixpath.commonprefix((base[1], test[1]))
770
+ if len(common) == len(base[1]):
771
+ return True
772
+ return False
773
+
774
+
775
+ class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
776
+
777
+ def find_user_password(self, realm, authuri):
778
+ user, password = HTTPPasswordMgr.find_user_password(self, realm,
779
+ authuri)
780
+ if user is not None:
781
+ return user, password
782
+ return HTTPPasswordMgr.find_user_password(self, None, authuri)
783
+
784
+
785
+ class AbstractBasicAuthHandler:
786
+
787
+ # XXX this allows for multiple auth-schemes, but will stupidly pick
788
+ # the last one with a realm specified.
789
+
790
+ rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I)
791
+
792
+ # XXX could pre-emptively send auth info already accepted (RFC 2617,
793
+ # end of section 2, and section 1.2 immediately after "credentials"
794
+ # production).
795
+
796
+ def __init__(self, password_mgr=None):
797
+ if password_mgr is None:
798
+ password_mgr = HTTPPasswordMgr()
799
+ self.passwd = password_mgr
800
+ self.add_password = self.passwd.add_password
801
+
802
+ def http_error_auth_reqed(self, authreq, host, req, headers):
803
+ # host may be an authority (without userinfo) or a URL with an
804
+ # authority
805
+ # XXX could be multiple headers
806
+ authreq = headers.get(authreq, None)
807
+ if authreq:
808
+ mo = AbstractBasicAuthHandler.rx.search(authreq)
809
+ if mo:
810
+ scheme, realm = mo.groups()
811
+ if scheme.lower() == 'basic':
812
+ return self.retry_http_basic_auth(host, req, realm)
813
+
814
+ def retry_http_basic_auth(self, host, req, realm):
815
+ user, pw = self.passwd.find_user_password(realm, host)
816
+ if pw is not None:
817
+ raw = "%s:%s" % (user, pw)
818
+ auth = 'Basic %s' % base64.b64encode(raw).strip()
819
+ if req.headers.get(self.auth_header, None) == auth:
820
+ return None
821
+ req.add_header(self.auth_header, auth)
822
+ return self.parent.open(req)
823
+ else:
824
+ return None
825
+
826
+
827
+ class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
828
+
829
+ auth_header = 'Authorization'
830
+
831
+ def http_error_401(self, req, fp, code, msg, headers):
832
+ url = req.get_full_url()
833
+ return self.http_error_auth_reqed('www-authenticate',
834
+ url, req, headers)
835
+
836
+
837
+ class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
838
+
839
+ auth_header = 'Proxy-authorization'
840
+
841
+ def http_error_407(self, req, fp, code, msg, headers):
842
+ # http_error_auth_reqed requires that there is no userinfo component in
843
+ # authority. Assume there isn't one, since urllib2 does not (and
844
+ # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
845
+ # userinfo.
846
+ authority = req.get_host()
847
+ return self.http_error_auth_reqed('proxy-authenticate',
848
+ authority, req, headers)
849
+
850
+
851
+ def randombytes(n):
852
+ """Return n random bytes."""
853
+ # Use /dev/urandom if it is available. Fall back to random module
854
+ # if not. It might be worthwhile to extend this function to use
855
+ # other platform-specific mechanisms for getting random bytes.
856
+ if os.path.exists("/dev/urandom"):
857
+ f = open("/dev/urandom")
858
+ s = f.read(n)
859
+ f.close()
860
+ return s
861
+ else:
862
+ L = [chr(random.randrange(0, 256)) for i in range(n)]
863
+ return "".join(L)
864
+
865
+ class AbstractDigestAuthHandler:
866
+ # Digest authentication is specified in RFC 2617.
867
+
868
+ # XXX The client does not inspect the Authentication-Info header
869
+ # in a successful response.
870
+
871
+ # XXX It should be possible to test this implementation against
872
+ # a mock server that just generates a static set of challenges.
873
+
874
+ # XXX qop="auth-int" supports is shaky
875
+
876
+ def __init__(self, passwd=None):
877
+ if passwd is None:
878
+ passwd = HTTPPasswordMgr()
879
+ self.passwd = passwd
880
+ self.add_password = self.passwd.add_password
881
+ self.retried = 0
882
+ self.nonce_count = 0
883
+
884
+ def reset_retry_count(self):
885
+ self.retried = 0
886
+
887
+ def http_error_auth_reqed(self, auth_header, host, req, headers):
888
+ authreq = headers.get(auth_header, None)
889
+ if self.retried > 5:
890
+ # Don't fail endlessly - if we failed once, we'll probably
891
+ # fail a second time. Hm. Unless the Password Manager is
892
+ # prompting for the information. Crap. This isn't great
893
+ # but it's better than the current 'repeat until recursion
894
+ # depth exceeded' approach <wink>
895
+ raise HTTPError(req.get_full_url(), 401, "digest auth failed",
896
+ headers, None)
897
+ else:
898
+ self.retried += 1
899
+ if authreq:
900
+ scheme = authreq.split()[0]
901
+ if scheme.lower() == 'digest':
902
+ return self.retry_http_digest_auth(req, authreq)
903
+
904
+ def retry_http_digest_auth(self, req, auth):
905
+ token, challenge = auth.split(' ', 1)
906
+ chal = parse_keqv_list(parse_http_list(challenge))
907
+ auth = self.get_authorization(req, chal)
908
+ if auth:
909
+ auth_val = 'Digest %s' % auth
910
+ if req.headers.get(self.auth_header, None) == auth_val:
911
+ return None
912
+ req.add_unredirected_header(self.auth_header, auth_val)
913
+ resp = self.parent.open(req)
914
+ return resp
915
+
916
+ def get_cnonce(self, nonce):
917
+ # The cnonce-value is an opaque
918
+ # quoted string value provided by the client and used by both client
919
+ # and server to avoid chosen plaintext attacks, to provide mutual
920
+ # authentication, and to provide some message integrity protection.
921
+ # This isn't a fabulous effort, but it's probably Good Enough.
922
+ dig = hashlib.sha1("%s:%s:%s:%s" % (self.nonce_count, nonce, time.ctime(),
923
+ randombytes(8))).hexdigest()
924
+ return dig[:16]
925
+
926
+ def get_authorization(self, req, chal):
927
+ try:
928
+ realm = chal['realm']
929
+ nonce = chal['nonce']
930
+ qop = chal.get('qop')
931
+ algorithm = chal.get('algorithm', 'MD5')
932
+ # mod_digest doesn't send an opaque, even though it isn't
933
+ # supposed to be optional
934
+ opaque = chal.get('opaque', None)
935
+ except KeyError:
936
+ return None
937
+
938
+ H, KD = self.get_algorithm_impls(algorithm)
939
+ if H is None:
940
+ return None
941
+
942
+ user, pw = self.passwd.find_user_password(realm, req.get_full_url())
943
+ if user is None:
944
+ return None
945
+
946
+ # XXX not implemented yet
947
+ if req.has_data():
948
+ entdig = self.get_entity_digest(req.get_data(), chal)
949
+ else:
950
+ entdig = None
951
+
952
+ A1 = "%s:%s:%s" % (user, realm, pw)
953
+ A2 = "%s:%s" % (req.get_method(),
954
+ # XXX selector: what about proxies and full urls
955
+ req.get_selector())
956
+ if qop == 'auth':
957
+ self.nonce_count += 1
958
+ ncvalue = '%08x' % self.nonce_count
959
+ cnonce = self.get_cnonce(nonce)
960
+ noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, H(A2))
961
+ respdig = KD(H(A1), noncebit)
962
+ elif qop is None:
963
+ respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
964
+ else:
965
+ # XXX handle auth-int.
966
+ raise URLError("qop '%s' is not supported." % qop)
967
+
968
+ # XXX should the partial digests be encoded too?
969
+
970
+ base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
971
+ 'response="%s"' % (user, realm, nonce, req.get_selector(),
972
+ respdig)
973
+ if opaque:
974
+ base += ', opaque="%s"' % opaque
975
+ if entdig:
976
+ base += ', digest="%s"' % entdig
977
+ base += ', algorithm="%s"' % algorithm
978
+ if qop:
979
+ base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
980
+ return base
981
+
982
+ def get_algorithm_impls(self, algorithm):
983
+ # lambdas assume digest modules are imported at the top level
984
+ if algorithm == 'MD5':
985
+ H = lambda x: hashlib.md5(x).hexdigest()
986
+ elif algorithm == 'SHA':
987
+ H = lambda x: hashlib.sha1(x).hexdigest()
988
+ # XXX MD5-sess
989
+ KD = lambda s, d: H("%s:%s" % (s, d))
990
+ return H, KD
991
+
992
+ def get_entity_digest(self, data, chal):
993
+ # XXX not implemented yet
994
+ return None
995
+
996
+
997
+ class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
998
+ """An authentication protocol defined by RFC 2069
999
+
1000
+ Digest authentication improves on basic authentication because it
1001
+ does not transmit passwords in the clear.
1002
+ """
1003
+
1004
+ auth_header = 'Authorization'
1005
+ handler_order = 490 # before Basic auth
1006
+
1007
+ def http_error_401(self, req, fp, code, msg, headers):
1008
+ host = urlparse.urlparse(req.get_full_url())[1]
1009
+ retry = self.http_error_auth_reqed('www-authenticate',
1010
+ host, req, headers)
1011
+ self.reset_retry_count()
1012
+ return retry
1013
+
1014
+
1015
+ class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1016
+
1017
+ auth_header = 'Proxy-Authorization'
1018
+ handler_order = 490 # before Basic auth
1019
+
1020
+ def http_error_407(self, req, fp, code, msg, headers):
1021
+ host = req.get_host()
1022
+ retry = self.http_error_auth_reqed('proxy-authenticate',
1023
+ host, req, headers)
1024
+ self.reset_retry_count()
1025
+ return retry
1026
+
1027
+ class AbstractHTTPHandler(BaseHandler):
1028
+
1029
+ def __init__(self, debuglevel=0):
1030
+ self._debuglevel = debuglevel
1031
+
1032
+ def set_http_debuglevel(self, level):
1033
+ self._debuglevel = level
1034
+
1035
+ def do_request_(self, request):
1036
+ host = request.get_host()
1037
+ if not host:
1038
+ raise URLError('no host given')
1039
+
1040
+ if request.has_data(): # POST
1041
+ data = request.get_data()
1042
+ if not request.has_header('Content-type'):
1043
+ request.add_unredirected_header(
1044
+ 'Content-type',
1045
+ 'application/x-www-form-urlencoded')
1046
+ if not request.has_header('Content-length'):
1047
+ request.add_unredirected_header(
1048
+ 'Content-length', '%d' % len(data))
1049
+
1050
+ scheme, sel = splittype(request.get_selector())
1051
+ sel_host, sel_path = splithost(sel)
1052
+ if not request.has_header('Host'):
1053
+ request.add_unredirected_header('Host', sel_host or host)
1054
+ for name, value in self.parent.addheaders:
1055
+ name = name.capitalize()
1056
+ if not request.has_header(name):
1057
+ request.add_unredirected_header(name, value)
1058
+
1059
+ return request
1060
+
1061
+ def do_open(self, http_class, req):
1062
+ """Return an addinfourl object for the request, using http_class.
1063
+
1064
+ http_class must implement the HTTPConnection API from httplib.
1065
+ The addinfourl return value is a file-like object. It also
1066
+ has methods and attributes including:
1067
+ - info(): return a mimetools.Message object for the headers
1068
+ - geturl(): return the original request URL
1069
+ - code: HTTP status code
1070
+ """
1071
+ host = req.get_host()
1072
+ if not host:
1073
+ raise URLError('no host given')
1074
+
1075
+ h = http_class(host) # will parse host:port
1076
+ h.set_debuglevel(self._debuglevel)
1077
+
1078
+ headers = dict(req.headers)
1079
+ headers.update(req.unredirected_hdrs)
1080
+ # We want to make an HTTP/1.1 request, but the addinfourl
1081
+ # class isn't prepared to deal with a persistent connection.
1082
+ # It will try to read all remaining data from the socket,
1083
+ # which will block while the server waits for the next request.
1084
+ # So make sure the connection gets closed after the (only)
1085
+ # request.
1086
+ headers["Connection"] = "close"
1087
+ headers = dict(
1088
+ (name.title(), val) for name, val in headers.items())
1089
+ try:
1090
+ h.request(req.get_method(), req.get_selector(), req.data, headers)
1091
+ r = h.getresponse()
1092
+ except socket.error, err: # XXX what error?
1093
+ raise URLError(err)
1094
+
1095
+ # Pick apart the HTTPResponse object to get the addinfourl
1096
+ # object initialized properly.
1097
+
1098
+ # Wrap the HTTPResponse object in socket's file object adapter
1099
+ # for Windows. That adapter calls recv(), so delegate recv()
1100
+ # to read(). This weird wrapping allows the returned object to
1101
+ # have readline() and readlines() methods.
1102
+
1103
+ # XXX It might be better to extract the read buffering code
1104
+ # out of socket._fileobject() and into a base class.
1105
+
1106
+ r.recv = r.read
1107
+ fp = socket._fileobject(r, close=True)
1108
+
1109
+ resp = addinfourl(fp, r.msg, req.get_full_url())
1110
+ resp.code = r.status
1111
+ resp.msg = r.reason
1112
+ return resp
1113
+
1114
+
1115
+ class HTTPHandler(AbstractHTTPHandler):
1116
+
1117
+ def http_open(self, req):
1118
+ return self.do_open(httplib.HTTPConnection, req)
1119
+
1120
+ http_request = AbstractHTTPHandler.do_request_
1121
+
1122
+ if hasattr(httplib, 'HTTPS'):
1123
+ class HTTPSHandler(AbstractHTTPHandler):
1124
+
1125
+ def https_open(self, req):
1126
+ return self.do_open(httplib.HTTPSConnection, req)
1127
+
1128
+ https_request = AbstractHTTPHandler.do_request_
1129
+
1130
+ class HTTPCookieProcessor(BaseHandler):
1131
+ def __init__(self, cookiejar=None):
1132
+ import cookielib
1133
+ if cookiejar is None:
1134
+ cookiejar = cookielib.CookieJar()
1135
+ self.cookiejar = cookiejar
1136
+
1137
+ def http_request(self, request):
1138
+ self.cookiejar.add_cookie_header(request)
1139
+ return request
1140
+
1141
+ def http_response(self, request, response):
1142
+ self.cookiejar.extract_cookies(response, request)
1143
+ return response
1144
+
1145
+ https_request = http_request
1146
+ https_response = http_response
1147
+
1148
+ class UnknownHandler(BaseHandler):
1149
+ def unknown_open(self, req):
1150
+ type = req.get_type()
1151
+ raise URLError('unknown url type: %s' % type)
1152
+
1153
+ def parse_keqv_list(l):
1154
+ """Parse list of key=value strings where keys are not duplicated."""
1155
+ parsed = {}
1156
+ for elt in l:
1157
+ k, v = elt.split('=', 1)
1158
+ if v[0] == '"' and v[-1] == '"':
1159
+ v = v[1:-1]
1160
+ parsed[k] = v
1161
+ return parsed
1162
+
1163
+ def parse_http_list(s):
1164
+ """Parse lists as described by RFC 2068 Section 2.
1165
+
1166
+ In particular, parse comma-separated lists where the elements of
1167
+ the list may include quoted-strings. A quoted-string could
1168
+ contain a comma. A non-quoted string could have quotes in the
1169
+ middle. Neither commas nor quotes count if they are escaped.
1170
+ Only double-quotes count, not single-quotes.
1171
+ """
1172
+ res = []
1173
+ part = ''
1174
+
1175
+ escape = quote = False
1176
+ for cur in s:
1177
+ if escape:
1178
+ part += cur
1179
+ escape = False
1180
+ continue
1181
+ if quote:
1182
+ if cur == '\\':
1183
+ escape = True
1184
+ continue
1185
+ elif cur == '"':
1186
+ quote = False
1187
+ part += cur
1188
+ continue
1189
+
1190
+ if cur == ',':
1191
+ res.append(part)
1192
+ part = ''
1193
+ continue
1194
+
1195
+ if cur == '"':
1196
+ quote = True
1197
+
1198
+ part += cur
1199
+
1200
+ # append last part
1201
+ if part:
1202
+ res.append(part)
1203
+
1204
+ return [part.strip() for part in res]
1205
+
1206
+ class FileHandler(BaseHandler):
1207
+ # Use local file or FTP depending on form of URL
1208
+ def file_open(self, req):
1209
+ url = req.get_selector()
1210
+ if url[:2] == '//' and url[2:3] != '/':
1211
+ req.type = 'ftp'
1212
+ return self.parent.open(req)
1213
+ else:
1214
+ return self.open_local_file(req)
1215
+
1216
+ # names for the localhost
1217
+ names = None
1218
+ def get_names(self):
1219
+ if FileHandler.names is None:
1220
+ try:
1221
+ FileHandler.names = (socket.gethostbyname('localhost'),
1222
+ socket.gethostbyname(socket.gethostname()))
1223
+ except socket.gaierror:
1224
+ FileHandler.names = (socket.gethostbyname('localhost'),)
1225
+ return FileHandler.names
1226
+
1227
+ # not entirely sure what the rules are here
1228
+ def open_local_file(self, req):
1229
+ import email.Utils
1230
+ import mimetypes
1231
+ host = req.get_host()
1232
+ file = req.get_selector()
1233
+ localfile = url2pathname(file)
1234
+ stats = os.stat(localfile)
1235
+ size = stats.st_size
1236
+ modified = email.Utils.formatdate(stats.st_mtime, usegmt=True)
1237
+ mtype = mimetypes.guess_type(file)[0]
1238
+ headers = mimetools.Message(StringIO(
1239
+ 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1240
+ (mtype or 'text/plain', size, modified)))
1241
+ if host:
1242
+ host, port = splitport(host)
1243
+ if not host or \
1244
+ (not port and socket.gethostbyname(host) in self.get_names()):
1245
+ return addinfourl(open(localfile, 'rb'),
1246
+ headers, 'file:'+file)
1247
+ raise URLError('file not on local host')
1248
+
1249
+ class FTPHandler(BaseHandler):
1250
+ def ftp_open(self, req):
1251
+ import ftplib
1252
+ import mimetypes
1253
+ host = req.get_host()
1254
+ if not host:
1255
+ raise IOError, ('ftp error', 'no host given')
1256
+ host, port = splitport(host)
1257
+ if port is None:
1258
+ port = ftplib.FTP_PORT
1259
+ else:
1260
+ port = int(port)
1261
+
1262
+ # username/password handling
1263
+ user, host = splituser(host)
1264
+ if user:
1265
+ user, passwd = splitpasswd(user)
1266
+ else:
1267
+ passwd = None
1268
+ host = unquote(host)
1269
+ user = unquote(user or '')
1270
+ passwd = unquote(passwd or '')
1271
+
1272
+ try:
1273
+ host = socket.gethostbyname(host)
1274
+ except socket.error, msg:
1275
+ raise URLError(msg)
1276
+ path, attrs = splitattr(req.get_selector())
1277
+ dirs = path.split('/')
1278
+ dirs = map(unquote, dirs)
1279
+ dirs, file = dirs[:-1], dirs[-1]
1280
+ if dirs and not dirs[0]:
1281
+ dirs = dirs[1:]
1282
+ try:
1283
+ fw = self.connect_ftp(user, passwd, host, port, dirs)
1284
+ type = file and 'I' or 'D'
1285
+ for attr in attrs:
1286
+ attr, value = splitvalue(attr)
1287
+ if attr.lower() == 'type' and \
1288
+ value in ('a', 'A', 'i', 'I', 'd', 'D'):
1289
+ type = value.upper()
1290
+ fp, retrlen = fw.retrfile(file, type)
1291
+ headers = ""
1292
+ mtype = mimetypes.guess_type(req.get_full_url())[0]
1293
+ if mtype:
1294
+ headers += "Content-type: %s\n" % mtype
1295
+ if retrlen is not None and retrlen >= 0:
1296
+ headers += "Content-length: %d\n" % retrlen
1297
+ sf = StringIO(headers)
1298
+ headers = mimetools.Message(sf)
1299
+ return addinfourl(fp, headers, req.get_full_url())
1300
+ except ftplib.all_errors, msg:
1301
+ raise IOError, ('ftp error', msg), sys.exc_info()[2]
1302
+
1303
+ def connect_ftp(self, user, passwd, host, port, dirs):
1304
+ fw = ftpwrapper(user, passwd, host, port, dirs)
1305
+ ## fw.ftp.set_debuglevel(1)
1306
+ return fw
1307
+
1308
+ class CacheFTPHandler(FTPHandler):
1309
+ # XXX would be nice to have pluggable cache strategies
1310
+ # XXX this stuff is definitely not thread safe
1311
+ def __init__(self):
1312
+ self.cache = {}
1313
+ self.timeout = {}
1314
+ self.soonest = 0
1315
+ self.delay = 60
1316
+ self.max_conns = 16
1317
+
1318
+ def setTimeout(self, t):
1319
+ self.delay = t
1320
+
1321
+ def setMaxConns(self, m):
1322
+ self.max_conns = m
1323
+
1324
+ def connect_ftp(self, user, passwd, host, port, dirs):
1325
+ key = user, host, port, '/'.join(dirs)
1326
+ if key in self.cache:
1327
+ self.timeout[key] = time.time() + self.delay
1328
+ else:
1329
+ self.cache[key] = ftpwrapper(user, passwd, host, port, dirs)
1330
+ self.timeout[key] = time.time() + self.delay
1331
+ self.check_cache()
1332
+ return self.cache[key]
1333
+
1334
+ def check_cache(self):
1335
+ # first check for old ones
1336
+ t = time.time()
1337
+ if self.soonest <= t:
1338
+ for k, v in self.timeout.items():
1339
+ if v < t:
1340
+ self.cache[k].close()
1341
+ del self.cache[k]
1342
+ del self.timeout[k]
1343
+ self.soonest = min(self.timeout.values())
1344
+
1345
+ # then check the size
1346
+ if len(self.cache) == self.max_conns:
1347
+ for k, v in self.timeout.items():
1348
+ if v == self.soonest:
1349
+ del self.cache[k]
1350
+ del self.timeout[k]
1351
+ break
1352
+ self.soonest = min(self.timeout.values())
1353
+
1354
+ class GopherHandler(BaseHandler):
1355
+ def gopher_open(self, req):
1356
+ # XXX can raise socket.error
1357
+ import gopherlib # this raises DeprecationWarning in 2.5
1358
+ host = req.get_host()
1359
+ if not host:
1360
+ raise GopherError('no host given')
1361
+ host = unquote(host)
1362
+ selector = req.get_selector()
1363
+ type, selector = splitgophertype(selector)
1364
+ selector, query = splitquery(selector)
1365
+ selector = unquote(selector)
1366
+ if query:
1367
+ query = unquote(query)
1368
+ fp = gopherlib.send_query(selector, query, host)
1369
+ else:
1370
+ fp = gopherlib.send_selector(selector, host)
1371
+ return addinfourl(fp, noheaders(), req.get_full_url())