-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathmirrors.go
375 lines (323 loc) · 11.3 KB
/
mirrors.go
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// Copyright (c) 2014-2019 Ludovic Fauvet
// Licensed under the MIT license
package mirrors
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
. "github.com/etix/mirrorbits/config"
"github.com/etix/mirrorbits/core"
"github.com/etix/mirrorbits/database"
"github.com/etix/mirrorbits/filesystem"
"github.com/etix/mirrorbits/network"
"github.com/etix/mirrorbits/utils"
"github.com/gomodule/redigo/redis"
)
type Protocol uint
const (
UNDEFINED Protocol = iota
HTTP
HTTPS
)
func (p Protocol) String() string {
switch p {
case UNDEFINED:
return "undefined"
case HTTP:
return "HTTP"
case HTTPS:
return "HTTPS"
default:
return "unknown"
}
}
// Mirror is the structure representing all the information about a mirror
type Mirror struct {
ID int `redis:"ID" yaml:"-"`
Name string `redis:"name" yaml:"Name"`
HttpURL string `redis:"http" yaml:"HttpURL"`
RsyncURL string `redis:"rsync" yaml:"RsyncURL"`
FtpURL string `redis:"ftp" yaml:"FtpURL"`
SponsorName string `redis:"sponsorName" yaml:"SponsorName"`
SponsorURL string `redis:"sponsorURL" yaml:"SponsorURL"`
SponsorLogoURL string `redis:"sponsorLogo" yaml:"SponsorLogoURL"`
AdminName string `redis:"adminName" yaml:"AdminName"`
AdminEmail string `redis:"adminEmail" yaml:"AdminEmail"`
CustomData string `redis:"customData" yaml:"CustomData"`
ContinentOnly bool `redis:"continentOnly" yaml:"ContinentOnly"`
CountryOnly bool `redis:"countryOnly" yaml:"CountryOnly"`
ASOnly bool `redis:"asOnly" yaml:"ASOnly"`
Score int `redis:"score" yaml:"Score"`
Latitude float32 `redis:"latitude" yaml:"Latitude"`
Longitude float32 `redis:"longitude" yaml:"Longitude"`
ContinentCode string `redis:"continentCode" yaml:"ContinentCode"`
CountryCodes string `redis:"countryCodes" yaml:"CountryCodes"`
ExcludedCountryCodes string `redis:"excludedCountryCodes" yaml:"ExcludedCountryCodes"`
Asnum uint `redis:"asnum" yaml:"ASNum"`
Comment string `redis:"comment" yaml:"-"`
Enabled bool `redis:"enabled" yaml:"Enabled"`
HttpUp bool `redis:"httpUp" json:"-" yaml:"-"`
HttpsUp bool `redis:"httpsUp" json:"-" yaml:"-"`
HttpDownReason string `redis:"httpDownReason" json:",omitempty" yaml:"-"`
HttpsDownReason string `redis:"httpsDownReason" json:",omitempty" yaml:"-"`
StateSince Time `redis:"stateSince" json:",omitempty" yaml:"-"`
AllowRedirects Redirects `redis:"allowredirects" json:",omitempty" yaml:"AllowRedirects"`
TZOffset int64 `redis:"tzoffset" json:"-" yaml:"-"` // timezone offset in ms
Distance float32 `redis:"-" yaml:"-"`
CountryFields []string `redis:"-" json:"-" yaml:"-"`
ExcludedCountryFields []string `redis:"-" json:"-" yaml:"-"`
Filepath string `redis:"-" json:"-" yaml:"-"`
Weight float32 `redis:"-" json:"-" yaml:"-"`
ComputedScore int `redis:"-" yaml:"-"`
LastSync Time `redis:"lastSync" yaml:"-"`
LastSuccessfulSync Time `redis:"lastSuccessfulSync" yaml:"-"`
LastSuccessfulSyncProtocol core.ScannerType `redis:"lastSuccessfulSyncProtocol" yaml:"-"`
LastSuccessfulSyncPrecision core.Precision `redis:"lastSuccessfulSyncPrecision" yaml:"-"`
LastModTime Time `redis:"lastModTime" yaml:"-"`
FileInfo *filesystem.FileInfo `redis:"-" json:"-" yaml:"-"` // Details of the requested file on this specific mirror
AbsoluteURL string `redis:"-" yaml:"-"` // Absolute HttpURL, guaranteed to start with a scheme
ExcludeReason string `redis:"-" json:",omitempty" yaml:"-"` // Reason why the mirror was excluded
}
// Prepare must be called after retrieval from the database to reformat some values
func (m *Mirror) Prepare() {
m.CountryFields = strings.Fields(m.CountryCodes)
m.ExcludedCountryFields = strings.Fields(m.ExcludedCountryCodes)
}
// IsHTTPOnly returns true if the mirror has an HTTP address
func (m *Mirror) IsHTTPOnly() bool {
return strings.HasPrefix(m.HttpURL, "http://")
}
// IsHTTPSOnly returns true if the mirror has an HTTPS address
func (m *Mirror) IsHTTPSOnly() bool {
return strings.HasPrefix(m.HttpURL, "https://")
}
// IsUp returns true if the mirror is up (for a mirror that supports both HTTP
// and HTTPS, it means both are up)
func (m *Mirror) IsUp() bool {
if m.HttpUp == m.HttpsUp {
return m.HttpUp
}
if m.IsHTTPOnly() {
return m.HttpUp
}
if m.IsHTTPSOnly() {
return m.HttpsUp
}
return false
}
// Mirrors represents a slice of Mirror
type Mirrors []Mirror
// Len return the number of Mirror in the slice
func (s Mirrors) Len() int { return len(s) }
// Swap swaps mirrors at index i and j
func (s Mirrors) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// ByRank is used to sort a slice of Mirror by their rank
type ByRank struct {
Mirrors
ClientInfo network.GeoIPRecord
}
// Less compares two mirrors based on their rank
func (m ByRank) Less(i, j int) bool {
if m.ClientInfo.IsValid() {
if m.ClientInfo.ASNum == m.Mirrors[i].Asnum {
if m.Mirrors[i].Asnum != m.Mirrors[j].Asnum {
return true
}
} else if m.ClientInfo.ASNum == m.Mirrors[j].Asnum {
return false
}
//TODO Simplify me
if m.ClientInfo.CountryCode != "" {
if utils.IsInSlice(m.ClientInfo.CountryCode, m.Mirrors[i].CountryFields) {
if !utils.IsInSlice(m.ClientInfo.CountryCode, m.Mirrors[j].CountryFields) {
return true
}
} else if utils.IsInSlice(m.ClientInfo.CountryCode, m.Mirrors[j].CountryFields) {
return false
}
}
if m.ClientInfo.ContinentCode != "" {
if m.ClientInfo.ContinentCode == m.Mirrors[i].ContinentCode {
if m.ClientInfo.ContinentCode != m.Mirrors[j].ContinentCode {
return true
}
} else if m.ClientInfo.ContinentCode == m.Mirrors[j].ContinentCode {
return false
}
}
return m.Mirrors[i].Distance < m.Mirrors[j].Distance
}
// Randomize the output if we miss client info
return rand.Intn(2) == 0
}
// ByComputedScore is used to sort a slice of Mirror by their score
type ByComputedScore struct {
Mirrors
}
// Less compares two mirrors based on their score
func (b ByComputedScore) Less(i, j int) bool {
return b.Mirrors[i].ComputedScore > b.Mirrors[j].ComputedScore
}
// ByExcludeReason is used to sort a slice of Mirror alphabetically by their exclude reason
type ByExcludeReason struct {
Mirrors
}
// Less compares two mirrors based on their exclude reason
func (b ByExcludeReason) Less(i, j int) bool {
if b.Mirrors[i].ExcludeReason < b.Mirrors[j].ExcludeReason {
return true
}
return false
}
// EnableMirror enables the given mirror
func EnableMirror(r *database.Redis, id int) error {
return SetMirrorEnabled(r, id, true)
}
// DisableMirror disables the given mirror
func DisableMirror(r *database.Redis, id int) error {
return SetMirrorEnabled(r, id, false)
}
// SetMirrorEnabled marks a mirror as enabled or disabled
func SetMirrorEnabled(r *database.Redis, id int, state bool) error {
conn := r.Get()
defer conn.Close()
key := fmt.Sprintf("MIRROR_%d", id)
_, err := conn.Do("HMSET", key, "enabled", state)
// Publish update
if err == nil {
database.Publish(conn, database.MIRROR_UPDATE, strconv.Itoa(id))
if state == true {
PushLog(r, NewLogEnabled(id))
} else {
PushLog(r, NewLogDisabled(id))
}
}
return err
}
// MarkMirrorUp marks the given mirror as up
func MarkMirrorUp(r *database.Redis, id int, proto Protocol) error {
return SetMirrorState(r, id, proto, true, "")
}
// MarkMirrorDown marks the given mirror as down
func MarkMirrorDown(r *database.Redis, id int, proto Protocol, reason string) error {
return SetMirrorState(r, id, proto, false, reason)
}
// SetMirrorState sets the state of a mirror to up or down, over HTTP or HTTPS,
// with an optional reason
func SetMirrorState(r *database.Redis, id int, proto Protocol, state bool, reason string) error {
conn := r.Get()
defer conn.Close()
key := fmt.Sprintf("MIRROR_%d", id)
var upField, reasonField string
switch proto {
case HTTP:
upField, reasonField = "httpUp", "httpDownReason"
case HTTPS:
upField, reasonField = "httpsUp", "httpsDownReason"
default:
return fmt.Errorf("Unknown protocol: %s", proto)
}
previousState, err := redis.Bool(conn.Do("HGET", key, upField))
if err != nil && err != redis.ErrNil {
return err
}
var args []interface{}
args = append(args, key, upField, state, reasonField, reason)
if state != previousState {
args = append(args, "stateSince", time.Now().Unix())
}
_, err = conn.Do("HMSET", args...)
if err == nil {
// Publish update
database.Publish(conn, database.MIRROR_UPDATE, strconv.Itoa(id))
if state != previousState {
PushLog(r, NewLogStateChanged(id, proto, state, reason))
}
}
return err
}
// Results is the resulting struct of a request and is
// used by the renderers to generate the final page.
type Results struct {
FileInfo filesystem.FileInfo
IP string
ClientInfo network.GeoIPRecord
MirrorList Mirrors
ExcludedList Mirrors `json:",omitempty"`
Fallback bool `json:",omitempty"`
LocalJSPath string
}
// Redirects is handling the per-mirror authorization of HTTP redirects
type Redirects int
// Allowed will return true if redirects are authorized for this mirror
func (r *Redirects) Allowed() bool {
switch *r {
case 1:
return true
case 2:
return false
default:
return GetConfig().DisallowRedirects == false
}
}
// MarshalYAML converts internal values to YAML
func (r Redirects) MarshalYAML() (interface{}, error) {
var b *bool
switch r {
case 1:
v := true
b = &v
case 2:
v := false
b = &v
default:
}
return b, nil
}
// UnmarshalYAML converts YAML to internal values
func (r *Redirects) UnmarshalYAML(unmarshal func(interface{}) error) error {
var b *bool
if err := unmarshal(&b); err != nil {
return err
}
if b == nil {
*r = 0
} else if *b == true {
*r = 1
} else {
*r = 2
}
return nil
}
// Time is a structure holding a time.Time object.
// It is used to serialize and deserialize a time
// held in a redis database.
type Time struct {
time.Time
}
// RedisArg serialize the time.Time object
func (t Time) RedisArg() interface{} {
return t.UTC().Unix()
}
// RedisScan deserialize the time.Time object
func (t *Time) RedisScan(src interface{}) (err error) {
switch src := src.(type) {
case int64:
t.Time = time.Unix(src, 0)
case []byte:
var i int64
i, err = strconv.ParseInt(string(src), 10, 64)
t.Time = time.Unix(i, 0)
default:
err = fmt.Errorf("cannot convert from %T to %T", src, t)
}
return err
}
// FromTime returns a Time from a time.Time
func (t Time) FromTime(time time.Time) Time {
return Time{
Time: time,
}
}