Exemple #1
0
    def found_terminator (self):
        self.buffer, data = [], ''.join(self.buffer)

        if self.pstate is self.STATE_LENGTH:
            packet_length = int(data, 16)
            self.set_terminator (packet_length)
            self.pstate = self.STATE_PACKET
        else:
            self.set_terminator (8)
            self.pstate = self.STATE_LENGTH
            (path, params) = marshal.loads (data)
            o = self.root

            e = None

            try:
                for p in path:
                    o = getattr (o, p)
                result = apply (o, params)
            except:
                e = repr (asyncore.compact_traceback())
                result = None

            rb = marshal.dumps ((e,result))
            self.push (('%08x' % len(rb)) + rb)
Exemple #2
0
    def found_terminator(self):
        self.buffer, data = [], ''.join(self.buffer)

        if self.pstate is self.STATE_LENGTH:
            packet_length = int(data, 16)
            self.set_terminator(packet_length)
            self.pstate = self.STATE_PACKET
        else:
            self.set_terminator(8)
            self.pstate = self.STATE_LENGTH
            (path, params) = marshal.loads(data)
            o = self.root

            e = None

            try:
                for p in path:
                    o = getattr(o, p)
                result = apply(o, params)
            except:
                e = repr(asyncore.compact_traceback())
                result = None

            rb = marshal.dumps((e, result))
            self.push(('%08x' % len(rb)) + rb)
Exemple #3
0
    def found_terminator (self):

        line = self.in_buffer

        if not len(line):
            return

        sp = line.find(' ')
        if sp != -1:
            line = [line[:sp], line[sp+1:]]
        else:
            line = [line]

        command = line[0].lower()
        # watch especially for 'urgent' abort commands.
        if command.find('abor') != -1:
            # ascii_letters for python 3
            letters = getattr(string, "letters", string.ascii_letters)

            # strip off telnet sync chars and the like...
            while command and command[0] not in letters:
                command = command[1:]

        fun_name = 'cmd_%s' % command
        if command != 'pass':
            self.log ('<== %s' % repr(self.in_buffer)[1:-1])
        else:
            self.log ('<== %s' % line[0]+' <password>')
        self.in_buffer = ''
        if not hasattr (self, fun_name):
            self.command_not_understood (line[0])
            return
        if hasattr(self,'_rnfr_src') and fun_name!='cmd_rnto':
            del self._rnfr_src
            self.respond ('503 RNTO Command expected!')
            return

        fun = getattr (self, fun_name)
        if (not self.authorized) and (command not in ('user', 'pass', 'help', 'quit')):
            self.respond ('530 Please log in with USER and PASS')
        elif (not self.check_command_authorization (command)):
            self.command_not_authorized (command)
        else:
            try:
                result = apply (fun, (line,))
            except:
                self.server.total_exceptions.increment()
                (file, fun, line), t,v, tbinfo = asyncore.compact_traceback()
                if self.client_dc:
                    try:
                        self.client_dc.close()
                    except:
                        pass
                self.respond (
                        '451 Server Error: %s, %s: file: %s line: %s' % (
                                t,v,file,line,
                                )
                        )
Exemple #4
0
 def reap (self):          # find DNS requests that have timed out
     now = int(time.time())
     if now - self.last_reap_time > 180:        # reap every 3 minutes
         self.last_reap_time = now              # update before we forget
         for k,(host,unpack,callback,when) in self.request_map.items():
             if now - when > 180:               # over 3 minutes old
                 del self.request_map[k]
                 try:                           # same code as in handle_read
                     callback (host, 0, None)   # timeout val is (0,None)
                 except:
                     (file,fun,line), t, v, tbinfo = asyncore.compact_traceback()
                     self.log_info('%s %s %s' % (t,v,tbinfo), 'error')
Exemple #5
0
 def handle_read (self):
     reply, whence = self.socket.recvfrom (512)
     # for security reasons we may want to double-check
     # that <whence> is the server we sent the request to.
     id = (ord(reply[0])<<8) + ord(reply[1])
     if self.request_map.has_key (id):
         host, unpack, callback, when = self.request_map[id]
         del self.request_map[id]
         ttl, answer = unpack (reply)
         try:
             callback (host, ttl, answer)
         except:
             (file,fun,line), t, v, tbinfo = asyncore.compact_traceback()
             self.log_info('%s %s %s' % ( t,v,tbinfo), 'error')
 def handle_read(self):
     try:
         self.recv(8192)
     except socket.error:
         return
     self.lock.acquire()
     try:
         for thunk in self.thunks:
             try:
                 thunk()
             except:
                 nil, t, v, tbinfo = asyncore.compact_traceback()
                 print ("exception in trigger thunk:" " (%s:%s %s)" % (t, v, tbinfo))
         self.thunks = []
     finally:
         self.lock.release()
Exemple #7
0
 def handle_read(self):
     try:
         self.recv(8192)
     except socket.error:
         return
     self.lock.acquire()
     try:
         for thunk in self.thunks:
             try:
                 thunk()
             except:
                 nil, t, v, tbinfo = asyncore.compact_traceback()
                 print('exception in trigger thunk:'
                       ' (%s:%s %s)' % (t, v, tbinfo))
         self.thunks = []
     finally:
         self.lock.release()
Exemple #8
0
    def found_terminator (self):
        self.buffer, data = [], ''.join(self.buffer)

        if self.pstate is self.STATE_LENGTH:
            packet_length = int(data, 16)
            self.set_terminator (packet_length)
            self.pstate = self.STATE_PACKET
        else:

            self.set_terminator (8)
            self.pstate = self.STATE_LENGTH

            oid, kind, arg = marshal.loads (data)

            obj, refcnt = self.proxies[oid]
            e = None
            reply_kind = 2

            try:
                if kind == 0:
                    # __call__
                    result = apply (obj, arg)
                elif kind == 1:
                    # __getattr__
                    result = getattr (obj, arg)
                elif kind == 2:
                    # __setattr__
                    key, value = arg
                    setattr (obj, key, value)
                    result = None
                elif kind == 3:
                    # __repr__
                    result = repr(obj)
                elif kind == 4:
                    # __del__
                    self.forget_reference (oid)
                    result = None
                elif kind == 5:
                    # __getitem__
                    result = obj[arg]
                elif kind == 6:
                    # __setitem__
                    (key, value) = arg
                    obj[key] = value
                    result = None
                elif kind == 7:
                    # __len__
                    result = len(obj)

            except:
                reply_kind = 1
                (file,fun,line), t, v, tbinfo = asyncore.compact_traceback()
                result = '%s:%s:%s:%s (%s:%s)' % (MY_NAME, file, fun, line, t, str(v))
                self.log_info (result, 'error')
                self.exception_counter.increment()

            self.request_counter.increment()

            # optimize a common case
            if type(result) is types.InstanceType:
                can_marshal = 0
            else:
                can_marshal = 1

            try:
                rb = marshal.dumps ((reply_kind, result))
            except ValueError:
                can_marshal = 0

            if not can_marshal:
                # unmarshallable object, return a reference
                rid = id(result)
                self.new_reference (result)
                rb = marshal.dumps ((0, rid))

            self.push_with_producer (
                    scanning_producer (
                            ('%08x' % len(rb)) + rb,
                            buffer_size = 65536
                            )
                    )
Exemple #9
0
    def found_terminator (self):
        if self.current_request:
            self.current_request.found_terminator()
        else:
            header = self.in_buffer
            self.in_buffer = ''
            lines = string.split (header, '\r\n')

            # --------------------------------------------------
            # crack the request header
            # --------------------------------------------------

            while lines and not lines[0]:
                # as per the suggestion of http-1.1 section 4.1, (and
                # Eric Parker <*****@*****.**>), ignore a leading
                # blank lines (buggy browsers tack it onto the end of
                # POST requests)
                lines = lines[1:]

            if not lines:
                self.close_when_done()
                return

            request = lines[0]

            command, uri, version = crack_request (request)
            header = join_headers (lines[1:])

            # unquote path if necessary (thanks to Skip Montanaro for pointing
            # out that we must unquote in piecemeal fashion).
            rpath, rquery = splitquery(uri)
            if '%' in rpath:
                if rquery:
                    uri = unquote (rpath) + '?' + rquery
                else:
                    uri = unquote (rpath)

            r = http_request (self, request, command, uri, version, header)
            self.request_counter.increment()
            self.server.total_requests.increment()

            if command is None:
                self.log_info ('Bad HTTP request: %s' % repr(request), 'error')
                r.error (400)
                return

            # --------------------------------------------------
            # handler selection and dispatch
            # --------------------------------------------------
            for h in self.server.handlers:
                if h.match (r):
                    try:
                        self.current_request = r
                        # This isn't used anywhere.
                        # r.handler = h # CYCLE
                        h.handle_request (r)
                    except:
                        self.server.exceptions.increment()
                        (file, fun, line), t, v, tbinfo = asyncore.compact_traceback()
                        self.log_info(
                                        'Server Error: %s, %s: file: %s line: %s' % (t,v,file,line),
                                        'error')
                        try:
                            r.error (500)
                        except:
                            pass
                    return

            # no handlers, so complain
            r.error (404)
Exemple #10
0
    def found_terminator(self):
        self.buffer, data = [], ''.join(self.buffer)

        if self.pstate is self.STATE_LENGTH:
            packet_length = int(data, 16)
            self.set_terminator(packet_length)
            self.pstate = self.STATE_PACKET
        else:

            self.set_terminator(8)
            self.pstate = self.STATE_LENGTH

            oid, kind, arg = marshal.loads(data)

            obj, refcnt = self.proxies[oid]
            e = None
            reply_kind = 2

            try:
                if kind == 0:
                    # __call__
                    result = apply(obj, arg)
                elif kind == 1:
                    # __getattr__
                    result = getattr(obj, arg)
                elif kind == 2:
                    # __setattr__
                    key, value = arg
                    setattr(obj, key, value)
                    result = None
                elif kind == 3:
                    # __repr__
                    result = repr(obj)
                elif kind == 4:
                    # __del__
                    self.forget_reference(oid)
                    result = None
                elif kind == 5:
                    # __getitem__
                    result = obj[arg]
                elif kind == 6:
                    # __setitem__
                    (key, value) = arg
                    obj[key] = value
                    result = None
                elif kind == 7:
                    # __len__
                    result = len(obj)

            except:
                reply_kind = 1
                (file, fun, line), t, v, tbinfo = asyncore.compact_traceback()
                result = '%s:%s:%s:%s (%s:%s)' % (MY_NAME, file, fun, line, t,
                                                  str(v))
                self.log_info(result, 'error')
                self.exception_counter.increment()

            self.request_counter.increment()

            # optimize a common case
            if type(result) is types.InstanceType:
                can_marshal = 0
            else:
                can_marshal = 1

            try:
                rb = marshal.dumps((reply_kind, result))
            except ValueError:
                can_marshal = 0

            if not can_marshal:
                # unmarshallable object, return a reference
                rid = id(result)
                self.new_reference(result)
                rb = marshal.dumps((0, rid))

            self.push_with_producer(
                scanning_producer(('%08x' % len(rb)) + rb, buffer_size=65536))
Exemple #11
0
 def handle_error (self):      # don't close the connection on error
     (file,fun,line), t, v, tbinfo = asyncore.compact_traceback()
     self.log_info(
                     'Problem with DNS lookup (%s:%s %s)' % (t, v, tbinfo),
                     'error')
Exemple #12
0
 def found_terminator (self):
     line = self.clean_line (self.data)
     self.data = ''
     self.line_counter.increment()
     # check for special case inputs...
     if not line and not self.multi_line:
         self.prompt()
         return
     if line in ['\004', 'exit']:
         self.push ('BCNU\r\n')
         self.close_when_done()
         return
     oldout = sys.stdout
     olderr = sys.stderr
     try:
         p = output_producer(self, olderr)
         sys.stdout = p
         sys.stderr = p
         try:
             # this is, of course, a blocking operation.
             # if you wanted to thread this, you would have
             # to synchronize, etc... and treat the output
             # like a pipe.  Not Fun.
             #
             # try eval first.  If that fails, try exec.  If that fails,
             # hurl.
             try:
                 if self.multi_line:
                     # oh, this is horrible...
                     raise SyntaxError
                 co = compile (line, repr(self), 'eval')
                 result = eval (co, self.local_env)
                 method = 'eval'
                 if result is not None:
                     print repr(result)
                 self.local_env['_'] = result
             except SyntaxError:
                 try:
                     if self.multi_line:
                         if line and line[0] in [' ','\t']:
                             self.multi_line.append (line)
                             self.push ('... ')
                             return
                         else:
                             self.multi_line.append (line)
                             line = '\n'.join(self.multi_line)
                             co = compile (line, repr(self), 'exec')
                             self.multi_line = []
                     else:
                         co = compile (line, repr(self), 'exec')
                 except SyntaxError, why:
                     if why.args[0] == 'unexpected EOF while parsing':
                         self.push ('... ')
                         self.multi_line.append (line)
                         return
                     else:
                         t,v,tb = sys.exc_info()
                         del tb
                         raise t(v)
                 exec co in self.local_env
                 method = 'exec'
         except:
             method = 'exception'
             self.multi_line = []
             (file, fun, line), t, v, tbinfo = asyncore.compact_traceback()
             self.log_info('%s %s %s' %(t, v, tbinfo), 'warning')
     finally:
         sys.stdout = oldout
         sys.stderr = olderr
     self.log_info('%s:%s (%s)> %s' % (
             self.number,
             self.line_counter,
             method,
             repr(line))
             )
     self.push_with_producer (p)
     self.prompt()