captcha.go 2.8 KB

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