Advertisement
fire219

stupid simple HTTP server

May 24th, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.25 KB | None | 0 0
  1. # Experimental HTTP Server #
  2. ############################
  3. # Author: Matthew Petry    #
  4. #        (fire219)         #
  5. ############################
  6. # DO NOT USE FOR ANY PRODUCTION PURPOSE; USE NGINX, APACHE, LIGHTTPD, ETC. #
  7.  
  8. import socket
  9. import time
  10. import os
  11. import datetime
  12. import queue
  13. import threading
  14.  
  15. version = "v0.1"
  16. utc_datetime = datetime.datetime.now()
  17.  
  18. ### Configuration ###
  19.  
  20. """
  21. # CONFIGURATION VARIABLES #
  22.  
  23. webport: TCP port that the server listens on
  24. maxconn: Maximum amount of incoming connections which will be allowed.
  25.          Any connections beyond this amount will be denied.
  26.          Note: maxconn only applies to the server socket
  27.         (akin to the queue at a movie theater).
  28. filelocation: Absolute path to the location where the webserver is
  29.          *INSTALLED*. Use "\\" for Windows-style paths.
  30. """
  31.  
  32. webport = 81
  33. maxconn = 10
  34. filelocation = "C:\\Users\\Matthew\\Documents\\pythonwebserver"            
  35.  
  36. ### End Configuration ###
  37.  
  38. ### Function Definitions ###
  39.  
  40. def mlog(logqueue): # MultiLog -- Log message to console and to file
  41.    
  42.     if os.path.isfile(filelocation+'/main.log') == True:
  43.         logw = open(filelocation+'/main.log', 'a')
  44.         logw.write('---LOG CONTINUED---\n')
  45.         logw.close()
  46.  
  47.     else:
  48.         logw = open(filelocation+'/main.log', 'w')
  49.         logw.write('---LOG STARTED---\n')
  50.         logw.close()
  51.  
  52.    
  53.     while 1:
  54.         if logqueue.empty() == False:  
  55.             logw = open(filelocation+'/main.log', 'a') 
  56.             utc_datetime = datetime.datetime.now() 
  57.             logline = "[" + utc_datetime.strftime("%Y-%m-%d %H:%M:%S.%f")+ "] " + logqueue.get()
  58.             print(logline)
  59.             logw.write(logline + '\n')
  60.             logw.close()
  61.            
  62. def clienthandler(clientsocket, address): # Client request handler
  63.     rawclientreq = str(clientsocket.recv(2048))
  64.     logqueue.put("Received from " + str(address) + ": " + rawclientreq)
  65.     if not "HTTP" in rawclientreq:
  66.         clientsocket.close()
  67.         return()
  68.     clientreq = rawclientreq[2:] #Remove byte marker and
  69.     clientreq = clientreq[:-9]
  70.     clientreq = clientreq.split('\\r\\n')
  71.    
  72.     if "Host: " in clientreq[1]:
  73.         hostreq = clientreq[1]
  74.         hostreq = hostreq[6:]
  75.         if ":" in hostreq:
  76.             hostreq = hostreq.split(":")[0]
  77.         if os.path.isdir(filelocation+'/sites/' + hostreq + '/') == True:      
  78.             filerequest = clientreq[0]
  79.             filerequest = filerequest[filerequest.index("/"):]
  80.             filerequest = filerequest[0:(filerequest.index("HTTP") - 1)]
  81.             filerequest = filerequest.strip('..') # Protection against Directory Traversal
  82.             if filerequest == "/" :
  83.                 filerequest = "/index.html"
  84.             if os.path.isfile(filelocation+'/sites/' + hostreq + filerequest) == True:
  85.                 readfile = open(filelocation+'/sites/' + hostreq + filerequest, 'rb')
  86.                 print("sending file")
  87.                 bytesend(clientsocket, "HTTP/1.1 200 OK \r\n\r\n")
  88.                 clientsocket.send(readfile.read())
  89.                 bytesend(clientsocket, '\r\n')
  90.             else:
  91.                 bytesend(clientsocket, "HTTP/1.1 404 Not Found \r\n\r\n <html><h1>File not found.</h1></html>\r\n")        
  92.         else:  
  93.             bytesend(clientsocket, "HTTP/1.1 404 Not Found \r\n\r\n <html><h1>Webserver not found.</h1></html>\r\n")
  94.     clientsocket.close()
  95.  
  96. def bytesend(clientsocket,string)# Send UTF-8 byte encoded data over clientsocket (because Python 3 sucks)
  97.     clientsocket.send(string.encode())
  98.  
  99. ### End Function Definitions ###
  100.  
  101. ### Initialization ###
  102.  
  103. logqueue = queue.Queue()
  104. logthread = threading.Thread(target=mlog, args=(logqueue,))
  105. logthread.start()  
  106. logqueue.put("Web Server " + version + " is starting!")
  107.  
  108. # creates an IPv4 streaming socket, binds to the TCP socket defined in the
  109. # config section, and sets maximum amount of connections on this server socket.
  110.  
  111. serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  112. serversock.bind(('', webport))
  113. serversock.listen(maxconn)
  114. logqueue.put("Server socket has been bound on port " + str(webport))
  115. logqueue.put("Current hostname: " + socket.gethostname())
  116.  
  117. ### End Socket initialization ###
  118.  
  119. ### Server Socket loop ###
  120.  
  121. # This loop is the server socket, which is the queue of connections/users
  122. # waiting to be allocated a dedicated server thread ("client socket").
  123.  
  124. while 1:
  125.     (clientsocket, address) = serversock.accept()
  126.     csock = threading.Thread(target=clienthandler, args=(clientsocket,address))
  127.     logqueue.put("Connection request from " + str(address))
  128.     csock.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement