uuid.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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. RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [
  47. 'reserved for NCS compatibility', 'specified in RFC 4122',
  48. 'reserved for Microsoft compatibility', 'reserved for future definition']
  49. int_ = int # The built-in int type
  50. bytes_ = bytes # The built-in bytes type
  51. class SafeUUID(Enum):
  52. safe = 0
  53. unsafe = -1
  54. unknown = None
  55. class UUID:
  56. """Instances of the UUID class represent UUIDs as specified in RFC 4122.
  57. UUID objects are immutable, hashable, and usable as dictionary keys.
  58. Converting a UUID to a string with str() yields something in the form
  59. '12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts
  60. five possible forms: a similar string of hexadecimal digits, or a tuple
  61. of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
  62. 48-bit values respectively) as an argument named 'fields', or a string
  63. of 16 bytes (with all the integer fields in big-endian order) as an
  64. argument named 'bytes', or a string of 16 bytes (with the first three
  65. fields in little-endian order) as an argument named 'bytes_le', or a
  66. single 128-bit integer as an argument named 'int'.
  67. UUIDs have these read-only attributes:
  68. bytes the UUID as a 16-byte string (containing the six
  69. integer fields in big-endian byte order)
  70. bytes_le the UUID as a 16-byte string (with time_low, time_mid,
  71. and time_hi_version in little-endian byte order)
  72. fields a tuple of the six integer fields of the UUID,
  73. which are also available as six individual attributes
  74. and two derived attributes:
  75. time_low the first 32 bits of the UUID
  76. time_mid the next 16 bits of the UUID
  77. time_hi_version the next 16 bits of the UUID
  78. clock_seq_hi_variant the next 8 bits of the UUID
  79. clock_seq_low the next 8 bits of the UUID
  80. node the last 48 bits of the UUID
  81. time the 60-bit timestamp
  82. clock_seq the 14-bit sequence number
  83. hex the UUID as a 32-character hexadecimal string
  84. int the UUID as a 128-bit integer
  85. urn the UUID as a URN as specified in RFC 4122
  86. variant the UUID variant (one of the constants RESERVED_NCS,
  87. RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE)
  88. version the UUID version number (1 through 5, meaningful only
  89. when the variant is RFC_4122)
  90. is_safe An enum indicating whether the UUID has been generated in
  91. a way that is safe for multiprocessing applications, via
  92. uuid_generate_time_safe(3).
  93. """
  94. __slots__ = ('int', 'is_safe', '__weakref__')
  95. def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
  96. int=None, version=None,
  97. *, is_safe=SafeUUID.unknown):
  98. r"""Create a UUID from either a string of 32 hexadecimal digits,
  99. a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
  100. in little-endian order as the 'bytes_le' argument, a tuple of six
  101. integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
  102. 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
  103. the 'fields' argument, or a single 128-bit integer as the 'int'
  104. argument. When a string of hex digits is given, curly braces,
  105. hyphens, and a URN prefix are all optional. For example, these
  106. expressions all yield the same UUID:
  107. UUID('{12345678-1234-5678-1234-567812345678}')
  108. UUID('12345678123456781234567812345678')
  109. UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
  110. UUID(bytes='\x12\x34\x56\x78'*4)
  111. UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
  112. '\x12\x34\x56\x78\x12\x34\x56\x78')
  113. UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
  114. UUID(int=0x12345678123456781234567812345678)
  115. Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must
  116. be given. The 'version' argument is optional; if given, the resulting
  117. UUID will have its variant and version set according to RFC 4122,
  118. overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.
  119. is_safe is an enum exposed as an attribute on the instance. It
  120. indicates whether the UUID has been generated in a way that is safe
  121. for multiprocessing applications, via uuid_generate_time_safe(3).
  122. """
  123. if [hex, bytes, bytes_le, fields, int].count(None) != 4:
  124. raise TypeError('one of the hex, bytes, bytes_le, fields, '
  125. 'or int arguments must be given')
  126. if hex is not None:
  127. hex = hex.replace('urn:', '').replace('uuid:', '')
  128. hex = hex.strip('{}').replace('-', '')
  129. if len(hex) != 32:
  130. raise ValueError('badly formed hexadecimal UUID string')
  131. int = int_(hex, 16)
  132. if bytes_le is not None:
  133. if len(bytes_le) != 16:
  134. raise ValueError('bytes_le is not a 16-char string')
  135. bytes = (bytes_le[4-1::-1] + bytes_le[6-1:4-1:-1] +
  136. bytes_le[8-1:6-1:-1] + bytes_le[8:])
  137. if bytes is not None:
  138. if len(bytes) != 16:
  139. raise ValueError('bytes is not a 16-char string')
  140. assert isinstance(bytes, bytes_), repr(bytes)
  141. int = int_.from_bytes(bytes, byteorder='big')
  142. if fields is not None:
  143. if len(fields) != 6:
  144. raise ValueError('fields is not a 6-tuple')
  145. (time_low, time_mid, time_hi_version,
  146. clock_seq_hi_variant, clock_seq_low, node) = fields
  147. if not 0 <= time_low < 1<<32:
  148. raise ValueError('field 1 out of range (need a 32-bit value)')
  149. if not 0 <= time_mid < 1<<16:
  150. raise ValueError('field 2 out of range (need a 16-bit value)')
  151. if not 0 <= time_hi_version < 1<<16:
  152. raise ValueError('field 3 out of range (need a 16-bit value)')
  153. if not 0 <= clock_seq_hi_variant < 1<<8:
  154. raise ValueError('field 4 out of range (need an 8-bit value)')
  155. if not 0 <= clock_seq_low < 1<<8:
  156. raise ValueError('field 5 out of range (need an 8-bit value)')
  157. if not 0 <= node < 1<<48:
  158. raise ValueError('field 6 out of range (need a 48-bit value)')
  159. clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low
  160. int = ((time_low << 96) | (time_mid << 80) |
  161. (time_hi_version << 64) | (clock_seq << 48) | node)
  162. if int is not None:
  163. if not 0 <= int < 1<<128:
  164. raise ValueError('int is out of range (need a 128-bit value)')
  165. if version is not None:
  166. if not 1 <= version <= 5:
  167. raise ValueError('illegal version number')
  168. # Set the variant to RFC 4122.
  169. int &= ~(0xc000 << 48)
  170. int |= 0x8000 << 48
  171. # Set the version number.
  172. int &= ~(0xf000 << 64)
  173. int |= version << 76
  174. object.__setattr__(self, 'int', int)
  175. object.__setattr__(self, 'is_safe', is_safe)
  176. def __getstate__(self):
  177. d = {'int': self.int}
  178. if self.is_safe != SafeUUID.unknown:
  179. # is_safe is a SafeUUID instance. Return just its value, so that
  180. # it can be un-pickled in older Python versions without SafeUUID.
  181. d['is_safe'] = self.is_safe.value
  182. return d
  183. def __setstate__(self, state):
  184. object.__setattr__(self, 'int', state['int'])
  185. # is_safe was added in 3.7; it is also omitted when it is "unknown"
  186. object.__setattr__(self, 'is_safe',
  187. SafeUUID(state['is_safe'])
  188. if 'is_safe' in state else SafeUUID.unknown)
  189. def __eq__(self, other):
  190. if isinstance(other, UUID):
  191. return self.int == other.int
  192. return NotImplemented
  193. # Q. What's the value of being able to sort UUIDs?
  194. # A. Use them as keys in a B-Tree or similar mapping.
  195. def __lt__(self, other):
  196. if isinstance(other, UUID):
  197. return self.int < other.int
  198. return NotImplemented
  199. def __gt__(self, other):
  200. if isinstance(other, UUID):
  201. return self.int > other.int
  202. return NotImplemented
  203. def __le__(self, other):
  204. if isinstance(other, UUID):
  205. return self.int <= other.int
  206. return NotImplemented
  207. def __ge__(self, other):
  208. if isinstance(other, UUID):
  209. return self.int >= other.int
  210. return NotImplemented
  211. def __hash__(self):
  212. return hash(self.int)
  213. def __int__(self):
  214. return self.int
  215. def __repr__(self):
  216. return '%s(%r)' % (self.__class__.__name__, str(self))
  217. def __setattr__(self, name, value):
  218. raise TypeError('UUID objects are immutable')
  219. def __str__(self):
  220. hex = '%032x' % self.int
  221. return '%s-%s-%s-%s-%s' % (
  222. hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])
  223. @property
  224. def bytes(self):
  225. return self.int.to_bytes(16, 'big')
  226. @property
  227. def bytes_le(self):
  228. bytes = self.bytes
  229. return (bytes[4-1::-1] + bytes[6-1:4-1:-1] + bytes[8-1:6-1:-1] +
  230. bytes[8:])
  231. @property
  232. def fields(self):
  233. return (self.time_low, self.time_mid, self.time_hi_version,
  234. self.clock_seq_hi_variant, self.clock_seq_low, self.node)
  235. @property
  236. def time_low(self):
  237. return self.int >> 96
  238. @property
  239. def time_mid(self):
  240. return (self.int >> 80) & 0xffff
  241. @property
  242. def time_hi_version(self):
  243. return (self.int >> 64) & 0xffff
  244. @property
  245. def clock_seq_hi_variant(self):
  246. return (self.int >> 56) & 0xff
  247. @property
  248. def clock_seq_low(self):
  249. return (self.int >> 48) & 0xff
  250. @property
  251. def time(self):
  252. return (((self.time_hi_version & 0x0fff) << 48) |
  253. (self.time_mid << 32) | self.time_low)
  254. @property
  255. def clock_seq(self):
  256. return (((self.clock_seq_hi_variant & 0x3f) << 8) |
  257. self.clock_seq_low)
  258. @property
  259. def node(self):
  260. return self.int & 0xffffffffffff
  261. @property
  262. def hex(self):
  263. return '%032x' % self.int
  264. @property
  265. def urn(self):
  266. return 'urn:uuid:' + str(self)
  267. @property
  268. def variant(self):
  269. if not self.int & (0x8000 << 48):
  270. return RESERVED_NCS
  271. elif not self.int & (0x4000 << 48):
  272. return RFC_4122
  273. elif not self.int & (0x2000 << 48):
  274. return RESERVED_MICROSOFT
  275. else:
  276. return RESERVED_FUTURE
  277. @property
  278. def version(self):
  279. # The version bits are only meaningful for RFC 4122 UUIDs.
  280. if self.variant == RFC_4122:
  281. return int((self.int >> 76) & 0xf)
  282. def _popen(command, *args):
  283. import os, shutil, subprocess
  284. executable = shutil.which(command)
  285. if executable is None:
  286. path = os.pathsep.join(('/sbin', '/usr/sbin'))
  287. executable = shutil.which(command, path=path)
  288. if executable is None:
  289. return None
  290. # LC_ALL=C to ensure English output, stderr=DEVNULL to prevent output
  291. # on stderr (Note: we don't have an example where the words we search
  292. # for are actually localized, but in theory some system could do so.)
  293. env = dict(os.environ)
  294. env['LC_ALL'] = 'C'
  295. proc = subprocess.Popen((executable,) + args,
  296. stdout=subprocess.PIPE,
  297. stderr=subprocess.DEVNULL,
  298. env=env)
  299. return proc
  300. # For MAC (a.k.a. IEEE 802, or EUI-48) addresses, the second least significant
  301. # bit of the first octet signifies whether the MAC address is universally (0)
  302. # or locally (1) administered. Network cards from hardware manufacturers will
  303. # always be universally administered to guarantee global uniqueness of the MAC
  304. # address, but any particular machine may have other interfaces which are
  305. # locally administered. An example of the latter is the bridge interface to
  306. # the Touch Bar on MacBook Pros.
  307. #
  308. # This bit works out to be the 42nd bit counting from 1 being the least
  309. # significant, or 1<<41. We'll prefer universally administered MAC addresses
  310. # over locally administered ones since the former are globally unique, but
  311. # we'll return the first of the latter found if that's all the machine has.
  312. #
  313. # See https://en.wikipedia.org/wiki/MAC_address#Universal_vs._local
  314. def _is_universal(mac):
  315. return not (mac & (1 << 41))
  316. def _find_mac(command, args, hw_identifiers, get_index):
  317. first_local_mac = None
  318. try:
  319. proc = _popen(command, *args.split())
  320. if not proc:
  321. return None
  322. with proc:
  323. for line in proc.stdout:
  324. words = line.lower().rstrip().split()
  325. for i in range(len(words)):
  326. if words[i] in hw_identifiers:
  327. try:
  328. word = words[get_index(i)]
  329. mac = int(word.replace(b':', b''), 16)
  330. if _is_universal(mac):
  331. return mac
  332. first_local_mac = first_local_mac or mac
  333. except (ValueError, IndexError):
  334. # Virtual interfaces, such as those provided by
  335. # VPNs, do not have a colon-delimited MAC address
  336. # as expected, but a 16-byte HWAddr separated by
  337. # dashes. These should be ignored in favor of a
  338. # real MAC address
  339. pass
  340. except OSError:
  341. pass
  342. return first_local_mac or None
  343. def _ifconfig_getnode():
  344. """Get the hardware address on Unix by running ifconfig."""
  345. # This works on Linux ('' or '-a'), Tru64 ('-av'), but not all Unixes.
  346. keywords = (b'hwaddr', b'ether', b'address:', b'lladdr')
  347. for args in ('', '-a', '-av'):
  348. mac = _find_mac('ifconfig', args, keywords, lambda i: i+1)
  349. if mac:
  350. return mac
  351. return None
  352. def _ip_getnode():
  353. """Get the hardware address on Unix by running ip."""
  354. # This works on Linux with iproute2.
  355. mac = _find_mac('ip', 'link', [b'link/ether'], lambda i: i+1)
  356. if mac:
  357. return mac
  358. return None
  359. def _arp_getnode():
  360. """Get the hardware address on Unix by running arp."""
  361. import os, socket
  362. try:
  363. ip_addr = socket.gethostbyname(socket.gethostname())
  364. except OSError:
  365. return None
  366. # Try getting the MAC addr from arp based on our IP address (Solaris).
  367. mac = _find_mac('arp', '-an', [os.fsencode(ip_addr)], lambda i: -1)
  368. if mac:
  369. return mac
  370. # This works on OpenBSD
  371. mac = _find_mac('arp', '-an', [os.fsencode(ip_addr)], lambda i: i+1)
  372. if mac:
  373. return mac
  374. # This works on Linux, FreeBSD and NetBSD
  375. mac = _find_mac('arp', '-an', [os.fsencode('(%s)' % ip_addr)],
  376. lambda i: i+2)
  377. # Return None instead of 0.
  378. if mac:
  379. return mac
  380. return None
  381. def _lanscan_getnode():
  382. """Get the hardware address on Unix by running lanscan."""
  383. # This might work on HP-UX.
  384. return _find_mac('lanscan', '-ai', [b'lan0'], lambda i: 0)
  385. def _netstat_getnode():
  386. """Get the hardware address on Unix by running netstat."""
  387. # This might work on AIX, Tru64 UNIX.
  388. first_local_mac = None
  389. try:
  390. proc = _popen('netstat', '-ia')
  391. if not proc:
  392. return None
  393. with proc:
  394. words = proc.stdout.readline().rstrip().split()
  395. try:
  396. i = words.index(b'Address')
  397. except ValueError:
  398. return None
  399. for line in proc.stdout:
  400. try:
  401. words = line.rstrip().split()
  402. word = words[i]
  403. if len(word) == 17 and word.count(b':') == 5:
  404. mac = int(word.replace(b':', b''), 16)
  405. if _is_universal(mac):
  406. return mac
  407. first_local_mac = first_local_mac or mac
  408. except (ValueError, IndexError):
  409. pass
  410. except OSError:
  411. pass
  412. return first_local_mac or None
  413. def _ipconfig_getnode():
  414. """Get the hardware address on Windows by running ipconfig.exe."""
  415. import os, re, subprocess
  416. first_local_mac = None
  417. dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
  418. try:
  419. import ctypes
  420. buffer = ctypes.create_string_buffer(300)
  421. ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)
  422. dirs.insert(0, buffer.value.decode('mbcs'))
  423. except:
  424. pass
  425. for dir in dirs:
  426. try:
  427. proc = subprocess.Popen([os.path.join(dir, 'ipconfig'), '/all'],
  428. stdout=subprocess.PIPE,
  429. encoding="oem")
  430. except OSError:
  431. continue
  432. with proc:
  433. for line in proc.stdout:
  434. value = line.split(':')[-1].strip().lower()
  435. if re.fullmatch('(?:[0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):
  436. mac = int(value.replace('-', ''), 16)
  437. if _is_universal(mac):
  438. return mac
  439. first_local_mac = first_local_mac or mac
  440. return first_local_mac or None
  441. def _netbios_getnode():
  442. """Get the hardware address on Windows using NetBIOS calls.
  443. See http://support.microsoft.com/kb/118623 for details."""
  444. import win32wnet, netbios
  445. first_local_mac = None
  446. ncb = netbios.NCB()
  447. ncb.Command = netbios.NCBENUM
  448. ncb.Buffer = adapters = netbios.LANA_ENUM()
  449. adapters._pack()
  450. if win32wnet.Netbios(ncb) != 0:
  451. return None
  452. adapters._unpack()
  453. for i in range(adapters.length):
  454. ncb.Reset()
  455. ncb.Command = netbios.NCBRESET
  456. ncb.Lana_num = ord(adapters.lana[i])
  457. if win32wnet.Netbios(ncb) != 0:
  458. continue
  459. ncb.Reset()
  460. ncb.Command = netbios.NCBASTAT
  461. ncb.Lana_num = ord(adapters.lana[i])
  462. ncb.Callname = '*'.ljust(16)
  463. ncb.Buffer = status = netbios.ADAPTER_STATUS()
  464. if win32wnet.Netbios(ncb) != 0:
  465. continue
  466. status._unpack()
  467. bytes = status.adapter_address[:6]
  468. if len(bytes) != 6:
  469. continue
  470. mac = int.from_bytes(bytes, 'big')
  471. if _is_universal(mac):
  472. return mac
  473. first_local_mac = first_local_mac or mac
  474. return first_local_mac or None
  475. _generate_time_safe = _UuidCreate = None
  476. _has_uuid_generate_time_safe = None
  477. # Import optional C extension at toplevel, to help disabling it when testing
  478. try:
  479. import _uuid
  480. except ImportError:
  481. _uuid = None
  482. def _load_system_functions():
  483. """
  484. Try to load platform-specific functions for generating uuids.
  485. """
  486. global _generate_time_safe, _UuidCreate, _has_uuid_generate_time_safe
  487. if _has_uuid_generate_time_safe is not None:
  488. return
  489. _has_uuid_generate_time_safe = False
  490. if sys.platform == "darwin" and int(os.uname().release.split('.')[0]) < 9:
  491. # The uuid_generate_* functions are broken on MacOS X 10.5, as noted
  492. # in issue #8621 the function generates the same sequence of values
  493. # in the parent process and all children created using fork (unless
  494. # those children use exec as well).
  495. #
  496. # Assume that the uuid_generate functions are broken from 10.5 onward,
  497. # the test can be adjusted when a later version is fixed.
  498. pass
  499. elif _uuid is not None:
  500. _generate_time_safe = _uuid.generate_time_safe
  501. _has_uuid_generate_time_safe = _uuid.has_uuid_generate_time_safe
  502. return
  503. try:
  504. # If we couldn't find an extension module, try ctypes to find
  505. # system routines for UUID generation.
  506. # Thanks to Thomas Heller for ctypes and for his help with its use here.
  507. import ctypes
  508. import ctypes.util
  509. # The uuid_generate_* routines are provided by libuuid on at least
  510. # Linux and FreeBSD, and provided by libc on Mac OS X.
  511. _libnames = ['uuid']
  512. if not sys.platform.startswith('win'):
  513. _libnames.append('c')
  514. for libname in _libnames:
  515. try:
  516. lib = ctypes.CDLL(ctypes.util.find_library(libname))
  517. except Exception: # pragma: nocover
  518. continue
  519. # Try to find the safe variety first.
  520. if hasattr(lib, 'uuid_generate_time_safe'):
  521. _uuid_generate_time_safe = lib.uuid_generate_time_safe
  522. # int uuid_generate_time_safe(uuid_t out);
  523. def _generate_time_safe():
  524. _buffer = ctypes.create_string_buffer(16)
  525. res = _uuid_generate_time_safe(_buffer)
  526. return bytes(_buffer.raw), res
  527. _has_uuid_generate_time_safe = True
  528. break
  529. elif hasattr(lib, 'uuid_generate_time'): # pragma: nocover
  530. _uuid_generate_time = lib.uuid_generate_time
  531. # void uuid_generate_time(uuid_t out);
  532. _uuid_generate_time.restype = None
  533. def _generate_time_safe():
  534. _buffer = ctypes.create_string_buffer(16)
  535. _uuid_generate_time(_buffer)
  536. return bytes(_buffer.raw), None
  537. break
  538. # On Windows prior to 2000, UuidCreate gives a UUID containing the
  539. # hardware address. On Windows 2000 and later, UuidCreate makes a
  540. # random UUID and UuidCreateSequential gives a UUID containing the
  541. # hardware address. These routines are provided by the RPC runtime.
  542. # NOTE: at least on Tim's WinXP Pro SP2 desktop box, while the last
  543. # 6 bytes returned by UuidCreateSequential are fixed, they don't appear
  544. # to bear any relationship to the MAC address of any network device
  545. # on the box.
  546. try:
  547. lib = ctypes.windll.rpcrt4
  548. except:
  549. lib = None
  550. _UuidCreate = getattr(lib, 'UuidCreateSequential',
  551. getattr(lib, 'UuidCreate', None))
  552. except Exception as exc:
  553. import warnings
  554. warnings.warn(f"Could not find fallback ctypes uuid functions: {exc}",
  555. ImportWarning)
  556. def _unix_getnode():
  557. """Get the hardware address on Unix using the _uuid extension module
  558. or ctypes."""
  559. _load_system_functions()
  560. uuid_time, _ = _generate_time_safe()
  561. return UUID(bytes=uuid_time).node
  562. def _windll_getnode():
  563. """Get the hardware address on Windows using ctypes."""
  564. import ctypes
  565. _load_system_functions()
  566. _buffer = ctypes.create_string_buffer(16)
  567. if _UuidCreate(_buffer) == 0:
  568. return UUID(bytes=bytes_(_buffer.raw)).node
  569. def _random_getnode():
  570. """Get a random node ID."""
  571. # RFC 4122, $4.1.6 says "For systems with no IEEE address, a randomly or
  572. # pseudo-randomly generated value may be used; see Section 4.5. The
  573. # multicast bit must be set in such addresses, in order that they will
  574. # never conflict with addresses obtained from network cards."
  575. #
  576. # The "multicast bit" of a MAC address is defined to be "the least
  577. # significant bit of the first octet". This works out to be the 41st bit
  578. # counting from 1 being the least significant bit, or 1<<40.
  579. #
  580. # See https://en.wikipedia.org/wiki/MAC_address#Unicast_vs._multicast
  581. import random
  582. return random.getrandbits(48) | (1 << 40)
  583. # _OS_GETTERS, when known, are targeted for a specific OS or platform.
  584. # The order is by 'common practice' on the specified platform.
  585. # Note: 'posix' and 'windows' _OS_GETTERS are prefixed by a dll/dlload() method
  586. # which, when successful, means none of these "external" methods are called.
  587. # _GETTERS is (also) used by test_uuid.py to SkipUnless(), e.g.,
  588. # @unittest.skipUnless(_uuid._ifconfig_getnode in _uuid._GETTERS, ...)
  589. if _LINUX:
  590. _OS_GETTERS = [_ip_getnode, _ifconfig_getnode]
  591. elif sys.platform == 'darwin':
  592. _OS_GETTERS = [_ifconfig_getnode, _arp_getnode, _netstat_getnode]
  593. elif sys.platform == 'win32':
  594. _OS_GETTERS = [_netbios_getnode, _ipconfig_getnode]
  595. elif _AIX:
  596. _OS_GETTERS = [_netstat_getnode]
  597. else:
  598. _OS_GETTERS = [_ifconfig_getnode, _ip_getnode, _arp_getnode,
  599. _netstat_getnode, _lanscan_getnode]
  600. if os.name == 'posix':
  601. _GETTERS = [_unix_getnode] + _OS_GETTERS
  602. elif os.name == 'nt':
  603. _GETTERS = [_windll_getnode] + _OS_GETTERS
  604. else:
  605. _GETTERS = _OS_GETTERS
  606. _node = None
  607. def getnode(*, getters=None):
  608. """Get the hardware address as a 48-bit positive integer.
  609. The first time this runs, it may launch a separate program, which could
  610. be quite slow. If all attempts to obtain the hardware address fail, we
  611. choose a random 48-bit number with its eighth bit set to 1 as recommended
  612. in RFC 4122.
  613. """
  614. global _node
  615. if _node is not None:
  616. return _node
  617. for getter in _GETTERS + [_random_getnode]:
  618. try:
  619. _node = getter()
  620. except:
  621. continue
  622. if (_node is not None) and (0 <= _node < (1 << 48)):
  623. return _node
  624. assert False, '_random_getnode() returned invalid value: {}'.format(_node)
  625. _last_timestamp = None
  626. def uuid1(node=None, clock_seq=None):
  627. """Generate a UUID from a host ID, sequence number, and the current time.
  628. If 'node' is not given, getnode() is used to obtain the hardware
  629. address. If 'clock_seq' is given, it is used as the sequence number;
  630. otherwise a random 14-bit sequence number is chosen."""
  631. # When the system provides a version-1 UUID generator, use it (but don't
  632. # use UuidCreate here because its UUIDs don't conform to RFC 4122).
  633. _load_system_functions()
  634. if _generate_time_safe is not None and node is clock_seq is None:
  635. uuid_time, safely_generated = _generate_time_safe()
  636. try:
  637. is_safe = SafeUUID(safely_generated)
  638. except ValueError:
  639. is_safe = SafeUUID.unknown
  640. return UUID(bytes=uuid_time, is_safe=is_safe)
  641. global _last_timestamp
  642. import time
  643. nanoseconds = time.time_ns()
  644. # 0x01b21dd213814000 is the number of 100-ns intervals between the
  645. # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
  646. timestamp = nanoseconds // 100 + 0x01b21dd213814000
  647. if _last_timestamp is not None and timestamp <= _last_timestamp:
  648. timestamp = _last_timestamp + 1
  649. _last_timestamp = timestamp
  650. if clock_seq is None:
  651. import random
  652. clock_seq = random.getrandbits(14) # instead of stable storage
  653. time_low = timestamp & 0xffffffff
  654. time_mid = (timestamp >> 32) & 0xffff
  655. time_hi_version = (timestamp >> 48) & 0x0fff
  656. clock_seq_low = clock_seq & 0xff
  657. clock_seq_hi_variant = (clock_seq >> 8) & 0x3f
  658. if node is None:
  659. node = getnode()
  660. return UUID(fields=(time_low, time_mid, time_hi_version,
  661. clock_seq_hi_variant, clock_seq_low, node), version=1)
  662. def uuid3(namespace, name):
  663. """Generate a UUID from the MD5 hash of a namespace UUID and a name."""
  664. from hashlib import md5
  665. hash = md5(namespace.bytes + bytes(name, "utf-8")).digest()
  666. return UUID(bytes=hash[:16], version=3)
  667. def uuid4():
  668. """Generate a random UUID."""
  669. return UUID(bytes=os.urandom(16), version=4)
  670. def uuid5(namespace, name):
  671. """Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
  672. from hashlib import sha1
  673. hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest()
  674. return UUID(bytes=hash[:16], version=5)
  675. # The following standard UUIDs are for use with uuid3() or uuid5().
  676. NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
  677. NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
  678. NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
  679. NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')