Advertisement
Guest User

Untitled

a guest
May 28th, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.84 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3.  
  4. import socket
  5. import urlparse
  6. import traceback
  7. import cgi
  8. import httplib
  9. import threading
  10. import sys
  11. import re
  12. import httplib
  13. import os
  14. import Cookie
  15. import sqlite3
  16. import random, crypt
  17.  
  18. conn = sqlite3.connect('webserve-info.db')
  19. # per-site secret; only first two characters are used.
  20. secret = 'ZZ'
  21.  
  22. # initialize random number generator from the system time on import.
  23. random.seed()
  24.  
  25. def add_user(user,pwd):
  26. c = conn.cursor()
  27. c.execute("INSERT INTO users (username, password) VALUES (?,?)", (user,pwd))
  28. conn.commit()
  29.  
  30.  
  31.  
  32. def serve(interface, port):
  33. sock = socket.socket()
  34. sock.bind((interface, port))
  35. sock.listen(10)
  36. while True:
  37. (client_sock, client_address) = sock.accept()
  38. #process = threading.Thread(target=handle_connection, args=(client_sock, client_address))
  39. #process.start()
  40. handle_connection(client_sock, client_address)
  41.  
  42. """
  43. def handle_connection(client_sock, client_address):
  44. full_data = ''
  45. while True:
  46. data = client_sock.recv(1)
  47. full_data += data
  48. if full_data.endswith('\r\n\r\n'):
  49. break
  50. header_lines = full_data.split('\r\n')
  51. method, path, _ = header_lines[0].split()
  52. _, _, path, query, _ = urlparse.urlsplit(path)
  53.  
  54. query = cgi.parse_qs(query)
  55.  
  56. headers = []
  57. for header_line in header_lines[1:]:
  58. headers.append(re.findall(r'(.*?): (.*)', header_line))
  59.  
  60. #print headers, 'HEADERSSSSSSSSSSSSSSSSSSSSSSSSSSS'
  61. post_data = None
  62. if method == 'POST':
  63. length = int(re.findall(r'Content-Length: (\d+)', full_data)[0])
  64. post_data = client_sock.recv(length)
  65. post_data = cgi.parse_qs(post_data)
  66.  
  67. status=data = ''
  68. recvheaders=[]
  69. sheaders=[]
  70. for x in headers:
  71. if x != []:
  72. (a,b) = x[0]
  73. sheaders.append((a,b))
  74.  
  75. try:
  76. status, recvheaders, data = delegate(method, path, sheaders, query, post_data)
  77. except Exception, e: # except everything because apparently ignoring exceptions is great! =P
  78. print e,"MESSAGE"
  79. status, recvheaders, data = 500, [('Content-Type', 'text/html')], '<h1>500 Internal Server Error</h1>'
  80.  
  81.  
  82. #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)
  83. try:
  84. response = "HTTP/1.1 %s %s\r\n" % (status, httplib.responses[status])
  85. except:
  86. status = 500
  87. response = "HTTP/1.1 %s %s\r\n" % (status, httplib.responses[status])
  88.  
  89.  
  90. for (header, val) in recvheaders:
  91. response+='%s: %s\r\n' % (header, val)
  92.  
  93. if data !='':
  94. response+='%s: %s\r\n' % ('content-length', len(data))
  95. response+='\r\n%s' % data
  96.  
  97. #print (response,), "response"
  98. client_sock.sendall(response)
  99. client_sock.close()
  100. """
  101.  
  102.  
  103. def handle_connection(client_sock, client_address):
  104. """
  105. 'handle_connection' is called for each client connection to the server.
  106.  
  107. handle_connection(client_sock, client_address) takes the socket
  108. and client address information returned by 'accept' and handles
  109. exactly one HTTP exchange.
  110.  
  111. 'delegate' is called to process the actual HTTP request.
  112.  
  113. This function returns nothing (a.k.a 'return', a.k.a 'return None').
  114.  
  115. No assumptions are made about the size of the input data; data should
  116. be read until the headers have been completely received. Any data
  117. following that should be parsed as POST data.
  118.  
  119. In case an exception is raised in 'delegate', an HTTP error 500
  120. (internal server error) is returned.
  121.  
  122. 'handle_connection' traps all exceptions.
  123. """
  124. try:
  125. data = ''
  126. try:
  127. while 1:
  128. r = client_sock.recv(4096)
  129. if not r:
  130. break
  131.  
  132. data += r
  133. if '\r\n\r\n' in data:
  134. break
  135. except socket.error:
  136. return
  137.  
  138. assert '\r\n\r\n' in data, data
  139. header_data, post_content = data.split('\r\n\r\n', 1)
  140.  
  141. lines = header_data.splitlines()
  142. (request_type, url, protocol) = lines[0].split()
  143.  
  144. headers = []
  145. for line in lines[1:]:
  146. line = line.strip()
  147. k, v = line.split(':', 1)
  148. v = v.strip()
  149. headers.append((k, v))
  150.  
  151. assert protocol.startswith('HTTP/')
  152.  
  153. urlobj = urlparse.urlsplit(url)
  154. path = urlobj.path
  155. query = urlobj.query
  156.  
  157. get_data = None
  158. if query:
  159. get_data = cgi.parse_qs(query)
  160.  
  161. post_data = None
  162. if request_type == 'POST':
  163. content_length = -1
  164. for k, v in headers:
  165. if k.lower() == 'content-length':
  166. content_length = int(v)
  167. break
  168.  
  169. while len(post_content) < content_length:
  170. remaining = content_length - len(post_content)
  171. post_content += client_sock.recv(remaining)
  172.  
  173. post_data = cgi.parse_qs(post_content)
  174.  
  175. code, headers, content = delegate(request_type, path, headers,
  176. get_data, post_data)
  177. except:
  178. print traceback.format_exc()
  179.  
  180. code = 500
  181. headers = [('Content-type', 'text/html')]
  182. content = 'error'
  183.  
  184. try:
  185. if code in httplib.responses:
  186. status_message = httplib.responses[code]
  187. else:
  188. code = 500
  189. status_message = "server error"
  190. content = "SERVER ERROR"
  191.  
  192. headers = [ '%s: %s\r\n' % (k, v) for k, v in headers ]
  193. headers += [ 'Content-Length: %d\r\n' % (len(content),) ]
  194. headers = "".join(headers)
  195.  
  196. out_data = "HTTP/1.0 %s %s\r\n%s\r\n%s" % (code, status_message,
  197. headers, content)
  198.  
  199. client_sock.sendall(out_data)
  200. client_sock.close()
  201. except socket.error:
  202. pass
  203.  
  204. return
  205.  
  206. def delegate(request_type, path, received_headers, GET_data, POST_data = None):
  207. funboy = path
  208. #if 'files' not in path:
  209. path = 'files/' + path
  210. path = path.lstrip('/')
  211. ulist = path.split('/')
  212. WUpath = os.path.join(*ulist)
  213. currdir = os.path.abspath('./')
  214. path = os.path.join(currdir, WUpath)
  215. path = os.path.abspath(path)
  216.  
  217. assert path.startswith(currdir)
  218.  
  219.  
  220. go = funboy[1:].replace('/','_')
  221. tcheck = go.split('_')[0]
  222.  
  223.  
  224. if go in globals():
  225. return globals()[go](received_headers, GET_data, POST_data)
  226. elif os.path.exists(path):
  227. if not os.path.isfile(path):
  228. return blank(request_type,path,received_headers,GET_data,POST_data)
  229. elif os.path.isfile(path):
  230. return files(request_type,path,received_headers,GET_data,POST_data)
  231. elif tcheck == 'test':
  232. return default(received_headers, GET_data, POST_data,path)
  233.  
  234. return 404, [],'<h1> path not found</h1>'
  235.  
  236. def default(received_headers, GET_data, POST_data,path):
  237. data = 'hello, %s' % path
  238. head = []
  239. for request_data, name in ((GET_data, 'get_data:'), (POST_data, 'post_data:')):
  240. if request_data:
  241. data += " %s" % name
  242. for key in request_data:
  243. for val in request_data[key]:
  244. data += " key=%s; value=%s;" % (key, val)
  245.  
  246. head.append(('Content-Type', 'text/html'))
  247.  
  248. return 200, head, data
  249.  
  250. def auth_login(H,G,P): #(Headers, Get_DATA, POST_DATA)
  251. #accounts = [('test','test'),('test2','testy')]
  252. header = []
  253. #checkconn = sqlite3.connect('webserve-info.db')
  254. c = conn.cursor()
  255.  
  256. try:
  257. if P['username'] and P['password']:
  258. username = P['username'][0]
  259. password = P['password'][0]
  260. except Exception, g:
  261. return 200,[], '<h1> %s not provided </h1>' % (g)
  262.  
  263.  
  264. c.execute("SELECT id FROM users WHERE username=? AND password = ?",(username,password))
  265. accounts = c.fetchone()
  266.  
  267. #print (accounts,)
  268.  
  269. if accounts:
  270. hashv = generate_session_id(username)
  271. c.execute("INSERT INTO sessions (user_id,session_id) VALUES (?,?)",(accounts[0],hashv))
  272. conn.commit()
  273. C = Cookie.SimpleCookie()
  274. C['session'] = hashv
  275. x = C.output()
  276. x += '; Path=/'
  277. header.insert(len(header), x.split(': ',1))
  278. return 200,header,'<h4>Login Succesful!</h4>'
  279.  
  280.  
  281. return 401,[],'<h1> Unauthorized Access</h1>'
  282.  
  283. def auth_jslogin(H,G,P): #(Headers, Get_DATA, POST_DATA)
  284. #accounts = [('test','test'),('test2','testy')]
  285. header = []
  286. #checkconn = sqlite3.connect('webserve-info.db')
  287. c = conn.cursor()
  288.  
  289. try:
  290. if P['username'] and P['password']:
  291. username = P['username'][0]
  292. password = P['password'][0]
  293. except Exception, g:
  294. return 200,[], '<h1> %s not provided </h1>' % (g)
  295.  
  296.  
  297. c.execute("SELECT id FROM users WHERE username=? AND password = ?",(username,password))
  298. accounts = c.fetchone()
  299.  
  300. #print (accounts,)
  301.  
  302. if accounts:
  303. hashv = generate_session_id(username)
  304. c.execute("INSERT INTO sessions (user_id,session_id) VALUES (?,?)",(accounts[0],hashv))
  305. conn.commit()
  306. return 200, [], hashv
  307.  
  308. return 200, [], 'Login Failed!'
  309.  
  310. def auth_logout(H,G,P):
  311. header = []
  312. C = Cookie.SimpleCookie()
  313. for (k, v) in H:
  314. if k.lower() == 'cookie':
  315. C.load(v)
  316.  
  317. c = conn.cursor()
  318. c.execute("""DELETE FROM sessions WHERE session_id = ?""", (C['session'].value,))
  319.  
  320. C['session'] = ''
  321. x = C.output()
  322. x += '; Path=/'
  323.  
  324. header.insert(len(header), x.split(': ',1))
  325. return 200,header,'<h4> Logout Succesful! </h4>'
  326.  
  327.  
  328. def auth_print(H,G,P):
  329. user=''
  330. if H:
  331. C = Cookie.SimpleCookie()
  332. for (k,v) in H:
  333. if k.lower() == 'cookie':
  334. C.load(v)
  335.  
  336. if 'session' in C:
  337. user = C['session'].value
  338.  
  339. c = conn.cursor()
  340. c.execute("SELECT * FROM users INNER JOIN sessions WHERE users.id = sessions.user_id AND sessions.session_id = ? LIMIT 1", (user,))
  341. user = c.fetchone()
  342.  
  343. if user:
  344. return 200,H,"you are user %s" % (user[1],)
  345.  
  346. return 200,H,'no user specified'
  347.  
  348. def generate_session_id(user):
  349. """
  350. Generate a unique session ID based on the user name with the given
  351. site-specific secret. How secure is this, really?
  352. """
  353. salt = secret[:2]
  354. return crypt.crypt(user + str(random.random()), salt)
  355.  
  356.  
  357.  
  358. def auto_complete_actor(H,G,P):
  359.  
  360. #print (P['info'][0],)
  361.  
  362. actor = P['info'][0]
  363. actor = actor+'%'
  364.  
  365. #print (actor,)
  366. cr = conn.cursor()
  367. cr.execute("SELECT actorname FROM actor2actorid WHERE actor2actorid.actorname LIKE ?", (actor,))
  368.  
  369. x = cr.fetchall()
  370. #print x
  371. results = ''
  372. if x:
  373. count = 0
  374. for item in x:
  375. if count>50:
  376. break
  377. (g,) = item
  378. results+=g
  379. results+='<br/>'
  380. count = count+1
  381. else:
  382. results = "..."
  383.  
  384. results+='<li onClick="fill1(\''+g+'\');">'+g+'</li>'
  385.  
  386. return 200, [], results
  387.  
  388.  
  389. def auto_complete_actress(H,G,P):
  390.  
  391. #print (P['info'][0],)
  392.  
  393. actress = P['info'][0]
  394. actress = actress+'%'
  395.  
  396. #print (actress,)
  397. cr = conn.cursor()
  398. cr.execute("SELECT actressname FROM actress2actressid WHERE actress2actressid.actressname LIKE ?", (actress,))
  399.  
  400. x = cr.fetchall()
  401. #print x
  402. results = ''
  403.  
  404. if x:
  405. count = 0
  406. for item in x:
  407. if count>50:
  408. break
  409. (g,) = item
  410. results+=g
  411. results+='<br/>'
  412. count = count+1
  413. else:
  414. results = "..."
  415.  
  416. results+='<li onClick="fill2(\''+g+'\');">'+g+'</li>'
  417.  
  418. return 200, [], results
  419.  
  420.  
  421.  
  422. def movies_search_pair(H,G,P):
  423.  
  424. actor = actress = ''
  425.  
  426. if P:
  427. actor = P['actor'][0]
  428. actress = P['actress'][0]
  429.  
  430. c = conn.cursor()
  431.  
  432.  
  433. returnstring = ''
  434. returnstring += "Actor: "
  435. returnstring +=actor
  436. returnstring += '\n'
  437. returnstring += 'and'
  438. returnstring += '\n'
  439. returnstring +="Actress: "
  440. returnstring += actress
  441. returnstring += '\n'
  442. returnstring += '\n'
  443. returnstring += "Were in:"
  444. returnstring += '\n'
  445.  
  446.  
  447. c.execute("SELECT moviename FROM movie2movieid \
  448. INNER JOIN actorid2movieid ON actorid2movieid.movieid = movie2movieid.movieid \
  449. INNER JOIN actressid2movieid ON actressid2movieid.movieid = movie2movieid.movieid \
  450. INNER JOIN actor2actorid ON actor2actorid.actorid = actorid2movieid.actorid \
  451. INNER JOIN actress2actressid ON actress2actressid.actressid = actressid2movieid.actressid \
  452. WHERE (actress2actressid.actressname LIKE ? and actor2actorid.actorname LIKE ?)", (actress, actor))
  453.  
  454.  
  455. #print actor, "and", actress
  456. x = c.fetchall()
  457. #print x
  458. if x:
  459. for item in x:
  460. (g,) = item
  461. returnstring+=g
  462. returnstring+='\n'
  463. else:
  464. returnstring += "No Movies Found"
  465.  
  466.  
  467.  
  468. return 200, [], returnstring
  469.  
  470.  
  471.  
  472. def files(request,path,H,G,P):
  473. temp = path
  474. 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'}
  475.  
  476. fp = open(path, 'rb')
  477. data = fp.read()
  478. fp.close()
  479.  
  480. ext = path[path.rfind('.')+1:]
  481.  
  482. temp = content[ext]
  483. (a,b) = temp.split(' ')
  484.  
  485. return 200, [(a,b)], data
  486.  
  487. def blank(request,path,H,G,P):
  488. temp = path.split('/files')[1]
  489. path =''
  490. path = '/files' + temp + '/index.html'
  491.  
  492.  
  493. path = path.lstrip('/')
  494. ulist = path.split('/')
  495. WUpath = os.path.join(*ulist)
  496. currdir = os.path.abspath('./')
  497. path = os.path.join(currdir,WUpath)
  498. path = os.path.abspath(path)
  499.  
  500. assert path.startswith(currdir)
  501.  
  502. fp = open(path, 'rb')
  503. data = fp.read()
  504. fp.close()
  505.  
  506. return 200, [('Content-Type', 'text/html')], data
  507.  
  508.  
  509.  
  510. if __name__ == '__main__':
  511. host = ''
  512. port = sys.argv[1]
  513. serve(host, int(port))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement