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