-
Notifications
You must be signed in to change notification settings - Fork 0
/
uuid
executable file
·1077 lines (978 loc) · 34.2 KB
/
uuid
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
# Copyright (C) 2022 by J.W https://github.com/jakwings/uuid.sh
#
# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
# 0. You just DO WHAT THE FUCK YOU WANT TO.
set -euf
# copy-able text should go to fd 3
exec 3>&1 1>&2
unset -v IFS # unexport
export LC_ALL=C
#export PATH=/usr/bin:/bin
# Specifications:
# - https://tools.ietf.org/html/rfc4122
# - https://www.rfc-editor.org/rfc/inline-errata/rfc4122.html
# - https://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01
# - https://tools.ietf.org/html/draft-peabody-dispatch-new-uuid-format-02
# Some proposed namespace UUIDs:
# - 6ba7b810-9dad-11d1-80b4-00c04fd430c8 Fully-Qualified Domain Name (FQDN, DNS)
# - 6ba7b811-9dad-11d1-80b4-00c04fd430c8 Uniform Resource Locator (URL)
# - 6ba7b812-9dad-11d1-80b4-00c04fd430c8 ISO Object Identifier (ISO OID)
# - 6ba7b814-9dad-11d1-80b4-00c04fd430c8 X.500 Distinguished Name (X.500 DN)
help() {
printf '%s' 'uuid.sh -- a UUID Generator in POSIX Shell
Usage:
uuid [<options>] [<version> [<arguments>]]
Generate a Universally Unique Identifier.
The default version to use is "v4".
Options:
-h, --help
Show this help information.
-b, --binary
Output bytes in binary instead of plain-text format.
-d, --decode
Extract data from UUIDs generated by this program.
-g, --guid
Output variant-2 UUIDs by costing 1 bit of randomness.
-n, --next
Output the next UUID for version 1, 2, 6, or 7.
-s, --seed <number>
Use a deterministic pseudo-random number generator.
-l, --lowercase
Use lower-case letters for UUID output in plain text.
-u, --uppercase
Use upper-case letters for UUID output in plain text.
Summary of available versions:
uuid v0 [<uuid>]
... Output key=value pairs for sourcing when -d flag is on ...
uuid v1 [<period> [<sequence> [<node>]]]
... Gregorian timestamp plus privacy and security concerns ...
uuid v2 <domain> <identifier> [<period> [<sequence> [<node>]]]
... v1 of less available IDs per clock tick but DCE Security ...
uuid v3 <uuid> <text>...
... 16 bytes of 6 fixed bits from a 16-byte MD5 hash ...
uuid v4 [<count>]
... 16 (pseudo-)random bytes of 6 predetermined bits ...
uuid v5 <uuid> <text>...
... 16 bytes of 6 fixed bits from a 20-byte SHA-1 hash ...
uuid v6 [<period> [<sequence> [<node>]]]
... Draft#2: lexicographically sortable by Gregorian timestamp ...
uuid v7 [<second> [<subsecond> [<sequence> [<node>]]]]
... Draft#2: lexicographically sortable by Unix Epoch timestamp ...
uuid v8 [<year> [<month> [<day> [<hour> [<minute> [<node>]]]]]]
... Draft#2: lexicographically sortable by custom timestamp ...
Notes:
For time-based UUIDs, users must provide a system-wide global lock
to avoid race conditions among generators runing at the same time.
Please reference section 4.2 of RFC4122 for useful tips.
https://www.rfc-editor.org/rfc/inline-errata/rfc4122.html
'
}
echo() {
printf '%s\n' "$*"
}
ekho() {
printf '[ERROR] %s\n' "$*"
}
die() {
[ 0 -ge "$#" ] || ekho "$@" >&2
exit 1
}
have() {
[ -x "$(command -v "$1" 2>/dev/null)" ]
}
case_in() {
eval "! case \"\$1\" in (${2:-\"\"}) false; esac"
}
# PCG Random Number Generation ported to POSIX shell {
#
# Notice from original implementation in the C programming language:
#
# Copyright 2014-2019 Melissa O'Neill <[email protected]>,
# and the PCG Project contributors.
#
# Licensed under the Apache License, Version 2.0 (provided in
# LICENSE-APACHE.txt and at http://www.apache.org/licenses/LICENSE-2.0)
# or under the MIT license (provided in LICENSE-MIT.txt and at
# http://opensource.org/licenses/MIT), at your option. This code may not
# be copied, modified, or distributed except according to those terms.
#
# Distributed on an "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND, either
# express or implied. See your chosen license for details.
#
# For additional information about the PCG random number generation scheme,
# visit http://www.pcg-random.org/.
if [ '#-9223372036854775808' = "#$(( 9223372036854775807 + 1 ))" ]; then
pcg64si_srandom_r() {
set -- "$(( $1 ))" 6364136223846793005 1442695040888963407
pcg_state="$(( (0 * $2 + $3 + $1) * $2 + $3 ))" pcg_max=9223372036854775807
}
pcg64si_random_r() {
set -- "${pcg_state}" "$(( (pcg_state >> 1) & pcg_max ))"
pcg_state="$(( pcg_state * 6364136223846793005 + 1442695040888963407 ))"
pcg_number="$(( (($2 >> (($2 >> 58) + 4)) ^ $1) * -5840758589994634535 ))"
pcg_number="$(( (((pcg_number >> 1) & pcg_max) >> 42) ^ pcg_number ))"
}
pcg_srand() {
pcg64si_srandom_r "$1"
}
pcg_rand() {
# TODO: send patches to http://gondor.apana.org.au/~herbert/dash/
# XXX(dash): -9223372036854775807 <= $(( -9223372036854775808 ))
# XXX(dash): -9223372036854775808 <= $(( x )) # x='-9223372036854775808'
if [ 0 -lt "$#" ]; then # [0, 2^63 - 1] when $1=-9223372036854775808
# https://www.pcg-random.org/posts/bounded-rands.html
set -- "$(( $1 ))"; set -- "$1" "$(( (pcg_max % $1 + 1 % $1) % $1 ))"
while true; do
pcg64si_random_r
pcg_number="$(( pcg_number < 0 ? pcg_max - ~pcg_number : pcg_number ))"
if [ "$2" -le "${pcg_number}" ]; then
pcg_number="$(( pcg_number % $1 ))"
break
fi
done
else
pcg64si_random_r # [0 - 2^63, 2^63 - 1] <=> [0, 2^64 - 1]
fi
}
elif [ '#-2147483648' = "#$(( 2147483647 + 1 ))" ]; then
pcg32si_srandom_r() {
set -- "$(( $1 ))" 747796405 2891336453
pcg_state="$(( (0 * $2 + $3 + $1) * $2 + $3 ))" pcg_max=2147483647
}
pcg32si_random_r() {
set -- "${pcg_state}" "$(( (pcg_state >> 1) & pcg_max ))"
pcg_state="$(( pcg_state * 747796405 + 2891336453 ))"
pcg_number="$(( (($2 >> (($2 >> 27) + 3)) ^ $1) * 277803737 ))"
pcg_number="$(( (((pcg_number >> 1) & pcg_max) >> 21) ^ pcg_number ))"
}
pcg_srand() {
pcg32si_srandom_r "$1"
}
pcg_rand() {
if [ 0 -lt "$#" ]; then # [0, 2^31 - 1] when $1=-2147483648
set -- "$(( $1 ))"; set -- "$1" "$(( (pcg_max % $1 + 1 % $1) % $1 ))"
while true; do
pcg32si_random_r
pcg_number="$(( pcg_number < 0 ? pcg_max - ~pcg_number : pcg_number ))"
if [ "$2" -le "${pcg_number}" ]; then
pcg_number="$(( pcg_number % $1 ))"
break
fi
done
else
pcg32si_random_r # [0 - 2^31, 2^31 - 1] <=> [0, 2^32 - 1]
fi
}
fi
pcg_clear() {
unset -v pcg_state pcg_number pcg_max
}
pcg_clear
# PCG Random Number Generation ported to POSIX shell }
genseed() (
set -e
IFS=" ' "'!"#$%&()*+,-./:;<=>?@GHIJKLMNOPQRSTUVWXYZ[\]^_`ghijklmnopqrstuvwxyz{|}~'
s='' i=0
while [ 8 -gt "${#s}" ]; do
IFS='' read -r z
for z in $z; do
s="${s}${z%%[!0-9A-Fa-f]*}"
done
done </dev/urandom
printf '0x%.8s\n' "${s}"
)
hex2bin() {
while [ 0 -lt "${#1}" ]; do
case "$1" in
([0-9A-Fa-f][0-9A-Fa-f]*)
set -- "${1#??}" "$1"
printf "\\$(printf '%03o' "$(( 0x${2%"$1"} ))")"
;;
(*) set -- "${1#?}"
esac
done
}
namespace_hash() {
# XXX: use a termporary file to detect pipefail?
{ hex2bin "$2"; shift 2; printf '%s' "$*"; } | openssl dgst -"$1" -hex -c
}
# usage: gettime second nanosecond
gettime() {
set -- "$1" "$2" "$(date "+$1=%s $2=\"\$(format_int %N)\"")"
case "${3-}" in
(*" $2="*\ [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\)*) eval "$3" ;;
(*" $2="*) eval "${3%%\ *} $2=0" ;;
(*) eval "$1=\"\$(date '+%s')\"; $2=0"
esac
}
swap32() {
eval ": \$(( $1 = (($1 >> 24) & 0xFF) \
| (($1 >> 8) & 0xFF00) \
| (($1 << 8) & 0xFF0000) \
| (($1 << 24) & 0xFF000000) ))"
}
swap16() {
eval ": \$(( $1 = (($1 >> 8) & 0xFF) | (($1 << 8) & 0xFF00) ))"
}
format_int() {
# remove whitespace and leading zeros while preserving signness
printf '%s\n' "$(( ${1%%[0-9]*}${1#"${1%%[1-9]*}"} + 0 ))"
}
format_uint() {
# remove whitespace, number sign and leading zeros
printf '%s\n' "$(( ${1#"${1%%[1-9]*}"} + 0 ))"
}
format_uuid() {
[ 16 -eq "$#" ] || return 1
if [ 1 != "${flg_bin-}" ]; then
printf '%s%s%s%s-%s%s-%s%s-%s%s-%s%s%s%s%s%s\n' "$@"
else
if [ 1 = "${flg_guid-}" ]; then
set -- "$4" "$3" "$2" "$1" "$6" "$5" "$8" "$7" \
"$9" "${10}" "${11}" "${12}" "${13}" "${14}" "${15}" "${16}"
fi
hex2bin "$*"
fi
}
# XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
# ^ ^
# (4 bits) version variant (2 bits: 10xx, 3 bits: 110x)
check_uuid() (
set -e
s="$1" i=0 err='' poo='' ver='' var=''
while [ 0 -lt "${#s}" ]; do
case "$(( i += 1 ))" in
(37) break ;;
(9|14|19|24) case_in "${s}" '-*' || err=1 poo="${poo} ${i}" ;;
(15) case_in "${s}" '[12345678]*' || err=1 ver="${i}" ;;
(20) case_in "${s}" '[89ABCDabcd]*' || err=1 var="${i}" ;;
(*) case_in "${s}" '[0-9A-Fa-f]*' || err=1 poo="${poo} ${i}"
esac
s="${s#?}"
done
if [ 36 != "${i}" ]; then
err=1
fi
if [ '' != "${poo}" ]; then
poo="$(
set -e
k=0; for i in $poo; do printf "%$(( i - k ))s" '^'; k="${i}"; done
)"
ekho 'UUID contains invalid characters'; ekho "$1"; ekho "${poo}"
fi
if [ '' != "${ver}" ]; then
poo="$(printf "%${ver}s" '^')"
ekho 'UUID contains invalid version bits'; ekho "$1"; ekho "${poo}"
fi
if [ '' != "${var}" ]; then
poo="$(printf "%${var}s" '^')"
ekho 'UUID contains invalid variant bits'; ekho "$1"; ekho "${poo}"
fi
if [ '' != "${err}" ]; then
ekho 'UUID must be hexadecimal digits (0-9 A-F a-f) in the form:'
ekho 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
die
fi
)
check_node() {
{ [ "$(( $1 * 2 ))" -eq "${#3}" ] && ! case_in "$3" '*[!0-9A-Fa-f]*'; } \
|| die "node must be $1 bytes ($(( $1 * 2 )) hex digits)"
check_uint node 0 "$2" "$(( 0x$3 ))"
}
check_seed() {
if ! { [ 0 -le "$1" ] || [ 0 -ge "$1" ]; }; then
die "invalid seed number: \"$1\""
fi
format_int "$1"
}
check_uint() {
# FIXME: $3 must be less than 2^(bits - 1)
if ! [ "$2" -le "$4" ] || ! [ "$3" -ge "$4" ]; then
die "$1 out of range [$2, $3]: $4"
fi
format_uint "$4"
}
need_args() {
case "$#" in
(2) die "$1 requires $2 argument(s)" ;; # e.g. need_args cmd ${2+2} 2
(3) [ "$3" -eq "$2" ] || die "$1 requires $3 argument(s)" ;;
(4)
[ "$3" -le "$2" ] || die "$1 requires at least $3 argument(s)"
[ "$4" -ge "$2" ] || die "$1 requires at most $4 argument(s)"
;;
(*) return 1
esac
}
uuid_v_() {
[ 1 != "${cfg_32bit}" ] || die 'unable to manipulate 64-bit numbers'
# ALERT: should not run in subshell
unset -v epoch_offset max_period max_sequence \
now now_s now_ns domain identifier period sequence node x
pcg_clear
y0="${flg_guid-0}"
max_node=281474976710655 # 48 bits 0xFFFFFFFFFFFF
v="$1"; shift
case "${v}" in
(1)
# count of the 100ns intervals
# from Gregorian Epoch (1582-10-15T00:00:00Z)
# to Unix Epoch (1970-01-01T00:00:00Z)
epoch_offset=122192928000000000
max_period=1152921504606846975 # 60 bits 0x0FFFFFFFFFFFFFFF
max_sequence="$(( 0x3FFF >> y0 ))" # 14 bits 0x3FFF
;;
(2)
domain="$(check_uint domain 0 255 "$1")"
identifier="$(check_uint identifier 0 4294967295 "$2")"
shift 2
epoch_offset=122192928000000000
max_period=268435455 # 28 bits 0x0FFFFFFF
max_sequence="$(( 0x3F >> y0 ))" # 6 bits 0x3F
;;
(6)
epoch_offset=122192928000000000
max_period=1152921504606846975 # 60 bits 0x0FFFFFFFFFFFFFFF
max_sequence="$(( 0x3FFF >> y0 ))" # 14 bits 0x3FFF
;;
(*) die uuid_v_
esac
if [ 1 = "${cfg_seed+1}" ]; then
pcg_srand "${cfg_seed}"
else
gettime now_s now_ns
pcg_srand "$(( now_s ^ now_ns ))" # good enough ^[1]
fi
if [ 0 -ge "$#" ] || [ 1 = "${flg_next-}" ]; then
if [ 1 != "${now_s+1}" ]; then
gettime now_s now_ns #[1]: openssl would cost another 10ms for seeding
fi
# NOTE: we have no system-wide global lock, don't emulate high resolution
case "${v}" in
(1|6) : $(( now = epoch_offset + now_s * 10000000 + now_ns / 100 )) ;;
(2) : $(( now = (epoch_offset + now_s * 10000000) >> 32 )) ;;
esac
fi
pcg_rand "${max_node} + 1" # unconditional, more deterministic results
if [ 3 -gt "$#" ]; then # state unavailable
# NOTE: we don't generate a real (and unique?) MAC address
node="${pcg_number}"
else
node="$(check_node 6 "${max_node}" "$3")"
fi
pcg_rand "${max_sequence} + 1"
if [ 2 -gt "$#" ]; then # node or sequence unknown
sequence="${pcg_number}"
else
# NOTE: unable to detect node change, not going to increment clock sequence
sequence="$(check_uint sequence 0 "${max_sequence}" "$2")"
fi
if [ 1 != "${flg_next-}" ]; then
if [ 1 -le "$#" ]; then
now="$(check_uint period 0 "${max_period}" "$1")"
fi
else
if [ 3 -le "$#" ]; then # state available
period="$(check_uint period 0 "${max_period}" "$1")"
case "${v}" in
(6) : $(( sequence = (sequence + (period <= now)) % max_sequence )) ;;
(*)
# NOTE: presume we are the only generator in service
if [ "${period}" -eq "${now}" ]; then
die 'running out of UUID for now'
fi
if [ "${period}" -gt "${now}" ]; then # system clock went backward
: $(( sequence = (sequence + 1) % max_sequence ))
fi
esac
fi
fi
if [ upper != "${flg_case-}" ]; then x=x; else x=X; fi
if [ 1 = "${flg_decode-}" ]; then
if [ 2 != "${v}" ]; then
printf "%u %u %012${x}\\n" "${now}" "${sequence}" "${node}" >&3
else
printf "%u %u %u %u %012${x}\\n" "${domain}" "${identifier}" \
"${now}" "${sequence}" "${node}" >&3
fi
exit 0
fi
if [ 2 = "${v}" ]; then
: $(( now = (now << 32) + identifier ))
: $(( sequence = (sequence << 8) + domain ))
fi
if [ 6 != "${v}" ]; then
: $(( time_low = now & 0xFFFFFFFF ))
: $(( time_mid = (now >> 32) & 0xFFFF ))
: $(( time_high = (v << 12) | ((now >> 48) & 0x0FFF) ))
else
: $(( time_low = ((now >> 28) & 0xFFFFFFFF) ))
: $(( time_mid = (now >> 12) & 0xFFFF ))
: $(( time_high = (v << 12) | (now & 0x0FFF) ))
fi
: $(( y1 = !(${flg_guid-0}) ? 0x8000 : 0xC000 ))
: $(( y2 = !(${flg_guid-0}) ? 0x3FFF : 0x1FFF ))
: $(( clk_seq = y1 | (sequence & y2) )) # include variant bits
uuid="$(
set -e
if [ 11 = "${flg_bin-}${flg_guid-}" ]; then
swap32 time_low; swap16 time_mid; swap16 time_high
fi
printf "%08${x}-%04${x}-%04${x}-%04${x}-%012${x}" \
"${time_low}" "${time_mid}" "${time_high}" "${clk_seq}" "${node}"
)"
if [ 1 != "${flg_bin-}" ]; then
echo "${uuid}" >&3
else
hex2bin "${uuid}" >&3
fi
exit 0 # avoid conflicts with unknown variables
}
# 0 10 20 30
# 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | time_low |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | time_mid | time_high_and_version |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |clk_seq_hi_res | clk_seq_low | node (0-1) |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | node (2-5) |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
uuid_v1() (
set -e
need_args uuid_v1 "$#" 0 3
uuid_v_ 1 ${1+"$@"}
)
# 0 10 20 30
# 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | local_identifier |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | time_mid | time_high_and_version |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |clk_seq_hi_res | domain | node (0-1) |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | node (2-5) |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
uuid_v2() (
set -e
need_args uuid_v2 "$#" 2 5
uuid_v_ 2 ${1+"$@"}
)
# 0 10 20 30
# 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | time_high |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | time_mid | time_low_and_version |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |clk_seq_hi_res | clk_seq_low | node (0-1) |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | node (2-5) |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
uuid_v6() (
set -e
need_args uuid_v6 "$#" 0 3
uuid_v_ 6 ${1+"$@"}
)
# 0 10 20 30
# 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | unixts |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |unixts | subsec_a | ver | subsec_b |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |var$ subsec_seq_node |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | subsec_seq_node |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
uuid_v7() (
set -e
[ 1 != "${cfg_32bit}" ] || die 'unable to manipulate 64-bit numbers'
need_args uuid_v7 "$#" 0 4
unset -v max_second max_subsecond max_sequence max_node \
now_s now_ss second subsecond sequence node x
pcg_clear
# 0 10 20 30
# 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | second |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |second | microsecond | ver | microsecond |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |var$ sequence | node (0-1) |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | node (2-5) |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
y0="${flg_guid-0}"
max_second=68719476735 # 36 bits 0x0FFFFFFFFF
max_subsecond=16777215 # 24 bits 0x00FFFFFF
max_sequence="$(( 0x3FFF >> y0 ))" # 14 bits 0x3FFF
max_node=281474976710655 # 48 bits 0xFFFFFFFFFFFF
if [ 1 = "${cfg_seed+1}" ]; then
pcg_srand "${cfg_seed}"
else
gettime now_s now_ss
pcg_srand "$(( now_s ^ now_ss ))"
fi
if [ 1 -ge "$#" ] || [ 1 = "${flg_next-}" ]; then
if [ 1 != "${now_ss+1}" ]; then
gettime now_s now_ss
fi
: $(( now_s = now_s & 0x0FFFFFFFFF ))
: $(( now_ss = (now_ss / 1000) & 0x00FFFFFF ))
fi
pcg_rand "${max_node} + 1"
if [ 4 -gt "$#" ]; then
node="${pcg_number}"
else
node="$(check_node 6 "${max_node}" "$4")"
fi
if [ 3 -gt "$#" ]; then
sequence=0
else
sequence="$(check_uint sequence 0 "${max_sequence}" "$3")"
fi
pcg_rand "${max_subsecond} + 1"
if [ 1 -gt "$#" ]; then
subsecond="${now_ss}"
elif [ 2 -gt "$#" ]; then
subsecond="${pcg_number}"
else
subsecond="$(check_uint subsecond:microsecond 0 "${max_subsecond}" "$2")"
fi
if [ 1 -gt "$#" ]; then
second="${now_s}"
else
second="$(check_uint second 0 "${max_second}" "$1")"
fi
if [ 1 = "${flg_next-}" ]; then
if [ 4 -le "$#" ]; then # state available
if [ "${second}.${subsecond}" = "${now_s}.${now_ss}" ]; then
# NOTE: presume we are the only generator in service
[ "${sequence}" -lt "${max_sequence}" ] \
|| die 'running out of UUID for now'
: $(( sequence += 1 ))
elif [ "${second}" -gt "${now_s}" ]; then
sequence=0
elif [ "${second}" -eq "${now_s}" ] && [ "${subsecond}" -gt "${now_ss}" ]
then
sequence=0
fi
fi
second="${now_s}"
subsecond="${now_ss}"
fi
if [ upper != "${flg_case-}" ]; then x=x; else x=X; fi
if [ 1 = "${flg_decode-}" ]; then
printf "%u %u %u %012${x}\\n" \
"${second}" "${subsecond}" "${sequence}" "${node}" >&3
return 0
fi
: $(( y1 = !(${flg_guid-0}) ? 0x8000 : 0xC000 ))
: $(( y2 = !(${flg_guid-0}) ? 0x3FFF : 0x1FFF ))
: $(( s1_08 = (second >> 4) & 0xFFFFFFFF ))
: $(( s2_04 = ((second & 0xF) << 12) | ((subsecond >> 12) & 0x0FFF) ))
: $(( s3_04 = 0x7000 | (subsecond & 0x0FFF) ))
: $(( s4_04 = (y1 | (sequence & y2)) ))
: $(( s5_12 = node & 0xFFFFFFFFFFFF ))
uuid="$(
set -e
if [ 11 = "${flg_bin-}${flg_guid-}" ]; then
swap32 s1_08; swap16 s2_04; swap16 s3_04
fi
printf "%08${x}-%04${x}-%04${x}-%04${x}-%012${x}" \
"${s1_08}" "${s2_04}" "${s3_04}" "${s4_04}" "${s5_12}"
)"
if [ 1 != "${flg_bin-}" ]; then
echo "${uuid}" >&3
else
hex2bin "${uuid}" >&3
fi
)
# 0 10 20 30
# 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | year-month-day |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | hour:minute | ver | random1 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |var$ random2 | node (0-1) |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | node (2-5) |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# This custom layout is designed for:
# - Time-ordred and lexicographically sortable UUIDs.
# - Calendar-based version numbers like 2020.2.2 and 2020-02-02T20:20.
# - Local Object IDs (26-bit randomness, extendable by 48-bit node).
# - Easy to contruct UUIDs even by hand rolling dices.
# 32 bits is enough for counting minutes elapsed since the year 1970 til 9999.
uuid_v8() (
set -e
need_args uuid_v8 "$#" 0 6
unset -v year month day hour minute node1 node2 random1 random2 x
pcg_clear
pcg_srand "${cfg_seed-"$(genseed)"}"
if [ 0 -ge "$#" ]; then
day="$(date '+year=%Y month=%m day=%d hour=%H minute=%M')"
eval "${day}"
else
year="$(check_uint year 0 9999 "$1")"
month="$(check_uint month 1 12 "${2-1}")"
hour="$(check_uint hour 0 23 "${4-0}")"
minute="$(check_uint minute 0 59 "${5-0}")"
case "${month}" in
([13578]|10|12)
day="$(check_uint "day of month#${month}" 1 31 "${3-1}")" ;;
([469]|11)
day="$(check_uint "day of month#${month}" 1 30 "${3-1}")" ;;
(2)
if [ 0 -ne "$(( year % 100 == 0 ? year % 400 : year % 4 ))" ]; then
day="$(check_uint "day of month#${month}" 1 28 "${3-1}")"
else
day="$(check_uint "day of month#${month}" 1 29 "${3-1}")"
fi
esac
fi
: $(( year = 0x${year} ))
: $(( month = 0x${month} ))
: $(( day = 0x${day} ))
: $(( hour = 0x${hour} ))
: $(( minute = 0x${minute} ))
if [ 6 -gt "$#" ]; then
#max_node=281474976710655 # 48 bits 0xFFFFFFFFFFFF
pcg_rand 16777216; node1="${pcg_number}"
pcg_rand 16777216; node2="${pcg_number}"
else
if [ 12 -ne "${#6}" ] || case_in "$6" '*[!0-9A-Fa-f]*'; then
die "node must be 6 bytes (12 hex digits)"
fi
pcg_rand 16777216; pcg_rand 16777216
node1="$(( 0x${6%??????} ))" node2="$(( 0x${6#??????} ))"
fi
if [ upper != "${flg_case-}" ]; then x=x; else x=X; fi
if [ 1 = "${flg_decode-}" ]; then
printf "%x %x %x %x %x %06${x}%06${x}\\n" \
"${year}" "${month}" "${day}" "${hour}" "${minute}" \
"${node1}" "${node2}" >&3
return 0
fi
pcg_rand 0x1000; random1="${pcg_number}"
pcg_rand 0x4000; random2="${pcg_number}"
: $(( y1 = !(${flg_guid-0}) ? 0x8000 : 0xC000 ))
: $(( y2 = !(${flg_guid-0}) ? 0x3FFF : 0x1FFF ))
: $(( s1_08 = ((year << 16) | (month << 8) | day) & 0xFFFFFFFFFF ))
: $(( s2_04 = ((hour << 8) | minute) & 0xFFFF ))
: $(( s3_04 = 0x8000 | (random1 & 0x0FFF) ))
: $(( s4_04 = (y1 | (random2 & y2)) ))
uuid="$(
set -e
if [ 11 = "${flg_bin-}${flg_guid-}" ]; then
swap32 s1_08; swap16 s2_04; swap16 s3_04
fi
# WTF: mksh does not have printf built-in therefore negative numbers suck
printf "%04${x}%04${x}-%04${x}-%04${x}-%04${x}-%06${x}%06${x}" \
"$(( (s1_08 >> 16) & 0xFFFF ))" "$(( s1_08 & 0xFFFF ))" \
"${s2_04}" "${s3_04}" "${s4_04}" "${node1}" "${node2}"
)"
if [ 1 != "${flg_bin-}" ]; then
echo "${uuid}" >&3
else
hex2bin "${uuid}" >&3
fi
)
uuid_v0() (
set -e
need_args uuid_v0 "$#" 0 1
# generate 32 completely random bytes and make it look like a UUID ?
if [ 0 -ge "$#" ]; then
[ 1 != "${flg_decode-}" ] \
|| die "uuid v0 ... unable to work on v0 UUIDs with --decode"
[ 1 != "${flg_guid-}" ] \
|| die "uuid v0 ... unable to work on v0 UUIDs with --guid"
bytes="$(
set -e
pcg_clear; i=0
if [ 1 != "${cfg_seed+1}" ] && have openssl; then
s="$(openssl rand -hex 16)"
while [ 16 -ge "$(( i += 1 ))" ]; do
printf " ${cfg_fmt}" "$(( 0x${s%"${s#??}"} ))"
s="${s#??}"
done
else
seed="${cfg_seed-"$(genseed)"}"
pcg_srand "${seed}"
while [ 16 -ge "$(( i += 1 ))" ]; do
pcg_rand 256
printf " ${cfg_fmt}" "${pcg_number}"
done
fi
)"
format_uuid $bytes >&3 || die 'O MY RNG GOD'
return 0
fi
# 8-4-4-4-12 XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
check_uuid "$1"
IFS='-'; set -- $1; unset -v IFS
case "$3" in
([12345678]???) version="${3%???}" ;;
(*) die uuid_v0
esac
case "$4" in
([89ABab]???) variant=1 ;;
([CDcd]???) variant=2 ;;
(*) die uuid_v0
esac
if [ 1 = "${variant}" ]; then y0=0; else y0=1; fi
if [ upper != "${flg_case-}" ]; then x=x; else x=X; fi
case "${version}" in
([345])
if [ 1 != "${flg_decode-}" ]; then
die "uuid v0 ... unable to work on v${version} UUIDs without --decode"
else
echo "uuid_version=${version}" >&3
echo "uuid_variant=${variant}" >&3
fi
;;
(2)
[ 1 != "${cfg_32bit}" ] || die 'unable to manipulate 64-bit numbers'
s="$(
set -e
printf '%u\n%u\n%u\n%u\n'"%06${x}%06${x}\\n" \
"$(( 0x${4#??} ))" \
"$(( 0x$1 ))" \
"$(( (0x${3#?} << 16) | 0x$2 ))" \
"$(( 0x${4%??} & (0x3F >> y0) ))" \
"$(( 0x${5%??????} ))" "$(( 0x${5#??????} ))"
)"
if [ 1 != "${flg_decode-}" ]; then
"uuid_v${version}" $s
else
set -- "${version}" "${variant}" $s
s="$(printf 'uuid_%s=%%s\n' version variant \
domain identifier period sequence node)"
printf "${s}\\n" "$@" >&3
fi
;;
(1|6)
[ 1 != "${cfg_32bit}" ] || die 'unable to manipulate 64-bit numbers'
s="$(
set -e
if [ 1 = "${version}" ]; then
printf '%u\n' "$(( (0x${3#?} << 48) | (0x$2 << 32) | 0x$1 ))"
else
printf '%u\n' "$(( (0x$1 << 28) | (0x$2 << 12) | 0x${3#?} ))"
fi
printf '%u\n' "$(( 0x$4 & (0x3FFF >> y0) ))"
printf "%06${x}%06${x}\\n" "$(( 0x${5%??????} ))" "$(( 0x${5#??????} ))"
)"
if [ 1 != "${flg_decode-}" ]; then
"uuid_v${version}" $s
else
set -- "${version}" "${variant}" $s
s="$(printf 'uuid_%s=%%s\n' version variant period sequence node)"
printf "${s}\\n" "$@" >&3
fi
;;
(7)
[ 1 != "${cfg_32bit}" ] || die 'unable to manipulate 64-bit numbers'
s="$(
set -e
printf '%u\n%u\n%u\n'"%06${x}%06${x}\\n" \
"$(( (0x$1 << 4) | (0x$2 >> 12) ))" \
"$(( (0x${2#?} << 12) | 0x${3#?} ))" \
"$(( 0x$4 & (0x3FFF >> y0) ))" \
"$(( 0x${5%??????} ))" "$(( 0x${5#??????} ))"
)"
if [ 1 != "${flg_decode-}" ]; then
"uuid_v${version}" $s
else
set -- "${version}" "${variant}" $s
s="$(printf 'uuid_%s=%%s\n' version variant \
second subsecond sequence node)"
printf "${s}\\n" "$@" >&3
fi
;;
(8)
s="$(
set -e
printf '%x\n%x\n%x\n%x\n%x\n'"%06${x}%06${x}\\n" \
"$(( (0x$1 >> 16) & 0xFFFF ))" \
"$(( (0x$1 >> 8) & 0xFF ))" \
"$(( 0x$1 & 0xFF ))" \
"$(( (0x$2 >> 8) & 0xFF ))" \
"$(( 0x$2 & 0xFF ))" \
"$(( 0x${5%??????} ))" "$(( 0x${5#??????} ))"
)"
if [ 1 != "${flg_decode-}" ]; then
"uuid_v${version}" $s
else
set -- "${version}" "${variant}" $s
s="$(printf 'uuid_%s=%%s\n' version variant \
year month day hour minute node)"
printf "${s}\\n" "$@" >&3
fi
esac
)
uuid_v3() (
set -e
[ 1 != "${flg_decode-}" ] || die '--decode does not work on "uuid v3 ..."'
need_args uuid_v3 "$#" 2 "$#"
check_uuid "$1"
bytes="$(
set -e
hash="$(namespace_hash md5 "$@")"
: $(( y1 = !(${flg_guid-0}) ? 0x80 : 0xC0 ))
: $(( y2 = !(${flg_guid-0}) ? 0x3F : 0x1F ))
IFS=':' i=0
for x in ${hash##*' '}; do
case "$(( i += 1 ))" in
(7) printf " ${cfg_fmt}" "$(( 0x30 | (0x${x} & 0x0F) ))" ;;
(9) printf " ${cfg_fmt}" "$(( y1 | (0x${x} & y2 ) ))" ;;
(*) printf " ${cfg_fmt}" "$(( 0x${x} ))"
esac
done
)"
format_uuid $bytes >&3 || die 'openssl fouled things up'
)
uuid_v5() (
set -e
[ 1 != "${flg_decode-}" ] || die '--decode does not work on "uuid v5 ..."'
need_args uuid_v5 "$#" 2 "$#"
check_uuid "$1"
bytes="$(
set -e
hash="$(namespace_hash sha1 "$@")"
: $(( y1 = !(${flg_guid-0}) ? 0x80 : 0xC0 ))
: $(( y2 = !(${flg_guid-0}) ? 0x3F : 0x1F ))
IFS=':' i=0
for x in ${hash##*' '}; do
case "$(( i += 1 ))" in
(17) break ;;
(7) printf " ${cfg_fmt}" "$(( 0x50 | (0x${x} & 0x0F) ))" ;;
(9) printf " ${cfg_fmt}" "$(( y1 | (0x${x} & y2 ) ))" ;;
(*) printf " ${cfg_fmt}" "$(( 0x${x} ))"
esac
done
)"
format_uuid $bytes >&3 || die 'openssl fouled things up'
)
uuid_v4() (
set -e
[ 1 != "${flg_decode-}" ] || die '--decode does not work on "uuid v4 ..."'
need_args uuid_v4 "$#" 0 1
[ 0 -ge "$#" ] || [ 0 -lt "$1" ] || die "invalid count of UUIDs: \"$1\""
pcg_clear
seed="${cfg_seed-}"
if [ 1 = "${seed:+1}" ]; then
pcg_srand "${seed}"
elif ! have openssl; then
seed="$(genseed)"
pcg_srand "${seed}"
fi
: $(( y1 = !(${flg_guid-0}) ? 0x80 : 0xC0 ))
: $(( y2 = !(${flg_guid-0}) ? 0x3F : 0x1F ))
count="${1-1}"
while [ 0 -le "$(( count -= 1 ))" ]; do
i=0
state="$(
set -e
printf "bytes='"
if [ 1 != "${seed:+1}" ]; then
s="$(openssl rand -hex 16)"
while [ 16 -ge "$(( i += 1 ))" ]; do
b="$(( 0x${s%"${s#??}"} ))"
s="${s#??}"
case "${i}" in
(7) printf " ${cfg_fmt}" "$(( 0x40 | (b & 0x0F) ))" ;;
(9) printf " ${cfg_fmt}" "$(( y1 | (b & y2 ) ))" ;;
(*) printf " ${cfg_fmt}" "${b}"
esac
done
printf "'"
else
while [ 16 -ge "$(( i += 1 ))" ]; do
pcg_rand 256
case "${i}" in
(7) printf " ${cfg_fmt}" "$(( 0x40 | (pcg_number & 0x0F) ))" ;;
(9) printf " ${cfg_fmt}" "$(( y1 | (pcg_number & y2 ) ))" ;;
(*) printf " ${cfg_fmt}" "${pcg_number}"
esac
done
printf "' pcg_state=%s" "${pcg_state}"
fi
)"
eval "${state}"
format_uuid $bytes >&3 || die 'O MY RNG GOD'