fork(3) download
  1. """Simple HTTP Server.
  2.  
  3. This module builds on BaseHTTPServer by implementing the standard GET
  4. and HEAD requests in a fairly straightforward manner.
  5.  
  6. """
  7.  
  8.  
  9. __version__ = "0.6"
  10.  
  11. __all__ = ["SimpleHTTPRequestHandler"]
  12.  
  13. import os
  14. import posixpath
  15. import BaseHTTPServer
  16. import urllib
  17. import cgi
  18. import sys
  19. import shutil
  20. import mimetypes
  21. try:
  22. from cStringIO import StringIO
  23. except ImportError:
  24. from StringIO import StringIO
  25. DIR=''
  26. prune_length=0
  27. def set_directory(d):
  28. global DIR,prune_length
  29. DIR=d
  30. prune_length=len(DIR)
  31. files=[]
  32.  
  33. class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  34.  
  35. """Simple HTTP request handler with GET and HEAD commands.
  36.  
  37. This serves files from the current directory and any of its
  38. subdirectories. The MIME type for files is determined by
  39. calling the .guess_type() method.
  40.  
  41. The GET and HEAD requests are identical except that the HEAD
  42. request omits the actual contents of the file.
  43.  
  44. """
  45.  
  46. server_version = "SimpleHTTP/" + __version__
  47.  
  48. def do_GET(self):
  49. """Serve a GET request."""
  50. f = self.send_head()
  51. if f:
  52. self.copyfile(f, self.wfile)
  53. f.close()
  54.  
  55. def do_HEAD(self):
  56. """Serve a HEAD request."""
  57. f = self.send_head()
  58. if f:
  59. f.close()
  60.  
  61. def send_head(self):
  62. """Common code for GET and HEAD commands.
  63.  
  64. This sends the response code and MIME headers.
  65.  
  66. Return value is either a file object (which has to be copied
  67. to the outputfile by the caller unless the command was HEAD,
  68. and must be closed by the caller under all circumstances), or
  69. None, in which case the caller has nothing further to do.
  70.  
  71. """
  72. #print self.path
  73. path = self.tanmay(self.path)
  74. self.tanmay(self.path)
  75. #print path
  76. f = None
  77. if os.path.isdir(path):
  78. if not self.path.endswith('/'):
  79. print 'tanmau'
  80. # redirect browser - doing basically what apache does
  81. self.send_response(301)
  82. self.send_header("Location", self.path + "/")
  83. self.end_headers()
  84. return None
  85. for index in "index.html", "index.htm":
  86. index = os.path.join(path, index)
  87. if os.path.exists(index):
  88. path = index
  89. break
  90. else:
  91. return self.list_directory(path)
  92. ctype = self.guess_type(path)
  93. try:
  94. # Always read in binary mode. Opening files in text mode may cause
  95. # newline translations, making the actual size of the content
  96. # transmitted *less* than the content-length!
  97. f = open(path, 'rb')
  98. except IOError:
  99. self.send_error(404, "File not found")
  100. return None
  101. self.send_response(200)
  102. self.send_header("Content-type", ctype)
  103. print ctype
  104. fs = os.fstat(f.fileno())
  105. self.send_header("Content-Length", str(fs[6]))
  106. self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
  107. self.end_headers()
  108. return f
  109.  
  110.  
  111. def list_directory(self, path):
  112. """Helper to produce a directory listing (absent index.html).
  113.  
  114. Return value is either a file object, or None (indicating an
  115. error). In either case, the headers are sent, making the
  116. interface the same as for send_head().
  117.  
  118. """
  119. try:
  120. list = os.listdir(path)
  121. except os.error:
  122. self.send_error(404, "No permission to list directory")
  123. return None
  124. list.sort(key=lambda a: a.lower())
  125. f = StringIO()
  126. displaypath = cgi.escape(urllib.unquote(self.path))
  127. f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
  128. f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath)
  129. f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)
  130. f.write("<hr>\n<ul>\n")
  131. for name in list:
  132. fullname = os.path.join(path, name)
  133. #print '###################'
  134. #print fullname
  135. displayname = linkname = name
  136. # Append / for directories or @ for symbolic links
  137. if os.path.isdir(fullname):
  138. displayname = name + "/"
  139. linkname = name + "/"
  140. if os.path.islink(fullname):
  141. displayname = name + "@"
  142. # Note: a link to a directory displays with @ and links with /
  143. try:
  144. f.write('<li><a href="%s">%s</a>\n'% (urllib.quote(linkname.encode("utf-8")), cgi.escape(displayname)))
  145. #print '<li><a href="%s">%s</a>\n'% (urllib.quote(linkname), cgi.escape(displayname))
  146. except:
  147. #f.write('<li><a href="%s">%s</a>\n'% (linkname, displayname))
  148. #print linkname
  149. continue
  150. f.write("</ul>\n<hr>\n</body>\n</html>\n")
  151. length = f.tell()
  152. f.seek(0)
  153. self.send_response(200)
  154. encoding = sys.getfilesystemencoding()
  155. self.send_header("Content-type", "text/html; charset=%s" % encoding)
  156. self.send_header("Content-Length", str(length))
  157. self.end_headers()
  158. return f
  159. def translate_path(self, path):
  160. """Translate a /-separated PATH to the local filename syntax.
  161.  
  162. Components that mean special things to the local file system
  163. (e.g. drive or directory names) are ignored. (XXX They should
  164. probably be diagnosed.)
  165.  
  166. """
  167. # abandon query parameters
  168. path = path.split('?',1)[0]
  169. path = path.split('#',1)[0]
  170. # Don't forget explicit trailing slash when normalizing. Issue17324
  171. trailing_slash = path.rstrip().endswith('/')
  172. path = posixpath.normpath(urllib.unquote(path))
  173. words = path.split('/')
  174. words = filter(None, words)
  175. path = os.getcwd()
  176. for word in words:
  177. drive, word = os.path.splitdrive(word)
  178. head, word = os.path.split(word)
  179. if word in (os.curdir, os.pardir): continue
  180. path = os.path.join(path, word)
  181. if trailing_slash:
  182. path += '/'
  183. return path
  184. def tanmay(self,p):
  185. x=url=urllib.unquote(p).decode('utf8')
  186. if x.endswith('/'):
  187. y=x[:-1]
  188. y=y.replace('/','\\')
  189. #print '@@@@@@@@@@@@@@@@@@@@@@'
  190. y+='/'
  191. #print True
  192. else:
  193. y=x
  194. y=y.replace('/','\\')
  195. path=DIR+y
  196. #print '@@@@@@@@@@@@@@@@@@@@@@'
  197. return path
  198. def copyfile(self, source, outputfile):
  199. """Copy all data between two file objects.
  200.  
  201. The SOURCE argument is a file object open for reading
  202. (or anything with a read() method) and the DESTINATION
  203. argument is a file object open for writing (or
  204. anything with a write() method).
  205.  
  206. The only reason for overriding this would be to change
  207. the block size or perhaps to replace newlines by CRLF
  208. -- note however that this the default server uses this
  209. to copy binary data as well.
  210.  
  211. """
  212. shutil.copyfileobj(source, outputfile)
  213. def guess_type(self, path):
  214. """Guess the type of a file.
  215.  
  216. Argument is a PATH (a filename).
  217.  
  218. Return value is a string of the form type/subtype,
  219. usable for a MIME Content-type header.
  220.  
  221. The default implementation looks the file's extension
  222. up in the table self.extensions_map, using application/octet-stream
  223. as a default; however it would be permissible (if
  224. slow) to look inside the data to make a better guess.
  225.  
  226. """
  227.  
  228. base, ext = posixpath.splitext(path)
  229. if ext in self.extensions_map:
  230. return self.extensions_map[ext]
  231. ext = ext.lower()
  232. if ext in self.extensions_map:
  233. return self.extensions_map[ext]
  234. else:
  235. return self.extensions_map['']
  236.  
  237. if not mimetypes.inited:
  238. mimetypes.init() # try to read system mime.types
  239. extensions_map = mimetypes.types_map.copy()
  240. extensions_map.update({
  241. '': 'application/octet-stream',
  242. '.mkv': 'octet-stream',
  243. '.avi': 'octet-stream',
  244. '.flv': 'octet-stream',# Default
  245. '.py': 'text/plain',
  246. '.c': 'text/plain',
  247. '.h': 'text/plain',
  248. })
  249.  
  250.  
  251. import os,time
  252. f=open('files.txt','w')
  253. def get_filepaths(directory):
  254. """
  255. This function will generate the file names in a directory
  256. tree by walking the tree either top-down or bottom-up. For each
  257. directory in the tree rooted at directory top (including top itself),
  258. it yields a 3-tuple (dirpath, dirnames, filenames).
  259. """
  260. file_paths = [] # List which will store all of the full filepaths.
  261. global prune_length
  262. print prune_length
  263. # Walk the tree.
  264. for root, directories, files in os.walk(directory):
  265. for filename in files:
  266. # Join the two strings in order to form the full filepath.
  267. filepath = os.path.join(root, filename)
  268. filepath=filepath.replace('\\','/')
  269. filepath=filepath[prune_length:]
  270. file_paths.append((filename,filepath)) # Add it to the list.
  271. print 'sleeping'
  272. time.sleep(2)
  273.  
  274. return file_paths # Self-explanatory.
  275.  
  276.  
  277. def test(HandlerClass = SimpleHTTPRequestHandler,
  278. ServerClass = BaseHTTPServer.HTTPServer):
  279. BaseHTTPServer.test(HandlerClass, ServerClass)
  280.  
  281.  
  282.  
  283.  
  284. '''
  285. '''
  286.  
  287. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  288. import os,urllib,urllib2
  289. from easygui import *
  290. import socket
  291. '''
  292. print([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])
  293.  
  294. '''
  295. ip=''
  296. try:
  297. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  298. s.connect(("Gmail",80))
  299. ip=s.getsockname()[0]
  300. s.close()
  301. except:
  302. print 'Internet Connectivity issues'
  303. pass
  304. nick=raw_input('Enter your nick\n')
  305. msgbox("Select the directory which you want to share")
  306. d=diropenbox()
  307. #print d
  308. def hello():
  309. global nick
  310. while True:
  311. if DIR!='':
  312. x=get_filepaths(DIR)
  313. print 'done'
  314. urllib2.urlopen('http://localhost:3000/upload/'+nick+'/',str(x))
  315. break
  316. else:
  317. print 'doing'
  318. continue
  319. def run():
  320. global ip, nick
  321. print('http server is starting...')
  322.  
  323. #ip and port of server
  324. #by default http server port is 80
  325. server_address = ('', 80)
  326. set_directory(d)
  327. httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
  328. sa = httpd.socket.getsockname()
  329. print "Serving HTTP on", sa[0], "port", sa[1], "..."
  330. try:
  331. x=urllib2.urlopen('http://localhost:3000/nick/'+nick+'/'+ip)
  332. x=x.read()
  333. print x
  334. except:
  335. print 'not found'
  336. httpd.serve_forever()
  337.  
  338. def main():
  339. from threading import Thread
  340.  
  341. # Second thread will print the hello message. Starting as a daemon means
  342. # the thread will not prevent the process from exiting.
  343. t = Thread(target=hello)
  344. t.daemon = True
  345. t.start()
  346. # Main thread will read and process input
  347. run()
  348. if __name__ == '__main__':
  349. main()
  350.  
Runtime error #stdin #stdout #stderr 0.05s 13088KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "prog.py", line 252, in <module>
IOError: [Errno 13] Permission denied: 'files.txt'