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