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