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