You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

481 lines
11 KiB

  1. // Copyright (C) 2013-2015 by Maxim Bublis <b@codemonkey.ru>
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining
  4. // a copy of this software and associated documentation files (the
  5. // "Software"), to deal in the Software without restriction, including
  6. // without limitation the rights to use, copy, modify, merge, publish,
  7. // distribute, sublicense, and/or sell copies of the Software, and to
  8. // permit persons to whom the Software is furnished to do so, subject to
  9. // the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be
  12. // included in all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  18. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  19. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  20. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. // Package uuid provides implementation of Universally Unique Identifier (UUID).
  22. // Supported versions are 1, 3, 4 and 5 (as specified in RFC 4122) and
  23. // version 2 (as specified in DCE 1.1).
  24. package uuid
  25. import (
  26. "bytes"
  27. "crypto/md5"
  28. "crypto/rand"
  29. "crypto/sha1"
  30. "database/sql/driver"
  31. "encoding/binary"
  32. "encoding/hex"
  33. "fmt"
  34. "hash"
  35. "net"
  36. "os"
  37. "sync"
  38. "time"
  39. )
  40. // UUID layout variants.
  41. const (
  42. VariantNCS = iota
  43. VariantRFC4122
  44. VariantMicrosoft
  45. VariantFuture
  46. )
  47. // UUID DCE domains.
  48. const (
  49. DomainPerson = iota
  50. DomainGroup
  51. DomainOrg
  52. )
  53. // Difference in 100-nanosecond intervals between
  54. // UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).
  55. const epochStart = 122192928000000000
  56. // Used in string method conversion
  57. const dash byte = '-'
  58. // UUID v1/v2 storage.
  59. var (
  60. storageMutex sync.Mutex
  61. storageOnce sync.Once
  62. epochFunc = unixTimeFunc
  63. clockSequence uint16
  64. lastTime uint64
  65. hardwareAddr [6]byte
  66. posixUID = uint32(os.Getuid())
  67. posixGID = uint32(os.Getgid())
  68. )
  69. // String parse helpers.
  70. var (
  71. urnPrefix = []byte("urn:uuid:")
  72. byteGroups = []int{8, 4, 4, 4, 12}
  73. )
  74. func initClockSequence() {
  75. buf := make([]byte, 2)
  76. safeRandom(buf)
  77. clockSequence = binary.BigEndian.Uint16(buf)
  78. }
  79. func initHardwareAddr() {
  80. interfaces, err := net.Interfaces()
  81. if err == nil {
  82. for _, iface := range interfaces {
  83. if len(iface.HardwareAddr) >= 6 {
  84. copy(hardwareAddr[:], iface.HardwareAddr)
  85. return
  86. }
  87. }
  88. }
  89. // Initialize hardwareAddr randomly in case
  90. // of real network interfaces absence
  91. safeRandom(hardwareAddr[:])
  92. // Set multicast bit as recommended in RFC 4122
  93. hardwareAddr[0] |= 0x01
  94. }
  95. func initStorage() {
  96. initClockSequence()
  97. initHardwareAddr()
  98. }
  99. func safeRandom(dest []byte) {
  100. if _, err := rand.Read(dest); err != nil {
  101. panic(err)
  102. }
  103. }
  104. // Returns difference in 100-nanosecond intervals between
  105. // UUID epoch (October 15, 1582) and current time.
  106. // This is default epoch calculation function.
  107. func unixTimeFunc() uint64 {
  108. return epochStart + uint64(time.Now().UnixNano()/100)
  109. }
  110. // UUID representation compliant with specification
  111. // described in RFC 4122.
  112. type UUID [16]byte
  113. // NullUUID can be used with the standard sql package to represent a
  114. // UUID value that can be NULL in the database
  115. type NullUUID struct {
  116. UUID UUID
  117. Valid bool
  118. }
  119. // The nil UUID is special form of UUID that is specified to have all
  120. // 128 bits set to zero.
  121. var Nil = UUID{}
  122. // Predefined namespace UUIDs.
  123. var (
  124. NamespaceDNS, _ = FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
  125. NamespaceURL, _ = FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
  126. NamespaceOID, _ = FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
  127. NamespaceX500, _ = FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
  128. )
  129. // And returns result of binary AND of two UUIDs.
  130. func And(u1 UUID, u2 UUID) UUID {
  131. u := UUID{}
  132. for i := 0; i < 16; i++ {
  133. u[i] = u1[i] & u2[i]
  134. }
  135. return u
  136. }
  137. // Or returns result of binary OR of two UUIDs.
  138. func Or(u1 UUID, u2 UUID) UUID {
  139. u := UUID{}
  140. for i := 0; i < 16; i++ {
  141. u[i] = u1[i] | u2[i]
  142. }
  143. return u
  144. }
  145. // Equal returns true if u1 and u2 equals, otherwise returns false.
  146. func Equal(u1 UUID, u2 UUID) bool {
  147. return bytes.Equal(u1[:], u2[:])
  148. }
  149. // Version returns algorithm version used to generate UUID.
  150. func (u UUID) Version() uint {
  151. return uint(u[6] >> 4)
  152. }
  153. // Variant returns UUID layout variant.
  154. func (u UUID) Variant() uint {
  155. switch {
  156. case (u[8] & 0x80) == 0x00:
  157. return VariantNCS
  158. case (u[8]&0xc0)|0x80 == 0x80:
  159. return VariantRFC4122
  160. case (u[8]&0xe0)|0xc0 == 0xc0:
  161. return VariantMicrosoft
  162. }
  163. return VariantFuture
  164. }
  165. // Bytes returns bytes slice representation of UUID.
  166. func (u UUID) Bytes() []byte {
  167. return u[:]
  168. }
  169. // Returns canonical string representation of UUID:
  170. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  171. func (u UUID) String() string {
  172. buf := make([]byte, 36)
  173. hex.Encode(buf[0:8], u[0:4])
  174. buf[8] = dash
  175. hex.Encode(buf[9:13], u[4:6])
  176. buf[13] = dash
  177. hex.Encode(buf[14:18], u[6:8])
  178. buf[18] = dash
  179. hex.Encode(buf[19:23], u[8:10])
  180. buf[23] = dash
  181. hex.Encode(buf[24:], u[10:])
  182. return string(buf)
  183. }
  184. // SetVersion sets version bits.
  185. func (u *UUID) SetVersion(v byte) {
  186. u[6] = (u[6] & 0x0f) | (v << 4)
  187. }
  188. // SetVariant sets variant bits as described in RFC 4122.
  189. func (u *UUID) SetVariant() {
  190. u[8] = (u[8] & 0xbf) | 0x80
  191. }
  192. // MarshalText implements the encoding.TextMarshaler interface.
  193. // The encoding is the same as returned by String.
  194. func (u UUID) MarshalText() (text []byte, err error) {
  195. text = []byte(u.String())
  196. return
  197. }
  198. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  199. // Following formats are supported:
  200. // "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
  201. // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
  202. // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
  203. func (u *UUID) UnmarshalText(text []byte) (err error) {
  204. if len(text) < 32 {
  205. err = fmt.Errorf("uuid: UUID string too short: %s", text)
  206. return
  207. }
  208. t := text[:]
  209. braced := false
  210. if bytes.Equal(t[:9], urnPrefix) {
  211. t = t[9:]
  212. } else if t[0] == '{' {
  213. braced = true
  214. t = t[1:]
  215. }
  216. b := u[:]
  217. for i, byteGroup := range byteGroups {
  218. if i > 0 {
  219. if t[0] != '-' {
  220. err = fmt.Errorf("uuid: invalid string format")
  221. return
  222. }
  223. t = t[1:]
  224. }
  225. if len(t) < byteGroup {
  226. err = fmt.Errorf("uuid: UUID string too short: %s", text)
  227. return
  228. }
  229. if i == 4 && len(t) > byteGroup &&
  230. ((braced && t[byteGroup] != '}') || len(t[byteGroup:]) > 1 || !braced) {
  231. err = fmt.Errorf("uuid: UUID string too long: %s", text)
  232. return
  233. }
  234. _, err = hex.Decode(b[:byteGroup/2], t[:byteGroup])
  235. if err != nil {
  236. return
  237. }
  238. t = t[byteGroup:]
  239. b = b[byteGroup/2:]
  240. }
  241. return
  242. }
  243. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  244. func (u UUID) MarshalBinary() (data []byte, err error) {
  245. data = u.Bytes()
  246. return
  247. }
  248. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
  249. // It will return error if the slice isn't 16 bytes long.
  250. func (u *UUID) UnmarshalBinary(data []byte) (err error) {
  251. if len(data) != 16 {
  252. err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data))
  253. return
  254. }
  255. copy(u[:], data)
  256. return
  257. }
  258. // Value implements the driver.Valuer interface.
  259. func (u UUID) Value() (driver.Value, error) {
  260. return u.String(), nil
  261. }
  262. // Scan implements the sql.Scanner interface.
  263. // A 16-byte slice is handled by UnmarshalBinary, while
  264. // a longer byte slice or a string is handled by UnmarshalText.
  265. func (u *UUID) Scan(src interface{}) error {
  266. switch src := src.(type) {
  267. case []byte:
  268. if len(src) == 16 {
  269. return u.UnmarshalBinary(src)
  270. }
  271. return u.UnmarshalText(src)
  272. case string:
  273. return u.UnmarshalText([]byte(src))
  274. }
  275. return fmt.Errorf("uuid: cannot convert %T to UUID", src)
  276. }
  277. // Value implements the driver.Valuer interface.
  278. func (u NullUUID) Value() (driver.Value, error) {
  279. if !u.Valid {
  280. return nil, nil
  281. }
  282. // Delegate to UUID Value function
  283. return u.UUID.Value()
  284. }
  285. // Scan implements the sql.Scanner interface.
  286. func (u *NullUUID) Scan(src interface{}) error {
  287. if src == nil {
  288. u.UUID, u.Valid = Nil, false
  289. return nil
  290. }
  291. // Delegate to UUID Scan function
  292. u.Valid = true
  293. return u.UUID.Scan(src)
  294. }
  295. // FromBytes returns UUID converted from raw byte slice input.
  296. // It will return error if the slice isn't 16 bytes long.
  297. func FromBytes(input []byte) (u UUID, err error) {
  298. err = u.UnmarshalBinary(input)
  299. return
  300. }
  301. // FromBytesOrNil returns UUID converted from raw byte slice input.
  302. // Same behavior as FromBytes, but returns a Nil UUID on error.
  303. func FromBytesOrNil(input []byte) UUID {
  304. uuid, err := FromBytes(input)
  305. if err != nil {
  306. return Nil
  307. }
  308. return uuid
  309. }
  310. // FromString returns UUID parsed from string input.
  311. // Input is expected in a form accepted by UnmarshalText.
  312. func FromString(input string) (u UUID, err error) {
  313. err = u.UnmarshalText([]byte(input))
  314. return
  315. }
  316. // FromStringOrNil returns UUID parsed from string input.
  317. // Same behavior as FromString, but returns a Nil UUID on error.
  318. func FromStringOrNil(input string) UUID {
  319. uuid, err := FromString(input)
  320. if err != nil {
  321. return Nil
  322. }
  323. return uuid
  324. }
  325. // Returns UUID v1/v2 storage state.
  326. // Returns epoch timestamp, clock sequence, and hardware address.
  327. func getStorage() (uint64, uint16, []byte) {
  328. storageOnce.Do(initStorage)
  329. storageMutex.Lock()
  330. defer storageMutex.Unlock()
  331. timeNow := epochFunc()
  332. // Clock changed backwards since last UUID generation.
  333. // Should increase clock sequence.
  334. if timeNow <= lastTime {
  335. clockSequence++
  336. }
  337. lastTime = timeNow
  338. return timeNow, clockSequence, hardwareAddr[:]
  339. }
  340. // NewV1 returns UUID based on current timestamp and MAC address.
  341. func NewV1() UUID {
  342. u := UUID{}
  343. timeNow, clockSeq, hardwareAddr := getStorage()
  344. binary.BigEndian.PutUint32(u[0:], uint32(timeNow))
  345. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
  346. binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
  347. binary.BigEndian.PutUint16(u[8:], clockSeq)
  348. copy(u[10:], hardwareAddr)
  349. u.SetVersion(1)
  350. u.SetVariant()
  351. return u
  352. }
  353. // NewV2 returns DCE Security UUID based on POSIX UID/GID.
  354. func NewV2(domain byte) UUID {
  355. u := UUID{}
  356. timeNow, clockSeq, hardwareAddr := getStorage()
  357. switch domain {
  358. case DomainPerson:
  359. binary.BigEndian.PutUint32(u[0:], posixUID)
  360. case DomainGroup:
  361. binary.BigEndian.PutUint32(u[0:], posixGID)
  362. }
  363. binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
  364. binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
  365. binary.BigEndian.PutUint16(u[8:], clockSeq)
  366. u[9] = domain
  367. copy(u[10:], hardwareAddr)
  368. u.SetVersion(2)
  369. u.SetVariant()
  370. return u
  371. }
  372. // NewV3 returns UUID based on MD5 hash of namespace UUID and name.
  373. func NewV3(ns UUID, name string) UUID {
  374. u := newFromHash(md5.New(), ns, name)
  375. u.SetVersion(3)
  376. u.SetVariant()
  377. return u
  378. }
  379. // NewV4 returns random generated UUID.
  380. func NewV4() UUID {
  381. u := UUID{}
  382. safeRandom(u[:])
  383. u.SetVersion(4)
  384. u.SetVariant()
  385. return u
  386. }
  387. // NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.
  388. func NewV5(ns UUID, name string) UUID {
  389. u := newFromHash(sha1.New(), ns, name)
  390. u.SetVersion(5)
  391. u.SetVariant()
  392. return u
  393. }
  394. // Returns UUID based on hashing of namespace UUID and name.
  395. func newFromHash(h hash.Hash, ns UUID, name string) UUID {
  396. u := UUID{}
  397. h.Write(ns[:])
  398. h.Write([]byte(name))
  399. copy(u[:], h.Sum(nil))
  400. return u
  401. }