Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
166 lines (138 loc) · 7.18 KB
/
Copy pathserver.py
File metadata and controls
166 lines (138 loc) · 7.18 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
# Author: Nadika Prabhath
# GitHub Username: nadikaprabhath
# GitHub URL: https://github.com/nadikaprabhath
# Copyright (c) 2025 Nadika Prabhath. All rights reserved.
#
# ---------------------------------------------------------------------------
# Improved / hardened version.
# Changes made compared to the original script (see chat for full explanation):
# 1. debug mode is OFF by default and only enabled via an env var
# 2. secret key is read from an environment variable instead of hardcoded
# 3. uploads are stored in a dedicated "uploads" subfolder, not the code dir
# 4. uploaded files get a collision-safe name (never silently overwrite)
# 5. a MAX_CONTENT_LENGTH limit is enforced to avoid huge-file DoS
# 6. zip files are now an allowed extension (stored as-is, NOT extracted,
# per your choice — extracting archives from untrusted uploads is a
# classic path-traversal / zip-slip risk, so it's deliberately skipped)
# 7. multiple files can be sent in one request (request.files.getlist),
# which is the practical way to "upload a folder" from a browser
# (browsers can't upload a raw folder as one HTTP file, but they can
# send all its files in one multipart request; a zip is still the
# simplest single-file way to move a whole folder)
# 8. basic logging via the `logging` module instead of raw prints
# ---------------------------------------------------------------------------
import os
import uuid
import logging
from flask import Flask, request, redirect, flash
from werkzeug.utils import secure_filename
app = Flask(__name__, static_folder='static', static_url_path='/static')
# --- Configuration -----------------------------------------------------
# Store uploads in a dedicated subfolder next to where the script is RUN
# FROM (the working directory), not next to __file__. Some editors/runners
# (e.g. VS Code's "Code Runner") execute a copy of the script from a temp
# location, which would otherwise put the uploads folder somewhere you
# can't find it. You can also force a specific location with UPLOAD_DIR.
BASE_DIR = os.environ.get('UPLOAD_DIR') or os.getcwd()
UPLOAD_FOLDER = os.path.join(BASE_DIR, "uploads")
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Secret key MUST come from the environment in real deployments.
# Falls back to a random key per-run if not set (sessions won't persist
# across restarts, but at least it's never a guessable hardcoded value).
app.secret_key = os.environ.get('FLASK_SECRET_KEY', uuid.uuid4().hex)
# Limit request body size (bytes). 200 MB here; tune to your needs.
app.config['MAX_CONTENT_LENGTH'] = 200 * 1024 * 1024
# Any extension NOT in this denylist is accepted (per user's request to
# support "all extensions"). Only genuinely dangerous/executable types are
# blocked, since accepting them could let someone drop a runnable script or
# server-side page (e.g. .php, .py) onto the server's filesystem.
DENIED_EXTENSIONS = {
'exe', 'sh', 'bat', 'cmd', 'com', 'msi', 'php', 'php3', 'php4', 'php5',
'phtml', 'py', 'pyc', 'pyw', 'js', 'jsp', 'jspx', 'asp', 'aspx', 'cgi',
'pl', 'rb', 'dll', 'so', 'jar', 'ps1', 'vbs', 'wsf', 'scr', 'apk',
}
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
logger = logging.getLogger(__name__)
def allowed_file(filename):
if '.' not in filename:
# No extension at all — allow it (e.g. a plain "README" file).
return True
ext = filename.rsplit('.', 1)[1].lower()
return ext not in DENIED_EXTENSIONS
def unique_path(directory, filename):
"""Return a path that doesn't overwrite an existing file, by appending
a short random suffix if the name is already taken."""
name, ext = os.path.splitext(filename)
candidate = os.path.join(directory, filename)
while os.path.exists(candidate):
candidate = os.path.join(directory, f"{name}_{uuid.uuid4().hex[:8]}{ext}")
return candidate
def save_upload(file_storage):
"""Validate and save a single uploaded file. Returns (ok, message)."""
if file_storage.filename == '':
return False, 'No file selected'
if not allowed_file(file_storage.filename):
return False, f'Invalid file type: {file_storage.filename}'
filename = secure_filename(file_storage.filename)
dest = unique_path(app.config['UPLOAD_FOLDER'], filename)
file_storage.save(dest)
logger.info('File saved: %s', dest)
return True, os.path.basename(dest)
@app.route('/')
def index():
# Serves static/index.html — the drag & drop upload page.
return app.send_static_file('index.html')
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
logger.info('Content-Type: %s', request.content_type)
logger.info('Files in request: %s', list(request.files.keys()))
# --- Multiple files in one request (e.g. all files of a folder,
# or a single zip representing a folder) ---
if request.files:
saved, errors = [], []
# getlist handles both a single <input name="file"> and
# multiple files sent under the same field name (e.g. via
# <input type="file" name="file" multiple>).
files = request.files.getlist('file') if 'file' in request.files else \
[f for key in request.files for f in request.files.getlist(key)]
for f in files:
logger.info('Incoming filename: %r', f.filename)
ok, result = save_upload(f)
(saved if ok else errors).append(result)
if errors:
logger.info('Rejected: %s', errors)
if not saved and errors:
return {'status': 'error', 'errors': errors}, 400
return {'status': 'ok', 'saved': saved, 'errors': errors}, 200
# --- Raw text/binary body (no multipart file) ---
elif request.data:
try:
text = request.data.decode('utf-8')
dest = unique_path(app.config['UPLOAD_FOLDER'], 'shared_text.txt')
with open(dest, 'w', encoding='utf-8') as f:
f.write(text)
logger.info('Text saved: %s', dest)
return 'Text shared successfully!'
except UnicodeDecodeError:
dest = unique_path(app.config['UPLOAD_FOLDER'], 'shared_binary.dat')
with open(dest, 'wb') as f:
f.write(request.data)
logger.info('Binary data saved as: %s', dest)
return 'Binary data received (check client setup for files)'
else:
return 'No data received', 400
return 'Server is running'
if __name__ == '__main__':
print()
print("-------------------------------------------------------")
print("Author: Nadika Prabhath")
print("GitHub Username: nadikaprabhath")
print("GitHub URL: https://github.com/nadikaprabhath")
print("Copyright (c) 2025 Nadika Prabhath. All rights reserved.")
print("-------------------------------------------------------")
print(f"Uploads will be saved to: {UPLOAD_FOLDER}")
print()
debug_mode = os.environ.get('FLASK_DEBUG', 'false').lower() == 'true'
app.run(host='0.0.0.0', port=5000, debug=debug_mode)