| 1 |
// Copyright (c) 2014-2019 Ludovic Fauvet |
| 2 |
// Licensed under the MIT license |
| 3 |
|
| 4 |
package http |
| 5 |
|
| 6 |
import ( |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"math" |
| 10 |
"math/rand" |
| 11 |
"sort" |
| 12 |
"strings" |
| 13 |
"time" |
| 14 |
|
| 15 |
. "github.com/etix/mirrorbits/config" |
| 16 |
"github.com/etix/mirrorbits/filesystem" |
| 17 |
"github.com/etix/mirrorbits/mirrors" |
| 18 |
"github.com/etix/mirrorbits/network" |
| 19 |
"github.com/etix/mirrorbits/utils" |
| 20 |
) |
| 21 |
|
| 22 |
var ( |
| 23 |
ErrInvalidFileInfo = errors.New("Invalid file info (modtime is zero)") |
| 24 |
) |
| 25 |
|
| 26 |
type mirrorSelection interface { |
| 27 |
// Selection must return an ordered list of selected mirror, |
| 28 |
// a list of rejected mirrors and and an error code. |
| 29 |
Selection(*Context, *mirrors.Cache, *filesystem.FileInfo, network.GeoIPRecord) (mirrors.Mirrors, mirrors.Mirrors, error) |
| 30 |
} |
| 31 |
|
| 32 |
// DefaultEngine is the default algorithm used for mirror selection |
| 33 |
type DefaultEngine struct{} |
| 34 |
|
| 35 |
// Selection returns an ordered list of selected mirror, a list of rejected mirrors and and an error code |
| 36 |
func (h DefaultEngine) Selection(ctx *Context, cache *mirrors.Cache, fileInfo *filesystem.FileInfo, clientInfo network.GeoIPRecord) (mlist mirrors.Mirrors, excluded mirrors.Mirrors, err error) { |
| 37 |
// Bail out early if we don't have valid file details |
| 38 |
if fileInfo.ModTime.IsZero() { |
| 39 |
err = ErrInvalidFileInfo |
| 40 |
return |
| 41 |
} |
| 42 |
|
| 43 |
// Prepare and return the list of all potential mirrors |
| 44 |
mlist, err = cache.GetMirrors(fileInfo.Path, clientInfo) |
| 45 |
if err != nil { |
| 46 |
return |
| 47 |
} |
| 48 |
|
| 49 |
// Filter the list of mirrors |
| 50 |
mlist, excluded, closestMirror, farthestMirror := Filter(mlist, ctx.SecureOption(), fileInfo, clientInfo) |
| 51 |
|
| 52 |
if !clientInfo.IsValid() { |
| 53 |
// Shuffle the list |
| 54 |
//XXX Should we use the fallbacks instead? |
| 55 |
for i := range mlist { |
| 56 |
j := rand.Intn(i + 1) |
| 57 |
mlist[i], mlist[j] = mlist[j], mlist[i] |
| 58 |
} |
| 59 |
|
| 60 |
// Shortcut |
| 61 |
if !ctx.IsMirrorlist() { |
| 62 |
// Reduce the number of mirrors to process |
| 63 |
mlist = mlist[:utils.Min(5, len(mlist))] |
| 64 |
} |
| 65 |
return |
| 66 |
} |
| 67 |
|
| 68 |
// We're not interested in divisions by zero |
| 69 |
if closestMirror == 0 { |
| 70 |
closestMirror = math.SmallestNonzeroFloat32 |
| 71 |
} |
| 72 |
|
| 73 |
/* Weight distribution for random selection [Probabilistic weight] */ |
| 74 |
|
| 75 |
// Compute score for each mirror and return the mirrors eligible for weight distribution. |
| 76 |
// This includes: |
| 77 |
// - mirrors found in a 1.5x (configurable) range from the closest mirror |
| 78 |
// - mirrors targeting the given country (as primary or secondary) |
| 79 |
// - mirrors being in the same AS number |
| 80 |
totalScore := 0 |
| 81 |
baseScore := int(farthestMirror) |
| 82 |
weights := map[int]int{} |
| 83 |
for i := 0; i < len(mlist); i++ { |
| 84 |
m := &mlist[i] |
| 85 |
|
| 86 |
if m.Distance > closestMirror*GetConfig().WeightDistributionRange { |
| 87 |
log.Debugf("[%s] ignored: too far (%.1f; maximum: %.1f)", m.Name, m.Distance, closestMirror*GetConfig().WeightDistributionRange) |
| 88 |
m.ComputedScore = 0 |
| 89 |
continue |
| 90 |
} |
| 91 |
|
| 92 |
if GetConfig().GeographicalSort { |
| 93 |
m.ComputedScore = baseScore - int(m.Distance) + 1 |
| 94 |
|
| 95 |
if m.Distance <= closestMirror*GetConfig().WeightDistributionRange { |
| 96 |
score := (float32(baseScore) - m.Distance) |
| 97 |
if !network.IsPrimaryCountry(clientInfo, m.CountryFields) { |
| 98 |
score /= 2 |
| 99 |
m.ComputedScore += int(score) |
| 100 |
} else if network.IsPrimaryCountry(clientInfo, m.CountryFields) { |
| 101 |
m.ComputedScore += int(float32(baseScore) - (m.Distance * 5)) |
| 102 |
} else if network.IsAdditionalCountry(clientInfo, m.CountryFields) { |
| 103 |
m.ComputedScore += int(float32(baseScore) - closestMirror) |
| 104 |
} |
| 105 |
|
| 106 |
if m.Asnum == clientInfo.ASNum { |
| 107 |
m.ComputedScore += baseScore / 2 |
| 108 |
} |
| 109 |
|
| 110 |
floatingScore := float64(m.ComputedScore) + (float64(m.ComputedScore) * (float64(m.Score) / 100)) + 0.5 |
| 111 |
|
| 112 |
// The minimum allowed score is 1 |
| 113 |
m.ComputedScore = int(math.Max(floatingScore, 1)) |
| 114 |
|
| 115 |
if m.ComputedScore > baseScore { |
| 116 |
// The weight must always be > 0 to not break the randomization below |
| 117 |
totalScore += m.ComputedScore - baseScore |
| 118 |
weights[m.ID] = m.ComputedScore - baseScore |
| 119 |
} |
| 120 |
} |
| 121 |
} else { // GetConfig().GeographicalSort == false |
| 122 |
if m.Score <= 0 { |
| 123 |
m.ComputedScore = 0 |
| 124 |
} else { |
| 125 |
totalScore += m.Score |
| 126 |
m.Weight = float32(m.Score) |
| 127 |
m.ComputedScore = m.Score |
| 128 |
weights[m.ID] = m.Score |
| 129 |
} |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
// Get the final number of mirrors selected for weight distribution |
| 134 |
selected := len(weights) |
| 135 |
|
| 136 |
// Sort mirrors by computed score |
| 137 |
sort.Sort(mirrors.ByComputedScore{Mirrors: mlist}) |
| 138 |
|
| 139 |
if selected > 1 { |
| 140 |
|
| 141 |
if ctx.IsMirrorlist() { |
| 142 |
// Don't reorder the results, just set the percentage |
| 143 |
for i := 0; i < selected; i++ { |
| 144 |
id := mlist[i].ID |
| 145 |
for j := 0; j < len(mlist); j++ { |
| 146 |
if mlist[j].ID == id { |
| 147 |
mlist[j].Weight = float32(float64(weights[id]) * 100 / float64(totalScore)) |
| 148 |
break |
| 149 |
} |
| 150 |
} |
| 151 |
} |
| 152 |
} else { |
| 153 |
// Randomize the order of the selected mirrors considering their weights |
| 154 |
weightedMirrors := make([]mirrors.Mirror, selected) |
| 155 |
rest := totalScore |
| 156 |
for i := 0; i < selected; i++ { |
| 157 |
var id int |
| 158 |
rv := rand.Int31n(int32(rest)) |
| 159 |
s := 0 |
| 160 |
for k, v := range weights { |
| 161 |
s += v |
| 162 |
if int32(s) > rv { |
| 163 |
id = k |
| 164 |
break |
| 165 |
} |
| 166 |
} |
| 167 |
for _, m := range mlist { |
| 168 |
if m.ID == id { |
| 169 |
m.Weight = float32(float64(weights[id]) * 100 / float64(totalScore)) |
| 170 |
weightedMirrors[i] = m |
| 171 |
break |
| 172 |
} |
| 173 |
} |
| 174 |
rest -= weights[id] |
| 175 |
delete(weights, id) |
| 176 |
} |
| 177 |
|
| 178 |
// Replace the head of the list by its reordered counterpart |
| 179 |
mlist = append(weightedMirrors, mlist[selected:]...) |
| 180 |
|
| 181 |
// Reduce the number of mirrors to return |
| 182 |
v := math.Min(math.Min(5, float64(selected)), float64(len(mlist))) |
| 183 |
mlist = mlist[:int(v)] |
| 184 |
} |
| 185 |
} else if selected == 1 && len(mlist) > 0 { |
| 186 |
mlist[0].Weight = 100 |
| 187 |
} |
| 188 |
return |
| 189 |
} |
| 190 |
|
| 191 |
// Filter mirror list, return the list of mirrors candidates for redirection, |
| 192 |
// and the list of mirrors that were excluded. Also return the distance of the |
| 193 |
// closest and farthest mirrors. |
| 194 |
func Filter(mlist mirrors.Mirrors, secureOption SecureOption, fileInfo *filesystem.FileInfo, clientInfo network.GeoIPRecord) (accepted mirrors.Mirrors, excluded mirrors.Mirrors, closestMirror float32, farthestMirror float32) { |
| 195 |
// Check if this file is allowed to be outdated |
| 196 |
checkSize := true |
| 197 |
maxOutdated := time.Duration(0) |
| 198 |
config := GetConfig().AllowOutdatedFiles |
| 199 |
for _, c := range config { |
| 200 |
if strings.HasPrefix(fileInfo.Path, c.Prefix) { |
| 201 |
checkSize = false |
| 202 |
maxOutdated = time.Duration(c.Minutes) * time.Minute |
| 203 |
break |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
accepted = make([]mirrors.Mirror, 0, len(mlist)) |
| 208 |
excluded = make([]mirrors.Mirror, 0, len(mlist)) |
| 209 |
|
| 210 |
for _, m := range mlist { |
| 211 |
// Is it enabled? |
| 212 |
if !m.Enabled { |
| 213 |
m.ExcludeReason = "Disabled" |
| 214 |
goto discard |
| 215 |
} |
| 216 |
|
| 217 |
// Is the procol requested supported by the mirror? |
| 218 |
// Is the mirror up for this protocol? |
| 219 |
switch secureOption { |
| 220 |
case WITHTLS: |
| 221 |
// HTTPS explicitly requested |
| 222 |
m.AbsoluteURL = ensureAbsolute(m.HttpURL, "https") |
| 223 |
httpsSupported := !strings.HasPrefix(m.HttpURL, "http://") |
| 224 |
if !httpsSupported { |
| 225 |
m.ExcludeReason = "Not HTTPS" |
| 226 |
} else if !m.HttpsUp { |
| 227 |
m.ExcludeReason = either(m.HttpsDownReason, "Down") |
| 228 |
} else { |
| 229 |
break |
| 230 |
} |
| 231 |
goto discard |
| 232 |
case WITHOUTTLS: |
| 233 |
// HTTP explicitly requested |
| 234 |
m.AbsoluteURL = ensureAbsolute(m.HttpURL, "http") |
| 235 |
httpSupported := !strings.HasPrefix(m.HttpURL, "https://") |
| 236 |
if !httpSupported { |
| 237 |
m.ExcludeReason = "Not HTTP" |
| 238 |
} else if !m.HttpUp { |
| 239 |
m.ExcludeReason = either(m.HttpDownReason, "Down") |
| 240 |
} else { |
| 241 |
break |
| 242 |
} |
| 243 |
goto discard |
| 244 |
default: |
| 245 |
// Any protocol will do - favor HTTPS if avail |
| 246 |
var httpReason, httpsReason string |
| 247 |
|
| 248 |
m.AbsoluteURL = ensureAbsolute(m.HttpURL, "https") |
| 249 |
httpsSupported := !strings.HasPrefix(m.HttpURL, "http://") |
| 250 |
if !httpsSupported { |
| 251 |
httpsReason = "Not HTTPS" |
| 252 |
} else if !m.HttpsUp { |
| 253 |
httpsReason = either(m.HttpsDownReason, "Down") |
| 254 |
} else { |
| 255 |
break |
| 256 |
} |
| 257 |
|
| 258 |
m.AbsoluteURL = ensureAbsolute(m.HttpURL, "http") |
| 259 |
httpSupported := !strings.HasPrefix(m.HttpURL, "https://") |
| 260 |
if !httpSupported { |
| 261 |
httpReason = "Not HTTP" |
| 262 |
} else if !m.HttpUp { |
| 263 |
httpReason = either(m.HttpDownReason, "Down") |
| 264 |
} else { |
| 265 |
break |
| 266 |
} |
| 267 |
|
| 268 |
if httpReason == httpsReason { |
| 269 |
m.ExcludeReason = httpReason |
| 270 |
} else { |
| 271 |
m.ExcludeReason = httpReason + " / " + httpsReason |
| 272 |
} |
| 273 |
goto discard |
| 274 |
} |
| 275 |
|
| 276 |
// Is it the same size / modtime as source? |
| 277 |
if m.FileInfo != nil { |
| 278 |
if checkSize && m.FileInfo.Size != fileInfo.Size { |
| 279 |
m.ExcludeReason = "File size mismatch" |
| 280 |
goto discard |
| 281 |
} |
| 282 |
if !m.FileInfo.ModTime.IsZero() { |
| 283 |
mModTime := m.FileInfo.ModTime |
| 284 |
if GetConfig().FixTimezoneOffsets { |
| 285 |
offset := time.Duration(m.TZOffset) * time.Millisecond |
| 286 |
mModTime = mModTime.Add(offset) |
| 287 |
} |
| 288 |
precision := m.LastSuccessfulSyncPrecision.Duration() |
| 289 |
mModTime = mModTime.Truncate(precision) |
| 290 |
lModTime := fileInfo.ModTime.Truncate(precision) |
| 291 |
delta := lModTime.Sub(mModTime) |
| 292 |
if delta < 0 || delta > maxOutdated { |
| 293 |
m.ExcludeReason = fmt.Sprintf("Mod time mismatch (diff: %s)", delta) |
| 294 |
goto discard |
| 295 |
} |
| 296 |
} |
| 297 |
} |
| 298 |
// Is it configured to serve its continent only? |
| 299 |
if m.ContinentOnly { |
| 300 |
if !clientInfo.IsValid() || clientInfo.ContinentCode != m.ContinentCode { |
| 301 |
m.ExcludeReason = "Continent only" |
| 302 |
goto discard |
| 303 |
} |
| 304 |
} |
| 305 |
// Is it configured to serve its country only? |
| 306 |
if m.CountryOnly { |
| 307 |
if !clientInfo.IsValid() || !utils.IsInSlice(clientInfo.CountryCode, m.CountryFields) { |
| 308 |
m.ExcludeReason = "Country only" |
| 309 |
goto discard |
| 310 |
} |
| 311 |
} |
| 312 |
// Is it in the same AS number? |
| 313 |
if m.ASOnly { |
| 314 |
if !clientInfo.IsValid() || clientInfo.ASNum != m.Asnum { |
| 315 |
m.ExcludeReason = "AS only" |
| 316 |
goto discard |
| 317 |
} |
| 318 |
} |
| 319 |
// Is the user's country code allowed on this mirror? |
| 320 |
if clientInfo.IsValid() && utils.IsInSlice(clientInfo.CountryCode, m.ExcludedCountryFields) { |
| 321 |
m.ExcludeReason = "User's country restriction" |
| 322 |
goto discard |
| 323 |
} |
| 324 |
// Keep track of the closest and farthest mirrors |
| 325 |
if len(accepted) == 0 { |
| 326 |
closestMirror = m.Distance |
| 327 |
} else if m.Distance < closestMirror { |
| 328 |
closestMirror = m.Distance |
| 329 |
} |
| 330 |
if m.Distance > farthestMirror { |
| 331 |
farthestMirror = m.Distance |
| 332 |
} |
| 333 |
accepted = append(accepted, m) |
| 334 |
continue |
| 335 |
discard: |
| 336 |
excluded = append(excluded, m) |
| 337 |
} |
| 338 |
|
| 339 |
return |
| 340 |
} |
| 341 |
|
| 342 |
// ensureAbsolute returns the url 'as is' if it's absolute (ie. it starts with |
| 343 |
// a scheme), otherwise it prepends '<scheme>://' and returns the result. |
| 344 |
func ensureAbsolute(url string, scheme string) string { |
| 345 |
if utils.HasAnyPrefix(url, "http://", "https://") { |
| 346 |
return url |
| 347 |
} |
| 348 |
return scheme + "://" + url |
| 349 |
} |
| 350 |
|
| 351 |
// either returns s if it's not empty, d otherwise |
| 352 |
func either(s string, d string) string { |
| 353 |
if s != "" { |
| 354 |
return s |
| 355 |
} |
| 356 |
return d |
| 357 |
} |