matrix.go 5.3 KB

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