Debian Codegraph @

src/webupload/lkwebupload/upload/views.py

raw
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2018-2022 Matthias Klumpp <[email protected]>
4 #
5 # SPDX-License-Identifier: LGPL-3.0+
6
7 import os
8 import re
9 import shutil
10
11 from flask import Blueprint, request
12
13 from ..app import gdata
14
15 upload = Blueprint('upload', __name__)
16
17 _filename_ascii_strip_re = re.compile(r'[^A-Za-z0-9_.\-~\+]')
18
19
20 def secure_upload_filename(filename):
21 """Create a secure version of a filename that can safely be stored
22 on a regular file system and passed to :func:`os.path.join`.
23
24 Unlike the function from Werkzeug, this method allows certain characters
25 commonly used in Debian package names as well.
26
27 :param filename: the filename to secure
28 :return: the secured filename, or an empty string
29 """
30 if isinstance(filename, str):
31 from unicodedata import normalize
32
33 filename = normalize('NFKD', filename).encode('ascii', 'ignore')
34 filename = filename.decode('ascii')
35 for sep in os.path.sep, os.path.altsep:
36 if sep:
37 filename = filename.replace(sep, ' ')
38 filename = str(_filename_ascii_strip_re.sub('', '_'.join(filename.split()))).strip('._')
39 return filename
40
41
42 @upload.route('/<repo_name>', methods=['PUT'], defaults={'filename': None})
43 @upload.route('/<repo_name>/<path:filename_raw>', methods=['PUT'])
44 def upload_repo_artifact(repo_name: str, filename_raw=None):
45 if not filename_raw:
46 return 'no repository name given', 400
47 if repo_name not in gdata.repo_names:
48 return 'repository not found or does not accept uploads', 422
49
50 filename = secure_upload_filename(filename_raw)
51 if not filename:
52 return 'bad filename: {}'.format(filename_raw), 422
53
54 target_fname = os.path.join(gdata.incoming_dir, repo_name, filename)
55 if os.path.exists(target_fname):
56 return 'upload already exists', 403
57 with open(target_fname, 'wb') as f:
58 while True:
59 chunk = request.stream.read(gdata.upload_chunk_size)
60 if len(chunk) == 0:
61 break
62 f.write(chunk)
63 shutil.chown(target_fname, group=gdata.master_user)
64 os.chmod(target_fname, 0o664)
65 return 'created', 201
66
67
68 @upload.route('/')
69 def index():
70 return '<html>Upload endpoint for <a href="https://dput.readthedocs.io/en/latest/">dput(1)</a>.'