-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethods.py
More file actions
216 lines (181 loc) · 8.28 KB
/
Copy pathmethods.py
File metadata and controls
216 lines (181 loc) · 8.28 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
import os
import json
import logging
from request import Request
from response import Response
from utils import (
validate_path, read_file_safe, get_file_mimetype,
is_supported_file_type, validate_host_header,
create_upload_filename, ensure_upload_directory
)
from exceptions import ForbiddenException
class Methods:
"""
HTTP Methods implementation for GET, POST, and other methods
"""
@staticmethod
def GET(request: Request) -> Response:
"""
Handle GET requests for HTML files and binary downloads
"""
logger = logging.getLogger('GET_Handler')
response = Response(request.version)
try:
# Validate Host header first
if not Methods._validate_host(request, response):
return response
# Handle root path - serve index.html
path = request.path
if path == '/' or path == '':
path = '/index.html'
# Validate and get safe file path
try:
safe_path = validate_path(path)
except ForbiddenException as e:
logger.warning(f'Path validation failed for {path}: {e.message}')
response.status = 403
response.message = 'Forbidden'
response.set_body('403 Forbidden: Access denied')
return response
# Check if file exists
if not os.path.exists(safe_path):
logger.info(f'File not found: {path}')
response.status = 404
response.message = 'Not Found'
response.set_body('404 Not Found')
return response
# Check if file type is supported
filename = os.path.basename(safe_path)
if not is_supported_file_type(filename):
logger.warning(f'Unsupported file type requested: {filename}')
response.status = 415
response.message = 'Unsupported Media Type'
response.set_body('415 Unsupported Media Type')
return response
# Get MIME type
mime_type = get_file_mimetype(filename)
# Handle HTML files (serve for viewing)
if mime_type.startswith('text/html'):
success, content, error = read_file_safe(path, 'r')
if not success:
logger.error(f'Error reading HTML file {path}: {error}')
response.status = 500
response.message = 'Internal Server Error'
response.set_body('500 Internal Server Error')
return response
response.set_html_body(content)
logger.info(f'Served HTML file: {filename} ({len(content)} bytes)')
# Handle binary files (download)
else:
success, content, error = read_file_safe(path, 'rb')
if not success:
logger.error(f'Error reading binary file {path}: {error}')
response.status = 500
response.message = 'Internal Server Error'
response.set_body('500 Internal Server Error')
return response
response.set_file_download(filename, content)
logger.info(f'Serving binary file: {filename} ({len(content)} bytes)')
return response
except Exception as e:
logger.error(f'Unexpected error in GET handler: {e}')
response.status = 500
response.message = 'Internal Server Error'
response.set_body('500 Internal Server Error')
return response
@staticmethod
def POST(request: Request) -> Response:
"""
Handle POST requests for JSON data upload
"""
logger = logging.getLogger('POST_Handler')
response = Response(request.version)
try:
# Validate Host header first
if not Methods._validate_host(request, response):
return response
# Check Content-Type
content_type = request.get_content_type()
if not content_type.startswith('application/json'):
logger.warning(f'Unsupported Content-Type for POST: {content_type}')
response.status = 415
response.message = 'Unsupported Media Type'
response.set_body('415 Unsupported Media Type: Only application/json accepted')
return response
# Parse JSON body
try:
json_data = request.get_json_body()
except ValueError as e:
logger.warning(f'Invalid JSON in POST request: {e}')
response.status = 400
response.message = 'Bad Request'
response.set_body('400 Bad Request: Invalid JSON')
return response
# Create uploads directory if it doesn't exist
upload_dir = ensure_upload_directory()
# Generate unique filename
filename = create_upload_filename()
file_path = os.path.join(upload_dir, filename)
# Write JSON data to file
try:
with open(file_path, 'w') as f:
json.dump(json_data, f, indent=2)
logger.info(f'JSON data saved to: {filename}')
# Create success response
response.status = 201
response.message = 'Created'
response_data = {
"status": "success",
"message": "File created successfully",
"filepath": f"/uploads/{filename}"
}
response.set_json_body(response_data)
except Exception as e:
logger.error(f'Error writing uploaded file: {e}')
response.status = 500
response.message = 'Internal Server Error'
response.set_body('500 Internal Server Error: Could not save file')
return response
except Exception as e:
logger.error(f'Unexpected error in POST handler: {e}')
response.status = 500
response.message = 'Internal Server Error'
response.set_body('500 Internal Server Error')
return response
@staticmethod
def OTHER(request: Request) -> Response:
"""
Handle unsupported HTTP methods
"""
logger = logging.getLogger('OTHER_Handler')
logger.warning(f'Unsupported method: {request.method}')
response = Response(request.version, 405, 'Method Not Allowed')
response.add_header('Allow', 'GET, POST')
response.set_body('405 Method Not Allowed: Only GET and POST methods are supported')
return response
@staticmethod
def _validate_host(request: Request, response: Response) -> bool:
"""
Validate Host header for security
Returns False if validation fails (response is already set)
"""
logger = logging.getLogger('HostValidator')
# Check if Host header exists
if not request.has_header('host'):
logger.warning('Request missing Host header')
response.status = 400
response.message = 'Bad Request'
response.set_body('400 Bad Request: Host header required')
return False
# For now, we'll accept any host header that looks reasonable
# In a production server, you'd validate against known good hosts
host = request.get_header('host')
# Basic validation - check for obviously malicious hosts
if any(char in host for char in ['<', '>', '"', "'"]):
logger.warning(f'Suspicious Host header: {host}')
response.status = 403
response.message = 'Forbidden'
response.set_body('403 Forbidden: Invalid Host header')
return False
logger.debug(f'Host validation: {host} ✓')
return True