This repository has been archived on 2023-07-11. You can view files and clone it, but cannot push or open issues or pull requests.
nginx-ldap-auth/src/timeout.go

121 lines
2.1 KiB
Go
Raw Normal View History

2018-09-15 15:05:36 -04:00
package main
import (
"sort"
"sync"
"time"
)
type passtimer struct {
password string
timer *time.Timer
}
type userpass struct {
correct *passtimer
wrong []passtimer
}
var (
2018-09-15 16:43:44 -04:00
passwords = map[string]*userpass{}
2018-09-15 15:05:36 -04:00
mutex = sync.RWMutex{}
)
func containsWrongPassword(data *userpass, password string) (int, bool) {
size := len(data.wrong)
if size == 0 {
return 0, false
}
pos := sort.Search(size, func(i int) bool {
2018-09-15 16:43:44 -04:00
return data.wrong[i].password >= password
2018-09-15 15:05:36 -04:00
})
return pos, pos < size &&
data.wrong[pos].password == password
}
func getCache(username, password string) (bool, bool) {
defer mutex.RUnlock()
mutex.RLock()
data, found := passwords[username]
if !found {
return false, false
}
if data.correct != nil && (*data.correct).password == password {
return true, true
}
2018-09-15 16:43:44 -04:00
_, found = containsWrongPassword(data, password)
2018-09-15 15:05:36 -04:00
return false, found
}
func putCache(username, password string, ok bool) {
defer mutex.Unlock()
mutex.Lock()
data, found := passwords[username]
if !found {
2018-09-15 16:43:44 -04:00
data = &userpass{}
2018-09-15 15:05:36 -04:00
passwords[username] = data
}
2018-09-15 16:43:44 -04:00
timeout := config.Timeout.Wrong
if ok {
timeout = config.Timeout.Success
}
pass := passtimer{
password: password,
timer: time.AfterFunc(timeout, func() {
removeCache(username, password, ok)
}),
}
2018-09-15 15:05:36 -04:00
if ok {
if data.correct != nil {
data.correct.timer.Stop()
}
2018-09-15 16:43:44 -04:00
data.correct = &pass
2018-09-15 15:05:36 -04:00
} else {
2018-09-15 16:43:44 -04:00
pos, found := containsWrongPassword(data, password)
2018-09-15 15:05:36 -04:00
if found {
data.wrong[pos].timer.Stop()
} else {
data.wrong = append(data.wrong, passtimer{})
copy(data.wrong[pos+1:], data.wrong[pos:])
}
data.wrong[pos] = pass
}
}
func removeCache(username, password string, ok bool) {
defer mutex.Unlock()
mutex.Lock()
data, found := passwords[username]
if !found {
return
}
if ok {
if data.correct != nil {
data.correct.timer.Stop()
data.correct = nil
}
} else {
2018-09-15 16:43:44 -04:00
pos, found := containsWrongPassword(data, password)
2018-09-15 15:05:36 -04:00
if found {
data.wrong[pos].timer.Stop()
data.wrong = data.wrong[:pos+copy(data.wrong[pos:], data.wrong[pos+1:])]
}
}
if data.correct == nil && len(data.wrong) == 0 {
delete(passwords, username)
}
}