wireguard.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. package docker
  2. import (
  3. "context"
  4. "fmt"
  5. "goseg/config"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "encoding/base64"
  10. "strings"
  11. "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/client"
  13. "github.com/docker/docker/api/types"
  14. // "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  15. )
  16. func LoadWireguard() error {
  17. logger.Info("Loading Startram Wireguard container")
  18. confPath := filepath.Join(config.BasePath, "settings", "wireguard.json")
  19. _, err := os.Open(confPath)
  20. if err != nil {
  21. // create a default if it doesn't exist
  22. err = config.CreateDefaultWGConf()
  23. if err != nil {
  24. // error if we can't create it
  25. errmsg := fmt.Sprintf("Unable to create WG config! %v", err)
  26. logger.Error(errmsg)
  27. panic(errmsg)
  28. }
  29. }
  30. logger.Info("Running Wireguard")
  31. info, err := StartContainer("wireguard", "wireguard")
  32. if err != nil {
  33. logger.Error(fmt.Sprintf("Error starting wireguard: %v", err))
  34. return err
  35. }
  36. config.UpdateContainerState("wireguard", info)
  37. return nil
  38. }
  39. // wireguard container config builder
  40. func wgContainerConf() (container.Config, container.HostConfig, error) {
  41. var containerConfig container.Config
  42. var hostConfig container.HostConfig
  43. // construct the container metadata from version server info
  44. containerInfo, err := GetLatestContainerInfo("wireguard")
  45. if err != nil {
  46. return containerConfig, hostConfig, err
  47. }
  48. desiredTag := containerInfo["tag"]
  49. desiredHash := containerInfo["hash"]
  50. desiredRepo := containerInfo["repo"]
  51. desiredImage := fmt.Sprintf("%s:%s@sha256:%s", desiredRepo, desiredTag, desiredHash)
  52. // construct the container config struct
  53. containerConfig = container.Config{
  54. Image: desiredImage,
  55. Entrypoint: []string{"/bin/bash"},
  56. Tty: true,
  57. OpenStdin: true,
  58. }
  59. // always on wg nw
  60. hostConfig = container.HostConfig{
  61. NetworkMode: "container:wireguard",
  62. }
  63. return containerConfig, hostConfig, nil
  64. }
  65. // wg client config builder
  66. func buildWgConf() (string, error) {
  67. confB64 := config.StartramConfig.Conf
  68. confBytes, err := base64.StdEncoding.DecodeString(confB64)
  69. if err != nil {
  70. return "", fmt.Errorf("Failed to decode remote WG base64: %v", err)
  71. }
  72. conf := string(confBytes)
  73. configData := config.Conf()
  74. res := strings.Replace(conf, "privkey", configData.Privkey, -1)
  75. return res, nil
  76. }
  77. // write wg config if it doesn't exist or doesn't match
  78. func writeWgConf() error {
  79. volumeExists := true
  80. // read existing and build current conf
  81. filePath := filepath.Join(config.DockerDir, "settings", "wireguard", "_data", "wg0.conf")
  82. existingConf, err := ioutil.ReadFile(filePath)
  83. if err != nil {
  84. volumeExists = false
  85. }
  86. newConf, err := buildWgConf()
  87. if err != nil {
  88. return err
  89. }
  90. ctx := context.Background()
  91. cli, err := client.NewClientWithOpts(client.FromEnv)
  92. if err != nil {
  93. return err
  94. }
  95. _, err = cli.VolumeInspect(ctx, "wireguard")
  96. if err != nil {
  97. volumeExists = false
  98. }
  99. // if theyre different, or if the volume doesnt exist, copy the new config to the volume
  100. if string(existingConf) != newConf || !volumeExists {
  101. err = ioutil.WriteFile("tmp/wg0.conf", []byte(newConf), 0644)
  102. if err != nil {
  103. return fmt.Errorf("Failed to write new WG config: %v", err)
  104. }
  105. // copy to volume
  106. err = copyFileToVolume(filepath.Join("tmp","wg0.conf"), "/etc/wireguard/", "wireguard")
  107. if err != nil {
  108. return fmt.Errorf("Failed to copy WG config file to volume: %v", err)
  109. }
  110. }
  111. return nil
  112. }
  113. // write wg conf to volume
  114. func copyFileToVolume(filePath string, targetPath string, volumeName string) error {
  115. ctx := context.Background()
  116. cli, err := client.NewClientWithOpts(client.FromEnv)
  117. if err != nil {
  118. return err
  119. }
  120. // temp container to mount
  121. resp, err := cli.ContainerCreate(ctx, &container.Config{
  122. Image: "busybox",
  123. Cmd: []string{"tail", "-f", "/dev/null"},
  124. }, &container.HostConfig{
  125. Binds: []string{volumeName + ":" + targetPath},
  126. }, nil, nil, "bb_temp")
  127. if err != nil {
  128. return err
  129. }
  130. if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
  131. return err
  132. }
  133. file, err := os.Open(filepath.Join(filePath))
  134. if err != nil {
  135. return fmt.Errorf("failed to open wg0 file: %v", err)
  136. }
  137. defer file.Close()
  138. // Copy the file to the volume via the temporary container
  139. err = cli.CopyToContainer(ctx, resp.ID, targetPath, file, types.CopyToContainerOptions{})
  140. if err != nil {
  141. return err
  142. }
  143. // remove temporary container
  144. if err := cli.ContainerRemove(ctx, resp.ID, types.ContainerRemoveOptions{Force: true}); err != nil {
  145. return err
  146. }
  147. return nil
  148. }