http.go 2.12 KB
Newer Older
1
// Copyright (C) 2017. See AUTHORS.
JT Olds's avatar
JT Olds committed
2 3 4 5 6 7 8 9 10 11 12 13
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
JT Olds's avatar
JT Olds committed
14 15 16 17

package openssl

import (
18
	"net/http"
JT Olds's avatar
JT Olds committed
19 20
)

JT Olds's avatar
JT Olds committed
21 22
// ListenAndServeTLS will take an http.Handler and serve it using OpenSSL over
// the given tcp address, configured to use the provided cert and key files.
JT Olds's avatar
JT Olds committed
23
func ListenAndServeTLS(addr string, cert_file string, key_file string,
24 25 26
	handler http.Handler) error {
	return ServerListenAndServeTLS(
		&http.Server{Addr: addr, Handler: handler}, cert_file, key_file)
JT Olds's avatar
JT Olds committed
27 28
}

JT Olds's avatar
JT Olds committed
29 30
// ServerListenAndServeTLS will take an http.Server and serve it using OpenSSL
// configured to use the provided cert and key files.
JT Olds's avatar
JT Olds committed
31
func ServerListenAndServeTLS(srv *http.Server,
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
	cert_file, key_file string) error {
	addr := srv.Addr
	if addr == "" {
		addr = ":https"
	}

	ctx, err := NewCtxFromFiles(cert_file, key_file)
	if err != nil {
		return err
	}

	l, err := Listen("tcp", addr, ctx)
	if err != nil {
		return err
	}

	return srv.Serve(l)
JT Olds's avatar
JT Olds committed
49 50 51 52 53 54 55 56 57 58 59 60 61
}

// TODO: http client integration
// holy crap, getting this integrated nicely with the Go stdlib HTTP client
// stack so that it does proxying, connection pooling, and most importantly
// hostname verification is really hard. So much stuff is hardcoded to just use
// the built-in TLS lib. I think to get this to work either some crazy
// hacktackery beyond me, an almost straight up fork of the HTTP client, or
// serious stdlib internal refactoring is necessary.
// even more so, good luck getting openssl to use the operating system default
// root certificates if the user doesn't provide any. sadlol
// NOTE: if you're going to try and write your own round tripper, at least use
//  openssl.Dial, or equivalent logic