]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
ircbot: optimize ignore loops
[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     Config.register Config::ArrayValue.new('irc.ignore_channels',
310       :default => [],
311       :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)")
312
313     Config.register Config::IntegerValue.new('core.save_every',
314       :default => 60, :validate => Proc.new{|v| v >= 0},
315       :on_change => Proc.new { |bot, v|
316         if @save_timer
317           if v > 0
318             @timer.reschedule(@save_timer, v)
319             @timer.unblock(@save_timer)
320           else
321             @timer.block(@save_timer)
322           end
323         else
324           if v > 0
325             @save_timer = @timer.add(v) { bot.save }
326           end
327           # Nothing to do when v == 0
328         end
329       },
330       :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
331
332     Config.register Config::BooleanValue.new('core.run_as_daemon',
333       :default => false, :requires_restart => true,
334       :desc => "Should the bot run as a daemon?")
335
336     Config.register Config::StringValue.new('log.file',
337       :default => false, :requires_restart => true,
338       :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
339     Config.register Config::IntegerValue.new('log.level',
340       :default => 1, :requires_restart => false,
341       :validate => Proc.new { |v| (0..5).include?(v) },
342       :on_change => Proc.new { |bot, v|
343         $logger.level = v
344       },
345       :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
346     Config.register Config::IntegerValue.new('log.keep',
347       :default => 1, :requires_restart => true,
348       :validate => Proc.new { |v| v >= 0 },
349       :desc => "How many old console messages logfiles to keep")
350     Config.register Config::IntegerValue.new('log.max_size',
351       :default => 10, :requires_restart => true,
352       :validate => Proc.new { |v| v > 0 },
353       :desc => "Maximum console messages logfile size (in megabytes)")
354
355     Config.register Config::ArrayValue.new('plugins.path',
356       :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
357       :requires_restart => false,
358       :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
359       :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")
360
361     Config.register Config::EnumValue.new('send.newlines',
362       :values => ['split', 'join'], :default => 'split',
363       :on_change => Proc.new { |bot, v|
364         bot.set_default_send_options :newlines => v.to_sym
365       },
366       :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")
367     Config.register Config::StringValue.new('send.join_with',
368       :default => ' ',
369       :on_change => Proc.new { |bot, v|
370         bot.set_default_send_options :join_with => v.dup
371       },
372       :desc => "String used to replace newlines when send.newlines is set to join")
373     Config.register Config::IntegerValue.new('send.max_lines',
374       :default => 5,
375       :validate => Proc.new { |v| v >= 0 },
376       :on_change => Proc.new { |bot, v|
377         bot.set_default_send_options :max_lines => v
378       },
379       :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
380     Config.register Config::EnumValue.new('send.overlong',
381       :values => ['split', 'truncate'], :default => 'split',
382       :on_change => Proc.new { |bot, v|
383         bot.set_default_send_options :overlong => v.to_sym
384       },
385       :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")
386     Config.register Config::StringValue.new('send.split_at',
387       :default => '\s+',
388       :on_change => Proc.new { |bot, v|
389         bot.set_default_send_options :split_at => Regexp.new(v)
390       },
391       :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
392     Config.register Config::BooleanValue.new('send.purge_split',
393       :default => true,
394       :on_change => Proc.new { |bot, v|
395         bot.set_default_send_options :purge_split => v
396       },
397       :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
398     Config.register Config::StringValue.new('send.truncate_text',
399       :default => "#{Reverse}...#{Reverse}",
400       :on_change => Proc.new { |bot, v|
401         bot.set_default_send_options :truncate_text => v.dup
402       },
403       :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")
404     Config.register Config::IntegerValue.new('send.penalty_pct',
405       :default => 100,
406       :validate => Proc.new { |v| v >= 0 },
407       :on_change => Proc.new { |bot, v|
408         bot.socket.penalty_pct = v
409       },
410       :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
411
412     @argv = params[:argv]
413     @run_dir = params[:run_dir] || Dir.pwd
414
415     unless FileTest.directory? Config::coredir
416       error "core directory '#{Config::coredir}' not found, did you setup.rb?"
417       exit 2
418     end
419
420     unless FileTest.directory? Config::datadir
421       error "data directory '#{Config::datadir}' not found, did you setup.rb?"
422       exit 2
423     end
424
425     unless botclass and not botclass.empty?
426       # We want to find a sensible default.
427       # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
428       # * On Windows (at least the NT versions) we want to put our stuff in the
429       #   Application Data folder.
430       # We don't use any particular O/S detection magic, exploiting the fact that
431       # Etc.getpwuid is nil on Windows
432       if Etc.getpwuid(Process::Sys.geteuid)
433         botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
434       else
435         if ENV.has_key?('APPDATA')
436           botclass = ENV['APPDATA'].dup
437           botclass.gsub!("\\","/")
438         end
439       end
440       botclass += "/.rbot"
441     end
442     botclass = File.expand_path(botclass)
443     @botclass = botclass.gsub(/\/$/, "")
444
445     if FileTest.directory? botclass
446       # compare the templates dir with the current botclass, and fill it in with
447       # any missing file.
448       # Sadly, FileUtils.cp_r doesn't have an :update option, so we have to do it
449       # manually
450       template = File.join Config::datadir, 'templates'
451       # note that we use the */** pattern because we don't want to match
452       # keywords.rbot, which gets deleted on load and would therefore be missing always
453       missing = Dir.chdir(template) { Dir.glob('*/**') } - Dir.chdir(botclass) { Dir.glob('*/**') }
454       missing.map do |f|
455         dest = File.join(botclass, f)
456         FileUtils.mkdir_p File.dirname dest
457         FileUtils.cp File.join(template, f), dest
458       end
459     else
460       log "no #{botclass} directory found, creating from templates.."
461       if FileTest.exist? botclass
462         error "file #{botclass} exists but isn't a directory"
463         exit 2
464       end
465       FileUtils.cp_r Config::datadir+'/templates', botclass
466     end
467
468     Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
469     Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
470
471     # Time at which the last PING was sent
472     @last_ping = nil
473     # Time at which the last line was RECV'd from the server
474     @last_rec = nil
475
476     @startup_time = Time.new
477
478     begin
479       @config = Config.manager
480       @config.bot_associate(self)
481     rescue Exception => e
482       fatal e
483       log_session_end
484       exit 2
485     end
486
487     if @config['core.run_as_daemon']
488       $daemonize = true
489     end
490
491     @logfile = @config['log.file']
492     if @logfile.class!=String || @logfile.empty?
493       @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
494       debug "Using `#{@logfile}' as debug log"
495     end
496
497     # See http://blog.humlab.umu.se/samuel/archives/000107.html
498     # for the backgrounding code
499     if $daemonize
500       begin
501         exit if fork
502         Process.setsid
503         exit if fork
504       rescue NotImplementedError
505         warning "Could not background, fork not supported"
506       rescue SystemExit
507         exit 0
508       rescue Exception => e
509         warning "Could not background. #{e.pretty_inspect}"
510       end
511       Dir.chdir botclass
512       # File.umask 0000                # Ensure sensible umask. Adjust as needed.
513     end
514
515     logger = Logger.new(@logfile,
516                         @config['log.keep'],
517                         @config['log.max_size']*1024*1024)
518     logger.datetime_format= $dateformat
519     logger.level = @config['log.level']
520     logger.level = $cl_loglevel if defined? $cl_loglevel
521     logger.level = 0 if $debug
522
523     restart_logger(logger)
524
525     log_session_start
526
527     if $daemonize
528       log "Redirecting standard input/output/error"
529       [$stdin, $stdout, $stderr].each do |fd|
530         begin
531           fd.reopen "/dev/null"
532         rescue Errno::ENOENT
533           # On Windows, there's not such thing as /dev/null
534           fd.reopen "NUL"
535         end
536       end
537
538       def $stdout.write(str=nil)
539         log str, 2
540         return str.to_s.size
541       end
542       def $stdout.write(str=nil)
543         if str.to_s.match(/:\d+: warning:/)
544           warning str, 2
545         else
546           error str, 2
547         end
548         return str.to_s.size
549       end
550     end
551
552     File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
553       pf << "#{$$}\n"
554     end
555
556     @registry = Registry.new self
557
558     @timer = Timer.new
559     @save_mutex = Mutex.new
560     if @config['core.save_every'] > 0
561       @save_timer = @timer.add(@config['core.save_every']) { save }
562     else
563       @save_timer = nil
564     end
565     @quit_mutex = Mutex.new
566
567     @plugins = nil
568     @lang = Language.new(self, @config['core.language'])
569
570     begin
571       @auth = Auth::manager
572       @auth.bot_associate(self)
573       # @auth.load("#{botclass}/botusers.yaml")
574     rescue Exception => e
575       fatal e
576       log_session_end
577       exit 2
578     end
579     @auth.everyone.set_default_permission("*", true)
580     @auth.botowner.password= @config['auth.password']
581
582     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
583     @plugins = Plugins::manager
584     @plugins.bot_associate(self)
585     setup_plugins_path()
586
587     if @config['server.name']
588         debug "upgrading configuration (server.name => server.list)"
589         srv_uri = 'irc://' + @config['server.name']
590         srv_uri += ":#{@config['server.port']}" if @config['server.port']
591         @config.items['server.list'.to_sym].set_string(srv_uri)
592         @config.delete('server.name'.to_sym)
593         @config.delete('server.port'.to_sym)
594         debug "server.list is now #{@config['server.list'].inspect}"
595     end
596
597     @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], :ssl => @config['server.ssl'], :penalty_pct =>@config['send.penalty_pct'])
598     @client = Client.new
599
600     @plugins.scan
601
602     # Channels where we are quiet
603     # Array of channels names where the bot should be quiet
604     # '*' means all channels
605     #
606     @quiet = Set.new
607     # but we always speak here
608     @not_quiet = Set.new
609
610     # the nick we want, if it's different from the irc.nick config value
611     # (e.g. as set by a !nick command)
612     @wanted_nick = nil
613
614     @client[:welcome] = proc {|data|
615       m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
616
617       @plugins.delegate("welcome", m)
618       @plugins.delegate("connect")
619     }
620
621     # TODO the next two @client should go into rfc2812.rb, probably
622     # Since capabs are two-steps processes, server.supports[:capab]
623     # should be a three-state: nil, [], [....]
624     asked_for = { :"identify-msg" => false }
625     @client[:isupport] = proc { |data|
626       if server.supports[:capab] and !asked_for[:"identify-msg"]
627         sendq "CAPAB IDENTIFY-MSG"
628         asked_for[:"identify-msg"] = true
629       end
630     }
631     @client[:datastr] = proc { |data|
632       if data[:text] == "IDENTIFY-MSG"
633         server.capabilities[:"identify-msg"] = true
634       else
635         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
636       end
637     }
638
639     @client[:privmsg] = proc { |data|
640       m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
641       # debug "Message source is #{data[:source].inspect}"
642       # debug "Message target is #{data[:target].inspect}"
643       # debug "Bot is #{myself.inspect}"
644
645       @config['irc.ignore_channels'].each { |channel|
646         if m.target.downcase == channel.downcase
647           m.ignored = true
648           break
649         end
650       }
651       @config['irc.ignore_users'].each { |mask|
652         if m.source.matches?(server.new_netmask(mask))
653           m.ignored = true
654           break
655         end
656       } unless m.ignored
657
658       @plugins.irc_delegate('privmsg', m)
659     }
660     @client[:notice] = proc { |data|
661       message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
662       # pass it off to plugins that want to hear everything
663       @plugins.irc_delegate "notice", message
664     }
665     @client[:motd] = proc { |data|
666       m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
667       @plugins.delegate "motd", m
668     }
669     @client[:nicktaken] = proc { |data|
670       new = "#{data[:nick]}_"
671       nickchg new
672       # If we're setting our nick at connection because our choice was taken,
673       # we have to fix our nick manually, because there will be no NICK message
674       # to inform us that our nick has been changed.
675       if data[:target] == '*'
676         debug "setting my connection nick to #{new}"
677         nick = new
678       end
679       @plugins.delegate "nicktaken", data[:nick]
680     }
681     @client[:badnick] = proc {|data|
682       warning "bad nick (#{data[:nick]})"
683     }
684     @client[:ping] = proc {|data|
685       sendq "PONG #{data[:pingid]}"
686     }
687     @client[:pong] = proc {|data|
688       @last_ping = nil
689     }
690     @client[:nick] = proc {|data|
691       # debug "Message source is #{data[:source].inspect}"
692       # debug "Bot is #{myself.inspect}"
693       source = data[:source]
694       old = data[:oldnick]
695       new = data[:newnick]
696       m = NickMessage.new(self, server, source, old, new)
697       m.is_on = data[:is_on]
698       if source == myself
699         debug "my nick is now #{new}"
700       end
701       @plugins.irc_delegate("nick", m)
702     }
703     @client[:quit] = proc {|data|
704       source = data[:source]
705       message = data[:message]
706       m = QuitMessage.new(self, server, source, source, message)
707       m.was_on = data[:was_on]
708       @plugins.irc_delegate("quit", m)
709     }
710     @client[:mode] = proc {|data|
711       m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
712       m.modes = data[:modes]
713       @plugins.delegate "modechange", m
714     }
715     @client[:whois] = proc {|data|
716       source = data[:source]
717       target = server.get_user(data[:whois][:nick])
718       m = WhoisMessage.new(self, server, source, target, data[:whois])
719       @plugins.delegate "whois", m
720     }
721     @client[:join] = proc {|data|
722       m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
723       sendq("MODE #{data[:channel]}", nil, 0) if m.address?
724       @plugins.irc_delegate("join", m)
725       sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
726     }
727     @client[:part] = proc {|data|
728       m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
729       @plugins.irc_delegate("part", m)
730     }
731     @client[:kick] = proc {|data|
732       m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
733       @plugins.irc_delegate("kick", m)
734     }
735     @client[:invite] = proc {|data|
736       m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
737       @plugins.irc_delegate("invite", m)
738     }
739     @client[:changetopic] = proc {|data|
740       m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
741       m.info_or_set = :set
742       @plugins.irc_delegate("topic", m)
743     }
744     # @client[:topic] = proc { |data|
745     #   irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
746     # }
747     @client[:topicinfo] = proc { |data|
748       channel = data[:channel]
749       topic = channel.topic
750       m = TopicMessage.new(self, server, data[:source], channel, topic)
751       m.info_or_set = :info
752       @plugins.irc_delegate("topic", m)
753     }
754     @client[:names] = proc { |data|
755       m = NamesMessage.new(self, server, server, data[:channel])
756       m.users = data[:users]
757       @plugins.delegate "names", m
758     }
759     @client[:error] = proc { |data|
760       raise ServerError, data[:message]
761     }
762     @client[:unknown] = proc { |data|
763       #debug "UNKNOWN: #{data[:serverstring]}"
764       m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
765       @plugins.delegate "unknown_message", m
766     }
767
768     set_default_send_options :newlines => @config['send.newlines'].to_sym,
769       :join_with => @config['send.join_with'].dup,
770       :max_lines => @config['send.max_lines'],
771       :overlong => @config['send.overlong'].to_sym,
772       :split_at => Regexp.new(@config['send.split_at']),
773       :purge_split => @config['send.purge_split'],
774       :truncate_text => @config['send.truncate_text'].dup
775
776     trap_sigs
777   end
778
779   def setup_plugins_path
780     @plugins.clear_botmodule_dirs
781     @plugins.add_botmodule_dir(Config::coredir + "/utils")
782     @plugins.add_botmodule_dir(Config::coredir)
783     @plugins.add_botmodule_dir("#{botclass}/plugins")
784
785     @config['plugins.path'].each do |_|
786         path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
787         @plugins.add_botmodule_dir(path)
788     end
789   end
790
791   def set_default_send_options(opts={})
792     # Default send options for NOTICE and PRIVMSG
793     unless defined? @default_send_options
794       @default_send_options = {
795         :queue_channel => nil,      # use default queue channel
796         :queue_ring => nil,         # use default queue ring
797         :newlines => :split,        # or :join
798         :join_with => ' ',          # by default, use a single space
799         :max_lines => 0,          # maximum number of lines to send with a single command
800         :overlong => :split,        # or :truncate
801         # TODO an array of splitpoints would be preferrable for this option:
802         :split_at => /\s+/,         # by default, split overlong lines at whitespace
803         :purge_split => true,       # should the split string be removed?
804         :truncate_text => "#{Reverse}...#{Reverse}"  # text to be appened when truncating
805       }
806     end
807     @default_send_options.update opts unless opts.empty?
808     end
809
810   # checks if we should be quiet on a channel
811   def quiet_on?(channel)
812     ch = channel.downcase
813     return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
814   end
815
816   def set_quiet(channel = nil)
817     if channel
818       ch = channel.downcase.dup
819       @not_quiet.delete(ch)
820       @quiet << ch
821     else
822       @quiet.clear
823       @not_quiet.clear
824       @quiet << '*'
825     end
826   end
827
828   def reset_quiet(channel = nil)
829     if channel
830       ch = channel.downcase.dup
831       @quiet.delete(ch)
832       @not_quiet << ch
833     else
834       @quiet.clear
835       @not_quiet.clear
836     end
837   end
838
839   # things to do when we receive a signal
840   def got_sig(sig, func=:quit)
841     debug "received #{sig}, queueing #{func}"
842     # this is not an interruption if we just need to reconnect
843     $interrupted += 1 unless func == :reconnect
844     self.send(func) unless @quit_mutex.locked?
845     debug "interrupted #{$interrupted} times"
846     if $interrupted >= 3
847       debug "drastic!"
848       log_session_end
849       exit 2
850     end
851   end
852
853   # trap signals
854   def trap_sigs
855     begin
856       trap("SIGINT") { got_sig("SIGINT") }
857       trap("SIGTERM") { got_sig("SIGTERM") }
858       trap("SIGHUP") { got_sig("SIGHUP", :restart) }
859       trap("SIGUSR1") { got_sig("SIGUSR1", :reconnect) }
860     rescue ArgumentError => e
861       debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
862     rescue Exception => e
863       debug "failed to trap signals: #{e.pretty_inspect}"
864     end
865   end
866
867   # connect the bot to IRC
868   def connect
869     begin
870       quit if $interrupted > 0
871       @socket.connect
872       @last_rec = Time.now
873     rescue => e
874       raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
875     end
876     quit if $interrupted > 0
877
878     realname = @config['irc.name'].clone || 'Ruby bot'
879     realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
880
881     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
882     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
883     quit if $interrupted > 0
884     myself.nick = @config['irc.nick']
885     myself.user = @config['irc.user']
886   end
887
888   # disconnect the bot from IRC, if connected, and then connect (again)
889   def reconnect(message=nil, too_fast=false)
890     # we will wait only if @last_rec was not nil, i.e. if we were connected or
891     # got disconnected by a network error
892     # if someone wants to manually call disconnect() _and_ reconnect(), they
893     # will have to take care of the waiting themselves
894     will_wait = !!@last_rec
895
896     if @socket.connected?
897       disconnect(message)
898     end
899
900     if will_wait
901       log "\n\nDisconnected\n\n"
902
903       quit if $interrupted > 0
904
905       log "\n\nWaiting to reconnect\n\n"
906       sleep @config['server.reconnect_wait']
907       sleep 10*@config['server.reconnect_wait'] if too_fast
908     end
909
910     connect
911   end
912
913   # begin event handling loop
914   def mainloop
915     while true
916       too_fast = false
917       begin
918         quit_msg = nil
919         reconnect(quit_msg, too_fast)
920         quit if $interrupted > 0
921         while @socket.connected?
922           quit if $interrupted > 0
923
924           # Wait for messages and process them as they arrive. If nothing is
925           # received, we call the ping_server() method that will PING the
926           # server if appropriate, or raise a TimeoutError if no PONG has been
927           # received in the user-chosen timeout since the last PING sent.
928           if @socket.select(1)
929             break unless reply = @socket.gets
930             @last_rec = Time.now
931             @client.process reply
932           else
933             ping_server
934           end
935         end
936
937       # I despair of this. Some of my users get "connection reset by peer"
938       # exceptions that ARENT SocketError's. How am I supposed to handle
939       # that?
940       rescue SystemExit
941         log_session_end
942         exit 0
943       rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
944         error "network exception: #{e.pretty_inspect}"
945         quit_msg = e.to_s
946       rescue ServerError
947         # received an ERROR from the server
948         quit_msg = "server ERROR: " + e.message
949         too_fast = e.message.index("reconnect too fast")
950         retry
951       rescue BDB::Fatal => e
952         fatal "fatal bdb error: #{e.pretty_inspect}"
953         DBTree.stats
954         # Why restart? DB problems are serious stuff ...
955         # restart("Oops, we seem to have registry problems ...")
956         log_session_end
957         exit 2
958       rescue Exception => e
959         error "non-net exception: #{e.pretty_inspect}"
960         quit_msg = e.to_s
961       rescue => e
962         fatal "unexpected exception: #{e.pretty_inspect}"
963         log_session_end
964         exit 2
965       end
966     end
967   end
968
969   # type:: message type
970   # where:: message target
971   # message:: message text
972   # send message +message+ of type +type+ to target +where+
973   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
974   # relevant say() or notice() methods. This one should be used for IRCd
975   # extensions you want to use in modules.
976   def sendmsg(type, where, original_message, options={})
977     opts = @default_send_options.merge(options)
978
979     # For starters, set up appropriate queue channels and rings
980     mchan = opts[:queue_channel]
981     mring = opts[:queue_ring]
982     if mchan
983       chan = mchan
984     else
985       chan = where
986     end
987     if mring
988       ring = mring
989     else
990       case where
991       when User
992         ring = 1
993       else
994         ring = 2
995       end
996     end
997
998     multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
999
1000     # if target is a channel with nocolor modes, strip colours
1001     if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1002       multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1003     end
1004
1005     messages = Array.new
1006     case opts[:newlines]
1007     when :join
1008       messages << [multi_line.gsub("\n", opts[:join_with])]
1009     when :split
1010       multi_line.each_line { |line|
1011         line.chomp!
1012         next unless(line.size > 0)
1013         messages << line
1014       }
1015     else
1016       raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1017     end
1018
1019     # The IRC protocol requires that each raw message must be not longer
1020     # than 512 characters. From this length with have to subtract the EOL
1021     # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1022     # that will be prepended by the server to all of our messages.
1023
1024     # The maximum raw message length we can send is therefore 512 - 2 - 2
1025     # minus the length of our hostmask.
1026
1027     max_len = 508 - myself.fullform.size
1028
1029     # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1030     # will have a + or - prepended
1031     if server.capabilities[:"identify-msg"]
1032       max_len -= 1
1033     end
1034
1035     # When splitting the message, we'll be prefixing the following string:
1036     # (e.g. "PRIVMSG #rbot :")
1037     fixed = "#{type} #{where} :"
1038
1039     # And this is what's left
1040     left = max_len - fixed.size
1041
1042     truncate = opts[:truncate_text]
1043     truncate = @default_send_options[:truncate_text] if truncate.size > left
1044     truncate = "" if truncate.size > left
1045
1046     all_lines = messages.map { |line|
1047       if line.size < left
1048         line
1049       else
1050         case opts[:overlong]
1051         when :split
1052           msg = line.dup
1053           sub_lines = Array.new
1054           begin
1055             sub_lines << msg.slice!(0, left)
1056             break if msg.empty?
1057             lastspace = sub_lines.last.rindex(opts[:split_at])
1058             if lastspace
1059               msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1060               msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1061             end
1062           end until msg.empty?
1063           sub_lines
1064         when :truncate
1065           line.slice(0, left - truncate.size) << truncate
1066         else
1067           raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1068         end
1069       end
1070     }.flatten
1071
1072     if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1073       lines = all_lines[0...opts[:max_lines]]
1074       new_last = lines.last.slice(0, left - truncate.size) << truncate
1075       lines.last.replace(new_last)
1076     else
1077       lines = all_lines
1078     end
1079
1080     lines.each { |line|
1081       sendq "#{fixed}#{line}", chan, ring
1082       delegate_sent(type, where, line)
1083     }
1084   end
1085
1086   # queue an arbitraty message for the server
1087   def sendq(message="", chan=nil, ring=0)
1088     # temporary
1089     @socket.queue(message, chan, ring)
1090   end
1091
1092   # send a notice message to channel/nick +where+
1093   def notice(where, message, options={})
1094     return if where.kind_of?(Channel) and quiet_on?(where)
1095     sendmsg "NOTICE", where, message, options
1096   end
1097
1098   # say something (PRIVMSG) to channel/nick +where+
1099   def say(where, message, options={})
1100     return if where.kind_of?(Channel) and quiet_on?(where)
1101     sendmsg "PRIVMSG", where, message, options
1102   end
1103
1104   def ctcp_notice(where, command, message, options={})
1105     return if where.kind_of?(Channel) and quiet_on?(where)
1106     sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1107   end
1108
1109   def ctcp_say(where, command, message, options={})
1110     return if where.kind_of?(Channel) and quiet_on?(where)
1111     sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1112   end
1113
1114   # perform a CTCP action with message +message+ to channel/nick +where+
1115   def action(where, message, options={})
1116     ctcp_say(where, 'ACTION', message, options)
1117   end
1118
1119   # quick way to say "okay" (or equivalent) to +where+
1120   def okay(where)
1121     say where, @lang.get("okay")
1122   end
1123
1124   # set topic of channel +where+ to +topic+
1125   # can also be used to retrieve the topic of channel +where+
1126   # by omitting the last argument
1127   def topic(where, topic=nil)
1128     if topic.nil?
1129       sendq "TOPIC #{where}", where, 2
1130     else
1131       sendq "TOPIC #{where} :#{topic}", where, 2
1132     end
1133   end
1134
1135   def disconnect(message=nil)
1136     message = @lang.get("quit") if (!message || message.empty?)
1137     if @socket.connected?
1138       begin
1139         debug "Clearing socket"
1140         @socket.clearq
1141         debug "Sending quit message"
1142         @socket.emergency_puts "QUIT :#{message}"
1143         debug "Logging quits"
1144         delegate_sent('QUIT', myself, message)
1145         debug "Flushing socket"
1146         @socket.flush
1147       rescue SocketError => e
1148         error "error while disconnecting socket: #{e.pretty_inspect}"
1149       end
1150       debug "Shutting down socket"
1151       @socket.shutdown
1152     end
1153     stop_server_pings
1154     @client.reset
1155   end
1156
1157   # disconnect from the server and cleanup all plugins and modules
1158   def shutdown(message=nil)
1159     @quit_mutex.synchronize do
1160       debug "Shutting down: #{message}"
1161       ## No we don't restore them ... let everything run through
1162       # begin
1163       #   trap("SIGINT", "DEFAULT")
1164       #   trap("SIGTERM", "DEFAULT")
1165       #   trap("SIGHUP", "DEFAULT")
1166       # rescue => e
1167       #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1168       # end
1169       debug "\tdisconnecting..."
1170       disconnect(message)
1171       debug "\tstopping timer..."
1172       @timer.stop
1173       debug "\tsaving ..."
1174       save
1175       debug "\tcleaning up ..."
1176       @save_mutex.synchronize do
1177         @plugins.cleanup
1178       end
1179       # debug "\tstopping timers ..."
1180       # @timer.stop
1181       # debug "Closing registries"
1182       # @registry.close
1183       debug "\t\tcleaning up the db environment ..."
1184       DBTree.cleanup_env
1185       log "rbot quit (#{message})"
1186     end
1187   end
1188
1189   # message:: optional IRC quit message
1190   # quit IRC, shutdown the bot
1191   def quit(message=nil)
1192     begin
1193       shutdown(message)
1194     ensure
1195       exit 0
1196     end
1197   end
1198
1199   # totally shutdown and respawn the bot
1200   def restart(message=nil)
1201     message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1202     shutdown(message)
1203     sleep @config['server.reconnect_wait']
1204     begin
1205       # now we re-exec
1206       # Note, this fails on Windows
1207       debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1208       log_session_end
1209       Dir.chdir(@run_dir)
1210       exec($0, *@argv)
1211     rescue Errno::ENOENT
1212       log_session_end
1213       exec("ruby", *(@argv.unshift $0))
1214     rescue Exception => e
1215       $interrupted += 1
1216       raise e
1217     end
1218   end
1219
1220   # call the save method for all of the botmodules
1221   def save
1222     @save_mutex.synchronize do
1223       @plugins.save
1224       DBTree.cleanup_logs
1225     end
1226   end
1227
1228   # call the rescan method for all of the botmodules
1229   def rescan
1230     debug "\tstopping timer..."
1231     @timer.stop
1232     @save_mutex.synchronize do
1233       @lang.rescan
1234       @plugins.rescan
1235     end
1236     @timer.start
1237   end
1238
1239   # channel:: channel to join
1240   # key::     optional channel key if channel is +s
1241   # join a channel
1242   def join(channel, key=nil)
1243     if(key)
1244       sendq "JOIN #{channel} :#{key}", channel, 2
1245     else
1246       sendq "JOIN #{channel}", channel, 2
1247     end
1248   end
1249
1250   # part a channel
1251   def part(channel, message="")
1252     sendq "PART #{channel} :#{message}", channel, 2
1253   end
1254
1255   # attempt to change bot's nick to +name+
1256   def nickchg(name)
1257     sendq "NICK #{name}"
1258   end
1259
1260   # changing mode
1261   def mode(channel, mode, target=nil)
1262     sendq "MODE #{channel} #{mode} #{target}", channel, 2
1263   end
1264
1265   # asking whois
1266   def whois(nick, target=nil)
1267     sendq "WHOIS #{target} #{nick}", nil, 0
1268   end
1269
1270   # kicking a user
1271   def kick(channel, user, msg)
1272     sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1273   end
1274
1275   # m::     message asking for help
1276   # topic:: optional topic help is requested for
1277   # respond to online help requests
1278   def help(topic=nil)
1279     topic = nil if topic == ""
1280     case topic
1281     when nil
1282       helpstr = _("help topics: ")
1283       helpstr += @plugins.helptopics
1284       helpstr += _(" (help <topic> for more info)")
1285     else
1286       unless(helpstr = @plugins.help(topic))
1287         helpstr = _("no help for topic %{topic}") % { :topic => topic }
1288       end
1289     end
1290     return helpstr
1291   end
1292
1293   # returns a string describing the current status of the bot (uptime etc)
1294   def status
1295     secs_up = Time.new - @startup_time
1296     uptime = Utils.secs_to_string secs_up
1297     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1298     return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1299              {
1300                :up => uptime, :plug => @plugins.length,
1301                :sent => @socket.lines_sent, :recv => @socket.lines_received
1302              })
1303   end
1304
1305   # We want to respond to a hung server in a timely manner. If nothing was received
1306   # in the user-selected timeout and we haven't PINGed the server yet, we PING
1307   # the server. If the PONG is not received within the user-defined timeout, we
1308   # assume we're in ping timeout and act accordingly.
1309   def ping_server
1310     act_timeout = @config['server.ping_timeout']
1311     return if act_timeout <= 0
1312     now = Time.now
1313     if @last_rec && now > @last_rec + act_timeout
1314       if @last_ping.nil?
1315         # No previous PING pending, send a new one
1316         sendq "PING :rbot"
1317         @last_ping = Time.now
1318       else
1319         diff = now - @last_ping
1320         if diff > act_timeout
1321           debug "no PONG from server in #{diff} seconds, reconnecting"
1322           # the actual reconnect is handled in the main loop:
1323           raise TimeoutError, "no PONG from server in #{diff} seconds"
1324         end
1325       end
1326     end
1327   end
1328
1329   def stop_server_pings
1330     # cancel previous PINGs and reset time of last RECV
1331     @last_ping = nil
1332     @last_rec = nil
1333   end
1334
1335   private
1336
1337   # delegate sent messages
1338   def delegate_sent(type, where, message)
1339     args = [self, server, myself, server.user_or_channel(where.to_s), message]
1340     case type
1341       when "NOTICE"
1342         m = NoticeMessage.new(*args)
1343       when "PRIVMSG"
1344         m = PrivMessage.new(*args)
1345       when "QUIT"
1346         m = QuitMessage.new(*args)
1347         m.was_on = myself.channels
1348     end
1349     @plugins.delegate('sent', m)
1350   end
1351
1352 end
1353
1354 end