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