Class: RubySMB::Dispatcher::Socket

Inherits:
Base
  • Object
show all
Defined in:
lib/ruby_smb/dispatcher/socket.rb

Overview

This class provides a wrapper around a Socket for the packet Dispatcher. It allows for dependency injection of different Socket implementations.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#nbss

Constructor Details

#initialize(tcp_socket) ⇒ Socket



12
13
14
15
16
17
# File 'lib/ruby_smb/dispatcher/socket.rb', line 12

def initialize(tcp_socket)
  @tcp_socket = tcp_socket
  if @tcp_socket.respond_to?(:setsockopt)
    @tcp_socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
  end
end

Instance Attribute Details

#tcp_socketIO



9
10
11
# File 'lib/ruby_smb/dispatcher/socket.rb', line 9

def tcp_socket
  @tcp_socket
end

Class Method Details

.connect(host, port: 445, socket: TCPSocket.new(host, port)) ⇒ Object



21
22
23
# File 'lib/ruby_smb/dispatcher/socket.rb', line 21

def self.connect(host, port: 445, socket: TCPSocket.new(host, port))
  new(socket)
end

Instance Method Details

#recv_packetString

Read a packet off the wire and parse it into a string Throw Error::NetBiosSessionService if there's an error reading the first 4 bytes, which are assumed to be the NetBiosSessionService header.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ruby_smb/dispatcher/socket.rb', line 44

def recv_packet
  begin
    IO.select([@tcp_socket])
    nbss_header = @tcp_socket.read(4) # Length of NBSS header. TODO: remove to a constant
    if nbss_header.nil?
      raise ::RubySMB::Error::NetBiosSessionService, 'NBSS Header is missing'
    else
      length = nbss_header.unpack('N').first
    end
    IO.select([@tcp_socket])
    data = @tcp_socket.read(length)
    data << @tcp_socket.read(length - data.length) while data.length < length

    data
  rescue Errno::EINVAL, Errno::ECONNABORTED, Errno::ECONNRESET, TypeError => e
    raise RubySMB::Error::CommunicationError, "An error occured reading from the Socket"
  end
end

#send_packet(packet) ⇒ void



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/ruby_smb/dispatcher/socket.rb', line 27

def send_packet(packet)
  data = nbss(packet) + packet.to_binary_s
  bytes_written = 0
  begin
    while bytes_written < data.size
      bytes_written += @tcp_socket.write(data[bytes_written..-1])
    end
  rescue IOError, Errno::ECONNABORTED, Errno::ECONNRESET => e
    raise RubySMB::Error::CommunicationError, "An error occured writing to the Socket"
  end
  nil
end