captcha.go 2.6 KB

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