Security performance improvements #1
No files matched your search
@@ -9,18 +9,18 @@ jobs:
|
|||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container:
|
container:
|
||||||
image: catthehacker/ubuntu:act-latest
|
image: registry.rznet.fr/tchivert/ubuntu:act-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0 # all history for all branches and tags
|
fetch-depth: 0 # all history for all branches and tags
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v2
|
uses: docker/setup-buildx-action@v4
|
||||||
|
|
||||||
- name: Login to registry
|
- name: Login to registry
|
||||||
uses: docker/login-action@v2
|
uses: docker/login-action@v4
|
||||||
with:
|
with:
|
||||||
registry: git.rznet.fr
|
registry: git.rznet.fr
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
name: test
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- "main"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
|
||||||
|
- name: go mod download
|
||||||
|
run: go mod download
|
||||||
|
|
||||||
|
- name: go build
|
||||||
|
run: go build -v ./...
|
||||||
|
|
||||||
|
- name: go vet
|
||||||
|
run: go vet ./...
|
||||||
|
|
||||||
|
- name: gofmt check
|
||||||
|
run: test -z "$(gofmt -l .)" || (echo "gofmt issues found:" && gofmt -l . && exit 1)
|
||||||
|
|
||||||
|
- name: go test
|
||||||
|
run: go test -v ./...
|
||||||
+13
-5
@@ -1,20 +1,28 @@
|
|||||||
FROM golang AS build
|
FROM golang:1.27-alpine AS build
|
||||||
|
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
|
|
||||||
COPY go.mod ./
|
COPY go.mod go.sum* ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
|
|
||||||
COPY *.go ./
|
COPY *.go ./
|
||||||
RUN CGO_ENABLED=0 GOOS=linux go build -o tbin .
|
RUN CGO_ENABLED=0 GOOS=linux go build -o tbin .
|
||||||
|
|
||||||
FROM alpine
|
FROM alpine:3.24
|
||||||
|
|
||||||
|
RUN addgroup -S tbin && adduser -S -u 1000 -G tbin tbin
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY --from=build /build/tbin ./
|
COPY --from=build /build/tbin ./
|
||||||
COPY index.html ./
|
COPY --chown=tbin:tbin index.html ./
|
||||||
COPY favicon.png ./
|
COPY --chown=tbin:tbin favicon.png ./
|
||||||
|
|
||||||
|
RUN mkdir -p /app/data && chown tbin:tbin /app/data
|
||||||
|
|
||||||
|
USER tbin
|
||||||
|
|
||||||
|
VOLUME /app/data
|
||||||
|
|
||||||
EXPOSE 4242
|
EXPOSE 4242
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ tbin is a simple pastebin application that allows you to store and share text sn
|
|||||||
Before building and starting tbin, ensure that you have the following software installed on your system:
|
Before building and starting tbin, ensure that you have the following software installed on your system:
|
||||||
|
|
||||||
- Docker
|
- Docker
|
||||||
- Go (if you want to build the application from source)
|
- Go 1.27+ (if you want to build the application from source)
|
||||||
|
|
||||||
## Building from source
|
## Building from source
|
||||||
|
|
||||||
@@ -28,6 +28,8 @@ tbin can also be started using Docker. To do this, follow these steps:
|
|||||||
4. Start the application using Docker Compose: `docker-compose up -d`
|
4. Start the application using Docker Compose: `docker-compose up -d`
|
||||||
5. tbin will be started as a Docker container and will be accessible via telnet and HTTP.
|
5. tbin will be started as a Docker container and will be accessible via telnet and HTTP.
|
||||||
|
|
||||||
|
The Docker container runs as a non-root user (UID 1000) and uses a named volume (`tbin-data`) for data persistence.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
To submit a text snippet using the telnet interface, follow these steps:
|
To submit a text snippet using the telnet interface, follow these steps:
|
||||||
@@ -36,7 +38,7 @@ To submit a text snippet using the telnet interface, follow these steps:
|
|||||||
2. Use the `nc` command to connect to the tbin server: `echo "Your text snippet" | nc localhost 4242`
|
2. Use the `nc` command to connect to the tbin server: `echo "Your text snippet" | nc localhost 4242`
|
||||||
3. The server will generate a unique URL for your text snippet, which will be displayed in the terminal.
|
3. The server will generate a unique URL for your text snippet, which will be displayed in the terminal.
|
||||||
|
|
||||||
Purges can be trigged with the `/purge` endpoint.
|
Purges can be trigged with the `/purge` endpoint (localhost only).
|
||||||
It will remove all snippets olders than the configuered TTL (default: 48 hours).
|
It will remove all snippets olders than the configuered TTL (default: 48 hours).
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
@@ -53,8 +55,39 @@ tbin can be configured using command-line flags when starting the application.
|
|||||||
- `--chunk`: Chunk size in bytes for reading data (default: 8192).
|
- `--chunk`: Chunk size in bytes for reading data (default: 8192).
|
||||||
- `--conn-time`: Connection timeout in seconds (default: 10).
|
- `--conn-time`: Connection timeout in seconds (default: 10).
|
||||||
- `--read-time`: Read timeout in seconds (default: 2).
|
- `--read-time`: Read timeout in seconds (default: 2).
|
||||||
- `--verbose`: Enable verbose logging (default: false).
|
- `--verbose`: Enable verbose (debug-level) logging (default: false).
|
||||||
- `--plaintext`: Only allow plaintext snippets (default: false).
|
- `--plaintext`: Only allow plaintext snippets (default: false).
|
||||||
|
- `--max-conns`: Maximum concurrent TCP connections (default: 100).
|
||||||
|
- `--rate-limit`: Max requests per second per IP, 0 to disable (default: 10).
|
||||||
|
- `--metrics-addr`: Prometheus metrics listen address, empty to disable (default: "").
|
||||||
|
|
||||||
|
## Monitoring
|
||||||
|
|
||||||
|
tbin exposes Prometheus metrics when `--metrics-addr` is set. The metrics server runs on a separate port and is not exposed on the main HTTP port. Available metrics:
|
||||||
|
|
||||||
|
- `tbin_pastes_total`: Total pastes created
|
||||||
|
- `tbin_pastes_bytes_total`: Total bytes of pastes created
|
||||||
|
- `tbin_http_requests_total`: HTTP requests by method, endpoint, and status
|
||||||
|
- `tbin_tcp_connections_total`: Total TCP connections accepted
|
||||||
|
- `tbin_tcp_active_connections`: Current active TCP connections
|
||||||
|
- `tbin_purge_runs_total`: Total purge operations executed
|
||||||
|
- `tbin_purge_files_total`: Files processed during purge by result
|
||||||
|
- `tbin_removes_total`: Total manual remove requests
|
||||||
|
|
||||||
|
A `/health` endpoint is also available on the HTTP port for health checks.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
- HTTP server has read/write/idle timeouts to prevent slowloris attacks
|
||||||
|
- Request body size is limited via `http.MaxBytesReader`
|
||||||
|
- TCP connections are rate-limited per-IP and capped with `--max-conns`
|
||||||
|
- HTTP requests are rate-limited per-IP
|
||||||
|
- Paste files are created with 0600 permissions and O_EXCL to prevent races
|
||||||
|
- The `/purge` endpoint is restricted to localhost
|
||||||
|
- Security headers (CSP, X-Frame-Options, etc.) are set on all responses
|
||||||
|
- Graceful shutdown on SIGTERM/SIGINT with WaitGroup tracking of in-flight requests
|
||||||
|
- Docker container runs as non-root user (UID 1000)
|
||||||
|
- Docker base images are pinned (golang:1.27-alpine, alpine:3.24)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
+4
-1
@@ -7,6 +7,9 @@ services:
|
|||||||
image: git.rznet.fr/tchivert/tbin
|
image: git.rznet.fr/tchivert/tbin
|
||||||
restart: always
|
restart: always
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/app/data
|
- tbin-data:/app/data
|
||||||
command:
|
command:
|
||||||
- --http-url=http://localhost:8080/
|
- --http-url=http://localhost:8080/
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
tbin-data:
|
||||||
@@ -1,3 +1,18 @@
|
|||||||
module tbin
|
module tbin
|
||||||
|
|
||||||
go 1.19
|
go 1.27
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/prometheus/client_golang v1.19.0
|
||||||
|
golang.org/x/time v0.5.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/beorn7/perks v1.0.1 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||||
|
github.com/prometheus/client_model v0.5.0 // indirect
|
||||||
|
github.com/prometheus/common v0.48.0 // indirect
|
||||||
|
github.com/prometheus/procfs v0.12.0 // indirect
|
||||||
|
golang.org/x/sys v0.16.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.32.0 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||||
|
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||||
|
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
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/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
|
github.com/prometheus/client_golang v1.19.0 h1:ygXvpU1AoN1MhdzckN+PyD9QJOSD4x7kmXYlnfbA6JU=
|
||||||
|
github.com/prometheus/client_golang v1.19.0/go.mod h1:ZRM9uEAypZakd+q/x7+gmsvXdURP+DABIEIjnmDdp+k=
|
||||||
|
github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw=
|
||||||
|
github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI=
|
||||||
|
github.com/prometheus/common v0.48.0 h1:QO8U2CdOzSn1BBsmXJXduaaW+dY/5QLjfB8svtSzKKE=
|
||||||
|
github.com/prometheus/common v0.48.0/go.mod h1:0/KsvlIEfPQCQ5I2iNSAWKPZziNCvRs5EC6ILDTlAPc=
|
||||||
|
github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo=
|
||||||
|
github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo=
|
||||||
|
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
|
||||||
|
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
|
||||||
|
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||||
|
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
|
||||||
|
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||||
+27
-2
@@ -57,7 +57,7 @@
|
|||||||
.paste-panel textarea {
|
.paste-panel textarea {
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
min-height: 560px;
|
min-height: 40vh;
|
||||||
resize: vertical;
|
resize: vertical;
|
||||||
background-color: #424242;
|
background-color: #424242;
|
||||||
color: #fff;
|
color: #fff;
|
||||||
@@ -191,6 +191,31 @@
|
|||||||
.privacy-panel .input {
|
.privacy-panel .input {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
.paste-panel textarea {
|
||||||
|
min-height: 30vh;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
body {
|
||||||
|
margin: 15px;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
font-size: 28px;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
font-size: 22px;
|
||||||
|
}
|
||||||
|
.paste-panel textarea {
|
||||||
|
min-height: 25vh;
|
||||||
|
}
|
||||||
|
.paste-panel .button {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
.privacy-panel .button {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
@@ -198,7 +223,7 @@
|
|||||||
<body>
|
<body>
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<div class="text-panel">
|
<div class="text-panel">
|
||||||
<h1><a href="http://tbin.fr/">Telnet Pastebin</a></h1>
|
<h1><a href="https://tbin.fr/">Telnet Pastebin</a></h1>
|
||||||
<p class="source"><a href="https://git.rznet.fr/tchivert/tbin">source</a></p>
|
<p class="source"><a href="https://git.rznet.fr/tchivert/tbin">source</a></p>
|
||||||
<h2>A simple pastebin you can use from your terminal</h2>
|
<h2>A simple pastebin you can use from your terminal</h2>
|
||||||
<h3>Usage</h3>
|
<h3>Usage</h3>
|
||||||
|
|||||||
@@ -1,20 +1,29 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"errors"
|
"errors"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"os/signal"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||||
|
"golang.org/x/time/rate"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -30,82 +39,266 @@ var (
|
|||||||
ttl = flag.Int("ttl", 48, "Time-to-live in hours for the snippets")
|
ttl = flag.Int("ttl", 48, "Time-to-live in hours for the snippets")
|
||||||
verbose = flag.Bool("verbose", false, "Verbose output")
|
verbose = flag.Bool("verbose", false, "Verbose output")
|
||||||
plaintext = flag.Bool("plaintext", false, "Only allow plaintext snippets")
|
plaintext = flag.Bool("plaintext", false, "Only allow plaintext snippets")
|
||||||
|
maxConns = flag.Int("max-conns", 100, "Maximum concurrent TCP connections")
|
||||||
|
rateLimit = flag.Int("rate-limit", 10, "Max requests per second per IP (0 to disable)")
|
||||||
|
metricsAddr = flag.String("metrics-addr", "", "Prometheus metrics listen address (empty to disable)")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
logger *slog.Logger
|
||||||
|
connSem chan struct{}
|
||||||
|
activeConns atomic.Int64
|
||||||
|
wg sync.WaitGroup
|
||||||
|
purgeMu sync.Mutex
|
||||||
|
|
||||||
|
metricPastesTotal prometheus.Counter
|
||||||
|
metricPastesBytes prometheus.Counter
|
||||||
|
metricHTTPRequests *prometheus.CounterVec
|
||||||
|
metricTCPConnections prometheus.Counter
|
||||||
|
metricActiveConns prometheus.Gauge
|
||||||
|
metricPurgeRuns prometheus.Counter
|
||||||
|
metricPurgeFilesTotal *prometheus.CounterVec
|
||||||
|
metricRemovesTotal prometheus.Counter
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxIPLimiterEntries = 10000
|
||||||
|
|
||||||
|
type ipLimiter struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
limiters map[string]*rate.Limiter
|
||||||
|
limit rate.Limit
|
||||||
|
burst int
|
||||||
|
}
|
||||||
|
|
||||||
|
func newIPLimiter(limit rate.Limit, burst int) *ipLimiter {
|
||||||
|
il := &ipLimiter{
|
||||||
|
limiters: make(map[string]*rate.Limiter),
|
||||||
|
limit: limit,
|
||||||
|
burst: burst,
|
||||||
|
}
|
||||||
|
go il.cleanup()
|
||||||
|
return il
|
||||||
|
}
|
||||||
|
|
||||||
|
func (il *ipLimiter) get(ip string) *rate.Limiter {
|
||||||
|
il.mu.Lock()
|
||||||
|
defer il.mu.Unlock()
|
||||||
|
l, ok := il.limiters[ip]
|
||||||
|
if !ok {
|
||||||
|
if len(il.limiters) >= maxIPLimiterEntries {
|
||||||
|
for k, v := range il.limiters {
|
||||||
|
if v.Tokens() == float64(il.burst) {
|
||||||
|
delete(il.limiters, k)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(il.limiters) >= maxIPLimiterEntries {
|
||||||
|
return rate.NewLimiter(rate.Limit(0), 0)
|
||||||
|
}
|
||||||
|
l = rate.NewLimiter(il.limit, il.burst)
|
||||||
|
il.limiters[ip] = l
|
||||||
|
}
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
func (il *ipLimiter) cleanup() {
|
||||||
|
ticker := time.NewTicker(10 * time.Minute)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for range ticker.C {
|
||||||
|
il.mu.Lock()
|
||||||
|
for ip, l := range il.limiters {
|
||||||
|
if l.Tokens() == float64(il.burst) {
|
||||||
|
delete(il.limiters, ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
il.mu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
httpIPLimiter *ipLimiter
|
||||||
|
tcpIPLimiter *ipLimiter
|
||||||
|
)
|
||||||
|
|
||||||
|
func initMetrics() {
|
||||||
|
metricPastesTotal = prometheus.NewCounter(prometheus.CounterOpts{
|
||||||
|
Name: "tbin_pastes_total",
|
||||||
|
Help: "Total number of pastes created",
|
||||||
|
})
|
||||||
|
metricPastesBytes = prometheus.NewCounter(prometheus.CounterOpts{
|
||||||
|
Name: "tbin_pastes_bytes_total",
|
||||||
|
Help: "Total bytes of pastes created",
|
||||||
|
})
|
||||||
|
metricHTTPRequests = prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||||
|
Name: "tbin_http_requests_total",
|
||||||
|
Help: "Total HTTP requests by method, endpoint, and status",
|
||||||
|
}, []string{"method", "endpoint", "status"})
|
||||||
|
metricTCPConnections = prometheus.NewCounter(prometheus.CounterOpts{
|
||||||
|
Name: "tbin_tcp_connections_total",
|
||||||
|
Help: "Total TCP connections accepted",
|
||||||
|
})
|
||||||
|
metricActiveConns = prometheus.NewGauge(prometheus.GaugeOpts{
|
||||||
|
Name: "tbin_tcp_active_connections",
|
||||||
|
Help: "Current active TCP connections",
|
||||||
|
})
|
||||||
|
metricPurgeRuns = prometheus.NewCounter(prometheus.CounterOpts{
|
||||||
|
Name: "tbin_purge_runs_total",
|
||||||
|
Help: "Total purge operations executed",
|
||||||
|
})
|
||||||
|
metricPurgeFilesTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||||
|
Name: "tbin_purge_files_total",
|
||||||
|
Help: "Files processed during purge by result",
|
||||||
|
}, []string{"result"})
|
||||||
|
metricRemovesTotal = prometheus.NewCounter(prometheus.CounterOpts{
|
||||||
|
Name: "tbin_removes_total",
|
||||||
|
Help: "Total manual remove requests",
|
||||||
|
})
|
||||||
|
|
||||||
|
prometheus.MustRegister(
|
||||||
|
metricPastesTotal,
|
||||||
|
metricPastesBytes,
|
||||||
|
metricHTTPRequests,
|
||||||
|
metricTCPConnections,
|
||||||
|
metricActiveConns,
|
||||||
|
metricPurgeRuns,
|
||||||
|
metricPurgeFilesTotal,
|
||||||
|
metricRemovesTotal,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
// Validate and normalize configuration
|
logLevel := slog.LevelInfo
|
||||||
|
if *verbose {
|
||||||
|
logLevel = slog.LevelDebug
|
||||||
|
}
|
||||||
|
logger = slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: logLevel}))
|
||||||
|
slog.SetDefault(logger)
|
||||||
|
|
||||||
|
initMetrics()
|
||||||
|
|
||||||
*buff *= 1024 * 1024
|
*buff *= 1024 * 1024
|
||||||
if *buff <= 0 {
|
if *buff <= 0 {
|
||||||
log.Fatal("Buffer size must be positive")
|
logger.Error("buffer size must be positive")
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if *chunkSize <= 0 {
|
if *chunkSize <= 0 {
|
||||||
log.Fatal("Chunk size must be positive")
|
logger.Error("chunk size must be positive")
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if *connTimeout <= 0 {
|
if *connTimeout <= 0 {
|
||||||
log.Fatal("Connection timeout must be positive")
|
logger.Error("connection timeout must be positive")
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if *readTimeout <= 0 {
|
if *readTimeout <= 0 {
|
||||||
log.Fatal("Read timeout must be positive")
|
logger.Error("read timeout must be positive")
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if *ttl <= 0 {
|
if *ttl <= 0 {
|
||||||
log.Fatal("TTL must be positive")
|
logger.Error("TTL must be positive")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if *maxConns <= 0 {
|
||||||
|
logger.Error("max connections must be positive")
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if !strings.HasSuffix(*httpURL, "/") {
|
if !strings.HasSuffix(*httpURL, "/") {
|
||||||
*httpURL += "/"
|
*httpURL += "/"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate and create data directory
|
|
||||||
if *dir == "" {
|
if *dir == "" {
|
||||||
log.Fatal("Data directory cannot be empty")
|
logger.Error("data directory cannot be empty")
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use absolute path for data directory to prevent path traversal
|
|
||||||
absDir, err := filepath.Abs(*dir)
|
absDir, err := filepath.Abs(*dir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error getting absolute path for data directory: %v", err)
|
logger.Error("error getting absolute path for data directory", "error", err)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
*dir = absDir
|
*dir = absDir
|
||||||
|
|
||||||
if err := os.MkdirAll(*dir, 0700); err != nil {
|
if err := os.MkdirAll(*dir, 0700); err != nil {
|
||||||
log.Fatalf("Error creating data directory %s: %v", *dir, err)
|
logger.Error("error creating data directory", "dir", *dir, "error", err)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("Starting tbin with data directory: %s", *dir)
|
connSem = make(chan struct{}, *maxConns)
|
||||||
log.Printf("Buffer size: %d MB", *buff/1024/1024)
|
|
||||||
log.Printf("TTL: %d hours", *ttl)
|
|
||||||
|
|
||||||
go listenTCP()
|
if *rateLimit > 0 {
|
||||||
listenHTTP()
|
httpIPLimiter = newIPLimiter(rate.Limit(*rateLimit), *rateLimit*2)
|
||||||
|
tcpIPLimiter = newIPLimiter(rate.Limit(*rateLimit), *rateLimit*2)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("starting tbin",
|
||||||
|
"data_dir", *dir,
|
||||||
|
"buffer_mb", *buff/1024/1024,
|
||||||
|
"ttl_hours", *ttl,
|
||||||
|
"max_conns", *maxConns,
|
||||||
|
"rate_limit", *rateLimit,
|
||||||
|
)
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
go listenTCP(ctx)
|
||||||
|
|
||||||
|
if *metricsAddr != "" {
|
||||||
|
go listenMetrics(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
listenHTTP(ctx)
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
logger.Info("shutdown complete")
|
||||||
}
|
}
|
||||||
|
|
||||||
func listenTCP() {
|
func listenTCP(ctx context.Context) {
|
||||||
l, err := net.Listen("tcp", *connHost+":"+*connPort)
|
l, err := net.Listen("tcp", *connHost+":"+*connPort)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Error listening: %v", err)
|
logger.Error("error listening TCP", "error", err)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
defer l.Close()
|
defer l.Close()
|
||||||
log.Printf("Listening on %s:%s for TCP connections", *connHost, *connPort)
|
|
||||||
|
go func() {
|
||||||
|
<-ctx.Done()
|
||||||
|
l.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
logger.Info("listening for TCP connections", "addr", *connHost+":"+*connPort)
|
||||||
for {
|
for {
|
||||||
conn, err := l.Accept()
|
conn, err := l.Accept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Error accepting: %v", err)
|
select {
|
||||||
continue
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
logger.Error("error accepting TCP connection", "error", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
}
|
}
|
||||||
go handleTCP(conn)
|
metricTCPConnections.Inc()
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
handleTCP(conn)
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func listenHTTP() {
|
func listenHTTP(ctx context.Context) {
|
||||||
// Set up security headers middleware
|
mux := http.NewServeMux()
|
||||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
// Security headers
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
w.Header().Set("X-Frame-Options", "DENY")
|
w.Header().Set("X-Frame-Options", "DENY")
|
||||||
w.Header().Set("X-XSS-Protection", "1; mode=block")
|
w.Header().Set("X-XSS-Protection", "1; mode=block")
|
||||||
@@ -115,96 +308,250 @@ func listenHTTP() {
|
|||||||
handleHTTP(w, r)
|
handleHTTP(w, r)
|
||||||
})
|
})
|
||||||
|
|
||||||
log.Printf("Listening on %s:%s for HTTP connections", *connHost, *httpPort)
|
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||||||
err := http.ListenAndServe(*connHost+":"+*httpPort, nil)
|
w.Header().Set("Content-Type", "application/json")
|
||||||
if err != nil {
|
w.Write([]byte(`{"status":"ok"}`))
|
||||||
log.Fatalf("Error listening: %v", err)
|
})
|
||||||
|
|
||||||
|
server := &http.Server{
|
||||||
|
Addr: *connHost + ":" + *httpPort,
|
||||||
|
Handler: mux,
|
||||||
|
ReadTimeout: 10 * time.Second,
|
||||||
|
WriteTimeout: 30 * time.Second,
|
||||||
|
IdleTimeout: 60 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
<-ctx.Done()
|
||||||
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
server.Shutdown(shutdownCtx)
|
||||||
|
}()
|
||||||
|
|
||||||
|
logger.Info("listening for HTTP connections", "addr", *connHost+":"+*httpPort)
|
||||||
|
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
|
logger.Error("error listening HTTP", "error", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func listenMetrics(ctx context.Context) {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.Handle("/metrics", promhttp.Handler())
|
||||||
|
|
||||||
|
server := &http.Server{
|
||||||
|
Addr: *metricsAddr,
|
||||||
|
Handler: mux,
|
||||||
|
ReadTimeout: 5 * time.Second,
|
||||||
|
WriteTimeout: 10 * time.Second,
|
||||||
|
IdleTimeout: 30 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
<-ctx.Done()
|
||||||
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
server.Shutdown(shutdownCtx)
|
||||||
|
}()
|
||||||
|
|
||||||
|
logger.Info("listening for metrics", "addr", *metricsAddr)
|
||||||
|
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
|
logger.Error("error listening metrics", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getRemoteIP(addr string) string {
|
||||||
|
host, _, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil {
|
||||||
|
return addr
|
||||||
|
}
|
||||||
|
return host
|
||||||
|
}
|
||||||
|
|
||||||
|
func isLocalhost(addr string) bool {
|
||||||
|
host := getRemoteIP(addr)
|
||||||
|
return host == "127.0.0.1" || host == "::1" || host == "localhost"
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleHTTP(w http.ResponseWriter, r *http.Request) {
|
func handleHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
if *verbose {
|
if *verbose {
|
||||||
log.Printf("HTTP %s %s %s", r.RemoteAddr, r.Method, r.URL.Path)
|
logger.Debug("http request", "remote", r.RemoteAddr, "method", r.Method, "path", r.URL.Path)
|
||||||
|
}
|
||||||
|
|
||||||
|
if httpIPLimiter != nil {
|
||||||
|
ip := getRemoteIP(r.RemoteAddr)
|
||||||
|
if !httpIPLimiter.get(ip).Allow() {
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "rate_limited", "429").Inc()
|
||||||
|
http.Error(w, "Too many requests", http.StatusTooManyRequests)
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Security: Prevent path traversal attacks
|
|
||||||
id := strings.TrimPrefix(r.URL.Path, "/")
|
id := strings.TrimPrefix(r.URL.Path, "/")
|
||||||
if strings.Contains(id, "..") || strings.Contains(id, "/") {
|
if strings.Contains(id, "..") || strings.Contains(id, "/") {
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "invalid_path", "400").Inc()
|
||||||
http.Error(w, "Invalid path", http.StatusBadRequest)
|
http.Error(w, "Invalid path", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
switch r.Method {
|
switch r.Method {
|
||||||
case "POST":
|
case "POST":
|
||||||
|
r.Body = http.MaxBytesReader(w, r.Body, int64(*buff)+1024)
|
||||||
|
|
||||||
switch id {
|
switch id {
|
||||||
case "paste":
|
case "paste":
|
||||||
|
if err := r.ParseForm(); err != nil {
|
||||||
|
var maxErr *http.MaxBytesError
|
||||||
|
if errors.As(err, &maxErr) {
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "paste", "413").Inc()
|
||||||
|
http.Error(w, "Data too large", http.StatusRequestEntityTooLarge)
|
||||||
|
} else {
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "paste", "400").Inc()
|
||||||
|
http.Error(w, "Invalid form data", http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
data := r.FormValue("paste")
|
data := r.FormValue("paste")
|
||||||
if data == "" {
|
if data == "" {
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "paste", "400").Inc()
|
||||||
http.Error(w, "Empty data", http.StatusBadRequest)
|
http.Error(w, "Empty data", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if len(data) > *buff {
|
if len(data) > *buff {
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "paste", "413").Inc()
|
||||||
http.Error(w, "Data too large", http.StatusRequestEntityTooLarge)
|
http.Error(w, "Data too large", http.StatusRequestEntityTooLarge)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
id = handleData([]byte(data))
|
newID := handleData([]byte(data))
|
||||||
if id == "" {
|
if newID == "" {
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "paste", "500").Inc()
|
||||||
http.Error(w, "Error generating file", http.StatusInternalServerError)
|
http.Error(w, "Error generating file", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
http.Redirect(w, r, "/"+id, http.StatusSeeOther)
|
metricHTTPRequests.WithLabelValues(r.Method, "paste", "303").Inc()
|
||||||
|
http.Redirect(w, r, "/"+newID, http.StatusSeeOther)
|
||||||
case "remove":
|
case "remove":
|
||||||
id = r.FormValue("remove")
|
if err := r.ParseForm(); err != nil {
|
||||||
if id != "" {
|
var maxErr *http.MaxBytesError
|
||||||
go handleRemove(id)
|
if errors.As(err, &maxErr) {
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "remove", "413").Inc()
|
||||||
|
http.Error(w, "Data too large", http.StatusRequestEntityTooLarge)
|
||||||
|
} else {
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "remove", "400").Inc()
|
||||||
|
http.Error(w, "Invalid form data", http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
removeID := r.FormValue("remove")
|
||||||
|
if removeID != "" {
|
||||||
|
metricRemovesTotal.Inc()
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
handleRemove(removeID)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "remove", "303").Inc()
|
||||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||||
|
default:
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "not_found", "404").Inc()
|
||||||
|
http.Error(w, "Not found", http.StatusNotFound)
|
||||||
}
|
}
|
||||||
case "GET":
|
case "GET":
|
||||||
switch {
|
switch {
|
||||||
case id == "":
|
case id == "":
|
||||||
id = "index.html"
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
w.Header().Set("Content-Type", "text/html")
|
w.Header().Set("Cache-Control", "public, max-age=3600")
|
||||||
|
serveFile(w, "index.html")
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "index", "200").Inc()
|
||||||
case strings.HasPrefix(id, "favicon"):
|
case strings.HasPrefix(id, "favicon"):
|
||||||
id = "favicon.png"
|
|
||||||
w.Header().Set("Content-Type", "image/png")
|
w.Header().Set("Content-Type", "image/png")
|
||||||
|
w.Header().Set("Cache-Control", "public, max-age=86400")
|
||||||
|
serveFile(w, "favicon.png")
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "favicon", "200").Inc()
|
||||||
case id == "example":
|
case id == "example":
|
||||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
w.Write([]byte("Hello there\n"))
|
w.Write([]byte("Hello there\n"))
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "example", "200").Inc()
|
||||||
return
|
return
|
||||||
case id == "purge":
|
case id == "purge":
|
||||||
// Security: Only allow purge from localhost or add authentication
|
if !isLocalhost(r.RemoteAddr) {
|
||||||
if r.RemoteAddr != "[::1]:" && !strings.HasPrefix(r.RemoteAddr, "127.0.0.1:") {
|
logger.Warn("unauthorized purge attempt", "remote", r.RemoteAddr)
|
||||||
log.Printf("Unauthorized purge attempt from %s", r.RemoteAddr)
|
metricHTTPRequests.WithLabelValues(r.Method, "purge", "401").Inc()
|
||||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Printf("Purge requested from %s", r.RemoteAddr)
|
logger.Info("purge requested", "remote", r.RemoteAddr)
|
||||||
go handlePurge()
|
metricHTTPRequests.WithLabelValues(r.Method, "purge", "200").Inc()
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
handlePurge()
|
||||||
|
}()
|
||||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
w.Write([]byte("OK\n"))
|
w.Write([]byte("OK\n"))
|
||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
w.Header().Set("X-Robots-Tag", "noindex,nofollow")
|
w.Header().Set("X-Robots-Tag", "noindex,nofollow")
|
||||||
id = *dir + "/" + id + ".txt"
|
filename := filepath.Join(*dir, id+".txt")
|
||||||
|
f, err := os.Open(filename)
|
||||||
|
if err != nil {
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "paste", "404").Inc()
|
||||||
|
http.Error(w, "Not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
metricHTTPRequests.WithLabelValues(r.Method, "paste", "200").Inc()
|
||||||
|
io.CopyN(w, f, int64(*buff))
|
||||||
}
|
}
|
||||||
f, err := os.Open(id)
|
default:
|
||||||
if err != nil {
|
metricHTTPRequests.WithLabelValues(r.Method, "method_not_allowed", "405").Inc()
|
||||||
http.Error(w, "Not found", http.StatusNotFound)
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
return
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
io.CopyN(w, f, int64(*buff))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleTCP(conn net.Conn) {
|
func serveFile(w http.ResponseWriter, name string) {
|
||||||
defer conn.Close()
|
f, err := os.Open(name)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
io.Copy(w, f)
|
||||||
|
}
|
||||||
|
|
||||||
// Rate limiting: limit concurrent connections per IP
|
func handleTCP(conn net.Conn) {
|
||||||
remoteAddr := conn.RemoteAddr().String()
|
remoteAddr := conn.RemoteAddr().String()
|
||||||
log.Printf("TCP %s connection", remoteAddr)
|
|
||||||
|
select {
|
||||||
|
case connSem <- struct{}{}:
|
||||||
|
defer func() { <-connSem }()
|
||||||
|
default:
|
||||||
|
logger.Warn("max connections reached, rejecting", "remote", remoteAddr)
|
||||||
|
conn.Write([]byte("Error: server busy, try again later\n"))
|
||||||
|
conn.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
active := activeConns.Add(1)
|
||||||
|
metricActiveConns.Set(float64(active))
|
||||||
|
defer func() {
|
||||||
|
activeConns.Add(-1)
|
||||||
|
metricActiveConns.Set(float64(activeConns.Load()))
|
||||||
|
conn.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
if tcpIPLimiter != nil {
|
||||||
|
ip := getRemoteIP(remoteAddr)
|
||||||
|
if !tcpIPLimiter.get(ip).Allow() {
|
||||||
|
logger.Warn("rate limit exceeded", "remote", remoteAddr)
|
||||||
|
conn.Write([]byte("Error: rate limit exceeded, slow down\n"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Debug("tcp connection", "remote", remoteAddr)
|
||||||
|
|
||||||
buf := make([]byte, *chunkSize)
|
buf := make([]byte, *chunkSize)
|
||||||
var data []byte
|
var data []byte
|
||||||
@@ -216,7 +563,7 @@ func handleTCP(conn net.Conn) {
|
|||||||
n, err := conn.Read(buf)
|
n, err := conn.Read(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err != io.EOF {
|
if err != io.EOF {
|
||||||
log.Printf("Error reading from %s: %v", remoteAddr, err)
|
logger.Debug("error reading from tcp", "remote", remoteAddr, "error", err)
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -224,7 +571,7 @@ func handleTCP(conn net.Conn) {
|
|||||||
dataLen += n
|
dataLen += n
|
||||||
|
|
||||||
if dataLen >= *buff {
|
if dataLen >= *buff {
|
||||||
log.Printf("Buffer limit exceeded from %s: %d bytes", remoteAddr, dataLen)
|
logger.Warn("buffer limit exceeded", "remote", remoteAddr, "bytes", dataLen)
|
||||||
conn.Write([]byte("Warning: " + strconv.Itoa(*buff/1024/1024) + "MB limit exceeded\n"))
|
conn.Write([]byte("Warning: " + strconv.Itoa(*buff/1024/1024) + "MB limit exceeded\n"))
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -233,15 +580,14 @@ func handleTCP(conn net.Conn) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if dataLen == 0 {
|
if dataLen == 0 {
|
||||||
log.Printf("No data received from %s", remoteAddr)
|
logger.Debug("no data received", "remote", remoteAddr)
|
||||||
conn.Write([]byte("Error: no data received\n"))
|
conn.Write([]byte("Error: no data received\n"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if *plaintext {
|
if *plaintext {
|
||||||
err := checkData(data)
|
if err := checkData(data); err != nil {
|
||||||
if err != nil {
|
logger.Warn("invalid data", "remote", remoteAddr, "error", err)
|
||||||
log.Printf("Invalid data from %s: %v", remoteAddr, err)
|
|
||||||
conn.Write([]byte("Error: " + err.Error() + "\n"))
|
conn.Write([]byte("Error: " + err.Error() + "\n"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -249,12 +595,12 @@ func handleTCP(conn net.Conn) {
|
|||||||
|
|
||||||
id := handleData(data)
|
id := handleData(data)
|
||||||
if id == "" {
|
if id == "" {
|
||||||
log.Printf("Error generating file for %s", remoteAddr)
|
logger.Error("error generating file", "remote", remoteAddr)
|
||||||
conn.Write([]byte("Error generating file\n"))
|
conn.Write([]byte("Error generating file\n"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("TCP %s %d %s.txt", remoteAddr, dataLen, id)
|
logger.Info("tcp paste created", "remote", remoteAddr, "bytes", dataLen, "id", id)
|
||||||
conn.Write([]byte(*httpURL + id + "\n"))
|
conn.Write([]byte(*httpURL + id + "\n"))
|
||||||
time.Sleep(100 * time.Millisecond)
|
time.Sleep(100 * time.Millisecond)
|
||||||
}
|
}
|
||||||
@@ -264,7 +610,6 @@ func checkData(data []byte) error {
|
|||||||
return errors.New("only plain text data is allowed")
|
return errors.New("only plain text data is allowed")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Additional validation: check for control characters (except newline)
|
|
||||||
for _, b := range data {
|
for _, b := range data {
|
||||||
if b < 32 && b != '\n' && b != '\t' && b != '\r' {
|
if b < 32 && b != '\n' && b != '\t' && b != '\r' {
|
||||||
return errors.New("control characters are not allowed")
|
return errors.New("control characters are not allowed")
|
||||||
@@ -278,43 +623,42 @@ func handleData(data []byte) string {
|
|||||||
var id string
|
var id string
|
||||||
for l := 6; l <= 16; l++ {
|
for l := 6; l <= 16; l++ {
|
||||||
id = generateId(data, l)
|
id = generateId(data, l)
|
||||||
if _, err := os.Stat(*dir + "/" + id + ".txt"); os.IsNotExist(err) {
|
if _, err := os.Stat(filepath.Join(*dir, id+".txt")); os.IsNotExist(err) {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
id = ""
|
id = ""
|
||||||
}
|
}
|
||||||
if id == "" {
|
if id == "" {
|
||||||
log.Println("Error no available id found")
|
logger.Error("no available id found")
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate ID format
|
|
||||||
if !isAlphanumeric(id) {
|
if !isAlphanumeric(id) {
|
||||||
log.Printf("Error invalid ID format: %s", id)
|
logger.Error("invalid ID format", "id", id)
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
filename := *dir + "/" + id + ".txt"
|
filename := filepath.Join(*dir, id+".txt")
|
||||||
f, err := os.Create(filename)
|
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Error creating file %s: %v", filename, err)
|
logger.Error("error creating file", "file", filename, "error", err)
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
defer f.Close()
|
defer f.Close()
|
||||||
|
|
||||||
// Ensure data ends with newline
|
|
||||||
if len(data) > 0 && data[len(data)-1] != '\n' {
|
if len(data) > 0 && data[len(data)-1] != '\n' {
|
||||||
data = append(data, '\n')
|
data = append(data, '\n')
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = f.Write(data)
|
if _, err := f.Write(data); err != nil {
|
||||||
if err != nil {
|
logger.Error("error writing to file", "file", filename, "error", err)
|
||||||
log.Printf("Error writing to file %s: %v", filename, err)
|
|
||||||
// Try to clean up the empty file
|
|
||||||
os.Remove(filename)
|
os.Remove(filename)
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
metricPastesTotal.Inc()
|
||||||
|
metricPastesBytes.Add(float64(len(data)))
|
||||||
|
|
||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,41 +681,46 @@ func isAlphanumeric(id string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func handleRemove(id string) {
|
func handleRemove(id string) {
|
||||||
// Extract ID from URL or direct input
|
parts := strings.Split(id, "/")
|
||||||
id = strings.TrimPrefix(strings.Split(id, "/")[len(strings.Split(id, "/"))-1], "/")
|
id = strings.TrimPrefix(parts[len(parts)-1], "/")
|
||||||
|
|
||||||
// Validate ID format
|
|
||||||
if id == "" || len(id) > 16 || !isAlphanumeric(id) {
|
if id == "" || len(id) > 16 || !isAlphanumeric(id) {
|
||||||
log.Printf("Error invalid id to remove: %s", id)
|
logger.Warn("invalid id to remove", "id", id)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
filename := *dir + "/" + id + ".txt"
|
filename := filepath.Join(*dir, id+".txt")
|
||||||
|
|
||||||
// Check if file exists before attempting to remove
|
|
||||||
if _, err := os.Stat(filename); os.IsNotExist(err) {
|
if _, err := os.Stat(filename); os.IsNotExist(err) {
|
||||||
log.Printf("File not found for removal: %s", filename)
|
logger.Debug("file not found for removal", "file", filename)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err := os.Remove(filename)
|
if err := os.Remove(filename); err != nil {
|
||||||
if err != nil {
|
logger.Error("error removing file", "file", filename, "error", err)
|
||||||
log.Printf("Error removing file %s: %v", filename, err)
|
|
||||||
} else {
|
} else {
|
||||||
log.Printf("File removed: %s", filename)
|
logger.Info("file removed", "file", filename)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func handlePurge() {
|
func handlePurge() {
|
||||||
|
if !purgeMu.TryLock() {
|
||||||
|
logger.Debug("purge already running, skipping")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer purgeMu.Unlock()
|
||||||
|
|
||||||
|
metricPurgeRuns.Inc()
|
||||||
|
logger.Info("purge started")
|
||||||
|
|
||||||
files, err := os.ReadDir(*dir)
|
files, err := os.ReadDir(*dir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Error reading data directory: %v", err)
|
logger.Error("error reading data directory", "error", err)
|
||||||
|
metricPurgeFilesTotal.WithLabelValues("error").Inc()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var filesRemoved int
|
var filesRemoved, filesSkipped, errorsEncountered int
|
||||||
var filesSkipped int
|
|
||||||
var errorsEncountered int
|
|
||||||
|
|
||||||
for _, file := range files {
|
for _, file := range files {
|
||||||
if file.IsDir() {
|
if file.IsDir() {
|
||||||
@@ -379,7 +728,6 @@ func handlePurge() {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only process .txt files
|
|
||||||
if !strings.HasSuffix(file.Name(), ".txt") {
|
if !strings.HasSuffix(file.Name(), ".txt") {
|
||||||
filesSkipped++
|
filesSkipped++
|
||||||
continue
|
continue
|
||||||
@@ -387,23 +735,29 @@ func handlePurge() {
|
|||||||
|
|
||||||
info, err := file.Info()
|
info, err := file.Info()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Error getting file info for %s: %v", file.Name(), err)
|
logger.Error("error getting file info", "file", file.Name(), "error", err)
|
||||||
errorsEncountered++
|
errorsEncountered++
|
||||||
|
metricPurgeFilesTotal.WithLabelValues("error").Inc()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if time.Since(info.ModTime()) > time.Duration(*ttl)*time.Hour {
|
if time.Since(info.ModTime()) > time.Duration(*ttl)*time.Hour {
|
||||||
filename := *dir + "/" + file.Name()
|
filename := filepath.Join(*dir, file.Name())
|
||||||
err = os.Remove(filename)
|
if err := os.Remove(filename); err != nil {
|
||||||
if err != nil {
|
logger.Error("error removing file", "file", filename, "error", err)
|
||||||
log.Printf("Error removing file %s: %v", filename, err)
|
|
||||||
errorsEncountered++
|
errorsEncountered++
|
||||||
|
metricPurgeFilesTotal.WithLabelValues("error").Inc()
|
||||||
} else {
|
} else {
|
||||||
filesRemoved++
|
filesRemoved++
|
||||||
log.Printf("File removed: %s", filename)
|
logger.Debug("file removed", "file", filename)
|
||||||
|
metricPurgeFilesTotal.WithLabelValues("removed").Inc()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("Purge done: %d files removed, %d files skipped, %d errors", filesRemoved, filesSkipped, errorsEncountered)
|
logger.Info("purge done",
|
||||||
|
"removed", filesRemoved,
|
||||||
|
"skipped", filesSkipped,
|
||||||
|
"errors", errorsEncountered,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user