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
  
#pike __REAL_VERSION__ 
 
//! 
//! Support for Universal Unique Identifiers (UUID) and 
//! Globally Unique Identifiers (GUID). 
//! 
//! @seealso 
//!   @dl 
//!     @item @rfc{4122@} 
//!       A Universally Unique IDentifier (UUID) URN Namespace. 
//!     @item ITU-T X.667 
//!       Generation and registration of Universally Unique 
//!       Identifiers (UUIDs) and their use as ASN.1 object 
//!       identifier components. 
//!   @enddl 
 
// 
// 2004-10-01 Henrik Grubbström 
// 2004-10-04 Martin Nilsson 
 
// Specifications: 
// 
// RFC 4122: A Universally Unique IDentifier (UUID) URN Namespace 
// CDE 1.1: Remote Procedure Call: Universal Unique Identifier (Open Group) 
// X.667: Generation and registration of Universally Unique Identifiers 
//        (UUIDs) and their use as ASN.1 object identifier components (ITU-T) 
 
// UUID format: 
// 
//   All fields are in network (bigendian) byte order. 
// 
//    Size    Field 
//      4     time_low 
//      2     time_mid 
//      2     time_hi_and_version 
//      1     clock_seq_hi_and_reserved 
//      1     clock_seq_low 
//      6     node 
// 
//   The UUID version is specified in the 4 most significant bits 
//   of time_hi_and_version. The remaining 60 bits of time_* are 
//   a time stamp. 
// 
//   The UUID variant is encoded in the most significant bit(s) of 
//   clock_seq_hi_and_reserved as follows: 
// 
//    Bits    Variant 
//     0--    NCS backward compat, reserved. 
//     10-    DCE. 
//     110    Microsoft GUID, reserved. 
//     111    Reserved for future use. 
 
// UUID version 1 format: 
// 
//   The time stamp is specified as the number of 100 ns intervals 
//   since 1582-10-15 00:00:00.00 GMT. 
 
// UUID version 1 DCE format: 
// 
//   The clock_seq_* field contains a 6 bit sequence number to 
//   avoid duplicate timestamps. 
// 
//   The node field contains the IEEE 802 (aka MAC) address for the 
//   node generating the UUID. 
// 
//   For systems without an IEEE 802 address, a random value 
//   with the multicast bit set may be used. 
 
// TODO: Check changes between draft-mealling-uuid-urn-03.txt and RFC 4122. 
 
#if 0 
  constant clk_offset = Calendar.ISO.Second(1582,10,15,0,0,0)-> 
    distance(Calendar.ISO.Second("unix",0))->how_many(Calendar.Second) 
    * 10000000; 
#else 
  constant clk_offset = 0x01b21dd213814000; 
#endif 
 
protected string low_format_uuid (string bin_uuid) 
{ 
  string ret = String.string2hex(bin_uuid); 
  while( sizeof(ret)<32 ) ret = "0"+ret; 
  return ret[..7] + "-" + ret[8..11] + "-" + ret[12..15]  +"-" + 
    ret[16..19] + "-" + ret[20..]; 
} 
 
 
//! Represents an UUID 
class UUID { 
 
  //! 60 bit value representing the time stamp. 
  int timestamp; // 60 bit value 
 
  //! Returns the posix time of the UUID. 
  int posix_time() { 
    return (timestamp-clk_offset)/10000000; 
  } 
 
  //! The version of the UUID. 
  int version = 1; // 4 bits 
 
  //! Returns a string representation of the version, e.g. 
  //! @expr{"Name-based (MD5)"@}. 
  string str_version() { 
    return ([ 1 : "Time-based", 
              2 : "DCE security", 
              3 : "Name-based (MD5)", 
              4 : "Random", 
              5 : "Name-based (SHA)"])[version] || "Unknown"; 
  } 
 
  //! The variant of the UUID. 
  int var = 1; // 0-2. 
 
  //! Returns a string representation of the variant, e.g. 
  //! @expr{"IETF draft variant"@}. 
  string str_variant() { 
    switch(var) { 
    case 0: return "Reserved, NCS backward compatibility"; 
    case 1: return "IETF draft variant"; 
    case 2: return "Reserved, Microsoft Corporation backward compatibility"; 
    default: return "Illegal variant"; 
    } 
  } 
 
  //! The clock sequence. Should be 13 to 15 bits depending on UUID 
  //! version. 
  int clk_seq; // 13-15 bit 
 
  //! The UUID node. Should be 48 bit. 
  int node; // 48 bit 
 
  //! Validates the current UUID. 
  void validate() { 
    if(!timestamp && !version && !var && !clk_seq && !node) 
      return; 
 
    if( !(< 0,1,2 >)[var] ) error("Illegal variant %O.\n", var); 
 
    if(timestamp & ~((1<<60)-1)) 
      error("Timestamp %O out of range.\n", timestamp); 
    if(version & ~15) 
      error("Version %O out of range.\n", version); 
 
    int seq_mask = ([ 0:~((1<<15)-1), 
                      1:~((1<<14)-1), 
                      2:~((1<<13)-1) ])[var]; 
    if(clk_seq & seq_mask) 
      error("Clock sequence %O out of range.\n", clk_seq); 
 
    if(node & ~((1<<48)-1)) 
      error("Node %012x out of range\n", node); 
  } 
 
  //! Returns the time_low field. 
  int time_low() { 
    return timestamp & 0xFFffFFff; 
  } 
 
  //! Returns the time_mid field. 
  int time_mid() { 
    return (timestamp >> 32) & 0xFFff; 
  } 
 
  //! Returns the time_hi_and_version field. 
  int time_hi_and_version() { 
    return ((timestamp >> 32+16) << 4) | version; 
  } 
 
  //! Encodes a binary representation of the UUID. 
  string encode() { 
 
    validate(); 
    string ret = ""; 
 
    // FIXME: The following ought to be a single sprintf(). 
 
    int t = timestamp; 
    ret += sprintf("%4c", t); // time_low 
    t >>= 32; 
    ret += sprintf("%2c", t); // time_mid 
    t >>= 16; 
    t |= version<<12; 
    ret += sprintf("%2c", t); 
 
    int variant_mask = (1<<(16-var))-1; 
    t = 0xffff & ~variant_mask; 
    t |= clk_seq & (variant_mask >> 1); 
    ret += sprintf("%2c", t); 
 
    ret += sprintf("%6c", node); 
 
    return ret; 
  } 
 
  //! Creates a string representation of the UUID. 
  string str() { 
    return low_format_uuid (encode()); 
  } 
 
  //! Creates a URN representation of the UUID. 
  string urn() { 
    return "urn:uuid:"+str(); 
  } 
 
  //! Optionally created with a string or binary representation of a UUID. 
  void create(void|string in) { 
    if(!in) return; 
    sscanf(in, "urn:%s", in); 
    sscanf(in, "uuid:%s", in); 
    switch(sizeof(in)) { 
    case 36: 
      in -= "-"; 
      if(sizeof(in)!=32) error("Illegal UUID.\n"); 
      // fallthrough 
    case 32: 
      in = String.hex2string(in); 
      // fallthrough 
    case 16: 
      int time_low, time_mid, time_hi_and_version; 
      sscanf(in, "%4c%2c%2c%2c%6c", time_low, time_mid, time_hi_and_version, 
             clk_seq, node); 
      version = (time_hi_and_version & 0xf000)>>12; 
      time_hi_and_version &= 0x0fff; 
      timestamp = time_hi_and_version<<(6*8) | time_mid<<(4*8) | time_low; 
      int var_mask = 1<<15; 
      for (var = 0; clk_seq & var_mask; var++, var_mask>>=1) 
        ; 
      clk_seq &= var_mask - 1; 
      break; 
    default: 
      error("Illegal UUID.\n"); 
    } 
    validate(); 
  } 
 
  protected mixed cast(string to) { 
    switch(to) { 
    case "string": return str(); 
    case "mapping": return ([ 
      "time_low" : time_low(), 
      "time_mid" : time_mid(), 
      "time_hi_and_version" : time_hi_and_version(), 
    ]); 
    } 
    return UNDEFINED; 
  } 
 
} 
 
// Internal clock sequence class. Only works for variant 4, but all others are 
// reserved, so it shouldn't be a problem in practice. 
protected class ClkSeq 
{ 
  int clk_seq = random(1<<14); 
  int last_time; 
 
  System.Time clock = System.Time(); 
 
  int time() { 
    return clock->usec_full*10 + clk_offset; 
  } 
 
  array(int) get() { 
 
    int timestamp = time(); 
 
    if( timestamp <= last_time) { 
      clk_seq++; 
      clk_seq &= (1<<14)-1; 
    } 
    last_time = timestamp; 
 
    return ({ timestamp, clk_seq }); 
  } 
 
  array(int) get_state() { 
    return ({ last_time, clk_seq }); 
  } 
 
  void set_state(int _last_time, int _clk_seq) { 
    last_time = _last_time; 
    clk_seq = _clk_seq; 
  } 
} 
 
protected ClkSeq clk_seq = ClkSeq(); 
 
//! Returns the internal clock state. Can be used for persistent 
//! storage when an application is terminated. 
//! @seealso 
//!   @[set_clock_state] 
array(int) get_clock_state() { 
  return clk_seq->get_state(); 
} 
 
//! Sets the internal clock state. 
//! @seealso 
//!   @[get_clock_state] 
void set_clock_state(int last_time, int seq) { 
  clk_seq->set_state(last_time, seq); 
} 
 
//! Creates a new version 1 UUID. 
//! @param node 
//!   Either the 48 bit IEEE 802 (aka MAC) address of the system or -1. 
UUID make_version1(int node) { 
  UUID u=UUID(); 
  [ u->timestamp, u->clk_seq ] = clk_seq->get(); 
  u->version = 1; 
  if(node<0) 
    u->node = random(1<<48) | 1<<40; 
  else 
    u->node = node; 
  return u; 
} 
 
#if constant(Crypto.MD5.hash) 
 
//! Creates a version 3 UUID with a @[name] string and a binary 
//! representation of a name space UUID. 
UUID make_version3(string name, string|UUID namespace) { 
 
  if(stringp(namespace)) 
    namespace = UUID(namespace); 
  namespace = namespace->encode(); 
 
  // FIXME: I don't see why the following reversals are needed; 
  //        the namespace should already be in network byte order. 
  //  /grubba 2004-10-05 
  //    Otherwise we get a result that differs from the example 
  //    execution of the reference implementation in the Internet 
  //    Draft. 
  //  /nilsson 2004-10-05 
  //    The implemenetaion in the Internet Draft is bugged. 
  //    It contains code like the following: 
  //        htonl(net_nsid.time_low); 
  //    where it is supposed to say 
  //        net_nsid.time_low = htonl(net_nsid.time_low); 
  //    Therefore it gives incorrect results on little endian 
  //    machines.  The code without reverse gives the same 
  //    result as the reference implementation _when run on a 
  //    big endian system_, and also the same as e.g. the Python 
  //    UUID module. 
  //  /marcus 2007-08-05 
  // step 2 
#if 0 
  namespace = reverse(namespace[0..3]) + reverse(namespace[4..5]) + 
    reverse(namespace[6..7]) + namespace[8..]; 
#endif 
 
  // step 3 
  string ret = Crypto.MD5.hash(namespace+name); 
 
#if 0 
  ret = reverse(ret[0..3]) + reverse(ret[4..5]) + 
    reverse(ret[6..7]) + ret[8..]; 
#endif 
 
  ret &= 
    "\xff\xff\xff\xff"              // time_low 
    "\xff\xff"                      // time_mid 
    "\x0f\xff"                      // time_hi_and_version 
    "\x3f\xff"                      // clock_seq_and_variant 
    "\xff\xff\xff\xff\xff\xff";     // node 
 
  ret |= 
    "\x00\x00\x00\x00"              // time_low 
    "\x00\x00"                      // time_mid 
    "\x30\x00"                      // time_hi_and_version 
    "\x80\x00"                      // clock_seq_and_veriant 
    "\x00\x00\x00\x00\x00\x00";     // node 
 
  return UUID(ret); 
} 
 
#endif 
 
//! Creates a version 4 (random) UUID. 
UUID make_version4() { 
  UUID u=UUID(); 
  u->timestamp = random(1<<60); 
  u->version = 4; 
  u->clk_seq = random(1<<14); 
  u->node = random(1<<48); 
  return u; 
} 
 
#if constant(Crypto.SHA1.hash) 
 
//! Creates a version 5 UUID with a @[name] string and a binary 
//! representation of a name space UUID. 
UUID make_version5(string name, string|UUID namespace) { 
 
  if(stringp(namespace)) 
    namespace = UUID(namespace); 
  namespace = namespace->encode(); 
 
  string ret = Crypto.SHA1.hash(namespace+name)[..15]; 
 
  ret &= 
    "\xff\xff\xff\xff"              // time_low 
    "\xff\xff"                      // time_mid 
    "\x0f\xff"                      // time_hi_and_version 
    "\x3f\xff"                      // clock_seq_and_variant 
    "\xff\xff\xff\xff\xff\xff";     // node 
 
  ret |= 
    "\x00\x00\x00\x00"              // time_low 
    "\x00\x00"                      // time_mid 
    "\x50\x00"                      // time_hi_and_version 
    "\x80\x00"                      // clock_seq_and_veriant 
    "\x00\x00\x00\x00\x00\x00";     // node 
 
  return UUID(ret); 
} 
 
#endif 
 
 
// Convenience functions 
 
//! Returns the string representation of the binary UUID @[uuid]. 
string format_uuid(string uuid) 
{ 
  if (sizeof (uuid) == 16) 
    return low_format_uuid (uuid); 
  return UUID(uuid)->str(); 
} 
 
//! Returns the binary representation of the UUID @[uuid]. 
string parse_uuid(string uuid) 
{ 
  if (sizeof (uuid) >= 32) { 
    string s = uuid - "-"; 
    if (sizeof (s) == 32) 
      return String.hex2string (s); 
  } 
  return UUID(uuid)->encode(); 
} 
 
// Some UUIDs: 
 
//! The Nil UUID. 
constant Nil_UUID = "00000000-0000-0000-0000-000000000000"; 
 
//! Name space UUID for DNS. 
constant NameSpace_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; 
 
//! Name space UUID for URL. 
constant NameSpace_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; 
 
//! Name space UUID for OID. 
constant NameSpace_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8"; 
 
//! Name space UUID for X500. 
constant NameSpace_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8"; 
 
//! Creates a null UUID object. 
UUID make_null() { 
  UUID u=UUID(); 
  u->version = 0; 
  u->var = 0; 
  u->clk_seq = 0; 
  return u; 
} 
 
// FIXME: Should version 5 be default if both are available? 
 
#if constant(Crypto.MD5.hash) 
 
//! Creates a DNS UUID with the given DNS name. 
UUID make_dns(string name) { 
  return make_version3(name, NameSpace_DNS); 
} 
 
//! Creates a URL UUID with the given URL. 
UUID make_url(string name) { 
  return make_version3(name, NameSpace_URL); 
} 
 
//! Creates an OID UUID with the given OID. 
UUID make_oid(string name) { 
  return make_version3(name, NameSpace_OID); 
} 
 
//! Creates an X500 UUID with the gived X500 address. 
UUID make_x500(string name) { 
  return make_version3(name, NameSpace_X500); 
} 
 
#elif constant(Crypto.SHA1.hash) 
 
//! Creates a DNS UUID with the given DNS name. 
UUID make_dns(string name) { 
  return make_version5(name, NameSpace_DNS); 
} 
 
//! Creates a URL UUID with the given URL. 
UUID make_url(string name) { 
  return make_version5(name, NameSpace_URL); 
} 
 
//! Creates an OID UUID with the given OID. 
UUID make_oid(string name) { 
  return make_version5(name, NameSpace_OID); 
} 
 
//! Creates an X500 UUID with the gived X500 address. 
UUID make_x500(string name) { 
  return make_version5(name, NameSpace_X500); 
} 
 
#endif