Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Experimental HTTP Server #
- ############################
- # Author: Matthew Petry #
- # (fire219) #
- ############################
- # DO NOT USE FOR ANY PRODUCTION PURPOSE; USE NGINX, APACHE, LIGHTTPD, ETC. #
- import socket
- import time
- import os
- import datetime
- import queue
- import threading
- version = "v0.1"
- utc_datetime = datetime.datetime.now()
- ### Configuration ###
- """
- # CONFIGURATION VARIABLES #
- webport: TCP port that the server listens on
- maxconn: Maximum amount of incoming connections which will be allowed.
- Any connections beyond this amount will be denied.
- Note: maxconn only applies to the server socket
- (akin to the queue at a movie theater).
- filelocation: Absolute path to the location where the webserver is
- *INSTALLED*. Use "\\" for Windows-style paths.
- """
- webport = 81
- maxconn = 10
- filelocation = "C:\\Users\\Matthew\\Documents\\pythonwebserver"
- ### End Configuration ###
- ### Function Definitions ###
- def mlog(logqueue): # MultiLog -- Log message to console and to file
- if os.path.isfile(filelocation+'/main.log') == True:
- logw = open(filelocation+'/main.log', 'a')
- logw.write('---LOG CONTINUED---\n')
- logw.close()
- else:
- logw = open(filelocation+'/main.log', 'w')
- logw.write('---LOG STARTED---\n')
- logw.close()
- while 1:
- if logqueue.empty() == False:
- logw = open(filelocation+'/main.log', 'a')
- utc_datetime = datetime.datetime.now()
- logline = "[" + utc_datetime.strftime("%Y-%m-%d %H:%M:%S.%f")+ "] " + logqueue.get()
- print(logline)
- logw.write(logline + '\n')
- logw.close()
- def clienthandler(clientsocket, address): # Client request handler
- rawclientreq = str(clientsocket.recv(2048))
- logqueue.put("Received from " + str(address) + ": " + rawclientreq)
- if not "HTTP" in rawclientreq:
- clientsocket.close()
- return()
- clientreq = rawclientreq[2:] #Remove byte marker and
- clientreq = clientreq[:-9]
- clientreq = clientreq.split('\\r\\n')
- if "Host: " in clientreq[1]:
- hostreq = clientreq[1]
- hostreq = hostreq[6:]
- if ":" in hostreq:
- hostreq = hostreq.split(":")[0]
- if os.path.isdir(filelocation+'/sites/' + hostreq + '/') == True:
- filerequest = clientreq[0]
- filerequest = filerequest[filerequest.index("/"):]
- filerequest = filerequest[0:(filerequest.index("HTTP") - 1)]
- filerequest = filerequest.strip('..') # Protection against Directory Traversal
- if filerequest == "/" :
- filerequest = "/index.html"
- if os.path.isfile(filelocation+'/sites/' + hostreq + filerequest) == True:
- readfile = open(filelocation+'/sites/' + hostreq + filerequest, 'rb')
- print("sending file")
- bytesend(clientsocket, "HTTP/1.1 200 OK \r\n\r\n")
- clientsocket.send(readfile.read())
- bytesend(clientsocket, '\r\n')
- else:
- bytesend(clientsocket, "HTTP/1.1 404 Not Found \r\n\r\n <html><h1>File not found.</h1></html>\r\n")
- else:
- bytesend(clientsocket, "HTTP/1.1 404 Not Found \r\n\r\n <html><h1>Webserver not found.</h1></html>\r\n")
- clientsocket.close()
- def bytesend(clientsocket,string): # Send UTF-8 byte encoded data over clientsocket (because Python 3 sucks)
- clientsocket.send(string.encode())
- ### End Function Definitions ###
- ### Initialization ###
- logqueue = queue.Queue()
- logthread = threading.Thread(target=mlog, args=(logqueue,))
- logthread.start()
- logqueue.put("Web Server " + version + " is starting!")
- # creates an IPv4 streaming socket, binds to the TCP socket defined in the
- # config section, and sets maximum amount of connections on this server socket.
- serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- serversock.bind(('', webport))
- serversock.listen(maxconn)
- logqueue.put("Server socket has been bound on port " + str(webport))
- logqueue.put("Current hostname: " + socket.gethostname())
- ### End Socket initialization ###
- ### Server Socket loop ###
- # This loop is the server socket, which is the queue of connections/users
- # waiting to be allocated a dedicated server thread ("client socket").
- while 1:
- (clientsocket, address) = serversock.accept()
- csock = threading.Thread(target=clienthandler, args=(clientsocket,address))
- logqueue.put("Connection request from " + str(address))
- csock.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement