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