matrix.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "sort"
  8. "strconv"
  9. "sync"
  10. "time"
  11. "github.com/lytics/multibayes"
  12. )
  13. //ByControlPlane contains all the channels we need.
  14. type ByControlPlane struct {
  15. BadTokens chan string
  16. GoodTokens chan string
  17. StatsTokens chan string
  18. }
  19. //ControPlane is the variabile
  20. var ControPlane ByControlPlane
  21. //ByClassifier is the structure containing our Pseudo-Bayes classifier.
  22. type ByClassifier struct {
  23. GOOD sync.Map
  24. BAD sync.Map
  25. MEH sync.Map
  26. STATS sync.Map
  27. bayez *multibayes.Classifier
  28. }
  29. //AddStats adds the statistics after proper blocking.
  30. func (c *ByClassifier) AddStats(action string) {
  31. var one int64 = 1
  32. if v, ok := c.STATS.Load(action); ok {
  33. c.STATS.Store(action, v.(int64)+1)
  34. } else {
  35. c.STATS.Store(action, one)
  36. }
  37. }
  38. //IsBAD inserts a bad key in the right place.
  39. func (c *ByClassifier) IsBAD(key string) {
  40. if _, ok := c.MEH.Load(key); ok {
  41. c.MEH.Store(key, time.Now().UnixNano())
  42. log.Println("Updated BAD into MEH: ", key)
  43. return
  44. }
  45. if _, ok := c.GOOD.Load(key); ok {
  46. c.MEH.Store(key, time.Now().UnixNano())
  47. c.GOOD.Delete(key)
  48. log.Println("Moved to MEH from GOOD: ", key)
  49. return
  50. }
  51. c.BAD.Store(key, time.Now().UnixNano())
  52. log.Println("Stored into BAD: ", key)
  53. }
  54. //IsGOOD inserts the key in the right place.
  55. func (c *ByClassifier) IsGOOD(key string) {
  56. if _, ok := c.MEH.Load(key); ok {
  57. c.MEH.Store(key, time.Now().UnixNano())
  58. log.Println("Updated GOOD into MEH: ", key)
  59. return
  60. }
  61. if _, ok := c.BAD.Load(key); ok {
  62. c.MEH.Store(key, time.Now().UnixNano())
  63. c.BAD.Delete(key)
  64. log.Println("Moved to MEH from BAD: ", key)
  65. return
  66. }
  67. c.GOOD.Store(key, time.Now().UnixNano())
  68. log.Println("Stored into GOOD: ", key)
  69. }
  70. //Posterior calculates the posterior probabilities in pseudo-bayes.
  71. func (c *ByClassifier) Posterior(hdr string) (ff map[string]float64) {
  72. defer func() {
  73. if a := recover(); a != nil {
  74. fmt.Println("OPS!: Recovering from:", a)
  75. ff = make(map[string]float64)
  76. ff["BAD"] = 0.5
  77. ff["GOOD"] = 0.5
  78. }
  79. }()
  80. return c.bayez.Posterior(hdr)
  81. }
  82. //Janitor keeps the maps under a certain size, keeping the biggest values.
  83. func (c *ByClassifier) Janitor(size int) {
  84. log.Println("Janitor Running")
  85. sortMap(&c.BAD, size)
  86. sortMap(&c.GOOD, size)
  87. sortMap(&c.MEH, size)
  88. log.Println("Janitor Finished.")
  89. }
  90. //RefreshBayes refresh the bayesian using values we stored
  91. func (c *ByClassifier) RefreshBayes() {
  92. log.Println("RefreshBayes Thread started")
  93. ticker := time.NewTicker(5 * time.Minute)
  94. for ; true; <-ticker.C {
  95. c.bayez = multibayes.NewClassifier()
  96. c.bayez.MinClassSize = 0
  97. c.BAD.Range(func(key interface{}, value interface{}) bool {
  98. c.bayez.Add(key.(string), []string{"BAD"})
  99. return true
  100. })
  101. c.GOOD.Range(func(key interface{}, value interface{}) bool {
  102. c.bayez.Add(key.(string), []string{"GOOD"})
  103. return true
  104. })
  105. c.MEH.Range(func(key interface{}, value interface{}) bool {
  106. c.bayez.Add(key.(string), []string{"GOOD", "BAD"})
  107. return true
  108. })
  109. }
  110. }
  111. //CleanThread is the Janitor thread
  112. func (c *ByClassifier) CleanThread() {
  113. for {
  114. MaxSize, err := strconv.Atoi(fmt.Sprintf("%d", Maturity))
  115. if err != nil {
  116. MaxSize = 1000
  117. log.Println("Maxsize converted to: ", MaxSize)
  118. }
  119. log.Println("Janitor Maxsize is now:", MaxSize)
  120. time.Sleep(10 * time.Second)
  121. c.Janitor(MaxSize)
  122. }
  123. }
  124. func (c *ByClassifier) enroll() {
  125. ControPlane.BadTokens = make(chan string, 2048)
  126. ControPlane.GoodTokens = make(chan string, 2048)
  127. ControPlane.StatsTokens = make(chan string, 2048)
  128. c.bayez = multibayes.NewClassifier()
  129. c.bayez.MinClassSize = 0
  130. c.readInitList("blacklist.txt", "BAD")
  131. c.readInitList("whitelist.txt", "GOOD")
  132. c.MEH.Store("Dildo", time.Now().UnixNano())
  133. go c.readBadTokens()
  134. go c.readGoodTokens()
  135. go c.readStatsTokens()
  136. log.Println("Classifier populated...")
  137. go c.CleanThread()
  138. go c.RefreshBayes()
  139. log.Println("Janitor Started")
  140. }
  141. func sortMap(unsorted *sync.Map, size int) {
  142. type Myt struct {
  143. Name string
  144. Num int64
  145. }
  146. var tempCont []Myt
  147. var tc Myt
  148. unsorted.Range(func(key interface{}, value interface{}) bool {
  149. tc.Name = key.(string)
  150. tc.Num = value.(int64)
  151. tempCont = append(tempCont, tc)
  152. return true
  153. })
  154. sort.Slice(tempCont, func(i, j int) bool { return tempCont[i].Num > tempCont[j].Num })
  155. if size > 0 && len(tempCont) > size {
  156. tempCont = tempCont[:size]
  157. }
  158. unsorted.Range(func(key interface{}, value interface{}) bool {
  159. unsorted.Delete(key)
  160. return true
  161. })
  162. for _, val := range tempCont {
  163. unsorted.Store(val.Name, val.Num)
  164. }
  165. }
  166. func (c *ByClassifier) readBadTokens() {
  167. log.Println("Start reading BAD tokens")
  168. for token := range ControPlane.BadTokens {
  169. log.Println("Received BAD Token: ", token)
  170. c.IsBAD(token)
  171. }
  172. }
  173. func (c *ByClassifier) readGoodTokens() {
  174. log.Println("Start reading GOOD tokens")
  175. for token := range ControPlane.GoodTokens {
  176. log.Println("Received GOOD Token: ", token)
  177. c.IsGOOD(token)
  178. }
  179. }
  180. func (c *ByClassifier) readStatsTokens() {
  181. log.Println("Start reading STATS tokens")
  182. for token := range ControPlane.StatsTokens {
  183. c.AddStats(token)
  184. }
  185. }
  186. func (c *ByClassifier) readInitList(filePath, class string) {
  187. inFile, err := os.Open(filePath)
  188. if err != nil {
  189. log.Println(err.Error() + `: ` + filePath)
  190. return
  191. }
  192. defer inFile.Close()
  193. scanner := bufio.NewScanner(inFile)
  194. for scanner.Scan() {
  195. if len(scanner.Text()) > 3 {
  196. switch class {
  197. case "BAD":
  198. log.Println("Loading into Blacklist: ", scanner.Text()) // the line
  199. c.IsBAD(scanner.Text())
  200. case "GOOD":
  201. log.Println("Loading into Whitelist: ", scanner.Text()) // the line
  202. c.IsGOOD(scanner.Text())
  203. }
  204. }
  205. }
  206. }