captcha.go 5.7 KB

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