-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathcandidate.go
90 lines (74 loc) · 1.79 KB
/
candidate.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
// Copyright (c) 2022-2024 Winlin
//
// SPDX-License-Identifier: MIT
package main
import (
"context"
"net"
"strings"
"sync"
// From ossrs.
"github.com/ossrs/go-oryx-lib/logger"
)
var candidateWorker *CandidateWorker
type CandidateWorker struct {
cancel context.CancelFunc
wg sync.WaitGroup
}
func NewCandidateWorker() *CandidateWorker {
return &CandidateWorker{}
}
func (v *CandidateWorker) Close() error {
if v.cancel != nil {
v.cancel()
}
v.wg.Wait()
return nil
}
func (v *CandidateWorker) Start(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
v.cancel = cancel
ctx = logger.WithContext(ctx)
logger.Tf(ctx, "candidate start a worker")
return nil
}
// Resolve host to ip. Return nil if ignore the host resolving, for example, user disable resolving by
// set env NAME_LOOKUP to false.
func (v *CandidateWorker) Resolve(host string) (net.IP, error) {
// Ignore the resolving.
if envNameLookup() == "off" {
return nil, nil
}
// Ignore the port.
if strings.Contains(host, ":") {
if hostname, _, err := net.SplitHostPort(host); err != nil {
return nil, err
} else {
host = hostname
}
}
// Resolve the localhost to possible IP address.
if host == "localhost" {
// If directly run in host, like debugging, use the private ipv4.
if envPlatformDocker() == "off" {
return conf.ipv4, nil
}
// If already set CANDIDATE, ignore lo.
if envCandidate() != "" {
return nil, nil
}
// Return lo for OBS WHIP or native client to access it.
return net.IPv4(127, 0, 0, 1), nil
}
// Directly use the ip if not name.
if ip := net.ParseIP(host); ip != nil {
return ip, nil
}
// Lookup the name to parse to ip.
if ips, err := net.LookupIP(host); err != nil {
return nil, err
} else if len(ips) > 0 {
return ips[0], nil
}
return nil, nil
}