Debian Codegraph @

lib/UUID.pm

raw
1 package UUID;
2 require 5.005063; # see MIN_PERL_VERSION in Makefile.PL
3 use strict;
4 use warnings;
5 use Carp 'croak';
6
7 require Exporter;
8 require DynaLoader;
9
10 use vars qw(@ISA %EXPORT_TAGS @EXPORT_OK $VERSION);
11 @ISA = qw(DynaLoader);
12
13 $VERSION = '0.39';
14
15 %EXPORT_TAGS = (
16 'all' => [qw(
17 &clear &compare &copy &generate &generate_random &generate_time
18 &generate_v0 &generate_v1 &generate_v3 &generate_v4 &generate_v5
19 &generate_v6 &generate_v7 &is_null &parse &time &type &unparse
20 &unparse_lower &unparse_upper &uuid &uuid0 &uuid1 &uuid3 &uuid4
21 &uuid5 &uuid6 &uuid7 &variant &version
22 )],
23 );
24
25 @EXPORT_OK = @{$EXPORT_TAGS{'all'}};
26
27 bootstrap UUID $VERSION;
28
29 sub import {
30 for (my $i=scalar(@_)-1 ; $i>0 ; --$i) {
31 my $v = $_[$i];
32 chomp $v;
33 # :persist=FOO
34 if (length($v) > 8 and substr($v,0,8) eq ':persist') {
35 my $arg = substr $v, 8;
36 if (length($arg) < 2 or substr($arg, 0, 1) ne '=') {
37 croak "Usage: :persist=FILE";
38 }
39 my $file = substr $arg, 1;
40 _persist($file);
41 splice @_, $i, 1;
42 next;
43 }
44 # :mac=random
45 if (length($v) == 11 and $v eq ':mac=random') {
46 _hide_mac();
47 splice @_, $i, 1;
48 next;
49 }
50 # :mac=unique
51 if (length($v) == 11 and $v eq ':mac=unique') {
52 _hide_always();
53 splice @_, $i, 1;
54 next;
55 }
56 # :defer[=N]
57 if (length($v) >= 6 and substr($v,0,6) eq ':defer') {
58 my $arg = substr $v, 6;
59 my $len = length $arg;
60 if ($len == 0) {
61 $arg = '=0.001';
62 }
63 elsif ($len == 1 or substr($arg, 0, 1) ne '=') {
64 croak "Usage: :defer[=N]";
65 }
66 my $val = substr $arg, 1;
67 _defer($val);
68 splice @_, $i, 1;
69 next;
70 }
71 }
72 goto &Exporter::import;
73 }
74
75 # Preloaded methods go here.
76
77 1;
78 __END__
79
80 =head1 NAME
81
82 UUID - Universally Unique Identifier library for Perl
83
84 =head1 SYNOPSIS
85
86 use UUID qw(uuid); # see EXPORTS
87 my $str = uuid(); # generate version 4 UUID string
88
89 $str = uuid1(); # new version 1 UUID string
90 $str = uuid4(); # new version 4 UUID string
91 $str = uuid6(); # new version 6 UUID string
92 $str = uuid7(); # new version 7 UUID string
93
94 UUID::generate_v1($bin); # new version 1 binary UUID
95 UUID::generate_v4($bin); # new version 4 binary UUID
96 UUID::generate_v6($bin); # new version 6 binary UUID
97 UUID::generate_v7($bin); # new version 7 binary UUID
98
99 UUID::parse($str, $bin); # map string to binary UUID
100
101 UUID::unparse($bin, $str); # stringify $bin; prefer lowercase
102
103 UUID::compare($bin1, $bin2); # compare binary UUIDs
104 UUID::copy($dst, $src); # copy binary UUID from $src to $dst
105
106 UUID::clear($bin); # set binary UUID to NULL
107 UUID::is_null($bin); # compare binary UUID to NULL
108
109 UUID::time($bin); # return UUID time
110 UUID::type($bin); # return UUID type
111 UUID::variant($bin); # return UUID variant
112 UUID::version($bin); # return UUID version
113
114 UUID::generate($bin); # alias for generate_v1()
115 UUID::generate_time($bin); # alias for generate_v1()
116 UUID::generate_random($bin); # alias for generate_v4()
117
118 UUID::unparse_lower($bin, $str); # force lowercase stringify
119 UUID::unparse_upper($bin, $str); # force uppercase stringify
120
121 # NAMESPACE is 'dns', 'url', 'oid', or 'x500'; case-insensitive.
122 $str = uuid3(dns => 'www.example.com');
123 $str = uuid5(url => 'https://www.example.com/foo.html');
124
125 UUID::generate_v3($bin, dns => 'www.example.com');
126 UUID::generate_v5($bin, url => 'https://www.example.com/foo.txt');
127
128
129 =head1 DESCRIPTION
130
131 The UUID library is used to generate unique identifiers for objects that
132 may be accessible beyond the local system. For instance, they could be
133 used to generate unique HTTP cookies across multiple web servers without
134 communication between the servers, and without fear of a name clash.
135
136 The generated UUIDs can be reasonably expected to be unique within a
137 system, and unique across all systems, and are compatible with those
138 created by the Open Software Foundation (OSF) Distributed Computing
139 Environment (DCE).
140
141 All generated UUIDs are either version 1, 3, 4, 5, 6, or version 7. And
142 all are variant 1, meaning compliant with the OSF DCE standard as
143 described in RFC4122.
144
145 Versions 6 and 7 are not yet standardized. They are presented here as
146 proposed in RFC4122bis, version 14, and may change in the future.
147 RFC4122bis is noted to replace RFC4122, if approved.
148
149 =head1 FUNCTIONS
150
151 Most of the UUID functions expose the historically underlying
152 I<libuuid> C interface rather directly. That is, many return their
153 values in their parameters and nothing else.
154
155 Not very Perlish, but it's been like that for a long time so not likely
156 to change any time soon.
157
158 All take or return UUIDs in either binary or string format. The string
159 format resembles the following:
160
161 21b081a3-de83-4480-a14f-e89a1dcf8f0f
162
163 Or, in terms of printf(3) format:
164
165 "%08x-%04x-%04x-%04x-%012x"
166
167 The binary form is simply a packed 16 byte binary value.
168
169 =head2 B<clear(> I<$uuid> B<)>
170
171 Sets binary I<$uuid> equal to the value of the NULL UUID.
172
173 =head2 B<compare(> I<$uuid1>B<,> I<$uuid2> B<)>
174
175 Compares two binary UUIDs.
176
177 Returns an integer less than, equal to, or greater than zero if
178 I<$uuid1> is less than, equal to, or greater than I<$uuid2>.
179
180 If one is defined and the other not, the defined value is deemed the
181 larger.
182
183 If either operand is not a binary UUID, falls back to a simple string
184 comparison returning similar values.
185
186 =head2 B<copy(> I<$dst>B<,> I<$src> B<)>
187
188 Copies the binary I<$src> UUID to I<$dst>.
189
190 If I<$src> isn't a UUID, I<$dst> is set to the NULL UUID.
191
192 =head2 B<generate(> I<$uuid> B<)>
193
194 Alias for B<generate_v4()>.
195
196 Prior to version 0.33, this function provided either a binary version 4
197 UUID or fell back to version 1 in some cases. This is no longer the
198 case. The fallback feature was removed with the addition of an onboard
199 crypto-strength number generator.
200
201 =head2 B<generate_random(> I<$uuid> B<)>
202
203 Alias for B<generate_v4()>.
204
205 =head2 B<generate_time(> I<$uuid> B<)>
206
207 Alias for B<generate_v1()>.
208
209 =head2 B<generate_v1(> I<$uuid> B<)>
210
211 Generates a new version 1 binary UUID using the current time and the
212 local ethernet MAC address, if available.
213
214 If the MAC address is not available at startup, or a randomized address
215 is requested (see B<:mac> in B<EXPORTS>), a random address is used. The
216 multicast bit of this address is set to avoid conflict with addresses
217 returned from network cards.
218
219 =head2 B<generate_v3(> I<$uuid>, I<NAMESPACE> =E<gt> I<NAME> B<)>
220
221 Generate a new version 3 binary UUID using the given namespace and name
222 hashed through the MD5 algorithm.
223
224 Namespace is one of "dns", "url", "oid", or "x500", and
225 case-insensitive. It is used to select the namespace UUID to hash with
226 the name.
227
228 Name should be an entity from the given namespace, but can really be any
229 text.
230
231 =head2 B<generate_v4(> I<$uuid> B<)>
232
233 Generates a new version 4 binary UUID using mostly random data. There
234 are 6 bits used for the UUID format, leaving 122 bits for randomness.
235
236 =head2 B<generate_v5(> I<$uuid>, I<NAMESPACE> =E<gt> I<NAME> B<)>
237
238 Generate a new version 5 binary UUID using the given namespace and name
239 hashed through the SHA1 algorithm.
240
241 Namespace is one of "dns", "url", "oid", or "x500", and
242 case-insensitive. It is used to select the namespace UUID to hash with
243 the name.
244
245 Name should be an entity from the given namespace, but can really be any
246 text.
247
248 =head2 B<generate_v6(> I<$uuid> B<)>
249
250 Generates a new version 6 binary UUID using the current time and the
251 local ethernet MAC address, if available.
252
253 If the MAC address is not available at startup, or a randomized address
254 is requested (see B<:mac> in B<EXPORTS>), a random address is used. The
255 multicast bit of this address is set to avoid conflict with addresses
256 returned from network cards.
257
258 Version 6 is the same as version 1, with reversed time fields to make it
259 more database friendly.
260
261 =head2 B<generate_v7(> I<$uuid> B<)>
262
263 Generates a new version 7 binary UUID using the current time and random
264 data. There are 6 bits used for the UUID format and 48 bits for
265 timestamp, leaving 74 bits for randomness.
266
267 Version 7 is the same as version 6, in that it uses reversed timestamp
268 fields, but also uses a Unix epoch time base instead of Gregorian.
269
270 =head2 B<is_null(> I<$uuid> B<)>
271
272 Compares the value of I<$uuid> to the NULL UUID.
273
274 Returns 1 if NULL, and 0 otherwise.
275
276 =head2 B<parse(> I<$string>B<,> I<$uuid> B<)>
277
278 Converts the string format UUID in I<$string> to binary and returns in
279 I<$uuid>. The previous content of I<$uuid>, if any, is lost.
280
281 Returns 0 on success and -1 on failure. Additionally on failure, the
282 content of I<$uuid> is unchanged.
283
284 =head2 B<time(> I<$uuid> B<)>
285
286 Returns the time element of a binary UUID in seconds since the epoch,
287 the same as I<Perl>'s B<time> function.
288
289 Keep in mind this only works for version 1, 6, and version 7 UUIDs.
290 Values returned from other versions are always 0.
291
292 =head2 B<type(> I<$uuid> B<)>
293
294 Alias for B<version()>.
295
296 =head2 B<unparse(> I<$uuid>B<,> I<$string> B<)>
297
298 Alias for B<unparse_lower()>.
299
300 Prior to version 0.32, casing of the return value was system-dependent.
301 Later versions are lowercase, per RFC4122.
302
303 =head2 B<unparse_lower(> I<$uuid>B<,> I<$string> B<)>
304
305 Converts the binary UUID in I<$uuid> to string format and returns in
306 I<$string>. The previous content of I<$string>, if any, is lost.
307
308 =head2 B<unparse_upper(> I<$uuid>B<,> I<$string> B<)>
309
310 Same as B<unparse_lower()> but I<$string> is forced to upper case.
311
312 =head2 B<uuid()>
313
314 Alias for B<uuid4()>.
315
316 =head2 B<uuid0()>
317
318 Returns a new string format NULL UUID.
319
320 =head2 B<uuid1()>
321
322 Returns a new string format version 1 UUID. Functionally the equivalent
323 of calling B<generate_v1()> then B<unparse()>, but throwing away the
324 intermediate binary UUID.
325
326 =head2 B<uuid3(NAMESPACE =E<gt> NAME)>
327
328 Same as B<uuid1()> but version 3. See B<generate_v3()>.
329
330 =head2 B<uuid4()>
331
332 Same as B<uuid1()> but version 4.
333
334 =head2 B<uuid5(NAMESPACE =E<gt> NAME)>
335
336 Same as B<uuid1()> but version 5. See B<generate_v5()>.
337
338 =head2 B<uuid6()>
339
340 Same as B<uuid1()> but version 6.
341
342 =head2 B<uuid7()>
343
344 Same as B<uuid1()> but version 7.
345
346 =head2 B<variant(> I<$uuid> B<)>
347
348 Returns the variant of binary I<$uuid>.
349
350 This module only generates variant 1 UUIDs. Others may be found in the
351 wild.
352
353 Known variants:
354
355 0 NCS
356 1 DCE
357 2 Microsoft
358 3 Other
359
360 =head2 B<version(> I<$uuid> B<)>
361
362 Returns the version of binary I<$uuid>.
363
364 This module only generates version 1, 3, 4, 5, 6, and version 7 UUIDs.
365 Others may be found in the wild.
366
367 Known versions:
368
369 v1 date/time and node address
370 v2 date/time and node address, security version
371 v3 namespace based, MD5 hash
372 v4 random
373 v5 namespace based, SHA-1 hash
374 v6 reverse date/time and node address
375 v7 reverse unix date/time and random
376 v8 custom
377
378 =head1 RANDOM NUMBERS
379
380 Version 4 and 7 UUIDs are partially filled with random numbers, as well
381 as versions 1 and 6 when used with the B<:mac> option.
382
383 Prior to version 0.33, UUID obtained randomness from the system's
384 I</dev/random> device, or similar interface. On some platforms it called
385 B<getrandom()> and on others it read directly from I</dev/urandom>. And
386 of course, Win32 did something completely different.
387
388 Starting in version 0.33, UUID generates random numbers itself using the
389 ChaCha20 algorithm which is considered crypto-strength in most circles.
390 This is the same algo used as the basis for many modern kernel RNGs,
391 albeit without the same entropy gathering ability.
392
393 To compensate, UUID mixes the output from ChaCha with output from
394 another RNG, Xoshiro. The idea is that by mixing the two, the true
395 output from either is effectively hidden, making discovery of either's
396 key much more unlikely than it already is. And without the keys, you
397 can't predict the future.
398
399 Well, that's the theory anyway.
400
401 Starting in version 0.38, the whole mix is initially seeded from the
402 best platform-specific source available which could be one or more of:
403
404 arc4random()
405 BCryptGenRandom()
406 CryptGenRandom()
407 getentropy()
408 getrandom()
409 /dev/urandom
410 /dev/random
411
412 =head1 TIME
413
414 Time-based UUIDs are formed with time-of-day information gathered from
415 I<Time::HiRes>. This provides a portable timestamp with 1us resolution
416 facilitating generation rates up to 1M UUIDs/sec without further action.
417
418 If UUIDs are required faster than 1us (i.e. > 1M UUIDs/sec), an internal
419 counter simulates 100ns intervals, which is the UUID resolution limit.
420 Each UUID within the same 1us tick will thus appear to be at successive
421 100ns intervals, which probably isn't true.
422
423 Should the internal counter exceed 9 within the same 1us period, it is
424 reset to 0 and the UUID sequence field is incremented, thus guaranteeing
425 uniqueness even though the time sequence will repeat.
426
427 This scheme raises the limit of time-based uniqueness to over 16G
428 UUIDs/sec, which is well beyond the best benchmarks seen to date.
429 (~14M/sec for v6 binary UUIDs on commodity hardware.)
430
431 Starting in version 0.38, the internal counter is moved to shared
432 memory, ensuring uniqueness among time-based UUIDs in forked or threaded
433 environments. Note that UUID must be loaded before forking or creating
434 threads for this guarantee to hold.
435
436 =head1 NAMESPACES
437
438 Versions 3 and 5 generate UUIDs within namespaces. What this really
439 means is that the I<NAME> value is concatenated with a dedicated
440 I<NAMESPACE> UUID before hashing.
441
442 Available namespaces and UUIDs:
443
444 dns 6ba7b810-9dad-11d1-80b4-00c04fd430c8
445 url 6ba7b811-9dad-11d1-80b4-00c04fd430c8
446 oid 6ba7b812-9dad-11d1-80b4-00c04fd430c8
447 x500 6ba7b814-9dad-11d1-80b4-00c04fd430c8
448
449 For example, if you need to create some UUIDs within your own
450 "questions" and "answers" namespaces using SHA1:
451
452 $ns_base = uuid5( dns => 'www.example.com' );
453
454 $ns_questions = uuid5( $ns_base, 'questions' );
455 $ns_answers = uuid5( $ns_base, 'answers' );
456
457 for $topic ( next_qa_aref() ) {
458 ($q, $a) = @$topic;
459 $uuid_question = uuid5( $ns_questions, $q );
460 $uuid_answer = uuid5( $ns_answers, $a );
461 ...
462 }
463
464 This way, you can deterministically convert existing (and likely
465 colliding) namespaces over to one UUID namespace, which is often useful
466 when merging datasets.
467
468 You also don't need to publish your base and namespace UUIDs. Anyone
469 using the same logic can generate the same question and answer UUIDs.
470
471 =head1 MAINTAINING STATE
472
473 Internal state is optionally maintained for timestamped UUIDs (versions
474 1, 6, and 7) via a file designated by the B<:persist> export tag. See
475 B<EXPORTS> for details.
476
477 The file records various internal states at the time the last UUID is
478 generated, preventing future instances from overlapping the prior UUID
479 sequence. This allows the sequence to absolutely survive reboots and,
480 more importantly, backwards resetting of system time.
481
482 If B<:persist> is not used, time resets will still be detected while the
483 module is loaded and handled by incrementing the UUID clock_seq field.
484 The clock_seq field is randomly initialized in this case anyway, so the
485 chance of overlap is low but still exists since clock_seq is only 14
486 bits wide. Using a random MAC will help (see B<:mac> in B<EXPORTS>),
487 adding an additional 48 bits of randomness.
488
489 B<NOTE:> Using B<:persist> incurs a serious performance penalty, in
490 excess of 95% on tested platforms. You can run C<make compare> in the
491 distribution directory to see how this might affect your application,
492 but unless you need many thousands of UUIDs/sec it's probably a
493 non-issue.
494
495 =head1 EXPORTS
496
497 None by default. All functions may be imported in the usual manner,
498 either individually or all at once using the B<:all> tag.
499
500 Beware that importing B<:all> clobbers I<Perl>'s B<time()>, not to
501 mention a few other commonly used subs, like B<copy()> from
502 I<File::Copy>.
503
504 =head2 B<:mac>=I<mode>
505
506 The MAC address used for MAC-inclusive UUIDS (versions 1 and 6) is
507 forced to always be random in one of two modes:
508
509 =over 4
510
511 I<random> The MAC address is generated once at startup and used through
512 the lifetime of the process. This is the default if a real MAC cannot be
513 found.
514
515 I<unique> A new MAC address is generated for each new UUID. It is not
516 guaranteed to be unique beyond the probability of randomness.
517
518 =back
519
520 =head2 B<:persist>=F<path/to/state.txt>
521
522 Path to timestamp state maintenance file. (See B<MAINTAINING STATE>.)
523 The path may be either relative or absolute.
524
525 If the file does not exist, it will be created provided the path
526 exists and the user has permission.
527
528 If the file cannot be opened, cannot be created, or is a symlink, UUID
529 will ignore it. No state will be maintained.
530
531 B<WARNING>: Do not B<:persist> in a public directory. See CVE-2013-4184.
532 UUID attempts to avoid this, but nothing is foolproof. Only YOU can
533 prevent symlink attacks!
534
535 =head2 B<:defer>[=I<N>]
536
537 Persistence of state is deferred I<N> seconds when generating time-based
538 UUIDs. More precisely, state is only saved every I<N> seconds. If UUIDs
539 are generated more often, those within the I<N> second window will not
540 save state.
541
542 Defer values greater than some platform-specific interval greatly reduce
543 the performance penalty introduced through persistence. While the
544 default, B<:defer=0.001>, is probably fine, you can run B<make persist>
545 in the distribution directory to see the effect of various values.
546
547 =head1 THREAD SAFETY
548
549 This module is believed to be thread safe.
550
551 =head1 UUID LIBRARY
552
553 Releases prior to UUID-0.32 required libuuid or similar be installed
554 first. This is no longer the case. Version 0.33 bundled the e2fsprogs
555 UUID code, and version 0.34 removed it altogether.
556
557 =head1 BENCHMARKS
558
559 There are a few benchmarks in the distribution ubin directory which
560 can be run either standalone or through the Makefile.
561
562 =head2 make compare
563
564 Runs all three of the following tests.
565
566 =head2 make speeds
567
568 Runs ubin/cmp_speeds.pl to compare the speeds of various UUID
569 versions.
570
571 =head2 make styles
572
573 Runs ubin/cmp_styles.pl to compare different UUID calling styles.
574
575 =head2 make persist
576
577 Runs ubin/cmp_persist.pl to compare different deferral values for
578 persistent state.
579
580 =head1 COPYRIGHT AND LICENSE
581
582 This software is Copyright (c) 2014-2026 by Rick Myers.
583
584 This is free software, licensed under:
585
586 The Artistic License 2.0 (GPL Compatible)
587
588 Details of this license can be found within the 'LICENSE' text file.
589
590 =head1 AUTHOR
591
592 Current maintainer:
593
594 Rick Myers <[email protected]>.
595
596 Authors and/or previous maintainers:
597
598 Lukas Zapletal
599
600 Joseph N. Hall
601
602 Colin Faber
603
604 Peter J. Braam
605
606 =head1 CONTRIBUTORS
607
608 David E. Wheeler
609
610 William Faulk
611
612 gregor herrmann
613
614 Slaven Rezic
615
616 twata
617
618 Christopher Rasch-Olsen Raa
619
620 Petr Pisar
621
622 Kurt Starsinic
623
624 Matt Martini
625
626 =head1 SEE ALSO
627
628 B<RFC4122> - L<https://www.rfc-editor.org/rfc/rfc4122>
629
630 B<RFC4122bis> - L<https://www.ietf.org/archive/id/draft-ietf-uuidrev-rfc4122bis-14.html>
631
632 B<perl(1)>.
633
634 =cut