-
Notifications
You must be signed in to change notification settings - Fork 0
/
LocoRuby.rb
261 lines (225 loc) · 7.59 KB
/
LocoRuby.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
require 'rubygems'
require 'logger'
require 'win32/autogui'
require 'win32ole'
include Autogui::Input
require 'webrick'
require 'fox16'
require 'irb'
gem 'ruby-debug', '= 0.10.3'
require 'ruby-debug'
require 'optparse'
class Logger
def format_message(level, time, progname, msg)
"#{time.strftime("%Y-%m-%d %H:%M:%S")} -- #{msg}\n"
end
end
module LocoRuby
class StoutClientLoader < WEBrick::HTTPServlet::AbstractServlet
def initialize(server)
@window = server[:Window]
@key = server[:Key]
super
@@ready ||= {}
@@response_id ||= {}
end
def do_GET(request, response)
response.status = 200
response.content_type = "text/plain"
if request.path == "/console"
@window.show
elsif request.path == "/debugger"
debugger
elsif request.path == "/ready"
ready = @@ready[request.query["session_id"]]
@logger.info "Ready Request: "
@logger.info " response_id: #{request.query["response_id"]}"
@logger.info " loco ruby expects: #{ready}"
if !request.query["response_id"] or !request.query["session_id"]
r = "no response_id provided"
elsif !request.query["session_id"]
r = "no session_id provided"
elsif !ready
r = "not ready"
elsif ready != request.query["response_id"]
r = "response_id does not match encrypted session_id"
else
r = "ready"
end
@logger.info "ready status request, returning '#{r}'"
response.body = "#{request.query['callback']}('#{r}')"
else
@logger.info "Confirming LocoRuby identity. Session id: #{request.query['session_id']}"
@@response_id[request.query["session_id"]] = response_id = (0...50).map{ ('a'..'z').to_a[rand(26)] }.join
@@ready[request.query["session_id"]] = nil
response.body = "#{request.query['callback']}({session_id: '#{LocoRuby::encrypt(request.query["session_id"])}', response_id: '#{response_id}'})"
@window.tray_icon_tip_text = "confirming local identity..."
end
end
def do_POST(request, response)
response.status = 200
response.content_type = "text/plain"
@logger.info "Request for code load. Confirming remote server identity"
response_id = @@response_id[request.query["session_id"]]
unless response_id && request.query["response_id"]==LocoRuby::encrypt(response_id)
response.status = 500
response.body = "failed security check."
@logger.error "failed security check - theirs/unencrytped/encrypted: #{request.query['response_id']}/#{response_id}/#{LocoRuby::encrypt(response_id)}"
@window.tray_icon_tip_text = "remote server failed security check!"
return
end
code_file_name = request.query['file_name'] || "loco_ruby_client_script.rb"
@logger.info "loading code...(#{request.query['code'].length} bytes)"
@logger.debug request.query["code"]
code_file = File.new(code_file_name, "w")
code_file.write(request.query["code"])
code_file.close
@logger.info "evaluating..."
begin
@logger.info result = load(code_file_name, true) #Class.new.instance_eval { load(code_file_name) }
@logger.info "ready"
@window.tray_icon_tip_text = "code loaded (#{request.query['code'].length} bytes)"
@@ready[request.query["session_id"]] = LocoRuby::encrypt(response_id)
response.body = result.to_s
rescue Exception => e
@logger.error "evaluation failed #{e.message} see http response for backtrace"
@window.tray_icon_tip_text = "code failed to load"
response.body = "#{e.message}\n#{e.backtrace}"
response.status = 500
end
end
end
class ConsoleInternal
RT_ICON = 3
DIFFERENCE = 11
RT_GROUP_ICON = RT_ICON + DIFFERENCE
NIF_MESSAGE = 1
NIF_ICON = 2
NIF_TIP = 4
NIM_ADD = 0
NIM_MODIFY = 1
NIM_DELETE = 2
IMAGE_ICON = 1
LR_LOADFROMFILE = 16
UID = 'LocoRuby'.hash
WM_SYSCOMMAND = 0x112
SC_CLOSE = 0xF060
NotifyIcon = Win32API.new('shell32', 'Shell_NotifyIconA', 'LP', 'I')
LoadImage = Win32API.new('user32', 'LoadImage', 'LPIIII', 'L')
SystemTrayIcon = LoadImage.call(0, "#{File.dirname(__FILE__)}/LocoRuby.ico", IMAGE_ICON, 0, 0, LR_LOADFROMFILE)
ShowWindow = Win32API.new('user32', 'ShowWindow', 'LI', 'I')
SendMessage = Win32API.new('user32', 'SendMessage', 'LLLP', 'L')
SetWindowText = Win32API.new('user32', 'SetWindowText', 'LP', 'L')
def initialize(title, log)
@console_handle = Win32API.new('kernel32','GetConsoleWindow','','L').call
@logger = log
@logger.info "closing any already running servers"
Autogui::EnumerateDesktopWindows.new().find do |w|
if w.title == title
SendMessage.call(w.handle, WM_SYSCOMMAND, SC_CLOSE, 0)
sleep 2 # not the best but...
@logger.info "found and closed running server"
true
end
end
SetWindowText.call(@console_handle, title)
tip_text = "initializing..."
pnid = [6*4+64, @console_handle, UID, NIF_ICON | NIF_TIP, 0, SystemTrayIcon].pack('LLIIIL') <<
tip_text << "\0"*(64 - tip_text.size)
if NotifyIcon.call(NIM_ADD, pnid)
@logger.info "system tray icon tip text initialized"
else
@logger.error "system tray icon tip text could not be initialized."
end
end
def shutdown
pnid = [6*4+64, @console_handle, UID, 0, 0, 0].pack('LLIIIL') << "\0"
@logger.info "deleting system tray icon. status = #{NotifyIcon.call(NIM_DELETE, pnid)}"
end
def tray_icon_tip_text=(tip_text)
pnid = [6*4+64, @console_handle, UID, NIF_ICON | NIF_TIP, 0, SystemTrayIcon].pack('LLIIIL') <<
tip_text << "\0"*(64 - tip_text.size)
if NotifyIcon.call(NIM_MODIFY, pnid)
@logger.info "system tray icon tip text updated: #{tip_text}"
else
@logger.error "system tray icon tip text could not be updated."
end
end
def hide
ShowWindow.call(@console_handle, 0)
end
def show
@logger.info "Show Console"
ShowWindow.call(@console_handle, 9)
Win32API.new('user32', 'BringWindowToTop', 'L', 'I').call(@console_handle)
end
end
end
if $0 == __FILE__ and !defined?(Ocra)
module LocoRuby
def self.encrypt(text)
if defined?(KEY)
Digest::SHA1.hexdigest("--#{KEY}--#{text}--")
else
""
end
end
port = "8000"
open_url = nil
OptionParser.new do |opts|
opts.banner = "Usage: LocoRuby [-d] [-kKey]"
opts.on("-d", "--debug", "debug mode leave console open") do
DEBUG = true
end
opts.on("-kKEY", "--key KEY", "use security key") do |key|
KEY = key
end
opts.on("-pPORT", "--port PORT", "port to listen on defaults to 8000") do |p|
port = p
end
opts.on("-oURL", "--open URL", "open URL in default browser once LocoRuby has started") do |url|
open_url = url
end
end.parse!
if defined?(LocoRuby::DEBUG)
log = Logger.new(STDOUT)
log.level = Logger::DEBUG
log.info "LocoRuby Starting. Debug level = DEBUG"
else
log = Logger.new("debug.log", "daily")
log.level = Logger::INFO
log.info "LocoRuby Starting. Debug level = INFO"
end
console = ConsoleInternal.new("LocoRuby Console", log)
console.tray_icon_tip_text = "mounting server..."
server = WEBrick::HTTPServer.new(
:Port => port,
:Logger => log,
:Window => console,
:StartCallback => Proc.new {`start #{open_url}` if open_url}
)
server.mount "/load_slave", StoutClientLoader
server.mount "/ready", StoutClientLoader
server.mount "/debugger", StoutClientLoader
server.mount "/console", StoutClientLoader
log.info "Server mounted. Starting server now"
console.tray_icon_tip_text = "server waiting..."
Console = console
Server = server
Log = log
if !defined?(LocoRuby::DEBUG)
console.hide
end
end
trap "SIGINT" do
LocoRuby::Log.info "CTL-C Captured"
LocoRuby::Server.shutdown
LocoRuby::Console.shutdown
end
begin
LocoRuby::Server.start
rescue
LocoRuby::Log.info "webrick shut down. Exiting program"
LocoRuby::Console.shutdown
end
end