-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttplib.py
More file actions
2089 lines (1744 loc) · 73.1 KB
/
httplib.py
File metadata and controls
2089 lines (1744 loc) · 73.1 KB
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import Protocol, Callable, Any, NoReturn, TypeVar, Awaitable, Union, overload
from traceback import format_exc
from functools import wraps
import threading
import asyncio
import hashlib
import socket
import base64
import json
import time
import hmac
import os
s = socket.socket()
# Type variable for the decorated function
F = TypeVar('F', bound=Callable[..., Awaitable[Any]])
class RouteHandler(Protocol):
async def __call__(self, *args: Any, **kwargs: Any) -> str | bytes | tuple[int, str | bytes] | None | NoReturn: ...
class ErrorHandler(Protocol):
async def __call__(self, *args: Any, **kwargs: Any) -> str | bytes | tuple[int, str | bytes]: ...
## Routing ##
routes: list[tuple[str, str, RouteHandler]] = []
errors: dict[int | None, ErrorHandler] = {}
## Websockets ##
ws_connections: dict[str, list[socket.socket]] = {}
## Logins ##
users: dict[str, bytes] = {}
profiles: dict[str, dict[str, Any]] = {}
sessions: dict[str, dict[str, Any]] = {}
## Rate limiting ##
# WebSocket rate limiting
ws_rate_limit_delays: dict[tuple[socket.socket, str], float] = {}
ws_rate_limit_counts: dict[tuple[socket.socket, str], list[float]] = {}
# HTTP rate limiting
rate_limit_delays: dict[tuple[str, str], float] = {}
rate_limit_counts: dict[tuple[str, str], list[float]] = {}
rate_limit_lock = threading.Lock()
## DOS Protection ##
# Global IP-based DOS protection
dos_ip_requests: dict[str, list[float]] = {} # IP -> list of request timestamps
dos_blocked_ips: dict[str, float] = {} # IP -> block expiry time
dos_lock = threading.Lock()
# DOS protection configuration
DOS_WINDOW_SIZE = 1 # seconds
DOS_MAX_REQUESTS = 100 # max requests per window per IP
DOS_BLOCK_DURATION = 3 # seconds to block IP after DOS detection
DOS_WEBSOCKET_MAX_CONNECTIONS = 100 # max WebSocket connections per IP
# WebSocket-specific DOS protection
ws_dos_violations: dict[socket.socket, int] = {} # socket -> violation count
ws_last_message: dict[socket.socket, float] = {} # socket -> last message time
ws_messages_per_second: dict[socket.socket, tuple[float, int]] = {} # socket -> (second_start, count)
ws_dos_lock = threading.Lock()
# WebSocket DOS protection configuration
DOS_WS_MAX_MESSAGES_PER_SECOND = 100 # max WebSocket messages per second
DOS_WS_MIN_MESSAGE_INTERVAL = 0.001 # minimum seconds between messages (1ms)
DOS_WS_MAX_VIOLATIONS = 3 # max violations before disconnection
# Simple log function with log levels
LOG_LEVELS = {"DEBUG": 10, "INFO": 20, "WARNING": 30, "ERROR": 40, "CRITICAL": 50}
log_level = LOG_LEVELS['INFO']
# Refined log level colors (bold, specific colors)
LOG_LEVEL_COLORS = {
"DEBUG": "\033[90;1m", # Bold gray
"INFO": "\033[94;1m", # Bold blue
"WARNING": "\033[93;1m", # Bold yellow
"ERROR": "\033[91;1m", # Bold red
"CRITICAL": "\033[41;97;1m" # Bold white on dark red bg
}
RESET_COLOR = "\033[0m"
# HTTP method colors for log_request
METHOD_COLORS = {
'GET': '\033[92m', # Green
'POST': '\033[96m', # Cyan
'PUT': '\033[95m', # Magenta
'DELETE': '\033[91m', # Red
'PATCH': '\033[93m', # Yellow
'OPTIONS': '\033[90m', # Gray
}
def log(message: str, level: str = "INFO") -> None:
"""
Log a message with a specified level and timestamp.
Supports colored output for different log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
Messages are only printed if their level meets the current log level threshold.
Args:
message: The message to log
level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL). Defaults to INFO.
Example:
```python
log("Server starting", "INFO")
log("User authentication failed", "WARNING")
log("Database connection error", "ERROR")
```
"""
level = level.upper()
if level not in LOG_LEVELS:
level = "INFO"
if LOG_LEVELS[level] >= log_level:
from datetime import datetime
ts = datetime.now().strftime('%H:%M:%S')
color = LOG_LEVEL_COLORS.get(level, "")
# Timestamp is plain, log level is bold and colored
print(f"[{ts}] {color}{level:>8}{RESET_COLOR}: {message}")
def log_request(method: str, path: str, status: int | None = None) -> None:
"""
Log HTTP requests with colored method names.
Automatically formats and logs HTTP requests with colored method names for better readability.
Each HTTP method has its own color (GET=green, POST=cyan, etc.).
Args:
method: HTTP method (GET, POST, PUT, DELETE, etc.)
path: Request path
status: Optional HTTP status code to include in the log
Example:
```python
log_request("GET", "/api/users")
log_request("POST", "/login", 200)
```
"""
method = method.upper()
color = METHOD_COLORS.get(method, '')
reset = RESET_COLOR if color else ''
status_str = f" {status}" if status is not None else ""
log(f"{color}{method}{reset} {path}{status_str}", "INFO")
# Request context
class Request:
def __init__(self):
self.headers: dict[str, str] = {}
self.params: dict[str, str] = {}
self.cookies: dict[str, str] = {}
self.path: str = ''
self.method: str = ''
self.body: str = ''
self.client_ip: str = ''
# Response context for managing cookies
class Response:
def __init__(self):
self.cookies: dict[str, dict[str, str]] = {} # cookie_name -> {value, path, domain, expires, etc}
def set_cookie(self, name: str, value: str, path: str = '/', domain: str = '',
expires: str = '', max_age: int = 0, secure: bool = False,
httponly: bool = False, samesite: str = ''):
"""Set a cookie with optional attributes"""
cookie_attrs = {'value': value}
if path: cookie_attrs['path'] = path
if domain: cookie_attrs['domain'] = domain
if expires: cookie_attrs['expires'] = expires
if max_age > 0: cookie_attrs['max_age'] = str(max_age)
if secure: cookie_attrs['secure'] = 'true'
if httponly: cookie_attrs['httponly'] = 'true'
if samesite: cookie_attrs['samesite'] = samesite
self.cookies[name] = cookie_attrs
def delete_cookie(self, name: str, path: str = '/'):
"""Delete a cookie by setting it to expire in the past"""
self.set_cookie(name, '', path=path, expires='Thu, 01 Jan 1970 00:00:00 GMT')
def get_cookie_headers(self) -> list[str]:
"""Generate Set-Cookie headers for all cookies"""
headers: list[str] = []
for name, attrs in self.cookies.items():
cookie_header = f"{name}={attrs['value']}"
for attr_name, attr_value in attrs.items():
if attr_name == 'value':
continue
elif attr_name in ['secure', 'httponly']:
if attr_value == 'true':
cookie_header += f"; {attr_name.replace('httponly', 'HttpOnly').replace('secure', 'Secure')}"
elif attr_name == 'max_age':
cookie_header += f"; Max-Age={attr_value}"
elif attr_name == 'samesite':
cookie_header += f"; SameSite={attr_value}"
else:
cookie_header += f"; {attr_name.capitalize()}={attr_value}"
headers.append(cookie_header)
return headers
# Use thread-local storage for safety with threads
_request_ctx = threading.local()
_response_ctx = threading.local()
def _get_request() -> Request:
if not hasattr(_request_ctx, 'request'):
_request_ctx.request = Request()
return _request_ctx.request
def _get_response() -> Response:
if not hasattr(_response_ctx, 'response'):
_response_ctx.response = Response()
return _response_ctx.response
# Flask-like global request and response objects
request = _get_request()
response = _get_response()
# Helpers
async def _normalize_path(path: str) -> str:
# Remove query string if present
path = path.split('?', 1)[0]
# Default to index.html for root
if path in ('', '/'):
path = '/index.html'
# Prevent directory traversal
path = os.path.normpath(path).replace('\\', '/')
if '..' in path or path.startswith('../') or path.startswith('/..'):
path = '/index.html'
# Ensure path starts with /static unless already present
if not path.removeprefix('/').startswith('static/'):
# Remove leading slash to avoid double slash
path = '/static' + (path if path.startswith('/') else f'/{path}')
# Ensure .html extension
if '.' not in path:
path += '.html'
return path.removeprefix('/')
# Parsers
async def _parse_headers(headers: str) -> dict[str, str]:
header_dict: dict[str, str] = {}
for line in headers.split('\n'):
line = line.strip()
if line:
key, value = line.split(':', 1)
header_dict[key.strip()] = value.strip()
return header_dict
async def _parse_params(query: str) -> dict[str,str]:
params:dict[str,str] = {}
if query:
for param in query.split('&'):
key, value = param.split('=', 1)
params[key] = value
return params
async def _parse_cookies(cookie_header: str) -> dict[str, str]:
"""Parse cookies from Cookie header"""
cookies: dict[str, str] = {}
if not cookie_header:
return cookies
# Split cookies by semicolon and parse each one
for cookie in cookie_header.split(';'):
cookie = cookie.strip()
if '=' in cookie:
name, value = cookie.split('=', 1)
cookies[name.strip()] = value.strip()
return cookies
# Urlencode
async def url_decode(value: str) -> str:
"""
Decode a URL-encoded string.
Converts percent-encoded characters (%20, %21, etc.) back to their original characters.
Also converts '+' characters to spaces (common in form data).
Args:
value: URL-encoded string to decode
Returns:
Decoded string
Example:
```python
decoded = await url_decode("Hello%20World%21") # "Hello World!"
form_data = await url_decode("first+name") # "first name"
```
"""
# Replace + with space (optional, for form data)
value = value.replace('+', ' ')
# Find all percent-encoded bytes
bytes_list = bytearray()
i = 0
while i < len(value):
if value[i] == '%' and i + 2 < len(value):
bytes_list.append(int(value[i+1:i+3], 16))
i += 3
else:
bytes_list.append(ord(value[i]))
i += 1
return bytes_list.decode('utf-8')
async def url_encode(value: str) -> str:
"""
Encode a string for safe use in URLs.
Converts special characters to percent-encoded format (%20, %21, etc.).
Alphanumeric characters and -_.~ are left unchanged as they're safe.
Args:
value: String to encode
Returns:
URL-encoded string
Example:
```python
encoded = await url_encode("Hello World!") # "Hello%20World%21"
safe_param = await url_encode("user@domain.com") # "user%40domain.com"
```
"""
encoded:list[str] = []
for char in value:
if char.isalnum() or char in '-_.~':
encoded.append(char)
else:
encoded.append(f'%{ord(char):02X}')
return ''.join(encoded)
async def get_error_shorthand(err_code: int) -> str:
"""
Get the standard HTTP status text for a given status code.
Returns the official HTTP status message for common status codes (200 OK, 404 Not Found, etc.).
Args:
err_code: HTTP status code
Returns:
Status text string, or 'Unknown Error' for unrecognized codes
Example:
```python
text = await get_error_shorthand(200) # "OK"
text = await get_error_shorthand(404) # "Not Found"
text = await get_error_shorthand(500) # "Internal Server Error"
```
"""
shorthand = {
100: 'Continue',
101: 'Switching Protocols',
102: 'Processing',
103: 'Early Hints',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
207: 'Multi-Status',
208: 'Already Reported',
226: 'IM Used',
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
307: 'Temporary Redirect',
308: 'Permanent Redirect',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Payload Too Large',
414: 'URI Too Long',
415: 'Unsupported Media Type',
416: 'Range Not Satisfiable',
417: 'Expectation Failed',
418: "I'm a teapot",
421: 'Misdirected Request',
422: 'Unprocessable Entity',
423: 'Locked',
424: 'Failed Dependency',
425: 'Too Early',
426: 'Upgrade Required',
428: 'Precondition Required',
429: 'Too Many Requests',
431: 'Request Header Fields Too Large',
451: 'Unavailable For Legal Reasons',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
506: 'Variant Also Negotiates',
507: 'Insufficient Storage',
508: 'Loop Detected',
510: 'Not Extended',
511: 'Network Authentication Required'
}
return shorthand.get(err_code, 'Unknown Error')
async def get_content_type(path: str) -> str:
"""
Determine the MIME content type based on file extension.
Returns the appropriate Content-Type header value for common file extensions.
Args:
path: File path or filename
Returns:
MIME type string (e.g., 'text/html', 'application/json')
Example:
```python
content_type = await get_content_type("index.html") # "text/html"
content_type = await get_content_type("api.json") # "application/json"
content_type = await get_content_type("style.css") # "text/css"
```
"""
if path.endswith('.html'):
return 'text/html'
elif path.endswith('.css'):
return 'text/css'
elif path.endswith('.js'):
return 'application/javascript'
elif path.endswith('.png'):
return 'image/png'
elif path.endswith('.jpg') or path.endswith('.jpeg'):
return 'image/jpeg'
elif path.endswith('.gif'):
return 'image/gif'
elif path.endswith('.svg'):
return 'image/svg+xml'
elif path.endswith('.json'):
return 'application/json'
elif path.endswith('.txt'):
return 'text/plain'
elif path.endswith('.xml'):
return 'application/xml'
else:
return 'text/plain'
def get_client_ip() -> str:
"""
Extract the client IP address from the current request context.
Attempts to get the real client IP by checking multiple sources in order:
1. Direct client IP from socket connection
2. X-Forwarded-For header (for proxy scenarios)
3. X-Real-IP header
4. Falls back to 'unknown' if none available
Returns:
Client IP address as string, or 'unknown' if unavailable
Example:
```python
@route('/api/user-info')
async def user_info():
client_ip = get_client_ip()
return f"Your IP is: {client_ip}"
```
"""
try:
req = _get_request()
# First check if we have the actual client IP from the socket
if req.client_ip:
return req.client_ip
# Try to get from X-Forwarded-For header
forwarded = req.headers.get('X-Forwarded-For', '')
if forwarded:
return forwarded.split(',')[0].strip()
# Try X-Real-IP
real_ip = req.headers.get('X-Real-IP', '')
if real_ip:
return real_ip
# Fallback to a default
return 'unknown'
except Exception:
return 'unknown'
def is_ip_blocked(ip: str) -> bool:
"""
Check if an IP address is currently blocked due to DOS protection.
Args:
ip: IP address to check
Returns:
True if IP is blocked, False otherwise
"""
if ip == 'unknown':
return False
current_time = time.time()
with dos_lock:
# Clean up expired blocks
expired_ips = [blocked_ip for blocked_ip, expiry in dos_blocked_ips.items()
if current_time > expiry]
for blocked_ip in expired_ips:
del dos_blocked_ips[blocked_ip]
log(f"Unblocked IP {blocked_ip} (block expired)", "INFO")
# Check if IP is currently blocked
if ip in dos_blocked_ips:
remaining_time = dos_blocked_ips[ip] - current_time
log(f"Blocked IP {ip} attempted request (blocked for {remaining_time:.1f}s more)", "WARNING")
return True
return False
def check_dos_protection(ip: str) -> bool:
"""
Check if an IP should be blocked for DOS protection.
Args:
ip: IP address to check
Returns:
True if IP should be blocked, False if allowed
"""
if ip == 'unknown':
return False
current_time = time.time()
with dos_lock:
# Initialize request history for new IPs
if ip not in dos_ip_requests:
dos_ip_requests[ip] = []
# Clean old requests outside the window
window_start = current_time - DOS_WINDOW_SIZE
dos_ip_requests[ip] = [req_time for req_time in dos_ip_requests[ip]
if req_time > window_start]
# Add current request
dos_ip_requests[ip].append(current_time)
# Check if DOS threshold exceeded
if len(dos_ip_requests[ip]) > DOS_MAX_REQUESTS:
# Block the IP
dos_blocked_ips[ip] = current_time + DOS_BLOCK_DURATION
log(f"DOS protection activated: blocked IP {ip} for {DOS_BLOCK_DURATION}s ({len(dos_ip_requests[ip])} requests in {DOS_WINDOW_SIZE}s)", "ERROR")
# Clear request history to prevent memory bloat
dos_ip_requests[ip] = []
return True
return False
def count_websocket_connections(ip: str) -> int:
"""
Count active WebSocket connections for an IP address.
Args:
ip: IP address to count connections for
Returns:
Number of active WebSocket connections for this IP
"""
count = 0
for route_connections in ws_connections.values():
for sock in route_connections:
try:
peer_addr = sock.getpeername()
if peer_addr and peer_addr[0] == ip:
count += 1
except Exception:
# Socket might be closed, ignore
pass
return count
def unblock_ip(ip: str) -> bool:
"""
Manually unblock an IP address.
Args:
ip: IP address to unblock
Returns:
True if IP was blocked and is now unblocked, False if IP wasn't blocked
"""
with dos_lock:
if ip in dos_blocked_ips:
del dos_blocked_ips[ip]
log(f"Manually unblocked IP {ip}", "INFO")
return True
return False
def get_blocked_ips() -> dict[str, float]:
"""
Get all currently blocked IPs and their unblock times.
Returns:
Dictionary mapping IP addresses to their unblock timestamps
"""
current_time = time.time()
with dos_lock:
# Clean up expired blocks first
expired_ips = [blocked_ip for blocked_ip, expiry in dos_blocked_ips.items()
if current_time > expiry]
for blocked_ip in expired_ips:
del dos_blocked_ips[blocked_ip]
# Return copy of current blocked IPs
return dos_blocked_ips.copy()
def get_dos_stats() -> dict[str, Any]:
"""
Get DOS protection statistics.
Returns:
Dictionary with DOS protection statistics
"""
current_time = time.time()
with dos_lock:
# Clean up old request history
total_tracked_ips = len(dos_ip_requests)
active_requests = 0
for requests in dos_ip_requests.values():
# Count recent requests (within window)
recent_requests = [req_time for req_time in requests
if current_time - req_time < DOS_WINDOW_SIZE]
active_requests += len(recent_requests)
blocked_count = len(dos_blocked_ips)
# Count total WebSocket connections
total_ws_connections = sum(len(conns) for conns in ws_connections.values())
# WebSocket DOS stats
with ws_dos_lock:
ws_tracked_sockets = len(ws_dos_violations)
ws_total_violations = sum(ws_dos_violations.values())
return {
'tracked_ips': total_tracked_ips,
'active_requests_in_window': active_requests,
'blocked_ips': blocked_count,
'total_websocket_connections': total_ws_connections,
'ws_tracked_sockets': ws_tracked_sockets,
'ws_total_violations': ws_total_violations,
'window_size_seconds': DOS_WINDOW_SIZE,
'max_requests_per_window': DOS_MAX_REQUESTS,
'block_duration_seconds': DOS_BLOCK_DURATION,
'max_websocket_connections_per_ip': DOS_WEBSOCKET_MAX_CONNECTIONS,
'ws_max_messages_per_second': DOS_WS_MAX_MESSAGES_PER_SECOND,
'ws_min_message_interval': DOS_WS_MIN_MESSAGE_INTERVAL,
'ws_max_violations': DOS_WS_MAX_VIOLATIONS
}
def _cleanup_websocket_dos_tracking(sock: socket.socket):
"""Clean up DOS tracking for a closed WebSocket."""
with ws_dos_lock:
if sock in ws_dos_violations:
del ws_dos_violations[sock]
if sock in ws_last_message:
del ws_last_message[sock]
if sock in ws_messages_per_second:
del ws_messages_per_second[sock]
def _check_websocket_dos_protection(sock: socket.socket) -> bool:
"""
Check WebSocket DOS protection for a specific socket.
Args:
sock: WebSocket socket to check
Returns:
True if should disconnect due to DOS protection, False if allowed
"""
current_time = time.time()
# Get client IP for additional blocking
try:
client_addr = sock.getpeername()
client_ip = client_addr[0] if client_addr else 'unknown'
except Exception:
client_ip = 'unknown'
# Check if IP is globally blocked
if is_ip_blocked(client_ip):
log(f"WebSocket message blocked: IP {client_ip} is globally blocked", "WARNING")
return True
with ws_dos_lock:
# Initialize tracking for new sockets
if sock not in ws_dos_violations:
ws_dos_violations[sock] = 0
if sock not in ws_last_message:
ws_last_message[sock] = 0.0
if sock not in ws_messages_per_second:
ws_messages_per_second[sock] = (current_time, 0)
# Check message frequency (messages per second)
second_start, message_count = ws_messages_per_second[sock]
if current_time - second_start >= 1.0:
# Reset counter every second
ws_messages_per_second[sock] = (current_time, 1)
else:
# Increment message count
message_count += 1
ws_messages_per_second[sock] = (second_start, message_count)
# Check if exceeding messages per second limit
if message_count > DOS_WS_MAX_MESSAGES_PER_SECOND:
ws_dos_violations[sock] += 1
log(f"WebSocket DOS: {client_ip} exceeded {DOS_WS_MAX_MESSAGES_PER_SECOND} messages/second (violation #{ws_dos_violations[sock]})", "WARNING")
if ws_dos_violations[sock] >= DOS_WS_MAX_VIOLATIONS:
log(f"WebSocket DOS: disconnecting {client_ip} after {ws_dos_violations[sock]} violations", "ERROR")
# Also trigger IP-level DOS protection
check_dos_protection(client_ip)
return True
return False # Just warn, don't disconnect yet
# Check minimum interval between messages
last_time = ws_last_message[sock]
if last_time > 0 and (current_time - last_time) < DOS_WS_MIN_MESSAGE_INTERVAL:
ws_dos_violations[sock] += 1
log(f"WebSocket DOS: {client_ip} messages too frequent, {current_time - last_time:.3f}s interval (violation #{ws_dos_violations[sock]})", "WARNING")
if ws_dos_violations[sock] >= DOS_WS_MAX_VIOLATIONS:
log(f"WebSocket DOS: disconnecting {client_ip} for rapid-fire messages", "ERROR")
check_dos_protection(client_ip)
return True
return False # Just warn, don't disconnect yet
# Update last message time
ws_last_message[sock] = current_time
# Reduce violation count on good behavior (every 10 good messages)
if ws_dos_violations[sock] > 0 and message_count <= 3 and int(current_time) % 10 == 0:
ws_dos_violations[sock] = max(0, ws_dos_violations[sock] - 1)
return False # Allow message
# Handlers
async def _handle_request(method: str, path: str, version: str, raw_headers: str, body: str = '', client_ip: str = '') -> bytes:
if version != 'HTTP/1.1':
return b'HTTP/1.1 505 HTTP Version Not Supported\r\n\r\n'
# DOS Protection - check if IP is blocked
if is_ip_blocked(client_ip):
return b'HTTP/1.1 429 Too Many Requests\r\nContent-Type: text/plain\r\n\r\nIP temporarily blocked due to suspicious activity'
# DOS Protection - check for abuse
if check_dos_protection(client_ip):
return b'HTTP/1.1 429 Too Many Requests\r\nContent-Type: text/plain\r\n\r\nToo many requests - IP blocked temporarily'
path, params = path.split('?', 1) if '?' in path else (path, '')
path = await url_decode(path)
headers = await _parse_headers(raw_headers)
params = await _parse_params(params)
# Update request context
req = _get_request()
req.headers = headers
req.params = params
req.cookies = await _parse_cookies(headers.get('Cookie', ''))
req.path = path
req.method = method.upper()
req.body = body
req.client_ip = client_ip
# Iter routes
for route_path, route_method, func in routes:
# Only handle non-WebSocket routes here
if route_method == method.upper() and route_method != 'ws':
path_vars = await _match_route(path, route_path)
if path_vars is not None:
try:
out = await func(**path_vars)
finally:
# Reset request context after handler (but keep response context for now)
req.headers = {}
req.params = {}
req.cookies = {}
req.path = ''
req.method = ''
if hasattr(req, 'body'):
del req.body
if isinstance(out, tuple) and len(out) == 2:
status_code, content = out
# Check for error handler
handler = errors.get(status_code) or errors.get(None)
if handler:
# If handler is for all errors, pass status_code as argument
if None in errors and handler == errors[None]:
out = await handler(status_code)
else:
out = await handler()
if isinstance(out, tuple) and len(out) == 2:
status_code, content = out
else:
content = out
# Determine content type and serialize content for error handler
if isinstance(content, (dict, list)):
content = json.dumps(content).encode()
content_type = 'application/json'
elif isinstance(content, str):
content = content.encode()
content_type = 'text/html'
elif isinstance(content, bytes):
content_type = 'text/html'
else:
content = str(content).encode()
content_type = 'text/html'
header = await _build_response(status_code, content_type)
# Reset response context after building response
_response_ctx.response = Response()
return header + content
else:
content = out
# Determine content type and serialize content
if isinstance(content, (dict, list)):
# Serialize dict/list to proper JSON
content = json.dumps(content).encode()
content_type = 'application/json'
elif isinstance(content, str):
content = content.encode()
content_type = 'text/html'
elif isinstance(content, bytes):
content_type = 'text/html'
else:
content = str(content).encode()
content_type = 'text/html'
header = await _build_response(200, content_type)
# Reset response context after building response
_response_ctx.response = Response()
return header + content
# 404 Not Found
status_code = 404
handler = errors.get(status_code) or errors.get(None)
if handler:
if None in errors and handler == errors[None]:
out = await handler(status_code)
else:
out = await handler()
if isinstance(out, tuple) and len(out) == 2:
status_code, content = out
else:
content = out
# Determine content type and serialize content
if isinstance(content, (dict, list)):
# Serialize dict/list to proper JSON
content = json.dumps(content).encode()
content_type = 'application/json'
elif isinstance(content, str):
content = content.encode()
content_type = 'text/html'
elif isinstance(content, bytes):
content_type = 'text/html'
else:
content = str(content).encode()
content_type = 'text/html'
header = await _build_response(status_code, content_type)
# Reset response context after building response
_response_ctx.response = Response()
return header + content
return b'HTTP/1.1 404 Not Found\r\n\r\n'
# Socket Handler
async def _csHandler(cs: socket.socket, addr: tuple[str, int]): # pragma: no cover
cs.setblocking(False) # Make client socket non-blocking for async operation
try:
request_data = await _receive_request(cs)
if not request_data:
return
method, path, version, headers_str, body = await _parse_http_request(request_data)
log_request(method, path)
if await _is_websocket_request(method, request_data):
await _handle_websocket(cs, path, request_data)
else:
await _handle_http_request(cs, method, path, version, headers_str, body, addr)
except Exception as e:
log(f"Error handling request: {e}", "ERROR")
finally:
cs.close()
# Request handling
async def _receive_request(cs: socket.socket) -> bytes: # pragma: no cover
"""Receive complete HTTP request data."""
loop = asyncio.get_event_loop()
data = b''
while True:
try:
chunk = await loop.sock_recv(cs, 4096)
if chunk == b'':
break
data += chunk
if len(chunk) < 4096:
break
except Exception:
break
return data
async def _parse_http_request(data: bytes) -> tuple[str, str, str, str, str]: # pragma: no cover
"""Parse HTTP request into components."""
header_split = data.split(b'\r\n\r\n', 1)
headers_part = header_split[0]
body_bytes = header_split[1] if len(header_split) == 2 else b''
headers_lines = headers_part.split(b'\r\n')
request_line = headers_lines[0].decode(errors='ignore')
headers_str = b'\r\n'.join(headers_lines[1:]).decode(errors='ignore')
method, path, version = request_line.split(' ', 2)
method = method.strip().upper()
# Handle request body for POST/PUT/PATCH
if method in ('POST', 'PUT', 'PATCH'):
body_bytes = await _read_request_body(headers_str, body_bytes)
body = body_bytes.decode(errors='ignore')
return method, path, version, headers_str, body
async def _read_request_body(headers_str: str, initial_body: bytes) -> bytes:
"""Read complete request body based on Content-Length."""
content_length = 0
for line in headers_str.split('\r\n'):
if line.lower().startswith('content-length:'):
try:
content_length = int(line.split(':', 1)[1].strip())
break
except (ValueError, IndexError):
pass
# Return initial body if it's already complete
if len(initial_body) >= content_length:
return initial_body[:content_length]
return initial_body
async def _parse_headers_bytes(data: bytes) -> dict[bytes, bytes]:
"""Parse HTTP headers from raw bytes."""
headers_lines = data.split(b'\r\n\r\n', 1)[0].split(b'\r\n')[1:]
header_dict: dict[bytes, bytes] = {}
for line in headers_lines:
if b':' in line:
key, value = line.split(b':', 1)
header_dict[key.strip().lower()] = value.strip()
return header_dict
async def _handle_http_request(cs: socket.socket, method: str, path: str,
version: str, headers_str: str, body: str, addr: tuple[str, int]):
"""Handle regular HTTP request."""
loop = asyncio.get_event_loop()