home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_308 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  8.2 KB  |  329 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __version__ = '0.4'
  5. __all__ = [
  6.     'CGIHTTPRequestHandler']
  7. import os
  8. import sys
  9. import urllib
  10. import BaseHTTPServer
  11. import SimpleHTTPServer
  12. import select
  13.  
  14. class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
  15.     have_fork = hasattr(os, 'fork')
  16.     have_popen2 = hasattr(os, 'popen2')
  17.     have_popen3 = hasattr(os, 'popen3')
  18.     rbufsize = 0
  19.     
  20.     def do_POST(self):
  21.         if self.is_cgi():
  22.             self.run_cgi()
  23.         else:
  24.             self.send_error(501, 'Can only POST to CGI scripts')
  25.  
  26.     
  27.     def send_head(self):
  28.         if self.is_cgi():
  29.             return self.run_cgi()
  30.         return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)
  31.  
  32.     
  33.     def is_cgi(self):
  34.         path = self.path
  35.         for x in self.cgi_directories:
  36.             i = len(x)
  37.             if path[:i] == x:
  38.                 if not path[i:] or path[i] == '/':
  39.                     self.cgi_info = (path[:i], path[i + 1:])
  40.                     return True
  41.         return False
  42.  
  43.     cgi_directories = [
  44.         '/cgi-bin',
  45.         '/htbin']
  46.     
  47.     def is_executable(self, path):
  48.         return executable(path)
  49.  
  50.     
  51.     def is_python(self, path):
  52.         (head, tail) = os.path.splitext(path)
  53.         return tail.lower() in ('.py', '.pyw')
  54.  
  55.     
  56.     def run_cgi(self):
  57.         path = self.path
  58.         (dir, rest) = self.cgi_info
  59.         i = path.find('/', len(dir) + 1)
  60.         while i >= 0:
  61.             nextdir = path[:i]
  62.             nextrest = path[i + 1:]
  63.             scriptdir = self.translate_path(nextdir)
  64.             if os.path.isdir(scriptdir):
  65.                 dir = nextdir
  66.                 rest = nextrest
  67.                 i = path.find('/', len(dir) + 1)
  68.                 continue
  69.             break
  70.         i = rest.rfind('?')
  71.         if i >= 0:
  72.             rest = rest[:i]
  73.             query = rest[i + 1:]
  74.         else:
  75.             query = ''
  76.         i = rest.find('/')
  77.         if i >= 0:
  78.             script = rest[:i]
  79.             rest = rest[i:]
  80.         else:
  81.             script = rest
  82.             rest = ''
  83.         scriptname = dir + '/' + script
  84.         scriptfile = self.translate_path(scriptname)
  85.         if not os.path.exists(scriptfile):
  86.             self.send_error(404, 'No such CGI script (%r)' % scriptname)
  87.             return None
  88.         if not os.path.isfile(scriptfile):
  89.             self.send_error(403, 'CGI script is not a plain file (%r)' % scriptname)
  90.             return None
  91.         ispy = self.is_python(scriptname)
  92.         env = { }
  93.         env['SERVER_SOFTWARE'] = self.version_string()
  94.         env['SERVER_NAME'] = self.server.server_name
  95.         env['GATEWAY_INTERFACE'] = 'CGI/1.1'
  96.         env['SERVER_PROTOCOL'] = self.protocol_version
  97.         env['SERVER_PORT'] = str(self.server.server_port)
  98.         env['REQUEST_METHOD'] = self.command
  99.         uqrest = urllib.unquote(rest)
  100.         env['PATH_INFO'] = uqrest
  101.         env['PATH_TRANSLATED'] = self.translate_path(uqrest)
  102.         env['SCRIPT_NAME'] = scriptname
  103.         host = self.address_string()
  104.         if host != self.client_address[0]:
  105.             env['REMOTE_HOST'] = host
  106.         
  107.         env['REMOTE_ADDR'] = self.client_address[0]
  108.         authorization = self.headers.getheader('authorization')
  109.         if authorization:
  110.             authorization = authorization.split()
  111.             if len(authorization) == 2:
  112.                 import base64
  113.                 import binascii
  114.                 env['AUTH_TYPE'] = authorization[0]
  115.                 if authorization[0].lower() == 'basic':
  116.                     
  117.                     try:
  118.                         authorization = base64.decodestring(authorization[1])
  119.                     except binascii.Error:
  120.                         pass
  121.  
  122.                     authorization = authorization.split(':')
  123.                     if len(authorization) == 2:
  124.                         env['REMOTE_USER'] = authorization[0]
  125.                     
  126.                 
  127.             
  128.         
  129.         if self.headers.typeheader is None:
  130.             env['CONTENT_TYPE'] = self.headers.type
  131.         else:
  132.             env['CONTENT_TYPE'] = self.headers.typeheader
  133.         length = self.headers.getheader('content-length')
  134.         if length:
  135.             env['CONTENT_LENGTH'] = length
  136.         
  137.         referer = self.headers.getheader('referer')
  138.         if referer:
  139.             env['HTTP_REFERER'] = referer
  140.         
  141.         accept = []
  142.         for line in self.headers.getallmatchingheaders('accept'):
  143.             if line[:1] in '\t\n\r ':
  144.                 accept.append(line.strip())
  145.                 continue
  146.             accept = accept + line[7:].split(',')
  147.         
  148.         env['HTTP_ACCEPT'] = ','.join(accept)
  149.         ua = self.headers.getheader('user-agent')
  150.         if ua:
  151.             env['HTTP_USER_AGENT'] = ua
  152.         
  153.         co = filter(None, self.headers.getheaders('cookie'))
  154.         if co:
  155.             env['HTTP_COOKIE'] = ', '.join(co)
  156.         
  157.         for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH', 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
  158.             env.setdefault(k, '')
  159.         
  160.         os.environ.update(env)
  161.         self.send_response(200, 'Script output follows')
  162.         decoded_query = query.replace('+', ' ')
  163.         if self.have_fork:
  164.             args = [
  165.                 script]
  166.             if '=' not in decoded_query:
  167.                 args.append(decoded_query)
  168.             
  169.             nobody = nobody_uid()
  170.             self.wfile.flush()
  171.             pid = os.fork()
  172.             if pid != 0:
  173.                 (pid, sts) = os.waitpid(pid, 0)
  174.                 while select.select([
  175.                     self.rfile], [], [], 0)[0]:
  176.                     if not self.rfile.read(1):
  177.                         break
  178.                         continue
  179.                 if sts:
  180.                     self.log_error('CGI script exit status %#x', sts)
  181.                 
  182.                 return None
  183.             
  184.             try:
  185.                 
  186.                 try:
  187.                     os.setuid(nobody)
  188.                 except os.error:
  189.                     pid != 0
  190.                     pid != 0
  191.                 except:
  192.                     pid != 0
  193.  
  194.                 os.dup2(self.rfile.fileno(), 0)
  195.                 os.dup2(self.wfile.fileno(), 1)
  196.                 os.execve(scriptfile, args, os.environ)
  197.             self.server.handle_error(self.request, self.client_address)
  198.             os._exit(127)
  199.  
  200.         elif self.have_popen2 or self.have_popen3:
  201.             import shutil
  202.             if self.have_popen3:
  203.                 popenx = os.popen3
  204.             else:
  205.                 popenx = os.popen2
  206.             cmdline = scriptfile
  207.             if self.is_python(scriptfile):
  208.                 interp = sys.executable
  209.                 if interp.lower().endswith('w.exe'):
  210.                     interp = interp[:-5] + interp[-4:]
  211.                 
  212.                 cmdline = '%s -u %s' % (interp, cmdline)
  213.             
  214.             if '=' not in query and '"' not in query:
  215.                 cmdline = '%s "%s"' % (cmdline, query)
  216.             
  217.             self.log_message('command: %s', cmdline)
  218.             
  219.             try:
  220.                 nbytes = int(length)
  221.             except (TypeError, ValueError):
  222.                 nbytes = 0
  223.  
  224.             files = popenx(cmdline, 'b')
  225.             fi = files[0]
  226.             fo = files[1]
  227.             if self.have_popen3:
  228.                 fe = files[2]
  229.             
  230.             if self.command.lower() == 'post' and nbytes > 0:
  231.                 data = self.rfile.read(nbytes)
  232.                 fi.write(data)
  233.             
  234.             while select.select([
  235.                 self.rfile._sock], [], [], 0)[0]:
  236.                 if not self.rfile._sock.recv(1):
  237.                     break
  238.                     continue
  239.             fi.close()
  240.             shutil.copyfileobj(fo, self.wfile)
  241.             if self.have_popen3:
  242.                 errors = fe.read()
  243.                 fe.close()
  244.                 if errors:
  245.                     self.log_error('%s', errors)
  246.                 
  247.             
  248.             sts = fo.close()
  249.             if sts:
  250.                 self.log_error('CGI script exit status %#x', sts)
  251.             else:
  252.                 self.log_message('CGI script exited OK')
  253.         else:
  254.             save_argv = sys.argv
  255.             save_stdin = sys.stdin
  256.             save_stdout = sys.stdout
  257.             save_stderr = sys.stderr
  258.             
  259.             try:
  260.                 save_cwd = os.getcwd()
  261.                 
  262.                 try:
  263.                     sys.argv = [
  264.                         scriptfile]
  265.                     if '=' not in decoded_query:
  266.                         sys.argv.append(decoded_query)
  267.                     
  268.                     sys.stdout = self.wfile
  269.                     sys.stdin = self.rfile
  270.                     execfile(scriptfile, {
  271.                         '__name__': '__main__' })
  272.                 finally:
  273.                     sys.argv = save_argv
  274.                     sys.stdin = save_stdin
  275.                     sys.stdout = save_stdout
  276.                     sys.stderr = save_stderr
  277.                     os.chdir(save_cwd)
  278.  
  279.             except SystemExit:
  280.                 sts = None
  281.                 self.log_error('CGI script exit status %s', str(sts))
  282.  
  283.             self.log_message('CGI script exited OK')
  284.  
  285.  
  286. nobody = None
  287.  
  288. def nobody_uid():
  289.     global nobody, nobody
  290.     if nobody:
  291.         return nobody
  292.     
  293.     try:
  294.         import pwd
  295.     except ImportError:
  296.         nobody
  297.         nobody
  298.         return -1
  299.  
  300.     
  301.     try:
  302.         nobody = pwd.getpwnam('nobody')[2]
  303.     except KeyError:
  304.         nobody
  305.         nobody
  306.         nobody = 1 + max(map((lambda x: x[2]), pwd.getpwall()))
  307.     except:
  308.         nobody
  309.  
  310.     return nobody
  311.  
  312.  
  313. def executable(path):
  314.     
  315.     try:
  316.         st = os.stat(path)
  317.     except os.error:
  318.         return False
  319.  
  320.     return st.st_mode & 73 != 0
  321.  
  322.  
  323. def test(HandlerClass = CGIHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer):
  324.     SimpleHTTPServer.test(HandlerClass, ServerClass)
  325.  
  326. if __name__ == '__main__':
  327.     test()
  328.  
  329.