public
Description: Direct Connect bot written in Ruby
Clone URL: git://github.com/kballard/dcbot.git
Search Repo:
dcbot / dcprotocol.rb
100644 533 lines (468 sloc) 13.578 kb
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
require 'stringio'
require 'cgi' # for entity-escaping
require 'bz2'
require "#{File.dirname(__FILE__)}/dcuser"
 
class DCProtocol < EventMachine::Connection
  include EventMachine::Protocols::LineText2
  
  CLIENT_NAME = "RubyBot"
  CLIENT_VERSION = "0.1"
  
  def self.registerClientVersion(name, version)
    CLIENT_NAME.replace name
    CLIENT_VERSION.replace version
  end
  
  def registerCallback(callback, &block)
    @callbacks[callback] << block
  end
  
  def lockToKey(lock)
    key = String.new(lock)
    1.upto(key.size - 1) do |i|
      key[i] = lock[i] ^ lock[i-1]
    end
    key[0] = lock[0] ^ lock[-1] ^ lock[-2] ^ 5
    
    # nibble-swap
    0.upto(key.size - 1) do |i|
      key[i] = ((key[i]<<4) & 240) | ((key[i]>>4) & 15)
    end
    
    0.upto(key.size - 1) do |i|
      if [0,5,36,96,124,126].include?(key[i]) then
        key[i,1] = ("/%%DCN%03d%%/" % key[i])
      end
    end
    
    key
  end
  
  def sanitize(data)
    data.gsub("|", "&#124;")
  end
  
  def unsanitize(data)
    CGI.unescapeHTML(data)
  end
  
  def send_command(cmd, *args)
    data = sanitize("$#{cmd}#{["", *args].join(" ")}") + "|"
    send_data(data)
  end
  
  def send_data(data)
    STDERR.puts "-> #{data.gsub(/[^\x20-\x7F]/, ".")}" if @debug
    super
  end
  
  def call_callback(callback, *args)
    @callbacks[callback].each do |proc|
      begin
        proc.call(self, *args)
      rescue Exception => e
        STDERR.puts "! Exception: #{e.message}"
        STDERR.puts e.backtrace.join("\n")
      end
    end
  end
  
  def connection_completed
    call_callback :connected
  end
  
  def receive_line(line)
    STDERR.puts "<- #{line.gsub(/[^\x20-\x7F]/, ".")}" if @debug
    line.chomp!("|")
    line = unsanitize(line)
    cmd = line.slice!(/^\S+/)
    line.slice!(/^ /)
    
    if cmd =~ /^<.*>$/ then
      # this is a specially-formatted command
      # but lets handle it like other commands
      nick = cmd[1...-1]
      if self.respond_to? "cmd_<>" then
        self.send "cmd_<>", nick, line
      else
        call_callback :error, "Unknown command: <#{nick}> #{line}"
      end
    elsif cmd =~ /^\$\S+$/ then
      # this is a proper command
      cmd.slice!(0)
      # hardcode the $To: command since the colon is ugly
      # this protocol is pretty messy
      cmd = "To" if cmd == "To:"
      if self.respond_to? "cmd_#{cmd}" then
        self.send "cmd_#{cmd}", line
      else
        call_callback :error, "Unknown command: $#{cmd} #{line}"
      end
    else
      call_callback :error, "Garbage data: #{line}"
    end
  end
  
  def post_init
    @callbacks = Hash.new { |h,k| h[k] = [] }
    @debug = false
    set_delimiter "|"
  end
  
  def unbind
    call_callback :unbind
  end
end
 
class DCClientProtocol < DCProtocol
  # known keys for args are:
  # password - server password
  # debug - should this socket print debug data?
  # description
  # speed
  # speed_class
  # email
  # slots - number of slots to declare as open
  def self.connect(host, port, nickname, args = {})
    EventMachine::connect(host, port, self) do |c|
      c.instance_eval do
        @nickname = nickname
        @config = args
        @debug = args[:debug]
        @config[:description] ||= ""
        @config[:speed] ||= "Bot"
        @config[:speed_class] ||= 1
        @config[:email] ||= ""
        @config[:slots] ||= 0
      end
      yield c if block_given?
    end
  end
  
  def sendPublicMessage(message)
    data = sanitize("<#{@nickname}> #{message}") + "|"
    send_data data
  end
  
  def sendPrivateMessage(recipient, message)
    send_command "To:", recipient, "From:", @nickname, "$<#{@nickname}>", message
  end
  
  def close
    @quit = true
    close_connection
  end
  
  attr_reader :nickname, :hubname, :quit, :users
  
  # protocol implementation
  
  def cmd_Lock(line)
    lock = line.split(" ")[0]
    key = lockToKey(lock)
    
    send_command("Key", "#{key}")
    send_command("ValidateNick", "#{@nickname}")
  end
  
  def cmd_ValidateDenide(line)
    call_callback :error, "Nickname in use or invalid"
    self.close
  end
  
  def cmd_GetPass(line)
    if @config.has_key? :password
      send_command "MyPass", @config[:password]
    else
      call_callback :error, "Password required but not given"
      self.close
    end
  end
  
  def cmd_BadPass(line)
    call_callback :error, "Bad password given"
    self.close
  end
  
  def cmd_LogedIn(line)
    call_callback :logged_in
  end
  
  def cmd_HubName(line)
    @hubname = line
    call_callback :hubname, @hubname
  end
  
  def cmd_Hello(line)
    nick = line
    if nick == @nickname then
      # this is us, we should respond
      send_command "Version", "1,0091"
      send_command "GetNickList"
      send_command "MyINFO", "$ALL #{@nickname} #{@config[:description]}<#{CLIENT_NAME} V:#{CLIENT_VERSION},M:P,H:1/0/0,S:#{@config[:slots]}>$", \
                             "$#{@config[:speed]}#{@config[:speed_class].chr}$#{@config[:email]}$0$"
    else
      user = DCUser.new(self, nick)
      @users[nick] = user
      call_callback :user_connected, user
    end
  end
  
  def cmd_NickList(line)
    nicks = line.split("$$")
    @users = {}
    nicks.each do |nick|
      @users[nick] = DCUser.new(self, nick)
    end
    call_callback :nicklist, @users.values
  end
  
  def cmd_OpList(line)
    nicks = line.split("$$")
    nicks.each do |nick|
      if @users.has_key? nick then
        @users[nick].op = true
      end
    end
    call_callback :oplist, @users.values.select { |user| user.op }
  end
  
  def cmd_MyINFO(line)
    if line =~ /^\$ALL (\S+) ([^$]*)\$ +\$([^$]*)\$([^$]*)\$([^$]*)\$$/ then
      nick = $1
      interest = $2
      speed = $3
      email = $4
      sharesize = $5
      tag = interest.slice!(/<[^>]+>$/)
      if speed.length > 0 and speed[-1] < 0x20 then
        # assume last byte a control character means it's the speed class
        speed_class = speed.slice!(-1)
      else
        speed_class = 0
      end
      user = @users[nick]
      if user and user.nickname != @nickname then
        user.setInfo(interest, tag, speed, speed_class, email, sharesize)
        call_callback :info, user
      end
    end
  end
  
  def cmd_ConnectToMe(line)
    # another peer is trying to connect to me
    if line =~ /^(\S+) (\S+):(\d+)$/ then
      mynick = $1
      ip = $2
      port = $3.to_i
      if mynick == @nickname then
        connect_to_peer(ip, port)
      else
        call_callback :error, "Strange ConnectToMe request: #{line}"
      end
    end
  end
  
  def cmd_RevConnectToMe(line)
    if line =~ /^(\S+) (\S+)$/ then
      # for the moment we're just going to be a passive client
      nick = $1
      mynick = $2
      if mynick == @nickname then
        user = @users[nick]
        if user then
          if not user.passive then
            # the passive switch keeps us from bouncing RevConnectToMe's back and forth
            user.passive = true
            call_callback :reverse_connection, user
            send_command "RevConnectToMe", mynick, nick
          else
            call_callback :reverse_connection_ignored, user
          end
        else
          call_callback :error, "RevConnectToMe request from unknown user: #{nick}"
        end
      else
        call_callback :error, "Strange RevConnectToMe request: #{line}"
      end
    end
  end
  
  define_method("cmd_<>") do |nick, line|
    call_callback :message, nick, line, false
  end
  
  def cmd_To(line)
    if line =~ /^(\S+) From: (\S+) \$<(\S+)> (.*)$/ then
      mynick = $1
      nick = $2
      displaynick = $3 # ignored for now
      message = $4
      call_callback :message, nick, message, true, (displaynick == "*")
    else
      call_callback :error, "Garbage $To: #{line}"
    end
  end
  
  def cmd_Quit(line)
    nick = line
    user = @users[nick]
    @users.delete nick
    if user.nil? then
      call_callback :error, "Unknown user Quit: #{nick}"
    else
      call_callback :user_quit, user
    end
  end
  
  def cmd_Search(line)
    # for the moment, completely ignore this
  end
  
  # utility methods
  
  def connect_to_peer(ip, port)
    begin
      @peers << EventMachine::connect(ip, port, DCPeerProtocol) do |c|
        parent = self
        debug = @debug || @config[:peer_debug]
        c.instance_eval do
          @parent = parent
          @host = ip
          @port = port
          @debug = debug
        end
        c.call_callback :initialized
      end
    rescue Exception => e
      call_callback :exception, "Could not connect to peer #{ip}:#{port}", e
    end
  end
  
  # event handling methods
  
  def post_init
    super
    @quit = false
    @peers = []
    @users = {}
    self.registerCallback :peer_unbind do |socket, peer|
      @peers.delete socket
    end
  end
  
  def unbind
    super
    @peers.each do |peer|
      peer.close_connection
    end
    @peers = []
  end
end
 
# major assumption in this implementation is that we are simply uploading
# if we want to be able to initiate downloads, this needs some tweaking
# we're also a passive client, so we're always connecting to the other client
class DCPeerProtocol < DCProtocol
  XML_FILE_LISTING = <<EOF
<?xml version="1.0" encoding="utf-8"?>
<FileListing Version="1" Generator="#{CLIENT_NAME} #{CLIENT_VERSION}">
<Directory Name="Send a /pm with !help for help">
</Directory>
</FileListing>
EOF
  XML_FILE_LISTING_BZ2 = BZ2.bzip2(XML_FILE_LISTING)
  
  SUPPORTED_EXTENSIONS = ["ADCGet", "XmlBZList", "TTHF"]
  
  attr_reader :remote_nick, :host, :port, :state
  
  def post_init
    super
    @state = :init
    @supports = nil
    self.registerCallback :error do |peer, message|
      peer.send_command "Error", message unless peer.state == :data
      peer.close_connection_after_writing
    end
  end
  
  # callbacks triggered from the peer always begin with peer_
  def call_callback(name, *args)
    super
    @parent.call_callback "peer_#{name.to_s}".to_sym, self, *args
  end
  
  def connection_completed
    super
    send_command "MyNick", @parent.nickname
    send_command "Lock", "EXTENDEDPROTOCOLABCABCABCABCABCABC", "Pk=#{CLIENT_NAME}#{CLIENT_VERSION}ABCABC"
  end
  
  def get_file_io(filename)
    if filename == "files.xml.bz2" then
      StringIO.new(XML_FILE_LISTING_BZ2)
    else
      nil
    end
  end
  
  # Protocol hooks
  
  def cmd_MyNick(line)
    @remote_nick = line
  end
  
  def cmd_Lock(line)
    lock = line.split(" ")[0]
    key = lockToKey(lock)
    send_command "Supports", *SUPPORTED_EXTENSIONS if lock =~ /^EXTENDEDPROTOCOL/
    send_command "Direction", "Upload", rand(0x7FFF)
    send_command "Key", key
  end
  
  def cmd_Key(line)
    # who cares if they got the key right? just ignore it
  end
  
  def cmd_Direction(line)
    direction, rnd = line.split(" ")
    if direction != "Download" then
      # why did they send me a ConnectToMe if they don't want to download?
      call_callback :error, "Unexpected peer direction: #{direction}"
      # close_connection
    end
    @state = :normal
  end
  
  def cmd_Supports(line)
    @supports = line.split(" ")
  end
  
  def cmd_Get(line)
    if line =~ /^([^$]+)\$(\d+)$/ then
      @state = :data
      filename = $1
      offset = $2.to_i - 1 # it's 1-based
      call_callback :get, filename
      @fileio = get_file_io(filename)
      if @fileio then
        @fileio.pos = offset
        send_command "FileLength", @fileio.size - @fileio.pos
      else
        send_command "Error", "File Not Available"
        close_connection_after_writing
      end
    else
      call_callback :error, "Unknown $Get format"
    end
  end
  
  def cmd_Send(line)
    if @fileio.nil? or @state != :data then
      # we haven't been asked for the file yet
      send_command "Error", "Unexpected $Send"
      close_connection_after_writing
    else
      data = @fileio.read(40906)
      send_data data
      if @fileio.eof? then
        @state = :normal
      end
    end
  end
  
  def cmd_ADCGET(line)
    if line =~ /^(\w+) (.+) (\d+) (-?\d+)(?: (.+))?$/ then
      type = $1
      identifier = $2
      startpos = $3.to_i
      length = $4.to_i
      flags = ($5 || "").split(" ")
      if flags.empty? then
        if type == "file" then
          call_callback :get, identifier
          fileio = get_file_io(identifier)
          if fileio then
            fileio.pos = startpos
            length = fileio.size - fileio.pos if length == -1
            send_command "ADCSND", "file", identifier, startpos, length
            send_data fileio.read(length)
          else
            send_command "Error", "File Not Available"
          end
        else
          send_command "Error", "Unknown $ADCGET type: #{type}"
        end
      else
        send_command "Error", "Unknown $ADCGET flags: #{flags.join(" ")}"
      end
    else
      send_command "Error", "Unknown $ADCGET format"
    end
  end
  
  def cmd_UGetBlock(line)
    if line =~ /^(\d+) (-?\d+) (.+)$/ then
      startpos = $1.to_i
      length = $2.to_i
      filename = $3
      call_callback :get, filename
      fileio = get_file_io(filename)
      if fileio then
        fileio.pos = startpos
        length = fileio.size - fileio.pos if length == -1
        send_command "Sending", length
        send_data fileio.read(length)
      else
        send_command "Failed", "File Not Available"
      end
    else
      send_command "Failed", "Unknown $UGetBlock format"
    end
  end
  
  def cmd_Canceled(line)
    close_connection
  end
  
  def cmd_Error(line)
    call_callback :error, "Peer Error: #{line}"
  end
end