Advertisement
Guest User

the ben tovim

a guest
Jan 20th, 2020
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.57 KB | None | 0 0
  1. # HTTP Server Shell
  2. # Author: Barak Gonen
  3. # Purpose: Provide a basis for Ex. 4.4
  4. # Note: The code is written in a simple way, without classes, log files or
  5. # other utilities, for educational purpose
  6. # Usage: Fill the missing functions and constants
  7.  
  8. # TO DO: import modules
  9.  
  10. import os
  11. # TO DO: set constants
  12. import socket
  13. from datetime import datetime
  14. from time import mktime
  15. from wsgiref.handlers import format_date_time
  16.  
  17. IP = '0.0.0.0'
  18. PORT = 80
  19. SOCKET_TIMEOUT = 5000 # 5000 ms
  20. DEFAULT_URL = '/index.html'
  21. REDIRECTION_DICTIONARY = []
  22.  
  23.  
  24. def makeHTTPResponse(status='200 OK', server='bentovimerrrr server (noder)',
  25. contentType='text/plain', content=''):
  26. # build a http requests
  27. return 'HTTP/1.1 %s\r\n' \
  28. 'Date: %s\r\n' \
  29. 'Server: %s\r\n' \
  30. 'Content-Type: %s\r\n' \
  31. 'Content-Length: %d\r\n' \
  32. '\r\n' \
  33. '%s' % (
  34. status, format_date_time(mktime(datetime.now().timetuple())),
  35. server, contentType, len(content), content)
  36.  
  37.  
  38. def handeHTTPRequest(request):
  39. # break down http request into a dictionary
  40. request = request.split('\r\n')
  41. dic = {}
  42. title = request[0].split(' ')
  43. dic['request-type'] = title[0]
  44. dic['route'] = title[1]
  45. dic['http-version'] = title[2]
  46. for i in range(2, len(request) - 2):
  47. header = request[i].split(':', 1)
  48. dic[header[0]] = header[1]
  49. dic['body'] = request[len(request) - 1]
  50. return dic
  51.  
  52.  
  53. def get_file_data(filename):
  54. # get file content
  55. file = open(filename, 'rb')
  56. content = file.read()
  57. file.close()
  58. # get file type
  59. fileType = filename.split('.')
  60. fileType = fileType[len(fileType) - 1]
  61. return content, fileType
  62.  
  63.  
  64. def handle_client_request(request, client_socket):
  65. """ Check the required resource, generate proper HTTP response and send to
  66. client"""
  67. # TO DO : add code that given a resource (URL and parameters) generates the
  68. # proper response
  69.  
  70. # get route
  71. resource = request['route']
  72.  
  73. # set url
  74. if resource == '' or resource == '/':
  75. url = DEFAULT_URL
  76. else:
  77. url = resource
  78.  
  79. # split to url, params
  80. try:
  81. url = url.split('?')
  82. try:
  83. url[1] = url[1].split('&')
  84. except:
  85. url[1] = [url[1]]
  86. except:
  87. pass
  88.  
  89. params = {}
  90. if len(url) == 2:
  91. for param in url[1]:
  92. param = param.split('=')
  93. params[param[0]] = param[1]
  94.  
  95. url = url[0]
  96.  
  97. # convert route to absolute directory
  98. url = './webroot' + url
  99. if request['request-type'] != 'GET':
  100. client_socket.send(
  101. makeHTTPResponse(
  102. content='<h1>ERROR: 405 Method Not Allowed</h1> <br> try a' +
  103. 'different route or different request route',
  104. status=405,
  105. contentType='text/html'))
  106. elif os.path.isfile(url):
  107. fileContent, fileType = get_file_data(url)
  108. if fileType == 'html':
  109. client_socket.send(
  110. makeHTTPResponse(content=fileContent, contentType='text/html'))
  111. elif fileType == 'js':
  112. client_socket.send(
  113. makeHTTPResponse(
  114. content=fileContent, contentType='text/javascript'))
  115. elif fileType == 'css':
  116. client_socket.send(
  117. makeHTTPResponse(content=fileContent, contentType='text/css'))
  118. elif fileType == 'jpg':
  119. client_socket.send(
  120. makeHTTPResponse(
  121. content=fileContent, contentType='image/jpeg'))
  122. elif fileType == 'ico':
  123. client_socket.send(
  124. makeHTTPResponse(
  125. content=fileContent, contentType='image/x-icon'))
  126. else:
  127. client_socket.send(
  128. makeHTTPResponse(
  129. content=fileContent, contentType='text/plain'))
  130.  
  131. client_socket.send(
  132. makeHTTPResponse(content='<h1>ERROR: 404 not found</h1> <br> try' +
  133. 'a different route', status=404,
  134. contentType='text/html'))
  135.  
  136.  
  137. def validate_http_request(request):
  138. """ Check if request is a valid HTTP request and returns TRUE / FALSE and
  139. the requested URL """
  140. # TO DO: write function
  141. try:
  142. request = handeHTTPRequest(request)
  143. return True, request
  144. except:
  145. return False, ''
  146.  
  147.  
  148. def handle_client(client_socket):
  149. """ Handles client requests: verifies client's requests are legal HTTP,
  150. calls function to handle the requests """
  151. print 'Client connected'
  152. while True:
  153. client_request = client_socket.recv(500000)
  154. valid_http, request = validate_http_request(client_request)
  155. if valid_http:
  156. print 'Got a valid HTTP request'
  157. handle_client_request(request, client_socket)
  158. else:
  159. print 'Error: Not a valid HTTP request'
  160. break
  161. print 'Closing connection'
  162. client_socket.close()
  163.  
  164.  
  165. def main():
  166. # Open a socket and loop forever while waiting for clients
  167. server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  168. server_socket.bind((IP, PORT))
  169. server_socket.listen(10)
  170. print "Listening for connections on port %d" % PORT
  171.  
  172. while True:
  173. client_socket, client_address = server_socket.accept()
  174. print 'New connection received'
  175. client_socket.settimeout(SOCKET_TIMEOUT)
  176. handle_client(client_socket)
  177.  
  178.  
  179. if __name__ == "__main__":
  180. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement