Ejemplo n.º 1
0
 def do_POST(self): # override
 
     # Check for Basic HTTP authentication
     if self.checkAuthorization():
         SimpleXMLRPCRequestHandler.do_POST(self)
     else:
         self.report_401()
Ejemplo n.º 2
0
    def do_POST(self):  # override

        # Check for Basic HTTP authentication
        if self.checkAuthorization():
            SimpleXMLRPCRequestHandler.do_POST(self)
        else:
            self.report_401()
 def do_POST(self):
     """Handles the HTTPS POST request."""
     SimpleXMLRPCRequestHandler.do_POST(self)
     try:
         # shut down the connection
         self.connection.shutdown()
     except:
         pass
Ejemplo n.º 4
0
 def do_POST(self):
     """Handles the HTTPS POST request."""
     SimpleXMLRPCRequestHandler.do_POST(self)
     try:
         # shut down the connection
         self.connection.shutdown()
     except:
         pass
Ejemplo n.º 5
0
    def do_POST(self):
        if self._server.auth_disabled:
            return SimpleXMLRPCRequestHandler.do_POST(self)

        hashfunc = self._server.hashfunc
        nonce = None

        if self.headers.has_key('authorization'):

            attrs = _parse_digest_header(self.headers['authorization'])
            if not attrs:
                _LOGGER.error(
                    "Illegal digest authentication from {host}".format(
                        host=self._client_address))
                self.send_response(400)
                return
            nonce = attrs['nonce']

            store = _persistence.current_persister()
            user = credentials.User.fetch_user(attrs['username'],
                                               protocol='xmlrpc')
            if not user:
                _LOGGER.error("Authentication failed for {user}@{host}".format(
                    user=attrs['username'], host=self._client_address[0]))
                self.send_response(400)
                return

            ha1 = user.password_hash
            ha2 = hashfunc('POST' + ':' + self.rpc_paths[1]).hexdigest()
            if 'qop' in attrs and attrs['qop'] in ('auth', 'auth-int'):
                data = "{nonce}:{nc}:{cnonce}:{qop}:{ha2}".format(
                    nonce=attrs['nonce'],
                    nc=attrs['nc'],
                    cnonce=attrs['cnonce'],
                    qop=attrs['qop'],
                    ha2=ha2)
                reqdigest = hashfunc(ha1 + ':' + data).hexdigest()
            else:
                kd = hashfunc(ha1 + ':' + nonce + ':' + ha2).hexdigest()

            if reqdigest == attrs['response']:
                self._authenticated = self._server.authorize_client(
                    nonce,
                    self._client_address,
                    attrs['username'], attrs['realm'],
                    nc=int(attrs['nc'], 16))
                self._user = user
            else:
                self.send_response(400)
                return

        if not self._authenticated:
            nonce = _digest_nonce(self._server.hashfunc,
                                  self._client_address)
            self.send_authentication(nonce)
            return

        return SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 6
0
    def do_POST(self):
        if self._server.auth_disabled:
            return SimpleXMLRPCRequestHandler.do_POST(self)

        hashfunc = self._server.hashfunc
        nonce = None

        if self.headers.has_key('authorization'):

            attrs = _parse_digest_header(self.headers['authorization'])
            if not attrs:
                _LOGGER.error(
                    "Illegal digest authentication from {host}".format(
                        host=self._client_address))
                self.send_response(400)
                return
            nonce = attrs['nonce']

            store = _persistence.current_persister()
            user = credentials.User.fetch_user(attrs['username'],
                                               protocol='xmlrpc')
            if not user:
                _LOGGER.error("Authentication failed for {user}@{host}".format(
                    user=attrs['username'], host=self._client_address[0]))
                self.send_response(400)
                return

            ha1 = user.password_hash
            ha2 = hashfunc('POST' + ':' + self.rpc_paths[1]).hexdigest()
            if 'qop' in attrs and attrs['qop'] in ('auth', 'auth-int'):
                data = "{nonce}:{nc}:{cnonce}:{qop}:{ha2}".format(
                    nonce=attrs['nonce'],
                    nc=attrs['nc'],
                    cnonce=attrs['cnonce'],
                    qop=attrs['qop'],
                    ha2=ha2)
                reqdigest = hashfunc(ha1 + ':' + data).hexdigest()
            else:
                kd = hashfunc(ha1 + ':' + nonce + ':' + ha2).hexdigest()

            if reqdigest == attrs['response']:
                self._authenticated = self._server.authorize_client(
                    nonce,
                    self._client_address,
                    attrs['username'],
                    attrs['realm'],
                    nc=int(attrs['nc'], 16))
                self._user = user
            else:
                self.send_response(400)
                return

        if not self._authenticated:
            nonce = _digest_nonce(self._server.hashfunc, self._client_address)
            self.send_authentication(nonce)
            return

        return SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 7
0
 def do_POST(self):
     try:
         remote_token = self.headers["Bitbake-token"]
     except:
         remote_token = None
     if remote_token != self.connection_token:
         self.report_503()
     else:
         SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 8
0
    def do_POST(self):
        print("Header::     <<", self.headers, ">>")
        print("RequestLine: <<", self.requestline, ">>")

        size = int(self.headers.get('content-length', 0))

        if size >= self.MAXSIZE:
            self.send_error(400, "Bad Request: Too Big Data <%d>bytes" % size)
        else:
            SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 9
0
 def do_POST(self):
     #send unauthorized if not in list   
     if self.client_address[0] not in settings.authorized_clients:
         self.send_response(401)
     else:
         #super(RequestHandler, self).do_POST(self)     
         #cannot use super() to make calls in python 2.7.5 with the 
         #SimpleXMLRPCRequestHandler, as its ultimate base class
         #BaseRequestHandler in SocketServer.py is not a new-style
         #class (it does not inherit from object).  Resort to manual
         #call to do_POST() instead.
         SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 10
0
	def do_POST(self):
		# authentication
		if self.authMap != None: # explicit None!
			if self.headers.has_key('authorization') and self.headers['authorization'].startswith('Basic '):
				authenticationString = base64.b64decode(self.headers['authorization'].split(' ')[1])
				if authenticationString.find(':') != -1:
					username, password = authenticationString.split(':', 1)
					if self.authMap.has_key(username) and self.verifyPassword(username, password):
						return SimpleXMLRPCRequestHandler.do_POST(self)
			self.send_response(401)
			self.end_headers()
			return False
		return SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 11
0
 def do_POST(self):
     try:
         remote_token = self.headers["Bitbake-token"]
     except:
         remote_token = None
     if remote_token != self.server.connection_token and remote_token != "observer":
         self.report_503()
     else:
         if remote_token == "observer":
             self.server.readonly = True
         else:
             self.server.readonly = False
         SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 12
0
 def do_POST(self):
     try:
         _, auth   = self.headers["authorization"].split()
         uid, md5  = base64.decodestring(auth).strip().split(':')
         vhost     = self.path.split('/')[1].lower()
         self.data = self.getUser(uid, md5, vhost)
         if self.data is None:
             raise AuthFailed
         # Call super.do_POST() to do the actual work
         SimpleXMLRPCRequestHandler.do_POST(self)
     except:
         self.send_response(401)
         self.end_headers()
Ejemplo n.º 13
0
 def do_POST(self):
     try:
         _, auth   = self.headers["authorization"].split()
         uid, md5  = base64.decodestring(auth).strip().split(':')
         vhost     = self.path.split('/')[1].lower()
         self.data = self.getUser(uid, md5, vhost)
         if self.data is None:
             raise AuthFailed
         # Call super.do_POST() to do the actual work
         SimpleXMLRPCRequestHandler.do_POST(self)
     except:
         self.send_response(401)
         self.end_headers()
Ejemplo n.º 14
0
 def do_POST(self):
     try:
         remote_token = self.headers["Bitbake-token"]
     except:
         remote_token = None
     if remote_token != self.server.connection_token and remote_token != "observer":
         self.report_503()
     else:
         if remote_token == "observer":
             self.server.readonly = True
         else:
             self.server.readonly = False
         SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 15
0
    def do_POST(self):
        """Extract username and password from authorization header."""

        # Try to extract username and password from HTTP Authentication.
        self.username = None
        self.password = None
        authorization = self.headers.get('authorization', ' ')
        scheme, challenge = authorization.split(' ', 1)

        if scheme.lower() == 'basic':
            decoded = base64.decodestring(challenge)
            self.username, self.password = decoded.split(':')

        SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 16
0
    def do_POST(self):
        """Extract username and password from authorization header."""

        # Try to extract username and password from HTTP Authentication.
        self.username = None
        self.password = None
        authorization = self.headers.get('authorization', ' ')
        scheme, challenge = authorization.split(' ', 1)

        if scheme.lower() == 'basic':
            decoded = base64.decodestring(challenge)
            self.username, self.password = decoded.split(':')

        SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 17
0
    def do_POST(self):
        """Extract username and password from authorization header."""

        db = None
        try:
            path = self.path.split('/')
            tracker_name = urllib.unquote(path[1]).lower()
            tracker = self.get_tracker(tracker_name)
            db = self.authenticate(tracker)

            instance = RoundupInstance(db, tracker.actions, None)
            self.server.register_instance(instance)
            SimpleXMLRPCRequestHandler.do_POST(self)
        except Unauthorised, message:
            self.send_error(403, '%s (%s)' % (self.path, message))
    def do_POST(self):
        """Extract username and password from authorization header."""

        db = None
        try:
            path = self.path.split('/')
            tracker_name = urllib.unquote(path[1]).lower()
            tracker = self.get_tracker(tracker_name)
            db = self.authenticate(tracker)

            instance = RoundupInstance(db, tracker.actions, None)
            self.server.register_instance(instance)
            SimpleXMLRPCRequestHandler.do_POST(self)
        except Unauthorised, message:
            self.send_error(403, '%s (%s)'%(self.path, message))
Ejemplo n.º 19
0
  def do_POST(self):
    (scheme, netloc, path, params, query, frag) = urlparse(self.path)
    if path.startswith('/::XMLRPC::/'):
      return SimpleXMLRPCRequestHandler.do_POST(self)

    config = self.server.session.config
    post_data = { }
    try:
      clength = int(self.headers.get('content-length'))
      ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
      if ctype == 'multipart/form-data':
        post_data = cgi.parse_multipart(self.rfile, pdict)
      elif ctype == 'application/x-www-form-urlencoded':
        if clength > 5*1024*1024:
          raise ValueError('OMG, input too big')
        post_data = cgi.parse_qs(self.rfile.read(clength), 1)
      else:
        raise ValueError('Unknown content-type')

    except (IOError, ValueError), e:
      r = self.server.session.ui.render_page(config,
                                   {'lastq': '', 'csrf': '', 'path': ''},
                                   body='POST geborked: %s' % e,
                                   title='Internal Error')
      self.send_full_response(r, code=500)
      return None
Ejemplo n.º 20
0
  def do_POST(self, method='POST'):
    (scheme, netloc, path, params, query, frag) = urlparse(self.path)
    if path.startswith('/::XMLRPC::/'):
      return SimpleXMLRPCRequestHandler.do_POST(self)

    config = self.server.session.config
    post_data = { }
    try:
      clength = int(self.headers.get('content-length'))
      ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
      if ctype == 'multipart/form-data':
        post_data = cgi.FieldStorage(
          fp=self.rfile,
          headers=self.headers,
          environ={'REQUEST_METHOD': method,
                   'CONTENT_TYPE': self.headers['Content-Type']}
        )
      elif ctype == 'application/x-www-form-urlencoded':
        if clength > 5*1024*1024:
          raise ValueError('OMG, input too big')
        post_data = cgi.parse_qs(self.rfile.read(clength), 1)
      else:
        raise ValueError('Unknown content-type')

    except (IOError, ValueError), e:
      r = self.server.session.ui.render_page(config, self._ERROR_CONTEXT,
                                             body='POST geborked: %s' % e,
                                             title='Internal Error')
      self.send_full_response(r, code=500)
      return None
Ejemplo n.º 21
0
  def do_POST(self):
    (scheme, netloc, path, params, query, frag) = urlparse(self.path)
    if path.startswith('/::XMLRPC::/'):
      return SimpleXMLRPCRequestHandler.do_POST(self)

    config = self.server.session.config
    post_data = { }
    try:
      clength = int(self.headers.get('content-length'))
      ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
      if ctype == 'multipart/form-data':
        post_data = cgi.parse_multipart(self.rfile, pdict)
      elif ctype == 'application/x-www-form-urlencoded':
        if clength > 5*1024*1024:
          raise ValueError('OMG, input too big')
        post_data = cgi.parse_qs(self.rfile.read(clength), 1)
      else:
        raise ValueError('Unknown content-type')

    except (IOError, ValueError), e:
      r = self.server.session.ui.render_page(config,
                                   {'lastq': '', 'csrf': '', 'path': ''},
                                   body='POST geborked: %s' % e,
                                   title='Internal Error')
      self.send_full_response(r, code=500)
      return None
Ejemplo n.º 22
0
    def do_POST(self, command='POST'):
        (scheme, netloc, path, params, query, frag) = urlparse(self.path)
        qs = parse_qs(query)
        self.getHostInfo()
        self.command = command

        if not self.performAuthChecks(scheme, netloc, path, qs): return

        posted = None
        self.post_data = tempfile.TemporaryFile()
        self.old_rfile = self.rfile
        try:
            # First, buffer the POST data to a file...
            clength = cleft = int(self.headers.get('content-length'))
            while cleft > 0:
                rbytes = min(64 * 1024, cleft)
                self.post_data.write(self.rfile.read(rbytes))
                cleft -= rbytes

            # Juggle things so the buffering is invisble.
            self.post_data.seek(0)
            self.rfile = self.post_data

            ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
            if ctype.lower() == 'multipart/form-data':
                self.post_data.seek(0)
                posted = cgi.FieldStorage(fp=self.post_data,
                                          headers=self.headers,
                                          environ={
                                              'REQUEST_METHOD': command,
                                              'CONTENT_TYPE': ctype
                                          })
            elif ctype.lower() == 'application/x-www-form-urlencoded':
                if clength >= 50 * 1024 * 1024:
                    raise Exception(("Refusing to parse giant posted query "
                                     "string (%s bytes).") % clength)
                posted = cgi.parse_qs(self.rfile.read(clength), 1)
            elif self.host_config.get('xmlrpc', False):
                # We wrap the XMLRPC request handler in _BEGIN/_END in order to
                # expose the request environment to the RPC functions.
                RCI = self.server.RCI
                return RCI._END(
                    SimpleXMLRPCRequestHandler.do_POST(RCI._BEGIN(self)))

            self.post_data.seek(0)
        except socket.error:
            pass
        except Exception, e:
            logging.Log([('err', 'POST error at %s: %s' % (path, e))])
            self.sendResponse('<h1>Internal Error</h1>\n',
                              code=500,
                              msg='Error')
            self.rfile = self.old_rfile
            self.post_data = None
            return
Ejemplo n.º 23
0
  def do_POST(self, command='POST'):
    (scheme, netloc, path, params, query, frag) = urlparse(self.path)
    qs = parse_qs(query)
    self.getHostInfo()
    self.command = command

    if not self.performAuthChecks(scheme, netloc, path, qs): return

    posted = None
    self.post_data = tempfile.TemporaryFile()
    self.old_rfile = self.rfile
    try:
      # First, buffer the POST data to a file...
      clength = cleft = int(self.headers.get('content-length'))
      while cleft > 0:
        rbytes = min(64*1024, cleft)
        self.post_data.write(self.rfile.read(rbytes))
        cleft -= rbytes

      # Juggle things so the buffering is invisble.
      self.post_data.seek(0)
      self.rfile = self.post_data

      ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
      if ctype == 'multipart/form-data':
        self.post_data.seek(0)
        posted = cgi.parse_multipart(self.rfile, pdict)
      elif ctype == 'application/x-www-form-urlencoded':
        if clength >= 50*1024*1024:
          raise Exception(("Refusing to parse giant posted query "
                           "string (%s bytes).") % clength)
        posted = cgi.parse_qs(self.rfile.read(clength), 1)
      elif self.host_config.get('xmlrpc', False):
        # We wrap the XMLRPC request handler in _BEGIN/_END in order to
        # expose the request environment to the RPC functions.
        RCI = self.server.RCI
        return RCI._END(SimpleXMLRPCRequestHandler.do_POST(RCI._BEGIN(self)))

      self.post_data.seek(0)
    except socket.error:
      pass
    except Exception, e:
      logging.Log([('err', 'POST error at %s: %s' % (path, e))])
      self.sendResponse('<h1>Internal Error</h1>\n', code=500, msg='Error')
      self.rfile = self.old_rfile
      self.post_data = None
      return
Ejemplo n.º 24
0
    def handle(self):
        self.raw_requestline = self.rfile.readline()
        if not self.parse_request(): # An error code has been sent, just exit
            return

        if SimpleXMLRPCRequestHandler.is_rpc_path_valid(self):
            # @CTB hack hack hack, I should be ashamed of myself.
            global client_ip
            client_ip = self.client_address[0]
            return SimpleXMLRPCRequestHandler.do_POST(self)

        handler = ServerHandler(
            self.rfile, self.wfile, self.get_stderr(), self.get_environ(),
            multithread=False, multiprocess=False
        )
        handler.request_handler = self      # backpointer for logging
        handler.run(self.server.get_app())
Ejemplo n.º 25
0
    def _handle(self):
        """
        Handle:
          /xmlrpc => SimpleXMLRPCServer
          /upload => self._handle_upload
          all else => WSGI app for Web UI
        """
        self.raw_requestline = self.rfile.readline()
        if not self.parse_request(): # An error code has been sent, just exit
            return

        print "SERVER HANDLE: path is '%s'" % self.path
        
        content_length = self.headers.getheader('content-length')
        if not content_length:
            content_length = 0
        content_length = int(content_length)

        print 'content length is:', content_length

        if content_length > self.MAX_CONTENT_LENGTH:
            message = "403 FORBIDDEN: You're trying to upload %d bytes; we only allow %d per request." % (content_length, self.MAX_CONTENT_LENGTH)
            self._send_html_response(403, message)
            return

        if SimpleXMLRPCRequestHandler.is_rpc_path_valid(self):
            # @CTB hack hack hack, I should be ashamed of myself.
            global client_ip
            client_ip = self.client_address[0]
            return SimpleXMLRPCRequestHandler.do_POST(self)
        
        elif self.path.startswith('/upload?'):
            return self._handle_upload()

        elif self.path.startswith('/notify'):
            return self._handle_notify()

        ## else:

        handler = ServerHandler(
            self.rfile, self.wfile, self.get_stderr(), self.get_environ(),
            multithread=False, multiprocess=False
        )
        handler.request_handler = self      # backpointer for logging
        handler.run(self.server.get_app())
Ejemplo n.º 26
0
    def handle(self):
        """
        Handle:
          /xmlrpc => SimpleXMLRPCServer
          /upload => self._handle_upload
          /notify => self._handle_notify
          all else => WSGI app for Web UI
        """
        self.raw_requestline = self.rfile.readline()
        if not self.parse_request(): # An error code has been sent, just exit
            return

        content_length = self.headers.getheader('content-length')
        if not content_length:
            content_length = 0
        content_length = int(content_length)

        print 'content length is:', content_length

        if content_length > self.MAX_CONTENT_LENGTH:
            message = too_big_message % (content_length,
                                         self.MAX_CONTENT_LENGTH)
            self._send_html_response(403, message)
            return

        if SimpleXMLRPCRequestHandler.is_rpc_path_valid(self):
            return SimpleXMLRPCRequestHandler.do_POST(self)
        
        elif self.path.startswith('/upload?'):
            return self._handle_upload()

        elif self.path.startswith('/notify'):
            return self._handle_notify()

        ## else:

        handler = ServerHandler(
            self.rfile, self.wfile, self.get_stderr(), self.get_environ(),
            multithread=False, multiprocess=False
        )
        handler.request_handler = self      # backpointer for logging
        handler.run(self.server.get_app())
Ejemplo n.º 27
0
    def handle(self):
        """
        Handle:
          /xmlrpc => SimpleXMLRPCServer
          /upload => self._handle_upload
          all else => WSGI app for Web UI
        """
        self.raw_requestline = self.rfile.readline()
        if not self.parse_request(): # An error code has been sent, just exit
            return

        content_length = self.headers.getheader('content-length')
        if not content_length:
            content_length = 0
        content_length = int(content_length)

        print 'content length is:', content_length

        if content_length > self.MAX_CONTENT_LENGTH:
            message = too_big_message % (content_length,
                                         self.MAX_CONTENT_LENGTH)
            self._send_html_response(403, message)
            return

        if SimpleXMLRPCRequestHandler.is_rpc_path_valid(self):
            return SimpleXMLRPCRequestHandler.do_POST(self)
        
        elif self.path.startswith('/upload?'):
            return self._handle_upload()

        ## else:

        handler = ServerHandler(
            self.rfile, self.wfile, self.get_stderr(), self.get_environ(),
            multithread=False, multiprocess=False
        )
        handler.request_handler = self      # backpointer for logging
        handler.run(self.server.get_app())
Ejemplo n.º 28
0
 def do_POST(self):
     if not(self.headers.has_key('accept-encoding') and self.headers['accept-encoding'] == 'gzip'):
         return SimpleXMLRPCRequestHandler.do_POST(self)
     else:
         if not self.is_rpc_path_valid():
             self.report_404()
             return
         try:
             max_chunk_size = 10*1024*1024
             size_remaining = int(self.headers["content-length"])
             L = []
             while size_remaining:
                 chunk_size = min(size_remaining, max_chunk_size)
                 L.append(self.rfile.read(chunk_size))
                 size_remaining -= len(L[-1])
             data = ''.join(L)
             data = zlib.decompress(data) # is_gzip
             response = self.server._marshaled_dispatch(
                     data, getattr(self, '_dispatch', None)
                 )
         except Exception, e:
             self.send_response(500)
             self.end_headers()
         else:
Ejemplo n.º 29
0
 def do_POST(self):
     MyXMLRPCServer.local.client_address = self.client_address
     SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 30
0
 def do_POST(self):
     global monitor
     monitor["clientIP"], monitor["clientPort"] = self.client_address
     SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 31
0
    def do_POST(self, command='POST'):
        (scheme, netloc, path, params, query, frag) = urlparse(self.path)
        qs = parse_qs(query)

        self.command = command
        self.post_data = tempfile.TemporaryFile()
        self.old_rfile = self.rfile
        try:
            # First, buffer the POST data to a file...
            uid = 1234
            clength = cleft = int(self.header('Content-Length'))

            # FIXME: Assume data goes to disk, check how much space we have left?
            if clength >= self.POST_MAX:
                self.post_progress(uid, path, cleft, clength, error='toobig')
                raise Exception(
                    ("Refusing to accept giant posted data (%s bytes).") %
                    clength)
            try:
                while cleft > 0:
                    rbytes = min(64 * 1024, cleft)
                    data = self.rfile.read(rbytes)
                    if len(data) == 0:
                        raise IOError('Premature EOF')
                    else:
                        self.post_data.write(data)
                        cleft -= len(data)
                        self.post_progress(uid, path, cleft, clength)
            except:
                self.post_progress(uid, path, cleft, clength, error='failed')
                raise

            # Juggle things so the buffering is invisble.
            self.post_data.seek(0)
            self.rfile = self.post_data

            ctype, pdict = cgi.parse_header(self.header('Content-Type', ''))
            if ctype == 'multipart/form-data':
                self.post_data.seek(0)
                posted = self.FIELDSTORAGE(boss=self.server.boss,
                                           fp=self.rfile,
                                           headers=self.headers,
                                           environ={
                                               'REQUEST_METHOD':
                                               'POST',
                                               'CONTENT_TYPE':
                                               self.headers['Content-Type']
                                           })

            elif ctype == 'application/x-www-form-urlencoded':
                if clength >= self.POST_UE_MAX:
                    raise Exception(("Refusing to parse giant posted query "
                                     "string (%s bytes).") % clength)
                posted = cgi.parse_qs(self.rfile.read(clength), 1)

            elif command == 'POST':
                # We wrap the XMLRPC request handler in _BEGIN/_END in order to
                # expose the request environment to the RPC functions.
                rci = self.server.xmlrpc
                try:
                    return SimpleXMLRPCRequestHandler.do_POST(rci._BEGIN(self))
                finally:
                    rci._END()
            else:
                posted = {}
                posted[command.upper()] = self.rfile.read(clength)

            self.post_data.seek(0)
        except:
            print '%s' % traceback.format_exc()
            self.sendResponse('<h1>Internal Error</h1>\n',
                              code=500,
                              msg='Error')
            self.rfile = self.old_rfile
            self.post_data = None
            return

        try:
            if 'cookie' in self.headers:
                cookies = Cookie.SimpleCookie(self.headers['cookie'])
            else:
                cookies = {}
            return self.handleHttpRequest(scheme, netloc, path, params, query,
                                          frag, qs, posted, cookies)
        except socket.error:
            pass
        except:
            print '%s' % traceback.format_exc()
            self.sendResponse('<h1>Internal Error</h1>\n',
                              code=500,
                              msg='Error')

        self.rfile = self.old_rfile
        self.post_data = None
Ejemplo n.º 32
0
 def do_POST(self):
     clientIP, clientPort = self.client_address
     print clientIP, clientPort
     SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 33
0
 def do_POST(self):
     global monitor
     monitor["clientIP"], monitor["clientPort"] = self.client_address
     SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 34
0
 def do_POST(self):
   MyXMLRPCServer.local.client_address = self.client_address
   SimpleXMLRPCRequestHandler.do_POST(self)
Ejemplo n.º 35
0
  def do_POST(self, command='POST'):
    (scheme, netloc, path, params, query, frag) = urlparse(self.path)
    qs = parse_qs(query)

    self.command = command
    self.post_data = tempfile.TemporaryFile()
    self.old_rfile = self.rfile
    try:
      # First, buffer the POST data to a file...
      uid = 1234
      clength = cleft = int(self.header('Content-Length'))

      # FIXME: Assume data goes to disk, check how much space we have left?
      if clength >= self.POST_MAX:
        self.post_progress(uid, path, cleft, clength, error='toobig')
        raise Exception(("Refusing to accept giant posted data (%s bytes)."
                         ) % clength)
      try:
        while cleft > 0:
          rbytes = min(64*1024, cleft)
          data = self.rfile.read(rbytes)
          if len(data) == 0:
            raise IOError('Premature EOF')
          else:
            self.post_data.write(data)
            cleft -= len(data)
            self.post_progress(uid, path, cleft, clength)
      except:
        self.post_progress(uid, path, cleft, clength, error='failed')
        raise

      # Juggle things so the buffering is invisble.
      self.post_data.seek(0)
      self.rfile = self.post_data

      ctype, pdict = cgi.parse_header(self.header('Content-Type', ''))
      if ctype == 'multipart/form-data':
        self.post_data.seek(0)
        posted = self.FIELDSTORAGE(
          boss=self.server.boss,
          fp=self.rfile,
          headers=self.headers,
          environ={'REQUEST_METHOD': 'POST',
                   'CONTENT_TYPE': self.headers['Content-Type']}
        )

      elif ctype == 'application/x-www-form-urlencoded':
        if clength >= self.POST_UE_MAX:
          raise Exception(("Refusing to parse giant posted query "
                           "string (%s bytes).") % clength)
        posted = cgi.parse_qs(self.rfile.read(clength), 1)

      elif command == 'POST':
        # We wrap the XMLRPC request handler in _BEGIN/_END in order to
        # expose the request environment to the RPC functions.
        rci = self.server.xmlrpc
        try:
          return SimpleXMLRPCRequestHandler.do_POST(rci._BEGIN(self))
        finally:
          rci._END()
      else:
        posted = {}
        posted[command.upper()] = self.rfile.read(clength)

      self.post_data.seek(0)
    except:
      print '%s' % traceback.format_exc()
      self.sendResponse('<h1>Internal Error</h1>\n', code=500, msg='Error')
      self.rfile = self.old_rfile
      self.post_data = None
      return

    try:
      if 'cookie' in self.headers:
        cookies = Cookie.SimpleCookie(self.headers['cookie'])
      else:
        cookies = {}
      return self.handleHttpRequest(scheme, netloc, path, params, query, frag,
                                    qs, posted, cookies)
    except socket.error:
      pass
    except:
      print '%s' % traceback.format_exc()
      self.sendResponse('<h1>Internal Error</h1>\n', code=500, msg='Error')

    self.rfile = self.old_rfile
    self.post_data = None