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