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