server.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package main
  2. import (
  3. "encoding/json"
  4. "flag"
  5. "net"
  6. "os"
  7. "github.com/cloudflare/cfssl/log"
  8. "github.com/cloudflare/cfssl/transport"
  9. "github.com/cloudflare/cfssl/transport/core"
  10. "github.com/cloudflare/cfssl/transport/example/exlib"
  11. )
  12. // maclient is a mutual-authentication server, meant to demonstrate
  13. // using the client-side mutual authentication side of the transport
  14. // package.
  15. func main() {
  16. var addr, conf string
  17. flag.StringVar(&addr, "a", "127.0.0.1:9876", "`address` of server")
  18. flag.StringVar(&conf, "f", "server.json", "config `file` to use")
  19. flag.Parse()
  20. var id = new(core.Identity)
  21. data, err := os.ReadFile(conf)
  22. if err != nil {
  23. exlib.Err(1, err, "reading config file")
  24. }
  25. err = json.Unmarshal(data, id)
  26. if err != nil {
  27. exlib.Err(1, err, "parsing config file")
  28. }
  29. tr, err := transport.New(exlib.Before, id)
  30. if err != nil {
  31. exlib.Err(1, err, "creating transport")
  32. }
  33. l, err := transport.Listen(addr, tr)
  34. if err != nil {
  35. exlib.Err(1, err, "setting up listener")
  36. }
  37. var errChan = make(chan error, 0)
  38. go func(ec <-chan error) {
  39. for {
  40. err, ok := <-ec
  41. if !ok {
  42. log.Warning("error channel closed, future errors will not be reported")
  43. break
  44. }
  45. log.Errorf("auto update error: %v", err)
  46. }
  47. }(errChan)
  48. log.Info("setting up auto-update")
  49. go l.AutoUpdate(nil, errChan)
  50. log.Info("listening on ", addr)
  51. exlib.Warn(serve(l), "serving listener")
  52. }
  53. func connHandler(conn net.Conn) {
  54. defer conn.Close()
  55. for {
  56. buf, err := exlib.Unpack(conn)
  57. if err != nil {
  58. exlib.Warn(err, "unpack message")
  59. return
  60. }
  61. if len(buf) == 0 {
  62. log.Info(conn.RemoteAddr(), " sent empty record, closing connection")
  63. return
  64. }
  65. log.Infof("received %d-byte message: %s", len(buf), buf)
  66. err = exlib.Pack(conn, []byte("OK"))
  67. if err != nil {
  68. exlib.Warn(err, "pack message")
  69. return
  70. }
  71. }
  72. }
  73. func serve(l net.Listener) error {
  74. defer l.Close()
  75. for {
  76. conn, err := l.Accept()
  77. if err != nil {
  78. exlib.Warn(err, "client connection failed")
  79. continue
  80. }
  81. log.Info("connection from ", conn.RemoteAddr())
  82. go connHandler(conn)
  83. }
  84. }