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