Esempio n. 1
0
// newServer returns a new instance of the server struct.
func newServer(listenAddrs []string) (*server, error) {
	login := cfg.Username + ":" + cfg.Password
	auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
	s := server{
		authsha: sha256.Sum256([]byte(auth)),
	}

	// Check for existence of cert file and key file
	if !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {
		// if both files do not exist, we generate them.
		err := genCertPair(cfg.RPCCert, cfg.RPCKey)
		if err != nil {
			return nil, err
		}
	}
	keypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)
	if err != nil {
		return nil, err
	}

	tlsConfig := tls.Config{
		Certificates: []tls.Certificate{keypair},
	}

	ipv4ListenAddrs, ipv6ListenAddrs, err := parseListeners(listenAddrs)
	listeners := make([]net.Listener, 0,
		len(ipv6ListenAddrs)+len(ipv4ListenAddrs))
	for _, addr := range ipv4ListenAddrs {
		listener, err := tls.Listen("tcp4", addr, &tlsConfig)
		if err != nil {
			log.Warnf("RPCS: Can't listen on %s: %v", addr,
				err)
			continue
		}
		listeners = append(listeners, listener)
	}

	for _, addr := range ipv6ListenAddrs {
		listener, err := tls.Listen("tcp6", addr, &tlsConfig)
		if err != nil {
			log.Warnf("RPCS: Can't listen on %s: %v", addr,
				err)
			continue
		}
		listeners = append(listeners, listener)
	}
	if len(listeners) == 0 {
		return nil, errors.New("no valid listen address")
	}

	s.listeners = listeners

	return &s, nil
}
Esempio n. 2
0
func generateListener(l net.Listener) (net.Listener, error) {
	targetPort := fmt.Sprintf("%s:%d", config.ListenAddress, config.ListenPort)

	if config.HttpServerOptions.UseSSL {
		log.WithFields(logrus.Fields{
			"prefix": "main",
		}).Info("--> Using SSL (https)")
		certs := make([]tls.Certificate, len(config.HttpServerOptions.Certificates))
		certNameMap := make(map[string]*tls.Certificate)
		for i, certData := range config.HttpServerOptions.Certificates {
			cert, err := tls.LoadX509KeyPair(certData.CertFile, certData.KeyFile)
			if err != nil {
				log.WithFields(logrus.Fields{
					"prefix": "main",
				}).Fatalf("Server error: loadkeys: %s", err)
			}
			certs[i] = cert
			certNameMap[certData.Name] = &certs[i]
		}

		config := tls.Config{
			Certificates:      certs,
			NameToCertificate: certNameMap,
			ServerName:        config.HttpServerOptions.ServerName,
			MinVersion:        config.HttpServerOptions.MinVersion,
		}
		return tls.Listen("tcp", targetPort, &config)

	} else if config.HttpServerOptions.UseLE_SSL {

		log.WithFields(logrus.Fields{
			"prefix": "main",
		}).Info("--> Using SSL LE (https)")

		GetLEState(&LE_MANAGER)

		config := tls.Config{
			GetCertificate: LE_MANAGER.GetCertificate,
		}
		return tls.Listen("tcp", targetPort, &config)

	} else {
		log.WithFields(logrus.Fields{
			"prefix": "main",
		}).Info("--> Standard listener (http)")
		return net.Listen("tcp", targetPort)
	}
}
func NewTLSListener(contextName string, address string, tlsListenerConfig config.TLSListenerConfig, envelopeChan chan *events.Envelope, logger *gosteno.Logger) (Listener, error) {
	tlsConfig, err := NewTLSConfig(tlsListenerConfig.CertFile, tlsListenerConfig.KeyFile, tlsListenerConfig.CAFile)
	if err != nil {
		return nil, err
	}

	listener, err := tls.Listen("tcp", address, tlsConfig)
	if err != nil {
		return nil, err
	}

	return &TLSListener{
		listener:       listener,
		envelopeChan:   envelopeChan,
		logger:         logger,
		connections:    make(map[net.Conn]struct{}),
		unmarshaller:   dropsonde_unmarshaller.NewDropsondeUnmarshaller(logger),
		stopped:        make(chan struct{}),
		listenerClosed: make(chan struct{}),

		receivedMessageCountMetricName: contextName + ".receivedMessageCount",
		receivedByteCountMetricName:    contextName + ".receivedByteCount",
		receiveErrorCountMetricName:    contextName + ".receiveErrorCount",
	}, nil
}
Esempio n. 4
0
func serveHTTP() {
	parsedAddr := fmt.Sprintf("%s:%d", host, port)
	if development {
		log.Println("Listening for WebSocket connections without TLS on " + parsedAddr)
		log.Fatal(http.ListenAndServe(parsedAddr, nil))
		return
	}
	// Requires cert.pem and cert.key to be present. See cert_setup.sh
	log.Println("Listening for WebSocket connections with TLS on " + parsedAddr)
	certificate, err := tls.X509KeyPair(
		[]byte(os.Getenv("WS_CERT")),
		[]byte(os.Getenv("WS_KEY")),
	)
	if err != nil {
		log.Fatal(err)
	}
	listener, err := tls.Listen(
		"tcp",
		parsedAddr,
		&tls.Config{Certificates: []tls.Certificate{certificate}},
	)
	if err != nil {
		log.Fatal(err)
	}
	log.Fatal(http.Serve(listener, nil))
}
Esempio n. 5
0
File: web.go Progetto: 2722/lantern
func startHttp() {
	http.HandleFunc("/register", register)
	http.HandleFunc("/unregister", unregister)
	laddr := fmt.Sprintf(":%d", *port)

	tlsConfig := tlsdefaults.Server()
	_, _, err := keyman.StoredPKAndCert(PKFile, CertFile, "Lantern", "localhost")
	if err != nil {
		log.Fatalf("Unable to initialize private key and certificate: %v", err)
	}
	cert, err := tls.LoadX509KeyPair(CertFile, PKFile)
	if err != nil {
		log.Fatalf("Unable to load certificate and key from %s and %s: %s", CertFile, PKFile, err)
	}
	tlsConfig.Certificates = []tls.Certificate{cert}

	log.Debugf("About to listen at %v", laddr)
	l, err := tls.Listen("tcp", laddr, tlsConfig)
	if err != nil {
		log.Fatalf("Unable to listen for tls connections at %s: %s", laddr, err)
	}

	log.Debug("About to serve")
	err = http.Serve(l, nil)
	if err != nil {
		log.Fatalf("Unable to serve: %s", err)
	}
}
Esempio n. 6
0
func SetupTCP(useTls bool, address string) {
	println("Setting Up TCP at:", address)
	const connectedAndWaitingMax = 0
	conChan := make(chan net.Conn, connectedAndWaitingMax)
	halt := make(chan int)

	var listener net.Listener
	var err os.Error
	if useTls {
		certs := make([]tls.Certificate, 1)
		c0, errx := tls.LoadX509KeyPair("cert/cert.pem", "cert/key.pem")
		certs[0] = c0
		fmt.Println(errx)
		config := tls.Config{Certificates: certs, ServerName: "TestServer"}
		listener, err = tls.Listen("tcp", ":6666", &config)
		println("TLS")
	} else {
		listener, err = net.Listen("tcp", ":6666")
		println("TCP")
	}

	if err != nil {
		println(err)
	}

	go getConnections(listener, conChan, halt)

	conChan2 := make(chan *LoggedIn, connectedAndWaitingMax)

	go welcomTestLoop(conChan, conChan2)
	go updateLoop(conChan2)

	println("TCP Setup")

}
Esempio n. 7
0
func (s *Server) run(addrString string) {
	restLogger.Info("Starting REST API on ", addrString)
	if s.snapTLS != nil {
		cer, err := tls.LoadX509KeyPair(s.snapTLS.cert, s.snapTLS.key)
		if err != nil {
			s.err <- err
			return
		}
		config := &tls.Config{Certificates: []tls.Certificate{cer}}
		ln, err := tls.Listen("tcp", addrString, config)
		if err != nil {
			s.err <- err
		}
		s.serverListener = ln
		s.wg.Add(1)
		go s.serveTLS(ln)
	} else {
		ln, err := net.Listen("tcp", addrString)
		if err != nil {
			s.err <- err
		}
		s.serverListener = ln
		s.addr = ln.Addr()
		s.wg.Add(1)
		go s.serve(ln)
	}
}
Esempio n. 8
0
func main() {
	cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
	if err != nil {
		log.Fatalf("server : loadkeys :%s", err)
	}
	config := tls.Config{Certificates: []tls.Certificate{cert}}
	config.Time = time.Now
	config.Rand = rand.Reader

	service := "127.0.0.1:10000"
	listener, err := tls.Listen("tcp", service, &config)
	if err != nil {
		log.Fatalf("server : listen: %s", err)
	}
	log.Print("server: listening")
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Panicf("server:accept :%s", err)
			break
		}
		log.Printf("server : accepted from %s", conn.RemoteAddr())
		go handleClient(conn)
	}
}
Esempio n. 9
0
func (s *server) Start() error {
	var l net.Listener
	var err error

	if s.opts.EnableTLS && s.opts.TLSConfig != nil {
		l, err = tls.Listen("tcp", s.address, s.opts.TLSConfig)
	} else {
		l, err = net.Listen("tcp", s.address)
	}
	if err != nil {
		return err
	}

	log.Infof("Listening on %s", l.Addr().String())

	s.mtx.Lock()
	s.address = l.Addr().String()
	s.mtx.Unlock()

	go http.Serve(l, s.mux)

	go func() {
		ch := <-s.exit
		ch <- l.Close()
	}()

	return nil
}
// startServingTLS creates and registers a secure listener and begins serving traffic.
func (s *TestHttpService) startServingTLS(addr string, cert []byte, key []byte, caCert []byte, handler *http.ServeMux) error {
	tlsCert, err := tls.X509KeyPair(append(cert, caCert...), key)

	if err != nil {
		return err
	}

	cfg := &tls.Config{
		Certificates: []tls.Certificate{tlsCert},
	}

	listener, err := tls.Listen("tcp", addr, cfg)

	if err != nil {
		return err
	}

	s.listeners = append(s.listeners, listener)
	fmt.Printf("Started, serving TLS at %s\n", listener.Addr().String())

	go func() {
		err := http.Serve(listener, handler)

		if err != nil {
			fmt.Printf("Server message: %v", err)
		}
	}()

	return nil
}
Esempio n. 11
0
/*
NewServer returns a server that listens on a TCP socket protected by
TLS, and automatically starts that server.
*/
func NewServer(address string, handler protocol.ConnectionHandlerFunc) (retServer *server, err error) {
	cert, err := Asset("self-signed.cert")
	if err != nil {
		return nil, err
	}

	key, err := Asset("self-signed.key")
	if err != nil {
		return nil, err
	}

	serverCert, err := tls.X509KeyPair(cert, key)
	if err != nil {
		return nil, err
	}

	serverTLSConf := &tls.Config{
		Certificates: []tls.Certificate{serverCert},
	}

	socket, err := tls.Listen("tcp", address, serverTLSConf)
	if err != nil {
		return
	}

	retServer = &server{
		s:       socket,
		handler: handler,
	}

	go retServer.listen()
	return
}
func listenWithCert(hostname string, address string) {

	listening.Add(1)
	go func() {
		log.Println("DEBUG - start mock server ..")
		// Establish a dummy TLS server
		var serverConfig tls.Config
		kp := makeCert(hostname)

		serverConfig.Certificates = []tls.Certificate{kp}

		listener, err := tls.Listen("tcp", address, &serverConfig)
		if err != nil {
			panic(err)
		}
		// Listen and handshake for a single connection
		defer listener.Close()
		listening.Done()

		conn, err := listener.Accept()
		if err != nil {
			panic(err)
		}
		defer conn.Close()
		tlsconn, ok := conn.(*tls.Conn)
		if !ok {
			panic("conn should of *tls.Conn")
		}
		if err := tlsconn.Handshake(); err != nil {
			return
		}
	}()
	listening.Wait()
}
Esempio n. 13
0
func Server() {
	host := config.Interface + ":" + config.Port
	cert, err := tls.LoadX509KeyPair("./certs/localhost1437319773023.pem", "./certs/localhost1437319773023.key")
	if err != nil {
		panic(err)
	}
	config := tls.Config{Certificates: []tls.Certificate{cert}, NextProtos: []string{"h2", "h2-14"}}
	listener, err := tls.Listen("tcp", host, &config)
	fmt.Println("Listening on https://" + host)
	fmt.Println("setInterval(function() { $.get('https://" + host + "') }, 750)")

	if err != nil {
		panic(err)
	}

	for {
		conn, err := listener.Accept()

		if err != nil {
			panic(err)
		}
		proto := conn.(*tls.Conn).ConnectionState().NegotiatedProtocol
		log.Println("Negotiated proto", proto)

		if err != nil {
			log.Printf("server: accept: %s", err)
			break
		}
		log.Printf("server: accepted from %s", conn.RemoteAddr())
		replay.TruncateFile()
		FuzzConnection(conn)
	}
}
Esempio n. 14
0
// Start network server
func (s *Server) Listen() error {
	tlsConfig, err := crypto.GetServerTlsConfig()
	if err != nil {
		return err
	}

	var listener net.Listener
	if tlsConfig != nil {
		listener, err = tls.Listen("tcp", s.address, tlsConfig)
	} else {
		listener, err = net.Listen("tcp", s.address)
		log.Println("Warning: creating a non-TLS insecure server")
	}
	if err != nil {
		return err
	}

	defer listener.Close()

	for {
		conn, err := listener.Accept()
		if err != nil {
			return err
		}

		s.newClient(conn)
	}

	return nil
}
Esempio n. 15
0
// Start a `how` server listening for connections at `addr`. You need to call Accept() on the
// returned socket to start accepting connections. `how` and `addr` are passed to `net.Listen()`
// and thus any values accepted by net.Listen are valid.
// The returned server has Handlers=DefaultHandlers and Limits=DefaultLimits set.
func Listen(how, addr string, config *tls.Config) (*Server, error) {

	l, err := tls.Listen(how, addr, config)

	if err != nil {
		return nil, err
	}

	if tcpl, ok := l.(*net.TCPListener); ok {
		// Wrap TCP listener to enable TCP keep-alive
		l = &tcpKeepAliveListener{tcpl}
	}

	s := NewServer(DefaultHandlers, DefaultLimits, l)

	if how == "unix" || how == "unixpacket" {
		// Unix sockets must be unlink()ed before being reused again.
		// Handle common process-killing signals so we can gracefully shut down.
		sigc := make(chan os.Signal, 1)
		signal.Notify(sigc, os.Interrupt, os.Kill, syscall.SIGTERM)
		go func(c chan os.Signal) {
			<-c // Wait for a signal
			//sig := <-c  // Wait for a signal
			//log.Printf("Caught signal %s: shutting down.", sig)
			s.Close() // Stop listening and unlink the socket
			os.Exit(0)
		}(sigc)
	}

	return s, nil
}
Esempio n. 16
0
func (self *HttpServer) startSsl(p *pat.PatternServeMux) {
	defer func() { self.shutdown <- true }()

	// return if the ssl port or cert weren't set
	if self.httpSslPort == "" || self.httpSslCert == "" {
		return
	}

	log.Info("Starting SSL api on port %s using certificate in %s", self.httpSslPort, self.httpSslCert)

	cert, err := tls.LoadX509KeyPair(self.httpSslCert, self.httpSslCert)
	if err != nil {
		panic(err)
	}

	self.sslConn, err = tls.Listen("tcp", self.httpSslPort, &tls.Config{
		Certificates: []tls.Certificate{cert},
	})
	if err != nil {
		panic(err)
	}

	if err := libhttp.Serve(self.sslConn, p); err != nil && !strings.Contains(err.Error(), "closed network") {
		panic(err)
	}
}
Esempio n. 17
0
func main() {
	random, _ := os.Open("/dev/urandom", os.O_RDONLY, 0)
	pembytes := readEntireFile("/home/kris/SSL/gr0g.crt")
	cert, _ := pem.Decode(pembytes)
	keybytes := readEntireFile("/home/kris/SSL/gr0g.key")
	pk, _ := pem.Decode(keybytes)

	privatekey, _ := x509.ParsePKCS1PrivateKey(pk.Bytes)

	config := new(tls.Config)
	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0].Certificate = [][]byte{cert.Bytes}
	config.Certificates[0].PrivateKey = privatekey
	config.Rand = random
	//config.RootCAs = caset
	config.Time = time.Seconds
	listener, err := tls.Listen("tcp", "0.0.0.0:8443", config)

	fmt.Printf("%s\n", err)
	for {
		conn, _ := listener.Accept()
		go func() {
			for {
				buf := make([]byte, 1024)
				_, err := conn.Read(buf)
				if err != nil {
					return
				}
				fmt.Printf("%s", buf)
			}
		}()
	}
}
Esempio n. 18
0
// SecureListen obtains a listener that accepts
// secure connections
func SecureServe(addr string, certFile, keyFile, caFile string) {
	config := tls.Config{}

	// load the server cert / key
	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		log.Fatalf("%s", err)
	}
	config.Certificates = []tls.Certificate{cert}

	// load the ca if necessary
	// FIXME(alainjobart) this doesn't quite work yet, have
	// to investigate
	if caFile != "" {
		config.ClientCAs = x509.NewCertPool()

		pemCerts, err := ioutil.ReadFile(caFile)
		if err != nil {
			log.Fatalf("%s", err)
		}
		if !config.ClientCAs.AppendCertsFromPEM(pemCerts) {
			log.Fatalf("%s", err)
		}

		config.ClientAuth = tls.RequireAndVerifyClientCert
	}
	l, err := tls.Listen("tcp", addr, &config)
	if err != nil {
		log.Fatalf("%s", err)
	}
	throttled := NewThrottledListener(l, *secureThrottle, *secureMaxBuffer)
	cl := proc.Published(throttled, "SecureConnections", "SecureAccepts")
	go http.Serve(cl, nil)
}
Esempio n. 19
0
func (t *TLSListener) Start() {
	var err error
	listenerClosed := make(chan struct{})

	listener, err := tls.Listen("tcp", t.address, t.config)
	if err != nil {
		t.logger.Fatalf("Failed to start TCP listener. %s", err)
	}

	t.lock.Lock()
	t.connections = make(map[net.Conn]struct{})
	t.stopped = make(chan struct{})
	t.listenerClosed = listenerClosed
	t.listener = listener
	t.lock.Unlock()

	t.logger.Infof("TCP listener listening on %s", t.address)
	for {
		conn, err := t.listener.Accept()
		if err != nil {
			close(listenerClosed)
			t.logger.Debugf("Error while reading: %s", err)
			return
		}
		t.addConnection(conn)
		go t.handleConnection(conn)
	}
}
Esempio n. 20
0
func runServer(ch chan bool, done chan bool) {
	cert, err := tls.LoadX509KeyPair("../cert.pem", "../key.pem")
	if err != nil {
		log.Fatalf("While loading tls certs: %v", err)
		return
	}
	config := tls.Config{Certificates: []tls.Certificate{cert}}
	ln, err := tls.Listen("tcp", addr, &config)
	if err != nil {
		log.Fatalf("When listening: %v", err)
		return
	}
	s := rpc.NewServer()
	if err := s.Register(&PostingList{}); err != nil {
		log.Fatalf("Error when registering rpc server: %v", err)
		return
	}

	ch <- true
	log.Debugln("Ready to accept new connection")
	conn, err := ln.Accept()
	if err != nil {
		log.Fatalf("cannot accept incoming tcp conn: %s", err)
		return
	}
	defer conn.Close()
	log.Debugln("Accepted a connection")
	go s.ServeConn(conn)
	<-done
}
Esempio n. 21
0
func listenTLS(addr string) (net.Listener, error) {
	host, _, err := net.SplitHostPort(addr)
	if err != nil {
		return nil, fmt.Errorf("Unable to split host and port for %v: %v\n", addr, err)
	}
	ctx := CertContext{
		PKFile:         "key.pem",
		ServerCertFile: "cert.pem",
	}
	err = ctx.InitServerCert(host)
	if err != nil {
		return nil, fmt.Errorf("Unable to init server cert: %s\n", err)
	}

	tlsConfig := tlsdefaults.Server()
	cert, err := tls.LoadX509KeyPair(ctx.ServerCertFile, ctx.PKFile)
	if err != nil {
		return nil, fmt.Errorf("Unable to load certificate and key from %s and %s: %s\n", ctx.ServerCertFile, ctx.PKFile, err)
	}
	tlsConfig.Certificates = []tls.Certificate{cert}

	listener, err := tls.Listen("tcp", addr, tlsConfig)
	if err != nil {
		return nil, fmt.Errorf("Unable to listen for tls connections at %s: %s\n", addr, err)
	}

	return listener, err
}
Esempio n. 22
0
func Init(listenAddr string, supervisorPort uint16, cpuIncr, memIncr uint, resDuration time.Duration) error {
	var err error
	err = LoadEnvs()
	if err != nil {
		return err
	}
	CPUSharesIncrement = cpuIncr
	MemoryLimitIncrement = memIncr
	atlantis.Tracker.ResultDuration = resDuration
	// init rpc stuff here
	lAddr = listenAddr
	lPort = strings.Split(lAddr, ":")[1]
	supervisor.Init(fmt.Sprintf("%d", supervisorPort))
	manager.Init(lPort)
	manager := new(ManagerRPC)
	server = rpc.NewServer()
	server.Register(manager)
	config := &tls.Config{}
	config.InsecureSkipVerify = true
	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0], err = tls.X509KeyPair(crypto.SERVER_CERT, crypto.SERVER_KEY)

	l, err = tls.Listen("tcp", lAddr, config)
	return err
}
Esempio n. 23
0
func RunServer(cfg Config) {
	memoryStore := NewStore()

	var ln net.Listener
	var err error

	if cfg.TLSEnabled() {
		ln, err = tls.Listen("tcp", ":"+cfg.Port, cfg.TLSConfig())
	} else {
		ln, err = net.Listen("tcp", ":"+cfg.Port)
	}
	if err != nil {
		log.Println("Failed to start server:", err.Error())
	}

	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Println("Client failed to open new connection:", err.Error())
		}

		id, err := newUUID()
		if err != nil {
			log.Println("Failed to create unique ID for new client")
			conn.Close()
			continue
		}

		log.Printf("New connection opened clientId=%s", id)

		c := NewClient(id, conn, memoryStore)
		go c.Handle()
	}
}
Esempio n. 24
0
// If http.ListenandServe return an error,
// it will throws a panic.
func wsListener() {
	if err := func() error {
		httpServeMux := http.NewServeMux()
		httpServeMux.Handle("/pub", websocket.Handler(WsHandle))
		var (
			l   net.Listener
			err error
		)
		if Conf.Tls {
			tlsConf := new(tls.Config)
			tlsConf.Certificates = make([]tls.Certificate, 1)
			tlsConf.Certificates[0], err = tls.X509KeyPair(Conf.Cert, Conf.Key)
			if err != nil {
				return err
			}
			l, err = tls.Listen("tcp", Conf.WebSocket_addr, tlsConf)
			if err != nil {
				return err
			}
			return http.Serve(l, httpServeMux)
		} else {
			return http.ListenAndServe(Conf.WebSocket_addr, httpServeMux)
		}
	}(); err != nil {
		panic(err)
	}
}
Esempio n. 25
0
// startServingTLS creates and registers a secure listener and begins serving traffic.
func (s *TestHttpService) startServingTLS(addr string, cert []byte, key []byte, caCert []byte, handler http.Handler) error {
	tlsCert, err := tls.X509KeyPair(append(cert, caCert...), key)

	if err != nil {
		return err
	}

	cfg := &tls.Config{
		Certificates: []tls.Certificate{tlsCert},
	}

	listener, err := tls.Listen("tcp", addr, cfg)

	if err != nil {
		return err
	}

	s.listeners = append(s.listeners, listener)
	glog.Infof("Started, serving TLS at %s\n", listener.Addr().String())

	go func() {
		if err := http.Serve(listener, handler); err != nil {
			glog.Errorf("HTTPS server failed: %v", err)
		}
	}()

	return nil
}
Esempio n. 26
0
func TestTLSCollectorServer(t *testing.T) {
	var numPackets int
	mc := collectorFunc(func(span SpanID, anns ...Annotation) error {
		numPackets++
		return nil
	})

	l, err := tls.Listen("tcp", "127.0.0.1:0", &localhostTLSConfig)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("TLS collector listening on %s", l.Addr())

	cs := NewServer(l, mc)
	go cs.Start()

	cc := &collectorT{t, NewTLSRemoteCollector(l.Addr().String(), &localhostTLSConfig)}
	cc.MustCollect(SpanID{1, 2, 3})
	cc.MustCollect(SpanID{2, 3, 4})
	if err := cc.Collector.(*RemoteCollector).Close(); err != nil {
		t.Error(err)
	}

	time.Sleep(20 * time.Millisecond)
	if want := 2; numPackets != want {
		t.Errorf("server collected %d packets, want %d", numPackets, want)
	}
}
Esempio n. 27
0
func NewSSLTestServer(t testing.TB, protocol uint8) *TestServer {
	pem, err := ioutil.ReadFile("testdata/pki/ca.crt")
	certPool := x509.NewCertPool()
	if !certPool.AppendCertsFromPEM(pem) {
		t.Fatalf("Failed parsing or appending certs")
	}
	mycert, err := tls.LoadX509KeyPair("testdata/pki/cassandra.crt", "testdata/pki/cassandra.key")
	if err != nil {
		t.Fatalf("could not load cert")
	}
	config := &tls.Config{
		Certificates: []tls.Certificate{mycert},
		RootCAs:      certPool,
	}
	listen, err := tls.Listen("tcp", "127.0.0.1:0", config)
	if err != nil {
		t.Fatal(err)
	}

	headerSize := 8
	if protocol > protoVersion2 {
		headerSize = 9
	}

	srv := &TestServer{
		Address:    listen.Addr().String(),
		listen:     listen,
		t:          t,
		protocol:   protocol,
		headerSize: headerSize,
		quit:       make(chan struct{}),
	}
	go srv.serve()
	return srv
}
Esempio n. 28
0
func NewServer(cfg *Config) (*Server, error) {
	s := new(Server)

	s.cfg = cfg

	s.addr = cfg.Addr

	if err := s.parseAllowIps(); err != nil {
		return nil, err
	}

	var err error

	if s.cfg.TlsServer {
		s.listener, err = tls.Listen(cfg.Net, s.addr, s.cfg.TlsServerConf)
	} else {
		s.listener, err = net.Listen(cfg.Net, s.addr)
	}

	if err != nil {
		return nil, err
	}

	if cfg.Net == "unix" {
		if err = os.Chmod(s.addr, 0777); err != nil {
			return nil, err
		}
	}

	log.Printf("server.NewServer Server running. address %s:%s, tls:%v", cfg.Net, s.addr, s.cfg.TlsServer)
	return s, nil
}
Esempio n. 29
0
func startHttpsServer(t *testing.T) {
	if httpsAddr != "" {
		return
	}

	var err error

	pk, err = keyman.GeneratePK(2048)
	if err != nil {
		t.Fatalf("Unable to generate key: %s", err)
	}

	// Generate self-signed certificate
	cert, err = pk.TLSCertificateFor("tlsdialer", "localhost", time.Now().Add(1*time.Hour), true, nil)
	if err != nil {
		t.Fatalf("Unable to generate cert: %s", err)
	}

	keypair, err := tls.X509KeyPair(cert.PEMEncoded(), pk.PEMEncoded())
	if err != nil {
		t.Fatalf("Unable to generate x509 key pair: %s", err)
	}

	l, err := tls.Listen("tcp", "localhost:0", &tls.Config{
		Certificates: []tls.Certificate{keypair},
	})
	if err != nil {
		t.Fatalf("HTTP unable to listen: %v", err)
	}
	httpsAddr = l.Addr().String()

	doStartServer(t, l)
}
Esempio n. 30
0
// Open starts the service
func (s *Service) Open() error {
	s.Logger.Println("Starting HTTP service")
	s.Logger.Println("Authentication enabled:", s.Handler.requireAuthentication)

	// Open listener.
	if s.https {
		cert, err := tls.LoadX509KeyPair(s.cert, s.cert)
		if err != nil {
			return err
		}

		listener, err := tls.Listen("tcp", s.addr, &tls.Config{
			Certificates: []tls.Certificate{cert},
		})
		if err != nil {
			return err
		}

		s.Logger.Println("Listening on HTTPS:", listener.Addr().String())
		s.ln = listener
	} else {
		listener, err := net.Listen("tcp", s.addr)
		if err != nil {
			return err
		}

		s.Logger.Println("Listening on HTTP:", listener.Addr().String())
		s.ln = listener
	}

	// Begin listening for requests in a separate goroutine.
	go s.serve()
	return nil
}