0
# Utilities and Global Settings
1
2
Comprehensive utility functions and global system settings for V2ray/Xray management. Provides network operations, validation functions, color output, certificate generation, BitTorrent blocking, scheduled updates, and system configuration management.
3
4
## Capabilities
5
6
### Color Output Utilities
7
8
Terminal color formatting for enhanced user interface and status indication.
9
10
```python { .api }
11
class ColorStr:
12
"""Terminal color string utilities for formatted output"""
13
14
RED = '\033[31m'
15
GREEN = '\033[32m'
16
YELLOW = '\033[33m'
17
BLUE = '\033[34m'
18
FUCHSIA = '\033[35m'
19
CYAN = '\033[36m'
20
WHITE = '\033[37m'
21
RESET = '\033[0m'
22
23
@classmethod
24
def red(cls, s):
25
"""
26
Apply red color to string.
27
28
Parameters:
29
- s (str): String to colorize
30
31
Returns:
32
str: Red-colored string with reset
33
"""
34
35
@classmethod
36
def green(cls, s):
37
"""Apply green color (success messages)"""
38
39
@classmethod
40
def yellow(cls, s):
41
"""Apply yellow color (warning messages)"""
42
43
@classmethod
44
def blue(cls, s):
45
"""Apply blue color (information messages)"""
46
47
@classmethod
48
def cyan(cls, s):
49
"""Apply cyan color (headers and titles)"""
50
51
@classmethod
52
def fuchsia(cls, s):
53
"""Apply fuchsia/magenta color"""
54
```
55
56
### Network Utilities
57
58
Network-related utility functions for IP detection, port management, and connectivity.
59
60
```python { .api }
61
def get_ip():
62
"""
63
Get server's public IP address.
64
65
Returns:
66
str: Public IPv4 address of the server
67
68
Uses multiple IP detection services for reliability.
69
"""
70
71
def port_is_use(port):
72
"""
73
Check if a port is currently in use.
74
75
Parameters:
76
- port (int): Port number to check
77
78
Returns:
79
bool: True if port is in use, False if available
80
"""
81
82
def random_port(start_port, end_port):
83
"""
84
Generate random port within specified range.
85
86
Parameters:
87
- start_port (int): Range start (inclusive)
88
- end_port (int): Range end (inclusive)
89
90
Returns:
91
int: Random port number within range
92
"""
93
94
def all_port():
95
"""
96
Get list of all configured proxy ports.
97
98
Returns:
99
list: All ports currently configured for V2ray/Xray
100
"""
101
102
def open_port(openport=-1):
103
"""
104
Open port(s) in system firewall.
105
106
Parameters:
107
- openport (int, optional): Specific port to open.
108
If -1, opens all configured ports.
109
110
Handles both iptables and ufw firewall management.
111
"""
112
```
113
114
### Validation Functions
115
116
Input validation and data verification utilities.
117
118
```python { .api }
119
def is_email(email):
120
"""
121
Validate email address format.
122
123
Parameters:
124
- email (str): Email address to validate
125
126
Returns:
127
bool: True if valid email format
128
"""
129
130
def is_ipv4(ip):
131
"""
132
Validate IPv4 address format.
133
134
Parameters:
135
- ip (str): IP address string
136
137
Returns:
138
bool: True if valid IPv4 address
139
"""
140
141
def is_ipv6(ip):
142
"""
143
Validate IPv6 address format.
144
145
Parameters:
146
- ip (str): IPv6 address string
147
148
Returns:
149
bool: True if valid IPv6 address
150
"""
151
152
def check_ip(ip):
153
"""
154
Check if IP address is valid (IPv4 or IPv6).
155
156
Parameters:
157
- ip (str): IP address to check
158
159
Returns:
160
bool: True if valid IP address
161
"""
162
```
163
164
### Cryptographic Utilities
165
166
Certificate generation and cryptographic key management.
167
168
```python { .api }
169
def gen_cert(domain, cert_type, email=""):
170
"""
171
Generate SSL certificates for TLS configuration.
172
173
Parameters:
174
- domain (str): Domain name for certificate
175
- cert_type (str): Certificate type ('self', 'letsencrypt', 'custom')
176
- email (str, optional): Email for Let's Encrypt registration
177
178
Returns:
179
tuple: (certificate_path, private_key_path)
180
181
Supports self-signed certificates and Let's Encrypt ACME.
182
"""
183
184
def x25519_key(private_key=None):
185
"""
186
Generate X25519 key pair for VLESS Reality.
187
188
Parameters:
189
- private_key (str, optional): Existing private key to derive public key
190
191
Returns:
192
tuple: (private_key, public_key) in base64 format
193
"""
194
```
195
196
### User Interface Utilities
197
198
Interactive input and user interface helper functions.
199
200
```python { .api }
201
def loop_input_choice_number(input_tip, length):
202
"""
203
Interactive number choice input with validation.
204
205
Parameters:
206
- input_tip (str): Prompt message for user
207
- length (int): Maximum valid choice number
208
209
Returns:
210
int: User's validated choice (1 to length)
211
212
Loops until valid input is provided.
213
"""
214
215
def readchar(prompt=""):
216
"""
217
Read single character input without Enter.
218
219
Parameters:
220
- prompt (str, optional): Prompt message
221
222
Returns:
223
str: Single character pressed by user
224
"""
225
226
def random_email():
227
"""
228
Generate random email address for testing.
229
230
Returns:
231
str: Random email in format user@domain.com
232
"""
233
```
234
235
### Data Formatting
236
237
Data conversion and formatting utilities.
238
239
```python { .api }
240
def bytes_2_human_readable(number_of_bytes, precision=1):
241
"""
242
Convert bytes to human-readable format.
243
244
Parameters:
245
- number_of_bytes (int): Raw byte count
246
- precision (int): Decimal places for display
247
248
Returns:
249
str: Formatted string (e.g., "1.5 GB", "256.7 MB", "42.3 KB")
250
251
Supports bytes, KB, MB, GB, TB, PB units.
252
"""
253
```
254
255
## Global Settings Management
256
257
### Configuration Management
258
259
```python { .api }
260
class Config:
261
"""Global configuration management"""
262
263
def __init__(self):
264
"""Initialize configuration manager"""
265
266
def get_data(self, key):
267
"""
268
Retrieve configuration value.
269
270
Parameters:
271
- key (str): Configuration key
272
273
Returns:
274
Any: Configuration value for the key
275
"""
276
277
def set_data(self, key, value):
278
"""
279
Set configuration value.
280
281
Parameters:
282
- key (str): Configuration key
283
- value (Any): Value to store
284
"""
285
286
def get_path(self, key):
287
"""
288
Get configuration file path.
289
290
Parameters:
291
- key (str): Path key ('config_path', etc.)
292
293
Returns:
294
str: File path for the specified key
295
"""
296
```
297
298
### BitTorrent Blocking
299
300
```python { .api }
301
def manage():
302
"""
303
Manage BitTorrent traffic blocking.
304
305
Interactive menu for:
306
- Enable/disable BT blocking via iptables
307
- Configure DPI-based protocol detection
308
- Whitelist/blacklist specific BT clients
309
"""
310
```
311
312
### Scheduled Updates
313
314
```python { .api }
315
def restartCron():
316
"""
317
Restart cron service for scheduled tasks.
318
319
Ensures cron daemon is running for automatic updates.
320
"""
321
322
def planUpdate():
323
"""
324
Configure scheduled V2ray updates.
325
326
Interactive setup for:
327
- Update frequency (daily, weekly, monthly)
328
- Update time preferences
329
- Automatic restart options
330
- Backup before update
331
"""
332
333
def manage():
334
"""
335
Manage scheduled update system.
336
337
Provides interface for configuring, enabling,
338
disabling, and monitoring automatic updates.
339
"""
340
```
341
342
### Firewall Management
343
344
```python { .api }
345
def iptables_open(iptable_way, port):
346
"""
347
Open port using specific iptables method.
348
349
Parameters:
350
- iptable_way (str): Firewall method ('iptables', 'ufw', 'firewalld')
351
- port (int): Port number to open
352
353
Handles different Linux firewall systems.
354
"""
355
356
def clean_iptables(port):
357
"""
358
Clean iptables rules for specified port.
359
360
Parameters:
361
- port (int): Port number to clean rules for
362
363
Removes all iptables rules related to the specified port,
364
including traffic accounting and forwarding rules.
365
"""
366
```
367
368
## Enumeration Types
369
370
```python { .api }
371
class StreamType(Enum):
372
"""Transport protocol enumeration"""
373
TCP = 'tcp'
374
TCP_HTTP = 'tcp_http'
375
WS = 'ws'
376
H2 = 'h2'
377
MKCP = 'mkcp'
378
QUIC = 'quic'
379
SOCKS = 'socks'
380
MTPROTO = 'mtproto'
381
SHADOWSOCKS = 'shadowsocks'
382
VLESS_TCP = 'vless_tcp'
383
VLESS_TLS = 'vless_tls'
384
VLESS_WS = 'vless_ws'
385
VLESS_REALITY = 'vless_reality'
386
TROJAN = 'trojan'
387
```
388
389
## Configuration Options
390
391
### Available Configuration Methods
392
393
```python { .api }
394
def header_type_list():
395
"""
396
Get list of available mKCP header masquerading types.
397
398
Returns:
399
list: ['none', 'srtp', 'utp', 'wechat-video', 'dtls', 'wireguard']
400
"""
401
402
def ss_method():
403
"""
404
Get list of supported Shadowsocks encryption methods.
405
406
Returns:
407
list: Available encryption methods for Shadowsocks
408
"""
409
410
def xtls_flow():
411
"""
412
Get list of supported XTLS flow control methods.
413
414
Returns:
415
list: Available XTLS flow types for VLESS
416
"""
417
```
418
419
## Usage Examples
420
421
### Color Output
422
423
```python
424
from v2ray_util.util_core.utils import ColorStr
425
426
print(ColorStr.green("Service started successfully"))
427
print(ColorStr.red("Error: Configuration invalid"))
428
print(ColorStr.yellow("Warning: Port already in use"))
429
print(ColorStr.cyan("V2ray Manager v3.11.4"))
430
```
431
432
### Network Operations
433
434
```python
435
from v2ray_util.util_core.utils import get_ip, port_is_use, random_port, open_port
436
437
# Get server IP
438
server_ip = get_ip()
439
print(f"Server IP: {server_ip}")
440
441
# Check port availability
442
if not port_is_use(8080):
443
print("Port 8080 is available")
444
445
# Generate random port
446
port = random_port(10000, 65535)
447
print(f"Random port: {port}")
448
449
# Open ports in firewall
450
open_port(8080) # Open specific port
451
open_port() # Open all configured ports
452
```
453
454
### Validation
455
456
```python
457
from v2ray_util.util_core.utils import is_email, is_ipv4, check_ip
458
459
# Validate email
460
if is_email("user@example.com"):
461
print("Valid email")
462
463
# Validate IP addresses
464
if is_ipv4("192.168.1.1"):
465
print("Valid IPv4")
466
467
if check_ip("2001:db8::1"):
468
print("Valid IP address")
469
```
470
471
### Certificate Generation
472
473
```python
474
from v2ray_util.util_core.utils import gen_cert, x25519_key
475
476
# Generate self-signed certificate
477
cert_path, key_path = gen_cert("example.com", "self")
478
479
# Generate Let's Encrypt certificate
480
cert_path, key_path = gen_cert("example.com", "letsencrypt", "admin@example.com")
481
482
# Generate X25519 keys
483
private_key, public_key = x25519_key()
484
```
485
486
### Configuration Management
487
488
```python
489
from v2ray_util.util_core.config import Config
490
491
config = Config()
492
493
# Get current language
494
lang = config.get_data('lang')
495
496
# Set language to English
497
config.set_data('lang', 'en')
498
```
499
500
### Global Settings
501
502
```python
503
from v2ray_util.global_setting import ban_bt, update_timer
504
505
# Manage BitTorrent blocking
506
ban_bt.manage()
507
508
# Configure scheduled updates
509
update_timer.manage()
510
```
511
512
## Error Handling
513
514
Utility functions handle common error conditions:
515
- Network connectivity issues
516
- Permission denied errors
517
- Invalid input validation
518
- Certificate generation failures
519
- Firewall configuration errors
520
521
All functions provide appropriate error messages and fallback mechanisms to maintain system stability.