captcha.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. package captcha
  2. import (
  3. "bytes"
  4. "os"
  5. "rand"
  6. "time"
  7. crand "crypto/rand"
  8. "github.com/dchest/uniuri"
  9. "io"
  10. "container/list"
  11. "sync"
  12. )
  13. const (
  14. // Expiration time for captchas
  15. Expiration = 2 * 60 // 2 minutes
  16. // The number of captchas created that triggers garbage collection
  17. CollectNum = 100
  18. // The number of numbers to use in captcha
  19. NumCount = 6
  20. )
  21. // expValue stores timestamp and id of captchas. It is used in a list inside
  22. // storage for indexing generated captchas by timestamp to enable garbage
  23. // collection of expired captchas.
  24. type expValue struct {
  25. timestamp int64
  26. id string
  27. }
  28. // storage is an internal storage for captcha ids and their values.
  29. type storage struct {
  30. mu sync.RWMutex
  31. ids map[string][]byte
  32. exp *list.List
  33. // Number of items stored after last collection
  34. colNum int
  35. }
  36. func newStore() *storage {
  37. s := new(storage)
  38. s.ids = make(map[string][]byte)
  39. s.exp = list.New()
  40. return s
  41. }
  42. var store = newStore()
  43. func init() {
  44. rand.Seed(time.Seconds())
  45. }
  46. func randomNumbers() []byte {
  47. n := make([]byte, NumCount)
  48. if _, err := io.ReadFull(crand.Reader, n); err != nil {
  49. panic(err)
  50. }
  51. for i := range n {
  52. n[i] %= 10
  53. }
  54. return n
  55. }
  56. // New creates a new captcha, saves it in the internal storage, and returns its
  57. // id.
  58. func New() string {
  59. ns := randomNumbers()
  60. id := uniuri.New()
  61. store.mu.Lock()
  62. defer store.mu.Unlock()
  63. store.ids[id] = ns
  64. store.exp.PushBack(expValue{time.Seconds(), id})
  65. store.colNum++
  66. if store.colNum > CollectNum {
  67. Collect()
  68. store.colNum = 0
  69. }
  70. return id
  71. }
  72. // WriteImage writes PNG-encoded captcha image of the given width and height
  73. // with the given captcha id into the io.Writer.
  74. func WriteImage(w io.Writer, id string, width, height int) os.Error {
  75. store.mu.RLock()
  76. defer store.mu.RUnlock()
  77. ns, ok := store.ids[id]
  78. if !ok {
  79. return os.NewError("captcha id not found")
  80. }
  81. return NewImage(ns, width, height).PNGEncode(w)
  82. }
  83. // Verify returns true if the given numbers are the numbers that were used to
  84. // create the given captcha id.
  85. //
  86. // The function deletes the captcha with the given id from the internal
  87. // storage, so that the same captcha can't be used anymore.
  88. func Verify(id string, numbers []byte) bool {
  89. store.mu.Lock()
  90. defer store.mu.Unlock()
  91. realns, ok := store.ids[id]
  92. if !ok {
  93. return false
  94. }
  95. store.ids[id] = nil, false
  96. return bytes.Equal(numbers, realns)
  97. }
  98. // Collect deletes expired and used captchas from the internal
  99. // storage. It is called automatically by New function every CollectNum
  100. // generated captchas, but still exported to enable freeing memory manually if
  101. // needed.
  102. func Collect() {
  103. now := time.Seconds()
  104. store.mu.Lock()
  105. defer store.mu.Unlock()
  106. for e := store.exp.Front(); e != nil; e = e.Next() {
  107. ev, ok := e.Value.(expValue)
  108. if !ok {
  109. return
  110. }
  111. if ev.timestamp+Expiration < now {
  112. store.ids[ev.id] = nil, false
  113. store.exp.Remove(e)
  114. } else {
  115. return
  116. }
  117. }
  118. }