dce.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2016 Google Inc. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package uuid
  5. import (
  6. "encoding/binary"
  7. "os"
  8. "strconv"
  9. "strings"
  10. )
  11. // A Domain represents a Version 2 domain
  12. type Domain byte
  13. // Domain constants for DCE Security (Version 2) UUIDs.
  14. const (
  15. Person = Domain(0)
  16. Group = Domain(1)
  17. Org = Domain(2)
  18. )
  19. // NewDCESecurity returns a DCE Security (Version 2) UUID.
  20. //
  21. // The domain should be one of Person, Group or Org.
  22. // On a POSIX system the id should be the users UID for the Person
  23. // domain and the users GID for the Group. The meaning of id for
  24. // the domain Org or on non-POSIX systems is site defined.
  25. //
  26. // For a given domain/id pair the same token may be returned for up to
  27. // 7 minutes and 10 seconds.
  28. func NewDCESecurity(domain Domain, id uint32) (UUID, error) {
  29. uuid, err := NewUUID()
  30. if err == nil {
  31. uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2
  32. uuid[9] = byte(domain)
  33. binary.BigEndian.PutUint32(uuid[0:], id)
  34. }
  35. return uuid, err
  36. }
  37. // NewDCEPerson returns a DCE Security (Version 2) UUID in the person
  38. // domain with the id returned by os.Getuid.
  39. //
  40. // NewDCESecurity(Person, uint32(os.Getuid()))
  41. func NewDCEPerson() (UUID, error) {
  42. return NewDCESecurity(Person, uint32(os.Getuid()))
  43. }
  44. // NewDCEGroup returns a DCE Security (Version 2) UUID in the group
  45. // domain with the id returned by os.Getgid.
  46. //
  47. // NewDCESecurity(Group, uint32(os.Getgid()))
  48. func NewDCEGroup() (UUID, error) {
  49. return NewDCESecurity(Group, uint32(os.Getgid()))
  50. }
  51. // Domain returns the domain for a Version 2 UUID. Domains are only defined
  52. // for Version 2 UUIDs.
  53. func (uuid UUID) Domain() Domain {
  54. return Domain(uuid[9])
  55. }
  56. // ID returns the id for a Version 2 UUID. IDs are only defined for Version 2
  57. // UUIDs.
  58. func (uuid UUID) ID() uint32 {
  59. return binary.BigEndian.Uint32(uuid[0:4])
  60. }
  61. func (d Domain) String() string {
  62. switch d {
  63. case Person:
  64. return "Person"
  65. case Group:
  66. return "Group"
  67. case Org:
  68. return "Org"
  69. }
  70. return strings.Join([]string{"Domain", strconv.Itoa(int(d))}, "")
  71. }