server.go 1.57 KB
Newer Older
Marten Seemann's avatar
Marten Seemann committed
1
package tlsdiag
2 3 4 5 6 7 8 9

import (
	"context"
	"flag"
	"fmt"
	"net"
	"time"

10
	"github.com/libp2p/go-libp2p-core/peer"
11 12 13
	libp2ptls "github.com/libp2p/go-libp2p-tls"
)

14
func StartServer() error {
15
	port := flag.Int("p", 5533, "port")
16
	keyType := flag.String("key", "ecdsa", "rsa, ecdsa, ed25519 or secp256k1")
17 18
	flag.Parse()

19
	priv, err := generateKey(*keyType)
20 21 22
	if err != nil {
		return err
	}
23

24 25 26 27
	id, err := peer.IDFromPrivateKey(priv)
	if err != nil {
		return err
	}
28
	fmt.Printf(" Peer ID: %s\n", id.Pretty())
29 30 31 32 33 34 35 36 37 38 39
	tp, err := libp2ptls.New(priv)
	if err != nil {
		return err
	}

	ln, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))
	if err != nil {
		return err
	}
	fmt.Printf("Listening for new connections on %s\n", ln.Addr())
	fmt.Printf("Now run the following command in a separate terminal:\n")
40
	fmt.Printf("\tgo run cmd/tlsdiag.go client -p %d -id %s\n", *port, id.Pretty())
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

	for {
		conn, err := ln.Accept()
		if err != nil {
			return err
		}
		fmt.Printf("Accepted raw connection from %s\n", conn.RemoteAddr())
		go func() {
			if err := handleConn(tp, conn); err != nil {
				fmt.Printf("Error handling connection from %s: %s\n", conn.RemoteAddr(), err)
			}
		}()
	}
}

func handleConn(tp *libp2ptls.Transport, conn net.Conn) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	sconn, err := tp.SecureInbound(ctx, conn)
	if err != nil {
		return err
	}
	fmt.Printf("Authenticated client: %s\n", sconn.RemotePeer().Pretty())
	fmt.Fprintf(sconn, "Hello client!")
	fmt.Printf("Closing connection to %s\n", conn.RemoteAddr())
	return sconn.Close()
}