fte.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package fte
  2. import (
  3. "crypto/aes"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. )
  8. const (
  9. COVERTEXT_HEADER_LEN_CIPHERTTEXT = 16
  10. )
  11. const (
  12. IV_LENGTH = 7
  13. MSG_COUNTER_LENGTH = 8
  14. CTXT_EXPANSION = 1 + IV_LENGTH + MSG_COUNTER_LENGTH + aes.BlockSize
  15. )
  16. var Verbose bool
  17. // Cache represents a cache of Ciphers & DFAs.
  18. type Cache struct {
  19. ciphers map[cacheKey]*Cipher
  20. dfas map[cacheKey]*DFA
  21. }
  22. // NewCache returns a new instance of Cache.
  23. func NewCache() *Cache {
  24. return &Cache{
  25. ciphers: make(map[cacheKey]*Cipher),
  26. dfas: make(map[cacheKey]*DFA),
  27. }
  28. }
  29. // Close close and removes all ciphers & dfas.
  30. func (c *Cache) Close() (err error) {
  31. for _, cipher := range c.ciphers {
  32. if e := cipher.Close(); e != nil && err == nil {
  33. err = e
  34. }
  35. }
  36. c.ciphers = nil
  37. for _, dfa := range c.dfas {
  38. if e := dfa.Close(); e != nil && err == nil {
  39. err = e
  40. }
  41. }
  42. c.dfas = nil
  43. return err
  44. }
  45. // Cipher returns a instance of Cipher associated with regex & n.
  46. // Creates a new cipher if one doesn't already exist.
  47. func (c *Cache) Cipher(regex string, n int) (_ *Cipher, err error) {
  48. cipher := c.ciphers[cacheKey{regex, n}]
  49. if cipher == nil {
  50. if cipher, err = NewCipher(regex, n); err != nil {
  51. return nil, err
  52. }
  53. c.ciphers[cacheKey{regex, n}] = cipher
  54. }
  55. return cipher, nil
  56. }
  57. // DFA returns a instance of DFA associated with regex & n.
  58. // Creates a new DFA if one doesn't already exist.
  59. func (c *Cache) DFA(regex string, n int) (_ *DFA, err error) {
  60. dfa := c.dfas[cacheKey{regex, n}]
  61. if dfa == nil {
  62. if dfa, err = NewDFA(regex, n); err != nil {
  63. return nil, err
  64. }
  65. c.dfas[cacheKey{regex, n}] = dfa
  66. }
  67. return dfa, nil
  68. }
  69. type cacheKey struct {
  70. regex string
  71. n int
  72. }
  73. func stderr() io.Writer {
  74. if Verbose {
  75. return os.Stderr
  76. }
  77. return ioutil.Discard
  78. }