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