about summary refs log tree commit diff
path: root/src/access.go
diff options
context:
space:
mode:
authormaride <maride@darknebu.la>2018-08-23 11:46:23 +0200
committermaride <maride@darknebu.la>2018-08-23 11:46:23 +0200
commit8b65f91699cd474563c0abacc726a3d47961a78f (patch)
tree5d811fe2e5b0ddc7ecafdb9c1ee0343d91fa768e /src/access.go
parent82c922d557f6628043ab771cdf10e4da9546347d (diff)
Add VPN container and access
Diffstat (limited to 'src/access.go')
-rw-r--r--src/access.go111
1 files changed, 111 insertions, 0 deletions
diff --git a/src/access.go b/src/access.go
new file mode 100644
index 0000000..6072025
--- /dev/null
+++ b/src/access.go
@@ -0,0 +1,111 @@
+package main
+
+import (
+	"github.com/docker/docker/api/types/container"
+	"github.com/docker/docker/api/types"
+	"time"
+	"errors"
+	"net/http"
+	"fmt"
+	"github.com/docker/docker/api/types/network"
+)
+
+var vpnContainerID string
+var vpnNetworkID string
+
+func startVPN() (err error) {
+	// Set up our context and Docker CLI connection
+	setupContext()
+	setupDockerCLI()
+	// Set up network
+	setupNetwork()
+
+	// Create container
+	resp, err := dockerCli.ContainerCreate(dockerCtx, &container.Config{
+		Image: "circus-vpn",
+	}, &container.HostConfig{
+		Privileged: true,
+	}, &network.NetworkingConfig{
+		EndpointsConfig: map[string]*network.EndpointSettings{
+			"endpoint": {
+				NetworkID: vpnNetworkID,
+			},
+		},
+	}, "")
+
+	if err != nil {
+		return err
+	}
+
+	// Start container
+	err = dockerCli.ContainerStart(dockerCtx, resp.ID, types.ContainerStartOptions{})
+	if err != nil {
+		return err
+	}
+
+	vpnContainerID = resp.ID
+
+	return nil
+}
+
+func stopVPN() {
+	setupContext()
+	setupDockerCLI()
+
+	timeout := time.Second * 5
+	dockerCli.ContainerStop(dockerCtx, vpnContainerID, &timeout)
+
+	vpnContainerID = ""
+}
+
+func setupNetwork() (error) {
+	setupContext()
+	setupDockerCLI()
+
+	if vpnNetworkID == "" {
+		response, err := dockerCli.NetworkCreate(dockerCtx, VPNNetworkName, types.NetworkCreate{
+			Internal: true,
+		})
+
+		if err != nil {
+			return err
+		}
+
+		vpnNetworkID = response.ID
+	}
+
+	return nil
+}
+
+func getCertificate() (string, error) {
+	if vpnContainerID == "" {
+		return "", errors.New("VPN container not up")
+	}
+
+	// Get IP of VPN container
+	inspectJSON, err := dockerCli.ContainerInspect(dockerCtx, vpnContainerID)
+	if err != nil {
+		return "", err
+	}
+
+	// get certificate
+	var certResponse *http.Response
+
+	for i := 0; i < 10; i++ {
+		certResponse, err = http.Get(fmt.Sprintf("http://%s:9999/", inspectJSON.NetworkSettings.Networks[VPNNetworkName].IPAddress))
+
+		if err == nil {
+			break
+		}
+		time.Sleep(time.Second)
+	}
+
+	if err != nil {
+		return "", err
+	}
+
+	buffer := make([]byte, 1024)
+	certResponse.Body.Read(buffer)
+
+	return string(buffer), nil
+}