mirror of
https://github.com/onyx-and-iris/q3rcon-proxy.git
synced 2026-03-03 23:59:11 +00:00
Compare commits
71 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
251168d2d4 | ||
|
|
ca006d7d73 | ||
| 225188bb70 | |||
| 63cf99b217 | |||
| 7a83fd6573 | |||
| b494e6cf8f | |||
| 9be4344144 | |||
| 775979bfc8 | |||
| 6bffa14240 | |||
| 74493e6f61 | |||
| 51a0065e79 | |||
| f07a45c81b | |||
| a70fdecdbb | |||
| fc6ac8fa4e | |||
| f6ea67b88c | |||
| d18834b290 | |||
| 46874f2cf5 | |||
| 1c5e18294e | |||
|
|
331bb61882 | ||
| 3db79314ce | |||
|
|
ecfbd8771b | ||
|
|
991e063390 | ||
|
|
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 |
6
.dockerignore
Normal file
6
.dockerignore
Normal file
@ -0,0 +1,6 @@
|
||||
*
|
||||
!cmd/
|
||||
!*.go
|
||||
|
||||
!go.mod
|
||||
!go.sum
|
||||
30
.github/workflows/golang-ci.yml
vendored
Normal file
30
.github/workflows/golang-ci.yml
vendored
Normal file
@ -0,0 +1,30 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['main']
|
||||
paths:
|
||||
- '**.go'
|
||||
pull_request:
|
||||
branches: ['main']
|
||||
paths:
|
||||
- '**.go'
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'pull_request'
|
||||
timeout-minutes: 3
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.24'
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
version: v2.6.0
|
||||
args: --config .golangci.yml
|
||||
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
|
||||
12
.gitignore
vendored
12
.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:
|
||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
||||
#
|
||||
@ -7,6 +9,7 @@
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
bin/
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
@ -19,7 +22,10 @@
|
||||
|
||||
# Go workspace file
|
||||
go.work
|
||||
# End of gignore: github.com/onyx-and-iris/gignore
|
||||
|
||||
# testing
|
||||
run.sh
|
||||
server.yaml
|
||||
# Added by goreleaser init:
|
||||
dist/
|
||||
|
||||
# env files
|
||||
.envrc
|
||||
142
.golangci.yml
Normal file
142
.golangci.yml
Normal file
@ -0,0 +1,142 @@
|
||||
version: '2'
|
||||
|
||||
run:
|
||||
timeout: 3m
|
||||
tests: true
|
||||
go: '1.24'
|
||||
|
||||
linters:
|
||||
disable: [errcheck]
|
||||
enable:
|
||||
# Default enabled linters
|
||||
- errcheck # Check for unchecked errors
|
||||
- govet # Go's built-in vetting tool
|
||||
- ineffassign # Detect ineffectual assignments
|
||||
- staticcheck # Advanced static analysis
|
||||
- unused # Check for unused code
|
||||
# Additional useful linters
|
||||
- misspell # Detect common misspellings
|
||||
- unparam # Check for unused function parameters
|
||||
- gosec # Security checks
|
||||
- asciicheck # Check for non-ASCII characters
|
||||
- errname # Check error variable names
|
||||
- godot # Check for missing periods in comments
|
||||
- revive # Highly configurable linter for style and correctness
|
||||
- gocritic # Detect code issues and suggest improvements
|
||||
- gocyclo # Check for cyclomatic complexity
|
||||
- dupl # Check for code duplication
|
||||
- predeclared # Check for shadowing of predeclared identifiers
|
||||
- copyloopvar # Check for loop variable capture in goroutines
|
||||
- errorlint # Check for common mistakes in error handling
|
||||
- goconst # Check for repeated strings that could be constants
|
||||
- gosmopolitan # Check for non-portable code
|
||||
|
||||
settings:
|
||||
misspell:
|
||||
locale: UK
|
||||
|
||||
errcheck:
|
||||
check-type-assertions: true
|
||||
check-blank: true
|
||||
exclude-functions:
|
||||
- fmt.Fprintf
|
||||
- fmt.Fprintln
|
||||
- fmt.Printf
|
||||
- fmt.Println
|
||||
- fmt.Errorf
|
||||
|
||||
revive:
|
||||
severity: warning
|
||||
rules:
|
||||
# Code quality and style
|
||||
- name: exported
|
||||
arguments:
|
||||
- 'checkPrivateReceivers'
|
||||
- 'sayRepetitiveInsteadOfStutters'
|
||||
- name: var-naming
|
||||
- name: package-comments
|
||||
- name: range-val-in-closure
|
||||
- name: time-naming
|
||||
- name: context-as-argument
|
||||
- name: context-keys-type
|
||||
- name: dot-imports
|
||||
- name: empty-block
|
||||
- name: error-return
|
||||
- name: error-strings
|
||||
- name: error-naming
|
||||
- name: if-return
|
||||
- name: increment-decrement
|
||||
- name: indent-error-flow
|
||||
- name: receiver-naming
|
||||
- name: redefines-builtin-id
|
||||
- name: superfluous-else
|
||||
- name: unexported-return
|
||||
- name: unreachable-code
|
||||
- name: unused-parameter
|
||||
- name: var-declaration
|
||||
- name: blank-imports
|
||||
- name: range
|
||||
|
||||
# Disabled rules (can be enabled if needed)
|
||||
# - name: line-length-limit
|
||||
# arguments: [120]
|
||||
# - name: function-length
|
||||
# arguments: [50, 0]
|
||||
# - name: cyclomatic
|
||||
# arguments: [10]
|
||||
|
||||
gosec:
|
||||
excludes:
|
||||
- G104 # Duplicated errcheck checks
|
||||
- G115 # integer overflow conversion int -> uint32
|
||||
|
||||
exclusions:
|
||||
warn-unused: false
|
||||
rules:
|
||||
# Exclude some linters from running on tests files.
|
||||
- path: _test\.go
|
||||
linters:
|
||||
- gocyclo
|
||||
- errcheck
|
||||
- dupl
|
||||
- gosec
|
||||
|
||||
paths:
|
||||
- vendor
|
||||
|
||||
# Formatters configuration
|
||||
formatters:
|
||||
# Enable specific formatters
|
||||
enable:
|
||||
- gofumpt # Stricter gofmt alternative
|
||||
- goimports # Organizes imports
|
||||
- gci # Controls import order/grouping
|
||||
- golines # Enforces line length
|
||||
|
||||
# Formatter-specific settings
|
||||
settings:
|
||||
goimports:
|
||||
local-prefixes: [github.com/onyx-and-iris/q3rcon-proxy]
|
||||
|
||||
gci:
|
||||
# Define import sections order
|
||||
sections:
|
||||
- standard # Standard library
|
||||
- default # Everything else
|
||||
- prefix(github.com/onyx-and-iris/q3rcon-proxy) # Current module
|
||||
|
||||
gofumpt:
|
||||
extra-rules: true # Enable additional formatting rules
|
||||
|
||||
exclusions:
|
||||
warn-unused: true
|
||||
|
||||
paths:
|
||||
- vendor
|
||||
|
||||
issues:
|
||||
# Limit the number of same issues reported to avoid spam
|
||||
max-same-issues: 50
|
||||
|
||||
# Limit the number of issues per linter to keep output manageable
|
||||
max-issues-per-linter: 100
|
||||
57
.goreleaser.yaml
Normal file
57
.goreleaser.yaml
Normal file
@ -0,0 +1,57 @@
|
||||
# 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
|
||||
- darwin
|
||||
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:'
|
||||
- '^chore:'
|
||||
|
||||
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",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}/cmd/q3rcon-proxy/main.go",
|
||||
"program": "${workspaceFolder}/cmd/q3rcon-proxy/",
|
||||
"env": {
|
||||
"Q3RCON_PROXY": "28961:28960",
|
||||
"Q3RCON_PORTS_MAPPING": "28961:28960",
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
62
CHANGELOG.md
62
CHANGELOG.md
@ -11,6 +11,67 @@ Before any major/minor/patch bump all unit tests will be run to verify they pass
|
||||
|
||||
- [x]
|
||||
|
||||
## [1.8.0] - 2026-02-18
|
||||
|
||||
### Changed
|
||||
|
||||
- *--ports-mapping* flag has been replaced with *--port-map*, which may be called several times. See [Flags](https://github.com/onyx-and-iris/q3rcon-proxy?tab=readme-ov-file#flags).
|
||||
- This also affects the env variable which is now `Q3RCON_PORT_MAP`, see [Environment Variables](https://github.com/onyx-and-iris/q3rcon-proxy?tab=readme-ov-file#environment-variables)
|
||||
|
||||
## [1.7.3] - 2026-02-16
|
||||
|
||||
### Added
|
||||
|
||||
- *--version/-v* flag for printing the version of the CLI.
|
||||
|
||||
### Changed
|
||||
|
||||
- now using [charmbracelet/log][charmlog] package for logging.
|
||||
|
||||
## [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
|
||||
|
||||
### Added
|
||||
@ -55,3 +116,4 @@ Before any major/minor/patch bump all unit tests will be run to verify they pass
|
||||
- All source files for lilproxy including full commit history.
|
||||
|
||||
[logrus]: https://github.com/sirupsen/logrus
|
||||
[charmlog]: https://github.com/charmbracelet/log
|
||||
|
||||
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" ]
|
||||
48
Makefile
48
Makefile
@ -1,2 +1,46 @@
|
||||
go-build:
|
||||
go build ./cmd/q3rcon-proxy/
|
||||
PROGRAM = q3rcon-proxy
|
||||
|
||||
GO = @go
|
||||
BIN_DIR := bin
|
||||
|
||||
WINDOWS=$(BIN_DIR)/$(PROGRAM)_windows_amd64.exe
|
||||
LINUX=$(BIN_DIR)/$(PROGRAM)_linux_amd64
|
||||
MACOS=$(BIN_DIR)/$(PROGRAM)_darwin_amd64
|
||||
VERSION=$(shell git describe --tags $(shell git rev-list --tags --max-count=1))
|
||||
|
||||
.DEFAULT_GOAL := build
|
||||
|
||||
.PHONY: fmt vet build windows linux macos test clean
|
||||
fmt:
|
||||
$(GO) fmt ./...
|
||||
|
||||
vet: fmt
|
||||
$(GO) vet ./...
|
||||
|
||||
build: vet windows linux macos | $(BIN_DIR)
|
||||
@echo version: $(VERSION)
|
||||
|
||||
windows: $(WINDOWS)
|
||||
|
||||
linux: $(LINUX)
|
||||
|
||||
macos: $(MACOS)
|
||||
|
||||
|
||||
$(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)/
|
||||
|
||||
$(MACOS):
|
||||
env GOOS=darwin GOARCH=amd64 go build -v -o $(MACOS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
|
||||
|
||||
test:
|
||||
$(GO) test ./...
|
||||
|
||||
$(BIN_DIR):
|
||||
@mkdir -p $@
|
||||
|
||||
clean:
|
||||
@rm -rv $(BIN_DIR)
|
||||
63
README.md
63
README.md
@ -6,25 +6,65 @@ A modification of [lilproxy][lilproxy_url] that forwards only Q3 rcon/query pack
|
||||
|
||||
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
|
||||
|
||||
Run one or multiple rcon proxies by setting an environment variable `Q3RCON_PROXY`
|
||||
|
||||
for example:
|
||||
#### Flags
|
||||
|
||||
```bash
|
||||
export Q3RCON_PROXY="20000:28960;20001:28961;20002:28962"
|
||||
#!/usr/bin/env bash
|
||||
|
||||
/usr/local/bin/q3rcon-proxy \
|
||||
--proxy-host=0.0.0.0 \
|
||||
--target-host=localhost \
|
||||
--port-map=20000:28960 --port-map=20001:28961 --port-map=20002:28962 \
|
||||
--session-timeout=20 \
|
||||
--loglevel=debug
|
||||
```
|
||||
|
||||
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.
|
||||
#### Environment Variables
|
||||
|
||||
Then just run the binary which you can compile yourself, download from `Releases` or use the included Dockerfile.
|
||||
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_PORT_MAP`: 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]).
|
||||
|
||||
example .envrc:
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
|
||||
export Q3RCON_PROXY_HOST="0.0.0.0"
|
||||
export Q3RCON_TARGET_HOST="localhost"
|
||||
export Q3RCON_PORT_MAP="20000:28960,20001:28961,20002:28962"
|
||||
export Q3RCON_SESSION_TIMEOUT=20
|
||||
```
|
||||
|
||||
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`:
|
||||
Set the log level with environment variable `Q3RCON_LOGLEVEL`.
|
||||
|
||||
`0 = Panic, 1 = Fatal, 2 = Error, 3 = Warning, 4 = Info, 5 = Debug, 6 = Trace`
|
||||
Acceptable values are:
|
||||
|
||||
- `trace`
|
||||
- `debug`
|
||||
- `info`
|
||||
- `warn`
|
||||
- `error`
|
||||
- `fatal`
|
||||
- `panic`
|
||||
|
||||
It defaults to `info`.
|
||||
|
||||
---
|
||||
|
||||
### Special Thanks
|
||||
|
||||
@ -32,3 +72,10 @@ Set the log level with environment variable `Q3RCON_LOGLEVEL`:
|
||||
|
||||
[lilproxy_url]: https://github.com/dgparker/lilproxy
|
||||
[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
|
||||
79
Taskfile.yml
Normal file
79
Taskfile.yml
Normal file
@ -0,0 +1,79 @@
|
||||
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'
|
||||
MACOS: '{{.BIN_DIR}}/{{.PROGRAM}}_darwin_amd64'
|
||||
VERSION:
|
||||
sh: 'git describe --tags $(git rev-list --tags --max-count=1)'
|
||||
|
||||
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
|
||||
- task: build-macos
|
||||
|
||||
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={{.VERSION}}" ./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={{.VERSION}}" ./cmd/{{.PROGRAM}}/
|
||||
internal: true
|
||||
|
||||
build-macos:
|
||||
desc: Build the q3rcon-proxy project for macOS
|
||||
cmds:
|
||||
- GOOS=darwin GOARCH=amd64 go build -o {{.MACOS}} -ldflags="-X main.version={{.VERSION}}" ./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 \
|
||||
--port-map=28961:28960 \
|
||||
--session-timeout=20 \
|
||||
--loglevel=debug
|
||||
@ -1,54 +1,176 @@
|
||||
// Package main implements a command-line application for a Quake 3 RCON proxy server.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"slices"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/charmbracelet/log"
|
||||
"github.com/urfave/cli/v3"
|
||||
|
||||
"github.com/onyx-and-iris/q3rcon-proxy/pkg/udpproxy"
|
||||
udpproxy "github.com/onyx-and-iris/q3rcon-proxy"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logLevel, err := getEnvInt("Q3RCON_LOGLEVEL")
|
||||
if err != nil {
|
||||
log.Fatalf("unable to parse Q3RCON_LEVEL: %s", err.Error())
|
||||
}
|
||||
if slices.Contains(log.AllLevels, log.Level(logLevel)) {
|
||||
log.SetLevel(log.Level(logLevel))
|
||||
var version string // Version holds the application version, set at build time using ldflags.
|
||||
|
||||
// versionFromBuild retrieves the version information from the build metadata.
|
||||
func versionFromBuild() string {
|
||||
if version != "" {
|
||||
return version
|
||||
}
|
||||
|
||||
proxies := os.Getenv("Q3RCON_PROXY")
|
||||
if proxies == "" {
|
||||
log.Fatal("env Q3RCON_PROXY required")
|
||||
info, ok := debug.ReadBuildInfo()
|
||||
if !ok {
|
||||
return "(unable to read version)"
|
||||
}
|
||||
|
||||
host := os.Getenv("Q3RCON_HOST")
|
||||
if host == "" {
|
||||
host = "0.0.0.0"
|
||||
}
|
||||
|
||||
for _, proxy := range strings.Split(proxies, ";") {
|
||||
go start(host, proxy)
|
||||
}
|
||||
|
||||
<-make(chan int)
|
||||
return strings.Split(info.Main.Version, "-")[0]
|
||||
}
|
||||
|
||||
func start(host, proxy string) {
|
||||
port, target := func() (string, string) {
|
||||
x := strings.Split(proxy, ":")
|
||||
return x[0], x[1]
|
||||
}()
|
||||
// proxyConfig holds the configuration for a single UDP proxy server.
|
||||
type proxyConfig struct {
|
||||
proxyHost string
|
||||
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 {
|
||||
func main() {
|
||||
cli.VersionPrinter = func(cmd *cli.Command) {
|
||||
fmt.Printf("q3rcon-proxy version: %s\n", cmd.Root().Version)
|
||||
}
|
||||
|
||||
cmd := &cli.Command{
|
||||
Name: "q3rcon-proxy",
|
||||
Usage: "A Quake 3 RCON proxy server",
|
||||
Version: versionFromBuild(),
|
||||
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.StringSliceFlag{
|
||||
Name: "port-map",
|
||||
Usage: "Ports mapping in the format proxyPort:targetPort (e.g., 27950:27960)",
|
||||
Sources: cli.EnvVars("Q3RCON_PORT_MAP"),
|
||||
Required: true,
|
||||
Action: func(_ context.Context, cmd *cli.Command, v []string) error {
|
||||
// Validate the ports mapping format and values
|
||||
for _, mapping := range v {
|
||||
src, dst := func(m string) (string, string) {
|
||||
parts := strings.Split(m, ":")
|
||||
if len(parts) != 2 {
|
||||
return "", ""
|
||||
}
|
||||
return parts[0], parts[1]
|
||||
}(mapping)
|
||||
|
||||
if src == "" || dst == "" {
|
||||
return fmt.Errorf(
|
||||
"invalid ports mapping: %s (expected format: proxyPort:targetPort)",
|
||||
mapping,
|
||||
)
|
||||
}
|
||||
n, err := strconv.Atoi(src)
|
||||
if err != nil || n <= 0 || n > 65535 {
|
||||
return fmt.Errorf("invalid proxy port: %s", src)
|
||||
}
|
||||
n, err = strconv.Atoi(dst)
|
||||
if err != nil || n <= 0 || n > 65535 {
|
||||
return fmt.Errorf("invalid target port: %s", dst)
|
||||
}
|
||||
if src == dst {
|
||||
return fmt.Errorf(
|
||||
"proxy port and target port cannot be the same: %s",
|
||||
src,
|
||||
)
|
||||
}
|
||||
log.Debugf(
|
||||
"Validated ports mapping: proxy port %s -> target port %s",
|
||||
src,
|
||||
dst,
|
||||
)
|
||||
}
|
||||
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 cmd.StringSlice("port-map") {
|
||||
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
|
||||
},
|
||||
}
|
||||
|
||||
if err := cmd.Run(context.Background(), os.Args); 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())
|
||||
}
|
||||
|
||||
// launchProxy initialises 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]
|
||||
|
||||
proxyAddr := net.JoinHostPort(cfg.proxyHost, proxyPort)
|
||||
targetAddr := net.JoinHostPort(cfg.targetHost, targetPort)
|
||||
|
||||
server, err := udpproxy.New(
|
||||
proxyAddr, targetAddr,
|
||||
udpproxy.WithSessionTimeout(time.Duration(cfg.sessionTimeout)*time.Minute))
|
||||
if err != nil {
|
||||
errChan <- fmt.Errorf("failed to create proxy: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Infof("q3rcon-proxy initialised: [proxy] (%s) [target] (%s)", proxyAddr, targetAddr)
|
||||
|
||||
errChan <- server.ListenAndServe()
|
||||
}
|
||||
|
||||
@ -1,18 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
4
debian/q3rcon-proxy.service
vendored
4
debian/q3rcon-proxy.service
vendored
@ -6,9 +6,9 @@ After=network.target
|
||||
[Service]
|
||||
Type=simple
|
||||
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_DEBUG=0"
|
||||
Environment="Q3RCON_LOGLEVEL=info"
|
||||
|
||||
ExecStart=/usr/local/bin/q3rcon-proxy
|
||||
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
|
||||
27
go.mod
27
go.mod
@ -1,7 +1,28 @@
|
||||
module github.com/onyx-and-iris/q3rcon-proxy
|
||||
|
||||
go 1.18
|
||||
go 1.25.0
|
||||
|
||||
require github.com/sirupsen/logrus v1.9.3
|
||||
require (
|
||||
github.com/charmbracelet/log v0.4.2
|
||||
github.com/urfave/cli/v3 v3.7.0
|
||||
)
|
||||
|
||||
require golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
|
||||
require (
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.4.2 // indirect
|
||||
github.com/charmbracelet/lipgloss v1.1.0 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.11.6 // indirect
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
|
||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||
github.com/clipperhouse/displaywidth v0.11.0 // indirect
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
|
||||
github.com/go-logfmt/logfmt v0.6.1 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.20 // indirect
|
||||
github.com/muesli/termenv v0.16.0 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
)
|
||||
|
||||
56
go.sum
56
go.sum
@ -1,15 +1,49 @@
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
|
||||
github.com/charmbracelet/colorprofile v0.4.2 h1:BdSNuMjRbotnxHSfxy+PCSa4xAmz7szw70ktAtWRYrY=
|
||||
github.com/charmbracelet/colorprofile v0.4.2/go.mod h1:0rTi81QpwDElInthtrQ6Ni7cG0sDtwAd4C4le060fT8=
|
||||
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
|
||||
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
|
||||
github.com/charmbracelet/log v0.4.2 h1:hYt8Qj6a8yLnvR+h7MwsJv/XvmBJXiueUcI3cIxsyig=
|
||||
github.com/charmbracelet/log v0.4.2/go.mod h1:qifHGX/tc7eluv2R6pWIpyHDDrrb/AG71Pf2ysQu5nw=
|
||||
github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=
|
||||
github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q=
|
||||
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
|
||||
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
|
||||
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
|
||||
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-logfmt/logfmt v0.6.1 h1:4hvbpePJKnIzH1B+8OR/JPbTx37NktoI9LE2QZBBkvE=
|
||||
github.com/go-logfmt/logfmt v0.6.1/go.mod h1:EV2pOAQoZaT1ZXZbqDl5hrymndi4SY9ED9/z6CO0XAk=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.20 h1:WcT52H91ZUAwy8+HUkdM3THM6gXqXuLJi9O3rjcQQaQ=
|
||||
github.com/mattn/go-runewidth v0.0.20/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
|
||||
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
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/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
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=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
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=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
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.7.0 h1:AGSnbUyjtLiM+WJUb4dzXKldl/gL+F8OwmRDtVr6g2U=
|
||||
github.com/urfave/cli/v3 v3.7.0/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
24
option.go
Normal file
24
option.go
Normal file
@ -0,0 +1,24 @@
|
||||
package udpproxy
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/log"
|
||||
)
|
||||
|
||||
// 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,85 +0,0 @@
|
||||
package udpproxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
laddr *net.UDPAddr
|
||||
raddr *net.UDPAddr
|
||||
|
||||
proxyConn *net.UDPConn
|
||||
|
||||
mutex sync.RWMutex
|
||||
sessions map[string]*session
|
||||
}
|
||||
|
||||
func New(port, target string) (*Client, error) {
|
||||
laddr, err := net.ResolveUDPAddr("udp", port)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
raddr, err := net.ResolveUDPAddr("udp", target)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Client{
|
||||
laddr: laddr,
|
||||
raddr: raddr,
|
||||
mutex: sync.RWMutex{},
|
||||
sessions: map[string]*session{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListenAndServe() error {
|
||||
var err error
|
||||
c.proxyConn, err = net.ListenUDP("udp", c.laddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
go c.pruneSessions()
|
||||
|
||||
buf := make([]byte, 2048)
|
||||
for {
|
||||
n, caddr, err := c.proxyConn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
}
|
||||
|
||||
session, ok := c.sessions[caddr.String()]
|
||||
if !ok {
|
||||
session, err = newSession(caddr, c.raddr, c.proxyConn)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
continue
|
||||
}
|
||||
|
||||
c.sessions[caddr.String()] = session
|
||||
}
|
||||
|
||||
go session.proxyTo(buf[:n])
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) pruneSessions() {
|
||||
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 _, session := range c.sessions {
|
||||
c.mutex.RLock()
|
||||
if time.Since(session.updateTime) > time.Minute*5 {
|
||||
delete(c.sessions, session.caddr.String())
|
||||
}
|
||||
c.mutex.RUnlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -7,7 +7,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/charmbracelet/log"
|
||||
)
|
||||
|
||||
type session struct {
|
||||
@ -19,7 +19,7 @@ type session struct {
|
||||
validator
|
||||
}
|
||||
|
||||
func newSession(caddr *net.UDPAddr, raddr *net.UDPAddr, proxyConn *net.UDPConn) (*session, error) {
|
||||
func newSession(caddr, raddr *net.UDPAddr, proxyConn *net.UDPConn) (*session, error) {
|
||||
serverConn, err := net.DialUDP("udp", nil, raddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -81,7 +81,11 @@ func (s *session) proxyTo(buf []byte) error {
|
||||
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])
|
||||
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")
|
||||
}
|
||||
@ -98,7 +102,12 @@ func (s *session) proxyTo(buf []byte) error {
|
||||
|
||||
if s.isRconRequestPacket(buf) {
|
||||
parts := strings.SplitN(string(buf), " ", 3)
|
||||
log.Infof("From [%s] To [%s] Command: %s", s.caddr.IP, s.serverConn.RemoteAddr(), parts[len(parts)-1])
|
||||
log.Infof(
|
||||
"From [%s] To [%s] Command: %s",
|
||||
s.caddr.IP,
|
||||
s.serverConn.RemoteAddr(),
|
||||
parts[len(parts)-1],
|
||||
)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
94
udpproxy.go
Normal file
94
udpproxy.go
Normal file
@ -0,0 +1,94 @@
|
||||
// Package udpproxy implements a simple UDP proxy server that forwards rcon and query packets between clients and a target server.
|
||||
package udpproxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/log"
|
||||
)
|
||||
|
||||
// Client represents a UDP proxy server that forwards rcon and query packets between clients and a target server.
|
||||
// It maintains a session cache to manage client sessions and handles packet forwarding between clients and the target server.
|
||||
type Client struct {
|
||||
laddr *net.UDPAddr
|
||||
raddr *net.UDPAddr
|
||||
|
||||
proxyConn *net.UDPConn
|
||||
|
||||
sessionCache sessionCache
|
||||
sessionTimeout time.Duration
|
||||
}
|
||||
|
||||
// New creates a new Client with the specified proxy and target addresses, and applies any provided options.
|
||||
func New(proxy, target string, options ...Option) (*Client, error) {
|
||||
laddr, err := net.ResolveUDPAddr("udp", proxy)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid proxy address: %w", err)
|
||||
}
|
||||
|
||||
raddr, err := net.ResolveUDPAddr("udp", target)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid target address: %w", err)
|
||||
}
|
||||
|
||||
c := &Client{
|
||||
laddr: laddr,
|
||||
raddr: raddr,
|
||||
sessionCache: newSessionCache(),
|
||||
sessionTimeout: 20 * time.Minute,
|
||||
}
|
||||
|
||||
for _, o := range options {
|
||||
o(c)
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// ListenAndServe starts the UDP proxy server and listens for incoming packets from clients.
|
||||
// It reads packets from the proxy connection, checks for existing sessions, and forwards packets to the target server.
|
||||
func (c *Client) ListenAndServe() error {
|
||||
var err error
|
||||
c.proxyConn, err = net.ListenUDP("udp", c.laddr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to listen on proxy address: %w", err)
|
||||
}
|
||||
|
||||
go c.pruneSessions()
|
||||
|
||||
buf := make([]byte, 2048)
|
||||
for {
|
||||
n, caddr, err := c.proxyConn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
}
|
||||
|
||||
session, ok := c.sessionCache.read(caddr.String())
|
||||
if !ok {
|
||||
session, err = newSession(caddr, c.raddr, c.proxyConn)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
continue
|
||||
}
|
||||
|
||||
c.sessionCache.insert(caddr.String(), session)
|
||||
}
|
||||
|
||||
go session.proxyTo(buf[:n])
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) pruneSessions() {
|
||||
ticker := time.NewTicker(1 * time.Minute)
|
||||
|
||||
for range ticker.C {
|
||||
for _, session := range c.sessionCache.data {
|
||||
if time.Since(session.updateTime) > c.sessionTimeout {
|
||||
c.sessionCache.delete(session.caddr.String())
|
||||
log.Debugf("session for %s deleted", session.caddr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user