PageRenderTime 127ms CodeModel.GetById 28ms RepoModel.GetById 6ms app.codeStats 0ms

/other/FetchData/mechanize/_msiecookiejar.py

http://github.com/jbeezley/wrf-fire
Python | 388 lines | 358 code | 10 blank | 20 comment | 5 complexity | bbd40e644e667cb31d17c37f310aef1d MD5 | raw file
Possible License(s): AGPL-1.0
  1. """Microsoft Internet Explorer cookie loading on Windows.
  2. Copyright 2002-2003 Johnny Lee <typo_pl@hotmail.com> (MSIE Perl code)
  3. Copyright 2002-2006 John J Lee <jjl@pobox.com> (The Python port)
  4. This code is free software; you can redistribute it and/or modify it
  5. under the terms of the BSD or ZPL 2.1 licenses (see the file
  6. COPYING.txt included with the distribution).
  7. """
  8. # XXX names and comments are not great here
  9. import os, re, time, struct, logging
  10. if os.name == "nt":
  11. import _winreg
  12. from _clientcookie import FileCookieJar, CookieJar, Cookie, \
  13. MISSING_FILENAME_TEXT, LoadError
  14. debug = logging.getLogger("mechanize").debug
  15. def regload(path, leaf):
  16. key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, path, 0,
  17. _winreg.KEY_ALL_ACCESS)
  18. try:
  19. value = _winreg.QueryValueEx(key, leaf)[0]
  20. except WindowsError:
  21. value = None
  22. return value
  23. WIN32_EPOCH = 0x019db1ded53e8000L # 1970 Jan 01 00:00:00 in Win32 FILETIME
  24. def epoch_time_offset_from_win32_filetime(filetime):
  25. """Convert from win32 filetime to seconds-since-epoch value.
  26. MSIE stores create and expire times as Win32 FILETIME, which is 64
  27. bits of 100 nanosecond intervals since Jan 01 1601.
  28. mechanize expects time in 32-bit value expressed in seconds since the
  29. epoch (Jan 01 1970).
  30. """
  31. if filetime < WIN32_EPOCH:
  32. raise ValueError("filetime (%d) is before epoch (%d)" %
  33. (filetime, WIN32_EPOCH))
  34. return divmod((filetime - WIN32_EPOCH), 10000000L)[0]
  35. def binary_to_char(c): return "%02X" % ord(c)
  36. def binary_to_str(d): return "".join(map(binary_to_char, list(d)))
  37. class MSIEBase:
  38. magic_re = re.compile(r"Client UrlCache MMF Ver \d\.\d.*")
  39. padding = "\x0d\xf0\xad\x0b"
  40. msie_domain_re = re.compile(r"^([^/]+)(/.*)$")
  41. cookie_re = re.compile("Cookie\:.+\@([\x21-\xFF]+).*?"
  42. "(.+\@[\x21-\xFF]+\.txt)")
  43. # path under HKEY_CURRENT_USER from which to get location of index.dat
  44. reg_path = r"software\microsoft\windows" \
  45. r"\currentversion\explorer\shell folders"
  46. reg_key = "Cookies"
  47. def __init__(self):
  48. self._delayload_domains = {}
  49. def _delayload_domain(self, domain):
  50. # if necessary, lazily load cookies for this domain
  51. delayload_info = self._delayload_domains.get(domain)
  52. if delayload_info is not None:
  53. cookie_file, ignore_discard, ignore_expires = delayload_info
  54. try:
  55. self.load_cookie_data(cookie_file,
  56. ignore_discard, ignore_expires)
  57. except (LoadError, IOError):
  58. debug("error reading cookie file, skipping: %s", cookie_file)
  59. else:
  60. del self._delayload_domains[domain]
  61. def _load_cookies_from_file(self, filename):
  62. debug("Loading MSIE cookies file: %s", filename)
  63. cookies = []
  64. cookies_fh = open(filename)
  65. try:
  66. while 1:
  67. key = cookies_fh.readline()
  68. if key == "": break
  69. rl = cookies_fh.readline
  70. def getlong(rl=rl): return long(rl().rstrip())
  71. def getstr(rl=rl): return rl().rstrip()
  72. key = key.rstrip()
  73. value = getstr()
  74. domain_path = getstr()
  75. flags = getlong() # 0x2000 bit is for secure I think
  76. lo_expire = getlong()
  77. hi_expire = getlong()
  78. lo_create = getlong()
  79. hi_create = getlong()
  80. sep = getstr()
  81. if "" in (key, value, domain_path, flags, hi_expire, lo_expire,
  82. hi_create, lo_create, sep) or (sep != "*"):
  83. break
  84. m = self.msie_domain_re.search(domain_path)
  85. if m:
  86. domain = m.group(1)
  87. path = m.group(2)
  88. cookies.append({"KEY": key, "VALUE": value,
  89. "DOMAIN": domain, "PATH": path,
  90. "FLAGS": flags, "HIXP": hi_expire,
  91. "LOXP": lo_expire, "HICREATE": hi_create,
  92. "LOCREATE": lo_create})
  93. finally:
  94. cookies_fh.close()
  95. return cookies
  96. def load_cookie_data(self, filename,
  97. ignore_discard=False, ignore_expires=False):
  98. """Load cookies from file containing actual cookie data.
  99. Old cookies are kept unless overwritten by newly loaded ones.
  100. You should not call this method if the delayload attribute is set.
  101. I think each of these files contain all cookies for one user, domain,
  102. and path.
  103. filename: file containing cookies -- usually found in a file like
  104. C:\WINNT\Profiles\joe\Cookies\joe@blah[1].txt
  105. """
  106. now = int(time.time())
  107. cookie_data = self._load_cookies_from_file(filename)
  108. for cookie in cookie_data:
  109. flags = cookie["FLAGS"]
  110. secure = ((flags & 0x2000) != 0)
  111. filetime = (cookie["HIXP"] << 32) + cookie["LOXP"]
  112. expires = epoch_time_offset_from_win32_filetime(filetime)
  113. if expires < now:
  114. discard = True
  115. else:
  116. discard = False
  117. domain = cookie["DOMAIN"]
  118. initial_dot = domain.startswith(".")
  119. if initial_dot:
  120. domain_specified = True
  121. else:
  122. # MSIE 5 does not record whether the domain cookie-attribute
  123. # was specified.
  124. # Assuming it wasn't is conservative, because with strict
  125. # domain matching this will match less frequently; with regular
  126. # Netscape tail-matching, this will match at exactly the same
  127. # times that domain_specified = True would. It also means we
  128. # don't have to prepend a dot to achieve consistency with our
  129. # own & Mozilla's domain-munging scheme.
  130. domain_specified = False
  131. # assume path_specified is false
  132. # XXX is there other stuff in here? -- eg. comment, commentURL?
  133. c = Cookie(0,
  134. cookie["KEY"], cookie["VALUE"],
  135. None, False,
  136. domain, domain_specified, initial_dot,
  137. cookie["PATH"], False,
  138. secure,
  139. expires,
  140. discard,
  141. None,
  142. None,
  143. {"flags": flags})
  144. if not ignore_discard and c.discard:
  145. continue
  146. if not ignore_expires and c.is_expired(now):
  147. continue
  148. CookieJar.set_cookie(self, c)
  149. def load_from_registry(self, ignore_discard=False, ignore_expires=False,
  150. username=None):
  151. """
  152. username: only required on win9x
  153. """
  154. cookies_dir = regload(self.reg_path, self.reg_key)
  155. filename = os.path.normpath(os.path.join(cookies_dir, "INDEX.DAT"))
  156. self.load(filename, ignore_discard, ignore_expires, username)
  157. def _really_load(self, index, filename, ignore_discard, ignore_expires,
  158. username):
  159. now = int(time.time())
  160. if username is None:
  161. username = os.environ['USERNAME'].lower()
  162. cookie_dir = os.path.dirname(filename)
  163. data = index.read(256)
  164. if len(data) != 256:
  165. raise LoadError("%s file is too short" % filename)
  166. # Cookies' index.dat file starts with 32 bytes of signature
  167. # followed by an offset to the first record, stored as a little-
  168. # endian DWORD.
  169. sig, size, data = data[:32], data[32:36], data[36:]
  170. size = struct.unpack("<L", size)[0]
  171. # check that sig is valid
  172. if not self.magic_re.match(sig) or size != 0x4000:
  173. raise LoadError("%s ['%s' %s] does not seem to contain cookies" %
  174. (str(filename), sig, size))
  175. # skip to start of first record
  176. index.seek(size, 0)
  177. sector = 128 # size of sector in bytes
  178. while 1:
  179. data = ""
  180. # Cookies are usually in two contiguous sectors, so read in two
  181. # sectors and adjust if not a Cookie.
  182. to_read = 2 * sector
  183. d = index.read(to_read)
  184. if len(d) != to_read:
  185. break
  186. data = data + d
  187. # Each record starts with a 4-byte signature and a count
  188. # (little-endian DWORD) of sectors for the record.
  189. sig, size, data = data[:4], data[4:8], data[8:]
  190. size = struct.unpack("<L", size)[0]
  191. to_read = (size - 2) * sector
  192. ## from urllib import quote
  193. ## print "data", quote(data)
  194. ## print "sig", quote(sig)
  195. ## print "size in sectors", size
  196. ## print "size in bytes", size*sector
  197. ## print "size in units of 16 bytes", (size*sector) / 16
  198. ## print "size to read in bytes", to_read
  199. ## print
  200. if sig != "URL ":
  201. assert sig in ("HASH", "LEAK", \
  202. self.padding, "\x00\x00\x00\x00"), \
  203. "unrecognized MSIE index.dat record: %s" % \
  204. binary_to_str(sig)
  205. if sig == "\x00\x00\x00\x00":
  206. # assume we've got all the cookies, and stop
  207. break
  208. if sig == self.padding:
  209. continue
  210. # skip the rest of this record
  211. assert to_read >= 0
  212. if size != 2:
  213. assert to_read != 0
  214. index.seek(to_read, 1)
  215. continue
  216. # read in rest of record if necessary
  217. if size > 2:
  218. more_data = index.read(to_read)
  219. if len(more_data) != to_read: break
  220. data = data + more_data
  221. cookie_re = ("Cookie\:%s\@([\x21-\xFF]+).*?" % username +
  222. "(%s\@[\x21-\xFF]+\.txt)" % username)
  223. m = re.search(cookie_re, data, re.I)
  224. if m:
  225. cookie_file = os.path.join(cookie_dir, m.group(2))
  226. if not self.delayload:
  227. try:
  228. self.load_cookie_data(cookie_file,
  229. ignore_discard, ignore_expires)
  230. except (LoadError, IOError):
  231. debug("error reading cookie file, skipping: %s",
  232. cookie_file)
  233. else:
  234. domain = m.group(1)
  235. i = domain.find("/")
  236. if i != -1:
  237. domain = domain[:i]
  238. self._delayload_domains[domain] = (
  239. cookie_file, ignore_discard, ignore_expires)
  240. class MSIECookieJar(MSIEBase, FileCookieJar):
  241. """FileCookieJar that reads from the Windows MSIE cookies database.
  242. MSIECookieJar can read the cookie files of Microsoft Internet Explorer
  243. (MSIE) for Windows version 5 on Windows NT and version 6 on Windows XP and
  244. Windows 98. Other configurations may also work, but are untested. Saving
  245. cookies in MSIE format is NOT supported. If you save cookies, they'll be
  246. in the usual Set-Cookie3 format, which you can read back in using an
  247. instance of the plain old CookieJar class. Don't save using the same
  248. filename that you loaded cookies from, because you may succeed in
  249. clobbering your MSIE cookies index file!
  250. You should be able to have LWP share Internet Explorer's cookies like
  251. this (note you need to supply a username to load_from_registry if you're on
  252. Windows 9x or Windows ME):
  253. cj = MSIECookieJar(delayload=1)
  254. # find cookies index file in registry and load cookies from it
  255. cj.load_from_registry()
  256. opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cj))
  257. response = opener.open("http://example.com/")
  258. Iterating over a delayloaded MSIECookieJar instance will not cause any
  259. cookies to be read from disk. To force reading of all cookies from disk,
  260. call read_all_cookies. Note that the following methods iterate over self:
  261. clear_temporary_cookies, clear_expired_cookies, __len__, __repr__, __str__
  262. and as_string.
  263. Additional methods:
  264. load_from_registry(ignore_discard=False, ignore_expires=False,
  265. username=None)
  266. load_cookie_data(filename, ignore_discard=False, ignore_expires=False)
  267. read_all_cookies()
  268. """
  269. def __init__(self, filename=None, delayload=False, policy=None):
  270. MSIEBase.__init__(self)
  271. FileCookieJar.__init__(self, filename, delayload, policy)
  272. def set_cookie(self, cookie):
  273. if self.delayload:
  274. self._delayload_domain(cookie.domain)
  275. CookieJar.set_cookie(self, cookie)
  276. def _cookies_for_request(self, request):
  277. """Return a list of cookies to be returned to server."""
  278. domains = self._cookies.copy()
  279. domains.update(self._delayload_domains)
  280. domains = domains.keys()
  281. cookies = []
  282. for domain in domains:
  283. cookies.extend(self._cookies_for_domain(domain, request))
  284. return cookies
  285. def _cookies_for_domain(self, domain, request):
  286. if not self._policy.domain_return_ok(domain, request):
  287. return []
  288. debug("Checking %s for cookies to return", domain)
  289. if self.delayload:
  290. self._delayload_domain(domain)
  291. return CookieJar._cookies_for_domain(self, domain, request)
  292. def read_all_cookies(self):
  293. """Eagerly read in all cookies."""
  294. if self.delayload:
  295. for domain in self._delayload_domains.keys():
  296. self._delayload_domain(domain)
  297. def load(self, filename, ignore_discard=False, ignore_expires=False,
  298. username=None):
  299. """Load cookies from an MSIE 'index.dat' cookies index file.
  300. filename: full path to cookie index file
  301. username: only required on win9x
  302. """
  303. if filename is None:
  304. if self.filename is not None: filename = self.filename
  305. else: raise ValueError(MISSING_FILENAME_TEXT)
  306. index = open(filename, "rb")
  307. try:
  308. self._really_load(index, filename, ignore_discard, ignore_expires,
  309. username)
  310. finally:
  311. index.close()