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