| 1 |
// Copyright (c) 2014-2019 Ludovic Fauvet |
| 2 |
// Licensed under the MIT license |
| 3 |
|
| 4 |
package mirrors |
| 5 |
|
| 6 |
import ( |
| 7 |
"fmt" |
| 8 |
"math/rand" |
| 9 |
"strconv" |
| 10 |
"strings" |
| 11 |
"time" |
| 12 |
|
| 13 |
. "github.com/etix/mirrorbits/config" |
| 14 |
"github.com/etix/mirrorbits/core" |
| 15 |
"github.com/etix/mirrorbits/database" |
| 16 |
"github.com/etix/mirrorbits/filesystem" |
| 17 |
"github.com/etix/mirrorbits/network" |
| 18 |
"github.com/etix/mirrorbits/utils" |
| 19 |
"github.com/gomodule/redigo/redis" |
| 20 |
) |
| 21 |
|
| 22 |
type Protocol uint |
| 23 |
|
| 24 |
const ( |
| 25 |
UNDEFINED Protocol = iota |
| 26 |
HTTP |
| 27 |
HTTPS |
| 28 |
) |
| 29 |
|
| 30 |
func (p Protocol) String() string { |
| 31 |
switch p { |
| 32 |
case UNDEFINED: |
| 33 |
return "undefined" |
| 34 |
case HTTP: |
| 35 |
return "HTTP" |
| 36 |
case HTTPS: |
| 37 |
return "HTTPS" |
| 38 |
default: |
| 39 |
return "unknown" |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
// Mirror is the structure representing all the information about a mirror |
| 44 |
type Mirror struct { |
| 45 |
ID int `redis:"ID" yaml:"-"` |
| 46 |
Name string `redis:"name" yaml:"Name"` |
| 47 |
HttpURL string `redis:"http" yaml:"HttpURL"` |
| 48 |
RsyncURL string `redis:"rsync" yaml:"RsyncURL"` |
| 49 |
FtpURL string `redis:"ftp" yaml:"FtpURL"` |
| 50 |
SponsorName string `redis:"sponsorName" yaml:"SponsorName"` |
| 51 |
SponsorURL string `redis:"sponsorURL" yaml:"SponsorURL"` |
| 52 |
SponsorLogoURL string `redis:"sponsorLogo" yaml:"SponsorLogoURL"` |
| 53 |
AdminName string `redis:"adminName" yaml:"AdminName"` |
| 54 |
AdminEmail string `redis:"adminEmail" yaml:"AdminEmail"` |
| 55 |
CustomData string `redis:"customData" yaml:"CustomData"` |
| 56 |
ContinentOnly bool `redis:"continentOnly" yaml:"ContinentOnly"` |
| 57 |
CountryOnly bool `redis:"countryOnly" yaml:"CountryOnly"` |
| 58 |
ASOnly bool `redis:"asOnly" yaml:"ASOnly"` |
| 59 |
Score int `redis:"score" yaml:"Score"` |
| 60 |
Latitude float32 `redis:"latitude" yaml:"Latitude"` |
| 61 |
Longitude float32 `redis:"longitude" yaml:"Longitude"` |
| 62 |
ContinentCode string `redis:"continentCode" yaml:"ContinentCode"` |
| 63 |
CountryCodes string `redis:"countryCodes" yaml:"CountryCodes"` |
| 64 |
ExcludedCountryCodes string `redis:"excludedCountryCodes" yaml:"ExcludedCountryCodes"` |
| 65 |
Asnum uint `redis:"asnum" yaml:"ASNum"` |
| 66 |
Comment string `redis:"comment" yaml:"-"` |
| 67 |
Enabled bool `redis:"enabled" yaml:"Enabled"` |
| 68 |
HttpUp bool `redis:"httpUp" json:"-" yaml:"-"` |
| 69 |
HttpsUp bool `redis:"httpsUp" json:"-" yaml:"-"` |
| 70 |
HttpDownReason string `redis:"httpDownReason" json:",omitempty" yaml:"-"` |
| 71 |
HttpsDownReason string `redis:"httpsDownReason" json:",omitempty" yaml:"-"` |
| 72 |
StateSince Time `redis:"stateSince" json:",omitempty" yaml:"-"` |
| 73 |
AllowRedirects Redirects `redis:"allowredirects" json:",omitempty" yaml:"AllowRedirects"` |
| 74 |
TZOffset int64 `redis:"tzoffset" json:"-" yaml:"-"` // timezone offset in ms |
| 75 |
Distance float32 `redis:"-" yaml:"-"` |
| 76 |
CountryFields []string `redis:"-" json:"-" yaml:"-"` |
| 77 |
ExcludedCountryFields []string `redis:"-" json:"-" yaml:"-"` |
| 78 |
Filepath string `redis:"-" json:"-" yaml:"-"` |
| 79 |
Weight float32 `redis:"-" json:"-" yaml:"-"` |
| 80 |
ComputedScore int `redis:"-" yaml:"-"` |
| 81 |
LastSync Time `redis:"lastSync" yaml:"-"` |
| 82 |
LastSuccessfulSync Time `redis:"lastSuccessfulSync" yaml:"-"` |
| 83 |
LastSuccessfulSyncProtocol core.ScannerType `redis:"lastSuccessfulSyncProtocol" yaml:"-"` |
| 84 |
LastSuccessfulSyncPrecision core.Precision `redis:"lastSuccessfulSyncPrecision" yaml:"-"` |
| 85 |
LastModTime Time `redis:"lastModTime" yaml:"-"` |
| 86 |
|
| 87 |
FileInfo *filesystem.FileInfo `redis:"-" json:"-" yaml:"-"` // Details of the requested file on this specific mirror |
| 88 |
AbsoluteURL string `redis:"-" yaml:"-"` // Absolute HttpURL, guaranteed to start with a scheme |
| 89 |
ExcludeReason string `redis:"-" json:",omitempty" yaml:"-"` // Reason why the mirror was excluded |
| 90 |
} |
| 91 |
|
| 92 |
// Prepare must be called after retrieval from the database to reformat some values |
| 93 |
func (m *Mirror) Prepare() { |
| 94 |
m.CountryFields = strings.Fields(m.CountryCodes) |
| 95 |
m.ExcludedCountryFields = strings.Fields(m.ExcludedCountryCodes) |
| 96 |
} |
| 97 |
|
| 98 |
// IsHTTPOnly returns true if the mirror has an HTTP address |
| 99 |
func (m *Mirror) IsHTTPOnly() bool { |
| 100 |
return strings.HasPrefix(m.HttpURL, "http://") |
| 101 |
} |
| 102 |
|
| 103 |
// IsHTTPSOnly returns true if the mirror has an HTTPS address |
| 104 |
func (m *Mirror) IsHTTPSOnly() bool { |
| 105 |
return strings.HasPrefix(m.HttpURL, "https://") |
| 106 |
} |
| 107 |
|
| 108 |
// IsUp returns true if the mirror is up (for a mirror that supports both HTTP |
| 109 |
// and HTTPS, it means both are up) |
| 110 |
func (m *Mirror) IsUp() bool { |
| 111 |
if m.HttpUp == m.HttpsUp { |
| 112 |
return m.HttpUp |
| 113 |
} |
| 114 |
if m.IsHTTPOnly() { |
| 115 |
return m.HttpUp |
| 116 |
} |
| 117 |
if m.IsHTTPSOnly() { |
| 118 |
return m.HttpsUp |
| 119 |
} |
| 120 |
return false |
| 121 |
} |
| 122 |
|
| 123 |
// Mirrors represents a slice of Mirror |
| 124 |
type Mirrors []Mirror |
| 125 |
|
| 126 |
// Len return the number of Mirror in the slice |
| 127 |
func (s Mirrors) Len() int { return len(s) } |
| 128 |
|
| 129 |
// Swap swaps mirrors at index i and j |
| 130 |
func (s Mirrors) Swap(i, j int) { s[i], s[j] = s[j], s[i] } |
| 131 |
|
| 132 |
// ByRank is used to sort a slice of Mirror by their rank |
| 133 |
type ByRank struct { |
| 134 |
Mirrors |
| 135 |
ClientInfo network.GeoIPRecord |
| 136 |
} |
| 137 |
|
| 138 |
// Less compares two mirrors based on their rank |
| 139 |
func (m ByRank) Less(i, j int) bool { |
| 140 |
if m.ClientInfo.IsValid() { |
| 141 |
if m.ClientInfo.ASNum == m.Mirrors[i].Asnum { |
| 142 |
if m.Mirrors[i].Asnum != m.Mirrors[j].Asnum { |
| 143 |
return true |
| 144 |
} |
| 145 |
} else if m.ClientInfo.ASNum == m.Mirrors[j].Asnum { |
| 146 |
return false |
| 147 |
} |
| 148 |
|
| 149 |
//TODO Simplify me |
| 150 |
if m.ClientInfo.CountryCode != "" { |
| 151 |
if utils.IsInSlice(m.ClientInfo.CountryCode, m.Mirrors[i].CountryFields) { |
| 152 |
if !utils.IsInSlice(m.ClientInfo.CountryCode, m.Mirrors[j].CountryFields) { |
| 153 |
return true |
| 154 |
} |
| 155 |
} else if utils.IsInSlice(m.ClientInfo.CountryCode, m.Mirrors[j].CountryFields) { |
| 156 |
return false |
| 157 |
} |
| 158 |
} |
| 159 |
if m.ClientInfo.ContinentCode != "" { |
| 160 |
if m.ClientInfo.ContinentCode == m.Mirrors[i].ContinentCode { |
| 161 |
if m.ClientInfo.ContinentCode != m.Mirrors[j].ContinentCode { |
| 162 |
return true |
| 163 |
} |
| 164 |
} else if m.ClientInfo.ContinentCode == m.Mirrors[j].ContinentCode { |
| 165 |
return false |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
return m.Mirrors[i].Distance < m.Mirrors[j].Distance |
| 170 |
} |
| 171 |
// Randomize the output if we miss client info |
| 172 |
return rand.Intn(2) == 0 |
| 173 |
} |
| 174 |
|
| 175 |
// ByComputedScore is used to sort a slice of Mirror by their score |
| 176 |
type ByComputedScore struct { |
| 177 |
Mirrors |
| 178 |
} |
| 179 |
|
| 180 |
// Less compares two mirrors based on their score |
| 181 |
func (b ByComputedScore) Less(i, j int) bool { |
| 182 |
return b.Mirrors[i].ComputedScore > b.Mirrors[j].ComputedScore |
| 183 |
} |
| 184 |
|
| 185 |
// ByExcludeReason is used to sort a slice of Mirror alphabetically by their exclude reason |
| 186 |
type ByExcludeReason struct { |
| 187 |
Mirrors |
| 188 |
} |
| 189 |
|
| 190 |
// Less compares two mirrors based on their exclude reason |
| 191 |
func (b ByExcludeReason) Less(i, j int) bool { |
| 192 |
if b.Mirrors[i].ExcludeReason < b.Mirrors[j].ExcludeReason { |
| 193 |
return true |
| 194 |
} |
| 195 |
return false |
| 196 |
} |
| 197 |
|
| 198 |
// EnableMirror enables the given mirror |
| 199 |
func EnableMirror(r *database.Redis, id int) error { |
| 200 |
return SetMirrorEnabled(r, id, true) |
| 201 |
} |
| 202 |
|
| 203 |
// DisableMirror disables the given mirror |
| 204 |
func DisableMirror(r *database.Redis, id int) error { |
| 205 |
return SetMirrorEnabled(r, id, false) |
| 206 |
} |
| 207 |
|
| 208 |
// SetMirrorEnabled marks a mirror as enabled or disabled |
| 209 |
func SetMirrorEnabled(r *database.Redis, id int, state bool) error { |
| 210 |
conn := r.Get() |
| 211 |
defer conn.Close() |
| 212 |
|
| 213 |
key := fmt.Sprintf("MIRROR_%d", id) |
| 214 |
_, err := conn.Do("HSET", key, "enabled", state) |
| 215 |
|
| 216 |
// Publish update |
| 217 |
if err == nil { |
| 218 |
database.Publish(conn, database.MIRROR_UPDATE, strconv.Itoa(id)) |
| 219 |
|
| 220 |
if state == true { |
| 221 |
PushLog(r, NewLogEnabled(id)) |
| 222 |
} else { |
| 223 |
PushLog(r, NewLogDisabled(id)) |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
return err |
| 228 |
} |
| 229 |
|
| 230 |
// MarkMirrorUp marks the given mirror as up |
| 231 |
func MarkMirrorUp(r *database.Redis, id int, proto Protocol) error { |
| 232 |
return SetMirrorState(r, id, proto, true, "") |
| 233 |
} |
| 234 |
|
| 235 |
// MarkMirrorDown marks the given mirror as down |
| 236 |
func MarkMirrorDown(r *database.Redis, id int, proto Protocol, reason string) error { |
| 237 |
return SetMirrorState(r, id, proto, false, reason) |
| 238 |
} |
| 239 |
|
| 240 |
// SetMirrorState sets the state of a mirror to up or down, over HTTP or HTTPS, |
| 241 |
// with an optional reason |
| 242 |
func SetMirrorState(r *database.Redis, id int, proto Protocol, state bool, reason string) error { |
| 243 |
conn := r.Get() |
| 244 |
defer conn.Close() |
| 245 |
|
| 246 |
key := fmt.Sprintf("MIRROR_%d", id) |
| 247 |
|
| 248 |
var upField, reasonField string |
| 249 |
|
| 250 |
switch proto { |
| 251 |
case HTTP: |
| 252 |
upField, reasonField = "httpUp", "httpDownReason" |
| 253 |
case HTTPS: |
| 254 |
upField, reasonField = "httpsUp", "httpsDownReason" |
| 255 |
default: |
| 256 |
return fmt.Errorf("Unknown protocol: %s", proto) |
| 257 |
} |
| 258 |
|
| 259 |
previousState, err := redis.Bool(conn.Do("HGET", key, upField)) |
| 260 |
if err != nil && err != redis.ErrNil { |
| 261 |
return err |
| 262 |
} |
| 263 |
|
| 264 |
var args []any |
| 265 |
args = append(args, key, upField, state, reasonField, reason) |
| 266 |
|
| 267 |
if state != previousState { |
| 268 |
args = append(args, "stateSince", time.Now().Unix()) |
| 269 |
} |
| 270 |
|
| 271 |
_, err = conn.Do("HSET", args...) |
| 272 |
|
| 273 |
if err == nil { |
| 274 |
// Publish update |
| 275 |
database.Publish(conn, database.MIRROR_UPDATE, strconv.Itoa(id)) |
| 276 |
|
| 277 |
if state != previousState { |
| 278 |
PushLog(r, NewLogStateChanged(id, proto, state, reason)) |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
return err |
| 283 |
} |
| 284 |
|
| 285 |
// Results is the resulting struct of a request and is |
| 286 |
// used by the renderers to generate the final page. |
| 287 |
type Results struct { |
| 288 |
FileInfo filesystem.FileInfo |
| 289 |
IP string |
| 290 |
ClientInfo network.GeoIPRecord |
| 291 |
MirrorList Mirrors |
| 292 |
ExcludedList Mirrors `json:",omitempty"` |
| 293 |
Fallback bool `json:",omitempty"` |
| 294 |
LocalJSPath string |
| 295 |
} |
| 296 |
|
| 297 |
// Redirects is handling the per-mirror authorization of HTTP redirects |
| 298 |
type Redirects int |
| 299 |
|
| 300 |
// Allowed will return true if redirects are authorized for this mirror |
| 301 |
func (r *Redirects) Allowed() bool { |
| 302 |
switch *r { |
| 303 |
case 1: |
| 304 |
return true |
| 305 |
case 2: |
| 306 |
return false |
| 307 |
default: |
| 308 |
return GetConfig().DisallowRedirects == false |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
// MarshalYAML converts internal values to YAML |
| 313 |
func (r Redirects) MarshalYAML() (any, error) { |
| 314 |
var b *bool |
| 315 |
switch r { |
| 316 |
case 1: |
| 317 |
v := true |
| 318 |
b = &v |
| 319 |
case 2: |
| 320 |
v := false |
| 321 |
b = &v |
| 322 |
default: |
| 323 |
} |
| 324 |
return b, nil |
| 325 |
} |
| 326 |
|
| 327 |
// UnmarshalYAML converts YAML to internal values |
| 328 |
func (r *Redirects) UnmarshalYAML(unmarshal func(any) error) error { |
| 329 |
var b *bool |
| 330 |
if err := unmarshal(&b); err != nil { |
| 331 |
return err |
| 332 |
} |
| 333 |
if b == nil { |
| 334 |
*r = 0 |
| 335 |
} else if *b == true { |
| 336 |
*r = 1 |
| 337 |
} else { |
| 338 |
*r = 2 |
| 339 |
} |
| 340 |
return nil |
| 341 |
} |
| 342 |
|
| 343 |
// Time is a structure holding a time.Time object. |
| 344 |
// It is used to serialize and deserialize a time |
| 345 |
// held in a redis database. |
| 346 |
type Time struct { |
| 347 |
time.Time |
| 348 |
} |
| 349 |
|
| 350 |
// RedisArg serialize the time.Time object |
| 351 |
func (t Time) RedisArg() any { |
| 352 |
return t.UTC().Unix() |
| 353 |
} |
| 354 |
|
| 355 |
// RedisScan deserialize the time.Time object |
| 356 |
func (t *Time) RedisScan(src any) (err error) { |
| 357 |
switch src := src.(type) { |
| 358 |
case int64: |
| 359 |
t.Time = time.Unix(src, 0) |
| 360 |
case []byte: |
| 361 |
var i int64 |
| 362 |
i, err = strconv.ParseInt(string(src), 10, 64) |
| 363 |
t.Time = time.Unix(i, 0) |
| 364 |
default: |
| 365 |
err = fmt.Errorf("cannot convert from %T to %T", src, t) |
| 366 |
} |
| 367 |
return err |
| 368 |
} |
| 369 |
|
| 370 |
// FromTime returns a Time from a time.Time |
| 371 |
func (t Time) FromTime(time time.Time) Time { |
| 372 |
return Time{ |
| 373 |
Time: time, |
| 374 |
} |
| 375 |
} |