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