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