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