Class: Pssh::Socket

Inherits:
Rack::WebSocket::Application
  • Object
show all
Defined in:
lib/pssh/socket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Socket



8
9
10
11
12
13
14
15
16
17
# File 'lib/pssh/socket.rb', line 8

def initialize(opts={})
  super

  # set up empty variables
  @sessions = {}
  @killed_sessions = []
  @existing_socket = false

  self.send Pssh.command.to_sym
end

Instance Attribute Details

#attach_cmdObject

Returns the value of attribute attach_cmd.



6
7
8
# File 'lib/pssh/socket.rb', line 6

def attach_cmd
  @attach_cmd
end

#pathObject

Returns the value of attribute path.



5
6
7
# File 'lib/pssh/socket.rb', line 5

def path
  @path
end

#sessionsObject

Returns the value of attribute sessions.



4
5
6
# File 'lib/pssh/socket.rb', line 4

def sessions
  @sessions
end

Instance Method Details

#clear_environmentObject



128
129
130
131
# File 'lib/pssh/socket.rb', line 128

def clear_environment
  ENV['TMUX'] = nil
  ENV['STY'] = nil
end

#close!Object



108
109
110
111
# File 'lib/pssh/socket.rb', line 108

def close!
  self.close_websocket
  @killed_sessions << @uuid
end

#close_websocketObject



93
94
95
96
97
98
99
100
# File 'lib/pssh/socket.rb', line 93

def close_websocket
  @sessions[@uuid][:socket].send_data({ close: true }.to_json) if @sessions[@uuid][:socket]
  @sessions[@uuid][:read].close if @sessions[@uuid][:read]
  @sessions[@uuid][:write].close if @sessions[@uuid][:write]
  @sessions[@uuid][:thread].exit if @sessions[@uuid][:thread]
  @sessions.delete @uuid
  super
end

#kill_all_sessionsObject



102
103
104
105
106
# File 'lib/pssh/socket.rb', line 102

def kill_all_sessions
  @sessions.each do |k,v|
    v[:socket].close!
  end
end

#on_close(env) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/pssh/socket.rb', line 79

def on_close(env)
  uuid = params(env)['uuid']
  @sessions[uuid][:active] = false
  Thread.new do
    sleep 10
    if @sessions[uuid][:active] == false
      @sessions[uuid][:read].close
      @sessions[uuid][:write].close
      @sessions.delete uuid
      print "\n#{user_string} detached.\n#{Pssh.prompt}"
    end
  end
end

#on_message(env, message) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/pssh/socket.rb', line 133

def on_message(env, message)
  uuid = params(env)['uuid']
  return unless @sessions[uuid]
  case message[0]
  when 's'
    unless @sessions[uuid][:started]
      @sessions[uuid][:started] = true
      @sessions[uuid][:thread] = Thread.new do
        begin
          if @sessions[uuid]
            size = message[1..-1].split ','
            send_display_message(uuid)
            clear_environment
            @sessions[uuid][:read], @sessions[uuid][:write], @sessions[uuid][:pid] = PTY.spawn(@command)
            @sessions[uuid][:write].winsize = [size[1].to_i, size[0].to_i]

            while(@sessions[uuid] && @sessions[uuid][:active]) do
              IO.select([@sessions[uuid][:read]])
              begin
                while (data = @sessions[uuid][:read].readpartial(2048)) do
                  data.encode!('UTF-16', 'UTF-8', :invalid => :replace, :replace => '')
                  data.encode!('UTF-8', 'UTF-16')
                  if data.valid_encoding?
                    @sessions[uuid][:socket].send_data({ data: data }.to_json)
                  end
                end
              rescue Exception => e
                if @sessions[uuid]
                  if e.is_a?(Errno::EAGAIN)
                    retry
                  else
                    @sessions[uuid][:active] = false
                  end
                end
              end
            end
          end

        rescue Exception => e
          puts e.inspect
          puts e.backtrace
          puts '---'
          retry
        end
      end
    end
  when 'd'
    @sessions[uuid][:write].write_nonblock message[1..-1] if Pssh.io_mode['w']
  when 'r'
    size = message[1..-1].split ','
    @sessions[uuid][:write].winsize= [size[1].to_i, size[0].to_i]
  end
end

#on_open(env) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/pssh/socket.rb', line 52

def on_open(env)
  uuid = @uuid = params(env)['uuid']
  if @killed_sessions.include? uuid
    # this session has been killed from the console and shouldn't be
    # restarted
    close_websocket and return
  end
  if @sessions[uuid]
    @sessions[uuid][:active] = true
  elsif Pssh.open_sessions.keys.include?(uuid)
    user_string = Pssh.open_sessions[uuid] ? "#{Pssh.open_sessions[uuid]} (#{uuid})" : uuid
    print "\n#{user_string} attached.\n#{Pssh.prompt}"
    @sessions[uuid] = {
      data: [],
      username: Pssh.open_sessions[uuid],
      user_string: user_string,
      active: true,
      started: false
    }
    Pssh.open_sessions.delete uuid
  else
    @sessions[uuid] = {socket: self}
    self.close! and return
  end
  @sessions[uuid][:socket] = self
end

#params(env) ⇒ Object



48
49
50
# File 'lib/pssh/socket.rb', line 48

def params(env)
  Hash[env['QUERY_STRING'].split('&').map { |e| e.split '=' }]
end

#screenObject



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/pssh/socket.rb', line 31

def screen
  if ENV['STY']
    @path = ENV['STY']
    @existing_socket = true
    @command = "screen -S #{@path} -X multiuser on && screen -x #{@path}"
  else
    @path = Pssh.default_socket_path
    @command = "screen -m -S #{@path}"
  end
  @attach_cmd = "screen -x #{@path}"
end

#send_display_message(uuid) ⇒ Object

Internal: Sends a message to the tmux or screen display notifying of a new user that has connected.

Returns nothing.



117
118
119
120
121
122
123
124
125
126
# File 'lib/pssh/socket.rb', line 117

def send_display_message(uuid)
  if @existing_socket
    case Pssh.command.to_sym
    when :tmux
      `tmux -S #{@path} display-message "#{@sessions[uuid][:user_string]} has connected"`
    when :screen
      `screen -S #{@path} -X wall "#{@sessions[uuid][:user_string]} has connected"`
    end
  end
end

#shellObject



43
44
45
46
# File 'lib/pssh/socket.rb', line 43

def shell
  @path = nil
  @command = 'sh'
end

#tmuxObject



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/pssh/socket.rb', line 19

def tmux
  if ENV['TMUX']
    @path = ENV['TMUX'].split(',').first
    @existing_socket = true
    @command = "tmux -S #{@path} attach"
  else
    @path = Pssh.default_socket_path
    @command = "tmux -S #{@path} new"
  end
  @attach_cmd = "tmux -S #{@path} attach"
end