2018-08-26 19:15:48 +08:00
|
|
|
//
|
|
|
|
// Copyright (c) 2018
|
|
|
|
// Mainflux
|
|
|
|
//
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
//
|
|
|
|
|
2018-08-16 19:41:27 +08:00
|
|
|
package cli
|
2018-07-11 19:53:37 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/tls"
|
|
|
|
"crypto/x509"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"strconv"
|
|
|
|
|
|
|
|
"github.com/mainflux/mainflux"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2018-08-16 19:41:27 +08:00
|
|
|
defCertsPath = "/src/github.com/mainflux/mainflux/docker/ssl/certs/"
|
|
|
|
envCertFile = "MF_CERT_FILE"
|
|
|
|
envKeyFile = "MF_KEY_FILE"
|
|
|
|
envCaFile = "MF_CA_FILE"
|
2018-07-11 19:53:37 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
httpClient = &http.Client{}
|
|
|
|
serverAddr = fmt.Sprintf("https://%s", "localhost")
|
|
|
|
|
2018-08-16 19:41:27 +08:00
|
|
|
defCertFile = fmt.Sprintf("%s%s%s", os.Getenv("GOPATH"), defCertsPath, "mainflux-server.crt")
|
|
|
|
defKeyFile = fmt.Sprintf("%s%s%s", os.Getenv("GOPATH"), defCertsPath, "mainflux-server.key")
|
|
|
|
defCaFile = fmt.Sprintf("%s%s%s", os.Getenv("GOPATH"), defCertsPath, "ca.crt")
|
2018-07-11 19:53:37 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// SetServerAddr - set addr using host and port
|
2018-08-17 10:58:09 +08:00
|
|
|
func SetServerAddr(proto string, host string, port int) {
|
|
|
|
serverAddr = fmt.Sprintf("%s://%s", proto, host)
|
2018-07-11 19:53:37 +08:00
|
|
|
|
|
|
|
if port != 0 {
|
|
|
|
serverAddr = fmt.Sprintf("%s:%s", serverAddr, strconv.Itoa(port))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func SetCerts() {
|
|
|
|
// Set certificates paths
|
|
|
|
certFile := mainflux.Env(envCertFile, defCertFile)
|
|
|
|
keyFile := mainflux.Env(envKeyFile, defKeyFile)
|
|
|
|
caFile := mainflux.Env(envCaFile, defCaFile)
|
|
|
|
|
|
|
|
// Load client cert
|
|
|
|
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Load CA cert
|
|
|
|
caCert, err := ioutil.ReadFile(caFile)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
caCertPool := x509.NewCertPool()
|
|
|
|
caCertPool.AppendCertsFromPEM(caCert)
|
|
|
|
|
|
|
|
// Setup HTTPS client
|
|
|
|
tlsConfig := &tls.Config{
|
|
|
|
Certificates: []tls.Certificate{cert},
|
|
|
|
RootCAs: caCertPool,
|
|
|
|
}
|
|
|
|
tlsConfig.BuildNameToCertificate()
|
|
|
|
transport := &http.Transport{TLSClientConfig: tlsConfig}
|
|
|
|
httpClient = &http.Client{Transport: transport}
|
|
|
|
}
|