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