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