2021-08-29 13:50:53 +02:00
|
|
|
package socket
|
|
|
|
|
|
|
|
import (
|
2021-08-29 17:02:31 +02:00
|
|
|
"bufio"
|
2021-08-29 13:50:53 +02:00
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"github.com/nlpodyssey/gopickle/pickle"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
commandTerminator = "<F2B_END_COMMAND>"
|
|
|
|
pingCommand = "ping"
|
2021-08-29 17:02:31 +02:00
|
|
|
socketReadBufferSize = 1024
|
2021-08-29 13:50:53 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func (s *Fail2BanSocket) sendCommand(command []string) (interface{}, error) {
|
|
|
|
err := s.write(command)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return s.read()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Fail2BanSocket) write(command []string) error {
|
|
|
|
err := s.encoder.Encode(command)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
_, err = s.socket.Write([]byte(commandTerminator))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Fail2BanSocket) read() (interface{}, error) {
|
2021-08-29 17:02:31 +02:00
|
|
|
reader := bufio.NewReader(s.socket)
|
|
|
|
|
|
|
|
data := []byte{}
|
|
|
|
for {
|
|
|
|
buf := make([]byte, socketReadBufferSize)
|
|
|
|
_, err := reader.Read(buf)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
data = append(data, buf...)
|
|
|
|
containsTerminator := bytes.Contains(data, []byte(commandTerminator))
|
|
|
|
if containsTerminator {
|
|
|
|
break
|
|
|
|
}
|
2021-08-29 13:50:53 +02:00
|
|
|
}
|
|
|
|
|
2021-08-29 17:02:31 +02:00
|
|
|
bufReader := bytes.NewReader(data)
|
2021-08-29 13:50:53 +02:00
|
|
|
unpickler := pickle.NewUnpickler(bufReader)
|
|
|
|
|
|
|
|
unpickler.FindClass = func(module, name string) (interface{}, error) {
|
|
|
|
if module == "builtins" && name == "str" {
|
|
|
|
return &Py_builtins_str{}, nil
|
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("class not found: " + module + " : " + name)
|
|
|
|
}
|
|
|
|
|
|
|
|
return unpickler.Load()
|
|
|
|
}
|