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