| 1 |
// Copyright 2012-2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"context" |
| 19 |
"encoding/json" |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"math" |
| 23 |
"math/bits" |
| 24 |
"net" |
| 25 |
"net/url" |
| 26 |
"reflect" |
| 27 |
"runtime" |
| 28 |
"strconv" |
| 29 |
"strings" |
| 30 |
"time" |
| 31 |
) |
| 32 |
|
| 33 |
// This map is used to store URLs string as the key with a reference count as |
| 34 |
// the value. This is used to handle gossiped URLs such as connect_urls, etc.. |
| 35 |
type refCountedUrlSet map[string]int |
| 36 |
|
| 37 |
// Ascii numbers 0-9 |
| 38 |
const ( |
| 39 |
asciiZero = 48 |
| 40 |
asciiNine = 57 |
| 41 |
) |
| 42 |
|
| 43 |
func versionComponents(version string) (major, minor, patch int, err error) { |
| 44 |
m := semVerRe.FindStringSubmatch(version) |
| 45 |
if len(m) == 0 { |
| 46 |
return 0, 0, 0, errors.New("invalid semver") |
| 47 |
} |
| 48 |
major, err = strconv.Atoi(m[1]) |
| 49 |
if err != nil { |
| 50 |
return -1, -1, -1, err |
| 51 |
} |
| 52 |
minor, err = strconv.Atoi(m[2]) |
| 53 |
if err != nil { |
| 54 |
return -1, -1, -1, err |
| 55 |
} |
| 56 |
patch, err = strconv.Atoi(m[3]) |
| 57 |
if err != nil { |
| 58 |
return -1, -1, -1, err |
| 59 |
} |
| 60 |
return major, minor, patch, err |
| 61 |
} |
| 62 |
|
| 63 |
func versionAtLeastCheckError(version string, emajor, eminor, epatch int) (bool, error) { |
| 64 |
major, minor, patch, err := versionComponents(version) |
| 65 |
if err != nil { |
| 66 |
return false, err |
| 67 |
} |
| 68 |
if major > emajor || |
| 69 |
(major == emajor && minor > eminor) || |
| 70 |
(major == emajor && minor == eminor && patch >= epatch) { |
| 71 |
return true, nil |
| 72 |
} |
| 73 |
return false, err |
| 74 |
} |
| 75 |
|
| 76 |
func versionAtLeast(version string, emajor, eminor, epatch int) bool { |
| 77 |
res, _ := versionAtLeastCheckError(version, emajor, eminor, epatch) |
| 78 |
return res |
| 79 |
} |
| 80 |
|
| 81 |
// parseSize expects decimal positive numbers. We |
| 82 |
// return -1 to signal error. |
| 83 |
func parseSize(d []byte) (n int) { |
| 84 |
const maxParseSizeLen = 9 //999M |
| 85 |
|
| 86 |
l := len(d) |
| 87 |
if l == 0 || l > maxParseSizeLen { |
| 88 |
return -1 |
| 89 |
} |
| 90 |
var ( |
| 91 |
i int |
| 92 |
dec byte |
| 93 |
) |
| 94 |
|
| 95 |
// Note: Use `goto` here to avoid for loop in order |
| 96 |
// to have the function be inlined. |
| 97 |
// See: https://github.com/golang/go/issues/14768 |
| 98 |
loop: |
| 99 |
dec = d[i] |
| 100 |
if dec < asciiZero || dec > asciiNine { |
| 101 |
return -1 |
| 102 |
} |
| 103 |
n = n*10 + (int(dec) - asciiZero) |
| 104 |
|
| 105 |
i++ |
| 106 |
if i < l { |
| 107 |
goto loop |
| 108 |
} |
| 109 |
return n |
| 110 |
} |
| 111 |
|
| 112 |
// parseInt64 expects decimal positive numbers. We |
| 113 |
// return -1 to signal error |
| 114 |
func parseInt64(d []byte) (n int64) { |
| 115 |
if len(d) == 0 { |
| 116 |
return -1 |
| 117 |
} |
| 118 |
for _, dec := range d { |
| 119 |
if dec < asciiZero || dec > asciiNine { |
| 120 |
return -1 |
| 121 |
} |
| 122 |
n = n*10 + (int64(dec) - asciiZero) |
| 123 |
} |
| 124 |
return n |
| 125 |
} |
| 126 |
|
| 127 |
// parseUint64 expects decimal positive numbers. Returns the value and true on success, |
| 128 |
// or 0 and false on invalid input or overflow. |
| 129 |
func parseUint64(d []byte) (uint64, bool) { |
| 130 |
if len(d) == 0 { |
| 131 |
return 0, false |
| 132 |
} |
| 133 |
var n uint64 |
| 134 |
for _, dec := range d { |
| 135 |
if dec < asciiZero || dec > asciiNine { |
| 136 |
return 0, false |
| 137 |
} |
| 138 |
digit := uint64(dec) - asciiZero |
| 139 |
if n > math.MaxUint64/10 || (n == math.MaxUint64/10 && digit > math.MaxUint64%10) { |
| 140 |
return 0, false |
| 141 |
} |
| 142 |
n = n*10 + digit |
| 143 |
} |
| 144 |
return n, true |
| 145 |
} |
| 146 |
|
| 147 |
// Helper to move from float seconds to time.Duration |
| 148 |
func secondsToDuration(seconds float64) time.Duration { |
| 149 |
ttl := seconds * float64(time.Second) |
| 150 |
return time.Duration(ttl) |
| 151 |
} |
| 152 |
|
| 153 |
// Parse a host/port string with a default port to use |
| 154 |
// if none (or 0 or -1) is specified in `hostPort` string. |
| 155 |
func parseHostPort(hostPort string, defaultPort int) (host string, port int, err error) { |
| 156 |
if hostPort != "" { |
| 157 |
host, sPort, err := net.SplitHostPort(hostPort) |
| 158 |
if ae, ok := err.(*net.AddrError); ok && strings.Contains(ae.Err, "missing port") { |
| 159 |
// try appending the current port |
| 160 |
host, sPort, err = net.SplitHostPort(fmt.Sprintf("%s:%d", hostPort, defaultPort)) |
| 161 |
} |
| 162 |
if err != nil { |
| 163 |
return "", -1, err |
| 164 |
} |
| 165 |
port, err = strconv.Atoi(strings.TrimSpace(sPort)) |
| 166 |
if err != nil { |
| 167 |
return "", -1, err |
| 168 |
} |
| 169 |
if port == 0 || port == -1 { |
| 170 |
port = defaultPort |
| 171 |
} |
| 172 |
return strings.TrimSpace(host), port, nil |
| 173 |
} |
| 174 |
return "", -1, errors.New("no hostport specified") |
| 175 |
} |
| 176 |
|
| 177 |
// Returns true if URL u1 represents the same URL than u2, |
| 178 |
// false otherwise. |
| 179 |
func urlsAreEqual(u1, u2 *url.URL) bool { |
| 180 |
return reflect.DeepEqual(u1, u2) |
| 181 |
} |
| 182 |
|
| 183 |
// comma produces a string form of the given number in base 10 with |
| 184 |
// commas after every three orders of magnitude. |
| 185 |
// |
| 186 |
// e.g. comma(834142) -> 834,142 |
| 187 |
// |
| 188 |
// This function was copied from the github.com/dustin/go-humanize |
| 189 |
// package (MIT License) and is Copyright Dustin Sallings <[email protected]> |
| 190 |
func comma(v int64) string { |
| 191 |
sign := "" |
| 192 |
|
| 193 |
// Min int64 can't be negated to a usable value, so it has to be special cased. |
| 194 |
if v == math.MinInt64 { |
| 195 |
return "-9,223,372,036,854,775,808" |
| 196 |
} |
| 197 |
|
| 198 |
if v < 0 { |
| 199 |
sign = "-" |
| 200 |
v = 0 - v |
| 201 |
} |
| 202 |
|
| 203 |
parts := []string{"", "", "", "", "", "", ""} |
| 204 |
j := len(parts) - 1 |
| 205 |
|
| 206 |
for v > 999 { |
| 207 |
parts[j] = strconv.FormatInt(v%1000, 10) |
| 208 |
switch len(parts[j]) { |
| 209 |
case 2: |
| 210 |
parts[j] = "0" + parts[j] |
| 211 |
case 1: |
| 212 |
parts[j] = "00" + parts[j] |
| 213 |
} |
| 214 |
v = v / 1000 |
| 215 |
j-- |
| 216 |
} |
| 217 |
parts[j] = strconv.Itoa(int(v)) |
| 218 |
return sign + strings.Join(parts[j:], ",") |
| 219 |
} |
| 220 |
|
| 221 |
// Adds urlStr to the given map. If the string was already present, simply |
| 222 |
// bumps the reference count. |
| 223 |
// Returns true only if it was added for the first time. |
| 224 |
func (m refCountedUrlSet) addUrl(urlStr string) bool { |
| 225 |
m[urlStr]++ |
| 226 |
return m[urlStr] == 1 |
| 227 |
} |
| 228 |
|
| 229 |
// Removes urlStr from the given map. If the string is not present, nothing |
| 230 |
// is done and false is returned. |
| 231 |
// If the string was present, its reference count is decreased. Returns true |
| 232 |
// if this was the last reference, false otherwise. |
| 233 |
func (m refCountedUrlSet) removeUrl(urlStr string) bool { |
| 234 |
removed := false |
| 235 |
if ref, ok := m[urlStr]; ok { |
| 236 |
if ref == 1 { |
| 237 |
removed = true |
| 238 |
delete(m, urlStr) |
| 239 |
} else { |
| 240 |
m[urlStr]-- |
| 241 |
} |
| 242 |
} |
| 243 |
return removed |
| 244 |
} |
| 245 |
|
| 246 |
// Returns the unique URLs in this map as a slice |
| 247 |
func (m refCountedUrlSet) getAsStringSlice() []string { |
| 248 |
a := make([]string, 0, len(m)) |
| 249 |
for u := range m { |
| 250 |
a = append(a, u) |
| 251 |
} |
| 252 |
return a |
| 253 |
} |
| 254 |
|
| 255 |
// natsListenConfig provides a common configuration to match the one used by |
| 256 |
// net.Listen() but with our own defaults. |
| 257 |
// Go 1.13 introduced default-on TCP keepalives with aggressive timings and |
| 258 |
// there's no sane portable way in Go with stdlib to split the initial timer |
| 259 |
// from the retry timer. Linux/BSD defaults are 2hrs/75s and Go sets both |
| 260 |
// to 15s; the issue re making them indepedently tunable has been open since |
| 261 |
// 2014 and this code here is being written in 2020. |
| 262 |
// The NATS protocol has its own L7 PING/PONG keepalive system and the Go |
| 263 |
// defaults are inappropriate for IoT deployment scenarios. |
| 264 |
// Replace any NATS-protocol calls to net.Listen(...) with |
| 265 |
// natsListenConfig.Listen(ctx,...) or use natsListen(); leave calls for HTTP |
| 266 |
// monitoring, etc, on the default. |
| 267 |
var natsListenConfig = &net.ListenConfig{ |
| 268 |
KeepAlive: -1, |
| 269 |
} |
| 270 |
|
| 271 |
// natsListen() is the same as net.Listen() except that TCP keepalives are |
| 272 |
// disabled (to match Go's behavior before Go 1.13). |
| 273 |
func natsListen(network, address string) (net.Listener, error) { |
| 274 |
return natsListenConfig.Listen(context.Background(), network, address) |
| 275 |
} |
| 276 |
|
| 277 |
// natsDialTimeout is the same as net.DialTimeout() except the TCP keepalives |
| 278 |
// are disabled (to match Go's behavior before Go 1.13). |
| 279 |
func natsDialTimeout(network, address string, timeout time.Duration) (net.Conn, error) { |
| 280 |
d := net.Dialer{ |
| 281 |
Timeout: timeout, |
| 282 |
KeepAlive: -1, |
| 283 |
} |
| 284 |
return d.Dial(network, address) |
| 285 |
} |
| 286 |
|
| 287 |
// redactURLList() returns a copy of a list of URL pointers where each item |
| 288 |
// in the list will either be the same pointer if the URL does not contain a |
| 289 |
// password, or to a new object if there is a password. |
| 290 |
// The intended use-case is for logging lists of URLs safely. |
| 291 |
func redactURLList(unredacted []*url.URL) []*url.URL { |
| 292 |
r := make([]*url.URL, len(unredacted)) |
| 293 |
// In the common case of no passwords, if we don't let the new object leave |
| 294 |
// this function then GC should be easier. |
| 295 |
needCopy := false |
| 296 |
for i := range unredacted { |
| 297 |
if unredacted[i] == nil { |
| 298 |
r[i] = nil |
| 299 |
continue |
| 300 |
} |
| 301 |
if _, has := unredacted[i].User.Password(); !has { |
| 302 |
r[i] = unredacted[i] |
| 303 |
continue |
| 304 |
} |
| 305 |
needCopy = true |
| 306 |
ru := *unredacted[i] |
| 307 |
ru.User = url.UserPassword(ru.User.Username(), "xxxxx") |
| 308 |
r[i] = &ru |
| 309 |
} |
| 310 |
if needCopy { |
| 311 |
return r |
| 312 |
} |
| 313 |
return unredacted |
| 314 |
} |
| 315 |
|
| 316 |
// redactURLString() attempts to redact a URL string. |
| 317 |
func redactURLString(raw string) string { |
| 318 |
if !strings.ContainsRune(raw, '@') { |
| 319 |
return raw |
| 320 |
} |
| 321 |
u, err := url.Parse(raw) |
| 322 |
if err != nil { |
| 323 |
return raw |
| 324 |
} |
| 325 |
return u.Redacted() |
| 326 |
} |
| 327 |
|
| 328 |
// getURLsAsString returns a slice of u.Host from the given slice of url.URL's |
| 329 |
func getURLsAsString(urls []*url.URL) []string { |
| 330 |
a := make([]string, 0, len(urls)) |
| 331 |
for _, u := range urls { |
| 332 |
a = append(a, u.Host) |
| 333 |
} |
| 334 |
return a |
| 335 |
} |
| 336 |
|
| 337 |
// copyBytes make a new slice of the same size as `src` and copy its content. |
| 338 |
// If `src` is nil or its length is 0, then this returns `nil` |
| 339 |
func copyBytes(src []byte) []byte { |
| 340 |
if len(src) == 0 { |
| 341 |
return nil |
| 342 |
} |
| 343 |
dst := make([]byte, len(src)) |
| 344 |
copy(dst, src) |
| 345 |
return dst |
| 346 |
} |
| 347 |
|
| 348 |
// copyStrings make a new slice of the same size than `src` and copy its content. |
| 349 |
// If `src` is nil, then this returns `nil` |
| 350 |
func copyStrings(src []string) []string { |
| 351 |
if src == nil { |
| 352 |
return nil |
| 353 |
} |
| 354 |
dst := make([]string, len(src)) |
| 355 |
copy(dst, src) |
| 356 |
return dst |
| 357 |
} |
| 358 |
|
| 359 |
// Returns a byte slice for the INFO protocol. |
| 360 |
func generateInfoJSON(info *Info) []byte { |
| 361 |
b, _ := json.Marshal(info) |
| 362 |
pcs := [][]byte{[]byte("INFO"), b, []byte(CR_LF)} |
| 363 |
return bytes.Join(pcs, []byte(" ")) |
| 364 |
} |
| 365 |
|
| 366 |
// parallelTaskQueue starts a number of goroutines and returns a channel |
| 367 |
// which functions can be sent to for queued parallel execution. The |
| 368 |
// goroutines will stop running when the returned channel is closed and |
| 369 |
// all queued tasks have completed. The passed in mp limits concurrency, |
| 370 |
// or a value <= 0 will default to GOMAXPROCS. |
| 371 |
func parallelTaskQueue(mp int) chan<- func() { |
| 372 |
if rmp := runtime.GOMAXPROCS(-1); mp <= 0 { |
| 373 |
mp = rmp |
| 374 |
} else { |
| 375 |
mp = max(rmp, mp) |
| 376 |
} |
| 377 |
tq := make(chan func(), mp) |
| 378 |
for range mp { |
| 379 |
go func() { |
| 380 |
for fn := range tq { |
| 381 |
fn() |
| 382 |
} |
| 383 |
}() |
| 384 |
} |
| 385 |
return tq |
| 386 |
} |
| 387 |
|
| 388 |
// addSaturate returns a + b, saturating at math.MaxInt64. |
| 389 |
// Both a and b must be non-negative. |
| 390 |
func addSaturate(a, b int64) int64 { |
| 391 |
sum, carry := bits.Add64(uint64(a), uint64(b), 0) |
| 392 |
if carry != 0 || sum > uint64(math.MaxInt64) { |
| 393 |
return math.MaxInt64 |
| 394 |
} |
| 395 |
return int64(sum) |
| 396 |
} |
| 397 |
|
| 398 |
// mulSaturate returns a * b, saturating at math.MaxInt64. |
| 399 |
// Both a and b must be non-negative. |
| 400 |
func mulSaturate(a, b int64) int64 { |
| 401 |
hi, lo := bits.Mul64(uint64(a), uint64(b)) |
| 402 |
if hi != 0 || lo > uint64(math.MaxInt64) { |
| 403 |
return math.MaxInt64 |
| 404 |
} |
| 405 |
return int64(lo) |
| 406 |
} |