blob: d4259ae0b3bd676338fd979b18c243d02ac4316d [file] [log] [blame]
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001r"""UUID objects (universally unique identifiers) according to RFC 4122.
2
3This module provides immutable UUID objects (class UUID) and the functions
4uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5
5UUIDs as specified in RFC 4122.
6
7If all you want is a unique ID, you should probably call uuid1() or uuid4().
8Note that uuid1() may compromise privacy since it creates a UUID containing
9the computer's network address. uuid4() creates a random UUID.
10
11Typical usage:
12
13 >>> import uuid
14
15 # make a UUID based on the host ID and current time
Georg Brandl1d523e12009-12-19 18:23:28 +000016 >>> uuid.uuid1() # doctest: +SKIP
Thomas Wouters0e3f5912006-08-11 14:57:12 +000017 UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
18
19 # make a UUID using an MD5 hash of a namespace UUID and a name
20 >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
21 UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
22
23 # make a random UUID
Georg Brandl1d523e12009-12-19 18:23:28 +000024 >>> uuid.uuid4() # doctest: +SKIP
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025 UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
26
27 # make a UUID using a SHA-1 hash of a namespace UUID and a name
28 >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
29 UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
30
31 # make a UUID from a string of hex digits (braces and hyphens ignored)
32 >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
33
34 # convert a UUID to a string of hex digits in standard form
35 >>> str(x)
36 '00010203-0405-0607-0809-0a0b0c0d0e0f'
37
38 # get the raw 16 bytes of the UUID
39 >>> x.bytes
Guido van Rossum65b6a802007-07-09 14:03:08 +000040 b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
Thomas Wouters0e3f5912006-08-11 14:57:12 +000041
42 # make a UUID from a 16-byte string
43 >>> uuid.UUID(bytes=x.bytes)
44 UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
45"""
46
Benjamin Peterson788cb522015-10-29 20:38:04 -070047import os
48
Barry Warsaw8c130d72017-02-18 15:45:49 -050049from enum import Enum
50
51
Thomas Wouters0e3f5912006-08-11 14:57:12 +000052__author__ = 'Ka-Ping Yee <ping@zesty.ca>'
Thomas Wouters0e3f5912006-08-11 14:57:12 +000053
54RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [
55 'reserved for NCS compatibility', 'specified in RFC 4122',
56 'reserved for Microsoft compatibility', 'reserved for future definition']
57
Guido van Rossum65b6a802007-07-09 14:03:08 +000058int_ = int # The built-in int type
59bytes_ = bytes # The built-in bytes type
Guido van Rossume2a383d2007-01-15 16:59:06 +000060
Barry Warsaw8c130d72017-02-18 15:45:49 -050061
62class SafeUUID(Enum):
63 safe = 0
64 unsafe = -1
65 unknown = None
66
67
68class UUID:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069 """Instances of the UUID class represent UUIDs as specified in RFC 4122.
70 UUID objects are immutable, hashable, and usable as dictionary keys.
71 Converting a UUID to a string with str() yields something in the form
72 '12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000073 five possible forms: a similar string of hexadecimal digits, or a tuple
74 of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
75 48-bit values respectively) as an argument named 'fields', or a string
76 of 16 bytes (with all the integer fields in big-endian order) as an
77 argument named 'bytes', or a string of 16 bytes (with the first three
78 fields in little-endian order) as an argument named 'bytes_le', or a
79 single 128-bit integer as an argument named 'int'.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080
81 UUIDs have these read-only attributes:
82
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000083 bytes the UUID as a 16-byte string (containing the six
84 integer fields in big-endian byte order)
85
86 bytes_le the UUID as a 16-byte string (with time_low, time_mid,
87 and time_hi_version in little-endian byte order)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000088
89 fields a tuple of the six integer fields of the UUID,
90 which are also available as six individual attributes
91 and two derived attributes:
92
93 time_low the first 32 bits of the UUID
94 time_mid the next 16 bits of the UUID
95 time_hi_version the next 16 bits of the UUID
96 clock_seq_hi_variant the next 8 bits of the UUID
97 clock_seq_low the next 8 bits of the UUID
98 node the last 48 bits of the UUID
99
100 time the 60-bit timestamp
101 clock_seq the 14-bit sequence number
102
103 hex the UUID as a 32-character hexadecimal string
104
105 int the UUID as a 128-bit integer
106
107 urn the UUID as a URN as specified in RFC 4122
108
109 variant the UUID variant (one of the constants RESERVED_NCS,
110 RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE)
111
112 version the UUID version number (1 through 5, meaningful only
113 when the variant is RFC_4122)
Barry Warsaw8c130d72017-02-18 15:45:49 -0500114
115 is_safe An enum indicating whether the UUID has been generated in
116 a way that is safe for multiprocessing applications, via
117 uuid_generate_time_safe(3).
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000118 """
119
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000120 def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
Barry Warsaw8c130d72017-02-18 15:45:49 -0500121 int=None, version=None,
122 *, is_safe=SafeUUID.unknown):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000123 r"""Create a UUID from either a string of 32 hexadecimal digits,
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000124 a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
125 in little-endian order as the 'bytes_le' argument, a tuple of six
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000126 integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
127 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
128 the 'fields' argument, or a single 128-bit integer as the 'int'
129 argument. When a string of hex digits is given, curly braces,
130 hyphens, and a URN prefix are all optional. For example, these
131 expressions all yield the same UUID:
132
133 UUID('{12345678-1234-5678-1234-567812345678}')
134 UUID('12345678123456781234567812345678')
135 UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
136 UUID(bytes='\x12\x34\x56\x78'*4)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000137 UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
138 '\x12\x34\x56\x78\x12\x34\x56\x78')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139 UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
140 UUID(int=0x12345678123456781234567812345678)
141
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000142 Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must
143 be given. The 'version' argument is optional; if given, the resulting
144 UUID will have its variant and version set according to RFC 4122,
145 overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.
Barry Warsaw8c130d72017-02-18 15:45:49 -0500146
147 is_safe is an enum exposed as an attribute on the instance. It
148 indicates whether the UUID has been generated in a way that is safe
149 for multiprocessing applications, via uuid_generate_time_safe(3).
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000150 """
151
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000152 if [hex, bytes, bytes_le, fields, int].count(None) != 4:
Berker Peksagd02eb8a2016-03-20 16:49:10 +0200153 raise TypeError('one of the hex, bytes, bytes_le, fields, '
154 'or int arguments must be given')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000155 if hex is not None:
156 hex = hex.replace('urn:', '').replace('uuid:', '')
157 hex = hex.strip('{}').replace('-', '')
158 if len(hex) != 32:
159 raise ValueError('badly formed hexadecimal UUID string')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000160 int = int_(hex, 16)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000161 if bytes_le is not None:
162 if len(bytes_le) != 16:
163 raise ValueError('bytes_le is not a 16-char string')
Serhiy Storchakafa9be4f2014-09-06 22:14:04 +0300164 bytes = (bytes_le[4-1::-1] + bytes_le[6-1:4-1:-1] +
165 bytes_le[8-1:6-1:-1] + bytes_le[8:])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000166 if bytes is not None:
167 if len(bytes) != 16:
168 raise ValueError('bytes is not a 16-char string')
Guido van Rossum65b6a802007-07-09 14:03:08 +0000169 assert isinstance(bytes, bytes_), repr(bytes)
Philip Jenvey1221f6b2013-08-29 18:33:50 -0700170 int = int_.from_bytes(bytes, byteorder='big')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000171 if fields is not None:
172 if len(fields) != 6:
173 raise ValueError('fields is not a 6-tuple')
174 (time_low, time_mid, time_hi_version,
175 clock_seq_hi_variant, clock_seq_low, node) = fields
Guido van Rossume2a383d2007-01-15 16:59:06 +0000176 if not 0 <= time_low < 1<<32:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000177 raise ValueError('field 1 out of range (need a 32-bit value)')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000178 if not 0 <= time_mid < 1<<16:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000179 raise ValueError('field 2 out of range (need a 16-bit value)')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000180 if not 0 <= time_hi_version < 1<<16:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000181 raise ValueError('field 3 out of range (need a 16-bit value)')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000182 if not 0 <= clock_seq_hi_variant < 1<<8:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000183 raise ValueError('field 4 out of range (need an 8-bit value)')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000184 if not 0 <= clock_seq_low < 1<<8:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000185 raise ValueError('field 5 out of range (need an 8-bit value)')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000186 if not 0 <= node < 1<<48:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000187 raise ValueError('field 6 out of range (need a 48-bit value)')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000188 clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low
189 int = ((time_low << 96) | (time_mid << 80) |
190 (time_hi_version << 64) | (clock_seq << 48) | node)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000191 if int is not None:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000192 if not 0 <= int < 1<<128:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000193 raise ValueError('int is out of range (need a 128-bit value)')
194 if version is not None:
195 if not 1 <= version <= 5:
196 raise ValueError('illegal version number')
197 # Set the variant to RFC 4122.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000198 int &= ~(0xc000 << 48)
199 int |= 0x8000 << 48
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000200 # Set the version number.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000201 int &= ~(0xf000 << 64)
202 int |= version << 76
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000203 self.__dict__['int'] = int
Barry Warsaw8c130d72017-02-18 15:45:49 -0500204 self.__dict__['is_safe'] = is_safe
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000205
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000206 def __eq__(self, other):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000207 if isinstance(other, UUID):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000208 return self.int == other.int
209 return NotImplemented
210
Guido van Rossum65b6a802007-07-09 14:03:08 +0000211 # Q. What's the value of being able to sort UUIDs?
212 # A. Use them as keys in a B-Tree or similar mapping.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000213
214 def __lt__(self, other):
215 if isinstance(other, UUID):
216 return self.int < other.int
217 return NotImplemented
218
219 def __gt__(self, other):
220 if isinstance(other, UUID):
221 return self.int > other.int
222 return NotImplemented
223
224 def __le__(self, other):
225 if isinstance(other, UUID):
226 return self.int <= other.int
227 return NotImplemented
228
229 def __ge__(self, other):
230 if isinstance(other, UUID):
231 return self.int >= other.int
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000232 return NotImplemented
233
234 def __hash__(self):
235 return hash(self.int)
236
237 def __int__(self):
238 return self.int
239
240 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300241 return '%s(%r)' % (self.__class__.__name__, str(self))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000242
243 def __setattr__(self, name, value):
244 raise TypeError('UUID objects are immutable')
245
246 def __str__(self):
247 hex = '%032x' % self.int
248 return '%s-%s-%s-%s-%s' % (
249 hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])
250
Guido van Rossum65b6a802007-07-09 14:03:08 +0000251 @property
252 def bytes(self):
Serhiy Storchakafa9be4f2014-09-06 22:14:04 +0300253 return self.int.to_bytes(16, 'big')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000254
Guido van Rossum65b6a802007-07-09 14:03:08 +0000255 @property
256 def bytes_le(self):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000257 bytes = self.bytes
Serhiy Storchakafa9be4f2014-09-06 22:14:04 +0300258 return (bytes[4-1::-1] + bytes[6-1:4-1:-1] + bytes[8-1:6-1:-1] +
Guido van Rossum65b6a802007-07-09 14:03:08 +0000259 bytes[8:])
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000260
Guido van Rossum65b6a802007-07-09 14:03:08 +0000261 @property
262 def fields(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000263 return (self.time_low, self.time_mid, self.time_hi_version,
264 self.clock_seq_hi_variant, self.clock_seq_low, self.node)
265
Guido van Rossum65b6a802007-07-09 14:03:08 +0000266 @property
267 def time_low(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000268 return self.int >> 96
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000269
Guido van Rossum65b6a802007-07-09 14:03:08 +0000270 @property
271 def time_mid(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000272 return (self.int >> 80) & 0xffff
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000273
Guido van Rossum65b6a802007-07-09 14:03:08 +0000274 @property
275 def time_hi_version(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000276 return (self.int >> 64) & 0xffff
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000277
Guido van Rossum65b6a802007-07-09 14:03:08 +0000278 @property
279 def clock_seq_hi_variant(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000280 return (self.int >> 56) & 0xff
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000281
Guido van Rossum65b6a802007-07-09 14:03:08 +0000282 @property
283 def clock_seq_low(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000284 return (self.int >> 48) & 0xff
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000285
Guido van Rossum65b6a802007-07-09 14:03:08 +0000286 @property
287 def time(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000288 return (((self.time_hi_version & 0x0fff) << 48) |
289 (self.time_mid << 32) | self.time_low)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000290
Guido van Rossum65b6a802007-07-09 14:03:08 +0000291 @property
292 def clock_seq(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000293 return (((self.clock_seq_hi_variant & 0x3f) << 8) |
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000294 self.clock_seq_low)
295
Guido van Rossum65b6a802007-07-09 14:03:08 +0000296 @property
297 def node(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000298 return self.int & 0xffffffffffff
299
Guido van Rossum65b6a802007-07-09 14:03:08 +0000300 @property
301 def hex(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000302 return '%032x' % self.int
303
Guido van Rossum65b6a802007-07-09 14:03:08 +0000304 @property
305 def urn(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000306 return 'urn:uuid:' + str(self)
307
Guido van Rossum65b6a802007-07-09 14:03:08 +0000308 @property
309 def variant(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000310 if not self.int & (0x8000 << 48):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000311 return RESERVED_NCS
Guido van Rossume2a383d2007-01-15 16:59:06 +0000312 elif not self.int & (0x4000 << 48):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000313 return RFC_4122
Guido van Rossume2a383d2007-01-15 16:59:06 +0000314 elif not self.int & (0x2000 << 48):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000315 return RESERVED_MICROSOFT
316 else:
317 return RESERVED_FUTURE
318
Guido van Rossum65b6a802007-07-09 14:03:08 +0000319 @property
320 def version(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000321 # The version bits are only meaningful for RFC 4122 UUIDs.
322 if self.variant == RFC_4122:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000323 return int((self.int >> 76) & 0xf)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000324
Serhiy Storchaka57b96772014-11-07 12:23:30 +0200325def _popen(command, *args):
Victor Stinnerb9d01992014-10-21 22:33:10 +0200326 import os, shutil, subprocess
R David Murray4be1e242013-12-17 21:13:16 -0500327 executable = shutil.which(command)
328 if executable is None:
329 path = os.pathsep.join(('/sbin', '/usr/sbin'))
330 executable = shutil.which(command, path=path)
331 if executable is None:
332 return None
Serhiy Storchaka57b96772014-11-07 12:23:30 +0200333 # LC_ALL=C to ensure English output, stderr=DEVNULL to prevent output
334 # on stderr (Note: we don't have an example where the words we search
335 # for are actually localized, but in theory some system could do so.)
336 env = dict(os.environ)
337 env['LC_ALL'] = 'C'
338 proc = subprocess.Popen((executable,) + args,
339 stdout=subprocess.PIPE,
340 stderr=subprocess.DEVNULL,
341 env=env)
342 return proc
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000343
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200344def _find_mac(command, args, hw_identifiers, get_index):
R David Murray4be1e242013-12-17 21:13:16 -0500345 try:
Serhiy Storchaka57b96772014-11-07 12:23:30 +0200346 proc = _popen(command, *args.split())
347 if not proc:
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200348 return
Victor Stinnerb9d01992014-10-21 22:33:10 +0200349 with proc:
350 for line in proc.stdout:
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200351 words = line.lower().rstrip().split()
R David Murray4be1e242013-12-17 21:13:16 -0500352 for i in range(len(words)):
353 if words[i] in hw_identifiers:
354 try:
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200355 word = words[get_index(i)]
Serhiy Storchaka57b96772014-11-07 12:23:30 +0200356 mac = int(word.replace(b':', b''), 16)
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200357 if mac:
358 return mac
R David Murray4be1e242013-12-17 21:13:16 -0500359 except (ValueError, IndexError):
360 # Virtual interfaces, such as those provided by
361 # VPNs, do not have a colon-delimited MAC address
362 # as expected, but a 16-byte HWAddr separated by
363 # dashes. These should be ignored in favor of a
364 # real MAC address
365 pass
R David Murray0ce3e9d2013-12-17 21:14:41 -0500366 except OSError:
R David Murray4be1e242013-12-17 21:13:16 -0500367 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000368
369def _ifconfig_getnode():
370 """Get the hardware address on Unix by running ifconfig."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000371 # This works on Linux ('' or '-a'), Tru64 ('-av'), but not all Unixes.
372 for args in ('', '-a', '-av'):
Victor Stinnerb9d01992014-10-21 22:33:10 +0200373 mac = _find_mac('ifconfig', args, [b'hwaddr', b'ether'], lambda i: i+1)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000374 if mac:
375 return mac
376
Serhiy Storchakaac4aa7b2014-11-30 20:39:04 +0200377def _ip_getnode():
378 """Get the hardware address on Unix by running ip."""
379 # This works on Linux with iproute2.
380 mac = _find_mac('ip', 'link list', [b'link/ether'], lambda i: i+1)
381 if mac:
382 return mac
383
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200384def _arp_getnode():
385 """Get the hardware address on Unix by running arp."""
386 import os, socket
Serhiy Storchaka525d5ae2014-11-21 21:55:39 +0200387 try:
388 ip_addr = socket.gethostbyname(socket.gethostname())
389 except OSError:
390 return None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000391
392 # Try getting the MAC addr from arp based on our IP address (Solaris).
Serhiy Storchaka57b96772014-11-07 12:23:30 +0200393 return _find_mac('arp', '-an', [os.fsencode(ip_addr)], lambda i: -1)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000394
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200395def _lanscan_getnode():
396 """Get the hardware address on Unix by running lanscan."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000397 # This might work on HP-UX.
Serhiy Storchaka57b96772014-11-07 12:23:30 +0200398 return _find_mac('lanscan', '-ai', [b'lan0'], lambda i: 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000399
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200400def _netstat_getnode():
401 """Get the hardware address on Unix by running netstat."""
402 # This might work on AIX, Tru64 UNIX and presumably on IRIX.
403 try:
Serhiy Storchaka57b96772014-11-07 12:23:30 +0200404 proc = _popen('netstat', '-ia')
405 if not proc:
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200406 return
Serhiy Storchaka57b96772014-11-07 12:23:30 +0200407 with proc:
408 words = proc.stdout.readline().rstrip().split()
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200409 try:
Serhiy Storchaka57b96772014-11-07 12:23:30 +0200410 i = words.index(b'Address')
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200411 except ValueError:
412 return
Serhiy Storchaka57b96772014-11-07 12:23:30 +0200413 for line in proc.stdout:
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200414 try:
415 words = line.rstrip().split()
416 word = words[i]
Serhiy Storchaka57b96772014-11-07 12:23:30 +0200417 if len(word) == 17 and word.count(b':') == 5:
418 mac = int(word.replace(b':', b''), 16)
Serhiy Storchakae66bb962014-11-07 12:19:40 +0200419 if mac:
420 return mac
421 except (ValueError, IndexError):
422 pass
423 except OSError:
424 pass
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000425
426def _ipconfig_getnode():
427 """Get the hardware address on Windows by running ipconfig.exe."""
428 import os, re
429 dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
430 try:
431 import ctypes
432 buffer = ctypes.create_string_buffer(300)
433 ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)
434 dirs.insert(0, buffer.value.decode('mbcs'))
435 except:
436 pass
437 for dir in dirs:
438 try:
439 pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200440 except OSError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000441 continue
Serhiy Storchakafa9be4f2014-09-06 22:14:04 +0300442 with pipe:
Brian Curtin69cd87b2010-11-05 14:48:35 +0000443 for line in pipe:
444 value = line.split(':')[-1].strip().lower()
445 if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):
446 return int(value.replace('-', ''), 16)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000447
448def _netbios_getnode():
449 """Get the hardware address on Windows using NetBIOS calls.
450 See http://support.microsoft.com/kb/118623 for details."""
451 import win32wnet, netbios
452 ncb = netbios.NCB()
453 ncb.Command = netbios.NCBENUM
454 ncb.Buffer = adapters = netbios.LANA_ENUM()
455 adapters._pack()
456 if win32wnet.Netbios(ncb) != 0:
457 return
458 adapters._unpack()
459 for i in range(adapters.length):
460 ncb.Reset()
461 ncb.Command = netbios.NCBRESET
462 ncb.Lana_num = ord(adapters.lana[i])
463 if win32wnet.Netbios(ncb) != 0:
464 continue
465 ncb.Reset()
466 ncb.Command = netbios.NCBASTAT
467 ncb.Lana_num = ord(adapters.lana[i])
468 ncb.Callname = '*'.ljust(16)
469 ncb.Buffer = status = netbios.ADAPTER_STATUS()
470 if win32wnet.Netbios(ncb) != 0:
471 continue
472 status._unpack()
Serhiy Storchakafa9be4f2014-09-06 22:14:04 +0300473 bytes = status.adapter_address[:6]
474 if len(bytes) != 6:
475 continue
476 return int.from_bytes(bytes, 'big')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000477
478# Thanks to Thomas Heller for ctypes and for his help with its use here.
479
480# If ctypes is available, use it to find system routines for UUID generation.
Guido van Rossumfb56d8f2007-07-20 17:45:09 +0000481# XXX This makes the module non-thread-safe!
Benjamin Peterson788cb522015-10-29 20:38:04 -0700482_uuid_generate_time = _UuidCreate = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000483try:
484 import ctypes, ctypes.util
Steve Dower71a36f72015-07-14 13:25:03 -0700485 import sys
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000486
487 # The uuid_generate_* routines are provided by libuuid on at least
488 # Linux and FreeBSD, and provided by libc on Mac OS X.
Steve Dower71a36f72015-07-14 13:25:03 -0700489 _libnames = ['uuid']
490 if not sys.platform.startswith('win'):
491 _libnames.append('c')
492 for libname in _libnames:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000493 try:
494 lib = ctypes.CDLL(ctypes.util.find_library(libname))
Barry Warsaw8c130d72017-02-18 15:45:49 -0500495 except Exception: # pragma: nocover
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000496 continue
Barry Warsaw8c130d72017-02-18 15:45:49 -0500497 # Try to find the safe variety first.
498 if hasattr(lib, 'uuid_generate_time_safe'):
499 _uuid_generate_time = lib.uuid_generate_time_safe
500 # int uuid_generate_time_safe(uuid_t out);
501 break
502 elif hasattr(lib, 'uuid_generate_time'): # pragma: nocover
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000503 _uuid_generate_time = lib.uuid_generate_time
Barry Warsaw8c130d72017-02-18 15:45:49 -0500504 # void uuid_generate_time(uuid_t out);
505 _uuid_generate_time.restype = None
Benjamin Peterson788cb522015-10-29 20:38:04 -0700506 break
Steve Dower71a36f72015-07-14 13:25:03 -0700507 del _libnames
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000508
Ronald Oussoren0f377a52010-06-27 12:45:47 +0000509 # The uuid_generate_* functions are broken on MacOS X 10.5, as noted
Ronald Oussorenac764d32010-05-05 15:32:33 +0000510 # in issue #8621 the function generates the same sequence of values
511 # in the parent process and all children created using fork (unless
512 # those children use exec as well).
513 #
Ronald Oussoren0f377a52010-06-27 12:45:47 +0000514 # Assume that the uuid_generate functions are broken from 10.5 onward,
Ronald Oussorenac764d32010-05-05 15:32:33 +0000515 # the test can be adjusted when a later version is fixed.
Ronald Oussorenac764d32010-05-05 15:32:33 +0000516 if sys.platform == 'darwin':
Larry Hastings605a62d2012-06-24 04:33:36 -0700517 if int(os.uname().release.split('.')[0]) >= 9:
Benjamin Peterson788cb522015-10-29 20:38:04 -0700518 _uuid_generate_time = None
Ronald Oussorenac764d32010-05-05 15:32:33 +0000519
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000520 # On Windows prior to 2000, UuidCreate gives a UUID containing the
521 # hardware address. On Windows 2000 and later, UuidCreate makes a
522 # random UUID and UuidCreateSequential gives a UUID containing the
523 # hardware address. These routines are provided by the RPC runtime.
524 # NOTE: at least on Tim's WinXP Pro SP2 desktop box, while the last
525 # 6 bytes returned by UuidCreateSequential are fixed, they don't appear
526 # to bear any relationship to the MAC address of any network device
527 # on the box.
528 try:
529 lib = ctypes.windll.rpcrt4
530 except:
531 lib = None
532 _UuidCreate = getattr(lib, 'UuidCreateSequential',
533 getattr(lib, 'UuidCreate', None))
534except:
535 pass
536
537def _unixdll_getnode():
538 """Get the hardware address on Unix using ctypes."""
Guido van Rossum37410aa2007-08-24 04:13:42 +0000539 _buffer = ctypes.create_string_buffer(16)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000540 _uuid_generate_time(_buffer)
Guido van Rossumfb56d8f2007-07-20 17:45:09 +0000541 return UUID(bytes=bytes_(_buffer.raw)).node
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000542
543def _windll_getnode():
544 """Get the hardware address on Windows using ctypes."""
Guido van Rossum37410aa2007-08-24 04:13:42 +0000545 _buffer = ctypes.create_string_buffer(16)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000546 if _UuidCreate(_buffer) == 0:
Guido van Rossumfb56d8f2007-07-20 17:45:09 +0000547 return UUID(bytes=bytes_(_buffer.raw)).node
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000548
549def _random_getnode():
550 """Get a random node ID, with eighth bit set as suggested by RFC 4122."""
551 import random
Serhiy Storchakafa9be4f2014-09-06 22:14:04 +0300552 return random.getrandbits(48) | 0x010000000000
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000553
554_node = None
555
556def getnode():
557 """Get the hardware address as a 48-bit positive integer.
558
559 The first time this runs, it may launch a separate program, which could
560 be quite slow. If all attempts to obtain the hardware address fail, we
561 choose a random 48-bit number with its eighth bit set to 1 as recommended
562 in RFC 4122.
563 """
564
565 global _node
566 if _node is not None:
567 return _node
568
569 import sys
570 if sys.platform == 'win32':
571 getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode]
572 else:
Serhiy Storchakaac4aa7b2014-11-30 20:39:04 +0200573 getters = [_unixdll_getnode, _ifconfig_getnode, _ip_getnode,
574 _arp_getnode, _lanscan_getnode, _netstat_getnode]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000575
576 for getter in getters + [_random_getnode]:
577 try:
578 _node = getter()
579 except:
580 continue
581 if _node is not None:
582 return _node
583
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000584_last_timestamp = None
585
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000586def uuid1(node=None, clock_seq=None):
587 """Generate a UUID from a host ID, sequence number, and the current time.
588 If 'node' is not given, getnode() is used to obtain the hardware
589 address. If 'clock_seq' is given, it is used as the sequence number;
590 otherwise a random 14-bit sequence number is chosen."""
591
592 # When the system provides a version-1 UUID generator, use it (but don't
593 # use UuidCreate here because its UUIDs don't conform to RFC 4122).
594 if _uuid_generate_time and node is clock_seq is None:
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +0000595 _buffer = ctypes.create_string_buffer(16)
Barry Warsaw8c130d72017-02-18 15:45:49 -0500596 safely_generated = _uuid_generate_time(_buffer)
597 try:
598 is_safe = SafeUUID(safely_generated)
599 except ValueError:
600 is_safe = SafeUUID.unknown
601 return UUID(bytes=bytes_(_buffer.raw), is_safe=is_safe)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000602
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000603 global _last_timestamp
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000604 import time
605 nanoseconds = int(time.time() * 1e9)
606 # 0x01b21dd213814000 is the number of 100-ns intervals between the
607 # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000608 timestamp = int(nanoseconds/100) + 0x01b21dd213814000
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000609 if _last_timestamp is not None and timestamp <= _last_timestamp:
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000610 timestamp = _last_timestamp + 1
611 _last_timestamp = timestamp
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000612 if clock_seq is None:
613 import random
Serhiy Storchakafa9be4f2014-09-06 22:14:04 +0300614 clock_seq = random.getrandbits(14) # instead of stable storage
Guido van Rossume2a383d2007-01-15 16:59:06 +0000615 time_low = timestamp & 0xffffffff
616 time_mid = (timestamp >> 32) & 0xffff
617 time_hi_version = (timestamp >> 48) & 0x0fff
618 clock_seq_low = clock_seq & 0xff
619 clock_seq_hi_variant = (clock_seq >> 8) & 0x3f
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000620 if node is None:
621 node = getnode()
622 return UUID(fields=(time_low, time_mid, time_hi_version,
623 clock_seq_hi_variant, clock_seq_low, node), version=1)
624
625def uuid3(namespace, name):
626 """Generate a UUID from the MD5 hash of a namespace UUID and a name."""
Guido van Rossume7ba4952007-06-06 23:52:48 +0000627 from hashlib import md5
Guido van Rossum65b6a802007-07-09 14:03:08 +0000628 hash = md5(namespace.bytes + bytes(name, "utf-8")).digest()
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000629 return UUID(bytes=hash[:16], version=3)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000630
631def uuid4():
632 """Generate a random UUID."""
Benjamin Peterson788cb522015-10-29 20:38:04 -0700633 return UUID(bytes=os.urandom(16), version=4)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000634
635def uuid5(namespace, name):
636 """Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
Guido van Rossume7ba4952007-06-06 23:52:48 +0000637 from hashlib import sha1
Guido van Rossum65b6a802007-07-09 14:03:08 +0000638 hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest()
Guido van Rossum5ed033b2007-07-09 14:29:40 +0000639 return UUID(bytes=hash[:16], version=5)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000640
641# The following standard UUIDs are for use with uuid3() or uuid5().
642
643NAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
644NAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
645NAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
646NAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')