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