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