Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import socket
- import urlparse
- import traceback
- import cgi
- import httplib
- import threading
- import sys
- import re
- import httplib
- import os
- import Cookie
- import sqlite3
- import random, crypt
- conn = sqlite3.connect('webserve-info.db')
- # per-site secret; only first two characters are used.
- secret = 'ZZ'
- # initialize random number generator from the system time on import.
- random.seed()
- def add_user(user,pwd):
- c = conn.cursor()
- c.execute("INSERT INTO users (username, password) VALUES (?,?)", (user,pwd))
- conn.commit()
- def serve(interface, port):
- sock = socket.socket()
- sock.bind((interface, port))
- sock.listen(10)
- while True:
- (client_sock, client_address) = sock.accept()
- #process = threading.Thread(target=handle_connection, args=(client_sock, client_address))
- #process.start()
- handle_connection(client_sock, client_address)
- """
- def handle_connection(client_sock, client_address):
- full_data = ''
- while True:
- data = client_sock.recv(1)
- full_data += data
- if full_data.endswith('\r\n\r\n'):
- break
- header_lines = full_data.split('\r\n')
- method, path, _ = header_lines[0].split()
- _, _, path, query, _ = urlparse.urlsplit(path)
- query = cgi.parse_qs(query)
- headers = []
- for header_line in header_lines[1:]:
- headers.append(re.findall(r'(.*?): (.*)', header_line))
- #print headers, 'HEADERSSSSSSSSSSSSSSSSSSSSSSSSSSS'
- post_data = None
- if method == 'POST':
- length = int(re.findall(r'Content-Length: (\d+)', full_data)[0])
- post_data = client_sock.recv(length)
- post_data = cgi.parse_qs(post_data)
- status=data = ''
- recvheaders=[]
- sheaders=[]
- for x in headers:
- if x != []:
- (a,b) = x[0]
- sheaders.append((a,b))
- try:
- status, recvheaders, data = delegate(method, path, sheaders, query, post_data)
- except Exception, e: # except everything because apparently ignoring exceptions is great! =P
- print e,"MESSAGE"
- status, recvheaders, data = 500, [('Content-Type', 'text/html')], '<h1>500 Internal Server Error</h1>'
- #response = "HTTP/1.1 %s\r\n%s\r\n\r\n%s" % ('200 OK' if status == 200 else '500 Internal Server Error', headers, data)
- try:
- response = "HTTP/1.1 %s %s\r\n" % (status, httplib.responses[status])
- except:
- status = 500
- response = "HTTP/1.1 %s %s\r\n" % (status, httplib.responses[status])
- for (header, val) in recvheaders:
- response+='%s: %s\r\n' % (header, val)
- if data !='':
- response+='%s: %s\r\n' % ('content-length', len(data))
- response+='\r\n%s' % data
- #print (response,), "response"
- client_sock.sendall(response)
- client_sock.close()
- """
- def handle_connection(client_sock, client_address):
- """
- 'handle_connection' is called for each client connection to the server.
- handle_connection(client_sock, client_address) takes the socket
- and client address information returned by 'accept' and handles
- exactly one HTTP exchange.
- 'delegate' is called to process the actual HTTP request.
- This function returns nothing (a.k.a 'return', a.k.a 'return None').
- No assumptions are made about the size of the input data; data should
- be read until the headers have been completely received. Any data
- following that should be parsed as POST data.
- In case an exception is raised in 'delegate', an HTTP error 500
- (internal server error) is returned.
- 'handle_connection' traps all exceptions.
- """
- try:
- data = ''
- try:
- while 1:
- r = client_sock.recv(4096)
- if not r:
- break
- data += r
- if '\r\n\r\n' in data:
- break
- except socket.error:
- return
- assert '\r\n\r\n' in data, data
- header_data, post_content = data.split('\r\n\r\n', 1)
- lines = header_data.splitlines()
- (request_type, url, protocol) = lines[0].split()
- headers = []
- for line in lines[1:]:
- line = line.strip()
- k, v = line.split(':', 1)
- v = v.strip()
- headers.append((k, v))
- assert protocol.startswith('HTTP/')
- urlobj = urlparse.urlsplit(url)
- path = urlobj.path
- query = urlobj.query
- get_data = None
- if query:
- get_data = cgi.parse_qs(query)
- post_data = None
- if request_type == 'POST':
- content_length = -1
- for k, v in headers:
- if k.lower() == 'content-length':
- content_length = int(v)
- break
- while len(post_content) < content_length:
- remaining = content_length - len(post_content)
- post_content += client_sock.recv(remaining)
- post_data = cgi.parse_qs(post_content)
- code, headers, content = delegate(request_type, path, headers,
- get_data, post_data)
- except:
- print traceback.format_exc()
- code = 500
- headers = [('Content-type', 'text/html')]
- content = 'error'
- try:
- if code in httplib.responses:
- status_message = httplib.responses[code]
- else:
- code = 500
- status_message = "server error"
- content = "SERVER ERROR"
- headers = [ '%s: %s\r\n' % (k, v) for k, v in headers ]
- headers += [ 'Content-Length: %d\r\n' % (len(content),) ]
- headers = "".join(headers)
- out_data = "HTTP/1.0 %s %s\r\n%s\r\n%s" % (code, status_message,
- headers, content)
- client_sock.sendall(out_data)
- client_sock.close()
- except socket.error:
- pass
- return
- def delegate(request_type, path, received_headers, GET_data, POST_data = None):
- funboy = path
- #if 'files' not in path:
- path = 'files/' + path
- path = path.lstrip('/')
- ulist = path.split('/')
- WUpath = os.path.join(*ulist)
- currdir = os.path.abspath('./')
- path = os.path.join(currdir, WUpath)
- path = os.path.abspath(path)
- assert path.startswith(currdir)
- go = funboy[1:].replace('/','_')
- tcheck = go.split('_')[0]
- if go in globals():
- return globals()[go](received_headers, GET_data, POST_data)
- elif os.path.exists(path):
- if not os.path.isfile(path):
- return blank(request_type,path,received_headers,GET_data,POST_data)
- elif os.path.isfile(path):
- return files(request_type,path,received_headers,GET_data,POST_data)
- elif tcheck == 'test':
- return default(received_headers, GET_data, POST_data,path)
- return 404, [],'<h1> path not found</h1>'
- def default(received_headers, GET_data, POST_data,path):
- data = 'hello, %s' % path
- head = []
- for request_data, name in ((GET_data, 'get_data:'), (POST_data, 'post_data:')):
- if request_data:
- data += " %s" % name
- for key in request_data:
- for val in request_data[key]:
- data += " key=%s; value=%s;" % (key, val)
- head.append(('Content-Type', 'text/html'))
- return 200, head, data
- def auth_login(H,G,P): #(Headers, Get_DATA, POST_DATA)
- #accounts = [('test','test'),('test2','testy')]
- header = []
- #checkconn = sqlite3.connect('webserve-info.db')
- c = conn.cursor()
- try:
- if P['username'] and P['password']:
- username = P['username'][0]
- password = P['password'][0]
- except Exception, g:
- return 200,[], '<h1> %s not provided </h1>' % (g)
- c.execute("SELECT id FROM users WHERE username=? AND password = ?",(username,password))
- accounts = c.fetchone()
- #print (accounts,)
- if accounts:
- hashv = generate_session_id(username)
- c.execute("INSERT INTO sessions (user_id,session_id) VALUES (?,?)",(accounts[0],hashv))
- conn.commit()
- C = Cookie.SimpleCookie()
- C['session'] = hashv
- x = C.output()
- x += '; Path=/'
- header.insert(len(header), x.split(': ',1))
- return 200,header,'<h4>Login Succesful!</h4>'
- return 401,[],'<h1> Unauthorized Access</h1>'
- def auth_jslogin(H,G,P): #(Headers, Get_DATA, POST_DATA)
- #accounts = [('test','test'),('test2','testy')]
- header = []
- #checkconn = sqlite3.connect('webserve-info.db')
- c = conn.cursor()
- try:
- if P['username'] and P['password']:
- username = P['username'][0]
- password = P['password'][0]
- except Exception, g:
- return 200,[], '<h1> %s not provided </h1>' % (g)
- c.execute("SELECT id FROM users WHERE username=? AND password = ?",(username,password))
- accounts = c.fetchone()
- #print (accounts,)
- if accounts:
- hashv = generate_session_id(username)
- c.execute("INSERT INTO sessions (user_id,session_id) VALUES (?,?)",(accounts[0],hashv))
- conn.commit()
- return 200, [], hashv
- return 200, [], 'Login Failed!'
- def auth_logout(H,G,P):
- header = []
- C = Cookie.SimpleCookie()
- for (k, v) in H:
- if k.lower() == 'cookie':
- C.load(v)
- c = conn.cursor()
- c.execute("""DELETE FROM sessions WHERE session_id = ?""", (C['session'].value,))
- C['session'] = ''
- x = C.output()
- x += '; Path=/'
- header.insert(len(header), x.split(': ',1))
- return 200,header,'<h4> Logout Succesful! </h4>'
- def auth_print(H,G,P):
- user=''
- if H:
- C = Cookie.SimpleCookie()
- for (k,v) in H:
- if k.lower() == 'cookie':
- C.load(v)
- if 'session' in C:
- user = C['session'].value
- c = conn.cursor()
- c.execute("SELECT * FROM users INNER JOIN sessions WHERE users.id = sessions.user_id AND sessions.session_id = ? LIMIT 1", (user,))
- user = c.fetchone()
- if user:
- return 200,H,"you are user %s" % (user[1],)
- return 200,H,'no user specified'
- def generate_session_id(user):
- """
- Generate a unique session ID based on the user name with the given
- site-specific secret. How secure is this, really?
- """
- salt = secret[:2]
- return crypt.crypt(user + str(random.random()), salt)
- def auto_complete_actor(H,G,P):
- #print (P['info'][0],)
- actor = P['info'][0]
- actor = actor+'%'
- #print (actor,)
- cr = conn.cursor()
- cr.execute("SELECT actorname FROM actor2actorid WHERE actor2actorid.actorname LIKE ?", (actor,))
- x = cr.fetchall()
- #print x
- results = ''
- if x:
- count = 0
- for item in x:
- if count>50:
- break
- (g,) = item
- results+=g
- results+='<br/>'
- count = count+1
- else:
- results = "..."
- results+='<li onClick="fill1(\''+g+'\');">'+g+'</li>'
- return 200, [], results
- def auto_complete_actress(H,G,P):
- #print (P['info'][0],)
- actress = P['info'][0]
- actress = actress+'%'
- #print (actress,)
- cr = conn.cursor()
- cr.execute("SELECT actressname FROM actress2actressid WHERE actress2actressid.actressname LIKE ?", (actress,))
- x = cr.fetchall()
- #print x
- results = ''
- if x:
- count = 0
- for item in x:
- if count>50:
- break
- (g,) = item
- results+=g
- results+='<br/>'
- count = count+1
- else:
- results = "..."
- results+='<li onClick="fill2(\''+g+'\');">'+g+'</li>'
- return 200, [], results
- def movies_search_pair(H,G,P):
- actor = actress = ''
- if P:
- actor = P['actor'][0]
- actress = P['actress'][0]
- c = conn.cursor()
- returnstring = ''
- returnstring += "Actor: "
- returnstring +=actor
- returnstring += '\n'
- returnstring += 'and'
- returnstring += '\n'
- returnstring +="Actress: "
- returnstring += actress
- returnstring += '\n'
- returnstring += '\n'
- returnstring += "Were in:"
- returnstring += '\n'
- c.execute("SELECT moviename FROM movie2movieid \
- INNER JOIN actorid2movieid ON actorid2movieid.movieid = movie2movieid.movieid \
- INNER JOIN actressid2movieid ON actressid2movieid.movieid = movie2movieid.movieid \
- INNER JOIN actor2actorid ON actor2actorid.actorid = actorid2movieid.actorid \
- INNER JOIN actress2actressid ON actress2actressid.actressid = actressid2movieid.actressid \
- WHERE (actress2actressid.actressname LIKE ? and actor2actorid.actorname LIKE ?)", (actress, actor))
- #print actor, "and", actress
- x = c.fetchall()
- #print x
- if x:
- for item in x:
- (g,) = item
- returnstring+=g
- returnstring+='\n'
- else:
- returnstring += "No Movies Found"
- return 200, [], returnstring
- def files(request,path,H,G,P):
- temp = path
- content = {'jpg':'Content-Type image/jpeg', 'html':'Content-Type text/html','txt':'Content-Type text/plain','htm':'Content-Type text/htm', 'css':'Content-Type text/css', 'js':'Content-Type text/javascript', 'png':'Content-Type image/png'}
- fp = open(path, 'rb')
- data = fp.read()
- fp.close()
- ext = path[path.rfind('.')+1:]
- temp = content[ext]
- (a,b) = temp.split(' ')
- return 200, [(a,b)], data
- def blank(request,path,H,G,P):
- temp = path.split('/files')[1]
- path =''
- path = '/files' + temp + '/index.html'
- path = path.lstrip('/')
- ulist = path.split('/')
- WUpath = os.path.join(*ulist)
- currdir = os.path.abspath('./')
- path = os.path.join(currdir,WUpath)
- path = os.path.abspath(path)
- assert path.startswith(currdir)
- fp = open(path, 'rb')
- data = fp.read()
- fp.close()
- return 200, [('Content-Type', 'text/html')], data
- if __name__ == '__main__':
- host = ''
- port = sys.argv[1]
- serve(host, int(port))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement