Class: Pwnlib::Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/pwnlib/timer.rb

Overview

A simple timer class. TODO(Darkpi): Python pwntools seems to have many unreasonable codes in this class,

not sure of the use case of this, check if everything is coded as
intended after we have some use cases. (e.g. sock)

NOTE(Darkpi): This class is actually quite weird, and expected to be used only in tubes.

Instance Method Summary collapse

Constructor Details

#initialize(timeout = nil) ⇒ Timer

Returns a new instance of Timer.

Difference with Python pwntools:

  • We just use nil for default and :forever for forever.



18
19
20
21
# File 'lib/pwnlib/timer.rb', line 18

def initialize(timeout = nil)
  @deadline = nil
  @timeout = timeout
end

Instance Method Details

#active?Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/pwnlib/timer.rb', line 27

def active?
  started? && (@deadline == :forever || Time.now < @deadline)
end

#countdown(timeout = nil) ⇒ Object

NOTE(Darkpi): timeout = nil means default value for the first time, and nop after that.

Raises:

  • (ArgumentError)

Difference with Python pwntools:

  • We do NOT allow nested countdown with non-default value. This simplifies thing a lot.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/pwnlib/timer.rb', line 45

def countdown(timeout = nil)
  raise ArgumentError, 'Need a block for countdown' unless block_given?

  if started?
    return yield if timeout.nil?

    raise 'Nested countdown not permitted'
  end

  timeout ||= @timeout || ::Pwnlib::Context.context.timeout

  @deadline = timeout == :forever ? :forever : Time.now + timeout

  begin
    yield
  ensure
    was_active = active?
    @deadline = nil
    raise ::Pwnlib::Errors::TimeoutError unless was_active
  end
end

#started?Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/pwnlib/timer.rb', line 23

def started?
  @deadline
end

#timeoutObject



31
32
33
34
35
# File 'lib/pwnlib/timer.rb', line 31

def timeout
  return @timeout || ::Pwnlib::Context.context.timeout unless started?

  @deadline == :forever ? :forever : [@deadline - Time.now, 0].max
end

#timeout=(timeout) ⇒ Object



37
38
39
40
41
# File 'lib/pwnlib/timer.rb', line 37

def timeout=(timeout)
  raise "Can't change timeout when countdown" if started?

  @timeout = timeout
end