dce.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2011 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. "fmt"
  8. "os"
  9. )
  10. // A Domain represents a Version 2 domain
  11. type Domain byte
  12. // Domain constants for DCE Security (Version 2) UUIDs.
  13. const (
  14. Person = Domain(0)
  15. Group = Domain(1)
  16. Org = Domain(2)
  17. )
  18. // NewDCESecurity returns a DCE Security (Version 2) UUID.
  19. //
  20. // The domain should be one of Person, Group or Org.
  21. // On a POSIX system the id should be the users UID for the Person
  22. // domain and the users GID for the Group. The meaning of id for
  23. // the domain Org or on non-POSIX systems is site defined.
  24. //
  25. // For a given domain/id pair the same token may be returned for up to
  26. // 7 minutes and 10 seconds.
  27. func NewDCESecurity(domain Domain, id uint32) UUID {
  28. uuid := NewUUID()
  29. if uuid != nil {
  30. uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2
  31. uuid[9] = byte(domain)
  32. binary.BigEndian.PutUint32(uuid[0:], id)
  33. }
  34. return uuid
  35. }
  36. // NewDCEPerson returns a DCE Security (Version 2) UUID in the person
  37. // domain with the id returned by os.Getuid.
  38. //
  39. // NewDCEPerson(Person, uint32(os.Getuid()))
  40. func NewDCEPerson() UUID {
  41. return NewDCESecurity(Person, uint32(os.Getuid()))
  42. }
  43. // NewDCEGroup returns a DCE Security (Version 2) UUID in the group
  44. // domain with the id returned by os.Getgid.
  45. //
  46. // NewDCEGroup(Group, uint32(os.Getgid()))
  47. func NewDCEGroup() UUID {
  48. return NewDCESecurity(Group, uint32(os.Getgid()))
  49. }
  50. // Domain returns the domain for a Version 2 UUID or false.
  51. func (uuid UUID) Domain() (Domain, bool) {
  52. if v, _ := uuid.Version(); v != 2 {
  53. return 0, false
  54. }
  55. return Domain(uuid[9]), true
  56. }
  57. // Id returns the id for a Version 2 UUID or false.
  58. func (uuid UUID) Id() (uint32, bool) {
  59. if v, _ := uuid.Version(); v != 2 {
  60. return 0, false
  61. }
  62. return binary.BigEndian.Uint32(uuid[0:4]), true
  63. }
  64. func (d Domain) String() string {
  65. switch d {
  66. case Person:
  67. return "Person"
  68. case Group:
  69. return "Group"
  70. case Org:
  71. return "Org"
  72. }
  73. return fmt.Sprintf("Domain%d", int(d))
  74. }