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