]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
+ @bot.wanted_nick stores the nick wanted by the bot
[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       @config['irc.join_channels'].each { |c|
614         debug "autojoining channel #{c}"
615         if(c =~ /^(\S+)\s+(\S+)$/i)
616           join $1, $2
617         else
618           join c if(c)
619         end
620       }
621     }
622
623     # TODO the next two @client should go into rfc2812.rb, probably
624     # Since capabs are two-steps processes, server.supports[:capab]
625     # should be a three-state: nil, [], [....]
626     asked_for = { :"identify-msg" => false }
627     @client[:isupport] = proc { |data|
628       if server.supports[:capab] and !asked_for[:"identify-msg"]
629         sendq "CAPAB IDENTIFY-MSG"
630         asked_for[:"identify-msg"] = true
631       end
632     }
633     @client[:datastr] = proc { |data|
634       if data[:text] == "IDENTIFY-MSG"
635         server.capabilities[:"identify-msg"] = true
636       else
637         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
638       end
639     }
640
641     @client[:privmsg] = proc { |data|
642       m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
643       # debug "Message source is #{data[:source].inspect}"
644       # debug "Message target is #{data[:target].inspect}"
645       # debug "Bot is #{myself.inspect}"
646
647       @config['irc.ignore_users'].each { |mask|
648         if m.source.matches?(server.new_netmask(mask))
649           m.ignored = true
650         end
651       }
652
653       @plugins.irc_delegate('privmsg', m)
654     }
655     @client[:notice] = proc { |data|
656       message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
657       # pass it off to plugins that want to hear everything
658       @plugins.irc_delegate "notice", message
659     }
660     @client[:motd] = proc { |data|
661       m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
662       @plugins.delegate "motd", m
663     }
664     @client[:nicktaken] = proc { |data|
665       new = "#{data[:nick]}_"
666       nickchg new
667       # If we're setting our nick at connection because our choice was taken,
668       # we have to fix our nick manually, because there will be no NICK message
669       # to inform us that our nick has been changed.
670       if data[:target] == '*'
671         debug "setting my connection nick to #{new}"
672         nick = new
673       end
674       @plugins.delegate "nicktaken", data[:nick]
675     }
676     @client[:badnick] = proc {|data|
677       warning "bad nick (#{data[:nick]})"
678     }
679     @client[:ping] = proc {|data|
680       sendq "PONG #{data[:pingid]}"
681     }
682     @client[:pong] = proc {|data|
683       @last_ping = nil
684     }
685     @client[:nick] = proc {|data|
686       # debug "Message source is #{data[:source].inspect}"
687       # debug "Bot is #{myself.inspect}"
688       source = data[:source]
689       old = data[:oldnick]
690       new = data[:newnick]
691       m = NickMessage.new(self, server, source, old, new)
692       m.is_on = data[:is_on]
693       if source == myself
694         debug "my nick is now #{new}"
695       end
696       @plugins.irc_delegate("nick", m)
697     }
698     @client[:quit] = proc {|data|
699       source = data[:source]
700       message = data[:message]
701       m = QuitMessage.new(self, server, source, source, message)
702       m.was_on = data[:was_on]
703       @plugins.irc_delegate("quit", m)
704     }
705     @client[:mode] = proc {|data|
706       m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
707       m.modes = data[:modes]
708       @plugins.delegate "modechange", m
709     }
710     @client[:join] = proc {|data|
711       m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
712       sendq("MODE #{data[:channel]}", nil, 0) if m.address?
713       @plugins.irc_delegate("join", m)
714       sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
715     }
716     @client[:part] = proc {|data|
717       m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
718       @plugins.irc_delegate("part", m)
719     }
720     @client[:kick] = proc {|data|
721       m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
722       @plugins.irc_delegate("kick", m)
723     }
724     @client[:invite] = proc {|data|
725       m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
726       @plugins.irc_delegate("invite", m)
727     }
728     @client[:changetopic] = proc {|data|
729       m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
730       m.info_or_set = :set
731       @plugins.irc_delegate("topic", m)
732     }
733     # @client[:topic] = proc { |data|
734     #   irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
735     # }
736     @client[:topicinfo] = proc { |data|
737       channel = data[:channel]
738       topic = channel.topic
739       m = TopicMessage.new(self, server, data[:source], channel, topic)
740       m.info_or_set = :info
741       @plugins.irc_delegate("topic", m)
742     }
743     @client[:names] = proc { |data|
744       m = NamesMessage.new(self, server, server, data[:channel])
745       m.users = data[:users]
746       @plugins.delegate "names", m
747     }
748     @client[:unknown] = proc { |data|
749       #debug "UNKNOWN: #{data[:serverstring]}"
750       m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
751       @plugins.delegate "unknown_message", m
752     }
753
754     set_default_send_options :newlines => @config['send.newlines'].to_sym,
755       :join_with => @config['send.join_with'].dup,
756       :max_lines => @config['send.max_lines'],
757       :overlong => @config['send.overlong'].to_sym,
758       :split_at => Regexp.new(@config['send.split_at']),
759       :purge_split => @config['send.purge_split'],
760       :truncate_text => @config['send.truncate_text'].dup
761
762     trap_sigs
763   end
764
765   def setup_plugins_path
766     @plugins.clear_botmodule_dirs
767     @plugins.add_botmodule_dir(Config::coredir + "/utils")
768     @plugins.add_botmodule_dir(Config::coredir)
769     @plugins.add_botmodule_dir("#{botclass}/plugins")
770
771     @config['plugins.path'].each do |_|
772         path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
773         @plugins.add_botmodule_dir(path)
774     end
775   end
776
777   def set_default_send_options(opts={})
778     # Default send options for NOTICE and PRIVMSG
779     unless defined? @default_send_options
780       @default_send_options = {
781         :queue_channel => nil,      # use default queue channel
782         :queue_ring => nil,         # use default queue ring
783         :newlines => :split,        # or :join
784         :join_with => ' ',          # by default, use a single space
785         :max_lines => 0,          # maximum number of lines to send with a single command
786         :overlong => :split,        # or :truncate
787         # TODO an array of splitpoints would be preferrable for this option:
788         :split_at => /\s+/,         # by default, split overlong lines at whitespace
789         :purge_split => true,       # should the split string be removed?
790         :truncate_text => "#{Reverse}...#{Reverse}"  # text to be appened when truncating
791       }
792     end
793     @default_send_options.update opts unless opts.empty?
794     end
795
796   # checks if we should be quiet on a channel
797   def quiet_on?(channel)
798     return @quiet.include?('*') || @quiet.include?(channel.downcase)
799   end
800
801   def set_quiet(channel = nil)
802     if channel
803       ch = channel.downcase.dup
804       @quiet << ch
805     else
806       @quiet.clear
807       @quiet << '*'
808     end
809   end
810
811   def reset_quiet(channel = nil)
812     if channel
813       @quiet.delete channel.downcase
814     else
815       @quiet.clear
816     end
817   end
818
819   # things to do when we receive a signal
820   def got_sig(sig, func=:quit)
821     debug "received #{sig}, queueing #{func}"
822     $interrupted += 1
823     self.send(func) unless @quit_mutex.locked?
824     debug "interrupted #{$interrupted} times"
825     if $interrupted >= 3
826       debug "drastic!"
827       log_session_end
828       exit 2
829     end
830   end
831
832   # trap signals
833   def trap_sigs
834     begin
835       trap("SIGINT") { got_sig("SIGINT") }
836       trap("SIGTERM") { got_sig("SIGTERM") }
837       trap("SIGHUP") { got_sig("SIGHUP", :restart) }
838     rescue ArgumentError => e
839       debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
840     rescue Exception => e
841       debug "failed to trap signals: #{e.pretty_inspect}"
842     end
843   end
844
845   # connect the bot to IRC
846   def connect
847     begin
848       quit if $interrupted > 0
849       @socket.connect
850     rescue => e
851       raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
852     end
853     quit if $interrupted > 0
854
855     realname = @config['irc.name'].clone || 'Ruby bot'
856     realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
857
858     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
859     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
860     quit if $interrupted > 0
861     myself.nick = @config['irc.nick']
862     myself.user = @config['irc.user']
863   end
864
865   # begin event handling loop
866   def mainloop
867     while true
868       begin
869         quit if $interrupted > 0
870         connect
871
872         quit_msg = nil
873         while @socket.connected?
874           quit if $interrupted > 0
875
876           # Wait for messages and process them as they arrive. If nothing is
877           # received, we call the ping_server() method that will PING the
878           # server if appropriate, or raise a TimeoutError if no PONG has been
879           # received in the user-chosen timeout since the last PING sent.
880           if @socket.select(1)
881             break unless reply = @socket.gets
882             @last_rec = Time.now
883             @client.process reply
884           else
885             ping_server
886           end
887         end
888
889       # I despair of this. Some of my users get "connection reset by peer"
890       # exceptions that ARENT SocketError's. How am I supposed to handle
891       # that?
892       rescue SystemExit
893         log_session_end
894         exit 0
895       rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
896         error "network exception: #{e.pretty_inspect}"
897         quit_msg = e.to_s
898       rescue BDB::Fatal => e
899         fatal "fatal bdb error: #{e.pretty_inspect}"
900         DBTree.stats
901         # Why restart? DB problems are serious stuff ...
902         # restart("Oops, we seem to have registry problems ...")
903         log_session_end
904         exit 2
905       rescue Exception => e
906         error "non-net exception: #{e.pretty_inspect}"
907         quit_msg = e.to_s
908       rescue => e
909         fatal "unexpected exception: #{e.pretty_inspect}"
910         log_session_end
911         exit 2
912       end
913
914       disconnect(quit_msg)
915
916       log "\n\nDisconnected\n\n"
917
918       quit if $interrupted > 0
919
920       log "\n\nWaiting to reconnect\n\n"
921       sleep @config['server.reconnect_wait']
922     end
923   end
924
925   # type:: message type
926   # where:: message target
927   # message:: message text
928   # send message +message+ of type +type+ to target +where+
929   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
930   # relevant say() or notice() methods. This one should be used for IRCd
931   # extensions you want to use in modules.
932   def sendmsg(type, where, original_message, options={})
933     opts = @default_send_options.merge(options)
934
935     # For starters, set up appropriate queue channels and rings
936     mchan = opts[:queue_channel]
937     mring = opts[:queue_ring]
938     if mchan
939       chan = mchan
940     else
941       chan = where
942     end
943     if mring
944       ring = mring
945     else
946       case where
947       when User
948         ring = 1
949       else
950         ring = 2
951       end
952     end
953
954     multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
955
956     # if target is a channel with nocolor modes, strip colours
957     if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
958       multi_line.replace BasicUserMessage.strip_formatting(multi_line)
959     end
960
961     messages = Array.new
962     case opts[:newlines]
963     when :join
964       messages << [multi_line.gsub("\n", opts[:join_with])]
965     when :split
966       multi_line.each_line { |line|
967         line.chomp!
968         next unless(line.size > 0)
969         messages << line
970       }
971     else
972       raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
973     end
974
975     # The IRC protocol requires that each raw message must be not longer
976     # than 512 characters. From this length with have to subtract the EOL
977     # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
978     # that will be prepended by the server to all of our messages.
979
980     # The maximum raw message length we can send is therefore 512 - 2 - 2
981     # minus the length of our hostmask.
982
983     max_len = 508 - myself.fullform.size
984
985     # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
986     # will have a + or - prepended
987     if server.capabilities[:"identify-msg"]
988       max_len -= 1
989     end
990
991     # When splitting the message, we'll be prefixing the following string:
992     # (e.g. "PRIVMSG #rbot :")
993     fixed = "#{type} #{where} :"
994
995     # And this is what's left
996     left = max_len - fixed.size
997
998     truncate = opts[:truncate_text]
999     truncate = @default_send_options[:truncate_text] if truncate.size > left
1000     truncate = "" if truncate.size > left
1001
1002     all_lines = messages.map { |line|
1003       if line.size < left
1004         line
1005       else
1006         case opts[:overlong]
1007         when :split
1008           msg = line.dup
1009           sub_lines = Array.new
1010           begin
1011             sub_lines << msg.slice!(0, left)
1012             break if msg.empty?
1013             lastspace = sub_lines.last.rindex(opts[:split_at])
1014             if lastspace
1015               msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1016               msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1017             end
1018           end until msg.empty?
1019           sub_lines
1020         when :truncate
1021           line.slice(0, left - truncate.size) << truncate
1022         else
1023           raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1024         end
1025       end
1026     }.flatten
1027
1028     if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1029       lines = all_lines[0...opts[:max_lines]]
1030       new_last = lines.last.slice(0, left - truncate.size) << truncate
1031       lines.last.replace(new_last)
1032     else
1033       lines = all_lines
1034     end
1035
1036     lines.each { |line|
1037       sendq "#{fixed}#{line}", chan, ring
1038       delegate_sent(type, where, line)
1039     }
1040   end
1041
1042   # queue an arbitraty message for the server
1043   def sendq(message="", chan=nil, ring=0)
1044     # temporary
1045     @socket.queue(message, chan, ring)
1046   end
1047
1048   # send a notice message to channel/nick +where+
1049   def notice(where, message, options={})
1050     return if where.kind_of?(Channel) and quiet_on?(where)
1051     sendmsg "NOTICE", where, message, options
1052   end
1053
1054   # say something (PRIVMSG) to channel/nick +where+
1055   def say(where, message, options={})
1056     return if where.kind_of?(Channel) and quiet_on?(where)
1057     sendmsg "PRIVMSG", where, message, options
1058   end
1059
1060   def ctcp_notice(where, command, message, options={})
1061     return if where.kind_of?(Channel) and quiet_on?(where)
1062     sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1063   end
1064
1065   def ctcp_say(where, command, message, options={})
1066     return if where.kind_of?(Channel) and quiet_on?(where)
1067     sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1068   end
1069
1070   # perform a CTCP action with message +message+ to channel/nick +where+
1071   def action(where, message, options={})
1072     ctcp_say(where, 'ACTION', message, options)
1073   end
1074
1075   # quick way to say "okay" (or equivalent) to +where+
1076   def okay(where)
1077     say where, @lang.get("okay")
1078   end
1079
1080   # set topic of channel +where+ to +topic+
1081   # can also be used to retrieve the topic of channel +where+
1082   # by omitting the last argument
1083   def topic(where, topic=nil)
1084     if topic.nil?
1085       sendq "TOPIC #{where}", where, 2
1086     else
1087       sendq "TOPIC #{where} :#{topic}", where, 2
1088     end
1089   end
1090
1091   def disconnect(message=nil)
1092     message = @lang.get("quit") if (!message || message.empty?)
1093     if @socket.connected?
1094       begin
1095         debug "Clearing socket"
1096         @socket.clearq
1097         debug "Sending quit message"
1098         @socket.emergency_puts "QUIT :#{message}"
1099         debug "Logging quits"
1100         delegate_sent('QUIT', myself, message)
1101         debug "Flushing socket"
1102         @socket.flush
1103       rescue SocketError => e
1104         error "error while disconnecting socket: #{e.pretty_inspect}"
1105       end
1106       debug "Shutting down socket"
1107       @socket.shutdown
1108     end
1109     stop_server_pings
1110     @client.reset
1111   end
1112
1113   # disconnect from the server and cleanup all plugins and modules
1114   def shutdown(message=nil)
1115     @quit_mutex.synchronize do
1116       debug "Shutting down: #{message}"
1117       ## No we don't restore them ... let everything run through
1118       # begin
1119       #   trap("SIGINT", "DEFAULT")
1120       #   trap("SIGTERM", "DEFAULT")
1121       #   trap("SIGHUP", "DEFAULT")
1122       # rescue => e
1123       #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1124       # end
1125       debug "\tdisconnecting..."
1126       disconnect(message)
1127       debug "\tstopping timer..."
1128       @timer.stop
1129       debug "\tsaving ..."
1130       save
1131       debug "\tcleaning up ..."
1132       @save_mutex.synchronize do
1133         @plugins.cleanup
1134       end
1135       # debug "\tstopping timers ..."
1136       # @timer.stop
1137       # debug "Closing registries"
1138       # @registry.close
1139       debug "\t\tcleaning up the db environment ..."
1140       DBTree.cleanup_env
1141       log "rbot quit (#{message})"
1142     end
1143   end
1144
1145   # message:: optional IRC quit message
1146   # quit IRC, shutdown the bot
1147   def quit(message=nil)
1148     begin
1149       shutdown(message)
1150     ensure
1151       exit 0
1152     end
1153   end
1154
1155   # totally shutdown and respawn the bot
1156   def restart(message=nil)
1157     message = "restarting, back in #{@config['server.reconnect_wait']}..." if (!message || message.empty?)
1158     shutdown(message)
1159     sleep @config['server.reconnect_wait']
1160     begin
1161       # now we re-exec
1162       # Note, this fails on Windows
1163       debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1164       log_session_end
1165       Dir.chdir(@run_dir)
1166       exec($0, *@argv)
1167     rescue Errno::ENOENT
1168       log_session_end
1169       exec("ruby", *(@argv.unshift $0))
1170     rescue Exception => e
1171       $interrupted += 1
1172       raise e
1173     end
1174   end
1175
1176   # call the save method for all of the botmodules
1177   def save
1178     @save_mutex.synchronize do
1179       @plugins.save
1180       DBTree.cleanup_logs
1181     end
1182   end
1183
1184   # call the rescan method for all of the botmodules
1185   def rescan
1186     debug "\tstopping timer..."
1187     @timer.stop
1188     @save_mutex.synchronize do
1189       @lang.rescan
1190       @plugins.rescan
1191     end
1192     @timer.start
1193   end
1194
1195   # channel:: channel to join
1196   # key::     optional channel key if channel is +s
1197   # join a channel
1198   def join(channel, key=nil)
1199     if(key)
1200       sendq "JOIN #{channel} :#{key}", channel, 2
1201     else
1202       sendq "JOIN #{channel}", channel, 2
1203     end
1204   end
1205
1206   # part a channel
1207   def part(channel, message="")
1208     sendq "PART #{channel} :#{message}", channel, 2
1209   end
1210
1211   # attempt to change bot's nick to +name+
1212   def nickchg(name)
1213     sendq "NICK #{name}"
1214   end
1215
1216   # changing mode
1217   def mode(channel, mode, target=nil)
1218     sendq "MODE #{channel} #{mode} #{target}", channel, 2
1219   end
1220
1221   # kicking a user
1222   def kick(channel, user, msg)
1223     sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1224   end
1225
1226   # m::     message asking for help
1227   # topic:: optional topic help is requested for
1228   # respond to online help requests
1229   def help(topic=nil)
1230     topic = nil if topic == ""
1231     case topic
1232     when nil
1233       helpstr = _("help topics: ")
1234       helpstr += @plugins.helptopics
1235       helpstr += _(" (help <topic> for more info)")
1236     else
1237       unless(helpstr = @plugins.help(topic))
1238         helpstr = _("no help for topic %{topic}") % { :topic => topic }
1239       end
1240     end
1241     return helpstr
1242   end
1243
1244   # returns a string describing the current status of the bot (uptime etc)
1245   def status
1246     secs_up = Time.new - @startup_time
1247     uptime = Utils.secs_to_string secs_up
1248     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1249     return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1250              {
1251                :up => uptime, :plug => @plugins.length,
1252                :sent => @socket.lines_sent, :recv => @socket.lines_received
1253              })
1254   end
1255
1256   # We want to respond to a hung server in a timely manner. If nothing was received
1257   # in the user-selected timeout and we haven't PINGed the server yet, we PING
1258   # the server. If the PONG is not received within the user-defined timeout, we
1259   # assume we're in ping timeout and act accordingly.
1260   def ping_server
1261     act_timeout = @config['server.ping_timeout']
1262     return if act_timeout <= 0
1263     now = Time.now
1264     if @last_rec && now > @last_rec + act_timeout
1265       if @last_ping.nil?
1266         # No previous PING pending, send a new one
1267         sendq "PING :rbot"
1268         @last_ping = Time.now
1269       else
1270         diff = now - @last_ping
1271         if diff > act_timeout
1272           debug "no PONG from server in #{diff} seconds, reconnecting"
1273           # the actual reconnect is handled in the main loop:
1274           raise TimeoutError, "no PONG from server in #{diff} seconds"
1275         end
1276       end
1277     end
1278   end
1279
1280   def stop_server_pings
1281     # cancel previous PINGs and reset time of last RECV
1282     @last_ping = nil
1283     @last_rec = nil
1284   end
1285
1286   private
1287
1288   # delegate sent messages
1289   def delegate_sent(type, where, message)
1290     args = [self, server, myself, server.user_or_channel(where.to_s), message]
1291     case type
1292       when "NOTICE"
1293         m = NoticeMessage.new(*args)
1294       when "PRIVMSG"
1295         m = PrivMessage.new(*args)
1296       when "QUIT"
1297         m = QuitMessage.new(*args)
1298     end
1299     @plugins.delegate('sent', m)
1300   end
1301
1302 end
1303
1304 end