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