Skip to content

Instantly share code, notes, and snippets.

@vitouXY
Last active May 19, 2020 02:10
Show Gist options
  • Save vitouXY/55ea00e5b353e5e563d784add63b476b to your computer and use it in GitHub Desktop.
Save vitouXY/55ea00e5b353e5e563d784add63b476b to your computer and use it in GitHub Desktop.
Simple HTTP Server With Upload. /HTTPS /Authentication
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8 :
from __future__ import print_function, unicode_literals
"""
Simple HTTP Server With Upload ...and SSL ... and Authentication.
This module builds on BaseHTTPServer by implementing the standard GET
and HEAD requests in a fairly straightforward manner.
"""
"""
# Config File: settings.py
base_url = '/home/pi/'
host = '0.0.0.0'
port = 10080
https = True
cert_pem = '/opt/usr-scpts-py/HTTPSrv.pem'
auth = True
username = 'pi'
password = 'raspberry'
db_tmpfile = '/tmp/.nodata.db'
# $ openssl req -new -x509 -keyout sslcert_httppython.pem \
# -out sslcert_httppython.pem -days 365 -nodes
# $ openssl req -x509 -nodes -sha256 -days 365 -newkey rsa:2048 \
# -keyout sslcert_httppython.pem -out sslcert_httppython.pem
# $ chmod 444 sslcert_httppython.pem
"""
"""
Index's File Names : ".nomedia.txt", ".nodata.txt"
"""
__version__ = "0.2-3"
__all__ = ["SimpleHTTPRequestHandler"]
__author__ = "bones7456"
__home_page__ = "http://localhost/"
__ssl_addition__ = 'rhmoult'
__contributor__ = "wonjohnchoi"
import sys
import os
if sys.version_info >= (3, 0):
sys.exit("{}: Currently, this program runs only on python2.".format(sys.version_info[0]))
#if os.geteuid() != 0:
# sys.exit('{}: Operation not permitted'.format(os.geteuid()))
if os.name != 'posix':
sys.exit('{}: Platform not supported'.format(os.name))
import posixpath
import BaseHTTPServer
import urllib
import cgi
import shutil
import mimetypes
import re
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import base64
import ssl # Modification by rmoulton
# set/load default config...
CONFIGVAR_base_url = './'
CONFIGVAR_host = '0.0.0.0'
CONFIGVAR_port = 10080
CONFIGVAR_https = True
CONFIGVAR_cert_pem = '/opt/usr-scpts-py/HTTPSrv.pem'
CONFIGVAR_auth = True
CONFIGVAR_username = 'admin'
CONFIGVAR_password = 'P455W0RD5'
CONFIGVAR_db_tmpfile = '/tmp/.nodata.db'
try:
import settings # settings.py
CONFIGVAR_base_url = settings.base_url
CONFIGVAR_host = settings.host
CONFIGVAR_port = settings.port
CONFIGVAR_https = settings.https
CONFIGVAR_cert_pem = settings.cert_pem
CONFIGVAR_auth = settings.auth
CONFIGVAR_username = settings.username
CONFIGVAR_password = settings.password
CONFIGVAR_db_tmpfile = settings.db_tmpfile
print("Config loaded from file!")
except ImportError:
print("Config file not loaded!")
###################################
import signal
def keyboardInterruptHandler(signal, frame):
print(" KeyboardInterrupt (ID: {}) has been caught. Cleaning up..." . format(signal))
exit(0)
signal.signal(signal.SIGINT, keyboardInterruptHandler)
def bytes2human(n):
"""
>>> bytes2human(10000)
'9K'
>>> bytes2human(100001221)
'95M'
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = int(float(n) / prefix[s])
return '%s%s' % (value, s)
return "%sB" % n
os.chdir(CONFIGVAR_base_url)
""" for Authentication Only """
def key():
return base64.b64encode('%s:%s' % (CONFIGVAR_username, CONFIGVAR_password))
class Counter:
''' instantiate only once '''
def __init__(self):
import sqlite3
#print('<-> Making sqlite3 database')
self.conn = sqlite3.connect(CONFIGVAR_db_tmpfile)
self.cursor = self.conn.cursor()
self.cursor.execute('''CREATE TABLE IF NOT EXISTS counter
(fullpath text primary key, count integer)''')
def incr_counter(self, path):
''' Increase the counter that counts how many times a path is visited '''
res = self.read_counter(path)
# print('incr_counter:', path, res, '->', res + 1)
res += 1
self.cursor.execute('REPLACE INTO counter(fullpath, count) VALUES(?, ?)', (path, res))
self.conn.commit()
pass
def read_counter(self, path):
''' Read the counter that counts how many times a path is visited '''
self.cursor.execute('SELECT * FROM "counter" WHERE "fullpath"=?', (path,))
row = self.cursor.fetchone()
count = 0
if row != None : count = row[1]
# print('read_counter:', path, count)
return count
class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
'''Simple HTTP request handler with GET/HEAD/POST commands.
This serves files from the current directory and any of its
subdirectories. The MIME type for files is determined by
calling the .guess_type() method. And can reveive file uploaded
by client.
The GET/HEAD/POST requests are identical except that the HEAD
request omits the actual contents of the file.
'''
server_version = "SimpleHTTPWithUpload/" + __version__
""" for Authentication Only """
if CONFIGVAR_auth == True: counter = Counter()
if CONFIGVAR_auth == True:
def is_authenticated(self):
auth_header = self.headers.getheader('Authorization')
return auth_header and auth_header == 'Basic ' + key()
def do_AUTHHEAD(self):
self.send_response(401)
self.send_header('WWW-Authenticate', 'Basic realm=\"RPi0W\"') # Test
self.send_header('Content-type', 'text/html')
self.end_headers()
def try_authenticate(self):
if not self.is_authenticated():
self.do_AUTHHEAD()
print('<!> Not Authenticated')
self.wfile.write('not authenticated')
return False
return True
def do_GET(self):
'''Serve a GET request.'''
""" for Authentication Only """
if CONFIGVAR_auth == True:
if not self.try_authenticate(): return
print('<!> Authenticated')
f = self.send_head()
if f:
self.copyfile(f, self.wfile)
f.close()
def do_HEAD(self):
'''Serve a HEAD request.'''
f = self.send_head()
if f:
f.close()
def do_POST(self):
'''Serve a POST request.'''
""" for Authentication Only """
if CONFIGVAR_auth == True:
if not self.try_authenticate(): return
print('<!> Authenticated')
r, info = self.deal_post_data()
print(r, info, "by: ", self.client_address)
f = StringIO()
f.write("""
<html lang='en'>
<head>
<title>RPi0W@web:~# ./upload</title>
<meta charset='UTF-8'>
<!-- --> <meta name='viewport' content='width=device-width, initial-scale=1'> <!-- -->
<link rel='icon' href='data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC1ElEQVR4AXVTA5NtRxi8lZ/xzEJs69nG2rZt27Zt27Zt23uii87MbIxT1WfYPR95AP6GM9+aXD39nZnLmevmLWeumR5S0Dndo2f/vP/nhGf/xtnrZsYXbllwMrbZAvfkDmQ3zCCvaRbeaV1QdsoTXLxtydE79O7fBE7I5s0finlybml9CC4ch1v6EPR9y2HoVwGPzGGEFk3AL2cQX8j4cfQuE/ldgKq+99Lj2Dl1AMZR3dAIaod2SAeGpjcY9MI6oejbCgXfFuiGdeCtp27HlEO5zOezN8w5Vd8GaBGSkl8r1ALamMjowj5G5vdx16oaXxqUMdyzrsZzuwpQDuXyaHC+UIzgawV3QMazGQ914vBEPx7PDRNxRzMaVx574MJ9t9/BRJ7Y1+E9iWA+5fJohO8ZZUHeuwWS7k044H7Bjz8L8NMvQoZf+ELwBSIIhSK6zwRuWVThC7VkUC6PpomaJOHWCGnPJij7t0M9sAPPnRrA/cQHADywrcNNi2pcM63EN8YV+I7gmmEhKJcJvHasgoxXC+R9WqEa0A5VIvDMsZFZAAAvnBvx2L4e921qcduyGreI2HWjohOBc8SMR6a5UCFEZb92aAR3ESs6YBU/ABFOPsfUYYi5NROrGvGICD13bMC3WmnMBRbE79Si+foRPVAL7IRuOBmDujCycICa/g00DG1ibv2YWNcOSY9WvHRpIvM2fCIbxoLI0njxlhWnH9pKaqAP+hF9CCycwvwGB+PoARgSTK4cIap8hooQSzug7NOAczcsWBr/KKTPpHyOvXPGYJc8hHryqkvGGKwSR2ARPwybxGF0TOzAkDzgkDKE9195skL6Wymfu2nR/I18ABeUP4Lg4il4Zk/AMW0MDqmjcM8aZ1Z5ZQ7iU0kf7tx1C1bK/9lMV+9ac0qkcWgD5TXPI5eAzhXJ3qX/a6Z/tvPZa2YuF25Ztpy7bnZIQedk7z/b+VeJV4IjkhVm5wAAAABJRU5ErkJggg==' title='RPi0W@web' type='image/x-icon' />
<link rel='shortcut icon' href='data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC1ElEQVR4AXVTA5NtRxi8lZ/xzEJs69nG2rZt27Zt27Zt23uii87MbIxT1WfYPR95AP6GM9+aXD39nZnLmevmLWeumR5S0Dndo2f/vP/nhGf/xtnrZsYXbllwMrbZAvfkDmQ3zCCvaRbeaV1QdsoTXLxtydE79O7fBE7I5s0finlybml9CC4ch1v6EPR9y2HoVwGPzGGEFk3AL2cQX8j4cfQuE/ldgKq+99Lj2Dl1AMZR3dAIaod2SAeGpjcY9MI6oejbCgXfFuiGdeCtp27HlEO5zOezN8w5Vd8GaBGSkl8r1ALamMjowj5G5vdx16oaXxqUMdyzrsZzuwpQDuXyaHC+UIzgawV3QMazGQ914vBEPx7PDRNxRzMaVx574MJ9t9/BRJ7Y1+E9iWA+5fJohO8ZZUHeuwWS7k044H7Bjz8L8NMvQoZf+ELwBSIIhSK6zwRuWVThC7VkUC6PpomaJOHWCGnPJij7t0M9sAPPnRrA/cQHADywrcNNi2pcM63EN8YV+I7gmmEhKJcJvHasgoxXC+R9WqEa0A5VIvDMsZFZAAAvnBvx2L4e921qcduyGreI2HWjohOBc8SMR6a5UCFEZb92aAR3ESs6YBU/ABFOPsfUYYi5NROrGvGICD13bMC3WmnMBRbE79Si+foRPVAL7IRuOBmDujCycICa/g00DG1ibv2YWNcOSY9WvHRpIvM2fCIbxoLI0njxlhWnH9pKaqAP+hF9CCycwvwGB+PoARgSTK4cIap8hooQSzug7NOAczcsWBr/KKTPpHyOvXPGYJc8hHryqkvGGKwSR2ARPwybxGF0TOzAkDzgkDKE9195skL6Wymfu2nR/I18ABeUP4Lg4il4Zk/AMW0MDqmjcM8aZ1Z5ZQ7iU0kf7tx1C1bK/9lMV+9ac0qkcWgD5TXPI5eAzhXJ3qX/a6Z/tvPZa2YuF25Ztpy7bnZIQedk7z/b+VeJV4IjkhVm5wAAAABJRU5ErkJggg==' />
<meta name='google' value='notranslate'>
<script language='Javascript'> var TimeID; function timer() { window.clipboardData.clearData(); timeID = setTimeout('timer()', 100); } </script>
</head>
<body onload='timer()' oncontextmenu='return false' ondragstart='return false' onselectstart='return false' onkeydown='return false'>
<samp>
""")
f.write("""
<a style='all:unset;' href='/'>RPi0W@web</a>:~# ./upload<br/>
""")
# -----------------------------------------------------------------------------
f.write("""
<br/>!----------------------------------------&#187;
<ul>
""")
if r:
f.write("Success:<br/>")
else:
f.write("Failed:<br/>")
f.write(info)
f.write("""
<br/><a style='all:unset;' href='%s'>[&crarr;]</a>""" % self.headers['referer'])
f.write("""
</ul>
!----------------------------------------&#187;<br/><br/><center><small>RPi0W@web &copy; 2019. All Rights Not Reserved.</small></center>
</samp>
</body>
</html>
""")
length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(length))
self.send_header("imagetoolbar", "no")
self.send_header("pragma", "no-cache")
self.send_header("Expires", "0")
self.end_headers()
if f:
self.copyfile(f, self.wfile)
f.close()
def deal_post_data(self):
boundary = self.headers.plisttext.split("=")[1]
remainbytes = int(self.headers['content-length'])
line = self.rfile.readline()
remainbytes -= len(line)
if boundary not in line:
return False, "Content NOT begin with boundary"
line = self.rfile.readline()
remainbytes -= len(line)
fn = re.findall(r'Content-Disposition.*name="file"; filename="(.*)"', line)
if not fn:
return False, "Can't find out file name..."
path = self.translate_path(self.path)
fn = os.path.join(path, fn[0])
line = self.rfile.readline()
remainbytes -= len(line)
line = self.rfile.readline()
remainbytes -= len(line)
try:
out = open(fn, 'wb')
except IOError:
return False, "Can't create file to write, do you have permission to write?"
preline = self.rfile.readline()
remainbytes -= len(preline)
while remainbytes > 0:
line = self.rfile.readline()
remainbytes -= len(line)
if boundary in line:
preline = preline[0:-1]
if preline.endswith('\r'):
preline = preline[0:-1]
out.write(preline)
out.close()
return True, "File '{}' upload success!".format(fn)
else:
out.write(preline)
preline = line
return False, "Unexpect Ends of data."
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing further to do.
"""
path = self.translate_path(self.path)
# f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
for index in ".nomedia.txt", ".nodata.txt":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
# Always read in binary mode. Opening files in text mode may cause
# newline translations, making the actual size of the content
# transmitted *less* than the content-length!
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(fs[6]))
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.send_header("imagetoolbar", "no")
self.send_header("pragma", "no-cache")
self.send_header("Expires", "0")
self.end_headers()
return f
def list_directory(self, path):
"""Helper to produce a directory listing (absent index.html).
Return value is either a file object, or None (indicating an
error). In either case, the headers are sent, making the
interface the same as for send_head().
~ HTML Code For Upload Mode:
f.write("<center><small>\n<form style='all:unset;' enctype='multipart/form-data' method='post'>\n<label for='fileup'>[SelectFile]</label><input id='fileup' style='display:none;' accept='.txt,text/plain,.tar.gz' name='file' type='file'/>\n<input style='all:unset;' type='submit' value='[&uArr;]'/></form>\n<hr size='1'></small></center><br/>\n")
f.write("<iframe src='asdfile.txt'></iframe>")
"""
try:
directory_list = os.listdir(path)
except os.error:
self.send_error(404, "No permission to list directory")
return None
directory_list.sort(key=lambda a: a.lower())
f = StringIO()
displaypath = cgi.escape(urllib.unquote(self.path))
displaypath_lst = displaypath.split('/')
displaypath_len = len(displaypath_lst)
if displaypath_lst[displaypath_len-1] == '': del displaypath_lst[displaypath_len-1]
if displaypath_lst[0] == '': del displaypath_lst[0]
displaypath_len = len(displaypath_lst)
#displaypath_lst.remove('')
#print(displaypath_lst)
#print(len(displaypath_lst))
item_url = '/'
item_name = ''
item_fullpath = ''
for item in displaypath_lst:
item_url = item_url + item + '/'
item_name = item + '/'
item_path = "<a style='all:unset;' href='%s'>%s</a>" % (item_url, item_name)
item_fullpath = item_fullpath + item_path
#print(item_fullpath)
f.write("""
<html lang='en'>
<head>
<title>RPi0W@web:~# ls %s</title>
<meta charset='UTF-8'>
<!-- --> <meta name='viewport' content='width=device-width, initial-scale=1'> <!-- -->
<link rel='icon' href='data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC1ElEQVR4AXVTA5NtRxi8lZ/xzEJs69nG2rZt27Zt27Zt23uii87MbIxT1WfYPR95AP6GM9+aXD39nZnLmevmLWeumR5S0Dndo2f/vP/nhGf/xtnrZsYXbllwMrbZAvfkDmQ3zCCvaRbeaV1QdsoTXLxtydE79O7fBE7I5s0finlybml9CC4ch1v6EPR9y2HoVwGPzGGEFk3AL2cQX8j4cfQuE/ldgKq+99Lj2Dl1AMZR3dAIaod2SAeGpjcY9MI6oejbCgXfFuiGdeCtp27HlEO5zOezN8w5Vd8GaBGSkl8r1ALamMjowj5G5vdx16oaXxqUMdyzrsZzuwpQDuXyaHC+UIzgawV3QMazGQ914vBEPx7PDRNxRzMaVx574MJ9t9/BRJ7Y1+E9iWA+5fJohO8ZZUHeuwWS7k044H7Bjz8L8NMvQoZf+ELwBSIIhSK6zwRuWVThC7VkUC6PpomaJOHWCGnPJij7t0M9sAPPnRrA/cQHADywrcNNi2pcM63EN8YV+I7gmmEhKJcJvHasgoxXC+R9WqEa0A5VIvDMsZFZAAAvnBvx2L4e921qcduyGreI2HWjohOBc8SMR6a5UCFEZb92aAR3ESs6YBU/ABFOPsfUYYi5NROrGvGICD13bMC3WmnMBRbE79Si+foRPVAL7IRuOBmDujCycICa/g00DG1ibv2YWNcOSY9WvHRpIvM2fCIbxoLI0njxlhWnH9pKaqAP+hF9CCycwvwGB+PoARgSTK4cIap8hooQSzug7NOAczcsWBr/KKTPpHyOvXPGYJc8hHryqkvGGKwSR2ARPwybxGF0TOzAkDzgkDKE9195skL6Wymfu2nR/I18ABeUP4Lg4il4Zk/AMW0MDqmjcM8aZ1Z5ZQ7iU0kf7tx1C1bK/9lMV+9ac0qkcWgD5TXPI5eAzhXJ3qX/a6Z/tvPZa2YuF25Ztpy7bnZIQedk7z/b+VeJV4IjkhVm5wAAAABJRU5ErkJggg==' title='RPi0W@web' type='image/x-icon' />
<link rel='shortcut icon' href='data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC1ElEQVR4AXVTA5NtRxi8lZ/xzEJs69nG2rZt27Zt27Zt23uii87MbIxT1WfYPR95AP6GM9+aXD39nZnLmevmLWeumR5S0Dndo2f/vP/nhGf/xtnrZsYXbllwMrbZAvfkDmQ3zCCvaRbeaV1QdsoTXLxtydE79O7fBE7I5s0finlybml9CC4ch1v6EPR9y2HoVwGPzGGEFk3AL2cQX8j4cfQuE/ldgKq+99Lj2Dl1AMZR3dAIaod2SAeGpjcY9MI6oejbCgXfFuiGdeCtp27HlEO5zOezN8w5Vd8GaBGSkl8r1ALamMjowj5G5vdx16oaXxqUMdyzrsZzuwpQDuXyaHC+UIzgawV3QMazGQ914vBEPx7PDRNxRzMaVx574MJ9t9/BRJ7Y1+E9iWA+5fJohO8ZZUHeuwWS7k044H7Bjz8L8NMvQoZf+ELwBSIIhSK6zwRuWVThC7VkUC6PpomaJOHWCGnPJij7t0M9sAPPnRrA/cQHADywrcNNi2pcM63EN8YV+I7gmmEhKJcJvHasgoxXC+R9WqEa0A5VIvDMsZFZAAAvnBvx2L4e921qcduyGreI2HWjohOBc8SMR6a5UCFEZb92aAR3ESs6YBU/ABFOPsfUYYi5NROrGvGICD13bMC3WmnMBRbE79Si+foRPVAL7IRuOBmDujCycICa/g00DG1ibv2YWNcOSY9WvHRpIvM2fCIbxoLI0njxlhWnH9pKaqAP+hF9CCycwvwGB+PoARgSTK4cIap8hooQSzug7NOAczcsWBr/KKTPpHyOvXPGYJc8hHryqkvGGKwSR2ARPwybxGF0TOzAkDzgkDKE9195skL6Wymfu2nR/I18ABeUP4Lg4il4Zk/AMW0MDqmjcM8aZ1Z5ZQ7iU0kf7tx1C1bK/9lMV+9ac0qkcWgD5TXPI5eAzhXJ3qX/a6Z/tvPZa2YuF25Ztpy7bnZIQedk7z/b+VeJV4IjkhVm5wAAAABJRU5ErkJggg==' />
<meta name='google' value='notranslate'>
<script language='Javascript'> var TimeID; function timer() { window.clipboardData.clearData(); timeID = setTimeout('timer()', 100); } </script>
</head>
<body onload='timer()' oncontextmenu='return false' ondragstart='return false' onselectstart='return false' onkeydown='return false'>
<samp>
""" % displaypath)
f.write("""
<center><small>
<form style='all:unset;' enctype='multipart/form-data' method='post'>
<label for='fileup'>[SelectFile]</label><input id='fileup' style='display:none;' accept='.txt,text/plain' name='file' type='file'/>
<input style='all:unset;' type='submit' value='[&uArr;]'/>
</form>
<br/><font>&laquo;----------------------------------------&raquo;</font>
</small></center><br/>
""") #" ""##&raq uo;#
f.write("""
<a style='all:unset;' href='/'>RPi0W@web</a>:~# ls <a style='all:unset;' href='/'>/</a>%s<br/>
""" % item_fullpath) # % displaypath)
f.write("""
<br/>!----------------------------------------&#187;
<ul>
""")
for name in directory_list:
fullname = os.path.join(path, name)
displayname = linkname = name
if os.path.isfile(fullname):
displayname = name
linkname = name
fil3 = open(fullname, 'r')
r3ad = fil3.read(140)
fil3_sz = bytes2human(os.path.getsize(fullname))
fil3_mt = mimetypes.MimeTypes().guess_type(fullname)[0]
#if (fil3_mt and fil3_mt.lower().split('/')[0].find('video') >= 0):
# f.write("<br /><video width='160' height='120' controls><source src='%s' type='video/mp4'>--Err</video>" % (urllib.quote(linkname)))
#textarea_c#cod3html = "<li><a style='all:unset;' href='%s'>%s</a>\n<pre><textarea style='font-family:monospace;font-size:10px;background-color:white;border:dashed 0px black;resize:vertical;overflow:hidden;max-height:200px;white-space:pre;' rows='1' cols='83' readonly>%s &#183;&#183;&#183;</textarea></pre>\n\n" % (urllib.quote(linkname), cgi.escape(displayname), r3ad)
#textarea_b#cod3html = "<li><a style='all:unset;' href='%s'>%s</a><br/><blockquote><pre><code>%s</code></pre> &#183;&#183;&#183;</blockquote>\n" % (urllib.quote(linkname), cgi.escape(displayname), r3ad)
#textarea_a#cod3html = "<li><a style='all:unset;' href='%s'>%s</a>\n<pre><textarea style='background-color:white;border:dashed 1px black;resize:none;white-space:pre;' rows='3' cols='50' readonly>%s &#183;&#183;&#183;</textarea>\n\n" % (urllib.quote(linkname), cgi.escape(displayname), r3ad)
cod3html = "<li><a style='all:unset;' href='%s'>%s</a> (%s, %s)\n" % (urllib.quote(linkname), cgi.escape(displayname), fil3_sz, fil3_mt)
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
linkname = name + "/"
cod3html = "<li><a style='all:unset;' href='%s'>%s</a>\n" % (urllib.quote(linkname), cgi.escape(displayname))
if os.path.islink(fullname):
displayname = name + "@"
# Note: a link to a directory displays with @ and links with /
cod3html = "<li><a style='all:unset;' href='%s'>%s</a>\n" % (urllib.quote(linkname), cgi.escape(displayname))
f.write("%s" % cod3html)
#" ""#f.write("<li><a style='all:unset;' href='%s'>%s</a>\n" % (urllib.quote(linkname), cgi.escape(displayname)))#" ""#
f.write("""
</ul>
!----------------------------------------&#187;<br/><br/><center><small>RPi0W@web &copy; 2019. All Rights Not Reserved.</small></center>
</samp>
</body>
</html>
""")
length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(length))
self.end_headers()
return f
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query parameters
path = path.split('?', 1)[0]
path = path.split('#', 1)[0]
path = posixpath.normpath(urllib.unquote(path))
words = path.split('/')
words = filter(None, words)
path = os.getcwd()
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir):
continue
path = os.path.join(path, word)
return path
def copyfile(self, source, outputfile):
"""Copy all data between two file objects.
The SOURCE argument is a file object open for reading
(or anything with a read() method) and the DESTINATION
argument is a file object open for writing (or
anything with a write() method).
The only reason for overriding this would be to change
the block size or perhaps to replace newlines by CRLF
-- note however that this the default server uses this
to copy binary data as well.
"""
shutil.copyfileobj(source, outputfile)
def guess_type(self, path):
"""Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess.
"""
base, ext = posixpath.splitext(path)
if ext in self.extensions_map:
return self.extensions_map[ext]
ext = ext.lower()
if ext in self.extensions_map:
return self.extensions_map[ext]
else:
return self.extensions_map['']
if not mimetypes.inited:
mimetypes.init() # try to read system mime.types
extensions_map = mimetypes.types_map.copy()
extensions_map.update({
'': 'text/plain; charset=UTF-8', # Default B
'.*': 'text/plain; charset=UTF-8',
'*': 'text/plain; charset=UTF-8'
})
"""Extensions B mime.types
extensions_map.update({
'': 'text/plain; charset=utf-8', # Default B
'.bin': 'application/octet-stream',
'.pdf': 'application/pdf',
'.tar': 'application/x-tar',
'.gz': 'application/octet-stream',
'.rar': 'application/x-rar-compressed',
'.exe': 'application/x-msdownload',
'.zip': 'application/zip',
'.7z': 'application/x-7z-compressed',
'.mp4': 'video/mp4',
'.flv': 'video/x-flv',
'.avi': 'video/x-msvideo',
'.wmv': 'video/x-ms-wmv',
'.webm': 'video/webm',
'.weba': 'audio/webm',
'.wav': 'audio/x-wav',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.doc': 'application/msword',
'.odt': 'application/vnd.oasis.opendocument.text',
'.xls': 'application/vnd.ms-excel',
'.xps': 'application/vnd.ms-xpsdocument',
'.ods': 'application/vnd.oasis.opendocument.spreadsheet',
'.png': 'image/png',
'.gif': 'image/gif',
'.jpeg': 'image/jpeg',
'.jpg': 'image/jpeg',
'.bmp': 'image/bmp',
'.ico': 'image/x-icon',
'.py': 'text/plain; charset=utf-8',
'.html': 'text/plain; charset=utf-8',
'.php': 'text/plain; charset=utf-8',
'.md': 'text/plain; charset=utf-8',
'.txt': 'text/plain; charset=utf-8',
'.*': 'text/plain; charset=utf-8',
'*': 'text/plain; charset=utf-8',
})
Extensions"""
"""Extensions B mime.types
extensions_map.update({
'': 'text/plain; charset=utf-8', # Default B
'': 'application/octet-stream', # Default A
'.py': 'text/plain; charset=utf-8',
'.html': 'text/plain; charset=utf-8',
'.php': 'text/plain; charset=utf-8',
'.md': 'text/plain; charset=utf-8',
'.txt': 'text/plain; charset=utf-8',
'README': 'text/plain; charset=utf-8',
})
Extensions"""
def run(HandlerClass=SimpleHTTPRequestHandler, ServerClass=BaseHTTPServer.HTTPServer, protocol="HTTP/1.0"):
# Serving HTTPx default :
#print("Serving HTTP on port 8000 ... \nPath: ", CONFIGVAR_base_url)
#print("Use <Ctrl-C> to stop.")
# ... HTTP .
#BaseHTTPServer.test(HandlerClass, ServerClass)
# Serving HTTPx custom :
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = CONFIGVAR_port
#server_address = ('', port)
server_address = (CONFIGVAR_host, port)
HandlerClass.protocol_version = protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
# ... HTTPS
httpProto = ''
if CONFIGVAR_https == True:
httpProto = 'S'
httpd.socket = ssl.wrap_socket(httpd.socket, certfile=CONFIGVAR_cert_pem, server_side=True)
# ... .
if CONFIGVAR_auth == True:
httpProto = httpProto + ' w/Auth'
print("Serving HTTP%s on %s port %s..." % (httpProto, sa[0], sa[1]))
print("Path[%s]" % (CONFIGVAR_base_url))
#print("Use <Ctrl-C> to stop.")
try:
httpd.serve_forever()
except:
sys.exit(' wOops!!')
if __name__ == '__main__':
run()
########################################################
"""
# > /dev/null 2>&1
# (/usr/bin/python2 /srv/bin/http2.py > /tmp/HTTPy.log &)
# screen -ls
# screen -dmS HTTPy /usr/bin/python2 /srv/bin/http2.py
# screen -r HTTPy
# # ctrl+a + ctrl+d
# screen -S HTTPy -p 0 -X quit && screen --wipe
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment