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