@rowstile/cli-linux-x64 0.1.0-alpha.2

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 (565) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +5 -0
  3. package/package.json +26 -0
  4. package/python/bin/python3.13 +0 -0
  5. package/python/bin/python3.13-config +122 -0
  6. package/python/lib/libpython3.13.so.1.0 +0 -0
  7. package/python/lib/libpython3.so +0 -0
  8. package/python/lib/python3.13/LICENSE.txt +277 -0
  9. package/python/lib/python3.13/__future__.py +147 -0
  10. package/python/lib/python3.13/__hello__.py +16 -0
  11. package/python/lib/python3.13/_aix_support.py +108 -0
  12. package/python/lib/python3.13/_android_support.py +192 -0
  13. package/python/lib/python3.13/_apple_support.py +66 -0
  14. package/python/lib/python3.13/_collections_abc.py +1187 -0
  15. package/python/lib/python3.13/_colorize.py +119 -0
  16. package/python/lib/python3.13/_compat_pickle.py +251 -0
  17. package/python/lib/python3.13/_compression.py +162 -0
  18. package/python/lib/python3.13/_ios_support.py +71 -0
  19. package/python/lib/python3.13/_markupbase.py +396 -0
  20. package/python/lib/python3.13/_opcode_metadata.py +343 -0
  21. package/python/lib/python3.13/_osx_support.py +579 -0
  22. package/python/lib/python3.13/_py_abc.py +147 -0
  23. package/python/lib/python3.13/_pydatetime.py +2640 -0
  24. package/python/lib/python3.13/_pydecimal.py +6356 -0
  25. package/python/lib/python3.13/_pyio.py +2714 -0
  26. package/python/lib/python3.13/_pylong.py +363 -0
  27. package/python/lib/python3.13/_pyrepl/__init__.py +19 -0
  28. package/python/lib/python3.13/_pyrepl/__main__.py +10 -0
  29. package/python/lib/python3.13/_pyrepl/_minimal_curses.py +68 -0
  30. package/python/lib/python3.13/_pyrepl/_threading_handler.py +74 -0
  31. package/python/lib/python3.13/_pyrepl/base_eventqueue.py +110 -0
  32. package/python/lib/python3.13/_pyrepl/commands.py +492 -0
  33. package/python/lib/python3.13/_pyrepl/completing_reader.py +295 -0
  34. package/python/lib/python3.13/_pyrepl/console.py +229 -0
  35. package/python/lib/python3.13/_pyrepl/curses.py +33 -0
  36. package/python/lib/python3.13/_pyrepl/fancy_termios.py +82 -0
  37. package/python/lib/python3.13/_pyrepl/historical_reader.py +419 -0
  38. package/python/lib/python3.13/_pyrepl/input.py +114 -0
  39. package/python/lib/python3.13/_pyrepl/keymap.py +213 -0
  40. package/python/lib/python3.13/_pyrepl/main.py +59 -0
  41. package/python/lib/python3.13/_pyrepl/mypy.ini +29 -0
  42. package/python/lib/python3.13/_pyrepl/pager.py +175 -0
  43. package/python/lib/python3.13/_pyrepl/reader.py +764 -0
  44. package/python/lib/python3.13/_pyrepl/readline.py +599 -0
  45. package/python/lib/python3.13/_pyrepl/simple_interact.py +180 -0
  46. package/python/lib/python3.13/_pyrepl/trace.py +21 -0
  47. package/python/lib/python3.13/_pyrepl/types.py +10 -0
  48. package/python/lib/python3.13/_pyrepl/unix_console.py +852 -0
  49. package/python/lib/python3.13/_pyrepl/unix_eventqueue.py +76 -0
  50. package/python/lib/python3.13/_pyrepl/utils.py +83 -0
  51. package/python/lib/python3.13/_pyrepl/windows_console.py +687 -0
  52. package/python/lib/python3.13/_pyrepl/windows_eventqueue.py +42 -0
  53. package/python/lib/python3.13/_sitebuiltins.py +91 -0
  54. package/python/lib/python3.13/_strptime.py +800 -0
  55. package/python/lib/python3.13/_sysconfigdata__linux_x86_64-linux-gnu.py +1079 -0
  56. package/python/lib/python3.13/_threading_local.py +120 -0
  57. package/python/lib/python3.13/_weakrefset.py +205 -0
  58. package/python/lib/python3.13/abc.py +188 -0
  59. package/python/lib/python3.13/antigravity.py +17 -0
  60. package/python/lib/python3.13/argparse.py +2690 -0
  61. package/python/lib/python3.13/ast.py +1865 -0
  62. package/python/lib/python3.13/asyncio/__init__.py +47 -0
  63. package/python/lib/python3.13/asyncio/__main__.py +211 -0
  64. package/python/lib/python3.13/asyncio/base_events.py +2086 -0
  65. package/python/lib/python3.13/asyncio/base_futures.py +67 -0
  66. package/python/lib/python3.13/asyncio/base_subprocess.py +312 -0
  67. package/python/lib/python3.13/asyncio/base_tasks.py +94 -0
  68. package/python/lib/python3.13/asyncio/constants.py +41 -0
  69. package/python/lib/python3.13/asyncio/coroutines.py +109 -0
  70. package/python/lib/python3.13/asyncio/events.py +885 -0
  71. package/python/lib/python3.13/asyncio/exceptions.py +62 -0
  72. package/python/lib/python3.13/asyncio/format_helpers.py +84 -0
  73. package/python/lib/python3.13/asyncio/futures.py +425 -0
  74. package/python/lib/python3.13/asyncio/locks.py +617 -0
  75. package/python/lib/python3.13/asyncio/log.py +7 -0
  76. package/python/lib/python3.13/asyncio/mixins.py +21 -0
  77. package/python/lib/python3.13/asyncio/proactor_events.py +891 -0
  78. package/python/lib/python3.13/asyncio/protocols.py +216 -0
  79. package/python/lib/python3.13/asyncio/queues.py +309 -0
  80. package/python/lib/python3.13/asyncio/runners.py +217 -0
  81. package/python/lib/python3.13/asyncio/selector_events.py +1328 -0
  82. package/python/lib/python3.13/asyncio/sslproto.py +929 -0
  83. package/python/lib/python3.13/asyncio/staggered.py +174 -0
  84. package/python/lib/python3.13/asyncio/streams.py +787 -0
  85. package/python/lib/python3.13/asyncio/subprocess.py +229 -0
  86. package/python/lib/python3.13/asyncio/taskgroups.py +278 -0
  87. package/python/lib/python3.13/asyncio/tasks.py +1121 -0
  88. package/python/lib/python3.13/asyncio/threads.py +26 -0
  89. package/python/lib/python3.13/asyncio/timeouts.py +185 -0
  90. package/python/lib/python3.13/asyncio/transports.py +337 -0
  91. package/python/lib/python3.13/asyncio/trsock.py +98 -0
  92. package/python/lib/python3.13/asyncio/unix_events.py +1550 -0
  93. package/python/lib/python3.13/asyncio/windows_events.py +906 -0
  94. package/python/lib/python3.13/asyncio/windows_utils.py +181 -0
  95. package/python/lib/python3.13/base64.py +628 -0
  96. package/python/lib/python3.13/bdb.py +973 -0
  97. package/python/lib/python3.13/bisect.py +118 -0
  98. package/python/lib/python3.13/bz2.py +352 -0
  99. package/python/lib/python3.13/cProfile.py +197 -0
  100. package/python/lib/python3.13/calendar.py +813 -0
  101. package/python/lib/python3.13/cmd.py +409 -0
  102. package/python/lib/python3.13/code.py +386 -0
  103. package/python/lib/python3.13/codecs.py +1132 -0
  104. package/python/lib/python3.13/codeop.py +155 -0
  105. package/python/lib/python3.13/collections/__init__.py +1603 -0
  106. package/python/lib/python3.13/colorsys.py +166 -0
  107. package/python/lib/python3.13/compileall.py +470 -0
  108. package/python/lib/python3.13/concurrent/__init__.py +1 -0
  109. package/python/lib/python3.13/concurrent/futures/__init__.py +54 -0
  110. package/python/lib/python3.13/concurrent/futures/_base.py +660 -0
  111. package/python/lib/python3.13/concurrent/futures/process.py +892 -0
  112. package/python/lib/python3.13/concurrent/futures/thread.py +240 -0
  113. package/python/lib/python3.13/configparser.py +1396 -0
  114. package/python/lib/python3.13/contextlib.py +814 -0
  115. package/python/lib/python3.13/contextvars.py +4 -0
  116. package/python/lib/python3.13/copy.py +306 -0
  117. package/python/lib/python3.13/copyreg.py +217 -0
  118. package/python/lib/python3.13/csv.py +527 -0
  119. package/python/lib/python3.13/ctypes/__init__.py +605 -0
  120. package/python/lib/python3.13/ctypes/_aix.py +327 -0
  121. package/python/lib/python3.13/ctypes/_endian.py +78 -0
  122. package/python/lib/python3.13/ctypes/macholib/README.ctypes +7 -0
  123. package/python/lib/python3.13/ctypes/macholib/__init__.py +9 -0
  124. package/python/lib/python3.13/ctypes/macholib/dyld.py +165 -0
  125. package/python/lib/python3.13/ctypes/macholib/dylib.py +42 -0
  126. package/python/lib/python3.13/ctypes/macholib/fetch_macholib +2 -0
  127. package/python/lib/python3.13/ctypes/macholib/fetch_macholib.bat +1 -0
  128. package/python/lib/python3.13/ctypes/macholib/framework.py +42 -0
  129. package/python/lib/python3.13/ctypes/util.py +387 -0
  130. package/python/lib/python3.13/ctypes/wintypes.py +202 -0
  131. package/python/lib/python3.13/curses/__init__.py +101 -0
  132. package/python/lib/python3.13/curses/ascii.py +99 -0
  133. package/python/lib/python3.13/curses/has_key.py +192 -0
  134. package/python/lib/python3.13/curses/panel.py +6 -0
  135. package/python/lib/python3.13/curses/textpad.py +236 -0
  136. package/python/lib/python3.13/dataclasses.py +1679 -0
  137. package/python/lib/python3.13/datetime.py +9 -0
  138. package/python/lib/python3.13/dbm/__init__.py +194 -0
  139. package/python/lib/python3.13/dbm/dumb.py +319 -0
  140. package/python/lib/python3.13/dbm/gnu.py +3 -0
  141. package/python/lib/python3.13/dbm/ndbm.py +3 -0
  142. package/python/lib/python3.13/dbm/sqlite3.py +144 -0
  143. package/python/lib/python3.13/decimal.py +109 -0
  144. package/python/lib/python3.13/difflib.py +2058 -0
  145. package/python/lib/python3.13/dis.py +1075 -0
  146. package/python/lib/python3.13/doctest.py +2919 -0
  147. package/python/lib/python3.13/email/__init__.py +61 -0
  148. package/python/lib/python3.13/email/_encoded_words.py +233 -0
  149. package/python/lib/python3.13/email/_header_value_parser.py +3153 -0
  150. package/python/lib/python3.13/email/_parseaddr.py +563 -0
  151. package/python/lib/python3.13/email/_policybase.py +382 -0
  152. package/python/lib/python3.13/email/architecture.rst +216 -0
  153. package/python/lib/python3.13/email/base64mime.py +115 -0
  154. package/python/lib/python3.13/email/charset.py +396 -0
  155. package/python/lib/python3.13/email/contentmanager.py +254 -0
  156. package/python/lib/python3.13/email/encoders.py +65 -0
  157. package/python/lib/python3.13/email/errors.py +117 -0
  158. package/python/lib/python3.13/email/feedparser.py +536 -0
  159. package/python/lib/python3.13/email/generator.py +530 -0
  160. package/python/lib/python3.13/email/header.py +582 -0
  161. package/python/lib/python3.13/email/headerregistry.py +618 -0
  162. package/python/lib/python3.13/email/iterators.py +68 -0
  163. package/python/lib/python3.13/email/message.py +1217 -0
  164. package/python/lib/python3.13/email/mime/__init__.py +0 -0
  165. package/python/lib/python3.13/email/mime/application.py +37 -0
  166. package/python/lib/python3.13/email/mime/audio.py +97 -0
  167. package/python/lib/python3.13/email/mime/base.py +29 -0
  168. package/python/lib/python3.13/email/mime/image.py +152 -0
  169. package/python/lib/python3.13/email/mime/message.py +33 -0
  170. package/python/lib/python3.13/email/mime/multipart.py +47 -0
  171. package/python/lib/python3.13/email/mime/nonmultipart.py +21 -0
  172. package/python/lib/python3.13/email/mime/text.py +40 -0
  173. package/python/lib/python3.13/email/parser.py +127 -0
  174. package/python/lib/python3.13/email/policy.py +232 -0
  175. package/python/lib/python3.13/email/quoprimime.py +300 -0
  176. package/python/lib/python3.13/email/utils.py +497 -0
  177. package/python/lib/python3.13/encodings/__init__.py +179 -0
  178. package/python/lib/python3.13/encodings/__pycache__/__init__.cpython-313.pyc +0 -0
  179. package/python/lib/python3.13/encodings/__pycache__/aliases.cpython-313.pyc +0 -0
  180. package/python/lib/python3.13/encodings/__pycache__/utf_8.cpython-313.pyc +0 -0
  181. package/python/lib/python3.13/encodings/aliases.py +560 -0
  182. package/python/lib/python3.13/encodings/ascii.py +50 -0
  183. package/python/lib/python3.13/encodings/base64_codec.py +55 -0
  184. package/python/lib/python3.13/encodings/big5.py +39 -0
  185. package/python/lib/python3.13/encodings/big5hkscs.py +39 -0
  186. package/python/lib/python3.13/encodings/bz2_codec.py +78 -0
  187. package/python/lib/python3.13/encodings/charmap.py +69 -0
  188. package/python/lib/python3.13/encodings/cp037.py +307 -0
  189. package/python/lib/python3.13/encodings/cp1006.py +307 -0
  190. package/python/lib/python3.13/encodings/cp1026.py +307 -0
  191. package/python/lib/python3.13/encodings/cp1125.py +698 -0
  192. package/python/lib/python3.13/encodings/cp1140.py +307 -0
  193. package/python/lib/python3.13/encodings/cp1250.py +307 -0
  194. package/python/lib/python3.13/encodings/cp1251.py +307 -0
  195. package/python/lib/python3.13/encodings/cp1252.py +307 -0
  196. package/python/lib/python3.13/encodings/cp1253.py +307 -0
  197. package/python/lib/python3.13/encodings/cp1254.py +307 -0
  198. package/python/lib/python3.13/encodings/cp1255.py +307 -0
  199. package/python/lib/python3.13/encodings/cp1256.py +307 -0
  200. package/python/lib/python3.13/encodings/cp1257.py +307 -0
  201. package/python/lib/python3.13/encodings/cp1258.py +307 -0
  202. package/python/lib/python3.13/encodings/cp273.py +307 -0
  203. package/python/lib/python3.13/encodings/cp424.py +307 -0
  204. package/python/lib/python3.13/encodings/cp437.py +698 -0
  205. package/python/lib/python3.13/encodings/cp500.py +307 -0
  206. package/python/lib/python3.13/encodings/cp720.py +309 -0
  207. package/python/lib/python3.13/encodings/cp737.py +698 -0
  208. package/python/lib/python3.13/encodings/cp775.py +697 -0
  209. package/python/lib/python3.13/encodings/cp850.py +698 -0
  210. package/python/lib/python3.13/encodings/cp852.py +698 -0
  211. package/python/lib/python3.13/encodings/cp855.py +698 -0
  212. package/python/lib/python3.13/encodings/cp856.py +307 -0
  213. package/python/lib/python3.13/encodings/cp857.py +694 -0
  214. package/python/lib/python3.13/encodings/cp858.py +698 -0
  215. package/python/lib/python3.13/encodings/cp860.py +698 -0
  216. package/python/lib/python3.13/encodings/cp861.py +698 -0
  217. package/python/lib/python3.13/encodings/cp862.py +698 -0
  218. package/python/lib/python3.13/encodings/cp863.py +698 -0
  219. package/python/lib/python3.13/encodings/cp864.py +690 -0
  220. package/python/lib/python3.13/encodings/cp865.py +698 -0
  221. package/python/lib/python3.13/encodings/cp866.py +698 -0
  222. package/python/lib/python3.13/encodings/cp869.py +689 -0
  223. package/python/lib/python3.13/encodings/cp874.py +307 -0
  224. package/python/lib/python3.13/encodings/cp875.py +307 -0
  225. package/python/lib/python3.13/encodings/cp932.py +39 -0
  226. package/python/lib/python3.13/encodings/cp949.py +39 -0
  227. package/python/lib/python3.13/encodings/cp950.py +39 -0
  228. package/python/lib/python3.13/encodings/euc_jis_2004.py +39 -0
  229. package/python/lib/python3.13/encodings/euc_jisx0213.py +39 -0
  230. package/python/lib/python3.13/encodings/euc_jp.py +39 -0
  231. package/python/lib/python3.13/encodings/euc_kr.py +39 -0
  232. package/python/lib/python3.13/encodings/gb18030.py +39 -0
  233. package/python/lib/python3.13/encodings/gb2312.py +39 -0
  234. package/python/lib/python3.13/encodings/gbk.py +39 -0
  235. package/python/lib/python3.13/encodings/hex_codec.py +55 -0
  236. package/python/lib/python3.13/encodings/hp_roman8.py +314 -0
  237. package/python/lib/python3.13/encodings/hz.py +39 -0
  238. package/python/lib/python3.13/encodings/idna.py +387 -0
  239. package/python/lib/python3.13/encodings/iso2022_jp.py +39 -0
  240. package/python/lib/python3.13/encodings/iso2022_jp_1.py +39 -0
  241. package/python/lib/python3.13/encodings/iso2022_jp_2.py +39 -0
  242. package/python/lib/python3.13/encodings/iso2022_jp_2004.py +39 -0
  243. package/python/lib/python3.13/encodings/iso2022_jp_3.py +39 -0
  244. package/python/lib/python3.13/encodings/iso2022_jp_ext.py +39 -0
  245. package/python/lib/python3.13/encodings/iso2022_kr.py +39 -0
  246. package/python/lib/python3.13/encodings/iso8859_1.py +307 -0
  247. package/python/lib/python3.13/encodings/iso8859_10.py +307 -0
  248. package/python/lib/python3.13/encodings/iso8859_11.py +307 -0
  249. package/python/lib/python3.13/encodings/iso8859_13.py +307 -0
  250. package/python/lib/python3.13/encodings/iso8859_14.py +307 -0
  251. package/python/lib/python3.13/encodings/iso8859_15.py +307 -0
  252. package/python/lib/python3.13/encodings/iso8859_16.py +307 -0
  253. package/python/lib/python3.13/encodings/iso8859_2.py +307 -0
  254. package/python/lib/python3.13/encodings/iso8859_3.py +307 -0
  255. package/python/lib/python3.13/encodings/iso8859_4.py +307 -0
  256. package/python/lib/python3.13/encodings/iso8859_5.py +307 -0
  257. package/python/lib/python3.13/encodings/iso8859_6.py +307 -0
  258. package/python/lib/python3.13/encodings/iso8859_7.py +307 -0
  259. package/python/lib/python3.13/encodings/iso8859_8.py +307 -0
  260. package/python/lib/python3.13/encodings/iso8859_9.py +307 -0
  261. package/python/lib/python3.13/encodings/johab.py +39 -0
  262. package/python/lib/python3.13/encodings/koi8_r.py +307 -0
  263. package/python/lib/python3.13/encodings/koi8_t.py +308 -0
  264. package/python/lib/python3.13/encodings/koi8_u.py +307 -0
  265. package/python/lib/python3.13/encodings/kz1048.py +307 -0
  266. package/python/lib/python3.13/encodings/latin_1.py +50 -0
  267. package/python/lib/python3.13/encodings/mac_arabic.py +698 -0
  268. package/python/lib/python3.13/encodings/mac_croatian.py +307 -0
  269. package/python/lib/python3.13/encodings/mac_cyrillic.py +307 -0
  270. package/python/lib/python3.13/encodings/mac_farsi.py +307 -0
  271. package/python/lib/python3.13/encodings/mac_greek.py +307 -0
  272. package/python/lib/python3.13/encodings/mac_iceland.py +307 -0
  273. package/python/lib/python3.13/encodings/mac_latin2.py +312 -0
  274. package/python/lib/python3.13/encodings/mac_roman.py +307 -0
  275. package/python/lib/python3.13/encodings/mac_romanian.py +307 -0
  276. package/python/lib/python3.13/encodings/mac_turkish.py +307 -0
  277. package/python/lib/python3.13/encodings/mbcs.py +47 -0
  278. package/python/lib/python3.13/encodings/oem.py +41 -0
  279. package/python/lib/python3.13/encodings/palmos.py +308 -0
  280. package/python/lib/python3.13/encodings/ptcp154.py +312 -0
  281. package/python/lib/python3.13/encodings/punycode.py +253 -0
  282. package/python/lib/python3.13/encodings/quopri_codec.py +56 -0
  283. package/python/lib/python3.13/encodings/raw_unicode_escape.py +46 -0
  284. package/python/lib/python3.13/encodings/rot_13.py +113 -0
  285. package/python/lib/python3.13/encodings/shift_jis.py +39 -0
  286. package/python/lib/python3.13/encodings/shift_jis_2004.py +39 -0
  287. package/python/lib/python3.13/encodings/shift_jisx0213.py +39 -0
  288. package/python/lib/python3.13/encodings/tis_620.py +307 -0
  289. package/python/lib/python3.13/encodings/undefined.py +49 -0
  290. package/python/lib/python3.13/encodings/unicode_escape.py +46 -0
  291. package/python/lib/python3.13/encodings/utf_16.py +155 -0
  292. package/python/lib/python3.13/encodings/utf_16_be.py +42 -0
  293. package/python/lib/python3.13/encodings/utf_16_le.py +42 -0
  294. package/python/lib/python3.13/encodings/utf_32.py +150 -0
  295. package/python/lib/python3.13/encodings/utf_32_be.py +37 -0
  296. package/python/lib/python3.13/encodings/utf_32_le.py +37 -0
  297. package/python/lib/python3.13/encodings/utf_7.py +38 -0
  298. package/python/lib/python3.13/encodings/utf_8.py +42 -0
  299. package/python/lib/python3.13/encodings/utf_8_sig.py +130 -0
  300. package/python/lib/python3.13/encodings/uu_codec.py +103 -0
  301. package/python/lib/python3.13/encodings/zlib_codec.py +77 -0
  302. package/python/lib/python3.13/enum.py +2183 -0
  303. package/python/lib/python3.13/filecmp.py +320 -0
  304. package/python/lib/python3.13/fileinput.py +442 -0
  305. package/python/lib/python3.13/fnmatch.py +192 -0
  306. package/python/lib/python3.13/fractions.py +1043 -0
  307. package/python/lib/python3.13/ftplib.py +975 -0
  308. package/python/lib/python3.13/functools.py +1036 -0
  309. package/python/lib/python3.13/genericpath.py +200 -0
  310. package/python/lib/python3.13/getopt.py +215 -0
  311. package/python/lib/python3.13/getpass.py +192 -0
  312. package/python/lib/python3.13/gettext.py +657 -0
  313. package/python/lib/python3.13/glob.py +572 -0
  314. package/python/lib/python3.13/graphlib.py +250 -0
  315. package/python/lib/python3.13/gzip.py +693 -0
  316. package/python/lib/python3.13/hashlib.py +255 -0
  317. package/python/lib/python3.13/heapq.py +603 -0
  318. package/python/lib/python3.13/hmac.py +220 -0
  319. package/python/lib/python3.13/html/__init__.py +132 -0
  320. package/python/lib/python3.13/html/entities.py +2513 -0
  321. package/python/lib/python3.13/html/parser.py +583 -0
  322. package/python/lib/python3.13/http/__init__.py +202 -0
  323. package/python/lib/python3.13/http/client.py +1598 -0
  324. package/python/lib/python3.13/http/cookiejar.py +2122 -0
  325. package/python/lib/python3.13/http/cookies.py +635 -0
  326. package/python/lib/python3.13/http/server.py +1355 -0
  327. package/python/lib/python3.13/imaplib.py +1769 -0
  328. package/python/lib/python3.13/importlib/__init__.py +136 -0
  329. package/python/lib/python3.13/importlib/_abc.py +39 -0
  330. package/python/lib/python3.13/importlib/_bootstrap.py +1559 -0
  331. package/python/lib/python3.13/importlib/_bootstrap_external.py +1826 -0
  332. package/python/lib/python3.13/importlib/abc.py +243 -0
  333. package/python/lib/python3.13/importlib/machinery.py +21 -0
  334. package/python/lib/python3.13/importlib/metadata/__init__.py +1093 -0
  335. package/python/lib/python3.13/importlib/metadata/_adapters.py +89 -0
  336. package/python/lib/python3.13/importlib/metadata/_collections.py +30 -0
  337. package/python/lib/python3.13/importlib/metadata/_functools.py +104 -0
  338. package/python/lib/python3.13/importlib/metadata/_itertools.py +73 -0
  339. package/python/lib/python3.13/importlib/metadata/_meta.py +67 -0
  340. package/python/lib/python3.13/importlib/metadata/_text.py +99 -0
  341. package/python/lib/python3.13/importlib/metadata/diagnose.py +21 -0
  342. package/python/lib/python3.13/importlib/readers.py +12 -0
  343. package/python/lib/python3.13/importlib/resources/__init__.py +43 -0
  344. package/python/lib/python3.13/importlib/resources/_adapters.py +168 -0
  345. package/python/lib/python3.13/importlib/resources/_common.py +211 -0
  346. package/python/lib/python3.13/importlib/resources/_functional.py +81 -0
  347. package/python/lib/python3.13/importlib/resources/_itertools.py +38 -0
  348. package/python/lib/python3.13/importlib/resources/abc.py +173 -0
  349. package/python/lib/python3.13/importlib/resources/readers.py +203 -0
  350. package/python/lib/python3.13/importlib/resources/simple.py +106 -0
  351. package/python/lib/python3.13/importlib/simple.py +14 -0
  352. package/python/lib/python3.13/importlib/util.py +274 -0
  353. package/python/lib/python3.13/inspect.py +3479 -0
  354. package/python/lib/python3.13/io.py +99 -0
  355. package/python/lib/python3.13/ipaddress.py +2440 -0
  356. package/python/lib/python3.13/json/__init__.py +365 -0
  357. package/python/lib/python3.13/json/decoder.py +364 -0
  358. package/python/lib/python3.13/json/encoder.py +446 -0
  359. package/python/lib/python3.13/json/scanner.py +73 -0
  360. package/python/lib/python3.13/json/tool.py +90 -0
  361. package/python/lib/python3.13/keyword.py +64 -0
  362. package/python/lib/python3.13/lib-dynload/.empty +0 -0
  363. package/python/lib/python3.13/lib-dynload/_dbm.cpython-313-x86_64-linux-gnu.so +0 -0
  364. package/python/lib/python3.13/linecache.py +236 -0
  365. package/python/lib/python3.13/locale.py +1987 -0
  366. package/python/lib/python3.13/logging/__init__.py +2330 -0
  367. package/python/lib/python3.13/logging/config.py +1080 -0
  368. package/python/lib/python3.13/logging/handlers.py +1629 -0
  369. package/python/lib/python3.13/lzma.py +364 -0
  370. package/python/lib/python3.13/mailbox.py +2219 -0
  371. package/python/lib/python3.13/mimetypes.py +679 -0
  372. package/python/lib/python3.13/modulefinder.py +671 -0
  373. package/python/lib/python3.13/multiprocessing/__init__.py +37 -0
  374. package/python/lib/python3.13/multiprocessing/connection.py +1216 -0
  375. package/python/lib/python3.13/multiprocessing/context.py +383 -0
  376. package/python/lib/python3.13/multiprocessing/dummy/__init__.py +126 -0
  377. package/python/lib/python3.13/multiprocessing/dummy/connection.py +75 -0
  378. package/python/lib/python3.13/multiprocessing/forkserver.py +373 -0
  379. package/python/lib/python3.13/multiprocessing/heap.py +337 -0
  380. package/python/lib/python3.13/multiprocessing/managers.py +1397 -0
  381. package/python/lib/python3.13/multiprocessing/pool.py +957 -0
  382. package/python/lib/python3.13/multiprocessing/popen_fork.py +97 -0
  383. package/python/lib/python3.13/multiprocessing/popen_forkserver.py +74 -0
  384. package/python/lib/python3.13/multiprocessing/popen_spawn_posix.py +76 -0
  385. package/python/lib/python3.13/multiprocessing/popen_spawn_win32.py +147 -0
  386. package/python/lib/python3.13/multiprocessing/process.py +436 -0
  387. package/python/lib/python3.13/multiprocessing/queues.py +399 -0
  388. package/python/lib/python3.13/multiprocessing/reduction.py +281 -0
  389. package/python/lib/python3.13/multiprocessing/resource_sharer.py +154 -0
  390. package/python/lib/python3.13/multiprocessing/resource_tracker.py +499 -0
  391. package/python/lib/python3.13/multiprocessing/shared_memory.py +544 -0
  392. package/python/lib/python3.13/multiprocessing/sharedctypes.py +240 -0
  393. package/python/lib/python3.13/multiprocessing/spawn.py +307 -0
  394. package/python/lib/python3.13/multiprocessing/synchronize.py +404 -0
  395. package/python/lib/python3.13/multiprocessing/util.py +562 -0
  396. package/python/lib/python3.13/netrc.py +199 -0
  397. package/python/lib/python3.13/ntpath.py +872 -0
  398. package/python/lib/python3.13/nturl2path.py +69 -0
  399. package/python/lib/python3.13/numbers.py +427 -0
  400. package/python/lib/python3.13/opcode.py +115 -0
  401. package/python/lib/python3.13/operator.py +467 -0
  402. package/python/lib/python3.13/optparse.py +1681 -0
  403. package/python/lib/python3.13/os.py +1184 -0
  404. package/python/lib/python3.13/pathlib/__init__.py +12 -0
  405. package/python/lib/python3.13/pathlib/_abc.py +930 -0
  406. package/python/lib/python3.13/pathlib/_local.py +861 -0
  407. package/python/lib/python3.13/pdb.py +2550 -0
  408. package/python/lib/python3.13/pickle.py +1860 -0
  409. package/python/lib/python3.13/pickletools.py +2904 -0
  410. package/python/lib/python3.13/pkgutil.py +529 -0
  411. package/python/lib/python3.13/platform.py +1454 -0
  412. package/python/lib/python3.13/plistlib.py +948 -0
  413. package/python/lib/python3.13/poplib.py +477 -0
  414. package/python/lib/python3.13/posixpath.py +578 -0
  415. package/python/lib/python3.13/pprint.py +658 -0
  416. package/python/lib/python3.13/profile.py +616 -0
  417. package/python/lib/python3.13/pstats.py +778 -0
  418. package/python/lib/python3.13/pty.py +211 -0
  419. package/python/lib/python3.13/py_compile.py +212 -0
  420. package/python/lib/python3.13/pyclbr.py +314 -0
  421. package/python/lib/python3.13/pydoc.py +2861 -0
  422. package/python/lib/python3.13/queue.py +383 -0
  423. package/python/lib/python3.13/quopri.py +237 -0
  424. package/python/lib/python3.13/random.py +1078 -0
  425. package/python/lib/python3.13/re/__init__.py +428 -0
  426. package/python/lib/python3.13/re/_casefix.py +106 -0
  427. package/python/lib/python3.13/re/_compiler.py +768 -0
  428. package/python/lib/python3.13/re/_constants.py +222 -0
  429. package/python/lib/python3.13/re/_parser.py +1081 -0
  430. package/python/lib/python3.13/reprlib.py +230 -0
  431. package/python/lib/python3.13/rlcompleter.py +222 -0
  432. package/python/lib/python3.13/runpy.py +326 -0
  433. package/python/lib/python3.13/sched.py +167 -0
  434. package/python/lib/python3.13/secrets.py +71 -0
  435. package/python/lib/python3.13/selectors.py +603 -0
  436. package/python/lib/python3.13/shelve.py +250 -0
  437. package/python/lib/python3.13/shlex.py +345 -0
  438. package/python/lib/python3.13/shutil.py +1569 -0
  439. package/python/lib/python3.13/signal.py +94 -0
  440. package/python/lib/python3.13/site.py +773 -0
  441. package/python/lib/python3.13/smtplib.py +1123 -0
  442. package/python/lib/python3.13/socket.py +988 -0
  443. package/python/lib/python3.13/socketserver.py +863 -0
  444. package/python/lib/python3.13/sqlite3/__init__.py +70 -0
  445. package/python/lib/python3.13/sqlite3/__main__.py +139 -0
  446. package/python/lib/python3.13/sqlite3/dbapi2.py +108 -0
  447. package/python/lib/python3.13/sqlite3/dump.py +118 -0
  448. package/python/lib/python3.13/sre_compile.py +7 -0
  449. package/python/lib/python3.13/sre_constants.py +7 -0
  450. package/python/lib/python3.13/sre_parse.py +7 -0
  451. package/python/lib/python3.13/ssl.py +1541 -0
  452. package/python/lib/python3.13/stat.py +212 -0
  453. package/python/lib/python3.13/statistics.py +1817 -0
  454. package/python/lib/python3.13/string.py +314 -0
  455. package/python/lib/python3.13/stringprep.py +272 -0
  456. package/python/lib/python3.13/struct.py +15 -0
  457. package/python/lib/python3.13/subprocess.py +2258 -0
  458. package/python/lib/python3.13/symtable.py +414 -0
  459. package/python/lib/python3.13/sysconfig/__init__.py +734 -0
  460. package/python/lib/python3.13/sysconfig/__main__.py +248 -0
  461. package/python/lib/python3.13/tabnanny.py +340 -0
  462. package/python/lib/python3.13/tarfile.py +3136 -0
  463. package/python/lib/python3.13/tempfile.py +958 -0
  464. package/python/lib/python3.13/textwrap.py +497 -0
  465. package/python/lib/python3.13/this.py +28 -0
  466. package/python/lib/python3.13/threading.py +1602 -0
  467. package/python/lib/python3.13/timeit.py +381 -0
  468. package/python/lib/python3.13/token.py +141 -0
  469. package/python/lib/python3.13/tokenize.py +592 -0
  470. package/python/lib/python3.13/tomllib/__init__.py +10 -0
  471. package/python/lib/python3.13/tomllib/_parser.py +703 -0
  472. package/python/lib/python3.13/tomllib/_re.py +107 -0
  473. package/python/lib/python3.13/tomllib/_types.py +10 -0
  474. package/python/lib/python3.13/tomllib/mypy.ini +15 -0
  475. package/python/lib/python3.13/trace.py +754 -0
  476. package/python/lib/python3.13/traceback.py +1639 -0
  477. package/python/lib/python3.13/tracemalloc.py +560 -0
  478. package/python/lib/python3.13/tty.py +73 -0
  479. package/python/lib/python3.13/types.py +346 -0
  480. package/python/lib/python3.13/typing.py +3846 -0
  481. package/python/lib/python3.13/unittest/__init__.py +80 -0
  482. package/python/lib/python3.13/unittest/__main__.py +18 -0
  483. package/python/lib/python3.13/unittest/_log.py +86 -0
  484. package/python/lib/python3.13/unittest/async_case.py +146 -0
  485. package/python/lib/python3.13/unittest/case.py +1478 -0
  486. package/python/lib/python3.13/unittest/loader.py +460 -0
  487. package/python/lib/python3.13/unittest/main.py +280 -0
  488. package/python/lib/python3.13/unittest/mock.py +3189 -0
  489. package/python/lib/python3.13/unittest/result.py +256 -0
  490. package/python/lib/python3.13/unittest/runner.py +292 -0
  491. package/python/lib/python3.13/unittest/signals.py +71 -0
  492. package/python/lib/python3.13/unittest/suite.py +379 -0
  493. package/python/lib/python3.13/unittest/util.py +170 -0
  494. package/python/lib/python3.13/urllib/__init__.py +0 -0
  495. package/python/lib/python3.13/urllib/error.py +74 -0
  496. package/python/lib/python3.13/urllib/parse.py +1264 -0
  497. package/python/lib/python3.13/urllib/request.py +2796 -0
  498. package/python/lib/python3.13/urllib/response.py +84 -0
  499. package/python/lib/python3.13/urllib/robotparser.py +363 -0
  500. package/python/lib/python3.13/uuid.py +784 -0
  501. package/python/lib/python3.13/warnings.py +735 -0
  502. package/python/lib/python3.13/wave.py +665 -0
  503. package/python/lib/python3.13/weakref.py +674 -0
  504. package/python/lib/python3.13/webbrowser.py +724 -0
  505. package/python/lib/python3.13/wsgiref/__init__.py +25 -0
  506. package/python/lib/python3.13/wsgiref/handlers.py +575 -0
  507. package/python/lib/python3.13/wsgiref/headers.py +192 -0
  508. package/python/lib/python3.13/wsgiref/simple_server.py +161 -0
  509. package/python/lib/python3.13/wsgiref/types.py +54 -0
  510. package/python/lib/python3.13/wsgiref/util.py +159 -0
  511. package/python/lib/python3.13/wsgiref/validate.py +438 -0
  512. package/python/lib/python3.13/xml/__init__.py +20 -0
  513. package/python/lib/python3.13/xml/dom/NodeFilter.py +27 -0
  514. package/python/lib/python3.13/xml/dom/__init__.py +140 -0
  515. package/python/lib/python3.13/xml/dom/domreg.py +99 -0
  516. package/python/lib/python3.13/xml/dom/expatbuilder.py +962 -0
  517. package/python/lib/python3.13/xml/dom/minicompat.py +109 -0
  518. package/python/lib/python3.13/xml/dom/minidom.py +2024 -0
  519. package/python/lib/python3.13/xml/dom/pulldom.py +336 -0
  520. package/python/lib/python3.13/xml/dom/xmlbuilder.py +389 -0
  521. package/python/lib/python3.13/xml/etree/ElementInclude.py +186 -0
  522. package/python/lib/python3.13/xml/etree/ElementPath.py +430 -0
  523. package/python/lib/python3.13/xml/etree/ElementTree.py +2116 -0
  524. package/python/lib/python3.13/xml/etree/__init__.py +33 -0
  525. package/python/lib/python3.13/xml/etree/cElementTree.py +3 -0
  526. package/python/lib/python3.13/xml/parsers/__init__.py +8 -0
  527. package/python/lib/python3.13/xml/parsers/expat.py +8 -0
  528. package/python/lib/python3.13/xml/sax/__init__.py +94 -0
  529. package/python/lib/python3.13/xml/sax/_exceptions.py +127 -0
  530. package/python/lib/python3.13/xml/sax/expatreader.py +454 -0
  531. package/python/lib/python3.13/xml/sax/handler.py +387 -0
  532. package/python/lib/python3.13/xml/sax/saxutils.py +369 -0
  533. package/python/lib/python3.13/xml/sax/xmlreader.py +378 -0
  534. package/python/lib/python3.13/xmlrpc/__init__.py +1 -0
  535. package/python/lib/python3.13/xmlrpc/client.py +1503 -0
  536. package/python/lib/python3.13/xmlrpc/server.py +1002 -0
  537. package/python/lib/python3.13/zipapp.py +229 -0
  538. package/python/lib/python3.13/zipfile/__init__.py +2391 -0
  539. package/python/lib/python3.13/zipfile/__main__.py +4 -0
  540. package/python/lib/python3.13/zipfile/_path/__init__.py +452 -0
  541. package/python/lib/python3.13/zipfile/_path/glob.py +113 -0
  542. package/python/lib/python3.13/zipimport.py +803 -0
  543. package/python/lib/python3.13/zoneinfo/__init__.py +34 -0
  544. package/python/lib/python3.13/zoneinfo/_common.py +172 -0
  545. package/python/lib/python3.13/zoneinfo/_tzpath.py +189 -0
  546. package/python/lib/python3.13/zoneinfo/_zoneinfo.py +779 -0
  547. package/python/licenses/LICENSE.bdb.txt +126 -0
  548. package/python/licenses/LICENSE.bzip2.txt +37 -0
  549. package/python/licenses/LICENSE.cpython.txt +771 -0
  550. package/python/licenses/LICENSE.expat.txt +21 -0
  551. package/python/licenses/LICENSE.libX11.txt +942 -0
  552. package/python/licenses/LICENSE.libXau.txt +21 -0
  553. package/python/licenses/LICENSE.libedit.txt +29 -0
  554. package/python/licenses/LICENSE.libffi.txt +21 -0
  555. package/python/licenses/LICENSE.liblzma.txt +13 -0
  556. package/python/licenses/LICENSE.libuuid.txt +27 -0
  557. package/python/licenses/LICENSE.libxcb.txt +30 -0
  558. package/python/licenses/LICENSE.mpdecimal.txt +24 -0
  559. package/python/licenses/LICENSE.ncurses.txt +29 -0
  560. package/python/licenses/LICENSE.openssl-1.1.txt +124 -0
  561. package/python/licenses/LICENSE.openssl-3.txt +177 -0
  562. package/python/licenses/LICENSE.sqlite.txt +23 -0
  563. package/python/licenses/LICENSE.tcl.txt +40 -0
  564. package/python/licenses/LICENSE.tix.txt +54 -0
  565. package/python/licenses/LICENSE.zlib.txt +21 -0
@@ -0,0 +1,2796 @@
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, 307, and 308 redirect errors, and the
15
+ HTTPDigestAuthHandler 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
+ OSError); 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
+
34
+ OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
35
+ the Handler classes, while dealing with requests and responses.
36
+
37
+ Request -- An object that encapsulates the state of a request. The
38
+ state can be as simple as the URL. It can also include extra HTTP
39
+ headers, e.g. a User-Agent.
40
+
41
+ BaseHandler --
42
+
43
+ internals:
44
+ BaseHandler and parent
45
+ _call_chain conventions
46
+
47
+ Example usage:
48
+
49
+ import urllib.request
50
+
51
+ # set up authentication info
52
+ authinfo = urllib.request.HTTPBasicAuthHandler()
53
+ authinfo.add_password(realm='PDQ Application',
54
+ uri='https://mahler:8092/site-updates.py',
55
+ user='klem',
56
+ passwd='geheim$parole')
57
+
58
+ proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"})
59
+
60
+ # build a new opener that adds authentication and caching FTP handlers
61
+ opener = urllib.request.build_opener(proxy_support, authinfo,
62
+ urllib.request.CacheFTPHandler)
63
+
64
+ # install it
65
+ urllib.request.install_opener(opener)
66
+
67
+ f = urllib.request.urlopen('https://www.python.org/')
68
+ """
69
+
70
+ # XXX issues:
71
+ # If an authentication error handler that tries to perform
72
+ # authentication for some reason but fails, how should the error be
73
+ # signalled? The client needs to know the HTTP error code. But if
74
+ # the handler knows that the problem was, e.g., that it didn't know
75
+ # that hash algo that requested in the challenge, it would be good to
76
+ # pass that information along to the client, too.
77
+ # ftp errors aren't handled cleanly
78
+ # check digest against correct (i.e. non-apache) implementation
79
+
80
+ # Possible extensions:
81
+ # complex proxies XXX not sure what exactly was meant by this
82
+ # abstract factory for opener
83
+
84
+ import base64
85
+ import bisect
86
+ import email
87
+ import hashlib
88
+ import http.client
89
+ import io
90
+ import os
91
+ import re
92
+ import socket
93
+ import string
94
+ import sys
95
+ import time
96
+ import tempfile
97
+ import contextlib
98
+ import warnings
99
+
100
+
101
+ from urllib.error import URLError, HTTPError, ContentTooShortError
102
+ from urllib.parse import (
103
+ urlparse, urlsplit, urljoin, unwrap, quote, unquote,
104
+ _splittype, _splithost, _splitport, _splituser, _splitpasswd,
105
+ _splitattr, _splitquery, _splitvalue, _splittag, _to_bytes,
106
+ unquote_to_bytes, urlunparse)
107
+ from urllib.response import addinfourl, addclosehook
108
+
109
+ # check for SSL
110
+ try:
111
+ import ssl
112
+ except ImportError:
113
+ _have_ssl = False
114
+ else:
115
+ _have_ssl = True
116
+
117
+ __all__ = [
118
+ # Classes
119
+ 'Request', 'OpenerDirector', 'BaseHandler', 'HTTPDefaultErrorHandler',
120
+ 'HTTPRedirectHandler', 'HTTPCookieProcessor', 'ProxyHandler',
121
+ 'HTTPPasswordMgr', 'HTTPPasswordMgrWithDefaultRealm',
122
+ 'HTTPPasswordMgrWithPriorAuth', 'AbstractBasicAuthHandler',
123
+ 'HTTPBasicAuthHandler', 'ProxyBasicAuthHandler', 'AbstractDigestAuthHandler',
124
+ 'HTTPDigestAuthHandler', 'ProxyDigestAuthHandler', 'HTTPHandler',
125
+ 'FileHandler', 'FTPHandler', 'CacheFTPHandler', 'DataHandler',
126
+ 'UnknownHandler', 'HTTPErrorProcessor',
127
+ # Functions
128
+ 'urlopen', 'install_opener', 'build_opener',
129
+ 'pathname2url', 'url2pathname', 'getproxies',
130
+ # Legacy interface
131
+ 'urlretrieve', 'urlcleanup', 'URLopener', 'FancyURLopener',
132
+ ]
133
+
134
+ # used in User-Agent header sent
135
+ __version__ = '%d.%d' % sys.version_info[:2]
136
+
137
+ _opener = None
138
+ def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
139
+ *, context=None):
140
+ '''Open the URL url, which can be either a string or a Request object.
141
+
142
+ *data* must be an object specifying additional data to be sent to
143
+ the server, or None if no such data is needed. See Request for
144
+ details.
145
+
146
+ urllib.request module uses HTTP/1.1 and includes a "Connection:close"
147
+ header in its HTTP requests.
148
+
149
+ The optional *timeout* parameter specifies a timeout in seconds for
150
+ blocking operations like the connection attempt (if not specified, the
151
+ global default timeout setting will be used). This only works for HTTP,
152
+ HTTPS and FTP connections.
153
+
154
+ If *context* is specified, it must be a ssl.SSLContext instance describing
155
+ the various SSL options. See HTTPSConnection for more details.
156
+
157
+
158
+ This function always returns an object which can work as a
159
+ context manager and has the properties url, headers, and status.
160
+ See urllib.response.addinfourl for more detail on these properties.
161
+
162
+ For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse
163
+ object slightly modified. In addition to the three new methods above, the
164
+ msg attribute contains the same information as the reason attribute ---
165
+ the reason phrase returned by the server --- instead of the response
166
+ headers as it is specified in the documentation for HTTPResponse.
167
+
168
+ For FTP, file, and data URLs and requests explicitly handled by legacy
169
+ URLopener and FancyURLopener classes, this function returns a
170
+ urllib.response.addinfourl object.
171
+
172
+ Note that None may be returned if no handler handles the request (though
173
+ the default installed global OpenerDirector uses UnknownHandler to ensure
174
+ this never happens).
175
+
176
+ In addition, if proxy settings are detected (for example, when a *_proxy
177
+ environment variable like http_proxy is set), ProxyHandler is default
178
+ installed and makes sure the requests are handled through the proxy.
179
+
180
+ '''
181
+ global _opener
182
+ if context:
183
+ https_handler = HTTPSHandler(context=context)
184
+ opener = build_opener(https_handler)
185
+ elif _opener is None:
186
+ _opener = opener = build_opener()
187
+ else:
188
+ opener = _opener
189
+ return opener.open(url, data, timeout)
190
+
191
+ def install_opener(opener):
192
+ global _opener
193
+ _opener = opener
194
+
195
+ _url_tempfiles = []
196
+ def urlretrieve(url, filename=None, reporthook=None, data=None):
197
+ """
198
+ Retrieve a URL into a temporary location on disk.
199
+
200
+ Requires a URL argument. If a filename is passed, it is used as
201
+ the temporary file location. The reporthook argument should be
202
+ a callable that accepts a block number, a read size, and the
203
+ total file size of the URL target. The data argument should be
204
+ valid URL encoded data.
205
+
206
+ If a filename is passed and the URL points to a local resource,
207
+ the result is a copy from local file to new file.
208
+
209
+ Returns a tuple containing the path to the newly created
210
+ data file as well as the resulting HTTPMessage object.
211
+ """
212
+ url_type, path = _splittype(url)
213
+
214
+ with contextlib.closing(urlopen(url, data)) as fp:
215
+ headers = fp.info()
216
+
217
+ # Just return the local path and the "headers" for file://
218
+ # URLs. No sense in performing a copy unless requested.
219
+ if url_type == "file" and not filename:
220
+ return os.path.normpath(path), headers
221
+
222
+ # Handle temporary file setup.
223
+ if filename:
224
+ tfp = open(filename, 'wb')
225
+ else:
226
+ tfp = tempfile.NamedTemporaryFile(delete=False)
227
+ filename = tfp.name
228
+ _url_tempfiles.append(filename)
229
+
230
+ with tfp:
231
+ result = filename, headers
232
+ bs = 1024*8
233
+ size = -1
234
+ read = 0
235
+ blocknum = 0
236
+ if "content-length" in headers:
237
+ size = int(headers["Content-Length"])
238
+
239
+ if reporthook:
240
+ reporthook(blocknum, bs, size)
241
+
242
+ while block := fp.read(bs):
243
+ read += len(block)
244
+ tfp.write(block)
245
+ blocknum += 1
246
+ if reporthook:
247
+ reporthook(blocknum, bs, size)
248
+
249
+ if size >= 0 and read < size:
250
+ raise ContentTooShortError(
251
+ "retrieval incomplete: got only %i out of %i bytes"
252
+ % (read, size), result)
253
+
254
+ return result
255
+
256
+ def urlcleanup():
257
+ """Clean up temporary files from urlretrieve calls."""
258
+ for temp_file in _url_tempfiles:
259
+ try:
260
+ os.unlink(temp_file)
261
+ except OSError:
262
+ pass
263
+
264
+ del _url_tempfiles[:]
265
+ global _opener
266
+ if _opener:
267
+ _opener = None
268
+
269
+ # copied from cookielib.py
270
+ _cut_port_re = re.compile(r":\d+$", re.ASCII)
271
+ def request_host(request):
272
+ """Return request-host, as defined by RFC 2965.
273
+
274
+ Variation from RFC: returned value is lowercased, for convenient
275
+ comparison.
276
+
277
+ """
278
+ url = request.full_url
279
+ host = urlparse(url)[1]
280
+ if host == "":
281
+ host = request.get_header("Host", "")
282
+
283
+ # remove port, if present
284
+ host = _cut_port_re.sub("", host, 1)
285
+ return host.lower()
286
+
287
+ class Request:
288
+
289
+ def __init__(self, url, data=None, headers={},
290
+ origin_req_host=None, unverifiable=False,
291
+ method=None):
292
+ self.full_url = url
293
+ self.headers = {}
294
+ self.unredirected_hdrs = {}
295
+ self._data = None
296
+ self.data = data
297
+ self._tunnel_host = None
298
+ for key, value in headers.items():
299
+ self.add_header(key, value)
300
+ if origin_req_host is None:
301
+ origin_req_host = request_host(self)
302
+ self.origin_req_host = origin_req_host
303
+ self.unverifiable = unverifiable
304
+ if method:
305
+ self.method = method
306
+
307
+ @property
308
+ def full_url(self):
309
+ if self.fragment:
310
+ return '{}#{}'.format(self._full_url, self.fragment)
311
+ return self._full_url
312
+
313
+ @full_url.setter
314
+ def full_url(self, url):
315
+ # unwrap('<URL:type://host/path>') --> 'type://host/path'
316
+ self._full_url = unwrap(url)
317
+ self._full_url, self.fragment = _splittag(self._full_url)
318
+ self._parse()
319
+
320
+ @full_url.deleter
321
+ def full_url(self):
322
+ self._full_url = None
323
+ self.fragment = None
324
+ self.selector = ''
325
+
326
+ @property
327
+ def data(self):
328
+ return self._data
329
+
330
+ @data.setter
331
+ def data(self, data):
332
+ if data != self._data:
333
+ self._data = data
334
+ # issue 16464
335
+ # if we change data we need to remove content-length header
336
+ # (cause it's most probably calculated for previous value)
337
+ if self.has_header("Content-length"):
338
+ self.remove_header("Content-length")
339
+
340
+ @data.deleter
341
+ def data(self):
342
+ self.data = None
343
+
344
+ def _parse(self):
345
+ self.type, rest = _splittype(self._full_url)
346
+ if self.type is None:
347
+ raise ValueError("unknown url type: %r" % self.full_url)
348
+ self.host, self.selector = _splithost(rest)
349
+ if self.host:
350
+ self.host = unquote(self.host)
351
+
352
+ def get_method(self):
353
+ """Return a string indicating the HTTP request method."""
354
+ default_method = "POST" if self.data is not None else "GET"
355
+ return getattr(self, 'method', default_method)
356
+
357
+ def get_full_url(self):
358
+ return self.full_url
359
+
360
+ def set_proxy(self, host, type):
361
+ if self.type == 'https' and not self._tunnel_host:
362
+ self._tunnel_host = self.host
363
+ else:
364
+ self.type= type
365
+ self.selector = self.full_url
366
+ self.host = host
367
+
368
+ def has_proxy(self):
369
+ return self.selector == self.full_url
370
+
371
+ def add_header(self, key, val):
372
+ # useful for something like authentication
373
+ self.headers[key.capitalize()] = val
374
+
375
+ def add_unredirected_header(self, key, val):
376
+ # will not be added to a redirected request
377
+ self.unredirected_hdrs[key.capitalize()] = val
378
+
379
+ def has_header(self, header_name):
380
+ return (header_name in self.headers or
381
+ header_name in self.unredirected_hdrs)
382
+
383
+ def get_header(self, header_name, default=None):
384
+ return self.headers.get(
385
+ header_name,
386
+ self.unredirected_hdrs.get(header_name, default))
387
+
388
+ def remove_header(self, header_name):
389
+ self.headers.pop(header_name, None)
390
+ self.unredirected_hdrs.pop(header_name, None)
391
+
392
+ def header_items(self):
393
+ hdrs = {**self.unredirected_hdrs, **self.headers}
394
+ return list(hdrs.items())
395
+
396
+ class OpenerDirector:
397
+ def __init__(self):
398
+ client_version = "Python-urllib/%s" % __version__
399
+ self.addheaders = [('User-agent', client_version)]
400
+ # self.handlers is retained only for backward compatibility
401
+ self.handlers = []
402
+ # manage the individual handlers
403
+ self.handle_open = {}
404
+ self.handle_error = {}
405
+ self.process_response = {}
406
+ self.process_request = {}
407
+
408
+ def add_handler(self, handler):
409
+ if not hasattr(handler, "add_parent"):
410
+ raise TypeError("expected BaseHandler instance, got %r" %
411
+ type(handler))
412
+
413
+ added = False
414
+ for meth in dir(handler):
415
+ if meth in ["redirect_request", "do_open", "proxy_open"]:
416
+ # oops, coincidental match
417
+ continue
418
+
419
+ i = meth.find("_")
420
+ protocol = meth[:i]
421
+ condition = meth[i+1:]
422
+
423
+ if condition.startswith("error"):
424
+ j = condition.find("_") + i + 1
425
+ kind = meth[j+1:]
426
+ try:
427
+ kind = int(kind)
428
+ except ValueError:
429
+ pass
430
+ lookup = self.handle_error.get(protocol, {})
431
+ self.handle_error[protocol] = lookup
432
+ elif condition == "open":
433
+ kind = protocol
434
+ lookup = self.handle_open
435
+ elif condition == "response":
436
+ kind = protocol
437
+ lookup = self.process_response
438
+ elif condition == "request":
439
+ kind = protocol
440
+ lookup = self.process_request
441
+ else:
442
+ continue
443
+
444
+ handlers = lookup.setdefault(kind, [])
445
+ if handlers:
446
+ bisect.insort(handlers, handler)
447
+ else:
448
+ handlers.append(handler)
449
+ added = True
450
+
451
+ if added:
452
+ bisect.insort(self.handlers, handler)
453
+ handler.add_parent(self)
454
+
455
+ def close(self):
456
+ # Only exists for backwards compatibility.
457
+ pass
458
+
459
+ def _call_chain(self, chain, kind, meth_name, *args):
460
+ # Handlers raise an exception if no one else should try to handle
461
+ # the request, or return None if they can't but another handler
462
+ # could. Otherwise, they return the response.
463
+ handlers = chain.get(kind, ())
464
+ for handler in handlers:
465
+ func = getattr(handler, meth_name)
466
+ result = func(*args)
467
+ if result is not None:
468
+ return result
469
+
470
+ def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
471
+ # accept a URL or a Request object
472
+ if isinstance(fullurl, str):
473
+ req = Request(fullurl, data)
474
+ else:
475
+ req = fullurl
476
+ if data is not None:
477
+ req.data = data
478
+
479
+ req.timeout = timeout
480
+ protocol = req.type
481
+
482
+ # pre-process request
483
+ meth_name = protocol+"_request"
484
+ for processor in self.process_request.get(protocol, []):
485
+ meth = getattr(processor, meth_name)
486
+ req = meth(req)
487
+
488
+ sys.audit('urllib.Request', req.full_url, req.data, req.headers, req.get_method())
489
+ response = self._open(req, data)
490
+
491
+ # post-process response
492
+ meth_name = protocol+"_response"
493
+ for processor in self.process_response.get(protocol, []):
494
+ meth = getattr(processor, meth_name)
495
+ response = meth(req, response)
496
+
497
+ return response
498
+
499
+ def _open(self, req, data=None):
500
+ result = self._call_chain(self.handle_open, 'default',
501
+ 'default_open', req)
502
+ if result:
503
+ return result
504
+
505
+ protocol = req.type
506
+ result = self._call_chain(self.handle_open, protocol, protocol +
507
+ '_open', req)
508
+ if result:
509
+ return result
510
+
511
+ return self._call_chain(self.handle_open, 'unknown',
512
+ 'unknown_open', req)
513
+
514
+ def error(self, proto, *args):
515
+ if proto in ('http', 'https'):
516
+ # XXX http[s] protocols are special-cased
517
+ dict = self.handle_error['http'] # https is not different than http
518
+ proto = args[2] # YUCK!
519
+ meth_name = 'http_error_%s' % proto
520
+ http_err = 1
521
+ orig_args = args
522
+ else:
523
+ dict = self.handle_error
524
+ meth_name = proto + '_error'
525
+ http_err = 0
526
+ args = (dict, proto, meth_name) + args
527
+ result = self._call_chain(*args)
528
+ if result:
529
+ return result
530
+
531
+ if http_err:
532
+ args = (dict, 'default', 'http_error_default') + orig_args
533
+ return self._call_chain(*args)
534
+
535
+ # XXX probably also want an abstract factory that knows when it makes
536
+ # sense to skip a superclass in favor of a subclass and when it might
537
+ # make sense to include both
538
+
539
+ def build_opener(*handlers):
540
+ """Create an opener object from a list of handlers.
541
+
542
+ The opener will use several default handlers, including support
543
+ for HTTP, FTP and when applicable HTTPS.
544
+
545
+ If any of the handlers passed as arguments are subclasses of the
546
+ default handlers, the default handlers will not be used.
547
+ """
548
+ opener = OpenerDirector()
549
+ default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
550
+ HTTPDefaultErrorHandler, HTTPRedirectHandler,
551
+ FTPHandler, FileHandler, HTTPErrorProcessor,
552
+ DataHandler]
553
+ if hasattr(http.client, "HTTPSConnection"):
554
+ default_classes.append(HTTPSHandler)
555
+ skip = set()
556
+ for klass in default_classes:
557
+ for check in handlers:
558
+ if isinstance(check, type):
559
+ if issubclass(check, klass):
560
+ skip.add(klass)
561
+ elif isinstance(check, klass):
562
+ skip.add(klass)
563
+ for klass in skip:
564
+ default_classes.remove(klass)
565
+
566
+ for klass in default_classes:
567
+ opener.add_handler(klass())
568
+
569
+ for h in handlers:
570
+ if isinstance(h, type):
571
+ h = h()
572
+ opener.add_handler(h)
573
+ return opener
574
+
575
+ class BaseHandler:
576
+ handler_order = 500
577
+
578
+ def add_parent(self, parent):
579
+ self.parent = parent
580
+
581
+ def close(self):
582
+ # Only exists for backwards compatibility
583
+ pass
584
+
585
+ def __lt__(self, other):
586
+ if not hasattr(other, "handler_order"):
587
+ # Try to preserve the old behavior of having custom classes
588
+ # inserted after default ones (works only for custom user
589
+ # classes which are not aware of handler_order).
590
+ return True
591
+ return self.handler_order < other.handler_order
592
+
593
+
594
+ class HTTPErrorProcessor(BaseHandler):
595
+ """Process HTTP error responses."""
596
+ handler_order = 1000 # after all other processing
597
+
598
+ def http_response(self, request, response):
599
+ code, msg, hdrs = response.code, response.msg, response.info()
600
+
601
+ # According to RFC 2616, "2xx" code indicates that the client's
602
+ # request was successfully received, understood, and accepted.
603
+ if not (200 <= code < 300):
604
+ response = self.parent.error(
605
+ 'http', request, response, code, msg, hdrs)
606
+
607
+ return response
608
+
609
+ https_response = http_response
610
+
611
+ class HTTPDefaultErrorHandler(BaseHandler):
612
+ def http_error_default(self, req, fp, code, msg, hdrs):
613
+ raise HTTPError(req.full_url, code, msg, hdrs, fp)
614
+
615
+ class HTTPRedirectHandler(BaseHandler):
616
+ # maximum number of redirections to any single URL
617
+ # this is needed because of the state that cookies introduce
618
+ max_repeats = 4
619
+ # maximum total number of redirections (regardless of URL) before
620
+ # assuming we're in a loop
621
+ max_redirections = 10
622
+
623
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
624
+ """Return a Request or None in response to a redirect.
625
+
626
+ This is called by the http_error_30x methods when a
627
+ redirection response is received. If a redirection should
628
+ take place, return a new Request to allow http_error_30x to
629
+ perform the redirect. Otherwise, raise HTTPError if no-one
630
+ else should try to handle this url. Return None if you can't
631
+ but another Handler might.
632
+ """
633
+ m = req.get_method()
634
+ if (not (code in (301, 302, 303, 307, 308) and m in ("GET", "HEAD")
635
+ or code in (301, 302, 303) and m == "POST")):
636
+ raise HTTPError(req.full_url, code, msg, headers, fp)
637
+
638
+ # Strictly (according to RFC 2616), 301 or 302 in response to
639
+ # a POST MUST NOT cause a redirection without confirmation
640
+ # from the user (of urllib.request, in this case). In practice,
641
+ # essentially all clients do redirect in this case, so we do
642
+ # the same.
643
+
644
+ # Be conciliant with URIs containing a space. This is mainly
645
+ # redundant with the more complete encoding done in http_error_302(),
646
+ # but it is kept for compatibility with other callers.
647
+ newurl = newurl.replace(' ', '%20')
648
+
649
+ CONTENT_HEADERS = ("content-length", "content-type")
650
+ newheaders = {k: v for k, v in req.headers.items()
651
+ if k.lower() not in CONTENT_HEADERS}
652
+ return Request(newurl,
653
+ method="HEAD" if m == "HEAD" else "GET",
654
+ headers=newheaders,
655
+ origin_req_host=req.origin_req_host,
656
+ unverifiable=True)
657
+
658
+ # Implementation note: To avoid the server sending us into an
659
+ # infinite loop, the request object needs to track what URLs we
660
+ # have already seen. Do this by adding a handler-specific
661
+ # attribute to the Request object.
662
+ def http_error_302(self, req, fp, code, msg, headers):
663
+ # Some servers (incorrectly) return multiple Location headers
664
+ # (so probably same goes for URI). Use first header.
665
+ if "location" in headers:
666
+ newurl = headers["location"]
667
+ elif "uri" in headers:
668
+ newurl = headers["uri"]
669
+ else:
670
+ return
671
+
672
+ # fix a possible malformed URL
673
+ urlparts = urlparse(newurl)
674
+
675
+ # For security reasons we don't allow redirection to anything other
676
+ # than http, https or ftp.
677
+
678
+ if urlparts.scheme not in ('http', 'https', 'ftp', ''):
679
+ raise HTTPError(
680
+ newurl, code,
681
+ "%s - Redirection to url '%s' is not allowed" % (msg, newurl),
682
+ headers, fp)
683
+
684
+ if not urlparts.path and urlparts.netloc:
685
+ urlparts = list(urlparts)
686
+ urlparts[2] = "/"
687
+ newurl = urlunparse(urlparts)
688
+
689
+ # http.client.parse_headers() decodes as ISO-8859-1. Recover the
690
+ # original bytes and percent-encode non-ASCII bytes, and any special
691
+ # characters such as the space.
692
+ newurl = quote(
693
+ newurl, encoding="iso-8859-1", safe=string.punctuation)
694
+ newurl = urljoin(req.full_url, newurl)
695
+
696
+ # XXX Probably want to forget about the state of the current
697
+ # request, although that might interact poorly with other
698
+ # handlers that also use handler-specific request attributes
699
+ new = self.redirect_request(req, fp, code, msg, headers, newurl)
700
+ if new is None:
701
+ return
702
+
703
+ # loop detection
704
+ # .redirect_dict has a key url if url was previously visited.
705
+ if hasattr(req, 'redirect_dict'):
706
+ visited = new.redirect_dict = req.redirect_dict
707
+ if (visited.get(newurl, 0) >= self.max_repeats or
708
+ len(visited) >= self.max_redirections):
709
+ raise HTTPError(req.full_url, code,
710
+ self.inf_msg + msg, headers, fp)
711
+ else:
712
+ visited = new.redirect_dict = req.redirect_dict = {}
713
+ visited[newurl] = visited.get(newurl, 0) + 1
714
+
715
+ # Don't close the fp until we are sure that we won't use it
716
+ # with HTTPError.
717
+ fp.read()
718
+ fp.close()
719
+
720
+ return self.parent.open(new, timeout=req.timeout)
721
+
722
+ http_error_301 = http_error_303 = http_error_307 = http_error_308 = http_error_302
723
+
724
+ inf_msg = "The HTTP server returned a redirect error that would " \
725
+ "lead to an infinite loop.\n" \
726
+ "The last 30x error message was:\n"
727
+
728
+
729
+ def _parse_proxy(proxy):
730
+ """Return (scheme, user, password, host/port) given a URL or an authority.
731
+
732
+ If a URL is supplied, it must have an authority (host:port) component.
733
+ According to RFC 3986, having an authority component means the URL must
734
+ have two slashes after the scheme.
735
+ """
736
+ scheme, r_scheme = _splittype(proxy)
737
+ if not r_scheme.startswith("/"):
738
+ # authority
739
+ scheme = None
740
+ authority = proxy
741
+ else:
742
+ # URL
743
+ if not r_scheme.startswith("//"):
744
+ raise ValueError("proxy URL with no authority: %r" % proxy)
745
+ # We have an authority, so for RFC 3986-compliant URLs (by ss 3.
746
+ # and 3.3.), path is empty or starts with '/'
747
+ if '@' in r_scheme:
748
+ host_separator = r_scheme.find('@')
749
+ end = r_scheme.find("/", host_separator)
750
+ else:
751
+ end = r_scheme.find("/", 2)
752
+ if end == -1:
753
+ end = None
754
+ authority = r_scheme[2:end]
755
+ userinfo, hostport = _splituser(authority)
756
+ if userinfo is not None:
757
+ user, password = _splitpasswd(userinfo)
758
+ else:
759
+ user = password = None
760
+ return scheme, user, password, hostport
761
+
762
+ class ProxyHandler(BaseHandler):
763
+ # Proxies must be in front
764
+ handler_order = 100
765
+
766
+ def __init__(self, proxies=None):
767
+ if proxies is None:
768
+ proxies = getproxies()
769
+ assert hasattr(proxies, 'keys'), "proxies must be a mapping"
770
+ self.proxies = proxies
771
+ for type, url in proxies.items():
772
+ type = type.lower()
773
+ setattr(self, '%s_open' % type,
774
+ lambda r, proxy=url, type=type, meth=self.proxy_open:
775
+ meth(r, proxy, type))
776
+
777
+ def proxy_open(self, req, proxy, type):
778
+ orig_type = req.type
779
+ proxy_type, user, password, hostport = _parse_proxy(proxy)
780
+ if proxy_type is None:
781
+ proxy_type = orig_type
782
+
783
+ if req.host and proxy_bypass(req.host):
784
+ return None
785
+
786
+ if user and password:
787
+ user_pass = '%s:%s' % (unquote(user),
788
+ unquote(password))
789
+ creds = base64.b64encode(user_pass.encode()).decode("ascii")
790
+ req.add_header('Proxy-authorization', 'Basic ' + creds)
791
+ hostport = unquote(hostport)
792
+ req.set_proxy(hostport, proxy_type)
793
+ if orig_type == proxy_type or orig_type == 'https':
794
+ # let other handlers take care of it
795
+ return None
796
+ else:
797
+ # need to start over, because the other handlers don't
798
+ # grok the proxy's URL type
799
+ # e.g. if we have a constructor arg proxies like so:
800
+ # {'http': 'ftp://proxy.example.com'}, we may end up turning
801
+ # a request for http://acme.example.com/a into one for
802
+ # ftp://proxy.example.com/a
803
+ return self.parent.open(req, timeout=req.timeout)
804
+
805
+ class HTTPPasswordMgr:
806
+
807
+ def __init__(self):
808
+ self.passwd = {}
809
+
810
+ def add_password(self, realm, uri, user, passwd):
811
+ # uri could be a single URI or a sequence
812
+ if isinstance(uri, str):
813
+ uri = [uri]
814
+ if realm not in self.passwd:
815
+ self.passwd[realm] = {}
816
+ for default_port in True, False:
817
+ reduced_uri = tuple(
818
+ self.reduce_uri(u, default_port) for u in uri)
819
+ self.passwd[realm][reduced_uri] = (user, passwd)
820
+
821
+ def find_user_password(self, realm, authuri):
822
+ domains = self.passwd.get(realm, {})
823
+ for default_port in True, False:
824
+ reduced_authuri = self.reduce_uri(authuri, default_port)
825
+ for uris, authinfo in domains.items():
826
+ for uri in uris:
827
+ if self.is_suburi(uri, reduced_authuri):
828
+ return authinfo
829
+ return None, None
830
+
831
+ def reduce_uri(self, uri, default_port=True):
832
+ """Accept authority or URI and extract only the authority and path."""
833
+ # note HTTP URLs do not have a userinfo component
834
+ parts = urlsplit(uri)
835
+ if parts[1]:
836
+ # URI
837
+ scheme = parts[0]
838
+ authority = parts[1]
839
+ path = parts[2] or '/'
840
+ else:
841
+ # host or host:port
842
+ scheme = None
843
+ authority = uri
844
+ path = '/'
845
+ host, port = _splitport(authority)
846
+ if default_port and port is None and scheme is not None:
847
+ dport = {"http": 80,
848
+ "https": 443,
849
+ }.get(scheme)
850
+ if dport is not None:
851
+ authority = "%s:%d" % (host, dport)
852
+ return authority, path
853
+
854
+ def is_suburi(self, base, test):
855
+ """Check if test is below base in a URI tree
856
+
857
+ Both args must be URIs in reduced form.
858
+ """
859
+ if base == test:
860
+ return True
861
+ if base[0] != test[0]:
862
+ return False
863
+ prefix = base[1]
864
+ if prefix[-1:] != '/':
865
+ prefix += '/'
866
+ return test[1].startswith(prefix)
867
+
868
+
869
+ class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
870
+
871
+ def find_user_password(self, realm, authuri):
872
+ user, password = HTTPPasswordMgr.find_user_password(self, realm,
873
+ authuri)
874
+ if user is not None:
875
+ return user, password
876
+ return HTTPPasswordMgr.find_user_password(self, None, authuri)
877
+
878
+
879
+ class HTTPPasswordMgrWithPriorAuth(HTTPPasswordMgrWithDefaultRealm):
880
+
881
+ def __init__(self):
882
+ self.authenticated = {}
883
+ super().__init__()
884
+
885
+ def add_password(self, realm, uri, user, passwd, is_authenticated=False):
886
+ self.update_authenticated(uri, is_authenticated)
887
+ # Add a default for prior auth requests
888
+ if realm is not None:
889
+ super().add_password(None, uri, user, passwd)
890
+ super().add_password(realm, uri, user, passwd)
891
+
892
+ def update_authenticated(self, uri, is_authenticated=False):
893
+ # uri could be a single URI or a sequence
894
+ if isinstance(uri, str):
895
+ uri = [uri]
896
+
897
+ for default_port in True, False:
898
+ for u in uri:
899
+ reduced_uri = self.reduce_uri(u, default_port)
900
+ self.authenticated[reduced_uri] = is_authenticated
901
+
902
+ def is_authenticated(self, authuri):
903
+ for default_port in True, False:
904
+ reduced_authuri = self.reduce_uri(authuri, default_port)
905
+ for uri in self.authenticated:
906
+ if self.is_suburi(uri, reduced_authuri):
907
+ return self.authenticated[uri]
908
+
909
+
910
+ class AbstractBasicAuthHandler:
911
+
912
+ # XXX this allows for multiple auth-schemes, but will stupidly pick
913
+ # the last one with a realm specified.
914
+
915
+ # allow for double- and single-quoted realm values
916
+ # (single quotes are a violation of the RFC, but appear in the wild)
917
+ rx = re.compile('(?:^|,)' # start of the string or ','
918
+ '[ \t]*' # optional whitespaces
919
+ '([^ \t,]+)' # scheme like "Basic"
920
+ '[ \t]+' # mandatory whitespaces
921
+ # realm=xxx
922
+ # realm='xxx'
923
+ # realm="xxx"
924
+ 'realm=(["\']?)([^"\']*)\\2',
925
+ re.I)
926
+
927
+ # XXX could pre-emptively send auth info already accepted (RFC 2617,
928
+ # end of section 2, and section 1.2 immediately after "credentials"
929
+ # production).
930
+
931
+ def __init__(self, password_mgr=None):
932
+ if password_mgr is None:
933
+ password_mgr = HTTPPasswordMgr()
934
+ self.passwd = password_mgr
935
+ self.add_password = self.passwd.add_password
936
+
937
+ def _parse_realm(self, header):
938
+ # parse WWW-Authenticate header: accept multiple challenges per header
939
+ found_challenge = False
940
+ for mo in AbstractBasicAuthHandler.rx.finditer(header):
941
+ scheme, quote, realm = mo.groups()
942
+ if quote not in ['"', "'"]:
943
+ warnings.warn("Basic Auth Realm was unquoted",
944
+ UserWarning, 3)
945
+
946
+ yield (scheme, realm)
947
+
948
+ found_challenge = True
949
+
950
+ if not found_challenge:
951
+ if header:
952
+ scheme = header.split()[0]
953
+ else:
954
+ scheme = ''
955
+ yield (scheme, None)
956
+
957
+ def http_error_auth_reqed(self, authreq, host, req, headers):
958
+ # host may be an authority (without userinfo) or a URL with an
959
+ # authority
960
+ headers = headers.get_all(authreq)
961
+ if not headers:
962
+ # no header found
963
+ return
964
+
965
+ unsupported = None
966
+ for header in headers:
967
+ for scheme, realm in self._parse_realm(header):
968
+ if scheme.lower() != 'basic':
969
+ unsupported = scheme
970
+ continue
971
+
972
+ if realm is not None:
973
+ # Use the first matching Basic challenge.
974
+ # Ignore following challenges even if they use the Basic
975
+ # scheme.
976
+ return self.retry_http_basic_auth(host, req, realm)
977
+
978
+ if unsupported is not None:
979
+ raise ValueError("AbstractBasicAuthHandler does not "
980
+ "support the following scheme: %r"
981
+ % (scheme,))
982
+
983
+ def retry_http_basic_auth(self, host, req, realm):
984
+ user, pw = self.passwd.find_user_password(realm, host)
985
+ if pw is not None:
986
+ raw = "%s:%s" % (user, pw)
987
+ auth = "Basic " + base64.b64encode(raw.encode()).decode("ascii")
988
+ if req.get_header(self.auth_header, None) == auth:
989
+ return None
990
+ req.add_unredirected_header(self.auth_header, auth)
991
+ return self.parent.open(req, timeout=req.timeout)
992
+ else:
993
+ return None
994
+
995
+ def http_request(self, req):
996
+ if (not hasattr(self.passwd, 'is_authenticated') or
997
+ not self.passwd.is_authenticated(req.full_url)):
998
+ return req
999
+
1000
+ if not req.has_header('Authorization'):
1001
+ user, passwd = self.passwd.find_user_password(None, req.full_url)
1002
+ credentials = '{0}:{1}'.format(user, passwd).encode()
1003
+ auth_str = base64.standard_b64encode(credentials).decode()
1004
+ req.add_unredirected_header('Authorization',
1005
+ 'Basic {}'.format(auth_str.strip()))
1006
+ return req
1007
+
1008
+ def http_response(self, req, response):
1009
+ if hasattr(self.passwd, 'is_authenticated'):
1010
+ if 200 <= response.code < 300:
1011
+ self.passwd.update_authenticated(req.full_url, True)
1012
+ else:
1013
+ self.passwd.update_authenticated(req.full_url, False)
1014
+ return response
1015
+
1016
+ https_request = http_request
1017
+ https_response = http_response
1018
+
1019
+
1020
+
1021
+ class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
1022
+
1023
+ auth_header = 'Authorization'
1024
+
1025
+ def http_error_401(self, req, fp, code, msg, headers):
1026
+ url = req.full_url
1027
+ response = self.http_error_auth_reqed('www-authenticate',
1028
+ url, req, headers)
1029
+ return response
1030
+
1031
+
1032
+ class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
1033
+
1034
+ auth_header = 'Proxy-authorization'
1035
+
1036
+ def http_error_407(self, req, fp, code, msg, headers):
1037
+ # http_error_auth_reqed requires that there is no userinfo component in
1038
+ # authority. Assume there isn't one, since urllib.request does not (and
1039
+ # should not, RFC 3986 s. 3.2.1) support requests for URLs containing
1040
+ # userinfo.
1041
+ authority = req.host
1042
+ response = self.http_error_auth_reqed('proxy-authenticate',
1043
+ authority, req, headers)
1044
+ return response
1045
+
1046
+
1047
+ # Return n random bytes.
1048
+ _randombytes = os.urandom
1049
+
1050
+
1051
+ class AbstractDigestAuthHandler:
1052
+ # Digest authentication is specified in RFC 2617.
1053
+
1054
+ # XXX The client does not inspect the Authentication-Info header
1055
+ # in a successful response.
1056
+
1057
+ # XXX It should be possible to test this implementation against
1058
+ # a mock server that just generates a static set of challenges.
1059
+
1060
+ # XXX qop="auth-int" supports is shaky
1061
+
1062
+ def __init__(self, passwd=None):
1063
+ if passwd is None:
1064
+ passwd = HTTPPasswordMgr()
1065
+ self.passwd = passwd
1066
+ self.add_password = self.passwd.add_password
1067
+ self.retried = 0
1068
+ self.nonce_count = 0
1069
+ self.last_nonce = None
1070
+
1071
+ def reset_retry_count(self):
1072
+ self.retried = 0
1073
+
1074
+ def http_error_auth_reqed(self, auth_header, host, req, headers):
1075
+ authreq = headers.get(auth_header, None)
1076
+ if self.retried > 5:
1077
+ # Don't fail endlessly - if we failed once, we'll probably
1078
+ # fail a second time. Hm. Unless the Password Manager is
1079
+ # prompting for the information. Crap. This isn't great
1080
+ # but it's better than the current 'repeat until recursion
1081
+ # depth exceeded' approach <wink>
1082
+ raise HTTPError(req.full_url, 401, "digest auth failed",
1083
+ headers, None)
1084
+ else:
1085
+ self.retried += 1
1086
+ if authreq:
1087
+ scheme = authreq.split()[0]
1088
+ if scheme.lower() == 'digest':
1089
+ return self.retry_http_digest_auth(req, authreq)
1090
+ elif scheme.lower() != 'basic':
1091
+ raise ValueError("AbstractDigestAuthHandler does not support"
1092
+ " the following scheme: '%s'" % scheme)
1093
+
1094
+ def retry_http_digest_auth(self, req, auth):
1095
+ token, challenge = auth.split(' ', 1)
1096
+ chal = parse_keqv_list(filter(None, parse_http_list(challenge)))
1097
+ auth = self.get_authorization(req, chal)
1098
+ if auth:
1099
+ auth_val = 'Digest %s' % auth
1100
+ if req.headers.get(self.auth_header, None) == auth_val:
1101
+ return None
1102
+ req.add_unredirected_header(self.auth_header, auth_val)
1103
+ resp = self.parent.open(req, timeout=req.timeout)
1104
+ return resp
1105
+
1106
+ def get_cnonce(self, nonce):
1107
+ # The cnonce-value is an opaque
1108
+ # quoted string value provided by the client and used by both client
1109
+ # and server to avoid chosen plaintext attacks, to provide mutual
1110
+ # authentication, and to provide some message integrity protection.
1111
+ # This isn't a fabulous effort, but it's probably Good Enough.
1112
+ s = "%s:%s:%s:" % (self.nonce_count, nonce, time.ctime())
1113
+ b = s.encode("ascii") + _randombytes(8)
1114
+ dig = hashlib.sha1(b).hexdigest()
1115
+ return dig[:16]
1116
+
1117
+ def get_authorization(self, req, chal):
1118
+ try:
1119
+ realm = chal['realm']
1120
+ nonce = chal['nonce']
1121
+ qop = chal.get('qop')
1122
+ algorithm = chal.get('algorithm', 'MD5')
1123
+ # mod_digest doesn't send an opaque, even though it isn't
1124
+ # supposed to be optional
1125
+ opaque = chal.get('opaque', None)
1126
+ except KeyError:
1127
+ return None
1128
+
1129
+ H, KD = self.get_algorithm_impls(algorithm)
1130
+ if H is None:
1131
+ return None
1132
+
1133
+ user, pw = self.passwd.find_user_password(realm, req.full_url)
1134
+ if user is None:
1135
+ return None
1136
+
1137
+ # XXX not implemented yet
1138
+ if req.data is not None:
1139
+ entdig = self.get_entity_digest(req.data, chal)
1140
+ else:
1141
+ entdig = None
1142
+
1143
+ A1 = "%s:%s:%s" % (user, realm, pw)
1144
+ A2 = "%s:%s" % (req.get_method(),
1145
+ # XXX selector: what about proxies and full urls
1146
+ req.selector)
1147
+ # NOTE: As per RFC 2617, when server sends "auth,auth-int", the client could use either `auth`
1148
+ # or `auth-int` to the response back. we use `auth` to send the response back.
1149
+ if qop is None:
1150
+ respdig = KD(H(A1), "%s:%s" % (nonce, H(A2)))
1151
+ elif 'auth' in qop.split(','):
1152
+ if nonce == self.last_nonce:
1153
+ self.nonce_count += 1
1154
+ else:
1155
+ self.nonce_count = 1
1156
+ self.last_nonce = nonce
1157
+ ncvalue = '%08x' % self.nonce_count
1158
+ cnonce = self.get_cnonce(nonce)
1159
+ noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, 'auth', H(A2))
1160
+ respdig = KD(H(A1), noncebit)
1161
+ else:
1162
+ # XXX handle auth-int.
1163
+ raise URLError("qop '%s' is not supported." % qop)
1164
+
1165
+ # XXX should the partial digests be encoded too?
1166
+
1167
+ base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
1168
+ 'response="%s"' % (user, realm, nonce, req.selector,
1169
+ respdig)
1170
+ if opaque:
1171
+ base += ', opaque="%s"' % opaque
1172
+ if entdig:
1173
+ base += ', digest="%s"' % entdig
1174
+ base += ', algorithm="%s"' % algorithm
1175
+ if qop:
1176
+ base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
1177
+ return base
1178
+
1179
+ def get_algorithm_impls(self, algorithm):
1180
+ # lambdas assume digest modules are imported at the top level
1181
+ if algorithm == 'MD5':
1182
+ H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest()
1183
+ elif algorithm == 'SHA':
1184
+ H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest()
1185
+ # XXX MD5-sess
1186
+ else:
1187
+ raise ValueError("Unsupported digest authentication "
1188
+ "algorithm %r" % algorithm)
1189
+ KD = lambda s, d: H("%s:%s" % (s, d))
1190
+ return H, KD
1191
+
1192
+ def get_entity_digest(self, data, chal):
1193
+ # XXX not implemented yet
1194
+ return None
1195
+
1196
+
1197
+ class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1198
+ """An authentication protocol defined by RFC 2069
1199
+
1200
+ Digest authentication improves on basic authentication because it
1201
+ does not transmit passwords in the clear.
1202
+ """
1203
+
1204
+ auth_header = 'Authorization'
1205
+ handler_order = 490 # before Basic auth
1206
+
1207
+ def http_error_401(self, req, fp, code, msg, headers):
1208
+ host = urlparse(req.full_url)[1]
1209
+ retry = self.http_error_auth_reqed('www-authenticate',
1210
+ host, req, headers)
1211
+ self.reset_retry_count()
1212
+ return retry
1213
+
1214
+
1215
+ class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
1216
+
1217
+ auth_header = 'Proxy-Authorization'
1218
+ handler_order = 490 # before Basic auth
1219
+
1220
+ def http_error_407(self, req, fp, code, msg, headers):
1221
+ host = req.host
1222
+ retry = self.http_error_auth_reqed('proxy-authenticate',
1223
+ host, req, headers)
1224
+ self.reset_retry_count()
1225
+ return retry
1226
+
1227
+ class AbstractHTTPHandler(BaseHandler):
1228
+
1229
+ def __init__(self, debuglevel=None):
1230
+ self._debuglevel = debuglevel if debuglevel is not None else http.client.HTTPConnection.debuglevel
1231
+
1232
+ def set_http_debuglevel(self, level):
1233
+ self._debuglevel = level
1234
+
1235
+ def _get_content_length(self, request):
1236
+ return http.client.HTTPConnection._get_content_length(
1237
+ request.data,
1238
+ request.get_method())
1239
+
1240
+ def do_request_(self, request):
1241
+ host = request.host
1242
+ if not host:
1243
+ raise URLError('no host given')
1244
+
1245
+ if request.data is not None: # POST
1246
+ data = request.data
1247
+ if isinstance(data, str):
1248
+ msg = "POST data should be bytes, an iterable of bytes, " \
1249
+ "or a file object. It cannot be of type str."
1250
+ raise TypeError(msg)
1251
+ if not request.has_header('Content-type'):
1252
+ request.add_unredirected_header(
1253
+ 'Content-type',
1254
+ 'application/x-www-form-urlencoded')
1255
+ if (not request.has_header('Content-length')
1256
+ and not request.has_header('Transfer-encoding')):
1257
+ content_length = self._get_content_length(request)
1258
+ if content_length is not None:
1259
+ request.add_unredirected_header(
1260
+ 'Content-length', str(content_length))
1261
+ else:
1262
+ request.add_unredirected_header(
1263
+ 'Transfer-encoding', 'chunked')
1264
+
1265
+ sel_host = host
1266
+ if request.has_proxy():
1267
+ scheme, sel = _splittype(request.selector)
1268
+ sel_host, sel_path = _splithost(sel)
1269
+ if not request.has_header('Host'):
1270
+ request.add_unredirected_header('Host', sel_host)
1271
+ for name, value in self.parent.addheaders:
1272
+ name = name.capitalize()
1273
+ if not request.has_header(name):
1274
+ request.add_unredirected_header(name, value)
1275
+
1276
+ return request
1277
+
1278
+ def do_open(self, http_class, req, **http_conn_args):
1279
+ """Return an HTTPResponse object for the request, using http_class.
1280
+
1281
+ http_class must implement the HTTPConnection API from http.client.
1282
+ """
1283
+ host = req.host
1284
+ if not host:
1285
+ raise URLError('no host given')
1286
+
1287
+ # will parse host:port
1288
+ h = http_class(host, timeout=req.timeout, **http_conn_args)
1289
+ h.set_debuglevel(self._debuglevel)
1290
+
1291
+ headers = dict(req.unredirected_hdrs)
1292
+ headers.update(req.headers)
1293
+
1294
+ # TODO(jhylton): Should this be redesigned to handle
1295
+ # persistent connections?
1296
+
1297
+ # We want to make an HTTP/1.1 request, but the addinfourl
1298
+ # class isn't prepared to deal with a persistent connection.
1299
+ # It will try to read all remaining data from the socket,
1300
+ # which will block while the server waits for the next request.
1301
+ # So make sure the connection gets closed after the (only)
1302
+ # request.
1303
+ headers["Connection"] = "close"
1304
+ headers = {name.title(): val for name, val in headers.items()}
1305
+
1306
+ if req._tunnel_host:
1307
+ tunnel_headers = {}
1308
+ proxy_auth_hdr = "Proxy-Authorization"
1309
+ if proxy_auth_hdr in headers:
1310
+ tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
1311
+ # Proxy-Authorization should not be sent to origin
1312
+ # server.
1313
+ del headers[proxy_auth_hdr]
1314
+ h.set_tunnel(req._tunnel_host, headers=tunnel_headers)
1315
+
1316
+ try:
1317
+ try:
1318
+ h.request(req.get_method(), req.selector, req.data, headers,
1319
+ encode_chunked=req.has_header('Transfer-encoding'))
1320
+ except OSError as err: # timeout error
1321
+ raise URLError(err)
1322
+ r = h.getresponse()
1323
+ except:
1324
+ h.close()
1325
+ raise
1326
+
1327
+ # If the server does not send us a 'Connection: close' header,
1328
+ # HTTPConnection assumes the socket should be left open. Manually
1329
+ # mark the socket to be closed when this response object goes away.
1330
+ if h.sock:
1331
+ h.sock.close()
1332
+ h.sock = None
1333
+
1334
+ r.url = req.get_full_url()
1335
+ # This line replaces the .msg attribute of the HTTPResponse
1336
+ # with .headers, because urllib clients expect the response to
1337
+ # have the reason in .msg. It would be good to mark this
1338
+ # attribute is deprecated and get then to use info() or
1339
+ # .headers.
1340
+ r.msg = r.reason
1341
+ return r
1342
+
1343
+
1344
+ class HTTPHandler(AbstractHTTPHandler):
1345
+
1346
+ def http_open(self, req):
1347
+ return self.do_open(http.client.HTTPConnection, req)
1348
+
1349
+ http_request = AbstractHTTPHandler.do_request_
1350
+
1351
+ if hasattr(http.client, 'HTTPSConnection'):
1352
+
1353
+ class HTTPSHandler(AbstractHTTPHandler):
1354
+
1355
+ def __init__(self, debuglevel=None, context=None, check_hostname=None):
1356
+ debuglevel = debuglevel if debuglevel is not None else http.client.HTTPSConnection.debuglevel
1357
+ AbstractHTTPHandler.__init__(self, debuglevel)
1358
+ if context is None:
1359
+ http_version = http.client.HTTPSConnection._http_vsn
1360
+ context = http.client._create_https_context(http_version)
1361
+ if check_hostname is not None:
1362
+ context.check_hostname = check_hostname
1363
+ self._context = context
1364
+
1365
+ def https_open(self, req):
1366
+ return self.do_open(http.client.HTTPSConnection, req,
1367
+ context=self._context)
1368
+
1369
+ https_request = AbstractHTTPHandler.do_request_
1370
+
1371
+ __all__.append('HTTPSHandler')
1372
+
1373
+ class HTTPCookieProcessor(BaseHandler):
1374
+ def __init__(self, cookiejar=None):
1375
+ import http.cookiejar
1376
+ if cookiejar is None:
1377
+ cookiejar = http.cookiejar.CookieJar()
1378
+ self.cookiejar = cookiejar
1379
+
1380
+ def http_request(self, request):
1381
+ self.cookiejar.add_cookie_header(request)
1382
+ return request
1383
+
1384
+ def http_response(self, request, response):
1385
+ self.cookiejar.extract_cookies(response, request)
1386
+ return response
1387
+
1388
+ https_request = http_request
1389
+ https_response = http_response
1390
+
1391
+ class UnknownHandler(BaseHandler):
1392
+ def unknown_open(self, req):
1393
+ type = req.type
1394
+ raise URLError('unknown url type: %s' % type)
1395
+
1396
+ def parse_keqv_list(l):
1397
+ """Parse list of key=value strings where keys are not duplicated."""
1398
+ parsed = {}
1399
+ for elt in l:
1400
+ k, v = elt.split('=', 1)
1401
+ if v[0] == '"' and v[-1] == '"':
1402
+ v = v[1:-1]
1403
+ parsed[k] = v
1404
+ return parsed
1405
+
1406
+ def parse_http_list(s):
1407
+ """Parse lists as described by RFC 2068 Section 2.
1408
+
1409
+ In particular, parse comma-separated lists where the elements of
1410
+ the list may include quoted-strings. A quoted-string could
1411
+ contain a comma. A non-quoted string could have quotes in the
1412
+ middle. Neither commas nor quotes count if they are escaped.
1413
+ Only double-quotes count, not single-quotes.
1414
+ """
1415
+ res = []
1416
+ part = ''
1417
+
1418
+ escape = quote = False
1419
+ for cur in s:
1420
+ if escape:
1421
+ part += cur
1422
+ escape = False
1423
+ continue
1424
+ if quote:
1425
+ if cur == '\\':
1426
+ escape = True
1427
+ continue
1428
+ elif cur == '"':
1429
+ quote = False
1430
+ part += cur
1431
+ continue
1432
+
1433
+ if cur == ',':
1434
+ res.append(part)
1435
+ part = ''
1436
+ continue
1437
+
1438
+ if cur == '"':
1439
+ quote = True
1440
+
1441
+ part += cur
1442
+
1443
+ # append last part
1444
+ if part:
1445
+ res.append(part)
1446
+
1447
+ return [part.strip() for part in res]
1448
+
1449
+ class FileHandler(BaseHandler):
1450
+ # Use local file or FTP depending on form of URL
1451
+ def file_open(self, req):
1452
+ url = req.selector
1453
+ if url[:2] == '//' and url[2:3] != '/' and (req.host and
1454
+ req.host != 'localhost'):
1455
+ if not req.host in self.get_names():
1456
+ raise URLError("file:// scheme is supported only on localhost")
1457
+ else:
1458
+ return self.open_local_file(req)
1459
+
1460
+ # names for the localhost
1461
+ names = None
1462
+ def get_names(self):
1463
+ if FileHandler.names is None:
1464
+ try:
1465
+ FileHandler.names = tuple(
1466
+ socket.gethostbyname_ex('localhost')[2] +
1467
+ socket.gethostbyname_ex(socket.gethostname())[2])
1468
+ except socket.gaierror:
1469
+ FileHandler.names = (socket.gethostbyname('localhost'),)
1470
+ return FileHandler.names
1471
+
1472
+ # not entirely sure what the rules are here
1473
+ def open_local_file(self, req):
1474
+ import email.utils
1475
+ import mimetypes
1476
+ host = req.host
1477
+ filename = req.selector
1478
+ localfile = url2pathname(filename)
1479
+ try:
1480
+ stats = os.stat(localfile)
1481
+ size = stats.st_size
1482
+ modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
1483
+ mtype = mimetypes.guess_type(filename)[0]
1484
+ headers = email.message_from_string(
1485
+ 'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
1486
+ (mtype or 'text/plain', size, modified))
1487
+ if host:
1488
+ host, port = _splitport(host)
1489
+ if not host or \
1490
+ (not port and _safe_gethostbyname(host) in self.get_names()):
1491
+ if host:
1492
+ origurl = 'file://' + host + filename
1493
+ else:
1494
+ origurl = 'file://' + filename
1495
+ return addinfourl(open(localfile, 'rb'), headers, origurl)
1496
+ except OSError as exp:
1497
+ raise URLError(exp)
1498
+ raise URLError('file not on local host')
1499
+
1500
+ def _safe_gethostbyname(host):
1501
+ try:
1502
+ return socket.gethostbyname(host)
1503
+ except socket.gaierror:
1504
+ return None
1505
+
1506
+ class FTPHandler(BaseHandler):
1507
+ def ftp_open(self, req):
1508
+ import ftplib
1509
+ import mimetypes
1510
+ host = req.host
1511
+ if not host:
1512
+ raise URLError('ftp error: no host given')
1513
+ host, port = _splitport(host)
1514
+ if port is None:
1515
+ port = ftplib.FTP_PORT
1516
+ else:
1517
+ port = int(port)
1518
+
1519
+ # username/password handling
1520
+ user, host = _splituser(host)
1521
+ if user:
1522
+ user, passwd = _splitpasswd(user)
1523
+ else:
1524
+ passwd = None
1525
+ host = unquote(host)
1526
+ user = user or ''
1527
+ passwd = passwd or ''
1528
+
1529
+ try:
1530
+ host = socket.gethostbyname(host)
1531
+ except OSError as msg:
1532
+ raise URLError(msg)
1533
+ path, attrs = _splitattr(req.selector)
1534
+ dirs = path.split('/')
1535
+ dirs = list(map(unquote, dirs))
1536
+ dirs, file = dirs[:-1], dirs[-1]
1537
+ if dirs and not dirs[0]:
1538
+ dirs = dirs[1:]
1539
+ fw = None
1540
+ try:
1541
+ fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
1542
+ type = file and 'I' or 'D'
1543
+ for attr in attrs:
1544
+ attr, value = _splitvalue(attr)
1545
+ if attr.lower() == 'type' and \
1546
+ value in ('a', 'A', 'i', 'I', 'd', 'D'):
1547
+ type = value.upper()
1548
+ fp, retrlen = fw.retrfile(file, type)
1549
+ headers = ""
1550
+ mtype = mimetypes.guess_type(req.full_url)[0]
1551
+ if mtype:
1552
+ headers += "Content-type: %s\n" % mtype
1553
+ if retrlen is not None and retrlen >= 0:
1554
+ headers += "Content-length: %d\n" % retrlen
1555
+ headers = email.message_from_string(headers)
1556
+ return addinfourl(fp, headers, req.full_url)
1557
+ except Exception as exp:
1558
+ if fw is not None and not fw.keepalive:
1559
+ fw.close()
1560
+ if isinstance(exp, ftplib.all_errors):
1561
+ raise URLError(exp) from exp
1562
+ raise
1563
+
1564
+ def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1565
+ return ftpwrapper(user, passwd, host, port, dirs, timeout,
1566
+ persistent=False)
1567
+
1568
+ class CacheFTPHandler(FTPHandler):
1569
+ # XXX would be nice to have pluggable cache strategies
1570
+ # XXX this stuff is definitely not thread safe
1571
+ def __init__(self):
1572
+ self.cache = {}
1573
+ self.timeout = {}
1574
+ self.soonest = 0
1575
+ self.delay = 60
1576
+ self.max_conns = 16
1577
+
1578
+ def setTimeout(self, t):
1579
+ self.delay = t
1580
+
1581
+ def setMaxConns(self, m):
1582
+ self.max_conns = m
1583
+
1584
+ def connect_ftp(self, user, passwd, host, port, dirs, timeout):
1585
+ key = user, host, port, '/'.join(dirs), timeout
1586
+ conn = self.cache.get(key)
1587
+ if conn is None or not conn.keepalive:
1588
+ if conn is not None:
1589
+ conn.close()
1590
+ conn = self.cache[key] = ftpwrapper(user, passwd, host, port,
1591
+ dirs, timeout)
1592
+ self.timeout[key] = time.time() + self.delay
1593
+ self.check_cache()
1594
+ return conn
1595
+
1596
+ def check_cache(self):
1597
+ # first check for old ones
1598
+ t = time.time()
1599
+ if self.soonest <= t:
1600
+ for k, v in list(self.timeout.items()):
1601
+ if v < t:
1602
+ self.cache[k].close()
1603
+ del self.cache[k]
1604
+ del self.timeout[k]
1605
+ self.soonest = min(list(self.timeout.values()))
1606
+
1607
+ # then check the size
1608
+ if len(self.cache) == self.max_conns:
1609
+ for k, v in list(self.timeout.items()):
1610
+ if v == self.soonest:
1611
+ del self.cache[k]
1612
+ del self.timeout[k]
1613
+ break
1614
+ self.soonest = min(list(self.timeout.values()))
1615
+
1616
+ def clear_cache(self):
1617
+ for conn in self.cache.values():
1618
+ conn.close()
1619
+ self.cache.clear()
1620
+ self.timeout.clear()
1621
+
1622
+ class DataHandler(BaseHandler):
1623
+ def data_open(self, req):
1624
+ # data URLs as specified in RFC 2397.
1625
+ #
1626
+ # ignores POSTed data
1627
+ #
1628
+ # syntax:
1629
+ # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
1630
+ # mediatype := [ type "/" subtype ] *( ";" parameter )
1631
+ # data := *urlchar
1632
+ # parameter := attribute "=" value
1633
+ url = req.full_url
1634
+
1635
+ scheme, data = url.split(":",1)
1636
+ mediatype, data = data.split(",",1)
1637
+
1638
+ # Disallow control characters within mediatype.
1639
+ if re.search(r"[\x00-\x1F\x7F]", mediatype):
1640
+ raise ValueError(
1641
+ "Control characters not allowed in data: mediatype")
1642
+
1643
+ # even base64 encoded data URLs might be quoted so unquote in any case:
1644
+ data = unquote_to_bytes(data)
1645
+ if mediatype.endswith(";base64"):
1646
+ data = base64.decodebytes(data)
1647
+ mediatype = mediatype[:-7]
1648
+
1649
+ if not mediatype:
1650
+ mediatype = "text/plain;charset=US-ASCII"
1651
+
1652
+ headers = email.message_from_string("Content-type: %s\nContent-length: %d\n" %
1653
+ (mediatype, len(data)))
1654
+
1655
+ return addinfourl(io.BytesIO(data), headers, url)
1656
+
1657
+
1658
+ # Code move from the old urllib module
1659
+
1660
+ MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
1661
+
1662
+ # Helper for non-unix systems
1663
+ if os.name == 'nt':
1664
+ from nturl2path import url2pathname, pathname2url
1665
+ else:
1666
+ def url2pathname(pathname):
1667
+ """OS-specific conversion from a relative URL of the 'file' scheme
1668
+ to a file system path; not recommended for general use."""
1669
+ if pathname[:3] == '///':
1670
+ # URL has an empty authority section, so the path begins on the
1671
+ # third character.
1672
+ pathname = pathname[2:]
1673
+ elif pathname[:12] == '//localhost/':
1674
+ # Skip past 'localhost' authority.
1675
+ pathname = pathname[11:]
1676
+ encoding = sys.getfilesystemencoding()
1677
+ errors = sys.getfilesystemencodeerrors()
1678
+ return unquote(pathname, encoding=encoding, errors=errors)
1679
+
1680
+ def pathname2url(pathname):
1681
+ """OS-specific conversion from a file system path to a relative URL
1682
+ of the 'file' scheme; not recommended for general use."""
1683
+ if pathname[:2] == '//':
1684
+ # Add explicitly empty authority to avoid interpreting the path
1685
+ # as authority.
1686
+ pathname = '//' + pathname
1687
+ encoding = sys.getfilesystemencoding()
1688
+ errors = sys.getfilesystemencodeerrors()
1689
+ return quote(pathname, encoding=encoding, errors=errors)
1690
+
1691
+
1692
+ ftpcache = {}
1693
+
1694
+
1695
+ class URLopener:
1696
+ """Class to open URLs.
1697
+ This is a class rather than just a subroutine because we may need
1698
+ more than one set of global protocol-specific options.
1699
+ Note -- this is a base class for those who don't want the
1700
+ automatic handling of errors type 302 (relocated) and 401
1701
+ (authorization needed)."""
1702
+
1703
+ __tempfiles = None
1704
+
1705
+ version = "Python-urllib/%s" % __version__
1706
+
1707
+ # Constructor
1708
+ def __init__(self, proxies=None, **x509):
1709
+ msg = "%(class)s style of invoking requests is deprecated. " \
1710
+ "Use newer urlopen functions/methods" % {'class': self.__class__.__name__}
1711
+ warnings.warn(msg, DeprecationWarning, stacklevel=3)
1712
+ if proxies is None:
1713
+ proxies = getproxies()
1714
+ assert hasattr(proxies, 'keys'), "proxies must be a mapping"
1715
+ self.proxies = proxies
1716
+ self.key_file = x509.get('key_file')
1717
+ self.cert_file = x509.get('cert_file')
1718
+ self.addheaders = [('User-Agent', self.version), ('Accept', '*/*')]
1719
+ self.__tempfiles = []
1720
+ self.__unlink = os.unlink # See cleanup()
1721
+ self.tempcache = None
1722
+ # Undocumented feature: if you assign {} to tempcache,
1723
+ # it is used to cache files retrieved with
1724
+ # self.retrieve(). This is not enabled by default
1725
+ # since it does not work for changing documents (and I
1726
+ # haven't got the logic to check expiration headers
1727
+ # yet).
1728
+ self.ftpcache = ftpcache
1729
+ # Undocumented feature: you can use a different
1730
+ # ftp cache by assigning to the .ftpcache member;
1731
+ # in case you want logically independent URL openers
1732
+ # XXX This is not threadsafe. Bah.
1733
+
1734
+ def __del__(self):
1735
+ self.close()
1736
+
1737
+ def close(self):
1738
+ self.cleanup()
1739
+
1740
+ def cleanup(self):
1741
+ # This code sometimes runs when the rest of this module
1742
+ # has already been deleted, so it can't use any globals
1743
+ # or import anything.
1744
+ if self.__tempfiles:
1745
+ for file in self.__tempfiles:
1746
+ try:
1747
+ self.__unlink(file)
1748
+ except OSError:
1749
+ pass
1750
+ del self.__tempfiles[:]
1751
+ if self.tempcache:
1752
+ self.tempcache.clear()
1753
+
1754
+ def addheader(self, *args):
1755
+ """Add a header to be used by the HTTP interface only
1756
+ e.g. u.addheader('Accept', 'sound/basic')"""
1757
+ self.addheaders.append(args)
1758
+
1759
+ # External interface
1760
+ def open(self, fullurl, data=None):
1761
+ """Use URLopener().open(file) instead of open(file, 'r')."""
1762
+ fullurl = unwrap(_to_bytes(fullurl))
1763
+ fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]|")
1764
+ if self.tempcache and fullurl in self.tempcache:
1765
+ filename, headers = self.tempcache[fullurl]
1766
+ fp = open(filename, 'rb')
1767
+ return addinfourl(fp, headers, fullurl)
1768
+ urltype, url = _splittype(fullurl)
1769
+ if not urltype:
1770
+ urltype = 'file'
1771
+ if urltype in self.proxies:
1772
+ proxy = self.proxies[urltype]
1773
+ urltype, proxyhost = _splittype(proxy)
1774
+ host, selector = _splithost(proxyhost)
1775
+ url = (host, fullurl) # Signal special case to open_*()
1776
+ else:
1777
+ proxy = None
1778
+ name = 'open_' + urltype
1779
+ self.type = urltype
1780
+ name = name.replace('-', '_')
1781
+ if not hasattr(self, name) or name == 'open_local_file':
1782
+ if proxy:
1783
+ return self.open_unknown_proxy(proxy, fullurl, data)
1784
+ else:
1785
+ return self.open_unknown(fullurl, data)
1786
+ try:
1787
+ if data is None:
1788
+ return getattr(self, name)(url)
1789
+ else:
1790
+ return getattr(self, name)(url, data)
1791
+ except (HTTPError, URLError):
1792
+ raise
1793
+ except OSError as msg:
1794
+ raise OSError('socket error', msg) from msg
1795
+
1796
+ def open_unknown(self, fullurl, data=None):
1797
+ """Overridable interface to open unknown URL type."""
1798
+ type, url = _splittype(fullurl)
1799
+ raise OSError('url error', 'unknown url type', type)
1800
+
1801
+ def open_unknown_proxy(self, proxy, fullurl, data=None):
1802
+ """Overridable interface to open unknown URL type."""
1803
+ type, url = _splittype(fullurl)
1804
+ raise OSError('url error', 'invalid proxy for %s' % type, proxy)
1805
+
1806
+ # External interface
1807
+ def retrieve(self, url, filename=None, reporthook=None, data=None):
1808
+ """retrieve(url) returns (filename, headers) for a local object
1809
+ or (tempfilename, headers) for a remote object."""
1810
+ url = unwrap(_to_bytes(url))
1811
+ if self.tempcache and url in self.tempcache:
1812
+ return self.tempcache[url]
1813
+ type, url1 = _splittype(url)
1814
+ if filename is None and (not type or type == 'file'):
1815
+ try:
1816
+ fp = self.open_local_file(url1)
1817
+ hdrs = fp.info()
1818
+ fp.close()
1819
+ return url2pathname(_splithost(url1)[1]), hdrs
1820
+ except OSError:
1821
+ pass
1822
+ fp = self.open(url, data)
1823
+ try:
1824
+ headers = fp.info()
1825
+ if filename:
1826
+ tfp = open(filename, 'wb')
1827
+ else:
1828
+ garbage, path = _splittype(url)
1829
+ garbage, path = _splithost(path or "")
1830
+ path, garbage = _splitquery(path or "")
1831
+ path, garbage = _splitattr(path or "")
1832
+ suffix = os.path.splitext(path)[1]
1833
+ (fd, filename) = tempfile.mkstemp(suffix)
1834
+ self.__tempfiles.append(filename)
1835
+ tfp = os.fdopen(fd, 'wb')
1836
+ try:
1837
+ result = filename, headers
1838
+ if self.tempcache is not None:
1839
+ self.tempcache[url] = result
1840
+ bs = 1024*8
1841
+ size = -1
1842
+ read = 0
1843
+ blocknum = 0
1844
+ if "content-length" in headers:
1845
+ size = int(headers["Content-Length"])
1846
+ if reporthook:
1847
+ reporthook(blocknum, bs, size)
1848
+ while block := fp.read(bs):
1849
+ read += len(block)
1850
+ tfp.write(block)
1851
+ blocknum += 1
1852
+ if reporthook:
1853
+ reporthook(blocknum, bs, size)
1854
+ finally:
1855
+ tfp.close()
1856
+ finally:
1857
+ fp.close()
1858
+
1859
+ # raise exception if actual size does not match content-length header
1860
+ if size >= 0 and read < size:
1861
+ raise ContentTooShortError(
1862
+ "retrieval incomplete: got only %i out of %i bytes"
1863
+ % (read, size), result)
1864
+
1865
+ return result
1866
+
1867
+ # Each method named open_<type> knows how to open that type of URL
1868
+
1869
+ def _open_generic_http(self, connection_factory, url, data):
1870
+ """Make an HTTP connection using connection_class.
1871
+
1872
+ This is an internal method that should be called from
1873
+ open_http() or open_https().
1874
+
1875
+ Arguments:
1876
+ - connection_factory should take a host name and return an
1877
+ HTTPConnection instance.
1878
+ - url is the url to retrieval or a host, relative-path pair.
1879
+ - data is payload for a POST request or None.
1880
+ """
1881
+
1882
+ user_passwd = None
1883
+ proxy_passwd= None
1884
+ if isinstance(url, str):
1885
+ host, selector = _splithost(url)
1886
+ if host:
1887
+ user_passwd, host = _splituser(host)
1888
+ host = unquote(host)
1889
+ realhost = host
1890
+ else:
1891
+ host, selector = url
1892
+ # check whether the proxy contains authorization information
1893
+ proxy_passwd, host = _splituser(host)
1894
+ # now we proceed with the url we want to obtain
1895
+ urltype, rest = _splittype(selector)
1896
+ url = rest
1897
+ user_passwd = None
1898
+ if urltype.lower() != 'http':
1899
+ realhost = None
1900
+ else:
1901
+ realhost, rest = _splithost(rest)
1902
+ if realhost:
1903
+ user_passwd, realhost = _splituser(realhost)
1904
+ if user_passwd:
1905
+ selector = "%s://%s%s" % (urltype, realhost, rest)
1906
+ if proxy_bypass(realhost):
1907
+ host = realhost
1908
+
1909
+ if not host: raise OSError('http error', 'no host given')
1910
+
1911
+ if proxy_passwd:
1912
+ proxy_passwd = unquote(proxy_passwd)
1913
+ proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii')
1914
+ else:
1915
+ proxy_auth = None
1916
+
1917
+ if user_passwd:
1918
+ user_passwd = unquote(user_passwd)
1919
+ auth = base64.b64encode(user_passwd.encode()).decode('ascii')
1920
+ else:
1921
+ auth = None
1922
+ http_conn = connection_factory(host)
1923
+ headers = {}
1924
+ if proxy_auth:
1925
+ headers["Proxy-Authorization"] = "Basic %s" % proxy_auth
1926
+ if auth:
1927
+ headers["Authorization"] = "Basic %s" % auth
1928
+ if realhost:
1929
+ headers["Host"] = realhost
1930
+
1931
+ # Add Connection:close as we don't support persistent connections yet.
1932
+ # This helps in closing the socket and avoiding ResourceWarning
1933
+
1934
+ headers["Connection"] = "close"
1935
+
1936
+ for header, value in self.addheaders:
1937
+ headers[header] = value
1938
+
1939
+ if data is not None:
1940
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
1941
+ http_conn.request("POST", selector, data, headers)
1942
+ else:
1943
+ http_conn.request("GET", selector, headers=headers)
1944
+
1945
+ try:
1946
+ response = http_conn.getresponse()
1947
+ except http.client.BadStatusLine:
1948
+ # something went wrong with the HTTP status line
1949
+ raise URLError("http protocol error: bad status line")
1950
+
1951
+ # According to RFC 2616, "2xx" code indicates that the client's
1952
+ # request was successfully received, understood, and accepted.
1953
+ if 200 <= response.status < 300:
1954
+ return addinfourl(response, response.msg, "http:" + url,
1955
+ response.status)
1956
+ else:
1957
+ return self.http_error(
1958
+ url, response.fp,
1959
+ response.status, response.reason, response.msg, data)
1960
+
1961
+ def open_http(self, url, data=None):
1962
+ """Use HTTP protocol."""
1963
+ return self._open_generic_http(http.client.HTTPConnection, url, data)
1964
+
1965
+ def http_error(self, url, fp, errcode, errmsg, headers, data=None):
1966
+ """Handle http errors.
1967
+
1968
+ Derived class can override this, or provide specific handlers
1969
+ named http_error_DDD where DDD is the 3-digit error code."""
1970
+ # First check if there's a specific handler for this error
1971
+ name = 'http_error_%d' % errcode
1972
+ if hasattr(self, name):
1973
+ method = getattr(self, name)
1974
+ if data is None:
1975
+ result = method(url, fp, errcode, errmsg, headers)
1976
+ else:
1977
+ result = method(url, fp, errcode, errmsg, headers, data)
1978
+ if result: return result
1979
+ return self.http_error_default(url, fp, errcode, errmsg, headers)
1980
+
1981
+ def http_error_default(self, url, fp, errcode, errmsg, headers):
1982
+ """Default error handler: close the connection and raise OSError."""
1983
+ fp.close()
1984
+ raise HTTPError(url, errcode, errmsg, headers, None)
1985
+
1986
+ if _have_ssl:
1987
+ def _https_connection(self, host):
1988
+ if self.key_file or self.cert_file:
1989
+ http_version = http.client.HTTPSConnection._http_vsn
1990
+ context = http.client._create_https_context(http_version)
1991
+ context.load_cert_chain(self.cert_file, self.key_file)
1992
+ # cert and key file means the user wants to authenticate.
1993
+ # enable TLS 1.3 PHA implicitly even for custom contexts.
1994
+ if context.post_handshake_auth is not None:
1995
+ context.post_handshake_auth = True
1996
+ else:
1997
+ context = None
1998
+ return http.client.HTTPSConnection(host, context=context)
1999
+
2000
+ def open_https(self, url, data=None):
2001
+ """Use HTTPS protocol."""
2002
+ return self._open_generic_http(self._https_connection, url, data)
2003
+
2004
+ def open_file(self, url):
2005
+ """Use local file or FTP depending on form of URL."""
2006
+ if not isinstance(url, str):
2007
+ raise URLError('file error: proxy support for file protocol currently not implemented')
2008
+ if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
2009
+ raise ValueError("file:// scheme is supported only on localhost")
2010
+ else:
2011
+ return self.open_local_file(url)
2012
+
2013
+ def open_local_file(self, url):
2014
+ """Use local file."""
2015
+ import email.utils
2016
+ import mimetypes
2017
+ host, file = _splithost(url)
2018
+ localname = url2pathname(file)
2019
+ try:
2020
+ stats = os.stat(localname)
2021
+ except OSError as e:
2022
+ raise URLError(e.strerror, e.filename)
2023
+ size = stats.st_size
2024
+ modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
2025
+ mtype = mimetypes.guess_type(url)[0]
2026
+ headers = email.message_from_string(
2027
+ 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
2028
+ (mtype or 'text/plain', size, modified))
2029
+ if not host:
2030
+ urlfile = file
2031
+ if file[:1] == '/':
2032
+ urlfile = 'file://' + file
2033
+ return addinfourl(open(localname, 'rb'), headers, urlfile)
2034
+ host, port = _splitport(host)
2035
+ if (not port
2036
+ and socket.gethostbyname(host) in ((localhost(),) + thishost())):
2037
+ urlfile = file
2038
+ if file[:1] == '/':
2039
+ urlfile = 'file://' + file
2040
+ elif file[:2] == './':
2041
+ raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url)
2042
+ return addinfourl(open(localname, 'rb'), headers, urlfile)
2043
+ raise URLError('local file error: not on local host')
2044
+
2045
+ def open_ftp(self, url):
2046
+ """Use FTP protocol."""
2047
+ if not isinstance(url, str):
2048
+ raise URLError('ftp error: proxy support for ftp protocol currently not implemented')
2049
+ import mimetypes
2050
+ host, path = _splithost(url)
2051
+ if not host: raise URLError('ftp error: no host given')
2052
+ host, port = _splitport(host)
2053
+ user, host = _splituser(host)
2054
+ if user: user, passwd = _splitpasswd(user)
2055
+ else: passwd = None
2056
+ host = unquote(host)
2057
+ user = unquote(user or '')
2058
+ passwd = unquote(passwd or '')
2059
+ host = socket.gethostbyname(host)
2060
+ if not port:
2061
+ import ftplib
2062
+ port = ftplib.FTP_PORT
2063
+ else:
2064
+ port = int(port)
2065
+ path, attrs = _splitattr(path)
2066
+ path = unquote(path)
2067
+ dirs = path.split('/')
2068
+ dirs, file = dirs[:-1], dirs[-1]
2069
+ if dirs and not dirs[0]: dirs = dirs[1:]
2070
+ if dirs and not dirs[0]: dirs[0] = '/'
2071
+ key = user, host, port, '/'.join(dirs)
2072
+ # XXX thread unsafe!
2073
+ if len(self.ftpcache) > MAXFTPCACHE:
2074
+ # Prune the cache, rather arbitrarily
2075
+ for k in list(self.ftpcache):
2076
+ if k != key:
2077
+ v = self.ftpcache[k]
2078
+ del self.ftpcache[k]
2079
+ v.close()
2080
+ try:
2081
+ if key not in self.ftpcache:
2082
+ self.ftpcache[key] = \
2083
+ ftpwrapper(user, passwd, host, port, dirs)
2084
+ if not file: type = 'D'
2085
+ else: type = 'I'
2086
+ for attr in attrs:
2087
+ attr, value = _splitvalue(attr)
2088
+ if attr.lower() == 'type' and \
2089
+ value in ('a', 'A', 'i', 'I', 'd', 'D'):
2090
+ type = value.upper()
2091
+ (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
2092
+ mtype = mimetypes.guess_type("ftp:" + url)[0]
2093
+ headers = ""
2094
+ if mtype:
2095
+ headers += "Content-Type: %s\n" % mtype
2096
+ if retrlen is not None and retrlen >= 0:
2097
+ headers += "Content-Length: %d\n" % retrlen
2098
+ headers = email.message_from_string(headers)
2099
+ return addinfourl(fp, headers, "ftp:" + url)
2100
+ except ftperrors() as exp:
2101
+ raise URLError(f'ftp error: {exp}') from exp
2102
+
2103
+ def open_data(self, url, data=None):
2104
+ """Use "data" URL."""
2105
+ if not isinstance(url, str):
2106
+ raise URLError('data error: proxy support for data protocol currently not implemented')
2107
+ # ignore POSTed data
2108
+ #
2109
+ # syntax of data URLs:
2110
+ # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
2111
+ # mediatype := [ type "/" subtype ] *( ";" parameter )
2112
+ # data := *urlchar
2113
+ # parameter := attribute "=" value
2114
+ try:
2115
+ [type, data] = url.split(',', 1)
2116
+ except ValueError:
2117
+ raise OSError('data error', 'bad data URL')
2118
+ if not type:
2119
+ type = 'text/plain;charset=US-ASCII'
2120
+ semi = type.rfind(';')
2121
+ if semi >= 0 and '=' not in type[semi:]:
2122
+ encoding = type[semi+1:]
2123
+ type = type[:semi]
2124
+ else:
2125
+ encoding = ''
2126
+ msg = []
2127
+ msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
2128
+ time.gmtime(time.time())))
2129
+ msg.append('Content-type: %s' % type)
2130
+ if encoding == 'base64':
2131
+ # XXX is this encoding/decoding ok?
2132
+ data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
2133
+ else:
2134
+ data = unquote(data)
2135
+ msg.append('Content-Length: %d' % len(data))
2136
+ msg.append('')
2137
+ msg.append(data)
2138
+ msg = '\n'.join(msg)
2139
+ headers = email.message_from_string(msg)
2140
+ f = io.StringIO(msg)
2141
+ #f.fileno = None # needed for addinfourl
2142
+ return addinfourl(f, headers, url)
2143
+
2144
+
2145
+ class FancyURLopener(URLopener):
2146
+ """Derived class with handlers for errors we can handle (perhaps)."""
2147
+
2148
+ def __init__(self, *args, **kwargs):
2149
+ URLopener.__init__(self, *args, **kwargs)
2150
+ self.auth_cache = {}
2151
+ self.tries = 0
2152
+ self.maxtries = 10
2153
+
2154
+ def http_error_default(self, url, fp, errcode, errmsg, headers):
2155
+ """Default error handling -- don't raise an exception."""
2156
+ return addinfourl(fp, headers, "http:" + url, errcode)
2157
+
2158
+ def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
2159
+ """Error 302 -- relocated (temporarily)."""
2160
+ self.tries += 1
2161
+ try:
2162
+ if self.maxtries and self.tries >= self.maxtries:
2163
+ if hasattr(self, "http_error_500"):
2164
+ meth = self.http_error_500
2165
+ else:
2166
+ meth = self.http_error_default
2167
+ return meth(url, fp, 500,
2168
+ "Internal Server Error: Redirect Recursion",
2169
+ headers)
2170
+ result = self.redirect_internal(url, fp, errcode, errmsg,
2171
+ headers, data)
2172
+ return result
2173
+ finally:
2174
+ self.tries = 0
2175
+
2176
+ def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
2177
+ if 'location' in headers:
2178
+ newurl = headers['location']
2179
+ elif 'uri' in headers:
2180
+ newurl = headers['uri']
2181
+ else:
2182
+ return
2183
+ fp.close()
2184
+
2185
+ # In case the server sent a relative URL, join with original:
2186
+ newurl = urljoin(self.type + ":" + url, newurl)
2187
+
2188
+ urlparts = urlparse(newurl)
2189
+
2190
+ # For security reasons, we don't allow redirection to anything other
2191
+ # than http, https and ftp.
2192
+
2193
+ # We are using newer HTTPError with older redirect_internal method
2194
+ # This older method will get deprecated in 3.3
2195
+
2196
+ if urlparts.scheme not in ('http', 'https', 'ftp', ''):
2197
+ raise HTTPError(newurl, errcode,
2198
+ errmsg +
2199
+ " Redirection to url '%s' is not allowed." % newurl,
2200
+ headers, fp)
2201
+
2202
+ return self.open(newurl)
2203
+
2204
+ def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
2205
+ """Error 301 -- also relocated (permanently)."""
2206
+ return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2207
+
2208
+ def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
2209
+ """Error 303 -- also relocated (essentially identical to 302)."""
2210
+ return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2211
+
2212
+ def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
2213
+ """Error 307 -- relocated, but turn POST into error."""
2214
+ if data is None:
2215
+ return self.http_error_302(url, fp, errcode, errmsg, headers, data)
2216
+ else:
2217
+ return self.http_error_default(url, fp, errcode, errmsg, headers)
2218
+
2219
+ def http_error_308(self, url, fp, errcode, errmsg, headers, data=None):
2220
+ """Error 308 -- relocated, but turn POST into error."""
2221
+ if data is None:
2222
+ return self.http_error_301(url, fp, errcode, errmsg, headers, data)
2223
+ else:
2224
+ return self.http_error_default(url, fp, errcode, errmsg, headers)
2225
+
2226
+ def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
2227
+ retry=False):
2228
+ """Error 401 -- authentication required.
2229
+ This function supports Basic authentication only."""
2230
+ if 'www-authenticate' not in headers:
2231
+ URLopener.http_error_default(self, url, fp,
2232
+ errcode, errmsg, headers)
2233
+ stuff = headers['www-authenticate']
2234
+ match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
2235
+ if not match:
2236
+ URLopener.http_error_default(self, url, fp,
2237
+ errcode, errmsg, headers)
2238
+ scheme, realm = match.groups()
2239
+ if scheme.lower() != 'basic':
2240
+ URLopener.http_error_default(self, url, fp,
2241
+ errcode, errmsg, headers)
2242
+ if not retry:
2243
+ URLopener.http_error_default(self, url, fp, errcode, errmsg,
2244
+ headers)
2245
+ name = 'retry_' + self.type + '_basic_auth'
2246
+ if data is None:
2247
+ return getattr(self,name)(url, realm)
2248
+ else:
2249
+ return getattr(self,name)(url, realm, data)
2250
+
2251
+ def http_error_407(self, url, fp, errcode, errmsg, headers, data=None,
2252
+ retry=False):
2253
+ """Error 407 -- proxy authentication required.
2254
+ This function supports Basic authentication only."""
2255
+ if 'proxy-authenticate' not in headers:
2256
+ URLopener.http_error_default(self, url, fp,
2257
+ errcode, errmsg, headers)
2258
+ stuff = headers['proxy-authenticate']
2259
+ match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
2260
+ if not match:
2261
+ URLopener.http_error_default(self, url, fp,
2262
+ errcode, errmsg, headers)
2263
+ scheme, realm = match.groups()
2264
+ if scheme.lower() != 'basic':
2265
+ URLopener.http_error_default(self, url, fp,
2266
+ errcode, errmsg, headers)
2267
+ if not retry:
2268
+ URLopener.http_error_default(self, url, fp, errcode, errmsg,
2269
+ headers)
2270
+ name = 'retry_proxy_' + self.type + '_basic_auth'
2271
+ if data is None:
2272
+ return getattr(self,name)(url, realm)
2273
+ else:
2274
+ return getattr(self,name)(url, realm, data)
2275
+
2276
+ def retry_proxy_http_basic_auth(self, url, realm, data=None):
2277
+ host, selector = _splithost(url)
2278
+ newurl = 'http://' + host + selector
2279
+ proxy = self.proxies['http']
2280
+ urltype, proxyhost = _splittype(proxy)
2281
+ proxyhost, proxyselector = _splithost(proxyhost)
2282
+ i = proxyhost.find('@') + 1
2283
+ proxyhost = proxyhost[i:]
2284
+ user, passwd = self.get_user_passwd(proxyhost, realm, i)
2285
+ if not (user or passwd): return None
2286
+ proxyhost = "%s:%s@%s" % (quote(user, safe=''),
2287
+ quote(passwd, safe=''), proxyhost)
2288
+ self.proxies['http'] = 'http://' + proxyhost + proxyselector
2289
+ if data is None:
2290
+ return self.open(newurl)
2291
+ else:
2292
+ return self.open(newurl, data)
2293
+
2294
+ def retry_proxy_https_basic_auth(self, url, realm, data=None):
2295
+ host, selector = _splithost(url)
2296
+ newurl = 'https://' + host + selector
2297
+ proxy = self.proxies['https']
2298
+ urltype, proxyhost = _splittype(proxy)
2299
+ proxyhost, proxyselector = _splithost(proxyhost)
2300
+ i = proxyhost.find('@') + 1
2301
+ proxyhost = proxyhost[i:]
2302
+ user, passwd = self.get_user_passwd(proxyhost, realm, i)
2303
+ if not (user or passwd): return None
2304
+ proxyhost = "%s:%s@%s" % (quote(user, safe=''),
2305
+ quote(passwd, safe=''), proxyhost)
2306
+ self.proxies['https'] = 'https://' + proxyhost + proxyselector
2307
+ if data is None:
2308
+ return self.open(newurl)
2309
+ else:
2310
+ return self.open(newurl, data)
2311
+
2312
+ def retry_http_basic_auth(self, url, realm, data=None):
2313
+ host, selector = _splithost(url)
2314
+ i = host.find('@') + 1
2315
+ host = host[i:]
2316
+ user, passwd = self.get_user_passwd(host, realm, i)
2317
+ if not (user or passwd): return None
2318
+ host = "%s:%s@%s" % (quote(user, safe=''),
2319
+ quote(passwd, safe=''), host)
2320
+ newurl = 'http://' + host + selector
2321
+ if data is None:
2322
+ return self.open(newurl)
2323
+ else:
2324
+ return self.open(newurl, data)
2325
+
2326
+ def retry_https_basic_auth(self, url, realm, data=None):
2327
+ host, selector = _splithost(url)
2328
+ i = host.find('@') + 1
2329
+ host = host[i:]
2330
+ user, passwd = self.get_user_passwd(host, realm, i)
2331
+ if not (user or passwd): return None
2332
+ host = "%s:%s@%s" % (quote(user, safe=''),
2333
+ quote(passwd, safe=''), host)
2334
+ newurl = 'https://' + host + selector
2335
+ if data is None:
2336
+ return self.open(newurl)
2337
+ else:
2338
+ return self.open(newurl, data)
2339
+
2340
+ def get_user_passwd(self, host, realm, clear_cache=0):
2341
+ key = realm + '@' + host.lower()
2342
+ if key in self.auth_cache:
2343
+ if clear_cache:
2344
+ del self.auth_cache[key]
2345
+ else:
2346
+ return self.auth_cache[key]
2347
+ user, passwd = self.prompt_user_passwd(host, realm)
2348
+ if user or passwd: self.auth_cache[key] = (user, passwd)
2349
+ return user, passwd
2350
+
2351
+ def prompt_user_passwd(self, host, realm):
2352
+ """Override this in a GUI environment!"""
2353
+ import getpass
2354
+ try:
2355
+ user = input("Enter username for %s at %s: " % (realm, host))
2356
+ passwd = getpass.getpass("Enter password for %s in %s at %s: " %
2357
+ (user, realm, host))
2358
+ return user, passwd
2359
+ except KeyboardInterrupt:
2360
+ print()
2361
+ return None, None
2362
+
2363
+
2364
+ # Utility functions
2365
+
2366
+ _localhost = None
2367
+ def localhost():
2368
+ """Return the IP address of the magic hostname 'localhost'."""
2369
+ global _localhost
2370
+ if _localhost is None:
2371
+ _localhost = socket.gethostbyname('localhost')
2372
+ return _localhost
2373
+
2374
+ _thishost = None
2375
+ def thishost():
2376
+ """Return the IP addresses of the current host."""
2377
+ global _thishost
2378
+ if _thishost is None:
2379
+ try:
2380
+ _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
2381
+ except socket.gaierror:
2382
+ _thishost = tuple(socket.gethostbyname_ex('localhost')[2])
2383
+ return _thishost
2384
+
2385
+ _ftperrors = None
2386
+ def ftperrors():
2387
+ """Return the set of errors raised by the FTP class."""
2388
+ global _ftperrors
2389
+ if _ftperrors is None:
2390
+ import ftplib
2391
+ _ftperrors = ftplib.all_errors
2392
+ return _ftperrors
2393
+
2394
+ _noheaders = None
2395
+ def noheaders():
2396
+ """Return an empty email Message object."""
2397
+ global _noheaders
2398
+ if _noheaders is None:
2399
+ _noheaders = email.message_from_string("")
2400
+ return _noheaders
2401
+
2402
+
2403
+ # Utility classes
2404
+
2405
+ class ftpwrapper:
2406
+ """Class used by open_ftp() for cache of open FTP connections."""
2407
+
2408
+ def __init__(self, user, passwd, host, port, dirs, timeout=None,
2409
+ persistent=True):
2410
+ self.user = user
2411
+ self.passwd = passwd
2412
+ self.host = host
2413
+ self.port = port
2414
+ self.dirs = dirs
2415
+ self.timeout = timeout
2416
+ self.refcount = 0
2417
+ self.keepalive = persistent
2418
+ try:
2419
+ self.init()
2420
+ except:
2421
+ self.close()
2422
+ raise
2423
+
2424
+ def init(self):
2425
+ import ftplib
2426
+ self.busy = 0
2427
+ self.ftp = ftplib.FTP()
2428
+ self.ftp.connect(self.host, self.port, self.timeout)
2429
+ self.ftp.login(self.user, self.passwd)
2430
+ _target = '/'.join(self.dirs)
2431
+ self.ftp.cwd(_target)
2432
+
2433
+ def retrfile(self, file, type):
2434
+ import ftplib
2435
+ self.endtransfer()
2436
+ if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
2437
+ else: cmd = 'TYPE ' + type; isdir = 0
2438
+ try:
2439
+ self.ftp.voidcmd(cmd)
2440
+ except ftplib.all_errors:
2441
+ self.init()
2442
+ self.ftp.voidcmd(cmd)
2443
+ conn = None
2444
+ if file and not isdir:
2445
+ # Try to retrieve as a file
2446
+ try:
2447
+ cmd = 'RETR ' + file
2448
+ conn, retrlen = self.ftp.ntransfercmd(cmd)
2449
+ except ftplib.error_perm as reason:
2450
+ if str(reason)[:3] != '550':
2451
+ raise URLError(f'ftp error: {reason}') from reason
2452
+ if not conn:
2453
+ # Set transfer mode to ASCII!
2454
+ self.ftp.voidcmd('TYPE A')
2455
+ # Try a directory listing. Verify that directory exists.
2456
+ if file:
2457
+ pwd = self.ftp.pwd()
2458
+ try:
2459
+ try:
2460
+ self.ftp.cwd(file)
2461
+ except ftplib.error_perm as reason:
2462
+ raise URLError('ftp error: %r' % reason) from reason
2463
+ finally:
2464
+ self.ftp.cwd(pwd)
2465
+ cmd = 'LIST ' + file
2466
+ else:
2467
+ cmd = 'LIST'
2468
+ conn, retrlen = self.ftp.ntransfercmd(cmd)
2469
+ self.busy = 1
2470
+
2471
+ ftpobj = addclosehook(conn.makefile('rb'), self.file_close)
2472
+ self.refcount += 1
2473
+ conn.close()
2474
+ # Pass back both a suitably decorated object and a retrieval length
2475
+ return (ftpobj, retrlen)
2476
+
2477
+ def endtransfer(self):
2478
+ if not self.busy:
2479
+ return
2480
+ self.busy = 0
2481
+ try:
2482
+ self.ftp.voidresp()
2483
+ except ftperrors():
2484
+ pass
2485
+
2486
+ def close(self):
2487
+ self.keepalive = False
2488
+ if self.refcount <= 0:
2489
+ self.real_close()
2490
+
2491
+ def file_close(self):
2492
+ self.endtransfer()
2493
+ self.refcount -= 1
2494
+ if self.refcount <= 0 and not self.keepalive:
2495
+ self.real_close()
2496
+
2497
+ def real_close(self):
2498
+ self.endtransfer()
2499
+ try:
2500
+ self.ftp.close()
2501
+ except ftperrors():
2502
+ pass
2503
+
2504
+ # Proxy handling
2505
+ def getproxies_environment():
2506
+ """Return a dictionary of scheme -> proxy server URL mappings.
2507
+
2508
+ Scan the environment for variables named <scheme>_proxy;
2509
+ this seems to be the standard convention. If you need a
2510
+ different way, you can pass a proxies dictionary to the
2511
+ [Fancy]URLopener constructor.
2512
+ """
2513
+ # in order to prefer lowercase variables, process environment in
2514
+ # two passes: first matches any, second pass matches lowercase only
2515
+
2516
+ # select only environment variables which end in (after making lowercase) _proxy
2517
+ proxies = {}
2518
+ environment = []
2519
+ for name in os.environ:
2520
+ # fast screen underscore position before more expensive case-folding
2521
+ if len(name) > 5 and name[-6] == "_" and name[-5:].lower() == "proxy":
2522
+ value = os.environ[name]
2523
+ proxy_name = name[:-6].lower()
2524
+ environment.append((name, value, proxy_name))
2525
+ if value:
2526
+ proxies[proxy_name] = value
2527
+ # CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY
2528
+ # (non-all-lowercase) as it may be set from the web server by a "Proxy:"
2529
+ # header from the client
2530
+ # If "proxy" is lowercase, it will still be used thanks to the next block
2531
+ if 'REQUEST_METHOD' in os.environ:
2532
+ proxies.pop('http', None)
2533
+ for name, value, proxy_name in environment:
2534
+ # not case-folded, checking here for lower-case env vars only
2535
+ if name[-6:] == '_proxy':
2536
+ if value:
2537
+ proxies[proxy_name] = value
2538
+ else:
2539
+ proxies.pop(proxy_name, None)
2540
+ return proxies
2541
+
2542
+ def proxy_bypass_environment(host, proxies=None):
2543
+ """Test if proxies should not be used for a particular host.
2544
+
2545
+ Checks the proxy dict for the value of no_proxy, which should
2546
+ be a list of comma separated DNS suffixes, or '*' for all hosts.
2547
+
2548
+ """
2549
+ if proxies is None:
2550
+ proxies = getproxies_environment()
2551
+ # don't bypass, if no_proxy isn't specified
2552
+ try:
2553
+ no_proxy = proxies['no']
2554
+ except KeyError:
2555
+ return False
2556
+ # '*' is special case for always bypass
2557
+ if no_proxy == '*':
2558
+ return True
2559
+ host = host.lower()
2560
+ # strip port off host
2561
+ hostonly, port = _splitport(host)
2562
+ # check if the host ends with any of the DNS suffixes
2563
+ for name in no_proxy.split(','):
2564
+ name = name.strip()
2565
+ if name:
2566
+ name = name.lstrip('.') # ignore leading dots
2567
+ name = name.lower()
2568
+ if hostonly == name or host == name:
2569
+ return True
2570
+ name = '.' + name
2571
+ if hostonly.endswith(name) or host.endswith(name):
2572
+ return True
2573
+ # otherwise, don't bypass
2574
+ return False
2575
+
2576
+
2577
+ # This code tests an OSX specific data structure but is testable on all
2578
+ # platforms
2579
+ def _proxy_bypass_macosx_sysconf(host, proxy_settings):
2580
+ """
2581
+ Return True iff this host shouldn't be accessed using a proxy
2582
+
2583
+ This function uses the MacOSX framework SystemConfiguration
2584
+ to fetch the proxy information.
2585
+
2586
+ proxy_settings come from _scproxy._get_proxy_settings or get mocked ie:
2587
+ { 'exclude_simple': bool,
2588
+ 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16']
2589
+ }
2590
+ """
2591
+ from fnmatch import fnmatch
2592
+ from ipaddress import AddressValueError, IPv4Address
2593
+
2594
+ hostonly, port = _splitport(host)
2595
+
2596
+ def ip2num(ipAddr):
2597
+ parts = ipAddr.split('.')
2598
+ parts = list(map(int, parts))
2599
+ if len(parts) != 4:
2600
+ parts = (parts + [0, 0, 0, 0])[:4]
2601
+ return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
2602
+
2603
+ # Check for simple host names:
2604
+ if '.' not in host:
2605
+ if proxy_settings['exclude_simple']:
2606
+ return True
2607
+
2608
+ hostIP = None
2609
+ try:
2610
+ hostIP = int(IPv4Address(hostonly))
2611
+ except AddressValueError:
2612
+ pass
2613
+
2614
+ for value in proxy_settings.get('exceptions', ()):
2615
+ # Items in the list are strings like these: *.local, 169.254/16
2616
+ if not value: continue
2617
+
2618
+ m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value)
2619
+ if m is not None and hostIP is not None:
2620
+ base = ip2num(m.group(1))
2621
+ mask = m.group(2)
2622
+ if mask is None:
2623
+ mask = 8 * (m.group(1).count('.') + 1)
2624
+ else:
2625
+ mask = int(mask[1:])
2626
+
2627
+ if mask < 0 or mask > 32:
2628
+ # System libraries ignore invalid prefix lengths
2629
+ continue
2630
+
2631
+ mask = 32 - mask
2632
+
2633
+ if (hostIP >> mask) == (base >> mask):
2634
+ return True
2635
+
2636
+ elif fnmatch(host, value):
2637
+ return True
2638
+
2639
+ return False
2640
+
2641
+
2642
+ # Same as _proxy_bypass_macosx_sysconf, testable on all platforms
2643
+ def _proxy_bypass_winreg_override(host, override):
2644
+ """Return True if the host should bypass the proxy server.
2645
+
2646
+ The proxy override list is obtained from the Windows
2647
+ Internet settings proxy override registry value.
2648
+
2649
+ An example of a proxy override value is:
2650
+ "www.example.com;*.example.net; 192.168.0.1"
2651
+ """
2652
+ from fnmatch import fnmatch
2653
+
2654
+ host, _ = _splitport(host)
2655
+ proxy_override = override.split(';')
2656
+ for test in proxy_override:
2657
+ test = test.strip()
2658
+ # "<local>" should bypass the proxy server for all intranet addresses
2659
+ if test == '<local>':
2660
+ if '.' not in host:
2661
+ return True
2662
+ elif fnmatch(host, test):
2663
+ return True
2664
+ return False
2665
+
2666
+
2667
+ if sys.platform == 'darwin':
2668
+ from _scproxy import _get_proxy_settings, _get_proxies
2669
+
2670
+ def proxy_bypass_macosx_sysconf(host):
2671
+ proxy_settings = _get_proxy_settings()
2672
+ return _proxy_bypass_macosx_sysconf(host, proxy_settings)
2673
+
2674
+ def getproxies_macosx_sysconf():
2675
+ """Return a dictionary of scheme -> proxy server URL mappings.
2676
+
2677
+ This function uses the MacOSX framework SystemConfiguration
2678
+ to fetch the proxy information.
2679
+ """
2680
+ return _get_proxies()
2681
+
2682
+
2683
+
2684
+ def proxy_bypass(host):
2685
+ """Return True, if host should be bypassed.
2686
+
2687
+ Checks proxy settings gathered from the environment, if specified,
2688
+ or from the MacOSX framework SystemConfiguration.
2689
+
2690
+ """
2691
+ proxies = getproxies_environment()
2692
+ if proxies:
2693
+ return proxy_bypass_environment(host, proxies)
2694
+ else:
2695
+ return proxy_bypass_macosx_sysconf(host)
2696
+
2697
+ def getproxies():
2698
+ return getproxies_environment() or getproxies_macosx_sysconf()
2699
+
2700
+
2701
+ elif os.name == 'nt':
2702
+ def getproxies_registry():
2703
+ """Return a dictionary of scheme -> proxy server URL mappings.
2704
+
2705
+ Win32 uses the registry to store proxies.
2706
+
2707
+ """
2708
+ proxies = {}
2709
+ try:
2710
+ import winreg
2711
+ except ImportError:
2712
+ # Std module, so should be around - but you never know!
2713
+ return proxies
2714
+ try:
2715
+ internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
2716
+ r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
2717
+ proxyEnable = winreg.QueryValueEx(internetSettings,
2718
+ 'ProxyEnable')[0]
2719
+ if proxyEnable:
2720
+ # Returned as Unicode but problems if not converted to ASCII
2721
+ proxyServer = str(winreg.QueryValueEx(internetSettings,
2722
+ 'ProxyServer')[0])
2723
+ if '=' not in proxyServer and ';' not in proxyServer:
2724
+ # Use one setting for all protocols.
2725
+ proxyServer = 'http={0};https={0};ftp={0}'.format(proxyServer)
2726
+ for p in proxyServer.split(';'):
2727
+ protocol, address = p.split('=', 1)
2728
+ # See if address has a type:// prefix
2729
+ if not re.match('(?:[^/:]+)://', address):
2730
+ # Add type:// prefix to address without specifying type
2731
+ if protocol in ('http', 'https', 'ftp'):
2732
+ # The default proxy type of Windows is HTTP
2733
+ address = 'http://' + address
2734
+ elif protocol == 'socks':
2735
+ address = 'socks://' + address
2736
+ proxies[protocol] = address
2737
+ # Use SOCKS proxy for HTTP(S) protocols
2738
+ if proxies.get('socks'):
2739
+ # The default SOCKS proxy type of Windows is SOCKS4
2740
+ address = re.sub(r'^socks://', 'socks4://', proxies['socks'])
2741
+ proxies['http'] = proxies.get('http') or address
2742
+ proxies['https'] = proxies.get('https') or address
2743
+ internetSettings.Close()
2744
+ except (OSError, ValueError, TypeError):
2745
+ # Either registry key not found etc, or the value in an
2746
+ # unexpected format.
2747
+ # proxies already set up to be empty so nothing to do
2748
+ pass
2749
+ return proxies
2750
+
2751
+ def getproxies():
2752
+ """Return a dictionary of scheme -> proxy server URL mappings.
2753
+
2754
+ Returns settings gathered from the environment, if specified,
2755
+ or the registry.
2756
+
2757
+ """
2758
+ return getproxies_environment() or getproxies_registry()
2759
+
2760
+ def proxy_bypass_registry(host):
2761
+ try:
2762
+ import winreg
2763
+ except ImportError:
2764
+ # Std modules, so should be around - but you never know!
2765
+ return False
2766
+ try:
2767
+ internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
2768
+ r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
2769
+ proxyEnable = winreg.QueryValueEx(internetSettings,
2770
+ 'ProxyEnable')[0]
2771
+ proxyOverride = str(winreg.QueryValueEx(internetSettings,
2772
+ 'ProxyOverride')[0])
2773
+ # ^^^^ Returned as Unicode but problems if not converted to ASCII
2774
+ except OSError:
2775
+ return False
2776
+ if not proxyEnable or not proxyOverride:
2777
+ return False
2778
+ return _proxy_bypass_winreg_override(host, proxyOverride)
2779
+
2780
+ def proxy_bypass(host):
2781
+ """Return True, if host should be bypassed.
2782
+
2783
+ Checks proxy settings gathered from the environment, if specified,
2784
+ or the registry.
2785
+
2786
+ """
2787
+ proxies = getproxies_environment()
2788
+ if proxies:
2789
+ return proxy_bypass_environment(host, proxies)
2790
+ else:
2791
+ return proxy_bypass_registry(host)
2792
+
2793
+ else:
2794
+ # By default use environment variables
2795
+ getproxies = getproxies_environment
2796
+ proxy_bypass = proxy_bypass_environment