Commits

clach04 committed c38309e Draft Merge

merged py2.7/wget support with threaded mixin.

Comments (0)

Files changed (1)

 
 import sys, os, errno, socket, getopt, commands, tempfile
 import cgi, urllib, urlparse, BaseHTTPServer
+from SocketServer import ThreadingMixIn
 try:
     import readline
 except ImportError:
 
 maxdownloads = 1
 TM = object
-cpid = -1
 compressed = 'gz'
 upload = False
 
 
    return candidates[0]
 
-
-# our own HTTP server class, fixing up a change in python 2.7
-# since we do our fork() in the request handler
-# the server must not shutdown() the socket.
-
-class ForkingHTTPServer (BaseHTTPServer.HTTPServer):
-   def process_request(self, request, client_address):
-      self.finish_request (request, client_address)
-      self.close_request (request)
-
-
 # Main class implementing an HTTP-Requesthandler, that serves just a single
 # file and redirects all other requests to this file (this passes the actual
 # filename to the client).
          self.send_error (501, "Unsupported method (POST)")
          return
       
+      maxdownloads -= 1
+
+      if maxdownloads < 1:
+         httpd.shutdown()
+
       # taken from
       # http://mail.python.org/pipermail/python-list/2006-September/402441.html
 
       self.end_headers ()
       self.wfile.write (txt)
 
-      maxdownloads -= 1
-
       return
       
 
    def do_GET (self):
-      global maxdownloads, cpid, compressed, upload
+      global maxdownloads, compressed, upload
 
       # Form for uploading a file
       if upload:
 
       maxdownloads -= 1
 
-      # let a separate process handle the actual download, so that
-      # multiple downloads can happen simultaneously.
+      if maxdownloads < 1:
+         httpd.shutdown()
 
-      cpid = os.fork ()
+      type = None
+      
+      if os.path.isfile (self.filename):
+         type = "file"
+      elif os.path.isdir (self.filename):
+         type = "dir"
 
-      if cpid == 0:
-         # Child process
-         child = None
-         type = None
-         
-         if os.path.isfile (self.filename):
-            type = "file"
-         elif os.path.isdir (self.filename):
-            type = "dir"
+      if not type:
+         print >> sys.stderr, "can only serve files or directories. Aborting."
+         sys.exit (1)
 
-         if not type:
-            print >> sys.stderr, "can only serve files or directories. Aborting."
-            sys.exit (1)
+      self.send_response (200)
+      self.send_header ("Content-Type", "application/octet-stream")
+      self.send_header ("Content-Disposition", "attachment;filename=%s" % urllib.quote (os.path.basename (self.filename)))
+      if os.path.isfile (self.filename):
+         self.send_header ("Content-Length",
+                           os.path.getsize (self.filename))
+      self.end_headers ()
 
-         self.send_response (200)
-         self.send_header ("Content-Type", "application/octet-stream")
-         self.send_header ("Content-Disposition", "attachment;filename=%s" % urllib.quote (os.path.basename (self.filename)))
-         if os.path.isfile (self.filename):
-            self.send_header ("Content-Length",
-                              os.path.getsize (self.filename))
-         self.end_headers ()
+      try:
+         if type == "file":
+            datafile = file (self.filename)
+            shutil.copyfileobj (datafile, self.wfile)
+            datafile.close ()
+         elif type == "dir":
+            if compressed == 'zip':
+               ezfile = EvilZipStreamWrapper (self.wfile)
+               zfile = zipfile.ZipFile (ezfile, 'w', zipfile.ZIP_DEFLATED)
+               stripoff = os.path.dirname (self.filename) + os.sep
 
-         try:
-            if type == "file":
-               datafile = file (self.filename)
-               shutil.copyfileobj (datafile, self.wfile)
-               datafile.close ()
-            elif type == "dir":
-               if compressed == 'zip':
-                  ezfile = EvilZipStreamWrapper (self.wfile)
-                  zfile = zipfile.ZipFile (ezfile, 'w', zipfile.ZIP_DEFLATED)
-                  stripoff = os.path.dirname (self.filename) + os.sep
+               for root, dirs, files in os.walk (self.filename):
+                  for f in files:
+                     filename = os.path.join (root, f)
+                     if filename[:len (stripoff)] != stripoff:
+                        raise RuntimeException, "invalid filename assumptions, please report!"
+                     zfile.write (filename, filename[len (stripoff):])
+               zfile.close ()
+            else:
+               tfile = tarfile.open (mode=('w|' + compressed),
+                                     fileobj=self.wfile)
+               tfile.add (self.filename,
+                          arcname=os.path.basename(self.filename))
+               tfile.close ()
+      except Exception, e:
+         print e
+         print >>sys.stderr, "Connection broke. Aborting"
 
-                  for root, dirs, files in os.walk (self.filename):
-                     for f in files:
-                        filename = os.path.join (root, f)
-                        if filename[:len (stripoff)] != stripoff:
-                           raise RuntimeException, "invalid filename assumptions, please report!"
-                        zfile.write (filename, filename[len (stripoff):])
-                  zfile.close ()
-               else:
-                  tfile = tarfile.open (mode=('w|' + compressed),
-                                        fileobj=self.wfile)
-                  tfile.add (self.filename,
-                             arcname=os.path.basename (self.filename))
-                  tfile.close ()
-         except Exception, e:
-            print e
-            print >>sys.stderr, "Connection broke. Aborting"
+
+class ThreadedHTTPServer(ThreadingMixIn, BaseHTTPServer.HTTPServer):
+   """Handle requests in a separate thread"""
 
 
 def serve_files (filename, maxdown = 1, ip_addr = '', port = 8080):
-   global maxdownloads
+   global maxdownloads, httpd
 
    maxdownloads = maxdown
 
    FileServHTTPRequestHandler.filename = filename
 
    try:
-      httpd = ForkingHTTPServer ((ip_addr, port), FileServHTTPRequestHandler)
+      httpd = ThreadedHTTPServer ((ip_addr, port), FileServHTTPRequestHandler)
    except socket.error:
       print >>sys.stderr, "cannot bind to IP address '%s' port %d" % (ip_addr, port)
       sys.exit (1)
 
       print "Now serving on %s" % location
 
-   while cpid != 0 and maxdownloads > 0:
-      httpd.handle_request ()
+   httpd.serve_forever ()
 
 
 
 
    serve_files (filename, maxdown, ip_addr, port)
 
-   # wait for child processes to terminate
-   if cpid != 0:
-      try:
-         while 1:
-            os.wait ()
-      except OSError:
-         pass
-
 
 
 if __name__=='__main__':