index.cgi 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python3
  2. # vim: tabstop=4 shiftwidth=4 expandtab
  3. import cgi, os, re, string, random
  4. import cgitb
  5. FILES_DIR_URL = "https://yourdomainhere/simple-fileshare/files"
  6. cgitb.enable(display=0, logdir=".")
  7. form = cgi.FieldStorage()
  8. filename = ''
  9. fullFilename = ''
  10. filenameOutput = ''
  11. copyButton = ''
  12. try:
  13. # A nested FieldStorage instance holds the file
  14. fileitem = form['file']
  15. # Test if the file was uploaded
  16. if fileitem.filename:
  17. filetype = os.path.basename(fileitem.filename).split('.')[-1]
  18. if filetype: # sanitize
  19. filetype = ''.join(re.findall('[a-zA-Z0-9]',filetype))
  20. # Generate a random 16 char filename, to avoid directory traversal and whatnot
  21. filename = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(16)) + f".{filetype}"
  22. open(f"files/{filename}", 'wb').write(fileitem.file.read())
  23. if filename:
  24. fullFilename = f"{FILES_DIR_URL}/{filename}"
  25. filenameOutput = f"<p><input type='text' value='{fullFilename}' readonly style='width: 100%'></p>"
  26. copyButton = "<button onclick=\"copyLinkToClipboard()\">Copy link</button>"
  27. except:
  28. # We don't really want to do anything here...
  29. someVar = 0
  30. print("""Content-Type: text/html
  31. <!DOCTYPE html>
  32. <html>
  33. <head>
  34. <title>Simple Filesharing</title>
  35. <style>
  36. body {
  37. max-width: 45em; margin: auto; padding: 0 1em 5em; background-color: #333333; color: #dddddd;
  38. }
  39. </style>
  40. <script>
  41. function copyLinkToClipboard() {
  42. try {
  43. navigator.clipboard.writeText("%s");
  44. document.getElementById("output").innerHTML = "Link copied to clipboard";
  45. } catch (error) {
  46. console.error(error);
  47. }
  48. }
  49. </script>
  50. <meta charset='utf-8'>
  51. <meta name='viewport' content='width=device-width,initial-scale=1'>
  52. </head>
  53. <body>
  54. <form enctype="multipart/form-data" action="index.cgi" method="post">
  55. <p>File: <input type="file" name="file"><input type="submit" value="Upload"></p>
  56. %s
  57. </form>
  58. %s
  59. <p id="output"><p>
  60. </body>
  61. </html>
  62. """ % (fullFilename,filenameOutput,copyButton))