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