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