Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add bandwidth limiter in Route #668

Open
wants to merge 6 commits into
base: dev-next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions adapter/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ type Rule interface {
Match(metadata *InboundContext) bool
Outbound() string
String() string
Limiters() []string
}

type DNSRule interface {
Expand Down
4 changes: 4 additions & 0 deletions box.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/sagernet/sing-box/experimental"
"github.com/sagernet/sing-box/experimental/libbox/platform"
"github.com/sagernet/sing-box/inbound"
"github.com/sagernet/sing-box/limiter"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-box/outbound"
Expand Down Expand Up @@ -76,6 +77,9 @@ func New(options Options) (*Box, error) {
if err != nil {
return nil, E.Cause(err, "create log factory")
}
if len(options.Limiters) > 0 {
ctx = limiter.WithDefault(ctx, logFactory.NewLogger("limiter"), options.Limiters)
}
router, err := route.NewRouter(
ctx,
logFactory,
Expand Down
2 changes: 2 additions & 0 deletions docs/configuration/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ sing-box uses JSON for configuration files.
"ntp": {},
"inbounds": [],
"outbounds": [],
"limiters": [],
"route": {},
"experimental": {}
}
Expand All @@ -25,6 +26,7 @@ sing-box uses JSON for configuration files.
| `ntp` | [NTP](./ntp) |
| `inbounds` | [Inbound](./inbound) |
| `outbounds` | [Outbound](./outbound) |
| `limiters` | [Limiter](./limiter) |
| `route` | [Route](./route) |
| `experimental` | [Experimental](./experimental) |

Expand Down
2 changes: 2 additions & 0 deletions docs/configuration/index.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ sing-box 使用 JSON 作为配置文件格式。
"dns": {},
"inbounds": [],
"outbounds": [],
"limiters": [],
"route": {},
"experimental": {}
}
Expand All @@ -23,6 +24,7 @@ sing-box 使用 JSON 作为配置文件格式。
| `dns` | [DNS](./dns) |
| `inbounds` | [入站](./inbound) |
| `outbounds` | [出站](./outbound) |
| `limiters` | [限速](./limiter) |
| `route` | [路由](./route) |
| `experimental` | [实验性](./experimental) |

Expand Down
56 changes: 56 additions & 0 deletions docs/configuration/limiter/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Limiter

### Structure

```json
{
"limiters": [
{
"tag": "limiter-a",
"download": "10M",
"upload": "1M",
"auth_user": [
"user-a",
"user-b"
],
"auth_user_independent": false,
"inbound": [
"in-a",
"in-b"
],
"inbound_independent": false
}
]
}

```

### Fields

#### download upload

==Required==

Format: `[Integer][Unit]` e.g. `100M, 100m, 1G, 1g`.

Supported units (case insensitive): `B, K, M, G, T, P, E`.

#### tag

The tag of the limiter, used in route rule.

#### auth_user

Apply limiter for a group of usernames, see each inbound for details.

#### auth_user_independent

Make each auth_user's limiter independent. If disabled, the same limiter will be shared.

#### inbound

Apply limiter for a group of inbounds.

#### inbound_independent

Make each inbound's limiter independent. If disabled, the same limiter will be shared.
56 changes: 56 additions & 0 deletions docs/configuration/limiter/index.zh.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# 限速

### 结构

```json
{
"limiters": [
{
"tag": "limiter-a",
"download": "10M",
"upload": "1M",
"auth_user": [
"user-a",
"user-b"
],
"auth_user_independent": false,
"inbound": [
"in-a",
"in-b"
],
"inbound_independent": false
}
]
}

```

### 字段

#### download upload

==必填==

格式: `[Integer][Unit]` 例如: `100M, 100m, 1G, 1g`.

支持的单位 (大小写不敏感): `B, K, M, G, T, P, E`.

#### tag

限速标签,在路由规则中使用。

#### auth_user

用户组限速,参阅入站设置。

#### auth_user_independent

使每个用户有单独的限速。关闭时将共享限速。

#### inbound

入站组限速。

#### inbound_independent

使每个入站有单独的限速。关闭时将共享限速。
16 changes: 14 additions & 2 deletions docs/configuration/route/rule.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,22 @@
],
"clash_mode": "direct",
"invert": false,
"outbound": "direct"
"outbound": "direct",
"limiter": [
"limiter-a",
"limiter-b"
]
},
{
"type": "logical",
"mode": "and",
"rules": [],
"invert": false,
"outbound": "direct"
"outbound": "direct",
"limiter": [
"limiter-a",
"limiter-b"
]
}
]
}
Expand Down Expand Up @@ -238,6 +246,10 @@ Invert match result.

Tag of the target outbound.

#### limiter

Tags of [Limiter](/configuration/limiter). Take effect for all connections matching this rule.

### Logical Fields

#### type
Expand Down
16 changes: 14 additions & 2 deletions docs/configuration/route/rule.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,22 @@
],
"clash_mode": "direct",
"invert": false,
"outbound": "direct"
"outbound": "direct",
"limiter": [
"limiter-a",
"limiter-b"
]
},
{
"type": "logical",
"mode": "and",
"rules": [],
"invert": false,
"outbound": "direct"
"outbound": "direct",
"limiter": [
"limiter-a",
"limiter-b"
]
}
]
}
Expand Down Expand Up @@ -236,6 +244,10 @@

目标出站的标签。

#### limiter

[限速](/zh/configuration/inbound) 标签。对所有匹配该规则的连接生效。

### 逻辑字段

#### type
Expand Down
111 changes: 111 additions & 0 deletions limiter/builder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package limiter

import (
"context"
"fmt"
"net"

"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/humanize"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/service"
)

const (
prefixTag = "tag"
prefixUser = "user"
prefixInbound = "inbound"
)

var _ Manager = (*defaultManager)(nil)

type limiterKey struct {
Prefix string
Name string
}

type defaultManager struct {
mp map[limiterKey]*limiter
}

func WithDefault(ctx context.Context, logger log.ContextLogger, options []option.Limiter) context.Context {
m := &defaultManager{mp: make(map[limiterKey]*limiter)}
for i, option := range options {
if err := m.createLimiter(ctx, option); err != nil {
logger.ErrorContext(ctx, fmt.Sprintf("id=%d, %s", i, err))
} else {
logger.InfoContext(ctx, fmt.Sprintf("id=%d, tag=%s, users=%v, inbounds=%v, download=%s, upload=%s",
i, option.Tag, option.AuthUser, option.Inbound, option.Download, option.Upload))
}
}
return service.ContextWith[Manager](ctx, m)
}

func (m *defaultManager) createLimiter(ctx context.Context, option option.Limiter) (err error) {
var download, upload uint64
if option.Download != "" {
download, err = humanize.ParseBytes(option.Download)
if err != nil {
return err
}
}
if option.Upload != "" {
upload, err = humanize.ParseBytes(option.Upload)
if err != nil {
return err
}
}
if download == 0 && upload == 0 {
return E.New("download/upload, at least one must be set")
}
if option.Tag == "" && len(option.AuthUser) == 0 && len(option.Inbound) == 0 {
return E.New("tag/user/inbound, at least one must be set")
}
var sharedLimiter *limiter
if option.Tag != "" || !option.AuthUserIndependent || !option.InboundIndependent {
sharedLimiter = newLimiter(download, upload)
}
if option.Tag != "" {
m.mp[limiterKey{prefixTag, option.Tag}] = sharedLimiter
}
for _, user := range option.AuthUser {
if option.AuthUserIndependent {
m.mp[limiterKey{prefixUser, user}] = newLimiter(download, upload)
} else {
m.mp[limiterKey{prefixUser, user}] = sharedLimiter
}
}
for _, inbound := range option.Inbound {
if option.InboundIndependent {
m.mp[limiterKey{prefixInbound, inbound}] = newLimiter(download, upload)
} else {
m.mp[limiterKey{prefixInbound, inbound}] = sharedLimiter
}
}
return
}

func (m *defaultManager) NewConnWithLimiters(ctx context.Context, conn net.Conn, metadata *adapter.InboundContext, rule adapter.Rule) net.Conn {
var limiters []*limiter
if rule != nil {
for _, tag := range rule.Limiters() {
if v, ok := m.mp[limiterKey{prefixTag, tag}]; ok {
limiters = append(limiters, v)
}
}
}
if metadata != nil {
if v, ok := m.mp[limiterKey{prefixUser, metadata.User}]; ok {
limiters = append(limiters, v)
}
if v, ok := m.mp[limiterKey{prefixInbound, metadata.Inbound}]; ok {
limiters = append(limiters, v)
}
}
for _, limiter := range limiters {
conn = &connWithLimiter{Conn: conn, limiter: limiter, ctx: ctx}
}
return conn
}
Loading
Loading