2
2
mirror of https://github.com/octoleo/restic.git synced 2024-11-26 06:46:34 +00:00
restic/internal/backend/rest/config.go

91 lines
2.1 KiB
Go
Raw Normal View History

package rest
import (
"net/url"
"os"
"strings"
"github.com/restic/restic/internal/backend"
2017-07-23 12:21:03 +00:00
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/options"
)
// Config contains all configuration necessary to connect to a REST server.
type Config struct {
2017-06-05 22:25:22 +00:00
URL *url.URL
Connections uint `option:"connections" help:"set a limit for the number of concurrent connections (default: 5)"`
2017-06-05 22:25:22 +00:00
}
func init() {
options.Register("rest", Config{})
}
// NewConfig returns a new Config with the default values filled in.
func NewConfig() Config {
return Config{
Connections: 5,
2017-06-05 22:25:22 +00:00
}
}
// ParseConfig parses the string s and extracts the REST server URL.
func ParseConfig(s string) (*Config, error) {
if !strings.HasPrefix(s, "rest:") {
return nil, errors.New("invalid REST backend specification")
}
2020-03-20 22:52:27 +00:00
s = prepareURL(s)
u, err := url.Parse(s)
if err != nil {
return nil, errors.WithStack(err)
}
2017-06-05 22:25:22 +00:00
cfg := NewConfig()
cfg.URL = u
return &cfg, nil
}
2020-03-20 22:52:27 +00:00
// StripPassword removes the password from the URL
// If the repository location cannot be parsed as a valid URL, it will be returned as is
// (it's because this function is used for logging errors)
func StripPassword(s string) string {
scheme := s[:5]
s = prepareURL(s)
u, err := url.Parse(s)
if err != nil {
return scheme + s
}
if _, set := u.User.Password(); !set {
return scheme + s
}
// a password was set: we replace it with ***
return scheme + strings.Replace(u.String(), u.User.String()+"@", u.User.Username()+":***@", 1)
}
func prepareURL(s string) string {
s = s[5:]
if !strings.HasSuffix(s, "/") {
s += "/"
}
return s
}
var _ backend.ApplyEnvironmenter = &Config{}
// ApplyEnvironment saves values from the environment to the config.
func (cfg *Config) ApplyEnvironment(prefix string) {
username := cfg.URL.User.Username()
_, pwdSet := cfg.URL.User.Password()
// Only apply env variable values if neither username nor password are provided.
if username == "" && !pwdSet {
envName := os.Getenv(prefix + "RESTIC_REST_USERNAME")
envPwd := os.Getenv(prefix + "RESTIC_REST_PASSWORD")
cfg.URL.User = url.UserPassword(envName, envPwd)
}
}