wireguard.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package docker
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "fmt"
  6. "github.com/docker/docker/api/types"
  7. "github.com/docker/docker/api/types/container"
  8. "github.com/docker/docker/client"
  9. "goseg/config"
  10. "io/ioutil"
  11. "os"
  12. "path/filepath"
  13. "strings"
  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 container conf if it doesn't exist
  22. err = config.CreateDefaultWGConf()
  23. if err != nil {
  24. // error if we can't create it
  25. return err
  26. }
  27. }
  28. // create wg0.conf or update it
  29. err = WriteWgConf()
  30. if err != nil {
  31. return err
  32. }
  33. logger.Info("Running Wireguard")
  34. info, err := StartContainer("wireguard", "wireguard")
  35. if err != nil {
  36. logger.Error(fmt.Sprintf("Error starting wireguard: %v", err))
  37. return err
  38. }
  39. config.UpdateContainerState("wireguard", info)
  40. return nil
  41. }
  42. // wireguard container config builder
  43. func wgContainerConf() (container.Config, container.HostConfig, error) {
  44. var containerConfig container.Config
  45. var hostConfig container.HostConfig
  46. // construct the container metadata from version server info
  47. containerInfo, err := GetLatestContainerInfo("wireguard")
  48. if err != nil {
  49. return containerConfig, hostConfig, err
  50. }
  51. desiredImage := fmt.Sprintf("%s:%s@sha256:%s", containerInfo["repo"], containerInfo["tag"], containerInfo["hash"])
  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. // wg0.conf 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 latest conf
  78. func WriteWgConf() error {
  79. newConf, err := buildWgConf()
  80. if err != nil {
  81. return err
  82. }
  83. filePath := filepath.Join(config.DockerDir, "settings", "wireguard", "_data", "wg0.conf")
  84. existingConf, err := ioutil.ReadFile(filePath)
  85. if err != nil {
  86. // assume it doesn't exist, so write the current config
  87. return writeWgConfToFile(filePath, newConf)
  88. }
  89. if string(existingConf) != newConf {
  90. // If they differ, overwrite
  91. return writeWgConfToFile(filePath, newConf)
  92. }
  93. return nil
  94. }
  95. // either write directly or create volumes
  96. func writeWgConfToFile(filePath string, content string) error {
  97. // try writing
  98. err := ioutil.WriteFile(filePath, []byte(content), 0644)
  99. if err == nil {
  100. return nil
  101. }
  102. // ensure the directory structure exists
  103. dir := filepath.Dir(filePath)
  104. if err = os.MkdirAll(dir, 0755); err != nil {
  105. return err
  106. }
  107. // try writing again
  108. err = ioutil.WriteFile(filePath, []byte(content), 0644)
  109. if err != nil {
  110. err = copyFileToVolume(filePath, "/etc/wireguard/", "wireguard")
  111. // otherwise create the volume
  112. if err != nil {
  113. return fmt.Errorf("Failed to copy WG config file to volume: %v", err)
  114. }
  115. }
  116. return nil
  117. }
  118. // write wg conf to volume
  119. func copyFileToVolume(filePath string, targetPath string, volumeName string) error {
  120. ctx := context.Background()
  121. cli, err := client.NewClientWithOpts(client.FromEnv)
  122. if err != nil {
  123. return err
  124. }
  125. containerInfo, err := GetLatestContainerInfo("wireguard")
  126. if err != nil {
  127. return err
  128. }
  129. desiredImage := fmt.Sprintf("%s:%s@sha256:%s", containerInfo["repo"], containerInfo["tag"], containerInfo["hash"])
  130. // temp container to mount
  131. resp, err := cli.ContainerCreate(ctx, &container.Config{
  132. Image: desiredImage,
  133. }, &container.HostConfig{
  134. Binds: []string{volumeName + ":" + targetPath},
  135. }, nil, nil, "wg_writer")
  136. if err != nil {
  137. return err
  138. }
  139. if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
  140. return err
  141. }
  142. file, err := os.Open(filepath.Join(filePath))
  143. if err != nil {
  144. return fmt.Errorf("failed to open wg0 file: %v", err)
  145. }
  146. defer file.Close()
  147. // Copy the file to the volume via the temporary container
  148. err = cli.CopyToContainer(ctx, resp.ID, targetPath, file, types.CopyToContainerOptions{})
  149. if err != nil {
  150. return err
  151. }
  152. // remove temporary container
  153. if err := StopContainerByName("wg_writer"); err != nil {
  154. return err
  155. }
  156. if err := cli.ContainerRemove(ctx, resp.ID, types.ContainerRemoveOptions{Force: true}); err != nil {
  157. return err
  158. }
  159. defer func() {
  160. if removeErr := cli.ContainerRemove(ctx, resp.ID, types.ContainerRemoveOptions{Force: true}); removeErr != nil {
  161. logger.Error("Failed to remove temporary container: ", removeErr)
  162. }
  163. }()
  164. return nil
  165. }