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