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