2020-02-06 20:42:46 -05:00
|
|
|
package dns
|
|
|
|
|
|
|
|
|
|
import (
|
2020-10-18 02:24:34 +00:00
|
|
|
"context"
|
2020-02-06 20:42:46 -05:00
|
|
|
"fmt"
|
2020-12-29 02:55:34 +00:00
|
|
|
"io"
|
2020-04-12 20:05:28 +00:00
|
|
|
"net/http"
|
2020-12-29 00:55:31 +00:00
|
|
|
"os"
|
2020-02-06 20:42:46 -05:00
|
|
|
|
2020-07-26 12:07:06 +00:00
|
|
|
"github.com/qdm12/gluetun/internal/constants"
|
2020-02-06 20:42:46 -05:00
|
|
|
)
|
|
|
|
|
|
2020-10-18 02:24:34 +00:00
|
|
|
func (c *configurator) DownloadRootHints(ctx context.Context, uid, gid int) error {
|
2020-12-29 00:55:31 +00:00
|
|
|
return c.downloadAndSave(ctx, "root hints",
|
|
|
|
|
string(constants.NamedRootURL), string(constants.RootHints), uid, gid)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *configurator) DownloadRootKey(ctx context.Context, uid, gid int) error {
|
|
|
|
|
return c.downloadAndSave(ctx, "root key",
|
|
|
|
|
string(constants.RootKeyURL), string(constants.RootKey), uid, gid)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *configurator) downloadAndSave(ctx context.Context, logName, url, filepath string, uid, gid int) error {
|
|
|
|
|
c.logger.Info("downloading %s from %s", logName, url)
|
2020-12-29 02:55:34 +00:00
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
2020-02-06 20:42:46 -05:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
2020-12-29 02:55:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
response, err := c.client.Do(req)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
|
|
|
|
|
if response.StatusCode != http.StatusOK {
|
|
|
|
|
return fmt.Errorf("%w from %s: %s", ErrBadStatusCode, url, response.Status)
|
2020-02-06 20:42:46 -05:00
|
|
|
}
|
|
|
|
|
|
2020-12-29 00:55:31 +00:00
|
|
|
file, err := c.openFile(filepath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0400)
|
2020-02-06 20:42:46 -05:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2020-12-29 00:55:31 +00:00
|
|
|
|
2020-12-29 02:55:34 +00:00
|
|
|
_, err = io.Copy(file, response.Body)
|
2020-12-29 00:55:31 +00:00
|
|
|
if err != nil {
|
|
|
|
|
_ = file.Close()
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err = file.Chown(uid, gid)
|
|
|
|
|
if err != nil {
|
|
|
|
|
_ = file.Close()
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return file.Close()
|
2020-02-06 20:42:46 -05:00
|
|
|
}
|