Method: Rex::IO::Stream#write

Defined in:
lib/rex/io/stream.rb

#write(buf, opts = {}) ⇒ Object

This method writes the supplied buffer to the stream. This method intelligent reduces the size of supplied buffers so that ruby doesn’t get into a potential global thread blocking state when used on blocking sockets. That is, this method will send the supplied buffer in chunks of, at most, 32768 bytes.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rex/io/stream.rb', line 35

def write(buf, opts = {})
  total_sent   = 0
  total_length = buf.length
  block_size   = 32768

  begin
    while( total_sent < total_length )
      s = Rex::ThreadSafe.select( nil, [ fd ], nil, 0.2 )
      if( s == nil || s[0] == nil )
        next
      end
      data = buf[total_sent, block_size]
      sent = fd.write_nonblock( data )
      if sent > 0
        total_sent += sent
      end
    end
  rescue ::Errno::EAGAIN, ::Errno::EWOULDBLOCK
    # Sleep for a half a second, or until we can write again
    Rex::ThreadSafe.select( nil, [ fd ], nil, 0.5 )
    # Decrement the block size to handle full sendQs better
    block_size = 1024
    # Try to write the data again
    retry
  rescue ::IOError, ::Errno::EPIPE
    return nil
  end

  total_sent
end