fix: resolve golangci-lint warnings
Обновлен .golangci.yml В ci.yml установлены версии Go 'stable' и golangci-lint 'latest'
This commit is contained in:
1 parent
7abbd4986f
commit
03f9d424c5
5 files changed
+216
-85
No files matched your search
@@ -20,7 +20,7 @@ jobs:
|
|||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v6
|
uses: actions/setup-go@v6
|
||||||
with:
|
with:
|
||||||
go-version: '1.25.5'
|
go-version: 'stable'
|
||||||
|
|
||||||
- name: Cache Go modules
|
- name: Cache Go modules
|
||||||
uses: actions/cache@v5
|
uses: actions/cache@v5
|
||||||
@@ -47,7 +47,7 @@ jobs:
|
|||||||
- name: Run golangci-lint
|
- name: Run golangci-lint
|
||||||
uses: golangci/golangci-lint-action@v9
|
uses: golangci/golangci-lint-action@v9
|
||||||
with:
|
with:
|
||||||
version: v2.8.0
|
version: latest
|
||||||
args: --timeout=5m ./...
|
args: --timeout=5m ./...
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -87,7 +87,7 @@ jobs:
|
|||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v6
|
uses: actions/setup-go@v6
|
||||||
with:
|
with:
|
||||||
go-version: '1.25.5'
|
go-version: 'stable'
|
||||||
|
|
||||||
# Install Android NDK for android rows and expose ndk-path output
|
# Install Android NDK for android rows and expose ndk-path output
|
||||||
- name: Setup Android NDK
|
- name: Setup Android NDK
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
linters:
|
||||||
|
enable:
|
||||||
|
- errcheck
|
||||||
|
- gosimple
|
||||||
|
- govet
|
||||||
|
- ineffassign
|
||||||
|
- staticcheck
|
||||||
|
- typecheck
|
||||||
|
- unused
|
||||||
|
- revive
|
||||||
|
- misspell
|
||||||
|
- bodyclose
|
||||||
|
|
||||||
|
linters-settings:
|
||||||
|
errcheck:
|
||||||
|
check-blank: true
|
||||||
|
check-type-assertions: true
|
||||||
|
|
||||||
|
govet:
|
||||||
|
enable-all: true
|
||||||
|
disable:
|
||||||
|
- fieldalignment
|
||||||
|
|
||||||
|
revive:
|
||||||
|
rules:
|
||||||
|
- name: blank-imports
|
||||||
|
- name: dot-imports
|
||||||
|
- name: error-return
|
||||||
|
- name: error-strings
|
||||||
|
- name: error-naming
|
||||||
|
- name: exported
|
||||||
|
- name: if-return
|
||||||
|
- name: increment-decrement
|
||||||
|
- name: var-naming
|
||||||
|
- name: var-declaration
|
||||||
|
- name: package-comments
|
||||||
|
- name: range
|
||||||
|
- name: receiver-naming
|
||||||
|
- name: time-naming
|
||||||
|
- name: unexported-return
|
||||||
|
- name: indent-error-flow
|
||||||
|
- name: errorf
|
||||||
|
|
||||||
|
run:
|
||||||
|
timeout: 5m
|
||||||
|
tests: true
|
||||||
|
|
||||||
|
issues:
|
||||||
|
exclude-use-default: true
|
||||||
|
max-issues-per-linter: 0
|
||||||
|
max-same-issues: 0
|
||||||
+132
-67
@@ -148,18 +148,33 @@ type vkCaptchaError struct {
|
|||||||
ErrorCode int
|
ErrorCode int
|
||||||
ErrorMsg string
|
ErrorMsg string
|
||||||
CaptchaSid string
|
CaptchaSid string
|
||||||
RedirectUri string
|
RedirectURI string
|
||||||
SessionToken string
|
SessionToken string
|
||||||
CaptchaTs string
|
CaptchaTs string
|
||||||
CaptchaAttempt string
|
CaptchaAttempt string
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseVkCaptchaError(errData map[string]interface{}) *vkCaptchaError {
|
func parseVkCaptchaError(errData map[string]interface{}) *vkCaptchaError {
|
||||||
codeFloat, _ := errData["error_code"].(float64)
|
var codeFloat float64
|
||||||
redirectUri, _ := errData["redirect_uri"].(string)
|
if val, ok := errData["error_code"].(float64); ok {
|
||||||
errorMsg, _ := errData["error_msg"].(string)
|
codeFloat = val
|
||||||
|
}
|
||||||
|
|
||||||
|
var redirectURI string
|
||||||
|
if val, ok := errData["redirect_uri"].(string); ok {
|
||||||
|
redirectURI = val
|
||||||
|
}
|
||||||
|
|
||||||
|
var errorMsg string
|
||||||
|
if val, ok := errData["error_msg"].(string); ok {
|
||||||
|
errorMsg = val
|
||||||
|
}
|
||||||
|
|
||||||
|
var captchaSid string
|
||||||
|
if val, ok := errData["captcha_sid"].(string); ok {
|
||||||
|
captchaSid = val
|
||||||
|
}
|
||||||
|
|
||||||
captchaSid, _ := errData["captcha_sid"].(string)
|
|
||||||
if captchaSid == "" {
|
if captchaSid == "" {
|
||||||
if sidNum, ok := errData["captcha_sid"].(float64); ok {
|
if sidNum, ok := errData["captcha_sid"].(float64); ok {
|
||||||
captchaSid = fmt.Sprintf("%.0f", sidNum)
|
captchaSid = fmt.Sprintf("%.0f", sidNum)
|
||||||
@@ -167,8 +182,8 @@ func parseVkCaptchaError(errData map[string]interface{}) *vkCaptchaError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var sessionToken string
|
var sessionToken string
|
||||||
if redirectUri != "" {
|
if redirectURI != "" {
|
||||||
if parsed, err := neturl.Parse(redirectUri); err == nil {
|
if parsed, err := neturl.Parse(redirectURI); err == nil {
|
||||||
sessionToken = parsed.Query().Get("session_token")
|
sessionToken = parsed.Query().Get("session_token")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -191,7 +206,7 @@ func parseVkCaptchaError(errData map[string]interface{}) *vkCaptchaError {
|
|||||||
ErrorCode: int(codeFloat),
|
ErrorCode: int(codeFloat),
|
||||||
ErrorMsg: errorMsg,
|
ErrorMsg: errorMsg,
|
||||||
CaptchaSid: captchaSid,
|
CaptchaSid: captchaSid,
|
||||||
RedirectUri: redirectUri,
|
RedirectURI: redirectURI,
|
||||||
SessionToken: sessionToken,
|
SessionToken: sessionToken,
|
||||||
CaptchaTs: captchaTs,
|
CaptchaTs: captchaTs,
|
||||||
CaptchaAttempt: captchaAttempt,
|
CaptchaAttempt: captchaAttempt,
|
||||||
@@ -204,7 +219,7 @@ func solveVkCaptcha(ctx context.Context, captchaErr *vkCaptchaError, dialer *dns
|
|||||||
return "", fmt.Errorf("no session_token in redirect_uri")
|
return "", fmt.Errorf("no session_token in redirect_uri")
|
||||||
}
|
}
|
||||||
|
|
||||||
powInput, difficulty, err := fetchPowInput(ctx, captchaErr.RedirectUri, dialer)
|
powInput, difficulty, err := fetchPowInput(ctx, captchaErr.RedirectURI, dialer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("failed to fetch PoW input: %w", err)
|
return "", fmt.Errorf("failed to fetch PoW input: %w", err)
|
||||||
}
|
}
|
||||||
@@ -220,8 +235,8 @@ func solveVkCaptcha(ctx context.Context, captchaErr *vkCaptchaError, dialer *dns
|
|||||||
return successToken, nil
|
return successToken, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func fetchPowInput(ctx context.Context, redirectUri string, dialer *dnsdialer.Dialer) (string, int, error) {
|
func fetchPowInput(ctx context.Context, redirectURI string, dialer *dnsdialer.Dialer) (string, int, error) {
|
||||||
req, err := http.NewRequestWithContext(ctx, "GET", redirectUri, nil)
|
req, err := http.NewRequestWithContext(ctx, "GET", redirectURI, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", 0, err
|
return "", 0, err
|
||||||
}
|
}
|
||||||
@@ -361,8 +376,8 @@ func callCaptchaNotRobot(ctx context.Context, sessionToken, hash string, dialer
|
|||||||
if !ok {
|
if !ok {
|
||||||
return "", fmt.Errorf("invalid check response: %v", checkResp)
|
return "", fmt.Errorf("invalid check response: %v", checkResp)
|
||||||
}
|
}
|
||||||
status, _ := respObj["status"].(string)
|
status, ok := respObj["status"].(string)
|
||||||
if status != "OK" {
|
if !ok || status != "OK" {
|
||||||
return "", fmt.Errorf("check status: %s", status)
|
return "", fmt.Errorf("check status: %s", status)
|
||||||
}
|
}
|
||||||
successToken, ok := respObj["success_token"].(string)
|
successToken, ok := respObj["success_token"].(string)
|
||||||
@@ -481,8 +496,8 @@ func getVkCreds(link string, dialer *dnsdialer.Dialer) (string, string, string,
|
|||||||
|
|
||||||
// Check for captcha error
|
// Check for captcha error
|
||||||
if errObj, hasErr := resp["error"].(map[string]interface{}); hasErr {
|
if errObj, hasErr := resp["error"].(map[string]interface{}); hasErr {
|
||||||
errCode, _ := errObj["error_code"].(float64)
|
errCode, ok2 := errObj["error_code"].(float64)
|
||||||
if errCode == 14 {
|
if ok2 && errCode == 14 {
|
||||||
if attempt == maxCaptchaAttempts {
|
if attempt == maxCaptchaAttempts {
|
||||||
return "", "", "", fmt.Errorf("captcha failed after %d attempts", maxCaptchaAttempts)
|
return "", "", "", fmt.Errorf("captcha failed after %d attempts", maxCaptchaAttempts)
|
||||||
}
|
}
|
||||||
@@ -512,12 +527,12 @@ func getVkCreds(link string, dialer *dnsdialer.Dialer) (string, string, string,
|
|||||||
return "", "", "", fmt.Errorf("VK API error: %v", errObj)
|
return "", "", "", fmt.Errorf("VK API error: %v", errObj)
|
||||||
}
|
}
|
||||||
|
|
||||||
respMap, ok := resp["response"].(map[string]interface{})
|
respMap, okLoop := resp["response"].(map[string]interface{})
|
||||||
if !ok {
|
if !okLoop {
|
||||||
return "", "", "", fmt.Errorf("unexpected getAnonymousToken response: %v", resp)
|
return "", "", "", fmt.Errorf("unexpected getAnonymousToken response: %v", resp)
|
||||||
}
|
}
|
||||||
token2, ok = respMap["token"].(string)
|
token2, okLoop = respMap["token"].(string)
|
||||||
if !ok {
|
if !okLoop {
|
||||||
return "", "", "", fmt.Errorf("missing token in response: %v", resp)
|
return "", "", "", fmt.Errorf("missing token in response: %v", resp)
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
@@ -531,7 +546,10 @@ func getVkCreds(link string, dialer *dnsdialer.Dialer) (string, string, string,
|
|||||||
return "", "", "", fmt.Errorf("request error:%s", err)
|
return "", "", "", fmt.Errorf("request error:%s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
token3 := resp["session_key"].(string)
|
token3, ok := resp["session_key"].(string)
|
||||||
|
if !ok {
|
||||||
|
return "", "", "", fmt.Errorf("missing session_key in response: %v", resp)
|
||||||
|
}
|
||||||
|
|
||||||
data = fmt.Sprintf("joinLink=%s&isVideo=false&protocolVersion=5&anonymToken=%s&method=vchat.joinConversationByLink&format=JSON&application_key=CGMMEJLGDIHBABABA&session_key=%s", link, token2, token3)
|
data = fmt.Sprintf("joinLink=%s&isVideo=false&protocolVersion=5&anonymToken=%s&method=vchat.joinConversationByLink&format=JSON&application_key=CGMMEJLGDIHBABABA&session_key=%s", link, token2, token3)
|
||||||
url = "https://calls.okcdn.ru/fb.do"
|
url = "https://calls.okcdn.ru/fb.do"
|
||||||
@@ -541,9 +559,30 @@ func getVkCreds(link string, dialer *dnsdialer.Dialer) (string, string, string,
|
|||||||
return "", "", "", fmt.Errorf("request error:%s", err)
|
return "", "", "", fmt.Errorf("request error:%s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
user := resp["turn_server"].(map[string]interface{})["username"].(string)
|
turnServer, ok2 := resp["turn_server"].(map[string]interface{})
|
||||||
pass := resp["turn_server"].(map[string]interface{})["credential"].(string)
|
if !ok2 {
|
||||||
turn := resp["turn_server"].(map[string]interface{})["urls"].([]interface{})[0].(string)
|
return "", "", "", fmt.Errorf("missing turn_server in response: %v", resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
user, ok2 := turnServer["username"].(string)
|
||||||
|
if !ok2 {
|
||||||
|
return "", "", "", fmt.Errorf("missing username in turn_server: %v", turnServer)
|
||||||
|
}
|
||||||
|
|
||||||
|
pass, ok2 := turnServer["credential"].(string)
|
||||||
|
if !ok2 {
|
||||||
|
return "", "", "", fmt.Errorf("missing credential in turn_server: %v", turnServer)
|
||||||
|
}
|
||||||
|
|
||||||
|
urls, ok2 := turnServer["urls"].([]interface{})
|
||||||
|
if !ok2 || len(urls) == 0 {
|
||||||
|
return "", "", "", fmt.Errorf("missing or empty urls in turn_server: %v", turnServer)
|
||||||
|
}
|
||||||
|
|
||||||
|
turn, ok2 := urls[0].(string)
|
||||||
|
if !ok2 {
|
||||||
|
return "", "", "", fmt.Errorf("first url is not a string: %v", urls[0])
|
||||||
|
}
|
||||||
|
|
||||||
clean := strings.Split(turn, "?")[0]
|
clean := strings.Split(turn, "?")[0]
|
||||||
address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:")
|
address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:")
|
||||||
@@ -655,7 +694,7 @@ func getYandexCreds(link string) (string, string, string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type WSSAck struct {
|
type WSSAck struct {
|
||||||
Uid string `json:"uid"`
|
UID string `json:"uid"`
|
||||||
Ack struct {
|
Ack struct {
|
||||||
Status struct {
|
Status struct {
|
||||||
Code string `json:"code"`
|
Code string `json:"code"`
|
||||||
@@ -664,8 +703,8 @@ func getYandexCreds(link string) (string, string, string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type WSSData struct {
|
type WSSData struct {
|
||||||
ParticipantId string
|
ParticipantID string
|
||||||
RoomId string
|
RoomID string
|
||||||
Credentials string
|
Credentials string
|
||||||
Wss string
|
Wss string
|
||||||
}
|
}
|
||||||
@@ -701,8 +740,11 @@ func getYandexCreds(link string) (string, string, string, error) {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
body, _ := io.ReadAll(resp.Body)
|
readBody, err2 := io.ReadAll(resp.Body)
|
||||||
return "", "", "", fmt.Errorf("GetConference: status=%s body=%s", resp.Status, string(body))
|
if err2 != nil {
|
||||||
|
return "", "", "", fmt.Errorf("GetConference: status=%s (failed to read body: %v)", resp.Status, err2)
|
||||||
|
}
|
||||||
|
return "", "", "", fmt.Errorf("GetConference: status=%s body=%s", resp.Status, string(readBody))
|
||||||
}
|
}
|
||||||
|
|
||||||
var result ConferenceResponse
|
var result ConferenceResponse
|
||||||
@@ -710,8 +752,8 @@ func getYandexCreds(link string) (string, string, string, error) {
|
|||||||
return "", "", "", fmt.Errorf("decode conf: %v", err)
|
return "", "", "", fmt.Errorf("decode conf: %v", err)
|
||||||
}
|
}
|
||||||
data := WSSData{
|
data := WSSData{
|
||||||
ParticipantId: result.PeerID,
|
ParticipantID: result.PeerID,
|
||||||
RoomId: result.RoomID,
|
RoomID: result.RoomID,
|
||||||
Credentials: result.Credentials,
|
Credentials: result.Credentials,
|
||||||
Wss: result.ClientConfiguration.MediaServerURL,
|
Wss: result.ClientConfiguration.MediaServerURL,
|
||||||
}
|
}
|
||||||
@@ -723,10 +765,17 @@ func getYandexCreds(link string) (string, string, string, error) {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
dialer := websocket.Dialer{}
|
dialer := websocket.Dialer{}
|
||||||
conn, _, err := dialer.DialContext(ctx, data.Wss, h)
|
var conn *websocket.Conn
|
||||||
|
conn, resp, err = dialer.DialContext(ctx, data.Wss, h)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if resp != nil && resp.Body != nil {
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
}
|
||||||
return "", "", "", fmt.Errorf("ws dial: %w", err)
|
return "", "", "", fmt.Errorf("ws dial: %w", err)
|
||||||
}
|
}
|
||||||
|
if resp != nil && resp.Body != nil {
|
||||||
|
defer func() { _ = resp.Body.Close() }()
|
||||||
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
if closeErr := conn.Close(); closeErr != nil {
|
if closeErr := conn.Close(); closeErr != nil {
|
||||||
log.Printf("close websocket: %s", closeErr)
|
log.Printf("close websocket: %s", closeErr)
|
||||||
@@ -752,8 +801,8 @@ func getYandexCreds(link string) (string, string, string, error) {
|
|||||||
SendVideo: false,
|
SendVideo: false,
|
||||||
SendSharing: false,
|
SendSharing: false,
|
||||||
|
|
||||||
ParticipantID: data.ParticipantId,
|
ParticipantID: data.ParticipantID,
|
||||||
RoomID: data.RoomId,
|
RoomID: data.RoomID,
|
||||||
ServiceName: "telemost",
|
ServiceName: "telemost",
|
||||||
Credentials: data.Credentials,
|
Credentials: data.Credentials,
|
||||||
SdkInfo: SdkInfo{
|
SdkInfo: SdkInfo{
|
||||||
@@ -795,9 +844,13 @@ func getYandexCreds(link string) (string, string, string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if debug {
|
if debug {
|
||||||
b, _ := json.MarshalIndent(req1, "", " ")
|
b, err2 := json.MarshalIndent(req1, "", " ")
|
||||||
|
if err2 != nil {
|
||||||
|
log.Printf("Failed to marshal HELLO: %v", err2)
|
||||||
|
} else {
|
||||||
log.Printf("Sending HELLO:\n%s", string(b))
|
log.Printf("Sending HELLO:\n%s", string(b))
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if err := conn.WriteJSON(req1); err != nil {
|
if err := conn.WriteJSON(req1); err != nil {
|
||||||
return "", "", "", fmt.Errorf("ws write: %w", err)
|
return "", "", "", fmt.Errorf("ws write: %w", err)
|
||||||
@@ -873,7 +926,7 @@ func dtlsFunc(ctx context.Context, conn net.PacketConn, peer *net.UDPAddr) (net.
|
|||||||
|
|
||||||
func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, c chan<- error) {
|
func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.PacketConn, connchan chan<- net.PacketConn, okchan chan<- struct{}, c chan<- error) {
|
||||||
time.Sleep(time.Duration(rand.Intn(400)+100) * time.Millisecond)
|
time.Sleep(time.Duration(rand.Intn(400)+100) * time.Millisecond)
|
||||||
var err error = nil
|
var err error
|
||||||
defer func() { c <- err }()
|
defer func() { c <- err }()
|
||||||
dtlsctx, dtlscancel := context.WithCancel(ctx)
|
dtlsctx, dtlscancel := context.WithCancel(ctx)
|
||||||
defer dtlscancel()
|
defer dtlscancel()
|
||||||
@@ -1008,7 +1061,7 @@ type turnParams struct {
|
|||||||
|
|
||||||
func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UDPAddr, conn2 net.PacketConn, c chan<- error) {
|
func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UDPAddr, conn2 net.PacketConn, c chan<- error) {
|
||||||
time.Sleep(time.Duration(rand.Intn(400)+100) * time.Millisecond)
|
time.Sleep(time.Duration(rand.Intn(400)+100) * time.Millisecond)
|
||||||
var err error = nil
|
var err error
|
||||||
defer func() { c <- err }()
|
defer func() { c <- err }()
|
||||||
user, pass, url, err1 := turnParams.getCreds(turnParams.link)
|
user, pass, url, err1 := turnParams.getCreds(turnParams.link)
|
||||||
if err1 != nil {
|
if err1 != nil {
|
||||||
@@ -1028,13 +1081,13 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD
|
|||||||
}
|
}
|
||||||
var turnServerAddr string
|
var turnServerAddr string
|
||||||
turnServerAddr = net.JoinHostPort(urlhost, urlport)
|
turnServerAddr = net.JoinHostPort(urlhost, urlport)
|
||||||
turnServerUdpAddr, err1 := net.ResolveUDPAddr("udp", turnServerAddr)
|
turnServerUDPAddr, err1 := net.ResolveUDPAddr("udp", turnServerAddr)
|
||||||
if err1 != nil {
|
if err1 != nil {
|
||||||
err = fmt.Errorf("failed to resolve TURN server address: %s", err1)
|
err = fmt.Errorf("failed to resolve TURN server address: %s", err1)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
turnServerAddr = turnServerUdpAddr.String()
|
turnServerAddr = turnServerUDPAddr.String()
|
||||||
fmt.Println(turnServerUdpAddr.IP)
|
fmt.Println(turnServerUDPAddr.IP)
|
||||||
// Dial TURN Server
|
// Dial TURN Server
|
||||||
var cfg *turn.ClientConfig
|
var cfg *turn.ClientConfig
|
||||||
var turnConn net.PacketConn
|
var turnConn net.PacketConn
|
||||||
@@ -1042,7 +1095,7 @@ func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UD
|
|||||||
ctx1, cancel := context.WithTimeout(ctx, 5*time.Second)
|
ctx1, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if turnParams.udp {
|
if turnParams.udp {
|
||||||
conn, err2 := net.DialUDP("udp", nil, turnServerUdpAddr) // nolint: noctx
|
conn, err2 := net.DialUDP("udp", nil, turnServerUDPAddr) // nolint: noctx
|
||||||
if err2 != nil {
|
if err2 != nil {
|
||||||
err = fmt.Errorf("failed to connect to TURN server: %s", err2)
|
err = fmt.Errorf("failed to connect to TURN server: %s", err2)
|
||||||
return
|
return
|
||||||
@@ -1514,7 +1567,7 @@ func runTCPMode(ctx context.Context, tp *turnParams, peer *net.UDPAddr, listenAd
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
log.Panicf("TCP listen: %s", err)
|
log.Panicf("TCP listen: %s", err)
|
||||||
}
|
}
|
||||||
context.AfterFunc(ctx, func() { listener.Close() })
|
context.AfterFunc(ctx, func() { _ = listener.Close() })
|
||||||
log.Printf("TCP mode: listening on %s (round-robin across %d sessions)", listenAddr, numSessions)
|
log.Printf("TCP mode: listening on %s (round-robin across %d sessions)", listenAddr, numSessions)
|
||||||
|
|
||||||
var wgConn sync.WaitGroup
|
var wgConn sync.WaitGroup
|
||||||
@@ -1535,20 +1588,20 @@ func runTCPMode(ctx context.Context, tp *turnParams, peer *net.UDPAddr, listenAd
|
|||||||
sess := pool.pick()
|
sess := pool.pick()
|
||||||
if sess == nil || sess.IsClosed() {
|
if sess == nil || sess.IsClosed() {
|
||||||
log.Printf("No active sessions, rejecting connection")
|
log.Printf("No active sessions, rejecting connection")
|
||||||
tcpConn.Close()
|
_ = tcpConn.Close()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
wgConn.Add(1)
|
wgConn.Add(1)
|
||||||
go func(tc net.Conn, s *smux.Session) {
|
go func(tc net.Conn, s *smux.Session) {
|
||||||
defer wgConn.Done()
|
defer wgConn.Done()
|
||||||
defer tc.Close()
|
defer func() { _ = tc.Close() }()
|
||||||
stream, err := s.OpenStream()
|
stream, err := s.OpenStream()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("smux open stream error: %s", err)
|
log.Printf("smux open stream error: %s", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer stream.Close()
|
defer func() { _ = stream.Close() }()
|
||||||
pipe(ctx, tc, stream)
|
pipe(ctx, tc, stream)
|
||||||
}(tcpConn, sess)
|
}(tcpConn, sess)
|
||||||
}
|
}
|
||||||
@@ -1625,31 +1678,31 @@ func createSmuxSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr) (
|
|||||||
urlport = tp.port
|
urlport = tp.port
|
||||||
}
|
}
|
||||||
turnServerAddr := net.JoinHostPort(urlhost, urlport)
|
turnServerAddr := net.JoinHostPort(urlhost, urlport)
|
||||||
turnServerUdpAddr, err := net.ResolveUDPAddr("udp", turnServerAddr)
|
turnServerUDPAddr, err := net.ResolveUDPAddr("udp", turnServerAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, fmt.Errorf("resolve TURN addr: %w", err)
|
return nil, nil, fmt.Errorf("resolve TURN addr: %w", err)
|
||||||
}
|
}
|
||||||
turnServerAddr = turnServerUdpAddr.String()
|
turnServerAddr = turnServerUDPAddr.String()
|
||||||
|
|
||||||
// 2. Connect to TURN server
|
// 2. Connect to TURN server
|
||||||
var turnConn net.PacketConn
|
var turnConn net.PacketConn
|
||||||
ctx1, cancel1 := context.WithTimeout(ctx, 5*time.Second)
|
ctx1, cancel1 := context.WithTimeout(ctx, 5*time.Second)
|
||||||
defer cancel1()
|
defer cancel1()
|
||||||
if tp.udp {
|
if tp.udp {
|
||||||
conn, err := net.DialUDP("udp", nil, turnServerUdpAddr)
|
c, err1 := net.DialUDP("udp", nil, turnServerUDPAddr)
|
||||||
if err != nil {
|
if err1 != nil {
|
||||||
return nil, nil, fmt.Errorf("dial TURN (udp): %w", err)
|
return nil, nil, fmt.Errorf("dial TURN (udp): %w", err1)
|
||||||
}
|
}
|
||||||
cleanupFns = append(cleanupFns, func() { conn.Close() })
|
cleanupFns = append(cleanupFns, func() { _ = c.Close() })
|
||||||
turnConn = &connectedUDPConn{conn}
|
turnConn = &connectedUDPConn{c}
|
||||||
} else {
|
} else {
|
||||||
var d net.Dialer
|
var d net.Dialer
|
||||||
conn, err := d.DialContext(ctx1, "tcp", turnServerAddr)
|
c, err1 := d.DialContext(ctx1, "tcp", turnServerAddr)
|
||||||
if err != nil {
|
if err1 != nil {
|
||||||
return nil, nil, fmt.Errorf("dial TURN (tcp): %w", err)
|
return nil, nil, fmt.Errorf("dial TURN (tcp): %w", err1)
|
||||||
}
|
}
|
||||||
cleanupFns = append(cleanupFns, func() { conn.Close() })
|
cleanupFns = append(cleanupFns, func() { _ = c.Close() })
|
||||||
turnConn = turn.NewSTUNConn(conn)
|
turnConn = turn.NewSTUNConn(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Create TURN client and allocate relay
|
// 3. Create TURN client and allocate relay
|
||||||
@@ -1683,7 +1736,7 @@ func createSmuxSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr) (
|
|||||||
cleanup()
|
cleanup()
|
||||||
return nil, nil, fmt.Errorf("TURN allocate: %w", err)
|
return nil, nil, fmt.Errorf("TURN allocate: %w", err)
|
||||||
}
|
}
|
||||||
cleanupFns = append(cleanupFns, func() { relayConn.Close() })
|
cleanupFns = append(cleanupFns, func() { _ = relayConn.Close() })
|
||||||
log.Printf("relayed-address=%s", relayConn.LocalAddr().String())
|
log.Printf("relayed-address=%s", relayConn.LocalAddr().String())
|
||||||
|
|
||||||
// 4. Establish DTLS over TURN relay
|
// 4. Establish DTLS over TURN relay
|
||||||
@@ -1708,11 +1761,11 @@ func createSmuxSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr) (
|
|||||||
ctx2, cancel2 := context.WithTimeout(ctx, 30*time.Second)
|
ctx2, cancel2 := context.WithTimeout(ctx, 30*time.Second)
|
||||||
defer cancel2()
|
defer cancel2()
|
||||||
if err = dtlsConn.HandshakeContext(ctx2); err != nil {
|
if err = dtlsConn.HandshakeContext(ctx2); err != nil {
|
||||||
dtlsConn.Close()
|
_ = dtlsConn.Close()
|
||||||
cleanup()
|
cleanup()
|
||||||
return nil, nil, fmt.Errorf("DTLS handshake: %w", err)
|
return nil, nil, fmt.Errorf("DTLS handshake: %w", err)
|
||||||
}
|
}
|
||||||
cleanupFns = append(cleanupFns, func() { dtlsConn.Close() })
|
cleanupFns = append(cleanupFns, func() { _ = dtlsConn.Close() })
|
||||||
log.Printf("DTLS connection established")
|
log.Printf("DTLS connection established")
|
||||||
|
|
||||||
// 5. Create KCP session over DTLS
|
// 5. Create KCP session over DTLS
|
||||||
@@ -1721,7 +1774,7 @@ func createSmuxSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr) (
|
|||||||
cleanup()
|
cleanup()
|
||||||
return nil, nil, fmt.Errorf("KCP session: %w", err)
|
return nil, nil, fmt.Errorf("KCP session: %w", err)
|
||||||
}
|
}
|
||||||
cleanupFns = append(cleanupFns, func() { kcpSess.Close() })
|
cleanupFns = append(cleanupFns, func() { _ = kcpSess.Close() })
|
||||||
log.Printf("KCP session established")
|
log.Printf("KCP session established")
|
||||||
|
|
||||||
// 6. Create smux client session over KCP
|
// 6. Create smux client session over KCP
|
||||||
@@ -1730,7 +1783,7 @@ func createSmuxSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr) (
|
|||||||
cleanup()
|
cleanup()
|
||||||
return nil, nil, fmt.Errorf("smux client: %w", err)
|
return nil, nil, fmt.Errorf("smux client: %w", err)
|
||||||
}
|
}
|
||||||
cleanupFns = append(cleanupFns, func() { smuxSess.Close() })
|
cleanupFns = append(cleanupFns, func() { _ = smuxSess.Close() })
|
||||||
log.Printf("smux session established")
|
log.Printf("smux session established")
|
||||||
|
|
||||||
return smuxSess, cleanup, nil
|
return smuxSess, cleanup, nil
|
||||||
@@ -1760,8 +1813,12 @@ func (r *relayPacketConn) SetWriteDeadline(t time.Time) error { return r.relay.S
|
|||||||
func pipe(ctx context.Context, c1, c2 net.Conn) {
|
func pipe(ctx context.Context, c1, c2 net.Conn) {
|
||||||
ctx2, cancel := context.WithCancel(ctx)
|
ctx2, cancel := context.WithCancel(ctx)
|
||||||
context.AfterFunc(ctx2, func() {
|
context.AfterFunc(ctx2, func() {
|
||||||
_ = c1.SetDeadline(time.Now())
|
if err := c1.SetDeadline(time.Now()); err != nil {
|
||||||
_ = c2.SetDeadline(time.Now())
|
log.Printf("pipe: failed to set deadline c1: %v", err)
|
||||||
|
}
|
||||||
|
if err := c2.SetDeadline(time.Now()); err != nil {
|
||||||
|
log.Printf("pipe: failed to set deadline c2: %v", err)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
@@ -1769,14 +1826,22 @@ func pipe(ctx context.Context, c1, c2 net.Conn) {
|
|||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer cancel()
|
defer cancel()
|
||||||
_, _ = io.Copy(c1, c2)
|
if _, err := io.Copy(c1, c2); err != nil {
|
||||||
|
log.Printf("pipe: c1<-c2 copy error: %v", err)
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer cancel()
|
defer cancel()
|
||||||
_, _ = io.Copy(c2, c1)
|
if _, err := io.Copy(c2, c1); err != nil {
|
||||||
|
log.Printf("pipe: c2<-c1 copy error: %v", err)
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
_ = c1.SetDeadline(time.Time{})
|
if err := c1.SetDeadline(time.Time{}); err != nil {
|
||||||
_ = c2.SetDeadline(time.Time{})
|
log.Printf("pipe: failed to reset deadline c1: %v", err)
|
||||||
|
}
|
||||||
|
if err := c2.SetDeadline(time.Time{}); err != nil {
|
||||||
|
log.Printf("pipe: failed to reset deadline c2: %v", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+24
-12
@@ -167,7 +167,7 @@ func handleUDPConnection(ctx context.Context, conn net.Conn, connectAddr string)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err1 := serverConn.SetWriteDeadline(time.Now().Add(time.Minute * 30)); err1 != nil {
|
if err1 = serverConn.SetWriteDeadline(time.Now().Add(time.Minute * 30)); err1 != nil {
|
||||||
log.Printf("Failed: %s", err1)
|
log.Printf("Failed: %s", err1)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -198,7 +198,7 @@ func handleUDPConnection(ctx context.Context, conn net.Conn, connectAddr string)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err1 := conn.SetWriteDeadline(time.Now().Add(time.Minute * 30)); err1 != nil {
|
if err1 = conn.SetWriteDeadline(time.Now().Add(time.Minute * 30)); err1 != nil {
|
||||||
log.Printf("Failed: %s", err1)
|
log.Printf("Failed: %s", err1)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -221,7 +221,7 @@ func handleTCPConnection(ctx context.Context, dtlsConn net.Conn, connectAddr str
|
|||||||
log.Printf("KCP session error: %s", err)
|
log.Printf("KCP session error: %s", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer kcpSess.Close()
|
defer func() { _ = kcpSess.Close() }()
|
||||||
log.Printf("KCP session established (server)")
|
log.Printf("KCP session established (server)")
|
||||||
|
|
||||||
// 2. Create smux server session over KCP
|
// 2. Create smux server session over KCP
|
||||||
@@ -230,7 +230,7 @@ func handleTCPConnection(ctx context.Context, dtlsConn net.Conn, connectAddr str
|
|||||||
log.Printf("smux server error: %s", err)
|
log.Printf("smux server error: %s", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer smuxSess.Close()
|
defer func() { _ = smuxSess.Close() }()
|
||||||
log.Printf("smux session established (server)")
|
log.Printf("smux session established (server)")
|
||||||
|
|
||||||
// 3. Accept smux streams and forward to backend via TCP
|
// 3. Accept smux streams and forward to backend via TCP
|
||||||
@@ -249,7 +249,7 @@ func handleTCPConnection(ctx context.Context, dtlsConn net.Conn, connectAddr str
|
|||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func(s *smux.Stream) {
|
go func(s *smux.Stream) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer s.Close()
|
defer func() { _ = s.Close() }()
|
||||||
|
|
||||||
// Connect to backend (Xray/VLESS)
|
// Connect to backend (Xray/VLESS)
|
||||||
backendConn, err := net.DialTimeout("tcp", connectAddr, 10*time.Second)
|
backendConn, err := net.DialTimeout("tcp", connectAddr, 10*time.Second)
|
||||||
@@ -257,7 +257,7 @@ func handleTCPConnection(ctx context.Context, dtlsConn net.Conn, connectAddr str
|
|||||||
log.Printf("backend dial error: %s", err)
|
log.Printf("backend dial error: %s", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer backendConn.Close()
|
defer func() { _ = backendConn.Close() }()
|
||||||
|
|
||||||
// Bidirectional copy
|
// Bidirectional copy
|
||||||
pipeConn(ctx, s, backendConn)
|
pipeConn(ctx, s, backendConn)
|
||||||
@@ -270,8 +270,12 @@ func handleTCPConnection(ctx context.Context, dtlsConn net.Conn, connectAddr str
|
|||||||
func pipeConn(ctx context.Context, c1, c2 net.Conn) {
|
func pipeConn(ctx context.Context, c1, c2 net.Conn) {
|
||||||
ctx2, cancel := context.WithCancel(ctx)
|
ctx2, cancel := context.WithCancel(ctx)
|
||||||
context.AfterFunc(ctx2, func() {
|
context.AfterFunc(ctx2, func() {
|
||||||
_ = c1.SetDeadline(time.Now())
|
if err := c1.SetDeadline(time.Now()); err != nil {
|
||||||
_ = c2.SetDeadline(time.Now())
|
log.Printf("pipeConn: failed to set deadline c1: %v", err)
|
||||||
|
}
|
||||||
|
if err := c2.SetDeadline(time.Now()); err != nil {
|
||||||
|
log.Printf("pipeConn: failed to set deadline c2: %v", err)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
@@ -279,14 +283,22 @@ func pipeConn(ctx context.Context, c1, c2 net.Conn) {
|
|||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer cancel()
|
defer cancel()
|
||||||
_, _ = io.Copy(c1, c2)
|
if _, err := io.Copy(c1, c2); err != nil {
|
||||||
|
log.Printf("pipeConn: c1<-c2 copy error: %v", err)
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer cancel()
|
defer cancel()
|
||||||
_, _ = io.Copy(c2, c1)
|
if _, err := io.Copy(c2, c1); err != nil {
|
||||||
|
log.Printf("pipeConn: c2<-c1 copy error: %v", err)
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
_ = c1.SetDeadline(time.Time{})
|
if err := c1.SetDeadline(time.Time{}); err != nil {
|
||||||
_ = c2.SetDeadline(time.Time{})
|
log.Printf("pipeConn: failed to reset deadline c1: %v", err)
|
||||||
|
}
|
||||||
|
if err := c2.SetDeadline(time.Time{}); err != nil {
|
||||||
|
log.Printf("pipeConn: failed to reset deadline c2: %v", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+6
-3
@@ -52,14 +52,17 @@ func (d *DtlsPacketConn) SetWriteDeadline(t time.Time) error {
|
|||||||
func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool) (*kcp.UDPSession, error) {
|
func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool) (*kcp.UDPSession, error) {
|
||||||
pc := NewDtlsPacketConn(dtlsConn)
|
pc := NewDtlsPacketConn(dtlsConn)
|
||||||
|
|
||||||
block, _ := kcp.NewNoneBlockCrypt(nil) // DTLS already encrypts
|
block, err := kcp.NewNoneBlockCrypt(nil) // DTLS already encrypts
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
var sess *kcp.UDPSession
|
var sess *kcp.UDPSession
|
||||||
var err error
|
|
||||||
|
|
||||||
if isServer {
|
if isServer {
|
||||||
// Server: listen on the PacketConn and accept one session
|
// Server: listen on the PacketConn and accept one session
|
||||||
listener, err := kcp.ServeConn(block, 0, 0, pc)
|
var listener *kcp.Listener
|
||||||
|
listener, err = kcp.ServeConn(block, 0, 0, pc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user