uuid.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. r"""UUID objects (universally unique identifiers) according to RFC 4122.
  2. This module provides immutable UUID objects (class UUID) and the functions
  3. uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5
  4. UUIDs as specified in RFC 4122.
  5. If all you want is a unique ID, you should probably call uuid1() or uuid4().
  6. Note that uuid1() may compromise privacy since it creates a UUID containing
  7. the computer's network address. uuid4() creates a random UUID.
  8. Typical usage:
  9. >>> import uuid
  10. # make a UUID based on the host ID and current time
  11. >>> uuid.uuid1() # doctest: +SKIP
  12. UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
  13. # make a UUID using an MD5 hash of a namespace UUID and a name
  14. >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
  15. UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
  16. # make a random UUID
  17. >>> uuid.uuid4() # doctest: +SKIP
  18. UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
  19. # make a UUID using a SHA-1 hash of a namespace UUID and a name
  20. >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
  21. UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
  22. # make a UUID from a string of hex digits (braces and hyphens ignored)
  23. >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
  24. # convert a UUID to a string of hex digits in standard form
  25. >>> str(x)
  26. '00010203-0405-0607-0809-0a0b0c0d0e0f'
  27. # get the raw 16 bytes of the UUID
  28. >>> x.bytes
  29. b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
  30. # make a UUID from a 16-byte string
  31. >>> uuid.UUID(bytes=x.bytes)
  32. UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
  33. """
  34. import os
  35. import sys
  36. from enum import Enum
  37. __author__ = 'Ka-Ping Yee <ping@zesty.ca>'
  38. # The recognized platforms - known behaviors
  39. if sys.platform in ('win32', 'darwin'):
  40. _AIX = _LINUX = False
  41. else:
  42. import platform
  43. _platform_system = platform.system()
  44. _AIX = _platform_system == 'AIX'
  45. _LINUX = _platform_system == 'Linux'
  46. _MAC_DELIM = b':'
  47. _MAC_OMITS_LEADING_ZEROES = False
  48. if _AIX:
  49. _MAC_DELIM = b'.'
  50. _MAC_OMITS_LEADING_ZEROES = True
  51. RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [
  52. 'reserved for NCS compatibility', 'specified in RFC 4122',
  53. 'reserved for Microsoft compatibility', 'reserved for future definition']
  54. int_ = int # The built-in int type
  55. bytes_ = bytes # The built-in bytes type
  56. class SafeUUID(Enum):
  57. safe = 0
  58. unsafe = -1
  59. unknown = None
  60. class UUID:
  61. """Instances of the UUID class represent UUIDs as specified in RFC 4122.
  62. UUID objects are immutable, hashable, and usable as dictionary keys.
  63. Converting a UUID to a string with str() yields something in the form
  64. '12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts
  65. five possible forms: a similar string of hexadecimal digits, or a tuple
  66. of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
  67. 48-bit values respectively) as an argument named 'fields', or a string
  68. of 16 bytes (with all the integer fields in big-endian order) as an
  69. argument named 'bytes', or a string of 16 bytes (with the first three
  70. fields in little-endian order) as an argument named 'bytes_le', or a
  71. single 128-bit integer as an argument named 'int'.
  72. UUIDs have these read-only attributes:
  73. bytes the UUID as a 16-byte string (containing the six
  74. integer fields in big-endian byte order)
  75. bytes_le the UUID as a 16-byte string (with time_low, time_mid,
  76. and time_hi_version in little-endian byte order)
  77. fields a tuple of the six integer fields of the UUID,
  78. which are also available as six individual attributes
  79. and two derived attributes:
  80. time_low the first 32 bits of the UUID
  81. time_mid the next 16 bits of the UUID
  82. time_hi_version the next 16 bits of the UUID
  83. clock_seq_hi_variant the next 8 bits of the UUID
  84. clock_seq_low the next 8 bits of the UUID
  85. node the last 48 bits of the UUID
  86. time the 60-bit timestamp
  87. clock_seq the 14-bit sequence number
  88. hex the UUID as a 32-character hexadecimal string
  89. int the UUID as a 128-bit integer
  90. urn the UUID as a URN as specified in RFC 4122
  91. variant the UUID variant (one of the constants RESERVED_NCS,
  92. RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE)
  93. version the UUID version number (1 through 5, meaningful only
  94. when the variant is RFC_4122)
  95. is_safe An enum indicating whether the UUID has been generated in
  96. a way that is safe for multiprocessing applications, via
  97. uuid_generate_time_safe(3).
  98. """
  99. __slots__ = ('int', 'is_safe', '__weakref__')
  100. def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
  101. int=None, version=None,
  102. *, is_safe=SafeUUID.unknown):
  103. r"""Create a UUID from either a string of 32 hexadecimal digits,
  104. a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
  105. in little-endian order as the 'bytes_le' argument, a tuple of six
  106. integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
  107. 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
  108. the 'fields' argument, or a single 128-bit integer as the 'int'
  109. argument. When a string of hex digits is given, curly braces,
  110. hyphens, and a URN prefix are all optional. For example, these
  111. expressions all yield the same UUID:
  112. UUID('{12345678-1234-5678-1234-567812345678}')
  113. UUID('12345678123456781234567812345678')
  114. UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
  115. UUID(bytes='\x12\x34\x56\x78'*4)
  116. UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
  117. '\x12\x34\x56\x78\x12\x34\x56\x78')
  118. UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
  119. UUID(int=0x12345678123456781234567812345678)
  120. Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must
  121. be given. The 'version' argument is optional; if given, the resulting
  122. UUID will have its variant and version set according to RFC 4122,
  123. overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.
  124. is_safe is an enum exposed as an attribute on the instance. It
  125. indicates whether the UUID has been generated in a way that is safe
  126. for multiprocessing applications, via uuid_generate_time_safe(3).
  127. """
  128. if [hex, bytes, bytes_le, fields, int].count(None) != 4:
  129. raise TypeError('one of the hex, bytes, bytes_le, fields, '
  130. 'or int arguments must be given')
  131. if hex is not None:
  132. hex = hex.replace('urn:', '').replace('uuid:', '')
  133. hex = hex.strip('{}').replace('-', '')
  134. if len(hex) != 32:
  135. raise ValueError('badly formed hexadecimal UUID string')
  136. int = int_(hex, 16)
  137. if bytes_le is not None:
  138. if len(bytes_le) != 16:
  139. raise ValueError('bytes_le is not a 16-char string')
  140. bytes = (bytes_le[4-1::-1] + bytes_le[6-1:4-1:-1] +
  141. bytes_le[8-1:6-1:-1] + bytes_le[8:])
  142. if bytes is not None:
  143. if len(bytes) != 16:
  144. raise ValueError('bytes is not a 16-char string')
  145. assert isinstance(bytes, bytes_), repr(bytes)
  146. int = int_.from_bytes(bytes, byteorder='big')
  147. if fields is not None:
  148. if len(fields) != 6:
  149. raise ValueError('fields is not a 6-tuple')
  150. (time_low, time_mid, time_hi_version,
  151. clock_seq_hi_variant, clock_seq_low, node) = fields
  152. if not 0 <= time_low < 1<<32:
  153. raise ValueError('field 1 out of range (need a 32-bit value)')
  154. if not 0 <= time_mid < 1<<16:
  155. raise ValueError('field 2 out of range (need a 16-bit value)')
  156. if not 0 <= time_hi_version < 1<<16:
  157. raise ValueError('field 3 out of range (need a 16-bit value)')
  158. if not 0 <= clock_seq_hi_variant < 1<<8:
  159. raise ValueError('field 4 out of range (need an 8-bit value)')
  160. if not 0 <= clock_seq_low < 1<<8:
  161. raise ValueError('field 5 out of range (need an 8-bit value)')
  162. if not 0 <= node < 1<<48:
  163. raise ValueError('field 6 out of range (need a 48-bit value)')
  164. clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low
  165. int = ((time_low << 96) | (time_mid << 80) |
  166. (time_hi_version << 64) | (clock_seq << 48) | node)
  167. if int is not None:
  168. if not 0 <= int < 1<<128:
  169. raise ValueError('int is out of range (need a 128-bit value)')
  170. if version is not None:
  171. if not 1 <= version <= 5:
  172. raise ValueError('illegal version number')
  173. # Set the variant to RFC 4122.
  174. int &= ~(0xc000 << 48)
  175. int |= 0x8000 << 48
  176. # Set the version number.
  177. int &= ~(0xf000 << 64)
  178. int |= version << 76
  179. object.__setattr__(self, 'int', int)
  180. object.__setattr__(self, 'is_safe', is_safe)
  181. def __getstate__(self):
  182. d = {'int': self.int}
  183. if self.is_safe != SafeUUID.unknown:
  184. # is_safe is a SafeUUID instance. Return just its value, so that
  185. # it can be un-pickled in older Python versions without SafeUUID.
  186. d['is_safe'] = self.is_safe.value
  187. return d
  188. def __setstate__(self, state):
  189. object.__setattr__(self, 'int', state['int'])
  190. # is_safe was added in 3.7; it is also omitted when it is "unknown"
  191. object.__setattr__(self, 'is_safe',
  192. SafeUUID(state['is_safe'])
  193. if 'is_safe' in state else SafeUUID.unknown)
  194. def __eq__(self, other):
  195. if isinstance(other, UUID):
  196. return self.int == other.int
  197. return NotImplemented
  198. # Q. What's the value of being able to sort UUIDs?
  199. # A. Use them as keys in a B-Tree or similar mapping.
  200. def __lt__(self, other):
  201. if isinstance(other, UUID):
  202. return self.int < other.int
  203. return NotImplemented
  204. def __gt__(self, other):
  205. if isinstance(other, UUID):
  206. return self.int > other.int
  207. return NotImplemented
  208. def __le__(self, other):
  209. if isinstance(other, UUID):
  210. return self.int <= other.int
  211. return NotImplemented
  212. def __ge__(self, other):
  213. if isinstance(other, UUID):
  214. return self.int >= other.int
  215. return NotImplemented
  216. def __hash__(self):
  217. return hash(self.int)
  218. def __int__(self):
  219. return self.int
  220. def __repr__(self):
  221. return '%s(%r)' % (self.__class__.__name__, str(self))
  222. def __setattr__(self, name, value):
  223. raise TypeError('UUID objects are immutable')
  224. def __str__(self):
  225. hex = '%032x' % self.int
  226. return '%s-%s-%s-%s-%s' % (
  227. hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])
  228. @property
  229. def bytes(self):
  230. return self.int.to_bytes(16, 'big')
  231. @property
  232. def bytes_le(self):
  233. bytes = self.bytes
  234. return (bytes[4-1::-1] + bytes[6-1:4-1:-1] + bytes[8-1:6-1:-1] +
  235. bytes[8:])
  236. @property
  237. def fields(self):
  238. return (self.time_low, self.time_mid, self.time_hi_version,
  239. self.clock_seq_hi_variant, self.clock_seq_low, self.node)
  240. @property
  241. def time_low(self):
  242. return self.int >> 96
  243. @property
  244. def time_mid(self):
  245. return (self.int >> 80) & 0xffff
  246. @property
  247. def time_hi_version(self):
  248. return (self.int >> 64) & 0xffff
  249. @property
  250. def clock_seq_hi_variant(self):
  251. return (self.int >> 56) & 0xff
  252. @property
  253. def clock_seq_low(self):
  254. return (self.int >> 48) & 0xff
  255. @property
  256. def time(self):
  257. return (((self.time_hi_version & 0x0fff) << 48) |
  258. (self.time_mid << 32) | self.time_low)
  259. @property
  260. def clock_seq(self):
  261. return (((self.clock_seq_hi_variant & 0x3f) << 8) |
  262. self.clock_seq_low)
  263. @property
  264. def node(self):
  265. return self.int & 0xffffffffffff
  266. @property
  267. def hex(self):
  268. return '%032x' % self.int
  269. @property
  270. def urn(self):
  271. return 'urn:uuid:' + str(self)
  272. @property
  273. def variant(self):
  274. if not self.int & (0x8000 << 48):
  275. return RESERVED_NCS
  276. elif not self.int & (0x4000 << 48):
  277. return RFC_4122
  278. elif not self.int & (0x2000 << 48):
  279. return RESERVED_MICROSOFT
  280. else:
  281. return RESERVED_FUTURE
  282. @property
  283. def version(self):
  284. # The version bits are only meaningful for RFC 4122 UUIDs.
  285. if self.variant == RFC_4122:
  286. return int((self.int >> 76) & 0xf)
  287. def _get_command_stdout(command, *args):
  288. import io, os, shutil, subprocess
  289. try:
  290. path_dirs = os.environ.get('PATH', os.defpath).split(os.pathsep)
  291. path_dirs.extend(['/sbin', '/usr/sbin'])
  292. executable = shutil.which(command, path=os.pathsep.join(path_dirs))
  293. if executable is None:
  294. return None
  295. # LC_ALL=C to ensure English output, stderr=DEVNULL to prevent output
  296. # on stderr (Note: we don't have an example where the words we search
  297. # for are actually localized, but in theory some system could do so.)
  298. env = dict(os.environ)
  299. env['LC_ALL'] = 'C'
  300. proc = subprocess.Popen((executable,) + args,
  301. stdout=subprocess.PIPE,
  302. stderr=subprocess.DEVNULL,
  303. env=env)
  304. if not proc:
  305. return None
  306. stdout, stderr = proc.communicate()
  307. return io.BytesIO(stdout)
  308. except (OSError, subprocess.SubprocessError):
  309. return None
  310. # For MAC (a.k.a. IEEE 802, or EUI-48) addresses, the second least significant
  311. # bit of the first octet signifies whether the MAC address is universally (0)
  312. # or locally (1) administered. Network cards from hardware manufacturers will
  313. # always be universally administered to guarantee global uniqueness of the MAC
  314. # address, but any particular machine may have other interfaces which are
  315. # locally administered. An example of the latter is the bridge interface to
  316. # the Touch Bar on MacBook Pros.
  317. #
  318. # This bit works out to be the 42nd bit counting from 1 being the least
  319. # significant, or 1<<41. We'll prefer universally administered MAC addresses
  320. # over locally administered ones since the former are globally unique, but
  321. # we'll return the first of the latter found if that's all the machine has.
  322. #
  323. # See https://en.wikipedia.org/wiki/MAC_address#Universal_vs._local
  324. def _is_universal(mac):
  325. return not (mac & (1 << 41))
  326. def _find_mac_near_keyword(command, args, keywords, get_word_index):
  327. """Searches a command's output for a MAC address near a keyword.
  328. Each line of words in the output is case-insensitively searched for
  329. any of the given keywords. Upon a match, get_word_index is invoked
  330. to pick a word from the line, given the index of the match. For
  331. example, lambda i: 0 would get the first word on the line, while
  332. lambda i: i - 1 would get the word preceding the keyword.
  333. """
  334. stdout = _get_command_stdout(command, args)
  335. if stdout is None:
  336. return None
  337. first_local_mac = None
  338. for line in stdout:
  339. words = line.lower().rstrip().split()
  340. for i in range(len(words)):
  341. if words[i] in keywords:
  342. try:
  343. word = words[get_word_index(i)]
  344. mac = int(word.replace(_MAC_DELIM, b''), 16)
  345. except (ValueError, IndexError):
  346. # Virtual interfaces, such as those provided by
  347. # VPNs, do not have a colon-delimited MAC address
  348. # as expected, but a 16-byte HWAddr separated by
  349. # dashes. These should be ignored in favor of a
  350. # real MAC address
  351. pass
  352. else:
  353. if _is_universal(mac):
  354. return mac
  355. first_local_mac = first_local_mac or mac
  356. return first_local_mac or None
  357. def _parse_mac(word):
  358. # Accept 'HH:HH:HH:HH:HH:HH' MAC address (ex: '52:54:00:9d:0e:67'),
  359. # but reject IPv6 address (ex: 'fe80::5054:ff:fe9' or '123:2:3:4:5:6:7:8').
  360. #
  361. # Virtual interfaces, such as those provided by VPNs, do not have a
  362. # colon-delimited MAC address as expected, but a 16-byte HWAddr separated
  363. # by dashes. These should be ignored in favor of a real MAC address
  364. parts = word.split(_MAC_DELIM)
  365. if len(parts) != 6:
  366. return
  367. if _MAC_OMITS_LEADING_ZEROES:
  368. # (Only) on AIX the macaddr value given is not prefixed by 0, e.g.
  369. # en0 1500 link#2 fa.bc.de.f7.62.4 110854824 0 160133733 0 0
  370. # not
  371. # en0 1500 link#2 fa.bc.de.f7.62.04 110854824 0 160133733 0 0
  372. if not all(1 <= len(part) <= 2 for part in parts):
  373. return
  374. hexstr = b''.join(part.rjust(2, b'0') for part in parts)
  375. else:
  376. if not all(len(part) == 2 for part in parts):
  377. return
  378. hexstr = b''.join(parts)
  379. try:
  380. return int(hexstr, 16)
  381. except ValueError:
  382. return
  383. def _find_mac_under_heading(command, args, heading):
  384. """Looks for a MAC address under a heading in a command's output.
  385. The first line of words in the output is searched for the given
  386. heading. Words at the same word index as the heading in subsequent
  387. lines are then examined to see if they look like MAC addresses.
  388. """
  389. stdout = _get_command_stdout(command, args)
  390. if stdout is None:
  391. return None
  392. keywords = stdout.readline().rstrip().split()
  393. try:
  394. column_index = keywords.index(heading)
  395. except ValueError:
  396. return None
  397. first_local_mac = None
  398. for line in stdout:
  399. words = line.rstrip().split()
  400. try:
  401. word = words[column_index]
  402. except IndexError:
  403. continue
  404. mac = _parse_mac(word)
  405. if mac is None:
  406. continue
  407. if _is_universal(mac):
  408. return mac
  409. if first_local_mac is None:
  410. first_local_mac = mac
  411. return first_local_mac
  412. # The following functions call external programs to 'get' a macaddr value to
  413. # be used as basis for an uuid
  414. def _ifconfig_getnode():
  415. """Get the hardware address on Unix by running ifconfig."""
  416. # This works on Linux ('' or '-a'), Tru64 ('-av'), but not all Unixes.
  417. keywords = (b'hwaddr', b'ether', b'address:', b'lladdr')
  418. for args in ('', '-a', '-av'):
  419. mac = _find_mac_near_keyword('ifconfig', args, keywords, lambda i: i+1)
  420. if mac:
  421. return mac
  422. return None
  423. def _ip_getnode():
  424. """Get the hardware address on Unix by running ip."""
  425. # This works on Linux with iproute2.
  426. mac = _find_mac_near_keyword('ip', 'link', [b'link/ether'], lambda i: i+1)
  427. if mac:
  428. return mac
  429. return None
  430. def _arp_getnode():
  431. """Get the hardware address on Unix by running arp."""
  432. import os, socket
  433. try:
  434. ip_addr = socket.gethostbyname(socket.gethostname())
  435. except OSError:
  436. return None
  437. # Try getting the MAC addr from arp based on our IP address (Solaris).
  438. mac = _find_mac_near_keyword('arp', '-an', [os.fsencode(ip_addr)], lambda i: -1)
  439. if mac:
  440. return mac
  441. # This works on OpenBSD
  442. mac = _find_mac_near_keyword('arp', '-an', [os.fsencode(ip_addr)], lambda i: i+1)
  443. if mac:
  444. return mac
  445. # This works on Linux, FreeBSD and NetBSD
  446. mac = _find_mac_near_keyword('arp', '-an', [os.fsencode('(%s)' % ip_addr)],
  447. lambda i: i+2)
  448. # Return None instead of 0.
  449. if mac:
  450. return mac
  451. return None
  452. def _lanscan_getnode():
  453. """Get the hardware address on Unix by running lanscan."""
  454. # This might work on HP-UX.
  455. return _find_mac_near_keyword('lanscan', '-ai', [b'lan0'], lambda i: 0)
  456. def _netstat_getnode():
  457. """Get the hardware address on Unix by running netstat."""
  458. # This works on AIX and might work on Tru64 UNIX.
  459. return _find_mac_under_heading('netstat', '-ian', b'Address')
  460. def _ipconfig_getnode():
  461. """[DEPRECATED] Get the hardware address on Windows."""
  462. # bpo-40501: UuidCreateSequential() is now the only supported approach
  463. return _windll_getnode()
  464. def _netbios_getnode():
  465. """[DEPRECATED] Get the hardware address on Windows."""
  466. # bpo-40501: UuidCreateSequential() is now the only supported approach
  467. return _windll_getnode()
  468. # Import optional C extension at toplevel, to help disabling it when testing
  469. try:
  470. import _uuid
  471. _generate_time_safe = getattr(_uuid, "generate_time_safe", None)
  472. _UuidCreate = getattr(_uuid, "UuidCreate", None)
  473. _has_uuid_generate_time_safe = _uuid.has_uuid_generate_time_safe
  474. except ImportError:
  475. _uuid = None
  476. _generate_time_safe = None
  477. _UuidCreate = None
  478. _has_uuid_generate_time_safe = None
  479. def _load_system_functions():
  480. """[DEPRECATED] Platform-specific functions loaded at import time"""
  481. def _unix_getnode():
  482. """Get the hardware address on Unix using the _uuid extension module."""
  483. if _generate_time_safe:
  484. uuid_time, _ = _generate_time_safe()
  485. return UUID(bytes=uuid_time).node
  486. def _windll_getnode():
  487. """Get the hardware address on Windows using the _uuid extension module."""
  488. if _UuidCreate:
  489. uuid_bytes = _UuidCreate()
  490. return UUID(bytes_le=uuid_bytes).node
  491. def _random_getnode():
  492. """Get a random node ID."""
  493. # RFC 4122, $4.1.6 says "For systems with no IEEE address, a randomly or
  494. # pseudo-randomly generated value may be used; see Section 4.5. The
  495. # multicast bit must be set in such addresses, in order that they will
  496. # never conflict with addresses obtained from network cards."
  497. #
  498. # The "multicast bit" of a MAC address is defined to be "the least
  499. # significant bit of the first octet". This works out to be the 41st bit
  500. # counting from 1 being the least significant bit, or 1<<40.
  501. #
  502. # See https://en.wikipedia.org/wiki/MAC_address#Unicast_vs._multicast
  503. import random
  504. return random.getrandbits(48) | (1 << 40)
  505. # _OS_GETTERS, when known, are targeted for a specific OS or platform.
  506. # The order is by 'common practice' on the specified platform.
  507. # Note: 'posix' and 'windows' _OS_GETTERS are prefixed by a dll/dlload() method
  508. # which, when successful, means none of these "external" methods are called.
  509. # _GETTERS is (also) used by test_uuid.py to SkipUnless(), e.g.,
  510. # @unittest.skipUnless(_uuid._ifconfig_getnode in _uuid._GETTERS, ...)
  511. if _LINUX:
  512. _OS_GETTERS = [_ip_getnode, _ifconfig_getnode]
  513. elif sys.platform == 'darwin':
  514. _OS_GETTERS = [_ifconfig_getnode, _arp_getnode, _netstat_getnode]
  515. elif sys.platform == 'win32':
  516. # bpo-40201: _windll_getnode will always succeed, so these are not needed
  517. _OS_GETTERS = []
  518. elif _AIX:
  519. _OS_GETTERS = [_netstat_getnode]
  520. else:
  521. _OS_GETTERS = [_ifconfig_getnode, _ip_getnode, _arp_getnode,
  522. _netstat_getnode, _lanscan_getnode]
  523. if os.name == 'posix':
  524. _GETTERS = [_unix_getnode] + _OS_GETTERS
  525. elif os.name == 'nt':
  526. _GETTERS = [_windll_getnode] + _OS_GETTERS
  527. else:
  528. _GETTERS = _OS_GETTERS
  529. _node = None
  530. def getnode():
  531. """Get the hardware address as a 48-bit positive integer.
  532. The first time this runs, it may launch a separate program, which could
  533. be quite slow. If all attempts to obtain the hardware address fail, we
  534. choose a random 48-bit number with its eighth bit set to 1 as recommended
  535. in RFC 4122.
  536. """
  537. global _node
  538. if _node is not None:
  539. return _node
  540. for getter in _GETTERS + [_random_getnode]:
  541. try:
  542. _node = getter()
  543. except:
  544. continue
  545. if (_node is not None) and (0 <= _node < (1 << 48)):
  546. return _node
  547. assert False, '_random_getnode() returned invalid value: {}'.format(_node)
  548. _last_timestamp = None
  549. def uuid1(node=None, clock_seq=None):
  550. """Generate a UUID from a host ID, sequence number, and the current time.
  551. If 'node' is not given, getnode() is used to obtain the hardware
  552. address. If 'clock_seq' is given, it is used as the sequence number;
  553. otherwise a random 14-bit sequence number is chosen."""
  554. # When the system provides a version-1 UUID generator, use it (but don't
  555. # use UuidCreate here because its UUIDs don't conform to RFC 4122).
  556. if _generate_time_safe is not None and node is clock_seq is None:
  557. uuid_time, safely_generated = _generate_time_safe()
  558. try:
  559. is_safe = SafeUUID(safely_generated)
  560. except ValueError:
  561. is_safe = SafeUUID.unknown
  562. return UUID(bytes=uuid_time, is_safe=is_safe)
  563. global _last_timestamp
  564. import time
  565. nanoseconds = time.time_ns()
  566. # 0x01b21dd213814000 is the number of 100-ns intervals between the
  567. # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
  568. timestamp = nanoseconds // 100 + 0x01b21dd213814000
  569. if _last_timestamp is not None and timestamp <= _last_timestamp:
  570. timestamp = _last_timestamp + 1
  571. _last_timestamp = timestamp
  572. if clock_seq is None:
  573. import random
  574. clock_seq = random.getrandbits(14) # instead of stable storage
  575. time_low = timestamp & 0xffffffff
  576. time_mid = (timestamp >> 32) & 0xffff
  577. time_hi_version = (timestamp >> 48) & 0x0fff
  578. clock_seq_low = clock_seq & 0xff
  579. clock_seq_hi_variant = (clock_seq >> 8) & 0x3f
  580. if node is None:
  581. node = getnode()
  582. return UUID(fields=(time_low, time_mid, time_hi_version,
  583. clock_seq_hi_variant, clock_seq_low, node), version=1)
  584. def uuid3(namespace, name):
  585. """Generate a UUID from the MD5 hash of a namespace UUID and a name."""
  586. from hashlib import md5
  587. digest = md5(
  588. namespace.bytes + bytes(name, "utf-8"),
  589. usedforsecurity=False
  590. ).digest()
  591. return UUID(bytes=digest[:16], version=3)
  592. def uuid4():
  593. """Generate a random UUID."""
  594. return UUID(bytes=os.urandom(16), version=4)
  595. def uuid5(namespace, name):
  596. """Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
  597. from hashlib import sha1
  598. hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest()
  599. return UUID(bytes=hash[:16], version=5)
  600. # The following standard UUIDs are for use with uuid3() or uuid5().
  601. NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
  602. NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
  603. NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
  604. NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')