aboutsummaryrefslogtreecommitdiff
path: root/pkg/config/url.go
blob: 06796a2a1a08f3a635dd0bb8fff81703490d5599 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package config

import (
	"fmt"
	"net"
	"net/url"

	"gopkg.in/yaml.v3"
)

type Url struct {
	Scheme   string `yaml:"scheme"`
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	Root     string `yaml:"root"`
}

func (u *Url) Empty() bool {
	return u.Host == ""
}

func (u *Url) UnmarshalYAML(value *yaml.Node) (err error) {
	if value.ShortTag() == strTag {
		var val string
		var rawUrl *url.URL

		if err = value.Decode(&val); err != nil {
			return err
		}
		if rawUrl, err = url.Parse(val); err != nil {
			return err
		}

		u.Scheme = rawUrl.Scheme
		u.User = rawUrl.User.Username()
		u.Password, _ = rawUrl.User.Password()
		u.Host = rawUrl.Hostname()
		u.Port = rawUrl.Port()
		u.Root = rawUrl.Path
	} else {
		type _url Url // avoid recursion
		wrapped := (*_url)(u)
		if err = value.Decode(wrapped); err != nil {
			return err
		}
	}

	u.sanitize()

	if errors := u.validate(); len(errors) > 0 {
		errs := make([]string, len(errors)+1)
		copy(errs[1:], errors)
		errs[0] = fmt.Sprintf("line %d: Invalid target:", value.Line)
		return &yaml.TypeError{Errors: errs}
	}

	return nil
}

func (u *Url) String() string {
	var pwd string
	if u.Password != "" {
		pwd = ":******"
	}

	return fmt.Sprintf("%s://%s%s@%s%s", u.Scheme, u.User, pwd, u.HostPort(), u.Root)
}

func (u *Url) HostPort() string {
	if u.Port != "" {
		return net.JoinHostPort(u.Host, u.Port)
	}
	return u.Host
}

const (
	imapsPort   = "993"
	imapPort    = "143"
	imapsSchema = "imaps"
	imapSchema  = "imap"
)

func (u *Url) ForceTLS() bool {
	return u.Scheme == imapsSchema || u.Port == imapsPort
}

func (u *Url) setDefaultScheme() {
	if u.Scheme == "" {
		if u.Port == imapsPort {
			u.Scheme = imapsSchema
		} else {
			u.Scheme = imapSchema
		}
	}
}

func (u *Url) setDefaultPort() {
	if u.Port == "" {
		if u.Scheme == imapsSchema {
			u.Port = imapsPort
		} else {
			u.Port = imapPort
		}
	}
}

func (u *Url) sanitize() {
	u.setDefaultScheme()
	u.setDefaultPort()
}

func (u *Url) validate() (errors []string) {
	if u.Scheme != imapSchema && u.Scheme != imapsSchema {
		errors = append(errors, fmt.Sprintf("Unknown scheme %q", u.Scheme))
	}

	if u.Host == "" {
		errors = append(errors, "Host not set")
	}

	return
}