forked from libdns/alidns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaliSimple.go
More file actions
238 lines (212 loc) · 5.36 KB
/
aliSimple.go
File metadata and controls
238 lines (212 loc) · 5.36 KB
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package alidns
import (
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const defRegID string = "cn-hangzhou"
const addrOfAPI string = "%s://alidns.aliyuncs.com/"
// CredInfo implements param of the crediential
type CredInfo struct {
AccKeyID string `json:"access_key_id"`
AccKeySecret string `json:"access_key_secret"`
RegionID string `json:"region_id,omitempty"`
RAMRole string `json:"ram_role,omitempty"`
SecurityToken string `json:"security_token,omitempty"`
}
// AliClient abstructs the alidns.Client
type aliClient struct {
mutex sync.Mutex
APIHost string
reqMap []vKey
sigStr string
sigPwd string
}
// VKey implments of K-V struct
type vKey struct {
key string
val string
}
func newCredInfo(pAccKeyID, pAccKeySecret, pRegionID, pRAMRole, pSecurityToken string) *CredInfo {
if pAccKeyID == "" || pAccKeySecret == "" {
return nil
}
if len(pRegionID) == 0 {
pRegionID = defRegID
}
return &CredInfo{
AccKeyID: pAccKeyID,
AccKeySecret: pAccKeySecret,
RegionID: pRegionID,
RAMRole: pRAMRole,
SecurityToken: pSecurityToken,
}
}
func (c *mClient) getAliClient(cred *CredInfo, zone string) error {
cl0, err := c.aClient.getAliClientSche(cred, "https")
if err != nil {
return err
}
c.aClient = cl0
if zone != "" {
c.getDomainInfo(context.Background(), strings.Trim(zone, "."))
}
return nil
}
func (c *mClient) applyReq(cxt context.Context, method string, body io.Reader) (*http.Request, error) {
if method == "" {
method = "GET"
}
c0 := c.aClient
c0.signReq(method)
si0 := fmt.Sprintf("%s=%s", "Signature", strings.ReplaceAll(c0.sigStr, "+", "%2B"))
mURL := fmt.Sprintf("%s?%s&%s", c0.APIHost, c0.reqMapToStr(), si0)
req, err := http.NewRequestWithContext(cxt, method, mURL, body)
req.Header.Set("Accept", "application/json")
if err != nil {
return &http.Request{}, err
}
return req, nil
}
func (c *aliClient) getAliClientSche(cred *CredInfo, scheme string) (*aliClient, error) {
if cred == nil {
return &aliClient{}, errors.New("alidns: credentials missing")
}
if scheme == "" {
scheme = "http"
}
cl0 := &aliClient{
APIHost: fmt.Sprintf(addrOfAPI, scheme),
reqMap: []vKey{
{key: "AccessKeyId", val: cred.AccKeyID},
{key: "Format", val: "JSON"},
{key: "SignatureMethod", val: "HMAC-SHA1"},
{key: "SignatureNonce", val: fmt.Sprintf("%d", time.Now().UnixNano())},
{key: "SignatureVersion", val: "1.0"},
{key: "Timestamp", val: time.Now().UTC().Format("2006-01-02T15:04:05Z")},
{key: "Version", val: "2015-01-09"},
},
sigStr: "",
sigPwd: cred.AccKeySecret,
}
// Add SecurityToken if provided
if cred.SecurityToken != "" {
cl0.reqMap = append(cl0.reqMap, vKey{key: "SecurityToken", val: cred.SecurityToken})
}
// Add RAMRole if provided
if cred.RAMRole != "" {
cl0.reqMap = append(cl0.reqMap, vKey{key: "RoleArn", val: cred.RAMRole})
}
return cl0, nil
}
func (c *aliClient) signReq(method string) error {
if c.sigPwd == "" || len(c.reqMap) == 0 {
return errors.New("alidns: AccessKeySecret or Request(includes AccessKeyId) is Misssing")
}
sort.Sort(byKey(c.reqMap))
str := c.reqMapToStr()
str = c.reqStrToSign(str, method)
c.sigStr = signStr(str, c.sigPwd)
return nil
}
func (c *aliClient) addReqBody(key string, value string) error {
if key == "" && value == "" {
return errors.New("key or value is Empty")
}
el := vKey{key: key, val: value}
c.mutex.Lock()
for _, el0 := range c.reqMap {
if el.key == el0.key {
c.mutex.Unlock()
return errors.New("duplicate keys")
}
}
c.reqMap = append(c.reqMap, el)
c.mutex.Unlock()
return nil
}
func (c *aliClient) setReqBody(key string, value string) error {
if key == "" && value == "" {
return errors.New("key or value is Empty")
}
el := vKey{key: key, val: value}
c.mutex.Lock()
for in, el0 := range c.reqMap {
if el.key == el0.key {
(c.reqMap)[in] = el
c.mutex.Unlock()
return nil
}
}
c.mutex.Unlock()
return fmt.Errorf("entry of %s not found", key)
}
func (c *aliClient) reqStrToSign(ins string, method string) string {
if method == "" {
method = "GET"
}
ecReq := urlEncode(ins)
return fmt.Sprintf("%s&%s&%s", method, "%2F", ecReq)
}
func (c *aliClient) reqMapToStr() string {
m0 := c.reqMap
urlEn := url.Values{}
c.mutex.Lock()
for _, o := range m0 {
urlEn.Add(o.key, o.val)
}
c.mutex.Unlock()
return urlEn.Encode()
}
func signStr(ins string, sec string) string {
sec = sec + "&"
hm := hmac.New(sha1.New, []byte(sec))
hm.Write([]byte(ins))
sum := hm.Sum(nil)
return base64.StdEncoding.EncodeToString(sum)
}
func goVer() float64 {
verStr := runtime.Version()
verStr, _ = strings.CutPrefix(verStr, "go")
verStrs := strings.Split(verStr, ".")
var result float64
for i, v := range verStrs {
tmp, _ := strconv.ParseFloat(v, 32)
result = tmp * (1 / math.Pow10(i))
}
return result
}
func urlEncode(ins string) string {
str0 := ins
str0 = strings.Replace(str0, "+", "%20", -1)
str0 = strings.Replace(str0, "*", "%2A", -1)
str0 = strings.Replace(str0, "%7E", "~", -1)
str0 = url.QueryEscape(str0)
if goVer() > 1.20 {
str0 = strings.Replace(str0, "%26", "&", -1)
}
return str0
}
type byKey []vKey
func (v byKey) Len() int {
return len(v)
}
func (v byKey) Swap(i, j int) {
v[i], v[j] = v[j], v[i]
}
func (v byKey) Less(i, j int) bool {
return v[i].key < v[j].key
}