Browse Source

Initial commit

master 1.0.0
LowEel 2 weeks ago
parent
commit
abf901d932
90 changed files with 9854 additions and 0 deletions
  1. +6
    -0
      .gitignore
  2. +3
    -0
      .vscode/settings.json
  3. +15
    -0
      LICENSE
  4. +122
    -0
      README.md
  5. +51
    -0
      alloc.go
  6. +40
    -0
      assets/message.txt
  7. +237
    -0
      bindata.go
  8. +6
    -0
      blacklist.txt
  9. +24
    -0
      build.sh
  10. +147
    -0
      classifier.go
  11. +93
    -0
      file.go
  12. +11
    -0
      go.mod
  13. +10
    -0
      go.sum
  14. +80
    -0
      handler.go
  15. +125
    -0
      log.go
  16. +53
    -0
      main.go
  17. +276
    -0
      matrix.go
  18. +8
    -0
      run.sh
  19. +202
    -0
      vendor/github.com/blevesearch/bleve/LICENSE
  20. +152
    -0
      vendor/github.com/blevesearch/bleve/analysis/freq.go
  21. +7
    -0
      vendor/github.com/blevesearch/bleve/analysis/test_words.txt
  22. +84
    -0
      vendor/github.com/blevesearch/bleve/analysis/tokenizer/regexp/regexp.go
  23. +76
    -0
      vendor/github.com/blevesearch/bleve/analysis/tokenmap.go
  24. +103
    -0
      vendor/github.com/blevesearch/bleve/analysis/type.go
  25. +92
    -0
      vendor/github.com/blevesearch/bleve/analysis/util.go
  26. +101
    -0
      vendor/github.com/blevesearch/bleve/document/document.go
  27. +41
    -0
      vendor/github.com/blevesearch/bleve/document/field.go
  28. +123
    -0
      vendor/github.com/blevesearch/bleve/document/field_boolean.go
  29. +124
    -0
      vendor/github.com/blevesearch/bleve/document/field_composite.go
  30. +159
    -0
      vendor/github.com/blevesearch/bleve/document/field_datetime.go
  31. +152
    -0
      vendor/github.com/blevesearch/bleve/document/field_geopoint.go
  32. +145
    -0
      vendor/github.com/blevesearch/bleve/document/field_numeric.go
  33. +139
    -0
      vendor/github.com/blevesearch/bleve/document/field_text.go
  34. +66
    -0
      vendor/github.com/blevesearch/bleve/document/indexing_options.go
  35. +9
    -0
      vendor/github.com/blevesearch/bleve/geo/README.md
  36. +208
    -0
      vendor/github.com/blevesearch/bleve/geo/geo.go
  37. +98
    -0
      vendor/github.com/blevesearch/bleve/geo/geo_dist.go
  38. +111
    -0
      vendor/github.com/blevesearch/bleve/geo/geohash.go
  39. +179
    -0
      vendor/github.com/blevesearch/bleve/geo/parse.go
  40. +212
    -0
      vendor/github.com/blevesearch/bleve/geo/sloppy.go
  41. +110
    -0
      vendor/github.com/blevesearch/bleve/index/analysis.go
  42. +88
    -0
      vendor/github.com/blevesearch/bleve/index/field_cache.go
  43. +369
    -0
      vendor/github.com/blevesearch/bleve/index/index.go
  44. +62
    -0
      vendor/github.com/blevesearch/bleve/index/store/batch.go
  45. +174
    -0
      vendor/github.com/blevesearch/bleve/index/store/kvstore.go
  46. +64
    -0
      vendor/github.com/blevesearch/bleve/index/store/merge.go
  47. +33
    -0
      vendor/github.com/blevesearch/bleve/index/store/multiget.go
  48. +43
    -0
      vendor/github.com/blevesearch/bleve/numeric/bin.go
  49. +34
    -0
      vendor/github.com/blevesearch/bleve/numeric/float.go
  50. +111
    -0
      vendor/github.com/blevesearch/bleve/numeric/prefix_coded.go
  51. +89
    -0
      vendor/github.com/blevesearch/bleve/registry/analyzer.go
  52. +87
    -0
      vendor/github.com/blevesearch/bleve/registry/cache.go
  53. +89
    -0
      vendor/github.com/blevesearch/bleve/registry/char_filter.go
  54. +89
    -0
      vendor/github.com/blevesearch/bleve/registry/datetime_parser.go
  55. +89
    -0
      vendor/github.com/blevesearch/bleve/registry/fragment_formatter.go
  56. +89
    -0
      vendor/github.com/blevesearch/bleve/registry/fragmenter.go
  57. +89
    -0
      vendor/github.com/blevesearch/bleve/registry/highlighter.go
  58. +45
    -0
      vendor/github.com/blevesearch/bleve/registry/index_type.go
  59. +184
    -0
      vendor/github.com/blevesearch/bleve/registry/registry.go
  60. +51
    -0
      vendor/github.com/blevesearch/bleve/registry/store.go
  61. +89
    -0
      vendor/github.com/blevesearch/bleve/registry/token_filter.go
  62. +89
    -0
      vendor/github.com/blevesearch/bleve/registry/token_maps.go
  63. +89
    -0
      vendor/github.com/blevesearch/bleve/registry/tokenizer.go
  64. +52
    -0
      vendor/github.com/blevesearch/bleve/search/collector.go
  65. +55
    -0
      vendor/github.com/blevesearch/bleve/search/explanation.go
  66. +341
    -0
      vendor/github.com/blevesearch/bleve/search/facets_builder.go
  67. +64
    -0
      vendor/github.com/blevesearch/bleve/search/highlight/highlighter.go
  68. +105
    -0
      vendor/github.com/blevesearch/bleve/search/highlight/term_locations.go
  69. +114
    -0
      vendor/github.com/blevesearch/bleve/search/levenshtein.go
  70. +91
    -0
      vendor/github.com/blevesearch/bleve/search/pool.go
  71. +378
    -0
      vendor/github.com/blevesearch/bleve/search/search.go
  72. +741
    -0
      vendor/github.com/blevesearch/bleve/search/sort.go
  73. +69
    -0
      vendor/github.com/blevesearch/bleve/search/util.go
  74. +59
    -0
      vendor/github.com/blevesearch/bleve/size/sizes.go
  75. +8
    -0
      vendor/github.com/blevesearch/go-porterstemmer/.gitignore
  76. +16
    -0
      vendor/github.com/blevesearch/go-porterstemmer/.travis.yml
  77. +19
    -0
      vendor/github.com/blevesearch/go-porterstemmer/LICENSE
  78. +118
    -0
      vendor/github.com/blevesearch/go-porterstemmer/README.md
  79. +839
    -0
      vendor/github.com/blevesearch/go-porterstemmer/porterstemmer.go
  80. +2
    -0
      vendor/github.com/lytics/multibayes/.travis.yml
  81. +63
    -0
      vendor/github.com/lytics/multibayes/README.md
  82. +9
    -0
      vendor/github.com/lytics/multibayes/doc.go
  83. +66
    -0
      vendor/github.com/lytics/multibayes/encoding.go
  84. +73
    -0
      vendor/github.com/lytics/multibayes/sparse.go
  85. +181
    -0
      vendor/github.com/lytics/multibayes/stopbytes.go
  86. +33
    -0
      vendor/github.com/lytics/multibayes/testutil.go
  87. +166
    -0
      vendor/github.com/lytics/multibayes/tokenize.go
  88. +16
    -0
      vendor/modules.txt
  89. +4
    -0
      whitelist.txt
  90. +26
    -0
      zgc.go

+ 6
- 0
.gitignore View File

@ -0,0 +1,6 @@
zardoz
bayes.*
/logs
logs/*
binaries/*
binaries

+ 3
- 0
.vscode/settings.json View File

@ -0,0 +1,3 @@
{
"go.inferGopath": false
}

+ 15
- 0
LICENSE View File

@ -0,0 +1,15 @@
Zardoz: a lightweight WAF , based on Pseudo-Bayes machine learning.
Copyright (C) 2020 loweel@keinpfusch.net
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

+ 122
- 0
README.md View File

@ -0,0 +1,122 @@
# Zardoz: a lightweight WAF , based on Pseudo-Bayes machine learning.
Zardoz is a small WAF, aiming to take off HTTP calls which are well-known to end in some HTTP error. It behaves like a reverse proxy, running as a frontend. It intercepts the calls, forwards them when needed and learns how the server reacts from the Status Code.
After a while, the bayes classifier is able to understand what is a "good" HTTP call and a bad one, based on the header contents.
It is designed to don't consume much memory neither CPU, so that you don't need powerful servers to keep it running, neither it can introduce high latency on the web server.
## STATUS:
This is just an experiment I'm doing with Pseudo-Bayes classifiers. It works pretty well with my blog. Run in production at your own risk.
## Compiling:
Requirements:
- golang >= 1.12.9
build:
```bash
git clone https://git.keinpfusch.net/LowEel/zardoz
cd zardoz
go build
```
## Starting:
Zardoz has no configuration file, it entirely depends from environment string.
In Dockerfile, this maps like:
```bash
ENV REVERSEURL http://10.0.1.1:3000
ENV PROXYPORT :17000
ENV TRIGGER 0.6
ENV SENIORITY 1025
ENV DEBUG false
ENV DUMPFILE /somewhere/bayes.txt
ENV COLLECTION 2048
```
Using a bash script, this means something like:
```bash
export REVERSEURL=http://10.0.1.1:3000
export PROXYPORT=":17000"
export TRIGGER="0.6"
export SENIORITY="1025"
export DEBUG="true"
export DUMPFILE="/somewhere/bayes.txt"
export COLLECTION
./zardoz
```
## Understanding Configuration:
**REVERSEURL** is the server zardoz will be a reverse proxy for. This maps to IP and port of the server you want to protect.
**PROXYPORT** is the IP and PORT where zardoz will listen. If you want zardoz to listen on all ports, just write like ":17000", meaning, it will listen on all interfaces at port 17000
**TRIGGER**: this is one of the trickiest part. We can describe the behavior of zardoz in quadrants, like:
| - | BAD > GOOD | BAD < GOOD |
| ------------------------------- | ----------- | ---------- |
| **\| GOOD - BAD \| > TRIGGER** | BLOCK | PASS |
| **\| GOOD - BAD \| <= TRIGGER** | BLOCK+LEARN | PASS+LEARN |
The value of trigger can be from 0 to 1, like "0.5" or "0.6". The difference between BLOCK without learning and block with learning is execution time. On the point of view of user experience, it will change nothing (user will be blocked) but in case of "block+learn" the machine will try to learn the lesson.
Basically, if the GOOD and BAD are very far, "likelyhood" is very high, so that block and pass are taken strictly.
If the likelyhood is lesser than TRIGGER, then we aren't sure the prediction is good, so zardoz executes the PASS or BLOCK, but it waits for the response , and learns from it. To summerize, the concept is about "likelyhood", which makes the difference between an action and the same action + LEARN.
Personally I've got good results putting the trigger at 0.6, meaning this is not disturbing so much users, and in the same time it has filtered tons of malicious scan.
**SENIORITY**: since Zardoz will learn what is good for your web server, it takes time to gain seniority. To start Zardoz as empty and leave it to decide will generate some terrible behavior, because of false positives and false negatives. Plus, at the beginning Zardoz is supposed to ALWAYS learn.
The parameter "SENIORITY" is then the amount of requests it will set in "PASS+LEARN" before the filtering starts. During this time, it will learn from real traffic. It will block no traffic unless "seniority" is reach. If you set it to 1025, it will learn from 1025 requests and then it will start to actually filter the requests. The number depends by many factors: if you have a lot of page served and a lot of contents, I suggest to increase the number.
**DUMPFILE**
This is where you want the dumpfile to be saved. Useful with Docker volumes.
**COLLECTION**
The amount of collected tokens which are considered enough to do a good job. This depends by your service. This is useful to limit memory usage if your server has a very complex content, by example.
**TROUBLESHOOTING:**
If DEBUG is set to "false" or not set, minute Zardoz will dump the sparse matrix describing to the whole bayesian learning, into a file named bayes.json. This contains the weighted matrix of calls and classes. If Zardoz is not behaving like you expected, you may give a look to this file. The format is a classic sparse matrix. WARNING: this file **may** contain cookies or other sensitive headers.
DEBUG : if set to "true", Zardoz will create a folder "logs" and log what happens, together with the dump of sparse matrix. If set to "false" or not set, sparse matrix will be available on disk for post-mortem.
**CREDIT**
Credits for the Bayesian Implementation to Jake Brukhman : https://github.com/jbrukh/bayesian
## TODO:
- [ ] Loading Bayesian data from file.
- [X] Better Logging
- [ ] Configurable block message.
- [ ] Usage Statistics/Metrics sent to influxDB/prometheus/whatever

+ 51
- 0
alloc.go View File

@ -0,0 +1,51 @@
package main
import (
"fmt"
"log"
"net/http"
"time"
)
//HTTPFlow is a type containg all the data we need.
type HTTPFlow struct {
request *http.Request
response *http.Response
sensitivity float64 // value who triggers decisions
seniority int64
collection float64
refreshtime time.Duration
}
//DebugLog tells if logs are in debug mode or not
var DebugLog bool
//ProxyFlow represents our flow
var ProxyFlow HTTPFlow
//ZClassifier is our bayesian classifier
var ZClassifier *ByClassifier
//BlockMessage is the messgae we return when blocking
var BlockMessage string
//Maturity is the minimal amount of request , needed to say Zardoz has learnt enough
var Maturity int64
func init() {
ZClassifier = new(ByClassifier)
ZClassifier.enroll()
ProxyFlow.sensitivity = 0.5
ProxyFlow.seniority = 0
bl, err := Asset("assets/message.txt")
if err != nil {
log.Println("Cannot marshal asset error message!!")
BlockMessage = ""
} else {
BlockMessage = fmt.Sprintf("%s", bl)
}
}

+ 40
- 0
assets/message.txt
File diff suppressed because it is too large
View File


+ 237
- 0
bindata.go
File diff suppressed because it is too large
View File


+ 6
- 0
blacklist.txt View File

@ -0,0 +1,6 @@
penis
wallet
/.well-known/host-meta
/.well-known/host-meta/
/.well-known/nodeinfo

+ 24
- 0
build.sh View File

@ -0,0 +1,24 @@
#!/bin/bash
rm ./zardoz
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -mod=vendor
file zardoz
mv ./zardoz ./binaries/arm64/zardoz
tar -cvzf ./binaries/tgz/zardoz_arm64.tgz -C ./binaries/arm64 . --owner=0 --group=0
GOOS=linux GOARCH=arm CGO_ENABLED=0 GOARM=7 go build -mod=vendor
file zardoz
mv ./zardoz ./binaries/armv7/zardoz
tar -cvzf ./binaries/tgz/zardoz_armv7.tgz -C ./binaries/armv7 . --owner=0 --group=0
GOOS=linux GOARCH=mips CGO_ENABLED=0 go build -mod=vendor
file zardoz
mv ./zardoz ./binaries/mips32/zardoz
tar -cvzf ./binaries/tgz/zardoz_mips32.tgz -C ./binaries/mips32 . --owner=0 --group=0
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -mod=vendor
file zardoz
mv ./zardoz ./binaries/amd64/zardoz
tar -cvzf ./binaries/tgz/zardoz_amd64.tgz -C ./binaries/amd64 . --owner=0 --group=0

+ 147
- 0
classifier.go View File

@ -0,0 +1,147 @@
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
)
//Zexpressions is the set of regexp being used by zardoz
var Zexpressions = []string{
`[[:alpha:]]{4,32}`, // alpha digit token
`[ ]([A-Za-z0-9-_]{4,}\.)+\w+`, // domain name
`[ ]/[A-Za-z0-9-_/.]{4,}[ ]`, // URI path (also partial)
`[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}`, // IP address
`[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}`, // UUID
}
func passAndLearn(resp *http.Response) error {
ProxyFlow.response = resp
ProxyFlow.seniority++
req := ProxyFlow.request
switch {
case isAuth(resp):
log.Println("401: We don't want to store credentials")
case isError(resp):
buf := bytes.NewBufferString(BlockMessage)
resp.Body = ioutil.NopCloser(buf)
resp.Status = "403 Forbidden"
resp.StatusCode = 403
resp.Header["Content-Length"] = []string{fmt.Sprint(buf.Len())}
resp.Header.Set("Content-Encoding", "none")
resp.Header.Set("Cache-Control", "no-cache, no-store")
log.Println("Filing inside bad class")
feedRequest(req, "BAD")
ControPlane.StatsTokens <- "DOWNGRADE"
case isSuccess(resp):
log.Println("Filing inside Good Class: ", resp.StatusCode)
feedRequest(req, "GOOD")
}
return nil
}
func blockAndlearn(resp *http.Response) error {
ProxyFlow.response = resp
ProxyFlow.seniority++
req := ProxyFlow.request
buf := bytes.NewBufferString(BlockMessage)
resp.Body = ioutil.NopCloser(buf)
resp.Status = "403 Forbidden"
resp.StatusCode = 403
resp.Header["Content-Length"] = []string{fmt.Sprint(buf.Len())}
resp.Header.Set("Content-Encoding", "none")
resp.Header.Set("Cache-Control", "no-cache, no-store")
switch {
case isAuth(resp):
log.Println("401: We don't want to store credentials")
case isError(resp):
log.Println("Filing inside bad class")
feedRequest(req, "BAD")
case isSuccess(resp):
log.Println("Filing inside Good Class: ", resp.StatusCode)
ControPlane.StatsTokens <- "UPGRADED"
feedRequest(req, "GOOD")
}
return nil
}
func feedRequest(req *http.Request, class string) {
feed := SourceIP(req)
// feed := formatRequest(req)
if class == "BAD" {
log.Println("Feeding BAD token: ", feed)
ControPlane.BadTokens <- feed
}
if class == "GOOD" {
log.Println("Feeding GOOD Token:", feed)
ControPlane.GoodTokens <- feed
}
}
//Unique returns unique elements in the string
func Unique(slice []string) []string {
// create a map with all the values as key
uniqMap := make(map[string]struct{})
for _, v := range slice {
uniqMap[v] = struct{}{}
}
// turn the map keys into a slice
uniqSlice := make([]string, 0, len(uniqMap))
for v := range uniqMap {
uniqSlice = append(uniqSlice, v)
}
return uniqSlice
}
func isSuccess(resp *http.Response) bool {
return resp.StatusCode <= 299
}
func isAuth(resp *http.Response) bool {
return resp.StatusCode == 401
}
func isError(resp *http.Response) bool {
return resp.StatusCode >= 400 && resp.StatusCode != 401
}
//SourceIP returns the source IP of a http call
func SourceIP(req *http.Request) string {
var feed string
if feed = req.Header.Get("X-Forwarded-For"); feed != "" {
log.Println("Got X-Forwarded-For: " + feed)
} else {
feed, _, _ = net.SplitHostPort(req.RemoteAddr)
log.Println("NO X-Forwarded-For, using: "+feed+" from ", req.RemoteAddr)
}
return feed
}

+ 93
- 0
file.go View File

@ -0,0 +1,93 @@
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"time"
)
// WriteToFile will print any string of text to a file safely by
// checking for errors and syncing at the end.
func writeToFile(filename string, data string) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
_, err = io.WriteString(file, data)
if err != nil {
return err
}
return file.Sync()
}
func handlepanic() {
if a := recover(); a != nil {
fmt.Println("OPS!: Recovering from:", a)
}
}
func saveBayesToFile() {
log.Println("Trying to write json file")
defer handlepanic()
dumpfile := os.Getenv("DUMPFILE")
if dumpfile == "" {
dumpfile = "bayes.json"
}
ZClassifier.STATS.busy.Lock()
defer ZClassifier.STATS.busy.Unlock()
statsREPORT, err := json.MarshalIndent(ZClassifier.STATS.stats, "", " ")
if err != nil {
statsREPORT = []byte(err.Error())
}
ZClassifier.Working.busy.Lock()
defer ZClassifier.Working.busy.Unlock()
wScores, err := json.MarshalIndent(ZClassifier.Working.sMap, "", " ")
if err != nil {
wScores = []byte(err.Error())
}
ZClassifier.Learning.busy.Lock()
defer ZClassifier.Learning.busy.Unlock()
lScores, err := json.MarshalIndent(ZClassifier.Learning.sMap, "", " ")
if err != nil {
lScores = []byte(err.Error())
}
report := fmt.Sprintf("STATS: %s\n WORKING: %s\n LEARNING: %s\n", statsREPORT, wScores, lScores)
writeToFile(dumpfile, report)
log.Println(report)
}
func jsonEngine() {
for {
log.Println("Zardoz Seniority: ", ProxyFlow.seniority)
saveBayesToFile()
time.Sleep(1 * time.Minute)
}
}
func init() {
log.Printf("File Engine Starting")
go jsonEngine()
log.Printf("FIle Engine Started")
}

+ 11
- 0
go.mod View File

@ -0,0 +1,11 @@
module zardoz
go 1.13
require (
github.com/blevesearch/bleve v0.8.1 // indirect
github.com/blevesearch/go-porterstemmer v1.0.2 // indirect
github.com/go-bindata/go-bindata v3.1.2+incompatible // indirect
github.com/jteeuwen/go-bindata v3.0.7+incompatible // indirect
github.com/lytics/multibayes v0.0.0-20161108162840-3457a5582021
)

+ 10
- 0
go.sum View File

@ -0,0 +1,10 @@
github.com/blevesearch/bleve v0.8.1 h1:20zBREtGe8dvBxCC+717SaxKcUVQOWk3/Fm75vabKpU=
github.com/blevesearch/bleve v0.8.1/go.mod h1:Y2lmIkzV6mcNfAnAdOd+ZxHkHchhBfU/xroGIp61wfw=
github.com/blevesearch/go-porterstemmer v1.0.2 h1:qe7n69gBd1OLY5sHKnxQHIbzn0LNJA4hpAf+5XDxV2I=
github.com/blevesearch/go-porterstemmer v1.0.2/go.mod h1:haWQqFT3RdOGz7PJuM3or/pWNJS1pKkoZJWCkWu0DVA=
github.com/go-bindata/go-bindata v3.1.2+incompatible h1:5vjJMVhowQdPzjE1LdxyFF7YFTXg5IgGVW4gBr5IbvE=
github.com/go-bindata/go-bindata v3.1.2+incompatible/go.mod h1:xK8Dsgwmeed+BBsSy2XTopBn/8uK2HWuGSnA11C3Joo=
github.com/jteeuwen/go-bindata v3.0.7+incompatible h1:91Uy4d9SYVr1kyTJ15wJsog+esAZZl7JmEfTkwmhJts=
github.com/jteeuwen/go-bindata v3.0.7+incompatible/go.mod h1:JVvhzYOiGBnFSYRyV00iY8q7/0PThjIYav1p9h5dmKs=
github.com/lytics/multibayes v0.0.0-20161108162840-3457a5582021 h1:J9Pk5h7TJlqMQtcINI23BUa0+bbxRXPMf7r8gAlfNxo=
github.com/lytics/multibayes v0.0.0-20161108162840-3457a5582021/go.mod h1:lXjTNxya7kn6QNxA3fW8WGYQq0KL/SUcPE9AwcPSgwI=

+ 80
- 0
handler.go View File

@ -0,0 +1,80 @@
package main
import (
"fmt"
"log"
"math"
"net/http"
"net/http/httputil"
)
func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
//put the request inside our structure
ProxyFlow.request = r
log.Println("Received HTTP Request")
probs := ZClassifier.Posterior(SourceIP(r))
log.Printf("Posterior Probabilities: %+v\n", probs)
action := quadrant(probs)
ControPlane.StatsTokens <- action
switch action {
case "BLOCK", "BLOCKLEARN":
p.ModifyResponse = blockAndlearn
w.Header().Set("Probabilities", fmt.Sprintf("%v ", probs))
log.Println("Request Blocked")
p.ServeHTTP(w, r)
case "PASS", "PASSLEARN":
p.ModifyResponse = passAndLearn
w.Header().Set("Probabilities", fmt.Sprintf("%v ", probs))
p.ServeHTTP(w, r)
log.Println("Passing Request")
default:
log.Println("No Decision: PASS and LEARN")
p.ModifyResponse = passAndLearn
w.Header().Set("Probabilities", fmt.Sprintf("%v ", probs))
p.ServeHTTP(w, r)
}
}
}
func quadrant(p map[string]float64) string {
sure := math.Abs(p["BAD"]-p["GOOD"]) >= ProxyFlow.sensitivity
badish := p["BAD"] > p["GOOD"]
goodish := p["GOOD"] > p["BAD"]
if ProxyFlow.seniority < Maturity {
log.Println("Seniority too low. Waiting.")
return "PASSLEARN"
}
if sure {
if goodish {
return "PASS"
}
if badish {
return "BLOCK"
}
} else {
if goodish {
return "PASSLEARN"
}
if badish {
return "BLOCKLEARN"
}
}
return "PASSLEARN"
}

+ 125
- 0
log.go View File

@ -0,0 +1,125 @@
package main
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"time"
)
//Zardozlogfile defines the log structure
type Zardozlogfile struct {
filename string
logfile *os.File
active bool
}
//VSlogfile is the logger we use
var VSlogfile Zardozlogfile
func init() {
verbose := os.Getenv("DEBUG")
log.Println("Verbose mode on: ", verbose)
DebugLog = (verbose == "true")
log.Println("DebugLog: ", DebugLog)
log.Println("Starting Log Engine")
// just the first time
var currentFolder = Hpwd()
os.MkdirAll(filepath.Join(currentFolder, "logs"), 0755)
//
VSlogfile.active = DebugLog
VSlogfile.SetLogFolder()
go VSlogfile.RotateLogFolder()
}
//RotateLogFolder rotates the log folder
func (lf *Zardozlogfile) RotateLogFolder() {
for {
time.Sleep(1 * time.Hour)
if lf.logfile != nil {
err := lf.logfile.Close()
log.Println("[TOOLS][LOG] close logfile returned: ", err)
}
lf.SetLogFolder()
}
}
//SetLogFolder sets the log folder
func (lf *Zardozlogfile) SetLogFolder() {
if DebugLog {
lf.EnableLog()
} else {
lf.DisableLog()
}
if lf.active {
const layout = "2006-01-02.15"
orario := time.Now().UTC()
var currentFolder = Hpwd()
lf.filename = filepath.Join(currentFolder, "logs", "Zardoz."+orario.Format(layout)+"00.log")
lf.logfile, _ = os.Create(lf.filename)
log.Println("[TOOLS][LOG] Logfile is: " + lf.filename)
log.SetOutput(lf.logfile)
// log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
log.SetFlags(log.LstdFlags | log.LUTC)
} else {
log.SetOutput(ioutil.Discard)
}
}
//EnableLog enables logging
func (lf *Zardozlogfile) EnableLog() {
lf.active = true
}
//DisableLog disables logging
func (lf *Zardozlogfile) DisableLog() {
lf.active = false
log.SetFlags(0)
log.SetOutput(ioutil.Discard)
}
//LogEngineStart just triggers the init for the package, and logs it.
func LogEngineStart() {
log.Println("LogRotation Init")
}
//Hpwd behaves like the unix pwd command, returning the current path
func Hpwd() string {
tmpLoc, err := os.Getwd()
if err != nil {
tmpLoc = "/tmp"
log.Printf("[TOOLS][FS] Problem getting unix pwd: %s", err.Error())
}
return tmpLoc
}

+ 53
- 0
main.go View File

@ -0,0 +1,53 @@
package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
)
func main() {
vip := os.Getenv("REVERSEURL")
pport := os.Getenv("PROXYPORT")
sensitivity := os.Getenv("TRIGGER")
maturity := os.Getenv("SENIORITY")
collect := os.Getenv("COLLECTION")
log.Println("Reverse path is: ", vip)
log.Println("Reverse port is: ", pport)
remote, err := url.Parse(vip)
if err != nil {
panic(err)
}
ProxyFlow.sensitivity, err = strconv.ParseFloat(sensitivity, 64)
if err != nil {
ProxyFlow.sensitivity = 0.5
}
log.Println("Trigger is: ", ProxyFlow.sensitivity)
Maturity, err = strconv.ParseInt(maturity, 10, 64)
if err != nil {
Maturity = 1024
}
log.Println("Minimum request to learn: ", Maturity)
ProxyFlow.collection, err = strconv.ParseFloat(collect, 64)
if err != nil {
// This is because we assume every example should add at least one token
ProxyFlow.collection = float64(Maturity)
}
log.Println("Collection limit is: ", ProxyFlow.collection)
proxy := httputil.NewSingleHostReverseProxy(remote)
http.HandleFunc("/", handler(proxy))
err = http.ListenAndServe(pport, nil)
if err != nil {
panic(err)
}
}

+ 276
- 0
matrix.go View File

@ -0,0 +1,276 @@
package main
import (
"bufio"
"log"
"os"
"strings"
"sync"
"time"
)
//ByControlPlane contains all the channels we need.
type ByControlPlane struct {
BadTokens chan string
GoodTokens chan string
StatsTokens chan string
}
type safeClassifier struct {
sMap map[string]string
busy sync.Mutex
}
type safeStats struct {
stats map[string]int64
busy sync.Mutex
}
//ControPlane is the variabile
var ControPlane ByControlPlane
//ByClassifier is the structure containing our Pseudo-Bayes classifier.
type ByClassifier struct {
STATS safeStats
Learning safeClassifier
Working safeClassifier
Generation int64
}
//AddStats adds the statistics after proper blocking.
func (c *ByClassifier) AddStats(action string) {
c.STATS.busy.Lock()
defer c.STATS.busy.Unlock()
if _, exists := c.STATS.stats[action]; exists {
c.STATS.stats[action]++
} else {
c.STATS.stats[action] = 1
}
}
//IsBAD inserts a bad key in the right place.
func (c *ByClassifier) IsBAD(key string) {
log.Println("BAD Received", key)
k := strings.Fields(key)
c.Learning.busy.Lock()
defer c.Learning.busy.Unlock()
for _, tk := range k {
if kind, exists := c.Learning.sMap[tk]; exists {
switch kind {
case "BAD":
log.Println("Word was known as bad:", tk)
case "GOOD":
c.Learning.sMap[tk] = "MEH"
log.Println("So sad, work was known as good", tk)
case "MEH":
log.Println("Word was known as ambiguos:", tk)
}
} else {
c.Learning.sMap[tk] = "BAD"
}
}
log.Println("BAD Learned", key)
}
//IsGOOD inserts the key in the right place.
func (c *ByClassifier) IsGOOD(key string) {
k := strings.Fields(key)
log.Println("GOOD Received", key)
c.Learning.busy.Lock()
defer c.Learning.busy.Unlock()
for _, tk := range k {
if kind, exists := c.Learning.sMap[tk]; exists {
switch kind {
case "GOOD":
log.Println("Word was known as good: ", tk)
case "BAD":
c.Learning.sMap[tk] = "MEH"
log.Println("So sad, work was known as bad: ", tk)
case "MEH":
log.Println("Word was known as ambiguos: ", tk)
}
} else {
c.Learning.sMap[tk] = "GOOD"
}
}
log.Println("GOOD Learned", key)
}
//Posterior calculates Shannon based entropy using bad and good as different distributions
func (c *ByClassifier) Posterior(hdr string) map[string]float64 {
tokens := strings.Fields(hdr)
ff := make(map[string]float64)
if c.Generation == 0 || len(tokens) == 0 {
ff["BAD"] = 0.5
ff["GOOD"] = 0.5
return ff
}
log.Println("Posterior locking the Working Bayesian")
c.Working.busy.Lock()
defer c.Working.busy.Unlock()
var totalGood, totalBad float64
for _, tk := range tokens {
if kind, exists := c.Working.sMap[tk]; exists {
switch kind {
case "BAD":
totalBad++
case "GOOD":
totalGood++
}
}
}
ff["GOOD"] = 1 - (totalBad / float64(len(tokens)))
ff["BAD"] = 1 - (totalGood / float64(len(tokens)))
return ff
}
func (c *ByClassifier) enroll() {
ControPlane.BadTokens = make(chan string, 2048)
ControPlane.GoodTokens = make(chan string, 2048)
ControPlane.StatsTokens = make(chan string, 2048)
c.Generation = 0
c.Learning.sMap = make(map[string]string)
c.Working.sMap = make(map[string]string)
c.STATS.stats = make(map[string]int64)
c.readInitList("blacklist.txt", "BAD")
c.readInitList("whitelist.txt", "GOOD")
go c.readBadTokens()
go c.readGoodTokens()
go c.readStatsTokens()
go c.updateLearners()
log.Println("Classifier populated...")
}
func (c *ByClassifier) readBadTokens() {
log.Println("Start reading BAD tokens")
for token := range ControPlane.BadTokens {
log.Println("Received BAD Token: ", token)
c.IsBAD(token)
}
}
func (c *ByClassifier) readGoodTokens() {
log.Println("Start reading GOOD tokens")
for token := range ControPlane.GoodTokens {
log.Println("Received GOOD Token: ", token)
c.IsGOOD(token)
}
}
func (c *ByClassifier) readStatsTokens() {
log.Println("Start reading STATS tokens")
for token := range ControPlane.StatsTokens {
c.AddStats(token)
}
}
func (c *ByClassifier) readInitList(filePath, class string) {
inFile, err := os.Open(filePath)
if err != nil {
log.Println(err.Error() + `: ` + filePath)
return
}
defer inFile.Close()
scanner := bufio.NewScanner(inFile)
for scanner.Scan() {
if len(scanner.Text()) > 3 {
switch class {
case "BAD":
log.Println("Loading into Blacklist: ", scanner.Text()) // the line
c.IsBAD(scanner.Text())
case "GOOD":
log.Println("Loading into Whitelist: ", scanner.Text()) // the line
c.IsGOOD(scanner.Text())
}
}
}
}
func (c *ByClassifier) updateLearners() {
log.Println("Bayes Updater Start...")
ticker := time.NewTicker(10 * time.Second)
for ; true; <-ticker.C {
var currentGen int64
log.Println("Maturity is:", Maturity)
log.Println("Seniority is:", ProxyFlow.seniority)
if Maturity > 0 {
currentGen = ProxyFlow.seniority / Maturity
} else {
currentGen = 0
}
log.Println("Current Generation is: ", currentGen)
log.Println("Working Generation is: ", c.Generation)
if currentGen > c.Generation || float64(len(c.Learning.sMap)) > ProxyFlow.collection {
c.Learning.busy.Lock()
c.Working.busy.Lock()
c.Working.sMap = c.Learning.sMap
c.Learning.sMap = make(map[string]string)
c.Generation = currentGen
log.Println("Generation Updated to: ", c.Generation)
ControPlane.StatsTokens <- "GENERATION"
c.Learning.busy.Unlock()
c.Working.busy.Unlock()
}
}
}

+ 8
- 0
run.sh View File

@ -0,0 +1,8 @@
export REVERSEURL=https://google.com
export PROXYPORT=":8089"
export TRIGGER="0.6"
#export SENIORITY="1025"
export SENIORITY="15"
export DEBUG="true"
export DUMPFILE="bayes.json"
./zardoz

+ 202
- 0
vendor/github.com/blevesearch/bleve/LICENSE View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

+ 152
- 0
vendor/github.com/blevesearch/bleve/analysis/freq.go View File

@ -0,0 +1,152 @@
// Copyright (c) 2014 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package analysis
import (
"reflect"
"github.com/blevesearch/bleve/size"
)
var reflectStaticSizeTokenLocation int
var reflectStaticSizeTokenFreq int
func init() {
var tl TokenLocation
reflectStaticSizeTokenLocation = int(reflect.TypeOf(tl).Size())
var tf TokenFreq
reflectStaticSizeTokenFreq = int(reflect.TypeOf(tf).Size())
}
// TokenLocation represents one occurrence of a term at a particular location in
// a field. Start, End and Position have the same meaning as in analysis.Token.
// Field and ArrayPositions identify the field value in the source document.
// See document.Field for details.
type TokenLocation struct {
Field string
ArrayPositions []uint64
Start int
End int
Position int
}
func (tl *TokenLocation) Size() int {
rv := reflectStaticSizeTokenLocation
rv += len(tl.ArrayPositions) * size.SizeOfUint64
return rv
}
// TokenFreq represents all the occurrences of a term in all fields of a
// document.
type TokenFreq struct {
Term []byte
Locations []*TokenLocation
frequency int
}
func (tf *TokenFreq) Size() int {
rv := reflectStaticSizeTokenFreq
rv += len(tf.Term)
for _, loc := range tf.Locations {
rv += loc.Size()
}
return rv
}
func (tf *TokenFreq) Frequency() int {
return tf.frequency
}
// TokenFrequencies maps document terms to their combined frequencies from all
// fields.
type TokenFrequencies map[string]*TokenFreq
func (tfs TokenFrequencies) Size() int {
rv := size.SizeOfMap
rv += len(tfs) * (size.SizeOfString + size.SizeOfPtr)
for k, v := range tfs {
rv += len(k)
rv += v.Size()
}
return rv
}
func (tfs TokenFrequencies) MergeAll(remoteField string, other TokenFrequencies) {
// walk the new token frequencies
for tfk, tf := range other {
// set the remoteField value in incoming token freqs
for _, l := range tf.Locations {
l.Field = remoteField
}
existingTf, exists := tfs[tfk]
if exists {
existingTf.Locations = append(existingTf.Locations, tf.Locations...)
existingTf.frequency = existingTf.frequency + tf.frequency
} else {
tfs[tfk] = &TokenFreq{
Term: tf.Term,
frequency: tf.frequency,
Locations: make([]*TokenLocation, len(tf.Locations)),
}
copy(tfs[tfk].Locations, tf.Locations)
}
}
}
func TokenFrequency(tokens TokenStream, arrayPositions []uint64, includeTermVectors bool) TokenFrequencies {
rv := make(map[string]*TokenFreq, len(tokens))
if includeTermVectors {
tls := make([]TokenLocation, len(tokens))
tlNext := 0
for _, token := range tokens {
tls[tlNext] = TokenLocation{
ArrayPositions: arrayPositions,
Start: token.Start,
End: token.End,
Position: token.Position,
}
curr, ok := rv[string(token.Term)]
if ok {
curr.Locations = append(curr.Locations, &tls[tlNext])
curr.frequency++
} else {
rv[string(token.Term)] = &TokenFreq{
Term: token.Term,
Locations: []*TokenLocation{&tls[tlNext]},
frequency: 1,
}
}
tlNext++
}
} else {
for _, token := range tokens {
curr, exists := rv[string(token.Term)]
if exists {
curr.frequency++
} else {
rv[string(token.Term)] = &TokenFreq{
Term: token.Term,
frequency: 1,
}
}
}
}
return rv
}

+ 7
- 0
vendor/github.com/blevesearch/bleve/analysis/test_words.txt View File

@ -0,0 +1,7 @@
# full line comment
marty
steve # trailing comment
| different format of comment
dustin
siri | different style trailing comment
multiple words with different whitespace

+ 84
- 0
vendor/github.com/blevesearch/bleve/analysis/tokenizer/regexp/regexp.go View File

@ -0,0 +1,84 @@
// Copyright (c) 2014 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package regexp
import (
"fmt"
"regexp"
"strconv"
"github.com/blevesearch/bleve/analysis"
"github.com/blevesearch/bleve/registry"
)
const Name = "regexp"
var IdeographRegexp = regexp.MustCompile(`\p{Han}|\p{Hangul}|\p{Hiragana}|\p{Katakana}`)
type RegexpTokenizer struct {
r *regexp.Regexp
}
func NewRegexpTokenizer(r *regexp.Regexp) *RegexpTokenizer {
return &RegexpTokenizer{
r: r,
}
}
func (rt *RegexpTokenizer) Tokenize(input []byte) analysis.TokenStream {
matches := rt.r.FindAllIndex(input, -1)
rv := make(analysis.TokenStream, 0, len(matches))
for i, match := range matches {
matchBytes := input[match[0]:match[1]]
if match[1]-match[0] > 0 {
token := analysis.Token{
Term: matchBytes,
Start: match[0],
End: match[1],
Position: i + 1,
Type: detectTokenType(matchBytes),
}
rv = append(rv, &token)
}
}
return rv
}
func RegexpTokenizerConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.Tokenizer, error) {
rval, ok := config["regexp"].(string)
if !ok {
return nil, fmt.Errorf("must specify regexp")
}
r, err := regexp.Compile(rval)
if err != nil {
return nil, fmt.Errorf("unable to build regexp tokenizer: %v", err)
}
return NewRegexpTokenizer(r), nil
}
func init() {
registry.RegisterTokenizer(Name, RegexpTokenizerConstructor)
}
func detectTokenType(termBytes []byte) analysis.TokenType {
if IdeographRegexp.Match(termBytes) {
return analysis.Ideographic
}
_, err := strconv.ParseFloat(string(termBytes), 64)
if err == nil {
return analysis.Numeric
}
return analysis.AlphaNumeric
}

+ 76
- 0
vendor/github.com/blevesearch/bleve/analysis/tokenmap.go View File

@ -0,0 +1,76 @@
// Copyright (c) 2014 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package analysis
import (
"bufio"
"bytes"
"io"
"io/ioutil"
"strings"
)
type TokenMap map[string]bool
func NewTokenMap() TokenMap {
return make(TokenMap, 0)
}
// LoadFile reads in a list of tokens from a text file,
// one per line.
// Comments are supported using `#` or `|`
func (t TokenMap) LoadFile(filename string) error {
data, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
return t.LoadBytes(data)
}
// LoadBytes reads in a list of tokens from memory,
// one per line.
// Comments are supported using `#` or `|`
func (t TokenMap) LoadBytes(data []byte) error {
bytesReader := bytes.NewReader(data)
bufioReader := bufio.NewReader(bytesReader)
line, err := bufioReader.ReadString('\n')
for err == nil {
t.LoadLine(line)
line, err = bufioReader.ReadString('\n')
}
// if the err was EOF we still need to process the last value
if err == io.EOF {
t.LoadLine(line)
return nil
}
return err
}
func (t TokenMap) LoadLine(line string) {
// find the start of a comment, if any
startComment := strings.IndexAny(line, "#|")
if startComment >= 0 {
line = line[:startComment]
}
tokens := strings.Fields(line)
for _, token := range tokens {
t.AddToken(token)
}
}
func (t TokenMap) AddToken(token string) {
t[token] = true
}

+ 103
- 0
vendor/github.com/blevesearch/bleve/analysis/type.go View File

@ -0,0 +1,103 @@
// Copyright (c) 2014 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package analysis
import (
"fmt"
"time"
)
type CharFilter interface {
Filter([]byte) []byte
}
type TokenType int
const (
AlphaNumeric TokenType = iota
Ideographic
Numeric
DateTime
Shingle
Single
Double
Boolean
)
// Token represents one occurrence of a term at a particular location in a
// field.
type Token struct {
// Start specifies the byte offset of the beginning of the term in the
// field.
Start int `json:"start"`
// End specifies the byte offset of the end of the term in the field.
End int `json:"end"`
Term []byte `json:"term"`
// Position specifies the 1-based index of the token in the sequence of
// occurrences of its term in the field.
Position int `json:"position"`
Type TokenType `json:"type"`
KeyWord bool `json:"keyword"`
}
func (t *Token) String() string {
return fmt.Sprintf("Start: %d End: %d Position: %d Token: %s Type: %d", t.Start, t.End, t.Position, string(t.Term), t.Type)
}
type TokenStream []*Token
// A Tokenizer splits an input string into tokens, the usual behaviour being to
// map words to tokens.
type Tokenizer interface {
Tokenize([]byte) TokenStream
}
// A TokenFilter adds, transforms or removes tokens from a token stream.
type TokenFilter interface {
Filter(TokenStream) TokenStream
}
type Analyzer struct {
CharFilters []CharFilter
Tokenizer Tokenizer
TokenFilters []TokenFilter
}
func (a *Analyzer) Analyze(input []byte) TokenStream {
if a.CharFilters != nil {
for _, cf := range a.CharFilters {
input = cf.Filter(input)
}
}
tokens := a.Tokenizer.Tokenize(input)
if a.TokenFilters != nil {
for _, tf := range a.TokenFilters {
tokens = tf.Filter(tokens)
}
}
return tokens
}
var ErrInvalidDateTime = fmt.Errorf("unable to parse datetime with any of the layouts")
type DateTimeParser interface {
ParseDateTime(string) (time.Time, error)
}
type ByteArrayConverter interface {
Convert([]byte) (interface{}, error)
}

+ 92
- 0
vendor/github.com/blevesearch/bleve/analysis/util.go View File

@ -0,0 +1,92 @@
// Copyright (c) 2014 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package analysis
import (
"bytes"
"unicode/utf8"
)
func DeleteRune(in []rune, pos int) []rune {
if pos >= len(in) {
return in
}
copy(in[pos:], in[pos+1:])