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