matrix.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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) map[string]float64 {
  72. return c.bayez.Posterior(hdr)
  73. }
  74. //Janitor keeps the maps under a certain size, keeping the biggest values.
  75. func (c *ByClassifier) Janitor(size int) {
  76. log.Println("Janitor Running")
  77. sortMap(&c.BAD, size)
  78. sortMap(&c.GOOD, size)
  79. sortMap(&c.MEH, size)
  80. c.bayez = nil // mark it for garbage collection.
  81. c.bayez = multibayes.NewClassifier()
  82. c.bayez.MinClassSize = 0
  83. c.BAD.Range(func(key interface{}, value interface{}) bool {
  84. c.bayez.Add(key.(string), []string{"BAD"})
  85. return true
  86. })
  87. c.GOOD.Range(func(key interface{}, value interface{}) bool {
  88. c.bayez.Add(key.(string), []string{"GOOD"})
  89. return true
  90. })
  91. c.MEH.Range(func(key interface{}, value interface{}) bool {
  92. c.bayez.Add(key.(string), []string{"GOOD", "BAD"})
  93. return true
  94. })
  95. log.Println("Janitor Finished.")
  96. }
  97. //CleanThread is the Janitor thread
  98. func (c *ByClassifier) CleanThread() {
  99. for {
  100. MaxSize, err := strconv.Atoi(fmt.Sprintf("%d", Maturity))
  101. if err != nil {
  102. MaxSize = 1000
  103. log.Println("Maxsize converted to: ", MaxSize)
  104. }
  105. log.Println("Janitor Maxsize is now:", MaxSize)
  106. time.Sleep(10 * time.Second)
  107. c.Janitor(MaxSize)
  108. }
  109. }
  110. func (c *ByClassifier) enroll() {
  111. ControPlane.BadTokens = make(chan string, 2048)
  112. ControPlane.GoodTokens = make(chan string, 2048)
  113. ControPlane.StatsTokens = make(chan string, 2048)
  114. c.bayez = multibayes.NewClassifier()
  115. c.bayez.MinClassSize = 0
  116. c.readInitList("blacklist.txt", "BAD")
  117. c.readInitList("whitelist.txt", "GOOD")
  118. c.MEH.Store("Dildo", time.Now().UnixNano())
  119. go c.readBadTokens()
  120. go c.readGoodTokens()
  121. go c.readStatsTokens()
  122. log.Println("Classifier populated...")
  123. go c.CleanThread()
  124. log.Println("Janitor Started")
  125. }
  126. func sortMap(unsorted *sync.Map, size int) {
  127. type Myt struct {
  128. Name string
  129. Num int64
  130. }
  131. var tempCont []Myt
  132. var tc Myt
  133. unsorted.Range(func(key interface{}, value interface{}) bool {
  134. tc.Name = key.(string)
  135. tc.Num = value.(int64)
  136. tempCont = append(tempCont, tc)
  137. return true
  138. })
  139. sort.Slice(tempCont, func(i, j int) bool { return tempCont[i].Num > tempCont[j].Num })
  140. if size > 0 && len(tempCont) > size {
  141. tempCont = tempCont[:size]
  142. }
  143. unsorted.Range(func(key interface{}, value interface{}) bool {
  144. unsorted.Delete(key)
  145. return true
  146. })
  147. for _, val := range tempCont {
  148. unsorted.Store(val.Name, val.Num)
  149. }
  150. }
  151. func (c *ByClassifier) readBadTokens() {
  152. log.Println("Start reading BAD tokens")
  153. for token := range ControPlane.BadTokens {
  154. log.Println("Received BAD Token: ", token)
  155. c.IsBAD(token)
  156. }
  157. }
  158. func (c *ByClassifier) readGoodTokens() {
  159. log.Println("Start reading GOOD tokens")
  160. for token := range ControPlane.GoodTokens {
  161. log.Println("Received GOOD Token: ", token)
  162. c.IsGOOD(token)
  163. }
  164. }
  165. func (c *ByClassifier) readStatsTokens() {
  166. log.Println("Start reading STATS tokens")
  167. for token := range ControPlane.StatsTokens {
  168. c.AddStats(token)
  169. }
  170. }
  171. func (c *ByClassifier) readInitList(filePath, class string) {
  172. inFile, err := os.Open(filePath)
  173. if err != nil {
  174. log.Println(err.Error() + `: ` + filePath)
  175. return
  176. }
  177. defer inFile.Close()
  178. scanner := bufio.NewScanner(inFile)
  179. for scanner.Scan() {
  180. if len(scanner.Text()) > 3 {
  181. switch class {
  182. case "BAD":
  183. log.Println("Loading into Blacklist: ", scanner.Text()) // the line
  184. c.IsBAD(scanner.Text())
  185. case "GOOD":
  186. log.Println("Loading into Whitelist: ", scanner.Text()) // the line
  187. c.IsGOOD(scanner.Text())
  188. }
  189. }
  190. }
  191. }