matrix.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "sort"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "time"
  11. )
  12. //ByControlPlane contains all the channels we need.
  13. type ByControlPlane struct {
  14. BadTokens chan string
  15. GoodTokens chan string
  16. StatsTokens chan string
  17. }
  18. //ControPlane is the variabile
  19. var ControPlane ByControlPlane
  20. //ByClassifier is the structure containing our Pseudo-Bayes classifier.
  21. type ByClassifier struct {
  22. GOOD sync.Map
  23. BAD sync.Map
  24. MEH sync.Map
  25. STATS sync.Map
  26. }
  27. //AddStats adds the statistics after proper blocking.
  28. func (c *ByClassifier) AddStats(action string) {
  29. var one int64 = 1
  30. if v, ok := c.STATS.Load(action); ok {
  31. c.STATS.Store(action, v.(int64)+1)
  32. } else {
  33. c.STATS.Store(action, one)
  34. }
  35. }
  36. //IsBAD inserts a bad key in the right place.
  37. func (c *ByClassifier) IsBAD(key string) {
  38. if _, ok := c.MEH.Load(key); ok {
  39. c.MEH.Store(key, time.Now().UnixNano())
  40. log.Println("Updated BAD into MEH: ", key)
  41. return
  42. }
  43. if _, ok := c.GOOD.Load(key); ok {
  44. c.MEH.Store(key, time.Now().UnixNano())
  45. c.GOOD.Delete(key)
  46. log.Println("Moved to MEH from GOOD: ", key)
  47. return
  48. }
  49. c.BAD.Store(key, time.Now().UnixNano())
  50. log.Println("Stored into BAD: ", key)
  51. }
  52. //IsGOOD inserts the key in the right place.
  53. func (c *ByClassifier) IsGOOD(key string) {
  54. if _, ok := c.MEH.Load(key); ok {
  55. c.MEH.Store(key, time.Now().UnixNano())
  56. log.Println("Updated GOOD into MEH: ", key)
  57. return
  58. }
  59. if _, ok := c.BAD.Load(key); ok {
  60. c.MEH.Store(key, time.Now().UnixNano())
  61. c.BAD.Delete(key)
  62. log.Println("Moved to MEH from BAD: ", key)
  63. return
  64. }
  65. c.GOOD.Store(key, time.Now().UnixNano())
  66. log.Println("Stored into GOOD: ", key)
  67. }
  68. //Posterior calculates the posterior probabilities in pseudo-bayes.
  69. func (c *ByClassifier) Posterior(hdr string) map[string]float64 {
  70. headers := strings.Fields(sanitizeHeaders(hdr))
  71. var result = make(map[string]float64)
  72. result["BAD"] = 0
  73. result["GOOD"] = 0
  74. var tmpResGood, tmpResBad, tmpTotal float64
  75. for _, token := range headers {
  76. if _, ok := c.BAD.Load(token); ok {
  77. tmpResBad++
  78. tmpTotal++
  79. }
  80. if _, ok := c.GOOD.Load(token); ok {
  81. tmpResGood++
  82. tmpTotal++
  83. }
  84. }
  85. if tmpTotal == 0 {
  86. tmpTotal = 1
  87. }
  88. log.Printf("Bad Tokens: %f, Good Tokens %f , Total %f\n", tmpResBad, tmpResGood, tmpTotal)
  89. result["BAD"] = tmpResBad / tmpTotal
  90. result["GOOD"] = tmpResGood / tmpTotal
  91. return result
  92. }
  93. //Janitor keeps the maps under a certain size, keeping the biggest values.
  94. func (c *ByClassifier) Janitor(size int) {
  95. log.Println("Janitor Running")
  96. sortMap(&c.BAD, size)
  97. sortMap(&c.GOOD, size)
  98. sortMap(&c.MEH, size)
  99. log.Println("Janitor Finished.")
  100. }
  101. //CleanThread is the Janitor thread
  102. func (c *ByClassifier) CleanThread() {
  103. for {
  104. MaxSize, err := strconv.Atoi(fmt.Sprintf("%d", Maturity))
  105. if err != nil {
  106. MaxSize = 1000
  107. log.Println("Maxsize converted to: ", MaxSize)
  108. }
  109. log.Println("Janitor Maxsize is now:", MaxSize)
  110. time.Sleep(10 * time.Second)
  111. c.Janitor(MaxSize)
  112. }
  113. }
  114. func (c *ByClassifier) enroll() {
  115. ControPlane.BadTokens = make(chan string, 2048)
  116. ControPlane.GoodTokens = make(chan string, 2048)
  117. ControPlane.StatsTokens = make(chan string, 2048)
  118. c.IsBAD("/Penis/bad")
  119. c.IsGOOD("/Gun/good")
  120. c.MEH.Store("Dildo", time.Now().UnixNano())
  121. go c.readBadTokens()
  122. go c.readGoodTokens()
  123. go c.readStatsTokens()
  124. log.Println("Classifier populated...")
  125. go c.CleanThread()
  126. go c.CleanMEH()
  127. log.Println("Janitor Started")
  128. }
  129. func sortMap(unsorted *sync.Map, size int) {
  130. type Myt struct {
  131. Name string
  132. Num int64
  133. }
  134. var tempCont []Myt
  135. var tc Myt
  136. unsorted.Range(func(key interface{}, value interface{}) bool {
  137. tc.Name = key.(string)
  138. tc.Num = value.(int64)
  139. tempCont = append(tempCont, tc)
  140. return true
  141. })
  142. sort.Slice(tempCont, func(i, j int) bool { return tempCont[i].Num > tempCont[j].Num })
  143. if size > 0 && len(tempCont) > size {
  144. tempCont = tempCont[:size]
  145. }
  146. unsorted.Range(func(key interface{}, value interface{}) bool {
  147. unsorted.Delete(key)
  148. return true
  149. })
  150. for _, val := range tempCont {
  151. unsorted.Store(val.Name, val.Num)
  152. }
  153. }
  154. func (c *ByClassifier) readBadTokens() {
  155. log.Println("Start reading BAD tokens")
  156. for token := range ControPlane.BadTokens {
  157. log.Println("Received BAD Token: ", token)
  158. c.IsBAD(token)
  159. }
  160. }
  161. func (c *ByClassifier) readGoodTokens() {
  162. log.Println("Start reading GOOD tokens")
  163. for token := range ControPlane.GoodTokens {
  164. log.Println("Received GOOD Token: ", token)
  165. c.IsGOOD(token)
  166. }
  167. }
  168. func (c *ByClassifier) readStatsTokens() {
  169. log.Println("Start reading STATS tokens")
  170. for token := range ControPlane.StatsTokens {
  171. c.AddStats(token)
  172. }
  173. }
  174. //CleanMEH cleans periodically the spurious tokens.
  175. func (c *ByClassifier) CleanMEH() {
  176. var err error
  177. ProxyFlow.refreshtime, err = time.ParseDuration(os.Getenv("REFRESHTIME"))
  178. if err != nil {
  179. ProxyFlow.refreshtime = time.Duration(48 * time.Hour)
  180. }
  181. log.Println("Clean MEH Thread running each: ", ProxyFlow.refreshtime)
  182. for a := range time.Tick(ProxyFlow.refreshtime) {
  183. c.MEH.Range(func(key interface{}, value interface{}) bool {
  184. c.MEH.Delete(key)
  185. return true
  186. })
  187. log.Println("MEH Cleaned at:", a)
  188. }
  189. }