Class | PhusionPassenger::MessageChannel
In: | lib/phusion_passenger/message_channel.rb
Parent: | Object

This class provides convenience methods for:

- sending and receiving raw data over an IO channel.
- sending and receiving messages over an IO channel.
- file descriptor (IO object) passing over a Unix socket.

All of these methods use exceptions for error reporting.

There are two kinds of messages:

Array messages
  These are just a list of strings, and the message itself has a specific length. The contained strings may not contain NUL characters (`’\0‘`). Note that an array message must have at least one element.
Scalar messages
  These are byte strings which may contain arbitrary binary data. Scalar messages also have a specific length.

The protocol is designed to be low overhead, easy to implement and easy to parse.

MessageChannel is to be wrapped around an IO object. For example:

     a, b = IO.pipe
     channel1 = MessageChannel.new(a)
     channel2 = MessageChannel.new(b)

     # Send an array message.
     channel2.write("hello", "world !!")
     channel1.read    # => ["hello", "world !!"]

     # Send a scalar message.
     channel2.write_scalar("some long string which can contain arbitrary binary data")
     channel1.read_scalar

The life time of a MessageChannel is independent from that of the wrapped IO object. If a MessageChannel object is destroyed, the underlying IO object is not automatically closed. Call close() if you want to close the underlying IO object.

Note: Be careful with mixing the sending/receiving of array messages, scalar messages and IO objects. If you send a collection of any of these in a specific order, then the receiving side must receive them in the exact some order. So suppose you first send a message, then an IO object, then a scalar, then the receiving side must first receive a message, then an IO object, then a scalar. If the receiving side does things in the wrong order then bad things will happen.

### Methods

close fileno new read read_scalar recv_io send_io write write_scalar

### Attributes

io | [R] | The wrapped IO object.

### Public Class methods

new(io)

Create a new MessageChannel by wrapping the given IO object.

[Source]

        # File lib/phusion_passenger/message_channel.rb, line 83
    83:         def initialize(io)
    84:                 @io = io
    85:         end

### Public Instance methods

close()

Close the underlying IO stream. Might raise SystemCallError or IOError when something goes wrong.

[Source]

         # File lib/phusion_passenger/message_channel.rb, line 259
    259:         def close
    260:                 @io.close
    261:         end

fileno()

Return the file descriptor of the underlying IO object.

[Source]

         # File lib/phusion_passenger/message_channel.rb, line 253
    253:         def fileno
    254:                 return @io.fileno
    255:         end

read()

Read an array message from the underlying file descriptor. Returns the array message as an array, or nil when end-of-stream has been reached.

Might raise SystemCallError, IOError or SocketError when something goes wrong.

[Source]

         # File lib/phusion_passenger/message_channel.rb, line 93
     93:         def read
     94:                 buffer = ''
     95:                 while buffer.size < HEADER_SIZE
     96:                         buffer << @io.readpartial(HEADER_SIZE - buffer.size)
     97:                 end
     98:
     99:                 chunk_size = buffer.unpack('n')[0]
    100:                 buffer = ''
    101:                 while buffer.size < chunk_size
    102:                         buffer << @io.readpartial(chunk_size - buffer.size)
    103:                 end
    104:
    105:                 message = []
    106:                 offset = 0
    107:                 delimiter_pos = buffer.index(DELIMITER, offset)
    108:                 while !delimiter_pos.nil?
    109:                         if delimiter_pos == 0
    110:                                 message << ""
    111:                         else
    112:                                 message << buffer[offset .. delimiter_pos - 1]
    113:                         end
    114:                         offset = delimiter_pos + 1
    115:                         delimiter_pos = buffer.index(DELIMITER, offset)
    116:                 end
    117:                 return message
    118:         rescue Errno::ECONNRESET
    119:                 return nil
    120:         rescue EOFError
    121:                 return nil
    122:         end

read_scalar(max_size = nil)

Read a scalar message from the underlying IO object. Returns the read message, or nil on end-of-stream.

Might raise SystemCallError, IOError or SocketError when something goes wrong.

The `max_size` argument allows one to specify the maximum allowed size for the scalar message. If the received scalar message‘s size is larger than `max_size`, then a SecurityError will be raised.

[Source]

         # File lib/phusion_passenger/message_channel.rb, line 133
    133:         def read_scalar(max_size = nil)
    134:                 buffer = ''
    135:                 temp = ''
    136:                 while buffer.size < 4
    137:                         buffer << @io.readpartial(4 - buffer.size, temp)
    138:                 end
    139:                 size = buffer.unpack('N')[0]
    140:                 if size == 0
    141:                         return ''
    142:                 else
    143:                         if !max_size.nil? && size > max_size
    144:                                 raise SecurityError, "Scalar message size (#{size}) " <<
    145:                                         "exceeds maximum allowed size (#{max_size})."
    146:                         end
    147:                         buffer = ''
    148:                         while buffer.size < size
    149:                                 temp = '' # JRuby doesn't clear the buffer. TODO: remove this when JRuby has been fixed.
    150:                                 buffer << @io.readpartial(size - buffer.size, temp)
    151:                         end
    152:                         return buffer
    153:                 end
    154:         rescue Errno::ECONNRESET
    155:                 return nil
    156:         rescue EOFError
    157:                 return nil
    158:         end

recv_io(klass = IO, negotiate = true)

Receive an IO object (a file descriptor) from the channel. The other side must have sent an IO object by calling send_io(). Note that this only works on Unix sockets.

Might raise SystemCallError, IOError or SocketError when something goes wrong.

[Source]

         # File lib/phusion_passenger/message_channel.rb, line 196
    196:         def recv_io(klass = IO, negotiate = true)
    197:                 write("pass IO") if negotiate
    198:                 io = @io.recv_io(klass)
    199:                 write("got IO") if negotiate
    200:                 return io
    201:         end

send_io(io)

Send an IO object (a file descriptor) over the channel. The other side must receive the IO object by calling recv_io(). Note that this only works on Unix sockets.

Might raise SystemCallError, IOError or SocketError when something goes wrong.

[Source]

         # File lib/phusion_passenger/message_channel.rb, line 209
    209:         def send_io(io)
    210:                 # We read a message before actually calling #send_io
    211:                 # in order to prevent the other side from accidentally
    212:                 # read()ing past the normal data and reading our file
    213:                 # descriptor too.
    214:                 #
    215:                 # For example suppose that side A looks like this:
    216:                 #
    217:                 #   read(fd, buf, 1024)
    218:                 #   read_io(fd)
    219:                 #
    220:                 # and side B:
    221:                 #
    222:                 #   write(fd, buf, 100)
    223:                 #   send_io(fd_to_pass)
    224:                 #
    225:                 # If B completes both write() and send_io(), then A's read() call
    226:                 # reads past the 100 bytes that B sent. On some platforms, like
    227:                 # Linux, this will cause read_io() to fail. And it just so happens
    228:                 # that Ruby's IO#read method slurps more than just the given amount
    229:                 # of bytes.
    230:                 result = read
    231:                 if !result
    232:                         raise EOFError, "End of stream"
    233:                 elsif result != ["pass IO"]
    234:                         raise IOError, "IO passing pre-negotiation header expected"
    235:                 else
    236:                         @io.send_io(io)
    237:                         # Once you've sent the IO you expect to be able to close it on the
    238:                         # sender's side, even if the other side hasn't read the IO yet.
    239:                         # Not so: on some operating systems (I'm looking at you OS X) this
    240:                         # can cause the receiving side to receive a bad file descriptor.
    241:                         # The post negotiation protocol ensures that we block until the
    242:                         # other side has really received the IO.
    243:                         result = read
    244:                         if !result
    245:                                 raise EOFError, "End of stream"
    246:                         elsif result != ["got IO"]
    247:                                 raise IOError, "IO passing post-negotiation header expected"
    248:                         end
    249:                 end
    250:         end

write(name, *args)

Send an array message, which consists of the given elements, over the underlying file descriptor. name is the first element in the message, and args are the other elements. These arguments will internally be converted to strings by calling to_s().

Might raise SystemCallError, IOError or SocketError when something goes wrong.

[Source]

         # File lib/phusion_passenger/message_channel.rb, line 167
    167:         def write(name, *args)
    168:                 check_argument(name)
    169:                 args.each do |arg|
    170:                         check_argument(arg)
    171:                 end
    172:
    173:                 message = "#{name}#{DELIMITER}"
    174:                 args.each do |arg|
    175:                         message << arg.to_s << DELIMITER
    176:                 end
    177:                 @io.write([message.size].pack('n') << message)
    178:                 @io.flush
    179:         end

write_scalar(data)

Send a scalar message over the underlying IO object.

Might raise SystemCallError, IOError or SocketError when something goes wrong.

[Source]

         # File lib/phusion_passenger/message_channel.rb, line 185
    185:         def write_scalar(data)
    186:                 @io.write([data.size].pack('N') << data)
    187:                 @io.flush
    188:         end

[Validate]