Hunter0x7c7
2022-08-11 a82f9cb69f63aaeba40c024960deda7d75b9fece
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package command_test
 
import (
    "context"
    "testing"
    "time"
 
    "github.com/golang/mock/gomock"
    "github.com/google/go-cmp/cmp"
    "github.com/google/go-cmp/cmp/cmpopts"
    "google.golang.org/grpc"
    "google.golang.org/grpc/test/bufconn"
 
    "github.com/v2fly/v2ray-core/v5/app/router"
    . "github.com/v2fly/v2ray-core/v5/app/router/command"
    "github.com/v2fly/v2ray-core/v5/app/router/routercommon"
    "github.com/v2fly/v2ray-core/v5/app/stats"
    "github.com/v2fly/v2ray-core/v5/common"
    "github.com/v2fly/v2ray-core/v5/common/net"
    "github.com/v2fly/v2ray-core/v5/features/routing"
    "github.com/v2fly/v2ray-core/v5/testing/mocks"
)
 
func TestServiceSubscribeRoutingStats(t *testing.T) {
    c := stats.NewChannel(&stats.ChannelConfig{
        SubscriberLimit: 1,
        BufferSize:      0,
        Blocking:        true,
    })
    common.Must(c.Start())
    defer c.Close()
 
    lis := bufconn.Listen(1024 * 1024)
    bufDialer := func(context.Context, string) (net.Conn, error) {
        return lis.Dial()
    }
 
    testCases := []*RoutingContext{
        {InboundTag: "in", OutboundTag: "out"},
        {TargetIPs: [][]byte{{1, 2, 3, 4}}, TargetPort: 8080, OutboundTag: "out"},
        {TargetDomain: "example.com", TargetPort: 443, OutboundTag: "out"},
        {SourcePort: 9999, TargetPort: 9999, OutboundTag: "out"},
        {Network: net.Network_UDP, OutboundGroupTags: []string{"outergroup", "innergroup"}, OutboundTag: "out"},
        {Protocol: "bittorrent", OutboundTag: "blocked"},
        {User: "example@v2fly.org", OutboundTag: "out"},
        {SourceIPs: [][]byte{{127, 0, 0, 1}}, Attributes: map[string]string{"attr": "value"}, OutboundTag: "out"},
    }
    errCh := make(chan error)
    nextPub := make(chan struct{})
 
    // Server goroutine
    go func() {
        server := grpc.NewServer()
        RegisterRoutingServiceServer(server, NewRoutingServer(nil, c))
        errCh <- server.Serve(lis)
    }()
 
    // Publisher goroutine
    go func() {
        publishTestCases := func() error {
            ctx, cancel := context.WithTimeout(context.Background(), time.Second)
            defer cancel()
            for { // Wait until there's one subscriber in routing stats channel
                if len(c.Subscribers()) > 0 {
                    break
                }
                if ctx.Err() != nil {
                    return ctx.Err()
                }
            }
            for _, tc := range testCases {
                c.Publish(context.Background(), AsRoutingRoute(tc))
                time.Sleep(time.Millisecond)
            }
            return nil
        }
 
        if err := publishTestCases(); err != nil {
            errCh <- err
        }
 
        // Wait for next round of publishing
        <-nextPub
 
        if err := publishTestCases(); err != nil {
            errCh <- err
        }
    }()
 
    // Client goroutine
    go func() {
        defer lis.Close()
        conn, err := grpc.DialContext(context.Background(), "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
        if err != nil {
            errCh <- err
            return
        }
        defer conn.Close()
        client := NewRoutingServiceClient(conn)
 
        // Test retrieving all fields
        testRetrievingAllFields := func() error {
            streamCtx, streamClose := context.WithCancel(context.Background())
 
            // Test the unsubscription of stream works well
            defer func() {
                streamClose()
                timeOutCtx, timeout := context.WithTimeout(context.Background(), time.Second)
                defer timeout()
                for { // Wait until there's no subscriber in routing stats channel
                    if len(c.Subscribers()) == 0 {
                        break
                    }
                    if timeOutCtx.Err() != nil {
                        t.Error("unexpected subscribers not decreased in channel", timeOutCtx.Err())
                    }
                }
            }()
 
            stream, err := client.SubscribeRoutingStats(streamCtx, &SubscribeRoutingStatsRequest{})
            if err != nil {
                return err
            }
 
            for _, tc := range testCases {
                msg, err := stream.Recv()
                if err != nil {
                    return err
                }
                if r := cmp.Diff(msg, tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
                    t.Error(r)
                }
            }
 
            // Test that double subscription will fail
            errStream, err := client.SubscribeRoutingStats(context.Background(), &SubscribeRoutingStatsRequest{
                FieldSelectors: []string{"ip", "port", "domain", "outbound"},
            })
            if err != nil {
                return err
            }
            if _, err := errStream.Recv(); err == nil {
                t.Error("unexpected successful subscription")
            }
 
            return nil
        }
 
        // Test retrieving only a subset of fields
        testRetrievingSubsetOfFields := func() error {
            streamCtx, streamClose := context.WithCancel(context.Background())
            defer streamClose()
            stream, err := client.SubscribeRoutingStats(streamCtx, &SubscribeRoutingStatsRequest{
                FieldSelectors: []string{"ip", "port", "domain", "outbound"},
            })
            if err != nil {
                return err
            }
 
            // Send nextPub signal to start next round of publishing
            close(nextPub)
 
            for _, tc := range testCases {
                msg, err := stream.Recv()
                if err != nil {
                    return err
                }
                stat := &RoutingContext{ // Only a subset of stats is retrieved
                    SourceIPs:         tc.SourceIPs,
                    TargetIPs:         tc.TargetIPs,
                    SourcePort:        tc.SourcePort,
                    TargetPort:        tc.TargetPort,
                    TargetDomain:      tc.TargetDomain,
                    OutboundGroupTags: tc.OutboundGroupTags,
                    OutboundTag:       tc.OutboundTag,
                }
                if r := cmp.Diff(msg, stat, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
                    t.Error(r)
                }
            }
 
            return nil
        }
 
        if err := testRetrievingAllFields(); err != nil {
            errCh <- err
        }
        if err := testRetrievingSubsetOfFields(); err != nil {
            errCh <- err
        }
        errCh <- nil // Client passed all tests successfully
    }()
 
    // Wait for goroutines to complete
    select {
    case <-time.After(2 * time.Second):
        t.Fatal("Test timeout after 2s")
    case err := <-errCh:
        if err != nil {
            t.Fatal(err)
        }
    }
}
 
func TestSerivceTestRoute(t *testing.T) {
    c := stats.NewChannel(&stats.ChannelConfig{
        SubscriberLimit: 1,
        BufferSize:      16,
        Blocking:        true,
    })
    common.Must(c.Start())
    defer c.Close()
 
    r := new(router.Router)
    mockCtl := gomock.NewController(t)
    defer mockCtl.Finish()
    common.Must(r.Init(context.TODO(), &router.Config{
        Rule: []*router.RoutingRule{
            {
                InboundTag: []string{"in"},
                TargetTag:  &router.RoutingRule_Tag{Tag: "out"},
            },
            {
                Protocol:  []string{"bittorrent"},
                TargetTag: &router.RoutingRule_Tag{Tag: "blocked"},
            },
            {
                PortList:  &net.PortList{Range: []*net.PortRange{{From: 8080, To: 8080}}},
                TargetTag: &router.RoutingRule_Tag{Tag: "out"},
            },
            {
                SourcePortList: &net.PortList{Range: []*net.PortRange{{From: 9999, To: 9999}}},
                TargetTag:      &router.RoutingRule_Tag{Tag: "out"},
            },
            {
                Domain:    []*routercommon.Domain{{Type: routercommon.Domain_RootDomain, Value: "com"}},
                TargetTag: &router.RoutingRule_Tag{Tag: "out"},
            },
            {
                SourceGeoip: []*routercommon.GeoIP{{CountryCode: "private", Cidr: []*routercommon.CIDR{{Ip: []byte{127, 0, 0, 0}, Prefix: 8}}}},
                TargetTag:   &router.RoutingRule_Tag{Tag: "out"},
            },
            {
                UserEmail: []string{"example@v2fly.org"},
                TargetTag: &router.RoutingRule_Tag{Tag: "out"},
            },
            {
                Networks:  []net.Network{net.Network_UDP, net.Network_TCP},
                TargetTag: &router.RoutingRule_Tag{Tag: "out"},
            },
        },
    }, mocks.NewDNSClient(mockCtl), mocks.NewOutboundManager(mockCtl), nil))
 
    lis := bufconn.Listen(1024 * 1024)
    bufDialer := func(context.Context, string) (net.Conn, error) {
        return lis.Dial()
    }
 
    errCh := make(chan error)
 
    // Server goroutine
    go func() {
        server := grpc.NewServer()
        RegisterRoutingServiceServer(server, NewRoutingServer(r, c))
        errCh <- server.Serve(lis)
    }()
 
    // Client goroutine
    go func() {
        defer lis.Close()
        conn, err := grpc.DialContext(context.Background(), "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
        if err != nil {
            errCh <- err
        }
        defer conn.Close()
        client := NewRoutingServiceClient(conn)
 
        testCases := []*RoutingContext{
            {InboundTag: "in", OutboundTag: "out"},
            {TargetIPs: [][]byte{{1, 2, 3, 4}}, TargetPort: 8080, OutboundTag: "out"},
            {TargetDomain: "example.com", TargetPort: 443, OutboundTag: "out"},
            {SourcePort: 9999, TargetPort: 9999, OutboundTag: "out"},
            {Network: net.Network_UDP, Protocol: "bittorrent", OutboundTag: "blocked"},
            {User: "example@v2fly.org", OutboundTag: "out"},
            {SourceIPs: [][]byte{{127, 0, 0, 1}}, Attributes: map[string]string{"attr": "value"}, OutboundTag: "out"},
        }
 
        // Test simple TestRoute
        testSimple := func() error {
            for _, tc := range testCases {
                route, err := client.TestRoute(context.Background(), &TestRouteRequest{RoutingContext: tc})
                if err != nil {
                    return err
                }
                if r := cmp.Diff(route, tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
                    t.Error(r)
                }
            }
            return nil
        }
 
        // Test TestRoute with special options
        testOptions := func() error {
            sub, err := c.Subscribe()
            if err != nil {
                return err
            }
            for _, tc := range testCases {
                route, err := client.TestRoute(context.Background(), &TestRouteRequest{
                    RoutingContext: tc,
                    FieldSelectors: []string{"ip", "port", "domain", "outbound"},
                    PublishResult:  true,
                })
                if err != nil {
                    return err
                }
                stat := &RoutingContext{ // Only a subset of stats is retrieved
                    SourceIPs:         tc.SourceIPs,
                    TargetIPs:         tc.TargetIPs,
                    SourcePort:        tc.SourcePort,
                    TargetPort:        tc.TargetPort,
                    TargetDomain:      tc.TargetDomain,
                    OutboundGroupTags: tc.OutboundGroupTags,
                    OutboundTag:       tc.OutboundTag,
                }
                if r := cmp.Diff(route, stat, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
                    t.Error(r)
                }
                select { // Check that routing result has been published to statistics channel
                case msg, received := <-sub:
                    if route, ok := msg.(routing.Route); received && ok {
                        if r := cmp.Diff(AsProtobufMessage(nil)(route), tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
                            t.Error(r)
                        }
                    } else {
                        t.Error("unexpected failure in receiving published routing result for testcase", tc)
                    }
                case <-time.After(100 * time.Millisecond):
                    t.Error("unexpected failure in receiving published routing result", tc)
                }
            }
            return nil
        }
 
        if err := testSimple(); err != nil {
            errCh <- err
        }
        if err := testOptions(); err != nil {
            errCh <- err
        }
        errCh <- nil // Client passed all tests successfully
    }()
 
    // Wait for goroutines to complete
    select {
    case <-time.After(2 * time.Second):
        t.Fatal("Test timeout after 2s")
    case err := <-errCh:
        if err != nil {
            t.Fatal(err)
        }
    }
}