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