Ejemplo n.º 1
0
def task2(ident):
    global running
    for i in range(numtrips):
        if ident == 0:
            # give it a good chance to enter the next
            # barrier before the others are all out
            # of the current one
            delay = 0.001
        else:
            rmutex.acquire()
            delay = random.random() * numtasks * 0.02
            rmutex.release()
        if verbose:
            print 'task', ident, 'will run for', round(delay, 2), 'sec'
        time.sleep(delay)
        if verbose:
            print 'task', ident, 'entering barrier', i
        bar.enter()
        if verbose:
            print 'task', ident, 'leaving barrier', i
    mutex.acquire()
    running -= 1
    # Must release mutex before releasing done, else the main thread can
    # exit and set mutex to None as part of global teardown; then
    # mutex.release() raises AttributeError.
    finished = running == 0
    mutex.release()
    if finished:
        done.release()
Ejemplo n.º 2
0
def time_based_blind(test_char, current_character, comparator, sleep_int,
                     start_response, truth):
    # Snage the query string and parse it into a dict
    sleep_time = sleep_int * truth
    time.sleep(sleep_time)
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return ['Hello!\r\n']
Ejemplo n.º 3
0
    def run(self):
        delay = random.random() * 0.1
        if verbose:
            print 'task', self.getName(), 'will run for', delay, 'sec'

        self.sema.acquire()

        self.mutex.acquire()
        self.nrunning.inc()
        if verbose:
            print self.nrunning.get(), 'tasks are running'
        self.testcase.assert_(self.nrunning.get() <= 3)
        self.mutex.release()

        time.sleep(delay)
        if verbose:
            print 'task', self.getName(), 'done'

        self.mutex.acquire()
        self.nrunning.dec()
        self.testcase.assert_(self.nrunning.get() >= 0)
        if verbose:
            print self.getName(), 'is finished.', self.nrunning.get(), \
                  'tasks are running'
        self.mutex.release()

        self.sema.release()
Ejemplo n.º 4
0
def task2(ident):
    global running
    for i in range(numtrips):
        if ident == 0:
            # give it a good chance to enter the next
            # barrier before the others are all out
            # of the current one
            delay = 0.001
        else:
            rmutex.acquire()
            delay = random.random() * numtasks * 0.02
            rmutex.release()
        if verbose:
            print 'task', ident, 'will run for', round(delay, 2), 'sec'
        time.sleep(delay)
        if verbose:
            print 'task', ident, 'entering barrier', i
        bar.enter()
        if verbose:
            print 'task', ident, 'leaving barrier', i
    mutex.acquire()
    running -= 1
    # Must release mutex before releasing done, else the main thread can
    # exit and set mutex to None as part of global teardown; then
    # mutex.release() raises AttributeError.
    finished = running == 0
    mutex.release()
    if finished:
        done.release()
Ejemplo n.º 5
0
    def run(self):
        delay = random.random() * 0.1
        if verbose:
            print 'task', self.getName(), 'will run for', delay, 'sec'

        self.sema.acquire()

        self.mutex.acquire()
        self.nrunning.inc()
        if verbose:
            print self.nrunning.get(), 'tasks are running'
        self.testcase.assert_(self.nrunning.get() <= 3)
        self.mutex.release()

        time.sleep(delay)
        if verbose:
            print 'task', self.getName(), 'done'

        self.mutex.acquire()
        self.nrunning.dec()
        self.testcase.assert_(self.nrunning.get() >= 0)
        if verbose:
            print self.getName(), 'is finished.', self.nrunning.get(), \
                  'tasks are running'
        self.mutex.release()

        self.sema.release()
Ejemplo n.º 6
0
    def testLruAgeExpiry(self):
        def callback(input):
            return input * 2

        test_lru = lru.LruDict(callback, maximum_age=0.1)
        test_lru[100]
        self.assert_(100 in test_lru)
        time.sleep(0.2)
        self.assert_(100 not in test_lru)
Ejemplo n.º 7
0
    def testLruAgeExpiry(self):
        def callback(input):
            return input*2

        test_lru = lru.LruDict(callback, maximum_age=0.1)
        test_lru[100]
        self.assert_(100 in test_lru)
        time.sleep(0.2)
        self.assert_(100 not in test_lru)
Ejemplo n.º 8
0
def wait_running(nc):
    """Wait for running eventlet greenthreads.

    Eventlet sometimes has running greenthreads after waitall() returns.
    This requires a greened time module (so as not to block the I/O loop).
    """
    while nc.num_requests_running:
        nc.wait_all()
        time.sleep(0.5)
Ejemplo n.º 9
0
    def test_shell2(self):
        cmd = logshipper.input.Command("echo \"'\\\"\"")
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.01)
        cmd.stop()

        self.assertEqual(self.messages[0]['message'], "'\"")
Ejemplo n.º 10
0
    def test_oneshot(self):
        cmd = logshipper.input.Command("echo 123")
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.1)
        cmd.stop()

        self.assertEqual(len(self.messages), 1)
Ejemplo n.º 11
0
    def test_unicode2(self):
        cmd = logshipper.input.Command(u"echo \u2713")  # unicode checkmark
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.1)
        cmd.stop()

        self.assertEqual(self.messages[0]['message'], u"\u2713")
Ejemplo n.º 12
0
    def test_shell2(self):
        cmd = logshipper.input.Command("echo \"'\\\"\"")
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.01)
        cmd.stop()

        self.assertEqual(self.messages[0]['message'], "'\"")
Ejemplo n.º 13
0
def run_interaction(run_client):
    s, port = init_server()
    start_new_thread(handle_request, (s, run_client))
    if run_client:
        start_new_thread(make_request, (port, ))
    sleep(0.1 + SOCKET_TIMEOUT)
    #print sys.getrefcount(s.fd)
    #s.close()
    return weakref.ref(s.fd)
Ejemplo n.º 14
0
    def test_repeat(self):
        cmd = logshipper.input.Command("echo 123", interval=.1)
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.3)
        cmd.stop()

        self.assertGreater(len(self.messages), 1)
Ejemplo n.º 15
0
    def test_repeat(self):
        cmd = logshipper.input.Command("echo 123", interval=.1)
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.3)
        cmd.stop()

        self.assertGreater(len(self.messages), 1)
Ejemplo n.º 16
0
    def test_unicode2(self):
        cmd = logshipper.input.Command(u"echo \u2713")  # unicode checkmark
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.1)
        cmd.stop()

        self.assertEqual(self.messages[0]['message'], u"\u2713")
Ejemplo n.º 17
0
    def test_oneshot(self):
        cmd = logshipper.input.Command("echo 123")
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.1)
        cmd.stop()

        self.assertEqual(len(self.messages), 1)
Ejemplo n.º 18
0
def run_interaction(run_client):
    s, port = init_server()
    start_new_thread(handle_request, (s, run_client))
    if run_client:
        start_new_thread(make_request, (port,))
    sleep(0.1+SOCKET_TIMEOUT)
    #print sys.getrefcount(s.fd)
    #s.close()
    return weakref.ref(s.fd)
Ejemplo n.º 19
0
    def run(self):
        while self.should_run:
            start_time = time.time()
            if isinstance(self.commandline, six.string_types):
                self.process = subprocess.Popen(self.commandline,
                                                close_fds=True,
                                                env=self.env,
                                                shell=True,
                                                stdin=subprocess.PIPE,
                                                stdout=subprocess.PIPE,
                                                stderr=subprocess.PIPE)
            else:
                self.process = subprocess.Popen(self.commandline,
                                                close_fds=True,
                                                env=self.env,
                                                stdin=subprocess.PIPE,
                                                stdout=subprocess.PIPE,
                                                stderr=subprocess.PIPE)

            self.process.stdin.close()

            if self.separator == '\n':

                def process_pipe(pipe):
                    while not pipe.closed:
                        line = pipe.readline()
                        if not line:
                            break

                        line = line.decode('utf8')
                        self.emit({"message": line.rstrip('\n')})
            else:

                def process_pipe(pipe):
                    buf = u""
                    for chunk in codecs.iterdecode(pipe, 'utf8'):
                        buf += chunk
                        messages = buf.split(self.separator)
                        buf = messages[-1]
                        messages = messages[:-1]
                        for message in messages:
                            self.emit({"message": message})
                    if buf:
                        self.emit({"message": buf})

            stdout_thread = eventlet.spawn(process_pipe, self.process.stdout)
            stderr_thread = eventlet.spawn(process_pipe, self.process.stderr)

            self.process.wait()
            self.process = None

            stdout_thread.wait()
            stderr_thread.wait()

            took = time.time() - start_time
            time.sleep(self.interval - took)
Ejemplo n.º 20
0
    def test_kill(self):
        cmd = logshipper.input.Command("sleep .2; echo 123")
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.01)
        cmd.stop()
        time.sleep(0.3)

        self.assertEqual(len(self.messages), 0)
Ejemplo n.º 21
0
    def test_kill(self):
        cmd = logshipper.input.Command("sleep .2; echo 123")
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.01)
        cmd.stop()
        time.sleep(0.3)

        self.assertEqual(len(self.messages), 0)
Ejemplo n.º 22
0
    def test_unicode1(self):
        test_string = u"\u2713"  # unicode checkmark

        cmd = logshipper.input.Command(["echo", test_string])
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.1)
        cmd.stop()

        self.assertEqual(self.messages[0]['message'], test_string)
Ejemplo n.º 23
0
    def test_unicode1(self):
        test_string = u"\u2713"  # unicode checkmark

        cmd = logshipper.input.Command(["echo", test_string])
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.1)
        cmd.stop()

        self.assertEqual(self.messages[0]['message'], test_string)
Ejemplo n.º 24
0
 def time_based_line(test_char, current_character, comparator, sleep_int,
                     start_response):
     try:
         truth = (cmp(test_char, ord(current_character)) == comparator)
         sleep_time = float(sleep_int) * truth
         time.sleep(sleep_time)
         start_response('200 OK', ['Content-Type', 'text/plain'])
         return ['Hello!\r\n']
     except:
         start_response('400 Bad Request', [('Content-Type', 'text/plain')])
         return ['error\r\n']
Ejemplo n.º 25
0
 def __try_execute(cls, *command, **kwargs):
     tries = 0
     while True:
         try:
             utils.execute(*command, **kwargs)
             return True
         except exception.ProcessExecutionError:
             tries += 1
             if tries >= 3:
                 raise
             time.sleep(tries ** 2)
Ejemplo n.º 26
0
            def run(self):
                self.id = thread.get_ident()
                self.finished = False

                try:
                    while True:
                        worker_started.set()
                        time.sleep(0.1)
                except AsyncExc:
                    self.finished = True
                    worker_saw_exception.set()
Ejemplo n.º 27
0
def time_based_blind(test_char, current_character, comparator, sleep_int, start_response):
    try:
        truth = (cmp(test_char,ord(current_character)) == comparator)
        # Snage the query string and parse it into a dict
        sleep_time = float(sleep_int) * truth
        time.sleep(sleep_time)
        start_response('200 OK', [('Content-Type', 'text/plain')])
        return ['Hello!\r\n']
    except:
        start_response('400 Bad Request', [('Content-Type', 'text/plain')])
        return ['error\r\n']
Ejemplo n.º 28
0
            def run(self):
                self.id = thread.get_ident()
                self.finished = False

                try:
                    while True:
                        worker_started.set()
                        time.sleep(0.1)
                except AsyncExc:
                    self.finished = True
                    worker_saw_exception.set()
Ejemplo n.º 29
0
 def spam_to_me(address):
     sock = eventlet.connect(address)
     while True:
         try:
             sock.sendall(b'hello world')
             # Arbitrary delay to not use all available CPU, keeps the test
             # running quickly and reliably under a second
             time.sleep(0.001)
         except socket.error as e:
             if get_errno(e) == errno.EPIPE:
                 return
             raise
Ejemplo n.º 30
0
    def test_alt_separator(self):
        cmd = logshipper.input.Command(commandline="echo test__test2_boo",
                                       separator="__")
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.1)
        cmd.stop()
        time.sleep(0.1)

        self.assertEqual(self.messages[0]['message'], "test")
        self.assertEqual(self.messages[1]['message'], "test2_boo\n")
Ejemplo n.º 31
0
 def spam_to_me(address):
     sock = eventlet.connect(address)
     while True:
         try:
             sock.sendall(b'hello world')
             # Arbitrary delay to not use all available CPU, keeps the test
             # running quickly and reliably under a second
             time.sleep(0.001)
         except socket.error as e:
             if get_errno(e) == errno.EPIPE:
                 return
             raise
Ejemplo n.º 32
0
    def test_alt_separator(self):
        cmd = logshipper.input.Command(commandline="echo test__test2_boo",
                                       separator="__")
        cmd.set_handler(self.handler)

        cmd.start()
        time.sleep(0.1)
        cmd.stop()
        time.sleep(0.1)

        self.assertEqual(self.messages[0]['message'], "test")
        self.assertEqual(self.messages[1]['message'], "test2_boo\n")
Ejemplo n.º 33
0
 def reader():
     try:
         while True:
             data = client.recv(1024)
             assert data
             # Arbitrary delay to not use all available CPU, keeps the test
             # running quickly and reliably under a second
             time.sleep(0.001)
     except socket.error as e:
         # we get an EBADF because client is closed in the same process
         # (but a different greenthread)
         if get_errno(e) != errno.EBADF:
             raise
Ejemplo n.º 34
0
 def reader():
     try:
         while True:
             data = client.recv(1024)
             assert data
             # Arbitrary delay to not use all available CPU, keeps the test
             # running quickly and reliably under a second
             time.sleep(0.001)
     except socket.error as e:
         # we get an EBADF because client is closed in the same process
         # (but a different greenthread)
         if get_errno(e) != errno.EBADF:
             raise
Ejemplo n.º 35
0
def main(mysql, cassandra):
    user_server      = UserServer(mysql, cassandra)
    event_dispatcher = EventDispatcher(mysql, cassandra, user_server)
    event_server     = EventServer(event_dispatcher)
    pinger           = Pinger(mysql, user_server)
    
    eventlet.spawn(user_server)
    eventlet.spawn(event_server)
    eventlet.spawn(pinger)

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        clearViewers(mysql)
Ejemplo n.º 36
0
def task(ident):
    global running
    rmutex.acquire()
    delay = random.random() * numtasks * 0.02
    rmutex.release()
    if verbose:
        print 'task', ident, 'will run for', round(delay, 2), 'sec'
    time.sleep(delay)
    if verbose:
        print 'task', ident, 'done'
    mutex.acquire()
    running = running - 1
    if running == 0:
        done.release()
    mutex.release()
Ejemplo n.º 37
0
def task(ident):
    global running
    rmutex.acquire()
    delay = random.random() * numtasks * 0.02
    rmutex.release()
    if verbose:
        print 'task', ident, 'will run for', round(delay, 2), 'sec'
    time.sleep(delay)
    if verbose:
        print 'task', ident, 'done'
    mutex.acquire()
    running = running - 1
    if running == 0:
        done.release()
    mutex.release()
Ejemplo n.º 38
0
    def test_service_check_timeout(self):

        init_config = {}
        agent_config = {'timeout': 4}
        instances = []
        for wait in [1,2, 6, 8]:
            instances.append({'service_wait': wait, 'name' : 'dummy %d' % wait})
        self.dummy_service = DummyServiceCheck("dummy service", init_config, agent_config, instances=instances)
        self.dummy_service.run()
        time.sleep(10)
        self.assertEqual(self.dummy_service.statuses['dummy 1'][0], Status.UP)
        self.assertEqual(self.dummy_service.statuses['dummy 2'][0], Status.UP)

        self.assertEqual(self.dummy_service.statuses['dummy 6'][0], "FAILURE")
        self.assertEqual(self.dummy_service.statuses['dummy 8'][0], "FAILURE")
Ejemplo n.º 39
0
def threading_cleanup(num_active, num_limbo):
    from eventlet.green import threading
    from eventlet.green import time

    _MAX_COUNT = 10
    count = 0
    while len(threading._active) != num_active and count < _MAX_COUNT:
        print threading._active
        count += 1
        time.sleep(0.1)

    count = 0
    while len(threading._limbo) != num_limbo and count < _MAX_COUNT:
        print threading._limbo
        count += 1
        time.sleep(0.1)
Ejemplo n.º 40
0
def threading_cleanup(num_active, num_limbo):
    from eventlet.green import threading
    from eventlet.green import time

    _MAX_COUNT = 10
    count = 0
    while len(threading._active) != num_active and count < _MAX_COUNT:
        print threading._active
        count += 1
        time.sleep(0.1)

    count = 0
    while len(threading._limbo) != num_limbo and count < _MAX_COUNT:
        print threading._limbo
        count += 1
        time.sleep(0.1)
Ejemplo n.º 41
0
    def _get_output(self, prompt_expected=True, wait=200):
        """Retrieve output from _process.

        This method will wait until output is started to be received and then
        wait until no further output is received within a defined period
        :param prompt_expected:     only return when regular expression defined
                                    in _prompt_pattern is matched
        :param wait:                Time in milliseconds to wait in each of the
                                    two loops that wait for (more) output.
        """
        tmp_out = ''
        while tmp_out == '':
            self._file_read.seek(0, 1)
            tmp_out += self._file_read.read()
            # leave loop if underlying process has a return code
            # obviously meaning that it has terminated
            if self._process.poll() is not None:
                import json
                error = {"error": tmp_out}
                raise SubprocessError("subprocess with pid: %s has terminated "
                                      "unexpectedly with return code: %s\n%s"
                                      % (self._process.pid,
                                         self._process.poll(),
                                         json.dumps(error)))
            time.sleep(wait / 1000)
        stdout = tmp_out
        while (not tmp_out == '' or
               (not self._prompt_pattern.findall(stdout) and
                prompt_expected)):
            self._file_read.seek(0, 1)
            tmp_out = self._file_read.read()
            stdout += tmp_out
            # leave loop if underlying process has a return code
            # obviously meaning that it has terminated
            if self._process.poll() is not None:
                import json
                error = {"error": stdout}
                raise SubprocessError("subprocess with pid: %s has terminated "
                                      "unexpectedly with return code: %s\n%s"
                                      % (self._process.pid,
                                         self._process.poll(),
                                         json.dumps(error)))
            time.sleep(wait / 1000)
        self._output += stdout
        stdout = stdout.replace('\r', '').replace('\x08', '')
        return stdout
Ejemplo n.º 42
0
def testloop(proto, servers, hdlrcls, testfunc):
    for svrcls in servers:
        addr = pickaddr(proto)
        if verbose:
            print "ADDR =", addr
            print "CLASS =", svrcls
        t = ServerThread(addr, svrcls, hdlrcls)
        if verbose: print "server created"
        t.start()
        if verbose: print "server running"
        for i in range(NREQ):
            time.sleep(DELAY)
            if verbose: print "test client", i
            testfunc(proto, addr)
        if verbose: print "waiting for server"
        t.join()
        if verbose: print "done"
Ejemplo n.º 43
0
    def test_service_check_timeout(self):

        init_config = {}
        agent_config = {'timeout': 4}
        instances = []
        for wait in [1, 2, 6, 8]:
            instances.append({'service_wait': wait, 'name': 'dummy %d' % wait})
        self.dummy_service = DummyServiceCheck("dummy service",
                                               init_config,
                                               agent_config,
                                               instances=instances)
        self.dummy_service.run()
        time.sleep(10)
        self.assertEqual(self.dummy_service.statuses['dummy 1'][0], Status.UP)
        self.assertEqual(self.dummy_service.statuses['dummy 2'][0], Status.UP)

        self.assertEqual(self.dummy_service.statuses['dummy 6'][0], "FAILURE")
        self.assertEqual(self.dummy_service.statuses['dummy 8'][0], "FAILURE")
Ejemplo n.º 44
0
def parse_response(env, start_response):
    '''Parse out all necessary information and determine if the query resulted in a match'''

    #add in some random delay
    delay = random()
    time.sleep(delay / 10)

    try:
        params = parse_qs(env['QUERY_STRING'])

        # Extract out all of the sqli information
        row_index = int(params['row_index'][0])
        char_index = int(params['character_index'][0]) - 1
        test_char = int(params['character_value'][0])
        comparator = comparators.index(params['comparator'][0]) - 1
        try:
            sleep_int = float(params['sleep'].pop(0))
        except KeyError:
            sleep_int = 1

        # Determine which character position we are at during the injection
        current_character = datas[row_index][char_index]

        # figure out if it was true
        truth = (cmp(ord(current_character), test_char) == comparator)

        #some debugging
        #print "\n\n"
        #print "%d %s %d == %s" % (ord(current_character),params['comparator'][0],test_char,str(truth))
        #print "char_index       : %d" % char_index
        #print "row_index        : %d" % row_index

        # Call the function for what path was given based on the path provided
        response = types[env['PATH_INFO']](test_char, current_character,
                                           comparator, sleep_int,
                                           start_response, truth)

        return response
    except:
        start_response('400 Bad Request', [('Content-Type', 'text/plain')])
        return ['error\r\n']
Ejemplo n.º 45
0
class Tunnel(object):  # pylint: disable=R0902
    """Create a TCP server which will use TunnelHandler."""
    def __init__(self,
                 target_host,
                 target_port,
                 sshclient,
                 tunnel_host='localhost',
                 tunnel_port=0):
        """Constructor."""
        if not isinstance(sshclient, paramiko.SSHClient):
            raise TypeError("'sshclient' must be an instance of "
                            "paramiko.SSHClient.")

        self.target_host = target_host
        self.target_port = target_port
        self.target_address = (target_host, target_port)
        self.address = (tunnel_host, tunnel_port)

        self._tunnel = None
        self._tunnel_thread = None
        self.sshclient = sshclient
        self._ssh_transport = self.get_sshclient_transport(self.sshclient)

        TunnelHandler.target_address = self.target_address
        TunnelHandler.ssh_transport = self._ssh_transport

        self._tunnel = TunnelServer(self.address, TunnelHandler)
        # reset attribute to the port it has actually been set to
        self.address = self._tunnel.server_address
        tunnel_host, self.tunnel_port = self.address

    def get_sshclient_transport(self, sshclient):
        """Get the sshclient's transport.

        Connect the sshclient, that has been passed in and return its
        transport.
        """
        sshclient.connect()
        return sshclient.get_transport()

    def serve_forever(self, async=True):
        """Serve the tunnel forever.

        if async is True, this will be done in a background thread
        """
        if not async:
            self._tunnel.serve_forever()
        else:
            self._tunnel_thread = threading.Thread(
                target=self._tunnel.serve_forever)
            self._tunnel_thread.start()
            # cooperative yield
            time.sleep(0)
Ejemplo n.º 46
0
    def _get_output(self, prompt_expected=True, wait=500):
        """Retrieve output from _process.

        This method will wait until output is started to be received and then
        wait until no further output is received within a defined period
        :param prompt_expected:     only return when regular expression defined
                                    in _prompt_pattern is matched
        :param wait:                Time in milliseconds to wait in each of the
                                    two loops that wait for (more) output.
        """
        tmp_out = ''
        while tmp_out == '':
            self._file_read.seek(0, 1)
            tmp_out += self._file_read.read()
            # leave loop if underlying process has a return code
            # obviously meaning that it has terminated
            if self._handle_output(tmp_out):
                break
            time.sleep(float(wait) / 1000)
        else:
            LOG.debug("Loop 1 - stdout read: %s", tmp_out)

        stdout = tmp_out
        while (tmp_out != '' or
               (not self._prompt_pattern.findall(stdout) and
                prompt_expected)):
            self._file_read.seek(0, 1)
            tmp_out = self._file_read.read()
            stdout += tmp_out
            # leave loop if underlying process has a return code
            # obviously meaning that it has terminated
            if self._handle_output(tmp_out):
                break
            time.sleep(float(wait) / 1000)
        else:
            LOG.debug("Loop 2 - stdout read: %s", tmp_out)

        self._output += stdout
        stdout = stdout.replace('\r', '').replace('\x08', '')
        return stdout
Ejemplo n.º 47
0
def testloop(proto, servers, hdlrcls, testfunc):
    for svrcls in servers:
        addr = pickaddr(proto)
        if verbose:
            print "ADDR =", addr
            print "CLASS =", svrcls
        t = ServerThread(addr, svrcls, hdlrcls)
        if verbose:
            print "server created"
        t.start()
        if verbose:
            print "server running"
        for i in range(NREQ):
            time.sleep(DELAY)
            if verbose:
                print "test client", i
            testfunc(proto, addr)
        if verbose:
            print "waiting for server"
        t.join()
        if verbose:
            print "done"
Ejemplo n.º 48
0
    def _get_output(self, prompt_expected=True, wait=500):
        """Retrieve output from _process.

        This method will wait until output is started to be received and then
        wait until no further output is received within a defined period
        :param prompt_expected:     only return when regular expression defined
                                    in _prompt_pattern is matched
        :param wait:                Time in milliseconds to wait in each of the
                                    two loops that wait for (more) output.
        """
        tmp_out = ''
        while tmp_out == '':
            self._file_read.seek(0, 1)
            tmp_out += self._file_read.read()
            # leave loop if underlying process has a return code
            # obviously meaning that it has terminated
            if self._handle_output(tmp_out):
                break
            time.sleep(float(wait) / 1000)
        else:
            LOG.debug("Loop 1 - stdout read: %s", tmp_out)

        stdout = tmp_out
        while (tmp_out != '' or
               (not self._prompt_pattern.findall(stdout) and prompt_expected)):
            self._file_read.seek(0, 1)
            tmp_out = self._file_read.read()
            stdout += tmp_out
            # leave loop if underlying process has a return code
            # obviously meaning that it has terminated
            if self._handle_output(tmp_out):
                break
            time.sleep(float(wait) / 1000)
        else:
            LOG.debug("Loop 2 - stdout read: %s", tmp_out)

        self._output += stdout
        stdout = stdout.replace('\r', '').replace('\x08', '')
        return stdout
Ejemplo n.º 49
0
def parse_response(env, start_response):
    '''Parse out all necessary information and determine if the query resulted in a match'''

    #add in some random delay
    delay = random()
    time.sleep(delay/10)

    try:
        params =  parse_qs(env['QUERY_STRING'])

        # Extract out all of the sqli information
        row_index =  int(params['row_index'][0])
        char_index = int(params['character_index'][0]) - 1
        test_char = int(params['character_value'][0])
        comparator = comparators.index(params['comparator'][0]) - 1
        try:
            sleep_int = float(params['sleep'].pop(0))
        except KeyError:
            sleep_int = 1

        # Determine which character position we are at during the injection
        current_character = datas[row_index][char_index]

        # figure out if it was true
        truth = (cmp(ord(current_character),test_char) == comparator)

        #some debugging
        #print "\n\n"
        #print "%d %s %d == %s" % (ord(current_character),params['comparator'][0],test_char,str(truth))
        #print "char_index       : %d" % char_index
        #print "row_index        : %d" % row_index

        # Call the function for what path was given based on the path provided
        response = types[env['PATH_INFO']](test_char, current_character, comparator, sleep_int, start_response,truth)

        return response
    except:
        start_response('400 Bad Request', [('Content-Type', 'text/plain')])
        return ['error\r\n']
Ejemplo n.º 50
0
 def __call__(self):
     logging.info('Starting pinger')
     while True:
         time.sleep(60)
         self.ping()
Ejemplo n.º 51
0
 def _wait_for_data(self):
     curpos = self.fileobj.tell()
     cursize = os.fstat(self.fileobj.fileno()).st_size
     while curpos >= cursize:
         time.sleep(0.01)
         cursize = os.fstat(self.fileobj.fileno()).st_size
 def __init__(self):
     time.sleep(0.01)
Ejemplo n.º 53
0
 def sleep_func(wait):
     green_time.sleep(wait)
Ejemplo n.º 54
0
 def sleep_func(wait):
     green_time.sleep(wait)
Ejemplo n.º 55
0
def sleep(seconds=0):
    time.sleep(seconds)
Ejemplo n.º 56
0
def time_based_blind(test_char, current_character, comparator, sleep_int, start_response,truth):
    # Snage the query string and parse it into a dict
    sleep_time = sleep_int * truth
    time.sleep(sleep_time)
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return ['Hello!\r\n']
Ejemplo n.º 57
0
def sleep(seconds=0):
    time.sleep(seconds)
Ejemplo n.º 58
0
 def _delay(self, secs):
     greentime.sleep(secs)
Ejemplo n.º 59
0
def t():
    for i in range(1000):
        time.sleep(random.random() / 1000)