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