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