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