From 975b3a8eeef4e511baabe7e30b15ab28f552d160 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96zg=C3=BCr=20Kesim?= Date: Mon, 29 Jul 2013 12:08:57 +0200 Subject: [PATCH] initial tlsserver working --- tlsserver.go | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 tlsserver.go diff --git a/tlsserver.go b/tlsserver.go new file mode 100644 index 0000000..b414848 --- /dev/null +++ b/tlsserver.go @@ -0,0 +1,79 @@ +package main + +import ( + "crypto/tls" + "log" + "net" + "flag" + "fmt" + "os" + "os/exec" +) + +var ( + cfile = flag.String("cert", "cert.pem", "Certificate file in PEM format") + kfile = flag.String("key", "key.pem", "Key file in PEM format") + port = flag.Int("port", 1234, "Port to bind to") + args []string + nargs int +) + +func main() { + + flag.Parse() + args = flag.Args() + nargs = flag.NArg() + if nargs < 1 { + fmt.Println("Usage: tlsserver [options] cmd [flags for cmd]") + fmt.Println("options:") + flag.PrintDefaults() + os.Exit(1) + } + + // setup certs etc. for TLS-socket + tconf := new(tls.Config) + cert, err := tls.LoadX509KeyPair(*cfile, *kfile) + if err != nil { + fmt.Println("error with certs:", err) + os.Exit(2) + } + + tconf.Certificates = append(tconf.Certificates, cert) + tconf.BuildNameToCertificate() + + // start listening + sport := fmt.Sprintf(":%d", *port) + sock, err := tls.Listen("tcp", sport , tconf) + if err != nil { + fmt.Println("error with tcp-socket:", err) + os.Exit(3) + } + defer sock.Close() + + // accept-loop + for { + conn, err := sock.Accept() + if err != nil { + log.Println("error during Accept()", err) + continue + } + log.Println("Got connection:", conn.RemoteAddr()) + go handleConnection(conn) + } +} + +func handleConnection(conn net.Conn) { + defer conn.Close() + + // setup cmd + cmd := exec.Command(args[0]) + cmd.Args = args + cmd.Stdin = conn + cmd.Stdout = conn + cmd.Stderr = os.Stderr + err := cmd.Run() + if err != nil { + log.Println(err) + } + log.Println("Done with connection", conn.RemoteAddr()) +}