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