]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
ddbc6eb6f28fcb6c3e060e90b6a9790ad7ce0679
[user/henk/code/ruby/rbot.git] / lib / rbot / ircbot.rb
1 # encoding: UTF-8
2 #-- vim:sw=2:et
3 #++
4 #
5 # :title: rbot core
6
7 require 'thread'
8
9 require 'etc'
10 require 'date'
11 require 'fileutils'
12
13 require 'pp'
14
15 unless Kernel.respond_to? :pretty_inspect
16   def pretty_inspect
17     PP.pp(self, '')
18   end
19   public :pretty_inspect
20 end
21
22 class Exception
23   def pretty_print(q)
24     q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
25       if self.backtrace and not self.backtrace.empty?
26         q.text "\n"
27         q.seplist(self.backtrace, lambda { q.text "\n" } ) { |l| q.text l }
28       end
29     }
30   end
31 end
32
33 class ServerError < RuntimeError
34 end
35
36 # The following global is used for the improved signal handling.
37 $interrupted = 0
38
39 # these first
40 require 'rbot/logger'
41 require 'rbot/rbotconfig'
42 require 'rbot/load-gettext'
43 require 'rbot/config'
44 require 'rbot/irc'
45 require 'rbot/rfc2812'
46 require 'rbot/ircsocket'
47 require 'rbot/botuser'
48 require 'rbot/timer'
49 require 'rbot/registry'
50 require 'rbot/plugins'
51 require 'rbot/message'
52 require 'rbot/language'
53
54 module Irc
55
56 # Main bot class, which manages the various components, receives messages,
57 # handles them or passes them to plugins, and contains core functionality.
58 class Bot
59   COPYRIGHT_NOTICE = "(c) Giuseppe Bilotta and the rbot development team"
60   SOURCE_URL = "https://ruby-rbot.org"
61   # the bot's Auth data
62   attr_reader :auth
63
64   # the bot's Config data
65   attr_reader :config
66
67   # the botclass for this bot (determines configdir among other things)
68   attr_reader :botclass
69
70   # used to perform actions periodically (saves configuration once per minute
71   # by default)
72   attr_reader :timer
73
74   # synchronize with this mutex while touching permanent data files:
75   # saving, flushing, cleaning up ...
76   attr_reader :save_mutex
77
78   # bot's Language data
79   attr_reader :lang
80
81   # bot's irc socket
82   # TODO multiserver
83   attr_reader :socket
84
85   # bot's plugins. This is an instance of class Plugins
86   attr_reader :plugins
87
88   # bot's httputil helper object, for fetching resources via http. Sets up
89   # proxies etc as defined by the bot configuration/environment
90   attr_accessor :httputil
91
92   # mechanize agent factory
93   attr_accessor :agent
94
95   # loads and opens new registry databases, used by the plugins
96   attr_accessor :registry_factory
97
98   # web service
99   attr_accessor :webservice
100
101   # server we are connected to
102   # TODO multiserver
103   def server
104     @client.server
105   end
106
107   # bot User in the client/server connection
108   # TODO multiserver
109   def myself
110     @client.user
111   end
112
113   # bot nick in the client/server connection
114   def nick
115     myself.nick
116   end
117
118   # bot channels in the client/server connection
119   def channels
120     myself.channels
121   end
122
123   # nick wanted by the bot. This defaults to the irc.nick config value,
124   # but may be overridden by a manual !nick command
125   def wanted_nick
126     @wanted_nick || config['irc.nick']
127   end
128
129   # set the nick wanted by the bot
130   def wanted_nick=(wn)
131     if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
132       @wanted_nick = nil
133     else
134       @wanted_nick = wn.to_s.dup
135     end
136   end
137
138
139   # bot inspection
140   # TODO multiserver
141   def inspect
142     ret = self.to_s[0..-2]
143     ret << ' version=' << $version.inspect
144     ret << ' botclass=' << botclass.inspect
145     ret << ' lang="' << lang.language
146     if defined?(GetText)
147       ret << '/' << locale
148     end
149     ret << '"'
150     ret << ' nick=' << nick.inspect
151     ret << ' server='
152     if server
153       ret << (server.to_s + (socket ?
154         ' [' << socket.server_uri.to_s << ']' : '')).inspect
155       unless server.channels.empty?
156         ret << " channels="
157         ret << server.channels.map { |c|
158           "%s%s" % [c.modes_of(nick).map { |m|
159             server.prefix_for_mode(m)
160           }, c.name]
161         }.inspect
162       end
163     else
164       ret << '(none)'
165     end
166     ret << ' plugins=' << plugins.inspect
167     ret << ">"
168   end
169
170
171   # create a new Bot with botclass +botclass+
172   def initialize(botclass, params = {})
173     # Config for the core bot
174     # TODO should we split socket stuff into ircsocket, etc?
175     Config.register Config::ArrayValue.new('server.list',
176       :default => ['irc://localhost'], :wizard => true,
177       :requires_restart => true,
178       :desc => "List of irc servers rbot should try to connect to. Use comma to separate values. Servers are in format 'server.doma.in:port'. If port is not specified, default value (6667) is used.")
179     Config.register Config::BooleanValue.new('server.ssl',
180       :default => false, :requires_restart => true, :wizard => true,
181       :desc => "Use SSL to connect to this server?")
182     Config.register Config::BooleanValue.new('server.ssl_verify',
183       :default => false, :requires_restart => true,
184       :desc => "Verify the SSL connection?",
185       :wizard => true)
186     Config.register Config::StringValue.new('server.ssl_ca_file',
187       :default => default_ssl_ca_file, :requires_restart => true,
188       :desc => "The CA file used to verify the SSL connection.",
189       :wizard => true)
190     Config.register Config::StringValue.new('server.ssl_ca_path',
191       :default => default_ssl_ca_path, :requires_restart => true,
192       :desc => "Alternativly a directory that includes CA PEM files used to verify the SSL connection.",
193       :wizard => true)
194     Config.register Config::StringValue.new('server.password',
195       :default => false, :requires_restart => true,
196       :desc => "Password for connecting to this server (if required)",
197       :wizard => true)
198     Config.register Config::StringValue.new('server.bindhost',
199       :default => false, :requires_restart => true,
200       :desc => "Specific local host or IP for the bot to bind to (if required)",
201       :wizard => true)
202     Config.register Config::IntegerValue.new('server.reconnect_wait',
203       :default => 5, :validate => Proc.new{|v| v >= 0},
204       :desc => "Seconds to wait before attempting to reconnect, on disconnect")
205     Config.register Config::IntegerValue.new('server.ping_timeout',
206       :default => 30, :validate => Proc.new{|v| v >= 0},
207       :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
208     Config.register Config::ArrayValue.new('server.nocolor_modes',
209       :default => ['c'], :wizard => false,
210       :requires_restart => false,
211       :desc => "List of channel modes that require messages to be without colors")
212
213     Config.register Config::StringValue.new('irc.nick', :default => "rbot",
214       :desc => "IRC nickname the bot should attempt to use", :wizard => true,
215       :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
216     Config.register Config::StringValue.new('irc.name',
217       :default => "Ruby bot", :requires_restart => true,
218       :desc => "IRC realname the bot should use")
219     Config.register Config::BooleanValue.new('irc.name_copyright',
220       :default => true, :requires_restart => true,
221       :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
222     Config.register Config::StringValue.new('irc.user', :default => "rbot",
223       :requires_restart => true,
224       :desc => "local user the bot should appear to be", :wizard => true)
225     Config.register Config::ArrayValue.new('irc.join_channels',
226       :default => [], :wizard => true,
227       :desc => "What channels the bot should always join at startup. List multiple channels using commas to separate. If a channel requires a password, use a space after the channel name. e.g: '#chan1, #chan2, #secretchan secritpass, #chan3'")
228     Config.register Config::ArrayValue.new('irc.ignore_users',
229       :default => [],
230       :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
231     Config.register Config::ArrayValue.new('irc.ignore_channels',
232       :default => [],
233       :desc => "Which channels to ignore input in. This is mainly to turn the bot into a logbot that doesn't interact with users in any way (in the specified channels)")
234
235     Config.register Config::IntegerValue.new('core.save_every',
236       :default => 60, :validate => Proc.new{|v| v >= 0},
237       :on_change => Proc.new { |bot, v|
238         if @save_timer
239           if v > 0
240             @timer.reschedule(@save_timer, v)
241             @timer.unblock(@save_timer)
242           else
243             @timer.block(@save_timer)
244           end
245         else
246           if v > 0
247             @save_timer = @timer.add(v) { bot.save }
248           end
249           # Nothing to do when v == 0
250         end
251       },
252       :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
253
254     Config.register Config::BooleanValue.new('core.run_as_daemon',
255       :default => false, :requires_restart => true,
256       :desc => "Should the bot run as a daemon?")
257
258     Config.register Config::StringValue.new('log.file',
259       :default => false, :requires_restart => true,
260       :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
261     Config.register Config::IntegerValue.new('log.level',
262       :default => 1, :requires_restart => false,
263       :validate => Proc.new { |v| (0..5).include?(v) },
264       :on_change => Proc.new { |bot, v|
265         LoggerManager.instance.set_level(v)
266       },
267       :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
268     Config.register Config::IntegerValue.new('log.keep',
269       :default => 1, :requires_restart => true,
270       :validate => Proc.new { |v| v >= 0 },
271       :desc => "How many old console messages logfiles to keep")
272     Config.register Config::IntegerValue.new('log.max_size',
273       :default => 10, :requires_restart => true,
274       :validate => Proc.new { |v| v > 0 },
275       :desc => "Maximum console messages logfile size (in megabytes)")
276
277     Config.register Config::ArrayValue.new('plugins.path',
278       :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
279       :requires_restart => false,
280       :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
281       :desc => "Where the bot should look for plugins. List multiple directories using commas to separate. Use '(default)' for default prepackaged plugins collection, '(default)/contrib' for prepackaged unsupported plugins collection")
282
283     Config.register Config::EnumValue.new('send.newlines',
284       :values => ['split', 'join'], :default => 'split',
285       :on_change => Proc.new { |bot, v|
286         bot.set_default_send_options :newlines => v.to_sym
287       },
288       :desc => "When set to split, messages with embedded newlines will be sent as separate lines. When set to join, newlines will be replaced by the value of join_with")
289     Config.register Config::StringValue.new('send.join_with',
290       :default => ' ',
291       :on_change => Proc.new { |bot, v|
292         bot.set_default_send_options :join_with => v.dup
293       },
294       :desc => "String used to replace newlines when send.newlines is set to join")
295     Config.register Config::IntegerValue.new('send.max_lines',
296       :default => 5,
297       :validate => Proc.new { |v| v >= 0 },
298       :on_change => Proc.new { |bot, v|
299         bot.set_default_send_options :max_lines => v
300       },
301       :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
302     Config.register Config::EnumValue.new('send.overlong',
303       :values => ['split', 'truncate'], :default => 'split',
304       :on_change => Proc.new { |bot, v|
305         bot.set_default_send_options :overlong => v.to_sym
306       },
307       :desc => "When set to split, messages which are too long to fit in a single IRC line are split into multiple lines. When set to truncate, long messages are truncated to fit the IRC line length")
308     Config.register Config::StringValue.new('send.split_at',
309       :default => '\s+',
310       :on_change => Proc.new { |bot, v|
311         bot.set_default_send_options :split_at => Regexp.new(v)
312       },
313       :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
314     Config.register Config::BooleanValue.new('send.purge_split',
315       :default => true,
316       :on_change => Proc.new { |bot, v|
317         bot.set_default_send_options :purge_split => v
318       },
319       :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
320     Config.register Config::StringValue.new('send.truncate_text',
321       :default => "#{Reverse}...#{Reverse}",
322       :on_change => Proc.new { |bot, v|
323         bot.set_default_send_options :truncate_text => v.dup
324       },
325       :desc => "When truncating overlong messages (see send.overlong) or when sending too many lines per message (see send.max_lines) replace the end of the last line with this text")
326     Config.register Config::IntegerValue.new('send.penalty_pct',
327       :default => 100,
328       :validate => Proc.new { |v| v >= 0 },
329       :on_change => Proc.new { |bot, v|
330         bot.socket.penalty_pct = v
331       },
332       :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
333     Config.register Config::StringValue.new('core.db',
334       :default => default_db, :store_default => true,
335       :wizard => true,
336       :validate => Proc.new { |v| Registry::formats.include? v },
337       :requires_restart => true,
338       :desc => "DB adaptor to use for storing the plugin data/registries. Options: " + Registry::formats.join(', '))
339
340     @argv = params[:argv]
341     @run_dir = params[:run_dir] || Dir.pwd
342
343     unless FileTest.directory? Config::coredir
344       error "core directory '#{Config::coredir}' not found, did you setup.rb?"
345       exit 2
346     end
347
348     unless FileTest.directory? Config::datadir
349       error "data directory '#{Config::datadir}' not found, did you setup.rb?"
350       exit 2
351     end
352
353     unless botclass and not botclass.empty?
354       # We want to find a sensible default.
355       # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
356       # * On Windows (at least the NT versions) we want to put our stuff in the
357       #   Application Data folder.
358       # We don't use any particular O/S detection magic, exploiting the fact that
359       # Etc.getpwuid is nil on Windows
360       if Etc.getpwuid(Process::Sys.geteuid)
361         botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
362       else
363         if ENV.has_key?('APPDATA')
364           botclass = ENV['APPDATA'].dup
365           botclass.gsub!("\\","/")
366         end
367       end
368       botclass = File.join(botclass, ".rbot")
369     end
370     botclass = File.expand_path(botclass)
371     @botclass = botclass.gsub(/\/$/, "")
372
373     repopulate_botclass_directory
374
375     save_dir = File.join(@botclass, 'safe_save')
376     Dir.mkdir(save_dir) unless File.exist?(save_dir)
377     unless FileTest.directory? save_dir
378       error "safe save location #{save_dir} is not a directory"
379       exit 2
380     end
381
382     # Time at which the last PING was sent
383     @last_ping = nil
384     # Time at which the last line was RECV'd from the server
385     @last_rec = nil
386
387     @startup_time = Time.new
388
389     begin
390       @config = Config.manager
391       @config.bot_associate(self)
392     rescue Exception => e
393       fatal e
394       exit 2
395     end
396
397     if @config['core.run_as_daemon']
398       $daemonize = true
399     end
400
401     @registry_factory = Registry.new @config['core.db']
402     @registry_factory.migrate_registry_folder(path)
403
404     @logfile = @config['log.file']
405     if @logfile.class != String || @logfile.empty?
406       logfname =  File.basename(botclass).gsub(/^\.+/,'')
407       logfname << ".log"
408       @logfile = File.join(botclass, logfname)
409       debug "Using `#{@logfile}' as debug log"
410     end
411
412     # See http://blog.humlab.umu.se/samuel/archives/000107.html
413     # for the backgrounding code
414     if $daemonize
415       begin
416         exit if fork
417         Process.setsid
418         exit if fork
419       rescue NotImplementedError
420         warning "Could not background, fork not supported"
421       rescue SystemExit
422         exit 0
423       rescue Exception => e
424         warning "Could not background. #{e.pretty_inspect}"
425       end
426       Dir.chdir botclass
427       # File.umask 0000                # Ensure sensible umask. Adjust as needed.
428     end
429
430     # setup logger based on bot configuration
431     LoggerManager.instance.set_level(@config['log.level'])
432     LoggerManager.instance.set_logfile(@logfile, @config['log.keep'], @config['log.max_size'])
433
434     if $daemonize
435       log "Redirecting standard input/output/error"
436       [$stdin, $stdout, $stderr].each do |fd|
437         begin
438           fd.reopen "/dev/null"
439         rescue Errno::ENOENT
440           # On Windows, there's not such thing as /dev/null
441           fd.reopen "NUL"
442         end
443       end
444
445       def $stdout.write(str=nil)
446         log str, 2
447         return str.to_s.size
448       end
449       def $stdout.write(str=nil)
450         if str.to_s.match(/:\d+: warning:/)
451           warning str, 2
452         else
453           error str, 2
454         end
455         return str.to_s.size
456       end
457     end
458
459     File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
460       pf << "#{$$}\n"
461     end
462
463     @timer = Timer.new
464     @save_mutex = Mutex.new
465     if @config['core.save_every'] > 0
466       @save_timer = @timer.add(@config['core.save_every']) { save }
467     else
468       @save_timer = nil
469     end
470     @quit_mutex = Mutex.new
471
472     @plugins = nil
473     @lang = Language.new(self, @config['core.language'])
474
475     begin
476       @auth = Auth::manager
477       @auth.bot_associate(self)
478       # @auth.load("#{botclass}/botusers.yaml")
479     rescue Exception => e
480       fatal e
481       exit 2
482     end
483     @auth.everyone.set_default_permission("*", true)
484     @auth.botowner.password= @config['auth.password']
485
486     @plugins = Plugins::manager
487     @plugins.bot_associate(self)
488     setup_plugins_path()
489
490     if @config['server.name']
491         debug "upgrading configuration (server.name => server.list)"
492         srv_uri = 'irc://' + @config['server.name']
493         srv_uri += ":#{@config['server.port']}" if @config['server.port']
494         @config.items['server.list'.to_sym].set_string(srv_uri)
495         @config.delete('server.name'.to_sym)
496         @config.delete('server.port'.to_sym)
497         debug "server.list is now #{@config['server.list'].inspect}"
498     end
499
500     @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], 
501                               :ssl => @config['server.ssl'],
502                               :ssl_verify => @config['server.ssl_verify'],
503                               :ssl_ca_file => @config['server.ssl_ca_file'],
504                               :ssl_ca_path => @config['server.ssl_ca_path'],
505                               :penalty_pct => @config['send.penalty_pct'])
506     @client = Client.new
507
508     @plugins.scan
509
510     # Channels where we are quiet
511     # Array of channels names where the bot should be quiet
512     # '*' means all channels
513     #
514     @quiet = Set.new
515     # but we always speak here
516     @not_quiet = Set.new
517
518     # the nick we want, if it's different from the irc.nick config value
519     # (e.g. as set by a !nick command)
520     @wanted_nick = nil
521
522     @client[:welcome] = proc {|data|
523       m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
524
525       @plugins.delegate("welcome", m)
526       @plugins.delegate("connect")
527     }
528
529     # TODO the next two @client should go into rfc2812.rb, probably
530     # Since capabs are two-steps processes, server.supports[:capab]
531     # should be a three-state: nil, [], [....]
532     asked_for = { :"identify-msg" => false }
533     @client[:isupport] = proc { |data|
534       if server.supports[:capab] and !asked_for[:"identify-msg"]
535         sendq "CAPAB IDENTIFY-MSG"
536         asked_for[:"identify-msg"] = true
537       end
538     }
539     @client[:datastr] = proc { |data|
540       if data[:text] == "IDENTIFY-MSG"
541         server.capabilities[:"identify-msg"] = true
542       else
543         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
544       end
545     }
546
547     @client[:privmsg] = proc { |data|
548       m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
549       # debug "Message source is #{data[:source].inspect}"
550       # debug "Message target is #{data[:target].inspect}"
551       # debug "Bot is #{myself.inspect}"
552
553       @config['irc.ignore_channels'].each { |channel|
554         if m.target.downcase == channel.downcase
555           m.ignored = true
556           break
557         end
558       }
559       @config['irc.ignore_users'].each { |mask|
560         if m.source.matches?(server.new_netmask(mask))
561           m.ignored = true
562           break
563         end
564       } unless m.ignored
565
566       @plugins.irc_delegate('privmsg', m)
567     }
568     @client[:notice] = proc { |data|
569       message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
570       # pass it off to plugins that want to hear everything
571       @plugins.irc_delegate "notice", message
572     }
573     @client[:motd] = proc { |data|
574       m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
575       @plugins.delegate "motd", m
576     }
577     @client[:nicktaken] = proc { |data|
578       new = "#{data[:nick]}_"
579       nickchg new
580       # If we're setting our nick at connection because our choice was taken,
581       # we have to fix our nick manually, because there will be no NICK message
582       # to inform us that our nick has been changed.
583       if data[:target] == '*'
584         debug "setting my connection nick to #{new}"
585         nick = new
586       end
587       @plugins.delegate "nicktaken", data[:nick]
588     }
589     @client[:badnick] = proc {|data|
590       warning "bad nick (#{data[:nick]})"
591     }
592     @client[:ping] = proc {|data|
593       sendq "PONG #{data[:pingid]}"
594     }
595     @client[:pong] = proc {|data|
596       @last_ping = nil
597     }
598     @client[:nick] = proc {|data|
599       # debug "Message source is #{data[:source].inspect}"
600       # debug "Bot is #{myself.inspect}"
601       source = data[:source]
602       old = data[:oldnick]
603       new = data[:newnick]
604       m = NickMessage.new(self, server, source, old, new)
605       m.is_on = data[:is_on]
606       if source == myself
607         debug "my nick is now #{new}"
608       end
609       @plugins.irc_delegate("nick", m)
610     }
611     @client[:quit] = proc {|data|
612       source = data[:source]
613       message = data[:message]
614       m = QuitMessage.new(self, server, source, source, message)
615       m.was_on = data[:was_on]
616       @plugins.irc_delegate("quit", m)
617     }
618     @client[:mode] = proc {|data|
619       m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
620       m.modes = data[:modes]
621       @plugins.delegate "modechange", m
622     }
623     @client[:whois] = proc {|data|
624       source = data[:source]
625       target = server.get_user(data[:whois][:nick])
626       m = WhoisMessage.new(self, server, source, target, data[:whois])
627       @plugins.delegate "whois", m
628     }
629     @client[:list] = proc {|data|
630       source = data[:source]
631       m = ListMessage.new(self, server, source, source, data[:list])
632       @plugins.delegate "irclist", m
633     }
634     @client[:join] = proc {|data|
635       m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
636       sendq("MODE #{data[:channel]}", nil, 0) if m.address?
637       @plugins.irc_delegate("join", m)
638       sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
639     }
640     @client[:part] = proc {|data|
641       m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
642       @plugins.irc_delegate("part", m)
643     }
644     @client[:kick] = proc {|data|
645       m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
646       @plugins.irc_delegate("kick", m)
647     }
648     @client[:invite] = proc {|data|
649       m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
650       @plugins.irc_delegate("invite", m)
651     }
652     @client[:changetopic] = proc {|data|
653       m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
654       m.info_or_set = :set
655       @plugins.irc_delegate("topic", m)
656     }
657     # @client[:topic] = proc { |data|
658     #   irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
659     # }
660     @client[:topicinfo] = proc { |data|
661       channel = data[:channel]
662       topic = channel.topic
663       m = TopicMessage.new(self, server, data[:source], channel, topic)
664       m.info_or_set = :info
665       @plugins.irc_delegate("topic", m)
666     }
667     @client[:names] = proc { |data|
668       m = NamesMessage.new(self, server, server, data[:channel])
669       m.users = data[:users]
670       @plugins.delegate "names", m
671     }
672     @client[:banlist] = proc { |data|
673       m = BanlistMessage.new(self, server, server, data[:channel])
674       m.bans = data[:bans]
675       @plugins.delegate "banlist", m
676     }
677     @client[:nosuchtarget] = proc { |data|
678       m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
679       @plugins.delegate "nosuchtarget", m
680     }
681     @client[:error] = proc { |data|
682       raise ServerError, data[:message]
683     }
684     @client[:unknown] = proc { |data|
685       #debug "UNKNOWN: #{data[:serverstring]}"
686       m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
687       @plugins.delegate "unknown_message", m
688     }
689
690     set_default_send_options :newlines => @config['send.newlines'].to_sym,
691       :join_with => @config['send.join_with'].dup,
692       :max_lines => @config['send.max_lines'],
693       :overlong => @config['send.overlong'].to_sym,
694       :split_at => Regexp.new(@config['send.split_at']),
695       :purge_split => @config['send.purge_split'],
696       :truncate_text => @config['send.truncate_text'].dup
697
698     trap_signals
699   end
700
701   # Determine (if possible) a valid path to a CA certificate bundle. 
702   def default_ssl_ca_file
703     [ '/etc/ssl/certs/ca-certificates.crt', # Ubuntu/Debian
704       '/etc/ssl/certs/ca-bundle.crt', # Amazon Linux
705       '/etc/ssl/ca-bundle.pem', # OpenSUSE
706       '/etc/pki/tls/certs/ca-bundle.crt' # Fedora/RHEL
707     ].find do |file|
708       File.readable? file
709     end
710   end
711
712   def default_ssl_ca_path
713     file = default_ssl_ca_file
714     File.dirname file if file
715   end
716
717   # Determine if tokyocabinet is installed, if it is use it as a default.
718   def default_db
719     begin
720       require 'tokyocabinet'
721       return 'tc'
722     rescue LoadError
723       return 'dbm'
724     end
725   end
726
727   def repopulate_botclass_directory
728     template_dir = File.join Config::datadir, 'templates'
729     if FileTest.directory? @botclass
730       # compare the templates dir with the current botclass dir, filling up the
731       # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
732       # :update option, so we have to do it manually.
733       # Note that we use the */** pattern because we don't want to match
734       # keywords.rbot, which gets deleted on load and would therefore be missing
735       # always
736       missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
737       missing.map do |f|
738         dest = File.join(@botclass, f)
739         FileUtils.mkdir_p(File.dirname(dest))
740         FileUtils.cp File.join(template_dir, f), dest
741       end
742     else
743       log "no #{@botclass} directory found, creating from templates..."
744       if FileTest.exist? @botclass
745         error "file #{@botclass} exists but isn't a directory"
746         exit 2
747       end
748       FileUtils.cp_r template_dir, @botclass
749     end
750   end
751
752   # Return a path under the current botclass by joining the mentioned
753   # components. The components are automatically converted to String
754   def path(*components)
755     File.join(@botclass, *(components.map {|c| c.to_s}))
756   end
757
758   def setup_plugins_path
759     plugdir_default = File.join(Config::datadir, 'plugins')
760     plugdir_local = File.join(@botclass, 'plugins')
761     Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
762
763     @plugins.clear_botmodule_dirs
764     @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
765     @plugins.add_core_module_dir(Config::coredir)
766     if FileTest.directory? plugdir_local
767       @plugins.add_plugin_dir(plugdir_local)
768     else
769       warning "local plugin location #{plugdir_local} is not a directory"
770     end
771
772     @config['plugins.path'].each do |_|
773         path = _.sub(/^\(default\)/, plugdir_default)
774         @plugins.add_plugin_dir(path)
775     end
776   end
777
778   def set_default_send_options(opts={})
779     # Default send options for NOTICE and PRIVMSG
780     unless defined? @default_send_options
781       @default_send_options = {
782         :queue_channel => nil,      # use default queue channel
783         :queue_ring => nil,         # use default queue ring
784         :newlines => :split,        # or :join
785         :join_with => ' ',          # by default, use a single space
786         :max_lines => 0,          # maximum number of lines to send with a single command
787         :overlong => :split,        # or :truncate
788         # TODO an array of splitpoints would be preferrable for this option:
789         :split_at => /\s+/,         # by default, split overlong lines at whitespace
790         :purge_split => true,       # should the split string be removed?
791         :truncate_text => "#{Reverse}...#{Reverse}"  # text to be appened when truncating
792       }
793     end
794     @default_send_options.update opts unless opts.empty?
795   end
796
797   # checks if we should be quiet on a channel
798   def quiet_on?(channel)
799     ch = channel.downcase
800     return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
801   end
802
803   def set_quiet(channel = nil)
804     if channel
805       ch = channel.downcase.dup
806       @not_quiet.delete(ch)
807       @quiet << ch
808     else
809       @quiet.clear
810       @not_quiet.clear
811       @quiet << '*'
812     end
813   end
814
815   def reset_quiet(channel = nil)
816     if channel
817       ch = channel.downcase.dup
818       @quiet.delete(ch)
819       @not_quiet << ch
820     else
821       @quiet.clear
822       @not_quiet.clear
823     end
824   end
825
826   # things to do when we receive a signal
827   def handle_signal(sig)
828     func = case sig
829            when 'SIGHUP'
830              :restart
831            when 'SIGUSR1'
832              :reconnect
833            else
834              :quit
835            end
836     debug "received #{sig}, queueing #{func}"
837     # this is not an interruption if we just need to reconnect
838     $interrupted += 1 unless func == :reconnect
839     self.send(func) unless @quit_mutex.locked?
840     debug "interrupted #{$interrupted} times"
841     if $interrupted >= 3
842       debug "drastic!"
843       exit 2
844     end
845   end
846
847   # trap signals
848   def trap_signals
849     begin
850       %w(SIGINT SIGTERM SIGHUP SIGUSR1).each do |sig|
851         trap(sig) { Thread.new { handle_signal sig } }
852       end
853     rescue ArgumentError => e
854       debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
855     rescue Exception => e
856       debug "failed to trap signals: #{e.pretty_inspect}"
857     end
858   end
859
860   # connect the bot to IRC
861   def connect
862     # make sure we don't have any spurious ping checks running
863     # (and initialize the vars if this is the first time we connect)
864     stop_server_pings
865     begin
866       quit if $interrupted > 0
867       @socket.connect
868       @last_rec = Time.now
869     rescue Exception => e
870       uri = @socket.server_uri || '<unknown>'
871       error "failed to connect to IRC server at #{uri}"
872       error e
873       raise
874     end
875     quit if $interrupted > 0
876
877     realname = @config['irc.name'].clone || 'Ruby bot'
878     realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
879
880     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
881     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
882     quit if $interrupted > 0
883     myself.nick = @config['irc.nick']
884     myself.user = @config['irc.user']
885   end
886
887   # disconnect the bot from IRC, if connected, and then connect (again)
888   def reconnect(message=nil, too_fast=0)
889     # we will wait only if @last_rec was not nil, i.e. if we were connected or
890     # got disconnected by a network error
891     # if someone wants to manually call disconnect() _and_ reconnect(), they
892     # will have to take care of the waiting themselves
893     will_wait = !!@last_rec
894
895     if @socket.connected?
896       disconnect(message)
897     end
898
899     begin
900       if will_wait
901         log "\n\nDisconnected\n\n"
902
903         quit if $interrupted > 0
904
905         log "\n\nWaiting to reconnect\n\n"
906         sleep @config['server.reconnect_wait']
907         if too_fast > 0
908           tf = too_fast*@config['server.reconnect_wait']
909           tfu = Utils.secs_to_string(tf)
910           log "Will sleep for an extra #{tf}s (#{tfu})"
911           sleep tf
912         end
913       end
914
915       connect
916     rescue SystemExit
917       exit 0
918     rescue Exception => e
919       error e
920       will_wait = true
921       retry
922     end
923   end
924
925   # begin event handling loop
926   def mainloop
927     while true
928       too_fast = 0
929       quit_msg = nil
930       valid_recv = false # did we receive anything (valid) from the server yet?
931       begin
932         reconnect(quit_msg, too_fast)
933         quit if $interrupted > 0
934         valid_recv = false
935         while @socket.connected?
936           quit if $interrupted > 0
937
938           # Wait for messages and process them as they arrive. If nothing is
939           # received, we call the ping_server() method that will PING the
940           # server if appropriate, or raise a TimeoutError if no PONG has been
941           # received in the user-chosen timeout since the last PING sent.
942           if @socket.select(1)
943             break unless reply = @socket.gets
944             @last_rec = Time.now
945             @client.process reply
946             valid_recv = true
947             too_fast = 0
948           else
949             ping_server
950           end
951         end
952
953       # I despair of this. Some of my users get "connection reset by peer"
954       # exceptions that ARENT SocketError's. How am I supposed to handle
955       # that?
956       rescue SystemExit
957         exit 0
958       rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
959         error "network exception: #{e.pretty_inspect}"
960         quit_msg = e.to_s
961         too_fast += 10 if valid_recv
962       rescue ServerMessageParseError => e
963         # if the bot tried reconnecting too often, we can get forcefully
964         # disconnected by the server, while still receiving an empty message
965         # wait at least 10 minutes in this case
966         if e.message.empty?
967           oldtf = too_fast
968           too_fast = [too_fast, 300].max
969           too_fast*= 2
970           log "Empty message from server, extra delay multiplier #{oldtf} -> #{too_fast}"
971         end
972         quit_msg = "Unparseable Server Message: #{e.message.inspect}"
973         retry
974       rescue ServerError => e
975         quit_msg = "server ERROR: " + e.message
976         debug quit_msg
977         idx = e.message.index("connect too fast")
978         debug "'connect too fast' @ #{idx}"
979         if idx
980           oldtf = too_fast
981           too_fast += (idx+1)*2
982           log "Reconnecting too fast, extra delay multiplier #{oldtf} -> #{too_fast}"
983         end
984         idx = e.message.index(/a(uto)kill/i)
985         debug "'autokill' @ #{idx}"
986         if idx
987           # we got auto-killed. since we don't have an easy way to tell
988           # if it's permanent or temporary, we just set a rather high
989           # reconnection timeout
990           oldtf = too_fast
991           too_fast += (idx+1)*5
992           log "Killed by server, extra delay multiplier #{oldtf} -> #{too_fast}"
993         end
994         retry
995       rescue Exception => e
996         error "non-net exception: #{e.pretty_inspect}"
997         quit_msg = e.to_s
998       rescue => e
999         fatal "unexpected exception: #{e.pretty_inspect}"
1000         exit 2
1001       end
1002     end
1003   end
1004
1005   # type:: message type
1006   # where:: message target
1007   # message:: message text
1008   # send message +message+ of type +type+ to target +where+
1009   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1010   # relevant say() or notice() methods. This one should be used for IRCd
1011   # extensions you want to use in modules.
1012   def sendmsg(original_type, original_where, original_message, options={})
1013
1014     # filter message with sendmsg filters
1015     ds = DataStream.new original_message.to_s.dup,
1016       :type => original_type, :dest => original_where,
1017       :options => @default_send_options.merge(options)
1018     filters = filter_names(:sendmsg)
1019     filters.each do |fname|
1020       debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1021       ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1022     end
1023
1024     opts = ds[:options]
1025     type = ds[:type]
1026     where = ds[:dest]
1027     filtered = ds[:text]
1028
1029     if defined? WebServiceUser and where.instance_of? WebServiceUser
1030       debug 'sendmsg to web service!'
1031       where.response << filtered
1032       return
1033     end
1034
1035     # For starters, set up appropriate queue channels and rings
1036     mchan = opts[:queue_channel]
1037     mring = opts[:queue_ring]
1038     if mchan
1039       chan = mchan
1040     else
1041       chan = where
1042     end
1043     if mring
1044       ring = mring
1045     else
1046       case where
1047       when User
1048         ring = 1
1049       else
1050         ring = 2
1051       end
1052     end
1053
1054     multi_line = filtered.gsub(/[\r\n]+/, "\n")
1055
1056     # if target is a channel with nocolor modes, strip colours
1057     if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1058       multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1059     end
1060
1061     messages = Array.new
1062     case opts[:newlines]
1063     when :join
1064       messages << [multi_line.gsub("\n", opts[:join_with])]
1065     when :split
1066       multi_line.each_line { |line|
1067         line.chomp!
1068         next unless(line.size > 0)
1069         messages << line
1070       }
1071     else
1072       raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1073     end
1074
1075     # The IRC protocol requires that each raw message must be not longer
1076     # than 512 characters. From this length with have to subtract the EOL
1077     # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1078     # that will be prepended by the server to all of our messages.
1079
1080     # The maximum raw message length we can send is therefore 512 - 2 - 2
1081     # minus the length of our hostmask.
1082
1083     max_len = 508 - myself.fullform.size
1084
1085     # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1086     # will have a + or - prepended
1087     if server.capabilities[:"identify-msg"]
1088       max_len -= 1
1089     end
1090
1091     # When splitting the message, we'll be prefixing the following string:
1092     # (e.g. "PRIVMSG #rbot :")
1093     fixed = "#{type} #{where} :"
1094
1095     # And this is what's left
1096     left = max_len - fixed.size
1097
1098     truncate = opts[:truncate_text]
1099     truncate = @default_send_options[:truncate_text] if truncate.size > left
1100     truncate = "" if truncate.size > left
1101
1102     all_lines = messages.map { |line|
1103       if line.size < left
1104         line
1105       else
1106         case opts[:overlong]
1107         when :split
1108           msg = line.dup
1109           sub_lines = Array.new
1110           begin
1111             sub_lines << msg.slice!(0, left)
1112             break if msg.empty?
1113             lastspace = sub_lines.last.rindex(opts[:split_at])
1114             if lastspace
1115               msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1116               msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1117             end
1118           end until msg.empty?
1119           sub_lines
1120         when :truncate
1121           line.slice(0, left - truncate.size) << truncate
1122         else
1123           raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1124         end
1125       end
1126     }.flatten
1127
1128     if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1129       lines = all_lines[0...opts[:max_lines]]
1130       new_last = lines.last.slice(0, left - truncate.size) << truncate
1131       lines.last.replace(new_last)
1132     else
1133       lines = all_lines
1134     end
1135
1136     lines.each { |line|
1137       sendq "#{fixed}#{line}", chan, ring
1138       delegate_sent(type, where, line)
1139     }
1140   end
1141
1142   # queue an arbitraty message for the server
1143   def sendq(message="", chan=nil, ring=0)
1144     # temporary
1145     @socket.queue(message, chan, ring)
1146   end
1147
1148   # send a notice message to channel/nick +where+
1149   def notice(where, message, options={})
1150     return if where.kind_of?(Channel) and quiet_on?(where)
1151     sendmsg "NOTICE", where, message, options
1152   end
1153
1154   # say something (PRIVMSG) to channel/nick +where+
1155   def say(where, message, options={})
1156     return if where.kind_of?(Channel) and quiet_on?(where)
1157     sendmsg "PRIVMSG", where, message, options
1158   end
1159
1160   def ctcp_notice(where, command, message, options={})
1161     return if where.kind_of?(Channel) and quiet_on?(where)
1162     sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1163   end
1164
1165   def ctcp_say(where, command, message, options={})
1166     return if where.kind_of?(Channel) and quiet_on?(where)
1167     sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1168   end
1169
1170   # perform a CTCP action with message +message+ to channel/nick +where+
1171   def action(where, message, options={})
1172     ctcp_say(where, 'ACTION', message, options)
1173   end
1174
1175   # quick way to say "okay" (or equivalent) to +where+
1176   def okay(where)
1177     say where, @lang.get("okay")
1178   end
1179
1180   # set topic of channel +where+ to +topic+
1181   # can also be used to retrieve the topic of channel +where+
1182   # by omitting the last argument
1183   def topic(where, topic=nil)
1184     if topic.nil?
1185       sendq "TOPIC #{where}", where, 2
1186     else
1187       sendq "TOPIC #{where} :#{topic}", where, 2
1188     end
1189   end
1190
1191   def disconnect(message=nil)
1192     message = @lang.get("quit") if (!message || message.empty?)
1193     if @socket.connected?
1194       begin
1195         debug "Clearing socket"
1196         @socket.clearq
1197         debug "Sending quit message"
1198         @socket.emergency_puts "QUIT :#{message}"
1199         debug "Logging quits"
1200         delegate_sent('QUIT', myself, message)
1201         debug "Flushing socket"
1202         @socket.flush
1203       rescue SocketError => e
1204         error "error while disconnecting socket: #{e.pretty_inspect}"
1205       end
1206       debug "Shutting down socket"
1207       @socket.shutdown
1208     end
1209     stop_server_pings
1210     @client.reset
1211   end
1212
1213   # disconnect from the server and cleanup all plugins and modules
1214   def shutdown(message=nil)
1215     @quit_mutex.synchronize do
1216       debug "Shutting down: #{message}"
1217       ## No we don't restore them ... let everything run through
1218       # begin
1219       #   trap("SIGINT", "DEFAULT")
1220       #   trap("SIGTERM", "DEFAULT")
1221       #   trap("SIGHUP", "DEFAULT")
1222       # rescue => e
1223       #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1224       # end
1225       debug "\tdisconnecting..."
1226       disconnect(message)
1227       debug "\tstopping timer..."
1228       @timer.stop
1229       debug "\tsaving ..."
1230       save
1231       debug "\tcleaning up ..."
1232       @save_mutex.synchronize do
1233         begin
1234           @plugins.cleanup
1235         rescue
1236           debug "\tignoring cleanup error: #{$!}"
1237         end
1238       end
1239       # debug "\tstopping timers ..."
1240       # @timer.stop
1241       # debug "Closing registries"
1242       # @registry.close
1243       log "rbot quit (#{message})"
1244     end
1245   end
1246
1247   # message:: optional IRC quit message
1248   # quit IRC, shutdown the bot
1249   def quit(message=nil)
1250     begin
1251       shutdown(message)
1252     ensure
1253       exit 0
1254     end
1255   end
1256
1257   # totally shutdown and respawn the bot
1258   def restart(message=nil)
1259     message = _("restarting, back in %{wait}...") % {
1260       :wait => @config['server.reconnect_wait']
1261     } if (!message || message.empty?)
1262     shutdown(message)
1263     sleep @config['server.reconnect_wait']
1264     begin
1265       # now we re-exec
1266       # Note, this fails on Windows
1267       debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1268       Dir.chdir(@run_dir)
1269       exec($0, *@argv)
1270     rescue Errno::ENOENT
1271       exec("ruby", *(@argv.unshift $0))
1272     rescue Exception => e
1273       $interrupted += 1
1274       raise e
1275     end
1276   end
1277
1278   # call the save method for all or the specified botmodule
1279   #
1280   # :botmodule ::
1281   #   optional botmodule to save
1282   def save(botmodule=nil)
1283     @save_mutex.synchronize do
1284       @plugins.save(botmodule)
1285     end
1286   end
1287
1288   # call the rescan method for all or just the specified botmodule
1289   #
1290   # :botmodule ::
1291   #   instance of the botmodule to rescan
1292   def rescan(botmodule=nil)
1293     debug "\tstopping timer..."
1294     @timer.stop
1295     @save_mutex.synchronize do
1296       # @lang.rescan
1297       @plugins.rescan(botmodule)
1298     end
1299     @timer.start
1300   end
1301
1302   # channel:: channel to join
1303   # key::     optional channel key if channel is +s
1304   # join a channel
1305   def join(channel, key=nil)
1306     if(key)
1307       sendq "JOIN #{channel} :#{key}", channel, 2
1308     else
1309       sendq "JOIN #{channel}", channel, 2
1310     end
1311   end
1312
1313   # part a channel
1314   def part(channel, message="")
1315     sendq "PART #{channel} :#{message}", channel, 2
1316   end
1317
1318   # attempt to change bot's nick to +name+
1319   def nickchg(name)
1320     sendq "NICK #{name}"
1321   end
1322
1323   # changing mode
1324   def mode(channel, mode, target=nil)
1325     sendq "MODE #{channel} #{mode} #{target}", channel, 2
1326   end
1327
1328   # asking whois
1329   def whois(nick, target=nil)
1330     sendq "WHOIS #{target} #{nick}", nil, 0
1331   end
1332
1333   # kicking a user
1334   def kick(channel, user, msg)
1335     sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1336   end
1337
1338   # m::     message asking for help
1339   # topic:: optional topic help is requested for
1340   # respond to online help requests
1341   def help(topic=nil)
1342     topic = nil if topic == ""
1343     case topic
1344     when nil
1345       helpstr = _("help topics: ")
1346       helpstr += @plugins.helptopics
1347       helpstr += _(" (help <topic> for more info)")
1348     else
1349       unless(helpstr = @plugins.help(topic))
1350         helpstr = _("no help for topic %{topic}") % { :topic => topic }
1351       end
1352     end
1353     return helpstr
1354   end
1355
1356   # returns a string describing the current status of the bot (uptime etc)
1357   def status
1358     secs_up = Time.new - @startup_time
1359     uptime = Utils.secs_to_string secs_up
1360     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1361     return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1362              {
1363                :up => uptime, :plug => @plugins.length,
1364                :sent => @socket.lines_sent, :recv => @socket.lines_received
1365              })
1366   end
1367
1368   # We want to respond to a hung server in a timely manner. If nothing was received
1369   # in the user-selected timeout and we haven't PINGed the server yet, we PING
1370   # the server. If the PONG is not received within the user-defined timeout, we
1371   # assume we're in ping timeout and act accordingly.
1372   def ping_server
1373     act_timeout = @config['server.ping_timeout']
1374     return if act_timeout <= 0
1375     now = Time.now
1376     if @last_rec && now > @last_rec + act_timeout
1377       if @last_ping.nil?
1378         # No previous PING pending, send a new one
1379         sendq "PING :rbot"
1380         @last_ping = Time.now
1381       else
1382         diff = now - @last_ping
1383         if diff > act_timeout
1384           debug "no PONG from server in #{diff} seconds, reconnecting"
1385           # the actual reconnect is handled in the main loop:
1386           raise TimeoutError, "no PONG from server in #{diff} seconds"
1387         end
1388       end
1389     end
1390   end
1391
1392   def stop_server_pings
1393     # cancel previous PINGs and reset time of last RECV
1394     @last_ping = nil
1395     @last_rec = nil
1396   end
1397
1398   private
1399
1400   # delegate sent messages
1401   def delegate_sent(type, where, message)
1402     args = [self, server, myself, server.user_or_channel(where.to_s), message]
1403     case type
1404       when "NOTICE"
1405         m = NoticeMessage.new(*args)
1406       when "PRIVMSG"
1407         m = PrivMessage.new(*args)
1408       when "QUIT"
1409         m = QuitMessage.new(*args)
1410         m.was_on = myself.channels
1411     end
1412     @plugins.delegate('sent', m)
1413   end
1414
1415 end
1416
1417 end