Skip to content

Commit

Permalink
Merge pull request #4 from gptankit/master_tls_management
Browse files Browse the repository at this point in the history
Improvements to optional tls management
  • Loading branch information
gptankit authored Jun 11, 2018
2 parents 959dd02 + 9d7646c commit 0a20134
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 24 deletions.
64 changes: 64 additions & 0 deletions listener.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package main

import (
"crypto/rand"
"crypto/tls"
"model"
"net"
"time"
)

func getListener(sqp model.ServiceQProperties) (net.Listener, error) {

transport := "tcp"
addr := ":" + sqp.ListenerPort
certificate := sqp.SSLCertificateFile
key := sqp.SSLPrivateKeyFile

if !sqp.SSLEnabled {
return newListener(transport, addr)
} else {
return newListener(transport, addr, applyTLS(certificate, key))
}
}

func newListener(transport string, addr string, options ...func(*net.Listener) error) (net.Listener, error) {

listener, err := net.Listen(transport, addr)
if err != nil {
return listener, err
}

for _, option := range options {
err = option(&listener)
if err != nil {
return listener, err // further options won't be executed
}
}

return listener, nil
}

func applyTLS(certificate string, key string) func(*net.Listener) error {

return func(l *net.Listener) error {

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

tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
ServerName: "serviceq",
NextProtos: []string{"http/1.1", "http/1.0"},
Time: time.Now,
Rand: rand.Reader,
}
tlsConfig.BuildNameToCertificate()
tlsConfig.PreferServerCipherSuites = true

*l = tls.NewListener(*l, tlsConfig)
return nil
}
}
24 changes: 0 additions & 24 deletions serviceq.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package main

import (
"crypto/rand"
"crypto/tls"
"fmt"
"model"
"net"
Expand Down Expand Up @@ -35,28 +33,6 @@ func main() {
}
}

func getListener(sqp model.ServiceQProperties) (net.Listener, error) {

if sqp.SSLEnabled {
cert, err := tls.LoadX509KeyPair(sqp.SSLCertificateFile, sqp.SSLPrivateKeyFile)
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
ServerName: "serviceq",
NextProtos: []string{"http/1.1", "http/1.0"},
Time: time.Now,
Rand: rand.Reader,
}
tlsConfig.BuildNameToCertificate()
tlsConfig.PreferServerCipherSuites = true
return tls.Listen("tcp", ":"+sqp.ListenerPort, tlsConfig)
} else {
return net.Listen("tcp", ":"+sqp.ListenerPort)
}
}

func listenActive(listener net.Listener, creq chan interface{}, cwork chan int, sqp *model.ServiceQProperties) {

for {
Expand Down

0 comments on commit 0a20134

Please sign in to comment.