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