mirror of
https://github.com/onyx-and-iris/q3rcon-proxy.git
synced 2026-01-02 11:37:48 +00:00
Compare commits
58 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e5ba6d6fc | ||
|
|
7455aeed0f | ||
|
|
5490f13175 | ||
|
|
539a9f00a6 | ||
|
|
f66cb52cce | ||
|
|
a7ab564de4 | ||
|
|
34c003694d | ||
|
|
3ecce5bb66 | ||
|
|
4d42600ecd | ||
|
|
0116d3dbe1 | ||
|
|
7897348669 | ||
| 6489d1e556 | |||
| d0e3f5863a | |||
| a00796254d | |||
| 80ef18f705 | |||
| 40d79063f5 | |||
| 02e73a21c0 | |||
| 5e399b8590 | |||
| 28baa2ed00 | |||
| 58c95879cc | |||
| af0a72eb67 | |||
| 0d85129d31 | |||
| bf7bd4f5b8 | |||
| a13d3d7da3 | |||
| a0c1f15ef0 | |||
| e0dc2c02d9 | |||
| 514688b9ce | |||
| 43183717f6 | |||
|
|
464fbec85f | ||
| fd51761ab5 | |||
| 16e5e9c010 | |||
| 916d2a2d86 | |||
|
|
1bbe3102ce | ||
|
|
f1762cf3ad | ||
| 386aab510e | |||
| c8fd7a3f22 | |||
| db1c45a25b | |||
| a1ecf85cbb | |||
| 6c83d6ad2c | |||
| c2266ac9d9 | |||
| b0a6ba8180 | |||
| 9b4a05c0f4 | |||
| bfe31c28c8 | |||
| abc1ea9d3f | |||
| 82ca15f70e | |||
| 8cb5bc03c5 | |||
| 939d419438 | |||
| c42df03858 | |||
| 64c1df645d | |||
| 51f22f480b | |||
| 3d1c8f90f3 | |||
| 2fc0f7a74f | |||
| 6cd90ae1dd | |||
| 826756eb6e | |||
| 05fb7bdd0f | |||
| e8f213fded | |||
| 3a8758a4d7 | |||
| 2c8ae43303 |
6
.dockerignore
Normal file
6
.dockerignore
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
*
|
||||||
|
!cmd/
|
||||||
|
!*.go
|
||||||
|
|
||||||
|
!go.mod
|
||||||
|
!go.sum
|
||||||
31
.github/workflows/release.yml
vendored
Normal file
31
.github/workflows/release.yml
vendored
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
name: goreleaser
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
goreleaser:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
-
|
||||||
|
name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
-
|
||||||
|
name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
-
|
||||||
|
name: Run GoReleaser
|
||||||
|
uses: goreleaser/goreleaser-action@v6
|
||||||
|
with:
|
||||||
|
distribution: goreleaser
|
||||||
|
version: '~> v2'
|
||||||
|
args: release --clean
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
30
.github/workflows/update-go-modules.yml
vendored
Normal file
30
.github/workflows/update-go-modules.yml
vendored
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
name: Auto-Update Go Modules
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 0 * * 1" # Runs every Monday at midnight
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
update-go-modules:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: stable
|
||||||
|
|
||||||
|
- name: Update Dependencies
|
||||||
|
run: |
|
||||||
|
go get -u ./...
|
||||||
|
go mod tidy
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
|
git add go.mod go.sum
|
||||||
|
git commit -m "chore: auto-update Go modules"
|
||||||
|
git push
|
||||||
7
.gitignore
vendored
7
.gitignore
vendored
@ -1,3 +1,5 @@
|
|||||||
|
# Auto-generated .gitignore by gignore: github.com/onyx-and-iris/gignore
|
||||||
|
### Go ###
|
||||||
# If you prefer the allow list template instead of the deny list, see community template:
|
# If you prefer the allow list template instead of the deny list, see community template:
|
||||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
||||||
#
|
#
|
||||||
@ -7,6 +9,7 @@
|
|||||||
*.dll
|
*.dll
|
||||||
*.so
|
*.so
|
||||||
*.dylib
|
*.dylib
|
||||||
|
bin/
|
||||||
|
|
||||||
# Test binary, built with `go test -c`
|
# Test binary, built with `go test -c`
|
||||||
*.test
|
*.test
|
||||||
@ -19,3 +22,7 @@
|
|||||||
|
|
||||||
# Go workspace file
|
# Go workspace file
|
||||||
go.work
|
go.work
|
||||||
|
# End of gignore: github.com/onyx-and-iris/gignore
|
||||||
|
|
||||||
|
# Added by goreleaser init:
|
||||||
|
dist/
|
||||||
55
.goreleaser.yaml
Normal file
55
.goreleaser.yaml
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
# This is an example .goreleaser.yml file with some sensible defaults.
|
||||||
|
# Make sure to check the documentation at https://goreleaser.com
|
||||||
|
|
||||||
|
# The lines below are called `modelines`. See `:help modeline`
|
||||||
|
# Feel free to remove those if you don't want/need to use them.
|
||||||
|
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
|
||||||
|
# vim: set ts=2 sw=2 tw=0 fo=cnqoj
|
||||||
|
|
||||||
|
version: 2
|
||||||
|
|
||||||
|
before:
|
||||||
|
hooks:
|
||||||
|
# You may remove this if you don't use go modules.
|
||||||
|
- go mod tidy
|
||||||
|
# you may remove this if you don't need go generate
|
||||||
|
- go generate ./...
|
||||||
|
|
||||||
|
builds:
|
||||||
|
- main: ./cmd/q3rcon-proxy/
|
||||||
|
env:
|
||||||
|
- CGO_ENABLED=0
|
||||||
|
goos:
|
||||||
|
- linux
|
||||||
|
- windows
|
||||||
|
goarch:
|
||||||
|
- amd64
|
||||||
|
|
||||||
|
archives:
|
||||||
|
- formats: ['tar.gz']
|
||||||
|
# this name template makes the OS and Arch compatible with the results of `uname`.
|
||||||
|
name_template: >-
|
||||||
|
{{ .ProjectName }}_
|
||||||
|
{{- title .Os }}_
|
||||||
|
{{- if eq .Arch "amd64" }}x86_64
|
||||||
|
{{- else if eq .Arch "386" }}i386
|
||||||
|
{{- else }}{{ .Arch }}{{ end }}
|
||||||
|
{{- if .Arm }}v{{ .Arm }}{{ end }}
|
||||||
|
# use zip for windows archives
|
||||||
|
format_overrides:
|
||||||
|
- goos: windows
|
||||||
|
formats: ['zip']
|
||||||
|
|
||||||
|
changelog:
|
||||||
|
sort: asc
|
||||||
|
filters:
|
||||||
|
exclude:
|
||||||
|
- '^docs:'
|
||||||
|
- '^test:'
|
||||||
|
|
||||||
|
release:
|
||||||
|
footer: >-
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Released by [GoReleaser](https://github.com/goreleaser/goreleaser).
|
||||||
4
.vscode/launch.json
vendored
4
.vscode/launch.json
vendored
@ -9,9 +9,9 @@
|
|||||||
"type": "go",
|
"type": "go",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"mode": "auto",
|
"mode": "auto",
|
||||||
"program": "${workspaceFolder}/cmd/q3rcon-proxy/main.go",
|
"program": "${workspaceFolder}/cmd/q3rcon-proxy/",
|
||||||
"env": {
|
"env": {
|
||||||
"Q3RCON_PROXY": "28961:28960",
|
"Q3RCON_PORTS_MAPPING": "28961:28960",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
44
CHANGELOG.md
44
CHANGELOG.md
@ -11,6 +11,50 @@ Before any major/minor/patch bump all unit tests will be run to verify they pass
|
|||||||
|
|
||||||
- [x]
|
- [x]
|
||||||
|
|
||||||
|
## [1.7.0] - 2025-06-05
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Taskfile added for running and building project.
|
||||||
|
- The binary may be passed CLI flags as well as environment variables.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- CLI component rewritten with urfave/cli.
|
||||||
|
- env var `Q3RCON_TARGET_PORTS` renamed to `Q3RCON_PORTS_MAPPING`
|
||||||
|
|
||||||
|
## [1.4.0] - 2024-11-29
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- new environment variable `Q3RCON_TARGET_HOST` for setting the host the gameserver is on.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- environment variable `Q3RCON_HOST` renamed to `Q3RCON_PROXY_HOST`
|
||||||
|
- environment variable `Q3RCON_PROXY` renamed to `Q3RCON_TARGET_PORTS`.
|
||||||
|
- default session timeout changed from 5 to 20 minutes.
|
||||||
|
|
||||||
|
## [1.3.0] - 2024-10-23
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Add sessionCache for tracking sessions.
|
||||||
|
- Functional option `WithStaleTimeout` renamed to `WithSessionTimeout`
|
||||||
|
|
||||||
|
## [1.2.0] - 2024-10-19
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- optional function `WithStaleTimeout`, use it to configure the session timeout value.
|
||||||
|
- it defaults to 5 minutes.
|
||||||
|
|
||||||
|
## [1.1.0] - 2024-09-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- connection (challenge) requests are now logged.
|
||||||
|
|
||||||
## [0.6.0] - 2024-03-21
|
## [0.6.0] - 2024-03-21
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
14
Dockerfile
14
Dockerfile
@ -1,14 +0,0 @@
|
|||||||
FROM golang:1.21
|
|
||||||
|
|
||||||
WORKDIR /usr/src/app
|
|
||||||
|
|
||||||
# pre-copy/cache go.mod for pre-downloading dependencies and only redownloading them in subsequent builds if they change
|
|
||||||
COPY go.mod go.sum ./
|
|
||||||
RUN go mod download && go mod verify
|
|
||||||
|
|
||||||
# build binary and place into /usr/local/bin/
|
|
||||||
COPY . .
|
|
||||||
RUN go build -v -o /usr/local/bin/q3rcon-proxy ./cmd/q3rcon-proxy/
|
|
||||||
|
|
||||||
# Command to run when starting the container
|
|
||||||
ENTRYPOINT [ "q3rcon-proxy" ]
|
|
||||||
42
Makefile
42
Makefile
@ -1,2 +1,40 @@
|
|||||||
go-build:
|
PROGRAM = q3rcon-proxy
|
||||||
go build ./cmd/q3rcon-proxy/
|
|
||||||
|
GO = @go
|
||||||
|
BIN_DIR := bin
|
||||||
|
|
||||||
|
WINDOWS=$(BIN_DIR)/$(PROGRAM)_windows_amd64.exe
|
||||||
|
LINUX=$(BIN_DIR)/$(PROGRAM)_linux_amd64
|
||||||
|
VERSION=$(shell git log -n 1 --format=%h)
|
||||||
|
|
||||||
|
.DEFAULT_GOAL := build
|
||||||
|
|
||||||
|
.PHONY: fmt vet build windows linux test clean
|
||||||
|
fmt:
|
||||||
|
$(GO) fmt ./...
|
||||||
|
|
||||||
|
vet: fmt
|
||||||
|
$(GO) vet ./...
|
||||||
|
|
||||||
|
build: vet windows linux | $(BIN_DIR)
|
||||||
|
@echo version: $(VERSION)
|
||||||
|
|
||||||
|
windows: $(WINDOWS)
|
||||||
|
|
||||||
|
linux: $(LINUX)
|
||||||
|
|
||||||
|
|
||||||
|
$(WINDOWS):
|
||||||
|
env GOOS=windows GOARCH=amd64 go build -v -o $(WINDOWS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
|
||||||
|
|
||||||
|
$(LINUX):
|
||||||
|
env GOOS=linux GOARCH=amd64 go build -v -o $(LINUX) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
|
||||||
|
|
||||||
|
test:
|
||||||
|
$(GO) test ./...
|
||||||
|
|
||||||
|
$(BIN_DIR):
|
||||||
|
@mkdir -p $@
|
||||||
|
|
||||||
|
clean:
|
||||||
|
@rm -rv $(BIN_DIR)
|
||||||
72
README.md
72
README.md
@ -2,23 +2,58 @@
|
|||||||
|
|
||||||
A modification of [lilproxy][lilproxy_url] that forwards only Q3 rcon/query packets. Useful for separating the rcon port from the game server port.
|
A modification of [lilproxy][lilproxy_url] that forwards only Q3 rcon/query packets. Useful for separating the rcon port from the game server port.
|
||||||
|
|
||||||
### Use
|
|
||||||
|
|
||||||
Run one or multiple rcon proxies by setting an environment variable `Q3RCON_PROXY`
|
|
||||||
|
|
||||||
for example:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
export Q3RCON_PROXY="20000:28960;20001:28961;20002:28962"
|
|
||||||
```
|
|
||||||
|
|
||||||
This would configure q3rcon-proxy to run 3 proxy servers listening on ports `20000`, `20001` and `20002` that redirect rcon requests to game servers on ports `28960`, `28961` and `28962` respectively.
|
|
||||||
|
|
||||||
Then just run the binary which you can compile yourself, download from `Releases` or use the included Dockerfile.
|
|
||||||
|
|
||||||
### Why
|
### Why
|
||||||
|
|
||||||
Avoid sending plaintext rcon commands to the public game server port. In general I would advise anyone using rcon remotely to use a secured connection but perhaps you've passed rcon to a clan friend who doesn't know about secured connections. Now you can instruct them to use rcon only through a whitelisted port.
|
Unfortunately the Q3Rcon engine ties the rcon port to the game servers public port used for client connections. This proxy will allow you to run rcon through a separate whitelisted port.
|
||||||
|
|
||||||
|
### Use
|
||||||
|
|
||||||
|
#### Flags
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
/usr/local/bin/q3rcon-proxy \
|
||||||
|
--proxy-host=0.0.0.0 \
|
||||||
|
--target-host=localhost \
|
||||||
|
--ports-mapping=28961:28960 \
|
||||||
|
--session-timeout=20 \
|
||||||
|
--loglevel=debug
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Environment Variables
|
||||||
|
|
||||||
|
Each of the flags has a corresponding environment variable:
|
||||||
|
|
||||||
|
- `Q3RCON_PROXY_HOST`: The host the proxy server sits on.
|
||||||
|
- `Q3RCON_TARGET_HOST`: The host the game servers sit on.
|
||||||
|
- `Q3RCON_PORTS_MAPPING`: A mapping as a string with `source:target` pairs delimited by `;`.
|
||||||
|
- `Q3RCON_SESSION_TIMEOUT`: Timeout in seconds for each udp session.
|
||||||
|
- `Q3RCON_LOGLEVEL`: The application's logging level (see [Logging][logging]).
|
||||||
|
|
||||||
|
Multiple rcon proxies may be configured by setting *--ports-mapping/Q3RCON_PORTS_MAPPING* like so:
|
||||||
|
|
||||||
|
```console
|
||||||
|
export Q3RCON_PORTS_MAPPING="20000:28960;20001:28961;20002:28962"
|
||||||
|
```
|
||||||
|
|
||||||
|
This would configure q3rcon-proxy to run 3 proxy servers listening on ports 20000, 20001 and 20002 that redirect rcon requests to game servers on ports 28960, 28961 and 28962 respectively.
|
||||||
|
|
||||||
|
### Logging
|
||||||
|
|
||||||
|
Set the log level with environment variable `Q3RCON_LOGLEVEL`.
|
||||||
|
|
||||||
|
Acceptable values are:
|
||||||
|
|
||||||
|
- `trace`
|
||||||
|
- `debug`
|
||||||
|
- `info`
|
||||||
|
- `warn`
|
||||||
|
- `error`
|
||||||
|
- `fatal`
|
||||||
|
- `panic`
|
||||||
|
|
||||||
|
If not set it will default to `info`.
|
||||||
|
|
||||||
### Special Thanks
|
### Special Thanks
|
||||||
|
|
||||||
@ -26,3 +61,10 @@ Avoid sending plaintext rcon commands to the public game server port. In general
|
|||||||
|
|
||||||
[lilproxy_url]: https://github.com/dgparker/lilproxy
|
[lilproxy_url]: https://github.com/dgparker/lilproxy
|
||||||
[user_link]: https://github.com/dgparker
|
[user_link]: https://github.com/dgparker
|
||||||
|
|
||||||
|
### Further Notes
|
||||||
|
|
||||||
|
For a compatible rcon client also written in Go consider checking out the [Q3 Rcon][q3rcon] package.
|
||||||
|
|
||||||
|
[q3rcon]: https://github.com/onyx-and-iris/q3rcon
|
||||||
|
[logging]: https://github.com/onyx-and-iris/q3rcon-proxy/tree/dev?tab=readme-ov-file#logging
|
||||||
71
Taskfile.yml
Normal file
71
Taskfile.yml
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
version: '3'
|
||||||
|
|
||||||
|
includes:
|
||||||
|
docker: ./docker/Taskfile.docker.yml
|
||||||
|
|
||||||
|
vars:
|
||||||
|
PROGRAM: q3rcon-proxy
|
||||||
|
SHELL: '{{if eq .OS "Windows_NT"}}powershell{{end}}'
|
||||||
|
BIN_DIR: bin
|
||||||
|
|
||||||
|
WINDOWS: '{{.BIN_DIR}}/{{.PROGRAM}}_windows_amd64.exe'
|
||||||
|
LINUX: '{{.BIN_DIR}}/{{.PROGRAM}}_linux_amd64'
|
||||||
|
GIT_COMMIT:
|
||||||
|
sh: git log -n 1 --format=%h
|
||||||
|
|
||||||
|
tasks:
|
||||||
|
default:
|
||||||
|
desc: Build the q3rcon-proxy project
|
||||||
|
cmds:
|
||||||
|
- task: build
|
||||||
|
|
||||||
|
build:
|
||||||
|
desc: Build the q3rcon-proxy project
|
||||||
|
deps: [vet]
|
||||||
|
cmds:
|
||||||
|
- task: build-windows
|
||||||
|
- task: build-linux
|
||||||
|
|
||||||
|
vet:
|
||||||
|
desc: Vet the code
|
||||||
|
deps: [fmt]
|
||||||
|
cmds:
|
||||||
|
- go vet ./...
|
||||||
|
|
||||||
|
fmt:
|
||||||
|
desc: Fmt the code
|
||||||
|
cmds:
|
||||||
|
- go fmt ./...
|
||||||
|
|
||||||
|
build-windows:
|
||||||
|
desc: Build the q3rcon-proxy project for Windows
|
||||||
|
cmds:
|
||||||
|
- GOOS=windows GOARCH=amd64 go build -o {{.WINDOWS}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/
|
||||||
|
internal: true
|
||||||
|
|
||||||
|
build-linux:
|
||||||
|
desc: Build the q3rcon-proxy project for Linux
|
||||||
|
cmds:
|
||||||
|
- GOOS=linux GOARCH=amd64 go build -o {{.LINUX}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/
|
||||||
|
internal: true
|
||||||
|
|
||||||
|
test:
|
||||||
|
desc: Run tests
|
||||||
|
cmds:
|
||||||
|
- go test ./...
|
||||||
|
|
||||||
|
clean:
|
||||||
|
desc: Clean the build artifacts
|
||||||
|
cmds:
|
||||||
|
- '{{.SHELL}} rm -r {{.BIN_DIR}}'
|
||||||
|
|
||||||
|
run:
|
||||||
|
desc: Run the q3rcon-proxy project
|
||||||
|
cmds:
|
||||||
|
- |
|
||||||
|
go run ./cmd/{{.PROGRAM}} \
|
||||||
|
--proxy-host=0.0.0.0 \
|
||||||
|
--target-host=localhost \
|
||||||
|
--ports-mapping=28961:28960 \
|
||||||
|
--session-timeout=20 \
|
||||||
|
--loglevel=debug
|
||||||
@ -1,76 +1,132 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
udpproxy "github.com/onyx-and-iris/q3rcon-proxy"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
|
"github.com/urfave/cli/v3"
|
||||||
"github.com/onyx-and-iris/q3rcon-proxy/pkg/udpproxy"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func start(proxy string) {
|
// proxyConfig holds the configuration for a single UDP proxy server.
|
||||||
port, target := func() (string, string) {
|
type proxyConfig struct {
|
||||||
x := strings.Split(proxy, ":")
|
proxyHost string
|
||||||
return x[0], x[1]
|
targetHost string
|
||||||
}()
|
portsMapping []string
|
||||||
|
sessionTimeout int
|
||||||
c, err := udpproxy.New(fmt.Sprintf("%s:%s", host, port), fmt.Sprintf("127.0.0.1:%s", target))
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("q3rcon-proxy initialized: [proxy] (%s:%s) [target] (127.0.0.1:%s)", host, port, target)
|
|
||||||
|
|
||||||
log.Fatal(c.ListenAndServe())
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
proxies, host string
|
|
||||||
)
|
|
||||||
|
|
||||||
func getenvInt(key string) (int, error) {
|
|
||||||
s := os.Getenv(key)
|
|
||||||
if s == "" {
|
|
||||||
return 0, nil
|
|
||||||
}
|
|
||||||
v, err := strconv.Atoi(s)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return v, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
proxies = os.Getenv("Q3RCON_PROXY")
|
|
||||||
if proxies == "" {
|
|
||||||
log.Fatal("env Q3RCON_PROXY required")
|
|
||||||
}
|
|
||||||
|
|
||||||
host = os.Getenv("Q3RCON_HOST")
|
|
||||||
if host == "" {
|
|
||||||
host = "0.0.0.0"
|
|
||||||
}
|
|
||||||
|
|
||||||
debug, err := getenvInt("Q3RCON_DEBUG")
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if debug == 1 {
|
|
||||||
log.SetLevel(log.DebugLevel)
|
|
||||||
} else {
|
|
||||||
log.SetLevel(log.InfoLevel)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
for _, proxy := range strings.Split(proxies, ";") {
|
cmd := &cli.Command{
|
||||||
go start(proxy)
|
Name: "q3rcon-proxy",
|
||||||
|
Usage: "A Quake 3 RCON proxy server",
|
||||||
|
Flags: []cli.Flag{
|
||||||
|
&cli.StringFlag{
|
||||||
|
Name: "proxy-host",
|
||||||
|
Value: "0.0.0.0",
|
||||||
|
Usage: "Proxy host address",
|
||||||
|
Sources: cli.EnvVars("Q3RCON_PROXY_HOST"),
|
||||||
|
},
|
||||||
|
&cli.StringFlag{
|
||||||
|
Name: "target-host",
|
||||||
|
Value: "localhost",
|
||||||
|
Usage: "Target host address",
|
||||||
|
Sources: cli.EnvVars("Q3RCON_TARGET_HOST"),
|
||||||
|
},
|
||||||
|
&cli.StringFlag{
|
||||||
|
Name: "ports-mapping",
|
||||||
|
Usage: "Proxy and target ports (proxy:target)",
|
||||||
|
Sources: cli.EnvVars("Q3RCON_PORTS_MAPPING"),
|
||||||
|
Required: true,
|
||||||
|
Action: func(ctx context.Context, cmd *cli.Command, v string) error {
|
||||||
|
// Validate the ports mapping
|
||||||
|
for mapping := range strings.SplitSeq(v, ";") {
|
||||||
|
ports := strings.Split(mapping, ":")
|
||||||
|
if len(ports) != 2 {
|
||||||
|
return fmt.Errorf("invalid ports mapping: %s", mapping)
|
||||||
|
}
|
||||||
|
proxyPort, err := strconv.Atoi(ports[0])
|
||||||
|
if err != nil || proxyPort < 1 || proxyPort > 65535 {
|
||||||
|
return fmt.Errorf("invalid proxy port: %s", ports[0])
|
||||||
|
}
|
||||||
|
targetPort, err := strconv.Atoi(ports[1])
|
||||||
|
if err != nil || targetPort < 1 || targetPort > 65535 {
|
||||||
|
return fmt.Errorf("invalid target port: %s", ports[1])
|
||||||
|
}
|
||||||
|
if proxyPort == targetPort {
|
||||||
|
return fmt.Errorf("proxy and target ports cannot be the same: %s", mapping)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
},
|
||||||
|
&cli.IntFlag{
|
||||||
|
Name: "session-timeout",
|
||||||
|
Value: 20,
|
||||||
|
Usage: "Session timeout in minutes",
|
||||||
|
Sources: cli.EnvVars("Q3RCON_SESSION_TIMEOUT"),
|
||||||
|
},
|
||||||
|
&cli.StringFlag{
|
||||||
|
Name: "loglevel",
|
||||||
|
Value: "info",
|
||||||
|
Usage: "Log level (trace, debug, info, warn, error, fatal, panic)",
|
||||||
|
Sources: cli.EnvVars("Q3RCON_LOGLEVEL"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) {
|
||||||
|
logLevel, err := log.ParseLevel(cmd.String("loglevel"))
|
||||||
|
if err != nil {
|
||||||
|
return ctx, fmt.Errorf("invalid log level: %w", err)
|
||||||
|
}
|
||||||
|
log.SetLevel(logLevel)
|
||||||
|
return ctx, nil
|
||||||
|
},
|
||||||
|
Action: func(_ context.Context, cmd *cli.Command) error {
|
||||||
|
errChan := make(chan error)
|
||||||
|
|
||||||
|
for mapping := range strings.SplitSeq(cmd.String("ports-mapping"), ";") {
|
||||||
|
cfg := proxyConfig{
|
||||||
|
proxyHost: cmd.String("proxy-host"),
|
||||||
|
targetHost: cmd.String("target-host"),
|
||||||
|
portsMapping: strings.Split(mapping, ":"),
|
||||||
|
sessionTimeout: cmd.Int("session-timeout"),
|
||||||
|
}
|
||||||
|
|
||||||
|
go launchProxy(cfg, errChan)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Under normal circumstances, the main goroutine will block here.
|
||||||
|
// If we receive an error we will log it and exit
|
||||||
|
return <-errChan
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
<-make(chan int)
|
log.Fatal(cmd.Run(context.Background(), os.Args))
|
||||||
|
}
|
||||||
|
|
||||||
|
// launchProxy initializes the UDP proxy server with the given configuration.
|
||||||
|
// It listens on the specified proxy host and port, and forwards traffic to the target host and port.
|
||||||
|
// server.ListenAndServe blocks until the server is stopped or an error occurs.
|
||||||
|
func launchProxy(cfg proxyConfig, errChan chan<- error) {
|
||||||
|
proxyPort, targetPort := cfg.portsMapping[0], cfg.portsMapping[1]
|
||||||
|
|
||||||
|
hostAddr := fmt.Sprintf("%s:%s", cfg.proxyHost, proxyPort)
|
||||||
|
proxyAddr := fmt.Sprintf("%s:%s", cfg.targetHost, targetPort)
|
||||||
|
|
||||||
|
server, err := udpproxy.New(
|
||||||
|
hostAddr, proxyAddr,
|
||||||
|
udpproxy.WithSessionTimeout(time.Duration(cfg.sessionTimeout)*time.Minute))
|
||||||
|
if err != nil {
|
||||||
|
errChan <- fmt.Errorf("failed to create proxy: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("q3rcon-proxy initialized: [proxy] (%s) [target] (%s)", hostAddr, proxyAddr)
|
||||||
|
|
||||||
|
errChan <- server.ListenAndServe()
|
||||||
}
|
}
|
||||||
|
|||||||
4
debian/q3rcon-proxy.service
vendored
4
debian/q3rcon-proxy.service
vendored
@ -6,9 +6,9 @@ After=network.target
|
|||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
User=gameservers
|
User=gameservers
|
||||||
Environment="Q3RCON_PROXY=20000:28960;20001:28961;20002:28962"
|
Environment="Q3RCON_PORTS_MAPPING=20000:28960;20001:28961;20002:28962"
|
||||||
Environment="Q3RCON_HOST=0.0.0.0"
|
Environment="Q3RCON_HOST=0.0.0.0"
|
||||||
Environment="Q3RCON_DEBUG=0"
|
Environment="Q3RCON_LOGLEVEL=info"
|
||||||
|
|
||||||
ExecStart=/usr/local/bin/q3rcon-proxy
|
ExecStart=/usr/local/bin/q3rcon-proxy
|
||||||
Restart=always
|
Restart=always
|
||||||
|
|||||||
21
docker/Dockerfile
Normal file
21
docker/Dockerfile
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
FROM golang:1.24 AS build_image
|
||||||
|
|
||||||
|
WORKDIR /usr/src/app
|
||||||
|
|
||||||
|
# pre-copy/cache go.mod for pre-downloading dependencies and only redownloading them in subsequent builds if they change
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download && go mod verify
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# build binary, place into ./bin/
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux go build -o ./bin/q3rcon-proxy ./cmd/q3rcon-proxy/
|
||||||
|
|
||||||
|
FROM scratch AS final_image
|
||||||
|
|
||||||
|
WORKDIR /bin/
|
||||||
|
|
||||||
|
COPY --from=build_image /usr/src/app/bin/q3rcon-proxy .
|
||||||
|
|
||||||
|
# Command to run when starting the container
|
||||||
|
ENTRYPOINT [ "./q3rcon-proxy" ]
|
||||||
26
docker/Taskfile.docker.yml
Normal file
26
docker/Taskfile.docker.yml
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
version: '3'
|
||||||
|
|
||||||
|
vars:
|
||||||
|
IMAGE: q3rcon-proxy
|
||||||
|
|
||||||
|
tasks:
|
||||||
|
build:
|
||||||
|
desc: Build the Docker image
|
||||||
|
cmds:
|
||||||
|
- docker build -t {{.IMAGE}} -f docker/Dockerfile .
|
||||||
|
dir: .
|
||||||
|
|
||||||
|
login:
|
||||||
|
desc: Login to Github Container Registry
|
||||||
|
cmds:
|
||||||
|
- docker login ghcr.io -u {{.GHCR_USER}} --password-stdin <<< {{.GHCR_TOKEN}}
|
||||||
|
internal: true
|
||||||
|
|
||||||
|
push:
|
||||||
|
desc: Push the Docker image to Github Container Registry
|
||||||
|
deps:
|
||||||
|
- task: build
|
||||||
|
- task: login
|
||||||
|
cmds:
|
||||||
|
- docker tag {{.IMAGE}} ghcr.io/{{.GHCR_USER}}/{{.IMAGE}}:latest
|
||||||
|
- docker push ghcr.io/{{.GHCR_USER}}/{{.IMAGE}}:latest
|
||||||
11
go.mod
11
go.mod
@ -1,7 +1,12 @@
|
|||||||
module github.com/onyx-and-iris/q3rcon-proxy
|
module github.com/onyx-and-iris/q3rcon-proxy
|
||||||
|
|
||||||
go 1.18
|
go 1.24.0
|
||||||
|
|
||||||
require github.com/sirupsen/logrus v1.9.3
|
toolchain go1.24.1
|
||||||
|
|
||||||
require golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
|
require (
|
||||||
|
github.com/sirupsen/logrus v1.9.3
|
||||||
|
github.com/urfave/cli/v3 v3.6.1
|
||||||
|
)
|
||||||
|
|
||||||
|
require golang.org/x/sys v0.39.0 // indirect
|
||||||
|
|||||||
11
go.sum
11
go.sum
@ -6,10 +6,15 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
|
|||||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/urfave/cli/v3 v3.6.1 h1:j8Qq8NyUawj/7rTYdBGrxcH7A/j7/G8Q5LhWEW4G3Mo=
|
||||||
|
github.com/urfave/cli/v3 v3.6.1/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso=
|
||||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||||
|
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
22
option.go
Normal file
22
option.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package udpproxy
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Option is a functional option type that allows us to configure the Client.
|
||||||
|
type Option func(*Client)
|
||||||
|
|
||||||
|
// WithSessionTimeout is a functional option to set the session timeout
|
||||||
|
func WithSessionTimeout(timeout time.Duration) Option {
|
||||||
|
return func(c *Client) {
|
||||||
|
if timeout < time.Minute {
|
||||||
|
log.Warnf("cannot set stale session timeout to less than 1 minute.. defaulting to 20 minutes")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.sessionTimeout = timeout
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,32 +0,0 @@
|
|||||||
package udpproxy
|
|
||||||
|
|
||||||
type validator struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *validator) isRconRequestPacket(buf []byte) bool {
|
|
||||||
return string(buf[:8]) == "\xff\xff\xff\xffrcon"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *validator) isQueryRequestPacket(buf []byte) bool {
|
|
||||||
return string(buf[:13]) == "\xff\xff\xff\xffgetstatus" || string(buf[:11]) == "\xff\xff\xff\xffgetinfo"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *validator) isValidRequestPacket(buf []byte) bool {
|
|
||||||
return v.isRconRequestPacket(buf) || v.isQueryRequestPacket(buf)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *validator) isRconResponsePacket(buf []byte) bool {
|
|
||||||
return string(buf[:9]) == "\xff\xff\xff\xffprint"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *validator) isQueryResponsePacket(buf []byte) bool {
|
|
||||||
return string(buf[:18]) == "\xff\xff\xff\xffstatusResponse" || string(buf[:16]) == "\xff\xff\xff\xffinfoResponse"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *validator) isValidResponsePacket(buf []byte) bool {
|
|
||||||
return v.isRconResponsePacket(buf) || v.isQueryResponsePacket(buf)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *validator) isBadRconResponse(buf []byte) bool {
|
|
||||||
return string(buf[10:18]) == "Bad rcon"
|
|
||||||
}
|
|
||||||
@ -2,6 +2,7 @@ package udpproxy
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@ -29,6 +30,7 @@ func newSession(caddr *net.UDPAddr, raddr *net.UDPAddr, proxyConn *net.UDPConn)
|
|||||||
proxyConn: proxyConn,
|
proxyConn: proxyConn,
|
||||||
caddr: caddr,
|
caddr: caddr,
|
||||||
updateTime: time.Now(),
|
updateTime: time.Now(),
|
||||||
|
validator: newValidator(),
|
||||||
}
|
}
|
||||||
|
|
||||||
go session.listen()
|
go session.listen()
|
||||||
@ -37,8 +39,8 @@ func newSession(caddr *net.UDPAddr, raddr *net.UDPAddr, proxyConn *net.UDPConn)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *session) listen() error {
|
func (s *session) listen() error {
|
||||||
|
buf := make([]byte, 2048)
|
||||||
for {
|
for {
|
||||||
buf := make([]byte, 2048)
|
|
||||||
n, err := s.serverConn.Read(buf)
|
n, err := s.serverConn.Read(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error(err)
|
log.Error(err)
|
||||||
@ -67,7 +69,7 @@ func (s *session) proxyFrom(buf []byte) error {
|
|||||||
if s.isBadRconResponse(buf) {
|
if s.isBadRconResponse(buf) {
|
||||||
log.Infof("Response: Bad rcon from %s", s.caddr.IP)
|
log.Infof("Response: Bad rcon from %s", s.caddr.IP)
|
||||||
} else {
|
} else {
|
||||||
log.Debugf("Response: %s", string(buf[10:]))
|
log.Debugf("Response: %s", string(buf[len(s.rconResponseHeader):]))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -76,7 +78,13 @@ func (s *session) proxyFrom(buf []byte) error {
|
|||||||
|
|
||||||
func (s *session) proxyTo(buf []byte) error {
|
func (s *session) proxyTo(buf []byte) error {
|
||||||
if !s.isValidRequestPacket(buf) {
|
if !s.isValidRequestPacket(buf) {
|
||||||
err := errors.New("not a rcon or query request packet")
|
var err error
|
||||||
|
if s.isChallengeRequestPacket(buf) {
|
||||||
|
parts := strings.SplitN(string(buf), " ", 3)
|
||||||
|
err = fmt.Errorf("invalid challenge from %s with GUID: %s", s.caddr.IP, parts[len(parts)-1])
|
||||||
|
} else {
|
||||||
|
err = errors.New("not a rcon or query request packet")
|
||||||
|
}
|
||||||
log.Error(err.Error())
|
log.Error(err.Error())
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -89,8 +97,8 @@ func (s *session) proxyTo(buf []byte) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if s.isRconRequestPacket(buf) {
|
if s.isRconRequestPacket(buf) {
|
||||||
parts := strings.Split(string(buf), " ")
|
parts := strings.SplitN(string(buf), " ", 3)
|
||||||
log.Infof("From [%s] To [%s] Command: %s", s.caddr.IP, s.serverConn.RemoteAddr(), strings.Join(parts[2:], " "))
|
log.Infof("From [%s] To [%s] Command: %s", s.caddr.IP, s.serverConn.RemoteAddr(), parts[len(parts)-1])
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
41
sessioncache.go
Normal file
41
sessioncache.go
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
package udpproxy
|
||||||
|
|
||||||
|
import "sync"
|
||||||
|
|
||||||
|
// sessionCache tracks connection sessions
|
||||||
|
type sessionCache struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
data map[string]*session
|
||||||
|
}
|
||||||
|
|
||||||
|
// newSessionCache creates a usable sessionCache.
|
||||||
|
func newSessionCache() sessionCache {
|
||||||
|
return sessionCache{
|
||||||
|
data: make(map[string]*session),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// read returns the associated session for an addr
|
||||||
|
func (sc *sessionCache) read(addr string) (*session, bool) {
|
||||||
|
sc.mu.RLock()
|
||||||
|
defer sc.mu.RUnlock()
|
||||||
|
|
||||||
|
v, ok := sc.data[addr]
|
||||||
|
return v, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// insert adds a session for a given addr.
|
||||||
|
func (sc *sessionCache) insert(addr string, session *session) {
|
||||||
|
sc.mu.Lock()
|
||||||
|
defer sc.mu.Unlock()
|
||||||
|
|
||||||
|
sc.data[addr] = session
|
||||||
|
}
|
||||||
|
|
||||||
|
// delete removes the session for the given addr.
|
||||||
|
func (sc *sessionCache) delete(addr string) {
|
||||||
|
sc.mu.Lock()
|
||||||
|
defer sc.mu.Unlock()
|
||||||
|
|
||||||
|
delete(sc.data, addr)
|
||||||
|
}
|
||||||
@ -2,7 +2,6 @@ package udpproxy
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
@ -14,12 +13,12 @@ type Client struct {
|
|||||||
|
|
||||||
proxyConn *net.UDPConn
|
proxyConn *net.UDPConn
|
||||||
|
|
||||||
mutex sync.RWMutex
|
sessionCache sessionCache
|
||||||
sessions map[string]*session
|
sessionTimeout time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(port, target string) (*Client, error) {
|
func New(proxy, target string, options ...Option) (*Client, error) {
|
||||||
laddr, err := net.ResolveUDPAddr("udp", port)
|
laddr, err := net.ResolveUDPAddr("udp", proxy)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -29,12 +28,18 @@ func New(port, target string) (*Client, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Client{
|
c := &Client{
|
||||||
laddr: laddr,
|
laddr: laddr,
|
||||||
raddr: raddr,
|
raddr: raddr,
|
||||||
mutex: sync.RWMutex{},
|
sessionCache: newSessionCache(),
|
||||||
sessions: map[string]*session{},
|
sessionTimeout: 20 * time.Minute,
|
||||||
}, nil
|
}
|
||||||
|
|
||||||
|
for _, o := range options {
|
||||||
|
o(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) ListenAndServe() error {
|
func (c *Client) ListenAndServe() error {
|
||||||
@ -46,22 +51,22 @@ func (c *Client) ListenAndServe() error {
|
|||||||
|
|
||||||
go c.pruneSessions()
|
go c.pruneSessions()
|
||||||
|
|
||||||
|
buf := make([]byte, 2048)
|
||||||
for {
|
for {
|
||||||
buf := make([]byte, 2048)
|
|
||||||
n, caddr, err := c.proxyConn.ReadFromUDP(buf)
|
n, caddr, err := c.proxyConn.ReadFromUDP(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error(err)
|
log.Error(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
session, found := c.sessions[caddr.String()]
|
session, ok := c.sessionCache.read(caddr.String())
|
||||||
if !found {
|
if !ok {
|
||||||
session, err = newSession(caddr, c.raddr, c.proxyConn)
|
session, err = newSession(caddr, c.raddr, c.proxyConn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error(err)
|
log.Error(err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
c.sessions[caddr.String()] = session
|
c.sessionCache.insert(caddr.String(), session)
|
||||||
}
|
}
|
||||||
|
|
||||||
go session.proxyTo(buf[:n])
|
go session.proxyTo(buf[:n])
|
||||||
@ -71,15 +76,12 @@ func (c *Client) ListenAndServe() error {
|
|||||||
func (c *Client) pruneSessions() {
|
func (c *Client) pruneSessions() {
|
||||||
ticker := time.NewTicker(1 * time.Minute)
|
ticker := time.NewTicker(1 * time.Minute)
|
||||||
|
|
||||||
// the locks here could be abusive and i dont even know if this is a real
|
|
||||||
// problem but we definitely need to clean up stale sessions
|
|
||||||
for range ticker.C {
|
for range ticker.C {
|
||||||
for _, session := range c.sessions {
|
for _, session := range c.sessionCache.data {
|
||||||
c.mutex.RLock()
|
if time.Since(session.updateTime) > c.sessionTimeout {
|
||||||
if time.Since(session.updateTime) > time.Minute*5 {
|
c.sessionCache.delete(session.caddr.String())
|
||||||
delete(c.sessions, session.caddr.String())
|
log.Tracef("session for %s deleted", session.caddr)
|
||||||
}
|
}
|
||||||
c.mutex.RUnlock()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
65
validator.go
Normal file
65
validator.go
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
package udpproxy
|
||||||
|
|
||||||
|
import "bytes"
|
||||||
|
|
||||||
|
type validator struct {
|
||||||
|
rconRequestHeader []byte
|
||||||
|
getstatusRequestHeader []byte
|
||||||
|
getinfoRequestHeader []byte
|
||||||
|
getchallengeRequestHeader []byte
|
||||||
|
rconResponseHeader []byte
|
||||||
|
getstatusResponseHeader []byte
|
||||||
|
getinfoResponseHeader []byte
|
||||||
|
badRconIdentifier []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func newValidator() validator {
|
||||||
|
return validator{
|
||||||
|
rconRequestHeader: []byte("\xff\xff\xff\xffrcon"),
|
||||||
|
getstatusRequestHeader: []byte("\xff\xff\xff\xffgetstatus"),
|
||||||
|
getinfoRequestHeader: []byte("\xff\xff\xff\xffgetinfo"),
|
||||||
|
getchallengeRequestHeader: []byte("\xff\xff\xff\xffgetchallenge"),
|
||||||
|
rconResponseHeader: []byte("\xff\xff\xff\xffprint\n"),
|
||||||
|
getstatusResponseHeader: []byte("\xff\xff\xff\xffstatusResponse\n"),
|
||||||
|
getinfoResponseHeader: []byte("\xff\xff\xff\xffinfoResponse\n"),
|
||||||
|
badRconIdentifier: []byte("Bad rcon"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v validator) compare(buf, c []byte) bool {
|
||||||
|
return bytes.Equal(buf[:len(c)], c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v validator) isRconRequestPacket(buf []byte) bool {
|
||||||
|
return v.compare(buf, v.rconRequestHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v validator) isQueryRequestPacket(buf []byte) bool {
|
||||||
|
return v.compare(buf, v.getstatusRequestHeader) ||
|
||||||
|
v.compare(buf, v.getinfoRequestHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v validator) isValidRequestPacket(buf []byte) bool {
|
||||||
|
return v.isRconRequestPacket(buf) || v.isQueryRequestPacket(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v validator) isChallengeRequestPacket(buf []byte) bool {
|
||||||
|
return v.compare(buf, v.getchallengeRequestHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v validator) isRconResponsePacket(buf []byte) bool {
|
||||||
|
return v.compare(buf, v.rconResponseHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v validator) isQueryResponsePacket(buf []byte) bool {
|
||||||
|
return v.compare(buf, v.getstatusResponseHeader) ||
|
||||||
|
v.compare(buf, v.getinfoResponseHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v validator) isValidResponsePacket(buf []byte) bool {
|
||||||
|
return v.isRconResponsePacket(buf) || v.isQueryResponsePacket(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v validator) isBadRconResponse(buf []byte) bool {
|
||||||
|
return v.compare(buf[len(v.rconResponseHeader):], v.badRconIdentifier)
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user