#!/usr/bin/env python
import socket
import sys
import thread
import re
import datetime
port = int(sys.argv[1])
regex_topline = "^(GET) (/.*) HTTP/(.*)$"
regex_agent = "^User-Agent: (/.*)$"
regex_action_location = "^/(location|file|detail)=(.*)$"
root = "/home/michael/"
def error(message):
header = """HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Server: Nippysaurus Custom Server
Last-Modified: Mon, 23 May 2005 22:38:34 GMT
Connection: close
Content-Type: text/html; charset=UTF-8
"""
content = "error: " + message
return str(header) + str(content)
def detail(path):
None
def file(path):
None
def location(path):
response = """HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Server: Nippysaurus Custom Server
Last-Modified: Mon, 23 May 2005 22:38:34 GMT
Connection: close
Content-Type: text/html; charset=UTF-8
hello"""
response += "yep"
return response
def redirect(destination):
return "HTTP/1.1 301 Moved Permanently\nLocation: /" + destination
def process(request):
if request['resource'] == '/':
return redirect('location=/')
# Table of action functions which correspond to action types.
actions = {'location':location, 'file':file, 'detail':detail}
# In resource line, find request type and location that request refers to.
# Group 1 is request type ... "resource", "file", or "detail"
# Group 2 is file or folder request is referring to (resource).
m = re.match(regex_action_location,request['resource'])
if m:
return actions[m.group(1)](m.group(2))
else:
return error("invalid resource request format")
def connection(conn):
global id,idlock
idlock.acquire()
id += 1
idlock.release()
print "connection",id,"opened"
data = conn.recv(512)
if data:
request = {'type':None, 'resource':None, 'version':None, 'agent':None}
for line in data.rstrip("\n\r").splitlines():
# Find top line.
# Group 1 is request type.
# Group 2 is location request refers to.
# Group 3 is HTTP version.
m = re.match(regex_topline,line)
if m:
request['type'] = m.group(1)
request['resource'] = m.group(2)
request['version'] = m.group(3)
# Find user agent.
# Group 1 is user agent.
m = re.match(regex_agent,line)
if m:
request['agent'] = m.group(1)
# Formulate a response based on request information then send to client.
conn.send(process(request))
# No keepalive connections!
conn.close()
print "connection",id,"closed"
idlock = thread.allocate_lock()
id = 0
def listen():
s = None
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("",port))
s.listen(1)
print "listening on port",port
while 1:
(conn,addr) = s.accept()
thread.start_new_thread(connection,(conn,))
thread.start_new_thread(listen,())
#try:
# f = open("/home/michael/Desktop/TestTextt","r")
# print f.read()
#except IOError, (errno, strerror):
# print strerror
raw_input("")