captcha.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. // Package captcha implements generation and verification of image and audio
  2. // CAPTCHAs.
  3. //
  4. // A captcha solution is the sequence of digits 0-9 with the defined length.
  5. // There are two captcha representations: image and audio.
  6. //
  7. // An image representation is a PNG-encoded image with the solution printed on
  8. // it in such a way that makes it hard for computers to solve it using OCR.
  9. //
  10. // An audio representation is a WAVE-encoded (8 kHz unsigned 8-bit) sound
  11. // with the spoken solution (currently in English). To make it hard for
  12. // computers to solve audio captcha, the voice that pronounces numbers has
  13. // random speed and pitch, and there is a randomly generated background noise
  14. // mixed into the sound.
  15. //
  16. // This package doesn't require external files or libraries to generate captcha
  17. // representations; it is self-contained.
  18. //
  19. // To make captchas one-time, the package includes a memory storage that stores
  20. // captcha ids, their solutions, and expiration time. Used captchas are removed
  21. // from the store immediately after calling Verify or VerifyString, while
  22. // unused captchas (user loaded a page with captcha, but didn't submit the
  23. // form) are collected automatically after the predefined expiration time.
  24. // Developers can also provide custom store (for example, which saves captcha
  25. // ids and solutions in database) by implementing Store interface and
  26. // registering the object with SetCustomStore.
  27. //
  28. // Captchas are created by calling New, which returns the captcha id. Their
  29. // representations, though, are created on-the-fly by calling WriteImage or
  30. // WriteAudio functions. Created representations are not stored anywhere, so
  31. // subsequent calls to these functions with the same id will write the same
  32. // captcha solution, but with a different random representation. Reload
  33. // function will create a new different solution for the provided captcha,
  34. // allowing users to "reload" captcha if they can't solve the displayed one
  35. // without reloading the whole page. Verify and VerifyString are used to
  36. // verify that the given solution is the right one for the given captcha id.
  37. //
  38. // Server provides an http.Handler which can serve image and audio
  39. // representations of captchas automatically from the URL. It can also be used
  40. // to reload captchas. Refer to Server function documentation for details, or
  41. // take a look at the example in "example" subdirectory.
  42. package captcha
  43. import (
  44. "bytes"
  45. "crypto/rand"
  46. "github.com/dchest/uniuri"
  47. "io"
  48. "os"
  49. )
  50. const (
  51. // Standard number of digits in captcha.
  52. StdLength = 6
  53. // The number of captchas created that triggers garbage collection used
  54. // by default store.
  55. CollectNum = 100
  56. // Expiration time of captchas used by default store.
  57. Expiration = 10 * 60 // 10 minutes
  58. )
  59. var ErrNotFound = os.NewError("captcha with the given id not found")
  60. // globalStore is a shared storage for captchas, generated by New function.
  61. var globalStore = NewMemoryStore(CollectNum, Expiration)
  62. // SetCustomStore sets custom storage for captchas, replacing the default
  63. // memory store. This function must be called before generating any captchas.
  64. func SetCustomStore(s Store) {
  65. globalStore = s
  66. }
  67. // RandomDigits returns a byte slice of the given length containing random
  68. // digits in range 0-9.
  69. func RandomDigits(length int) []byte {
  70. d := make([]byte, length)
  71. if _, err := io.ReadFull(rand.Reader, d); err != nil {
  72. panic("error reading random source: " + err.String())
  73. }
  74. for i := range d {
  75. d[i] %= 10
  76. }
  77. return d
  78. }
  79. // New creates a new captcha of the given length, saves it in the internal
  80. // storage, and returns its id.
  81. func New(length int) (id string) {
  82. id = uniuri.New()
  83. globalStore.Set(id, RandomDigits(length))
  84. return
  85. }
  86. // Reload generates and remembers new digits for the given captcha id. This
  87. // function returns false if there is no captcha with the given id.
  88. //
  89. // After calling this function, the image or audio presented to a user must be
  90. // refreshed to show the new captcha representation (WriteImage and WriteAudio
  91. // will write the new one).
  92. func Reload(id string) bool {
  93. old := globalStore.Get(id, false)
  94. if old == nil {
  95. return false
  96. }
  97. globalStore.Set(id, RandomDigits(len(old)))
  98. return true
  99. }
  100. // WriteImage writes PNG-encoded image representation of the captcha with the
  101. // given id. The image will have the given width and height.
  102. func WriteImage(w io.Writer, id string, width, height int) os.Error {
  103. d := globalStore.Get(id, false)
  104. if d == nil {
  105. return ErrNotFound
  106. }
  107. _, err := NewImage(d, width, height).WriteTo(w)
  108. return err
  109. }
  110. // WriteAudio writes WAV-encoded audio representation of the captcha with the
  111. // given id.
  112. func WriteAudio(w io.Writer, id string) os.Error {
  113. d := globalStore.Get(id, false)
  114. if d == nil {
  115. return ErrNotFound
  116. }
  117. _, err := NewAudio(d).WriteTo(w)
  118. return err
  119. }
  120. // Verify returns true if the given digits are the ones that were used to
  121. // create the given captcha id.
  122. //
  123. // The function deletes the captcha with the given id from the internal
  124. // storage, so that the same captcha can't be verified anymore.
  125. func Verify(id string, digits []byte) bool {
  126. if digits == nil || len(digits) == 0 {
  127. return false
  128. }
  129. reald := globalStore.Get(id, true)
  130. if reald == nil {
  131. return false
  132. }
  133. return bytes.Equal(digits, reald)
  134. }
  135. // VerifyString is like Verify, but accepts a string of digits. It removes
  136. // spaces and commas from the string, but any other characters, apart from
  137. // digits and listed above, will cause the function to return false.
  138. func VerifyString(id string, digits string) bool {
  139. if digits == "" {
  140. return false
  141. }
  142. ns := make([]byte, len(digits))
  143. for i := range ns {
  144. d := digits[i]
  145. switch {
  146. case '0' <= d && d <= '9':
  147. ns[i] = d - '0'
  148. case d == ' ' || d == ',':
  149. // ignore
  150. default:
  151. return false
  152. }
  153. }
  154. return Verify(id, ns)
  155. }
  156. // Collect deletes expired or used captchas from the internal storage. It is
  157. // called automatically by New function every CollectNum generated captchas,
  158. // but still exported to enable freeing memory manually if needed.
  159. //
  160. // Collection is launched in a new goroutine.
  161. func Collect() {
  162. go globalStore.Collect()
  163. }