]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
fix: write override behavior
[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     # Time at which the last PING was sent
377     @last_ping = nil
378     # Time at which the last line was RECV'd from the server
379     @last_rec = nil
380
381     @startup_time = Time.new
382
383     begin
384       @config = Config.manager
385       @config.bot_associate(self)
386     rescue Exception => e
387       fatal e
388       exit 2
389     end
390
391     if @config['core.run_as_daemon']
392       $daemonize = true
393     end
394
395     @registry_factory = Registry.new @config['core.db']
396     @registry_factory.migrate_registry_folder(path)
397
398     @logfile = @config['log.file']
399     if @logfile.class != String || @logfile.empty?
400       logfname =  File.basename(botclass).gsub(/^\.+/,'')
401       logfname << ".log"
402       @logfile = File.join(botclass, logfname)
403       debug "Using `#{@logfile}' as debug log"
404     end
405
406     LoggerManager.instance.flush
407
408     # See http://blog.humlab.umu.se/samuel/archives/000107.html
409     # for the backgrounding code
410     if $daemonize
411       begin
412         exit if fork
413         Process.setsid
414         exit if fork
415       rescue NotImplementedError
416         warning "Could not background, fork not supported"
417       rescue SystemExit
418         exit 0
419       rescue Exception => e
420         warning "Could not background. #{e.pretty_inspect}"
421       end
422       Dir.chdir botclass
423       # File.umask 0000                # Ensure sensible umask. Adjust as needed.
424     end
425
426     # setup logger based on bot configuration, if not set from the command line
427     loglevel_set = $opts.has_key?('debug') or $opts.has_key?('loglevel')
428     LoggerManager.instance.set_level(@config['log.level']) unless loglevel_set
429
430     # Set the logfile
431     LoggerManager.instance.set_logfile(@logfile, @config['log.keep'], @config['log.max_size'])
432
433     if $daemonize
434       log "Redirecting standard input/output/error, console logger disabled"
435       LoggerManager.instance.flush
436       LoggerManager.instance.disable_console_logger
437
438       [$stdin, $stdout, $stderr].each do |fd|
439         begin
440           fd.reopen "/dev/null"
441         rescue Errno::ENOENT
442           # On Windows, there's not such thing as /dev/null
443           fd.reopen "NUL"
444         end
445       end
446
447       def $stdout.write(*args)
448         str = args.map { |s| s.to_s }.join("")
449         log str, 2
450         return str.bytesize
451       end
452       def $stderr.write(*args)
453         str = args.map { |s| s.to_s }.join("")
454         if str.to_s.match(/:\d+: warning:/)
455           warning str, 2
456         else
457           error str, 2
458         end
459         return str.bytesize
460       end
461
462       LoggerManager.instance.log_session_start
463     end
464
465     File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
466       pf << "#{$$}\n"
467     end
468
469     @timer = Timer.new
470     @save_mutex = Mutex.new
471     if @config['core.save_every'] > 0
472       @save_timer = @timer.add(@config['core.save_every']) { save }
473     else
474       @save_timer = nil
475     end
476     @quit_mutex = Mutex.new
477
478     @plugins = nil
479     @lang = Language.new(self, @config['core.language'])
480     @httputil = Utils::HttpUtil.new(self)
481
482     begin
483       @auth = Auth::manager
484       @auth.bot_associate(self)
485       # @auth.load("#{botclass}/botusers.yaml")
486     rescue Exception => e
487       fatal e
488       exit 2
489     end
490     @auth.everyone.set_default_permission("*", true)
491     @auth.botowner.password= @config['auth.password']
492
493     @plugins = Plugins::manager
494     @plugins.bot_associate(self)
495     setup_plugins_path()
496
497     if @config['server.name']
498         debug "upgrading configuration (server.name => server.list)"
499         srv_uri = 'irc://' + @config['server.name']
500         srv_uri += ":#{@config['server.port']}" if @config['server.port']
501         @config.items['server.list'.to_sym].set_string(srv_uri)
502         @config.delete('server.name'.to_sym)
503         @config.delete('server.port'.to_sym)
504         debug "server.list is now #{@config['server.list'].inspect}"
505     end
506
507     @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], 
508                               :ssl => @config['server.ssl'],
509                               :ssl_verify => @config['server.ssl_verify'],
510                               :ssl_ca_file => @config['server.ssl_ca_file'],
511                               :ssl_ca_path => @config['server.ssl_ca_path'],
512                               :penalty_pct => @config['send.penalty_pct'])
513     @client = Client.new
514
515     @plugins.scan
516
517     # Channels where we are quiet
518     # Array of channels names where the bot should be quiet
519     # '*' means all channels
520     #
521     @quiet = Set.new
522     # but we always speak here
523     @not_quiet = Set.new
524
525     # the nick we want, if it's different from the irc.nick config value
526     # (e.g. as set by a !nick command)
527     @wanted_nick = nil
528
529     @client[:welcome] = proc {|data|
530       m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
531
532       @plugins.delegate("welcome", m)
533       @plugins.delegate("connect")
534     }
535
536     # TODO the next two @client should go into rfc2812.rb, probably
537     # Since capabs are two-steps processes, server.supports[:capab]
538     # should be a three-state: nil, [], [....]
539     asked_for = { :"identify-msg" => false }
540     @client[:isupport] = proc { |data|
541       if server.supports[:capab] and !asked_for[:"identify-msg"]
542         sendq "CAPAB IDENTIFY-MSG"
543         asked_for[:"identify-msg"] = true
544       end
545     }
546     @client[:datastr] = proc { |data|
547       if data[:text] == "IDENTIFY-MSG"
548         server.capabilities[:"identify-msg"] = true
549       else
550         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
551       end
552     }
553
554     @client[:privmsg] = proc { |data|
555       m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
556       # debug "Message source is #{data[:source].inspect}"
557       # debug "Message target is #{data[:target].inspect}"
558       # debug "Bot is #{myself.inspect}"
559
560       @config['irc.ignore_channels'].each { |channel|
561         if m.target.downcase == channel.downcase
562           m.ignored = true
563           break
564         end
565       }
566       @config['irc.ignore_users'].each { |mask|
567         if m.source.matches?(server.new_netmask(mask))
568           m.ignored = true
569           break
570         end
571       } unless m.ignored
572
573       @plugins.irc_delegate('privmsg', m)
574     }
575     @client[:notice] = proc { |data|
576       message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
577       # pass it off to plugins that want to hear everything
578       @plugins.irc_delegate "notice", message
579     }
580     @client[:motd] = proc { |data|
581       m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
582       @plugins.delegate "motd", m
583     }
584     @client[:nicktaken] = proc { |data|
585       new = "#{data[:nick]}_"
586       nickchg new
587       # If we're setting our nick at connection because our choice was taken,
588       # we have to fix our nick manually, because there will be no NICK message
589       # to inform us that our nick has been changed.
590       if data[:target] == '*'
591         debug "setting my connection nick to #{new}"
592         @client.user.nick = new
593       end
594       @plugins.delegate "nicktaken", data[:nick]
595     }
596     @client[:badnick] = proc {|data|
597       warning "bad nick (#{data[:nick]})"
598     }
599     @client[:ping] = proc {|data|
600       sendq "PONG #{data[:pingid]}"
601     }
602     @client[:pong] = proc {|data|
603       @last_ping = nil
604     }
605     @client[:nick] = proc {|data|
606       # debug "Message source is #{data[:source].inspect}"
607       # debug "Bot is #{myself.inspect}"
608       source = data[:source]
609       old = data[:oldnick]
610       new = data[:newnick]
611       m = NickMessage.new(self, server, source, old, new)
612       m.is_on = data[:is_on]
613       if source == myself
614         debug "my nick is now #{new}"
615       end
616       @plugins.irc_delegate("nick", m)
617     }
618     @client[:quit] = proc {|data|
619       source = data[:source]
620       message = data[:message]
621       m = QuitMessage.new(self, server, source, source, message)
622       m.was_on = data[:was_on]
623       @plugins.irc_delegate("quit", m)
624     }
625     @client[:mode] = proc {|data|
626       m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
627       m.modes = data[:modes]
628       @plugins.delegate "modechange", m
629     }
630     @client[:whois] = proc {|data|
631       source = data[:source]
632       target = server.get_user(data[:whois][:nick])
633       m = WhoisMessage.new(self, server, source, target, data[:whois])
634       @plugins.delegate "whois", m
635     }
636     @client[:list] = proc {|data|
637       source = data[:source]
638       m = ListMessage.new(self, server, source, source, data[:list])
639       @plugins.delegate "irclist", m
640     }
641     @client[:join] = proc {|data|
642       m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
643       sendq("MODE #{data[:channel]}", nil, 0) if m.address?
644       @plugins.irc_delegate("join", m)
645       sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
646     }
647     @client[:part] = proc {|data|
648       m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
649       @plugins.irc_delegate("part", m)
650     }
651     @client[:kick] = proc {|data|
652       m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
653       @plugins.irc_delegate("kick", m)
654     }
655     @client[:invite] = proc {|data|
656       m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
657       @plugins.irc_delegate("invite", m)
658     }
659     @client[:changetopic] = proc {|data|
660       m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
661       m.info_or_set = :set
662       @plugins.irc_delegate("topic", m)
663     }
664     # @client[:topic] = proc { |data|
665     #   irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
666     # }
667     @client[:topicinfo] = proc { |data|
668       channel = data[:channel]
669       topic = channel.topic
670       m = TopicMessage.new(self, server, data[:source], channel, topic)
671       m.info_or_set = :info
672       @plugins.irc_delegate("topic", m)
673     }
674     @client[:names] = proc { |data|
675       m = NamesMessage.new(self, server, server, data[:channel])
676       m.users = data[:users]
677       @plugins.delegate "names", m
678     }
679     @client[:banlist] = proc { |data|
680       m = BanlistMessage.new(self, server, server, data[:channel])
681       m.bans = data[:bans]
682       @plugins.delegate "banlist", m
683     }
684     @client[:nosuchtarget] = proc { |data|
685       m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
686       @plugins.delegate "nosuchtarget", m
687     }
688     @client[:error] = proc { |data|
689       raise ServerError, data[:message]
690     }
691     @client[:unknown] = proc { |data|
692       #debug "UNKNOWN: #{data[:serverstring]}"
693       m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
694       @plugins.delegate "unknown_message", m
695     }
696
697     set_default_send_options :newlines => @config['send.newlines'].to_sym,
698       :join_with => @config['send.join_with'].dup,
699       :max_lines => @config['send.max_lines'],
700       :overlong => @config['send.overlong'].to_sym,
701       :split_at => Regexp.new(@config['send.split_at']),
702       :purge_split => @config['send.purge_split'],
703       :truncate_text => @config['send.truncate_text'].dup
704
705     trap_signals
706   end
707
708   # Determine (if possible) a valid path to a CA certificate bundle. 
709   def default_ssl_ca_file
710     [ '/etc/ssl/certs/ca-certificates.crt', # Ubuntu/Debian
711       '/etc/ssl/certs/ca-bundle.crt', # Amazon Linux
712       '/etc/ssl/ca-bundle.pem', # OpenSUSE
713       '/etc/pki/tls/certs/ca-bundle.crt' # Fedora/RHEL
714     ].find do |file|
715       File.readable? file
716     end
717   end
718
719   def default_ssl_ca_path
720     file = default_ssl_ca_file
721     File.dirname file if file
722   end
723
724   # Determine if tokyocabinet is installed, if it is use it as a default.
725   def default_db
726     begin
727       require 'tokyocabinet'
728       return 'tc'
729     rescue LoadError
730       return 'dbm'
731     end
732   end
733
734   def repopulate_botclass_directory
735     template_dir = File.join Config::datadir, 'templates'
736     if FileTest.directory? @botclass
737       # compare the templates dir with the current botclass dir, filling up the
738       # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
739       # :update option, so we have to do it manually.
740       # Note that we use the */** pattern because we don't want to match
741       # keywords.rbot, which gets deleted on load and would therefore be missing
742       # always
743       missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
744       missing.map do |f|
745         dest = File.join(@botclass, f)
746         FileUtils.mkdir_p(File.dirname(dest))
747         FileUtils.cp File.join(template_dir, f), dest
748       end
749     else
750       log "no #{@botclass} directory found, creating from templates..."
751       if FileTest.exist? @botclass
752         error "file #{@botclass} exists but isn't a directory"
753         exit 2
754       end
755       FileUtils.cp_r template_dir, @botclass
756     end
757   end
758
759   # Return a path under the current botclass by joining the mentioned
760   # components. The components are automatically converted to String
761   def path(*components)
762     File.join(@botclass, *(components.map {|c| c.to_s}))
763   end
764
765   def setup_plugins_path
766     plugdir_default = File.join(Config::datadir, 'plugins')
767     plugdir_local = File.join(@botclass, 'plugins')
768     Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
769
770     @plugins.clear_botmodule_dirs
771     @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
772     @plugins.add_core_module_dir(Config::coredir)
773     if FileTest.directory? plugdir_local
774       @plugins.add_plugin_dir(plugdir_local)
775     else
776       warning "local plugin location #{plugdir_local} is not a directory"
777     end
778
779     @config['plugins.path'].each do |_|
780         path = _.sub(/^\(default\)/, plugdir_default)
781         @plugins.add_plugin_dir(path)
782     end
783   end
784
785   def set_default_send_options(opts={})
786     # Default send options for NOTICE and PRIVMSG
787     unless defined? @default_send_options
788       @default_send_options = {
789         :queue_channel => nil,      # use default queue channel
790         :queue_ring => nil,         # use default queue ring
791         :newlines => :split,        # or :join
792         :join_with => ' ',          # by default, use a single space
793         :max_lines => 0,          # maximum number of lines to send with a single command
794         :overlong => :split,        # or :truncate
795         # TODO an array of splitpoints would be preferrable for this option:
796         :split_at => /\s+/,         # by default, split overlong lines at whitespace
797         :purge_split => true,       # should the split string be removed?
798         :truncate_text => "#{Reverse}...#{Reverse}"  # text to be appened when truncating
799       }
800     end
801     @default_send_options.update opts unless opts.empty?
802   end
803
804   # checks if we should be quiet on a channel
805   def quiet_on?(channel)
806     ch = channel.downcase
807     return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
808   end
809
810   def set_quiet(channel = nil)
811     if channel
812       ch = channel.downcase.dup
813       @not_quiet.delete(ch)
814       @quiet << ch
815     else
816       @quiet.clear
817       @not_quiet.clear
818       @quiet << '*'
819     end
820   end
821
822   def reset_quiet(channel = nil)
823     if channel
824       ch = channel.downcase.dup
825       @quiet.delete(ch)
826       @not_quiet << ch
827     else
828       @quiet.clear
829       @not_quiet.clear
830     end
831   end
832
833   # things to do when we receive a signal
834   def handle_signal(sig)
835     func = case sig
836            when 'SIGHUP'
837              :restart
838            when 'SIGUSR1'
839              :reconnect
840            else
841              :quit
842            end
843     debug "received #{sig}, queueing #{func}"
844     # this is not an interruption if we just need to reconnect
845     $interrupted += 1 unless func == :reconnect
846     self.send(func) unless @quit_mutex.locked?
847     debug "interrupted #{$interrupted} times"
848     if $interrupted >= 3
849       debug "drastic!"
850       exit 2
851     end
852   end
853
854   # trap signals
855   def trap_signals
856     begin
857       %w(SIGINT SIGTERM SIGHUP SIGUSR1).each do |sig|
858         trap(sig) { Thread.new { handle_signal sig } }
859       end
860     rescue ArgumentError => e
861       debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
862     rescue Exception => e
863       debug "failed to trap signals: #{e.pretty_inspect}"
864     end
865   end
866
867   # connect the bot to IRC
868   def connect
869     # make sure we don't have any spurious ping checks running
870     # (and initialize the vars if this is the first time we connect)
871     stop_server_pings
872     begin
873       quit if $interrupted > 0
874       @socket.connect
875       @last_rec = Time.now
876     rescue Exception => e
877       uri = @socket.server_uri || '<unknown>'
878       error "failed to connect to IRC server at #{uri}"
879       error e
880       raise
881     end
882     quit if $interrupted > 0
883
884     realname = @config['irc.name'].clone || 'Ruby bot'
885     realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
886
887     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
888     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
889     quit if $interrupted > 0
890     myself.nick = @config['irc.nick']
891     myself.user = @config['irc.user']
892   end
893
894   # disconnect the bot from IRC, if connected, and then connect (again)
895   def reconnect(message=nil, too_fast=0)
896     # we will wait only if @last_rec was not nil, i.e. if we were connected or
897     # got disconnected by a network error
898     # if someone wants to manually call disconnect() _and_ reconnect(), they
899     # will have to take care of the waiting themselves
900     will_wait = !!@last_rec
901
902     if @socket.connected?
903       disconnect(message)
904     end
905
906     begin
907       if will_wait
908         log "\n\nDisconnected\n\n"
909
910         quit if $interrupted > 0
911
912         log "\n\nWaiting to reconnect\n\n"
913         sleep @config['server.reconnect_wait']
914         if too_fast > 0
915           tf = too_fast*@config['server.reconnect_wait']
916           tfu = Utils.secs_to_string(tf)
917           log "Will sleep for an extra #{tf}s (#{tfu})"
918           sleep tf
919         end
920       end
921
922       connect
923     rescue SystemExit
924       exit 0
925     rescue Exception => e
926       error e
927       will_wait = true
928       retry
929     end
930   end
931
932   # begin event handling loop
933   def mainloop
934     @keep_looping = true
935     while @keep_looping
936       too_fast = 0
937       quit_msg = nil
938       valid_recv = false # did we receive anything (valid) from the server yet?
939       begin
940         reconnect(quit_msg, too_fast)
941         quit if $interrupted > 0
942         valid_recv = false
943         while @socket.connected?
944           quit if $interrupted > 0
945
946           # Wait for messages and process them as they arrive. If nothing is
947           # received, we call the ping_server() method that will PING the
948           # server if appropriate, or raise a TimeoutError if no PONG has been
949           # received in the user-chosen timeout since the last PING sent.
950           if @socket.select(1)
951             break unless reply = @socket.gets
952             @last_rec = Time.now
953             @client.process reply
954             valid_recv = true
955             too_fast = 0
956           else
957             ping_server
958           end
959         end
960
961       # I despair of this. Some of my users get "connection reset by peer"
962       # exceptions that ARENT SocketError's. How am I supposed to handle
963       # that?
964       rescue SystemExit
965         @keep_looping = false
966         break
967       rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
968         error "network exception: #{e.pretty_inspect}"
969         quit_msg = e.to_s
970         too_fast += 10 if valid_recv
971       rescue ServerMessageParseError => e
972         # if the bot tried reconnecting too often, we can get forcefully
973         # disconnected by the server, while still receiving an empty message
974         # wait at least 10 minutes in this case
975         if e.message.empty?
976           oldtf = too_fast
977           too_fast = [too_fast, 300].max
978           too_fast*= 2
979           log "Empty message from server, extra delay multiplier #{oldtf} -> #{too_fast}"
980         end
981         quit_msg = "Unparseable Server Message: #{e.message.inspect}"
982         retry
983       rescue ServerError => e
984         quit_msg = "server ERROR: " + e.message
985         debug quit_msg
986         idx = e.message.index("connect too fast")
987         debug "'connect too fast' @ #{idx}"
988         if idx
989           oldtf = too_fast
990           too_fast += (idx+1)*2
991           log "Reconnecting too fast, extra delay multiplier #{oldtf} -> #{too_fast}"
992         end
993         idx = e.message.index(/a(uto)kill/i)
994         debug "'autokill' @ #{idx}"
995         if idx
996           # we got auto-killed. since we don't have an easy way to tell
997           # if it's permanent or temporary, we just set a rather high
998           # reconnection timeout
999           oldtf = too_fast
1000           too_fast += (idx+1)*5
1001           log "Killed by server, extra delay multiplier #{oldtf} -> #{too_fast}"
1002         end
1003         retry
1004       rescue Exception => e
1005         error "non-net exception: #{e.pretty_inspect}"
1006         quit_msg = e.to_s
1007       rescue => e
1008         fatal "unexpected exception: #{e.pretty_inspect}"
1009         exit 2
1010       end
1011     end
1012   end
1013
1014   # type:: message type
1015   # where:: message target
1016   # message:: message text
1017   # send message +message+ of type +type+ to target +where+
1018   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1019   # relevant say() or notice() methods. This one should be used for IRCd
1020   # extensions you want to use in modules.
1021   def sendmsg(original_type, original_where, original_message, options={})
1022
1023     # filter message with sendmsg filters
1024     ds = DataStream.new original_message.to_s.dup,
1025       :type => original_type, :dest => original_where,
1026       :options => @default_send_options.merge(options)
1027     filters = filter_names(:sendmsg)
1028     filters.each do |fname|
1029       debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1030       ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1031     end
1032
1033     opts = ds[:options]
1034     type = ds[:type]
1035     where = ds[:dest]
1036     filtered = ds[:text]
1037
1038     if defined? WebServiceUser and where.instance_of? WebServiceUser
1039       debug 'sendmsg to web service!'
1040       where.response << filtered
1041       return
1042     end
1043
1044     # For starters, set up appropriate queue channels and rings
1045     mchan = opts[:queue_channel]
1046     mring = opts[:queue_ring]
1047     if mchan
1048       chan = mchan
1049     else
1050       chan = where
1051     end
1052     if mring
1053       ring = mring
1054     else
1055       case where
1056       when User
1057         ring = 1
1058       else
1059         ring = 2
1060       end
1061     end
1062
1063     multi_line = filtered.gsub(/[\r\n]+/, "\n")
1064
1065     # if target is a channel with nocolor modes, strip colours
1066     if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1067       multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1068     end
1069
1070     messages = Array.new
1071     case opts[:newlines]
1072     when :join
1073       messages << [multi_line.gsub("\n", opts[:join_with])]
1074     when :split
1075       multi_line.each_line { |line|
1076         line.chomp!
1077         next unless(line.size > 0)
1078         messages << line
1079       }
1080     else
1081       raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1082     end
1083
1084     # The IRC protocol requires that each raw message must be not longer
1085     # than 512 characters. From this length with have to subtract the EOL
1086     # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1087     # that will be prepended by the server to all of our messages.
1088
1089     # The maximum raw message length we can send is therefore 512 - 2 - 2
1090     # minus the length of our hostmask.
1091
1092     max_len = 508 - myself.fullform.size
1093
1094     # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1095     # will have a + or - prepended
1096     if server.capabilities[:"identify-msg"]
1097       max_len -= 1
1098     end
1099
1100     # When splitting the message, we'll be prefixing the following string:
1101     # (e.g. "PRIVMSG #rbot :")
1102     fixed = "#{type} #{where} :"
1103
1104     # And this is what's left
1105     left = max_len - fixed.size
1106
1107     truncate = opts[:truncate_text]
1108     truncate = @default_send_options[:truncate_text] if truncate.size > left
1109     truncate = "" if truncate.size > left
1110
1111     all_lines = messages.map { |line|
1112       if line.size < left
1113         line
1114       else
1115         case opts[:overlong]
1116         when :split
1117           msg = line.dup
1118           sub_lines = Array.new
1119           begin
1120             sub_lines << msg.slice!(0, left)
1121             break if msg.empty?
1122             lastspace = sub_lines.last.rindex(opts[:split_at])
1123             if lastspace
1124               msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1125               msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1126             end
1127           end until msg.empty?
1128           sub_lines
1129         when :truncate
1130           line.slice(0, left - truncate.size) << truncate
1131         else
1132           raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1133         end
1134       end
1135     }.flatten
1136
1137     if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1138       lines = all_lines[0...opts[:max_lines]]
1139       new_last = lines.last.slice(0, left - truncate.size) << truncate
1140       lines.last.replace(new_last)
1141     else
1142       lines = all_lines
1143     end
1144
1145     lines.each { |line|
1146       sendq "#{fixed}#{line}", chan, ring
1147       delegate_sent(type, where, line)
1148     }
1149   end
1150
1151   # queue an arbitraty message for the server
1152   def sendq(message="", chan=nil, ring=0)
1153     # temporary
1154     @socket.queue(message, chan, ring)
1155   end
1156
1157   # send a notice message to channel/nick +where+
1158   def notice(where, message, options={})
1159     return if where.kind_of?(Channel) and quiet_on?(where)
1160     sendmsg "NOTICE", where, message, options
1161   end
1162
1163   # say something (PRIVMSG) to channel/nick +where+
1164   def say(where, message, options={})
1165     return if where.kind_of?(Channel) and quiet_on?(where)
1166     sendmsg "PRIVMSG", where, message, options
1167   end
1168
1169   def ctcp_notice(where, command, message, options={})
1170     return if where.kind_of?(Channel) and quiet_on?(where)
1171     sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1172   end
1173
1174   def ctcp_say(where, command, message, options={})
1175     return if where.kind_of?(Channel) and quiet_on?(where)
1176     sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1177   end
1178
1179   # perform a CTCP action with message +message+ to channel/nick +where+
1180   def action(where, message, options={})
1181     ctcp_say(where, 'ACTION', message, options)
1182   end
1183
1184   # quick way to say "okay" (or equivalent) to +where+
1185   def okay(where)
1186     say where, @lang.get("okay")
1187   end
1188
1189   # set topic of channel +where+ to +topic+
1190   # can also be used to retrieve the topic of channel +where+
1191   # by omitting the last argument
1192   def topic(where, topic=nil)
1193     if topic.nil?
1194       sendq "TOPIC #{where}", where, 2
1195     else
1196       sendq "TOPIC #{where} :#{topic}", where, 2
1197     end
1198   end
1199
1200   def disconnect(message=nil)
1201     message = @lang.get("quit") if (!message || message.empty?)
1202     if @socket.connected?
1203       begin
1204         debug "Clearing socket"
1205         @socket.clearq
1206         debug "Sending quit message"
1207         @socket.emergency_puts "QUIT :#{message}"
1208         debug "Logging quits"
1209         delegate_sent('QUIT', myself, message)
1210         debug "Flushing socket"
1211         @socket.flush
1212       rescue SocketError => e
1213         error "error while disconnecting socket: #{e.pretty_inspect}"
1214       end
1215       debug "Shutting down socket"
1216       @socket.shutdown
1217     end
1218     stop_server_pings
1219     @client.reset
1220   end
1221
1222   # disconnect from the server and cleanup all plugins and modules
1223   def shutdown(message=nil)
1224     @quit_mutex.synchronize do
1225       debug "Shutting down: #{message}"
1226       ## No we don't restore them ... let everything run through
1227       # begin
1228       #   trap("SIGINT", "DEFAULT")
1229       #   trap("SIGTERM", "DEFAULT")
1230       #   trap("SIGHUP", "DEFAULT")
1231       # rescue => e
1232       #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1233       # end
1234       debug "\tdisconnecting..."
1235       disconnect(message)
1236       debug "\tstopping timer..."
1237       @timer.stop
1238       debug "\tsaving ..."
1239       save
1240       debug "\tcleaning up ..."
1241       @save_mutex.synchronize do
1242         begin
1243           @plugins.cleanup
1244         rescue
1245           debug "\tignoring cleanup error: #{$!}"
1246         end
1247       end
1248       @httputil.cleanup
1249       # debug "\tstopping timers ..."
1250       # @timer.stop
1251       # debug "Closing registries"
1252       # @registry.close
1253       log "rbot quit (#{message})"
1254     end
1255   end
1256
1257   # message:: optional IRC quit message
1258   # quit IRC, shutdown the bot
1259   def quit(message=nil)
1260     begin
1261       shutdown(message)
1262     ensure
1263       @keep_looping = false
1264     end
1265   end
1266
1267   # totally shutdown and respawn the bot
1268   def restart(message=nil)
1269     message = _("restarting, back in %{wait}...") % {
1270       :wait => @config['server.reconnect_wait']
1271     } if (!message || message.empty?)
1272     shutdown(message)
1273
1274     Irc::Bot::LoggerManager.instance.flush
1275     Irc::Bot::LoggerManager.instance.log_session_end
1276
1277     sleep @config['server.reconnect_wait']
1278     begin
1279       # now we re-exec
1280       # Note, this fails on Windows
1281       debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1282       Dir.chdir(@run_dir)
1283       exec($0, *@argv)
1284     rescue Errno::ENOENT
1285       exec("ruby", *(@argv.unshift $0))
1286     rescue Exception => e
1287       $interrupted += 1
1288       raise e
1289     end
1290   end
1291
1292   # call the save method for all or the specified botmodule
1293   #
1294   # :botmodule ::
1295   #   optional botmodule to save
1296   def save(botmodule=nil)
1297     @save_mutex.synchronize do
1298       @plugins.save(botmodule)
1299     end
1300   end
1301
1302   # call the rescan method for all or just the specified botmodule
1303   #
1304   # :botmodule ::
1305   #   instance of the botmodule to rescan
1306   def rescan(botmodule=nil)
1307     debug "\tstopping timer..."
1308     @timer.stop
1309     @save_mutex.synchronize do
1310       # @lang.rescan
1311       @plugins.rescan(botmodule)
1312     end
1313     @timer.start
1314   end
1315
1316   # channel:: channel to join
1317   # key::     optional channel key if channel is +s
1318   # join a channel
1319   def join(channel, key=nil)
1320     if(key)
1321       sendq "JOIN #{channel} :#{key}", channel, 2
1322     else
1323       sendq "JOIN #{channel}", channel, 2
1324     end
1325   end
1326
1327   # part a channel
1328   def part(channel, message="")
1329     sendq "PART #{channel} :#{message}", channel, 2
1330   end
1331
1332   # attempt to change bot's nick to +name+
1333   def nickchg(name)
1334     sendq "NICK #{name}"
1335   end
1336
1337   # changing mode
1338   def mode(channel, mode, target=nil)
1339     sendq "MODE #{channel} #{mode} #{target}", channel, 2
1340   end
1341
1342   # asking whois
1343   def whois(nick, target=nil)
1344     sendq "WHOIS #{target} #{nick}", nil, 0
1345   end
1346
1347   # kicking a user
1348   def kick(channel, user, msg)
1349     sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1350   end
1351
1352   # m::     message asking for help
1353   # topic:: optional topic help is requested for
1354   # respond to online help requests
1355   def help(topic=nil)
1356     topic = nil if topic == ""
1357     case topic
1358     when nil
1359       helpstr = _("help topics: ")
1360       helpstr += @plugins.helptopics
1361       helpstr += _(" (help <topic> for more info)")
1362     else
1363       unless(helpstr = @plugins.help(topic))
1364         helpstr = _("no help for topic %{topic}") % { :topic => topic }
1365       end
1366     end
1367     return helpstr
1368   end
1369
1370   # returns a string describing the current status of the bot (uptime etc)
1371   def status
1372     secs_up = Time.new - @startup_time
1373     uptime = Utils.secs_to_string secs_up
1374     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1375     return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1376              {
1377                :up => uptime, :plug => @plugins.length,
1378                :sent => @socket.lines_sent, :recv => @socket.lines_received
1379              })
1380   end
1381
1382   # We want to respond to a hung server in a timely manner. If nothing was received
1383   # in the user-selected timeout and we haven't PINGed the server yet, we PING
1384   # the server. If the PONG is not received within the user-defined timeout, we
1385   # assume we're in ping timeout and act accordingly.
1386   def ping_server
1387     act_timeout = @config['server.ping_timeout']
1388     return if act_timeout <= 0
1389     now = Time.now
1390     if @last_rec && now > @last_rec + act_timeout
1391       if @last_ping.nil?
1392         # No previous PING pending, send a new one
1393         sendq "PING :rbot"
1394         @last_ping = Time.now
1395       else
1396         diff = now - @last_ping
1397         if diff > act_timeout
1398           debug "no PONG from server in #{diff} seconds, reconnecting"
1399           # the actual reconnect is handled in the main loop:
1400           raise TimeoutError, "no PONG from server in #{diff} seconds"
1401         end
1402       end
1403     end
1404   end
1405
1406   def stop_server_pings
1407     # cancel previous PINGs and reset time of last RECV
1408     @last_ping = nil
1409     @last_rec = nil
1410   end
1411
1412   private
1413
1414   # delegate sent messages
1415   def delegate_sent(type, where, message)
1416     args = [self, server, myself, server.user_or_channel(where.to_s), message]
1417     case type
1418       when "NOTICE"
1419         m = NoticeMessage.new(*args)
1420       when "PRIVMSG"
1421         m = PrivMessage.new(*args)
1422       when "QUIT"
1423         m = QuitMessage.new(*args)
1424         m.was_on = myself.channels
1425     end
1426     @plugins.delegate('sent', m)
1427   end
1428
1429 end
1430
1431 end