Skip to content

Commit

Permalink
feat: rename project to Xray Torrent Blocker and update related confi…
Browse files Browse the repository at this point in the history
…gurations

- Renamed project from "Marzban Torrent Blocker" to "Xray Torrent Blocker"
- Updated module name, binary name, and service name to "tblocker"
- Added persistent IP block storage with JSON file
- Updated installation and configuration scripts
- Modified README and systemd service files
- Added new storage mechanism for tracking blocked IPs
- Implemented automatic block restoration and cleanup

Co-authored-by: aigoncharov <[email protected]>
  • Loading branch information
kutovoys and aigoncharov committed Feb 14, 2025
1 parent 294e30e commit 5a95812
Show file tree
Hide file tree
Showing 13 changed files with 295 additions and 70 deletions.
2 changes: 1 addition & 1 deletion .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ checksum:

builds:
- id: build
binary: torrent-blocker
binary: tblocker
env:
- CGO_ENABLED=0
goos:
Expand Down
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
all: amd64 arm64

amd64:
GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -X main.Version=v0.0.1dev" -o build/torrents-blocker_amd64
GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -X main.Version=v0.0.1dev" -o build/tblocker_amd64

arm64:
GOOS=linux GOARCH=arm64 go build -ldflags="-s -w -X main.Version=v0.0.1dev" -o build/torrents-blocker_arm64
GOOS=linux GOARCH=arm64 go build -ldflags="-s -w -X main.Version=v0.0.1dev" -o build/tblocker_arm64
32 changes: 23 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
# Marzban Torrent Blocker
# Xray Torrent Blocker

[![en](https://img.shields.io/badge/lang-en-red)](https://github.com/kutovoys/marzban-torrent-blocker/blob/main/README.md)
[![ru](https://img.shields.io/badge/lang-ru-blue)](https://github.com/kutovoys/marzban-torrent-blocker/blob/main/README.ru.md)
[![en](https://img.shields.io/badge/lang-en-red)](https://github.com/kutovoys/xray-torrent-blocker/blob/main/README.md)
[![ru](https://img.shields.io/badge/lang-ru-blue)](https://github.com/kutovoys/xray-torrent-blocker/blob/main/README.ru.md)

Marzban Torrent Blocker is an application designed to block torrent usage by users of the [Marzban](https://github.com/Gozargah/Marzban) panel. The application analyzes logs, detects torrent activity, and temporarily blocks the user, sending notifications to the administrator via Telegram, and optionally to the user.
It can also work with other panels and directly with Xray.
Xray Torrent Blocker is an application designed to block torrent usage by users of the [Xray-based](https://github.com/XTLS/Xray-core) panels. The application analyzes logs, detects torrent activity, and temporarily blocks the user, sending notifications to the administrator via Telegram, and optionally to the user.

## Features:

Expand All @@ -16,6 +15,9 @@ It can also work with other panels and directly with Xray.
- Configurable block duration.
- Supports temporary blocking with automatic unblocking.
- Simple installation and setup via systemd.
- Persistent block state between application restarts.
- Automatic block restoration after system reboot.
- Automatic cleanup of expired blocks.

## Preparation

Expand Down Expand Up @@ -66,7 +68,7 @@ It can also work with other panels and directly with Xray.
```yaml
volumes:
- /var/lib/marzban:/var/lib/marzban
- /var/lib/marzban-node:/var/lib/marzban-node #новый volume
- /var/lib/marzban-node:/var/lib/marzban-node #new volume
```
- Restart the panel with the following command:
Expand Down Expand Up @@ -96,12 +98,12 @@ To automatically install the application, follow these steps:
- The script will automatically install all dependencies, download the latest release, ask for the admin `Token` and `Chat ID`, and start the service.
- After installation, you can control the application via systemd:
```bash
systemctl start/status/stop torrent-blocker
systemctl start/status/stop tblocker
```

## Configuration

After installation, you can configure the application's behavior via the configuration file located at: `/opt/torrent-blocker/config.yaml`.
After installation, you can configure the application's behavior via the configuration file located at: `/opt/tblocker/config.yaml`.

Key configuration parameters:

Expand All @@ -116,8 +118,9 @@ Key configuration parameters:
- **TidRegex** — regular expression to extract the user's `CHAT_ID` from the log entry. Optional.
- **UserMessageTemplate** — the message template for notifying the user. Optional.
- **UsernameRegex** — regular expression to extract the user's login from the log entry. Optional.
- **StorageDir** — path to the directory for storing block data. Default: `/opt/tblocker`

An example configuration file with detailed comments is available at `/opt/torrent-blocker/config.yaml`.
An example configuration file with detailed comments is available at `/opt/tblocker/config.yaml.example`.

### Example for Sending Notifications to Users:

Expand All @@ -130,6 +133,17 @@ For example, if the user's login in Marzban looks like this: `kutovoys_tgid-1234

In this case, the administrator will receive notifications with the username `kutovoys`, and the user will also be notified directly via Telegram when they are blocked.

### Block Data Storage

The application stores block information in a JSON file in the directory specified by the `StorageDir` parameter. This ensures:

- Persistent block state between application restarts
- Automatic block restoration after system reboot
- Proper user unblocking even after application restart
- Automatic cleanup of expired blocks

The block data file is located at: `/opt/tblocker/blocked_ips.json`

## Contributing

We welcome contributions from the community! If you have ideas for improvements or have found a bug, please create an issue or submit a pull request on GitHub.
30 changes: 22 additions & 8 deletions README.ru.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
# Marzban Torrent Blocker
# Xray Torrent Blocker

[![en](https://img.shields.io/badge/lang-en-red)](https://github.com/kutovoys/marzban-torrent-blocker/blob/main/README.md)
[![ru](https://img.shields.io/badge/lang-ru-blue)](https://github.com/kutovoys/marzban-torrent-blocker/blob/main/README.ru.md)
[![en](https://img.shields.io/badge/lang-en-red)](https://github.com/kutovoys/xray-torrent-blocker/blob/main/README.md)
[![ru](https://img.shields.io/badge/lang-ru-blue)](https://github.com/kutovoys/xray-torrent-blocker/blob/main/README.ru.md)

Marzban Torrent Blocker — это приложение для блокировки использования торрентов пользователями панели [Marzban](https://github.com/Gozargah/Marzban). Приложение анализирует логи, обнаруживает использование торрентов и временно блокирует пользователя, отправляя уведомления в Telegram администратору и, опционально, пользователю.
Возможна работа и с другими панелями. А также напрямую с Xray.
Xray Torrent Blocker — это приложение для блокировки использования торрентов пользователями панелей на базе [Xray](https://github.com/XTLS/Xray-core). Приложение анализирует логи, обнаруживает использование торрентов и временно блокирует пользователя, отправляя уведомления в Telegram администратору и, опционально, пользователю.

## Возможности:

Expand All @@ -16,6 +15,9 @@ Marzban Torrent Blocker — это приложение для блокиров
- Настраиваемое время блокировки.
- Поддержка временной блокировки с последующей разблокировкой.
- Простая установка и настройка через systemd.
- Сохранение состояния блокировок между перезапусками приложения.
- Автоматическое восстановление блокировок после перезагрузки системы.
- Автоматическая очистка просроченных блокировок.

## Подготовка

Expand Down Expand Up @@ -96,12 +98,12 @@ volumes:
- Скрипт автоматически установит все зависимости, скачает последний релиз, спросит `Token` и `Chat ID` администратора и запустит сервис.
- После завершения установки приложение можно контролировать через systemd:
```bash
systemctl start/status/stop torrent-blocker
systemctl start/status/stop tblocker
```

## Конфигурация

После установки вы можете настроить поведение приложения через файл конфигурации, который находится по пути: `/opt/torrent-blocker/config.yaml`.
После установки вы можете настроить поведение приложения через файл конфигурации, который находится по пути: `/opt/tblocker/config.yaml`.

Основные параметры конфигурации:

Expand All @@ -116,8 +118,9 @@ volumes:
- **TidRegex** — регулярное выражение для извлечения `CHAT_ID` пользователя из строки лога. Опционально.
- **UserMessageTemplate** — шаблон сообщения для уведомления пользователя. Опционально.
- **UsernameRegex** — регулярное выражение для извлечения логина пользователя из строки лога. Опционально.
- **StorageDir** — путь к директории для хранения данных о блокировках. По умолчанию: `/opt/tblocker`

Пример файла конфигурации с подробными комментариями находится в `/opt/torrent-blocker/config.yaml`
Пример файла конфигурации с подробными комментариями находится в `/opt/tblocker/config.yaml.example`

### Пример для отправки сообщений пользователю:

Expand All @@ -130,6 +133,17 @@ volumes:

В таком случае администратор будет получать уведомления с именем пользователя `kutovoys`, а пользователь будет получать сообщения о блокировке напрямую через Telegram.

### Хранение данных о блокировках

Приложение сохраняет информацию о блокировках в JSON-файл в директории, указанной в параметре `StorageDir`. Это обеспечивает:

- Сохранение состояния блокировок между перезапусками приложения
- Автоматическое восстановление блокировок после перезагрузки системы
- Корректную разблокировку пользователей даже после перезапуска приложения
- Автоматическую очистку просроченных блокировок

Файл с данными о блокировках находится по пути: `/opt/tblocker/blocked_ips.json`

## Contributing

Мы приветствуем вклад от сообщества! Если у вас есть идеи для улучшений или вы нашли баг, пожалуйста, создайте issue или отправьте pull request на GitHub.
4 changes: 4 additions & 0 deletions config.yaml.example
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,7 @@ WebhookURL: "https://your-webhook-url.com/endpoint"
# Optional. JSON template for webhook
# Available variables: %s - username, %s - ip, %s - server, %s - action (block/unblock), %s - timestamp
WebhookTemplate: '{"username":"%s","ip":"%s","server":"%s","action":"%s","timestamp":"%s"}'

# Опционально. Путь к директории для хранения файла с заблокированными IP-адресами.
# Optional. Path to the directory for storing the blocked IP addresses file.
StorageDir: "/opt/tblocker"
7 changes: 7 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ var (
SendWebhook bool
WebhookURL string
WebhookTemplate string
StorageDir string
)

var (
Expand Down Expand Up @@ -75,6 +76,7 @@ type Config struct {
SendWebhook bool `yaml:"SendWebhook"`
WebhookURL string `yaml:"WebhookURL"`
WebhookTemplate string `yaml:"WebhookTemplate"`
StorageDir string `yaml:"StorageDir"`
}

func LoadConfig(configPath string) error {
Expand Down Expand Up @@ -134,5 +136,10 @@ func LoadConfig(configPath string) error {
WebhookTemplate = `{"username":"%s","ip":"%s","server":"%s","action":"%s","timestamp":"%s"}`
}

StorageDir = cfg.StorageDir
if StorageDir == "" {
StorageDir = "/opt/tblocker"
}

return err
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module torrents-blocker
module tblocker

go 1.21

Expand Down
28 changes: 14 additions & 14 deletions install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,18 @@ else
fi

echo "Downloading the latest version of torrent-blocker..."
LATEST_RELEASE=$(curl -s https://api.github.com/repos/kutovoys/marzban-torrent-blocker/releases/latest | grep tag_name | cut -d '"' -f 4)
URL="https://github.com/kutovoys/marzban-torrent-blocker/releases/download/${LATEST_RELEASE}/marzban-torrent-blocker-${LATEST_RELEASE}-linux-${ARCH}.tar.gz"
LATEST_RELEASE=$(curl -s https://api.github.com/repos/kutovoys/xray-torrent-blocker/releases/latest | grep tag_name | cut -d '"' -f 4)
URL="https://github.com/kutovoys/xray-torrent-blocker/releases/download/${LATEST_RELEASE}/xray-torrent-blocker-${LATEST_RELEASE}-linux-${ARCH}.tar.gz"

curl -sL "$URL" -o torrent-blocker.tar.gz
curl -sL "$URL" -o tblocker.tar.gz

echo "Extracting files..."
mkdir -p /opt/torrent-blocker
tar -xzf torrent-blocker.tar.gz -C /opt/torrent-blocker --overwrite
rm torrent-blocker.tar.gz
mkdir -p /opt/tblocker
tar -xzf tblocker.tar.gz -C /opt/tblocker --overwrite
rm tblocker.tar.gz

CONFIG_PATH="/opt/torrent-blocker/config.yaml"
CONFIG_TEMPLATE_PATH="/opt/torrent-blocker/config.yaml.example"
CONFIG_PATH="/opt/tblocker/config.yaml"
CONFIG_TEMPLATE_PATH="/opt/tblocker/config.yaml.example"

if [ ! -f "$CONFIG_PATH" ]; then
mv "$CONFIG_TEMPLATE_PATH" "$CONFIG_PATH"
Expand Down Expand Up @@ -79,23 +79,23 @@ if $ask_for_input; then
fi

echo "Setting up systemd service..."
curl -sL https://raw.githubusercontent.com/kutovoys/marzban-torrent-blocker/main/torrent-blocker.service -o /etc/systemd/system/torrent-blocker.service
curl -sL https://raw.githubusercontent.com/kutovoys/xray-torrent-blocker/main/tblocker.service -o /etc/systemd/system/tblocker.service

systemctl daemon-reload
systemctl enable torrent-blocker
systemctl start torrent-blocker
systemctl enable tblocker
systemctl start tblocker

systemctl status torrent-blocker --no-pager
systemctl status tblocker --no-pager

echo ""
echo "==============================================================="
echo ""
echo "Installation complete! The torrent-blocker service is running."
echo ""
echo "PLEASE SETUP UFW PROPERLY! (https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufw-on-ubuntu)"
echo "==============================================================="
echo ""
echo "You can configure additional options in the configuration file"
echo "/opt/torrent-blocker/config.yaml"
echo "/opt/tblocker/config.yaml"
echo "It is possible to enable sending user notifications via Telegram."
echo ""
echo "==============================================================="
13 changes: 9 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import (
"log"
"os"
"path/filepath"
"torrents-blocker/config"
"torrents-blocker/utils"
"tblocker/config"
"tblocker/storage"
"tblocker/utils"
)

var Version string
Expand All @@ -26,9 +27,7 @@ func initConfig() {
var showVersion bool

flag.StringVar(&configPath, "c", "", "Path to the configuration file")

flag.BoolVar(&showVersion, "v", false, "Display version")

flag.Parse()

if showVersion {
Expand All @@ -48,5 +47,11 @@ func initConfig() {
log.Fatalf("Failed to load configuration: %v", err)
}

store, err := storage.NewIPStorage(config.StorageDir, utils.UnblockIPAfterDelay)
if err != nil {
log.Fatalf("Failed to initialize IP storage: %v", err)
}
utils.SetIPStorage(store)

utils.ScheduleBlockedIPsUpdate()
}
Loading

0 comments on commit 5a95812

Please sign in to comment.