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