This repository has been archived by the owner on Oct 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathservice.go
398 lines (354 loc) · 8.08 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package captchouli
import (
"bytes"
"compress/gzip"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
"net/http"
"strconv"
"strings"
"sync"
"github.com/bakape/boorufetch"
"github.com/bakape/captchouli/v2/common"
"github.com/bakape/captchouli/v2/db"
"github.com/bakape/captchouli/v2/templates"
"github.com/julienschmidt/httprouter"
)
var (
headers = map[string]string{
"Cache-Control": "no-store, private",
"Access-Control-Allow-Origin": "*",
"Content-Encoding": "gzip",
"Content-Type": "text/html",
}
// Signifies the client had solved the captcha incorrectly
ErrInvalidSolution = Error{errors.New("invalid captcha solution")}
// Captcha ID is of invalid format
ErrInvalidID = Error{errors.New("invalid captcha id")}
// Prebuilt and cached
solutionIDs [9]string
)
func init() {
for i := 0; i < 9; i++ {
solutionIDs[i] = fmt.Sprintf("captchouli-%d", i)
}
}
// Source of image database to use for captcha image generation
type DataSource = common.DataSource
const (
Gelbooru = common.Gelbooru
Danbooru = common.Danbooru
)
const (
// minimum size of image pool for a tag
poolMinSize = 6
)
// Explicitness rating of image
type Rating = boorufetch.Rating
const (
Safe Rating = iota
Questionable
Explicit
)
// Options passed on Service creation
type Options struct {
// Silence non-error log outputs
Quiet bool
// Allow images with varying explicitness. Defaults to only Safe.
Explicitness []Rating
// Tags to source for captcha solutions. One tag is randomly chosen for each
// generated captcha. Required to contain at least 3 tags.
//
// Note that you can only include tags that are discernable from the
// character's face, such as who the character is (example: "cirno") or a
// facial feature of the character (example: "smug").
Tags []string
}
// Encapsulates a configured captcha-generation and verification service
type Service struct {
quiet bool
explicitnessStr string
explicitness []Rating
tags appendSlice
}
// Slice with thread-safe appending
type appendSlice struct {
mu sync.RWMutex
inner []string
}
func (s *appendSlice) Get() []string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.inner
}
func (s *appendSlice) Append(extra string) {
s.mu.Lock()
defer s.mu.Unlock()
s.inner = append(s.inner, extra)
}
// Create new captcha-generation and verification service
func NewService(opts Options) (s *Service, err error) {
if len(opts.Tags) < 3 {
err = Error{errors.New("at least 3 tags required")}
return
}
s = &Service{
quiet: opts.Quiet,
explicitness: opts.Explicitness,
}
if len(s.explicitness) == 0 {
s.explicitness = []Rating{Safe}
}
err = initClassifier()
if err != nil {
return
}
err = s.initPool(opts.Tags)
if err != nil {
return
}
if !s.quiet {
log.Println("captchouli: service started")
}
return
}
// Initialize pool with enough images, if lacking
func (s *Service) initPool(tags []string) (err error) {
formatErr := func(tag string, err error) error {
return Error{
Err: fmt.Errorf(
"error initializing image pool for tag `%s`: %w",
tag,
err,
),
}
}
// Init first 3 tags needed for operation first and init the rest
// eventually to reduce startup times
for _, tag := range tags[:3] {
err = s.initTag(tag)
if err != nil {
return formatErr(tag, err)
}
s.tags.Append(tag)
}
if len(tags) > 3 {
go func() {
for _, tag := range tags[3:] {
err = s.initTag(tag)
if err != nil {
log.Print(formatErr(tag, err))
} else {
s.tags.Append(tag)
}
}
}()
}
return
}
func (s *Service) formatExplicitness() string {
if s.explicitnessStr != "" {
return s.explicitnessStr
}
var w bytes.Buffer
w.WriteByte('[')
for i, r := range s.explicitness {
if i != 0 {
w.WriteString(", ")
}
w.WriteString(r.String())
}
w.WriteByte(']')
s.explicitnessStr = w.String()
return s.explicitnessStr
}
func (s *Service) initTag(tag string) (err error) {
var (
count, fetchCount int
first = true
f = s.filters(tag)
req = f.FetchRequest
)
for {
count, err = db.ImageCount(f)
if err != nil {
return
}
if count >= poolMinSize {
// Terminate open line
if fetchCount != 0 {
fmt.Print("\n")
}
return
} else if first {
first = false
log.Printf(
"captchouli: initializing tag=%s explicitness=%s\n",
tag,
s.formatExplicitness(),
)
}
if !s.quiet {
fetchCount++
fmt.Printf("captchouli: image fetch: %d\n", fetchCount)
}
err = fetch(req)
if err != nil {
return
}
}
}
func (s *Service) filters(tag string) db.Filters {
return db.Filters{
FetchRequest: common.FetchRequest{
Tag: tag,
},
Explicitness: s.explicitness,
}
}
// Creates a new captcha, writes its HTML contents to w and returns captcha ID.
//
// Depending on what type w is, you might want to buffer the output with
// bufio.NewWriter.
func (s *Service) NewCaptcha(w io.Writer, colour, background string,
) (id [64]byte, err error) {
tags := s.tags.Get()
tag := tags[common.RandomInt(len(tags))]
f := s.filters(tag)
n, err := db.ImageCount(f)
if err != nil {
return
}
if n < 4 {
// Not enough to generate captcha. Schedule a fetch and try a different
// tag.
if !common.IsTest {
scheduleFetch <- f.FetchRequest
}
return s.NewCaptcha(w, colour, background)
}
id, images, err := db.GenerateCaptcha(db.Filters{
FetchRequest: common.FetchRequest{
Tag: tag,
},
Explicitness: s.explicitness,
})
if err != nil {
return
}
if background == "" {
background = "#d6daf0"
}
if colour == "" {
colour = "black"
}
tagF := strings.Replace(tag, "_", " ", -1)
if len(tagF) != 0 {
// Don't title() tags of emoticons
switch tagF[0] {
case ';', ':', '=':
default:
tagF = strings.Title(tagF)
}
}
templates.WriteCaptcha(w, colour, background, tagF, id, images)
if !common.IsTest {
scheduleFetch <- f.FetchRequest
}
return
}
// Check a captcha solution for validity.
// solution: slice of selected image numbers
func CheckCaptcha(id [64]byte, solution []byte) error {
solved, err := db.CheckSolution(id, solution)
if err != nil {
return err
} else if !solved {
return ErrInvalidSolution
}
return nil
}
// Creates a routed handler for serving the API.
// The router implements http.Handler.
func (s *Service) Router() *httprouter.Router {
r := httprouter.New()
r.HandlerFunc("GET", "/", func(w http.ResponseWriter, r *http.Request) {
handleError(w, s.ServeNewCaptcha(w, r))
})
r.HandlerFunc("POST", "/", func(w http.ResponseWriter,
r *http.Request,
) {
handleError(w, s.ServeCheckCaptcha(w, r))
})
r.HandlerFunc("POST", "/status", func(w http.ResponseWriter,
r *http.Request,
) {
handleError(w, ServeStatus(w, r))
})
return r
}
// Generate new captcha and serve its HTML form
func (s *Service) ServeNewCaptcha(w http.ResponseWriter, r *http.Request,
) (err error) {
gw := gzip.NewWriter(w)
defer gw.Close()
h := w.Header()
for k, v := range headers {
h.Set(k, v)
}
err = r.ParseForm()
if err != nil {
return
}
_, err = s.NewCaptcha(gw, r.Form.Get(ColourKey), r.Form.Get(BackgroundKey))
return
}
// Serve POST requests for captcha solution validation
func (s *Service) ServeCheckCaptcha(w http.ResponseWriter, r *http.Request,
) (err error) {
id, err := ExtractID(r)
if err != nil {
return
}
solution, err := ExtractSolution(r)
if err != nil {
return
}
err = CheckCaptcha(id, solution)
switch err {
case nil:
dst := make([]byte, base64.StdEncoding.EncodedLen(len(id)))
base64.StdEncoding.Encode(dst, id[:])
w.Write(dst)
case ErrInvalidSolution:
err = s.ServeNewCaptcha(w, r)
}
return
}
func handleError(w http.ResponseWriter, err error) {
code := 500
switch err {
case nil:
return
case ErrInvalidID:
code = 400
}
http.Error(w, err.Error(), code)
}
// Serve captcha solved status. The captcha is deleted on a successful check to
// prevent replayagain attacks.
func ServeStatus(w http.ResponseWriter, r *http.Request) (err error) {
id, err := ExtractID(r)
if err != nil {
return
}
solved, err := db.IsSolved(id)
if err != nil {
return
}
w.Write(strconv.AppendBool(nil, solved))
return
}