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