]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
Merge pull request #4 from ahpook/rename_karma
[user/henk/code/ruby/rbot.git] / lib / rbot / ircbot.rb
1 # encoding: UTF-8
2 #-- vim:sw=2:et
3 #++
4 #
5 # :title: rbot core
6
7 require 'thread'
8
9 require 'etc'
10 require 'date'
11 require 'fileutils'
12 require 'logger'
13
14 $debug = false unless $debug
15 $daemonize = false unless $daemonize
16
17 $dateformat = "%Y/%m/%d %H:%M:%S"
18 $logger = Logger.new($stderr)
19 $logger.datetime_format = $dateformat
20 $logger.level = $cl_loglevel if defined? $cl_loglevel
21 $logger.level = 0 if $debug
22 $logger_stderr = $logger
23
24 $log_queue = Queue.new
25 $log_thread = nil
26
27 require 'pp'
28
29 unless Kernel.respond_to? :pretty_inspect
30   def pretty_inspect
31     PP.pp(self, '')
32   end
33   public :pretty_inspect
34 end
35
36 class Exception
37   def pretty_print(q)
38     q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
39       if self.backtrace and not self.backtrace.empty?
40         q.text "\n"
41         q.seplist(self.backtrace, lambda { q.text "\n" } ) { |l| q.text l }
42       end
43     }
44   end
45 end
46
47 class ServerError < RuntimeError
48 end
49
50 def rawlog(level, message=nil, who_pos=1)
51   call_stack = caller
52   if call_stack.length > who_pos
53     who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
54   else
55     who = "(unknown)"
56   end
57   # Output each line. To distinguish between separate messages and multi-line
58   # messages originating at the same time, we blank #{who} after the first message
59   # is output.
60   # Also, we output strings as-is but for other objects we use pretty_inspect
61   message = message.kind_of?(String) ? message : (message.pretty_inspect rescue '?')
62   qmsg = Array.new
63   message.each_line { |l|
64     qmsg.push [level, l.chomp, who]
65     who = ' ' * who.size
66   }
67   if level >= Logger::Severity::WARN and not $daemonize
68     qmsg.each do |l|
69       $logger_stderr.add(*l)
70     end
71   end
72   $log_queue.push qmsg
73 end
74
75 def halt_logger
76   if $log_thread && $log_thread.alive?
77     $log_queue << nil
78     $log_thread.join
79     $log_thread = nil
80   end
81 end
82
83 END { halt_logger }
84
85 def restart_logger(newlogger = false)
86   halt_logger
87
88   $logger = newlogger if newlogger
89
90   $log_thread = Thread.new do
91     ls = nil
92     while ls = $log_queue.pop
93       ls.each { |l| $logger.add(*l) }
94     end
95   end
96 end
97
98 restart_logger
99
100 def log_session_start
101   $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
102   restart_logger
103 end
104
105 def log_session_end
106   $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
107   $log_queue << nil
108 end
109
110 def debug(message=nil, who_pos=1)
111   rawlog(Logger::Severity::DEBUG, message, who_pos)
112 end
113
114 def log(message=nil, who_pos=1)
115   rawlog(Logger::Severity::INFO, message, who_pos)
116 end
117
118 def warning(message=nil, who_pos=1)
119   rawlog(Logger::Severity::WARN, message, who_pos)
120 end
121
122 def error(message=nil, who_pos=1)
123   rawlog(Logger::Severity::ERROR, message, who_pos)
124 end
125
126 def fatal(message=nil, who_pos=1)
127   rawlog(Logger::Severity::FATAL, message, who_pos)
128 end
129
130 debug "debug test"
131 log "log test"
132 warning "warning test"
133 error "error test"
134 fatal "fatal test"
135
136 # The following global is used for the improved signal handling.
137 $interrupted = 0
138
139 # these first
140 require 'rbot/rbotconfig'
141 begin
142   require 'rubygems'
143 rescue LoadError
144   log "rubygems unavailable"
145 end
146
147 require 'rbot/load-gettext'
148 require 'rbot/config'
149
150 require 'rbot/irc'
151 require 'rbot/rfc2812'
152 require 'rbot/ircsocket'
153 require 'rbot/botuser'
154 require 'rbot/timer'
155 require 'rbot/registry'
156 require 'rbot/plugins'
157 require 'rbot/message'
158 require 'rbot/language'
159
160 module Irc
161
162 # Main bot class, which manages the various components, receives messages,
163 # handles them or passes them to plugins, and contains core functionality.
164 class Bot
165   COPYRIGHT_NOTICE = "(c) Giuseppe Bilotta and the rbot development team"
166   SOURCE_URL = "http://ruby-rbot.org"
167   # the bot's Auth data
168   attr_reader :auth
169
170   # the bot's Config data
171   attr_reader :config
172
173   # the botclass for this bot (determines configdir among other things)
174   attr_reader :botclass
175
176   # used to perform actions periodically (saves configuration once per minute
177   # by default)
178   attr_reader :timer
179
180   # synchronize with this mutex while touching permanent data files:
181   # saving, flushing, cleaning up ...
182   attr_reader :save_mutex
183
184   # bot's Language data
185   attr_reader :lang
186
187   # bot's irc socket
188   # TODO multiserver
189   attr_reader :socket
190
191   # bot's plugins. This is an instance of class Plugins
192   attr_reader :plugins
193
194   # bot's httputil helper object, for fetching resources via http. Sets up
195   # proxies etc as defined by the bot configuration/environment
196   attr_accessor :httputil
197
198   # mechanize agent factory
199   attr_accessor :agent
200
201   # loads and opens new registry databases, used by the plugins
202   attr_accessor :registry_factory
203
204   # web service
205   attr_accessor :webservice
206
207   # server we are connected to
208   # TODO multiserver
209   def server
210     @client.server
211   end
212
213   # bot User in the client/server connection
214   # TODO multiserver
215   def myself
216     @client.user
217   end
218
219   # bot nick in the client/server connection
220   def nick
221     myself.nick
222   end
223
224   # bot channels in the client/server connection
225   def channels
226     myself.channels
227   end
228
229   # nick wanted by the bot. This defaults to the irc.nick config value,
230   # but may be overridden by a manual !nick command
231   def wanted_nick
232     @wanted_nick || config['irc.nick']
233   end
234
235   # set the nick wanted by the bot
236   def wanted_nick=(wn)
237     if wn.nil? or wn.to_s.downcase == config['irc.nick'].downcase
238       @wanted_nick = nil
239     else
240       @wanted_nick = wn.to_s.dup
241     end
242   end
243
244
245   # bot inspection
246   # TODO multiserver
247   def inspect
248     ret = self.to_s[0..-2]
249     ret << ' version=' << $version.inspect
250     ret << ' botclass=' << botclass.inspect
251     ret << ' lang="' << lang.language
252     if defined?(GetText)
253       ret << '/' << locale
254     end
255     ret << '"'
256     ret << ' nick=' << nick.inspect
257     ret << ' server='
258     if server
259       ret << (server.to_s + (socket ?
260         ' [' << socket.server_uri.to_s << ']' : '')).inspect
261       unless server.channels.empty?
262         ret << " channels="
263         ret << server.channels.map { |c|
264           "%s%s" % [c.modes_of(nick).map { |m|
265             server.prefix_for_mode(m)
266           }, c.name]
267         }.inspect
268       end
269     else
270       ret << '(none)'
271     end
272     ret << ' plugins=' << plugins.inspect
273     ret << ">"
274   end
275
276
277   # create a new Bot with botclass +botclass+
278   def initialize(botclass, params = {})
279     # Config for the core bot
280     # TODO should we split socket stuff into ircsocket, etc?
281     Config.register Config::ArrayValue.new('server.list',
282       :default => ['irc://localhost'], :wizard => true,
283       :requires_restart => true,
284       :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.")
285     Config.register Config::BooleanValue.new('server.ssl',
286       :default => false, :requires_restart => true, :wizard => true,
287       :desc => "Use SSL to connect to this server?")
288     Config.register Config::BooleanValue.new('server.ssl_verify',
289       :default => false, :requires_restart => true,
290       :desc => "Verify the SSL connection?",
291       :wizard => true)
292     Config.register Config::StringValue.new('server.ssl_ca_file',
293       :default => default_ssl_ca_file, :requires_restart => true,
294       :desc => "The CA file used to verify the SSL connection.",
295       :wizard => true)
296     Config.register Config::StringValue.new('server.ssl_ca_path',
297       :default => default_ssl_ca_path, :requires_restart => true,
298       :desc => "Alternativly a directory that includes CA PEM files used to verify the SSL connection.",
299       :wizard => true)
300     Config.register Config::StringValue.new('server.password',
301       :default => false, :requires_restart => true,
302       :desc => "Password for connecting to this server (if required)",
303       :wizard => true)
304     Config.register Config::StringValue.new('server.bindhost',
305       :default => false, :requires_restart => true,
306       :desc => "Specific local host or IP for the bot to bind to (if required)",
307       :wizard => true)
308     Config.register Config::IntegerValue.new('server.reconnect_wait',
309       :default => 5, :validate => Proc.new{|v| v >= 0},
310       :desc => "Seconds to wait before attempting to reconnect, on disconnect")
311     Config.register Config::IntegerValue.new('server.ping_timeout',
312       :default => 30, :validate => Proc.new{|v| v >= 0},
313       :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
314     Config.register Config::ArrayValue.new('server.nocolor_modes',
315       :default => ['c'], :wizard => false,
316       :requires_restart => false,
317       :desc => "List of channel modes that require messages to be without colors")
318
319     Config.register Config::StringValue.new('irc.nick', :default => "rbot",
320       :desc => "IRC nickname the bot should attempt to use", :wizard => true,
321       :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
322     Config.register Config::StringValue.new('irc.name',
323       :default => "Ruby bot", :requires_restart => true,
324       :desc => "IRC realname the bot should use")
325     Config.register Config::BooleanValue.new('irc.name_copyright',
326       :default => true, :requires_restart => true,
327       :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
328     Config.register Config::StringValue.new('irc.user', :default => "rbot",
329       :requires_restart => true,
330       :desc => "local user the bot should appear to be", :wizard => true)
331     Config.register Config::ArrayValue.new('irc.join_channels',
332       :default => [], :wizard => true,
333       :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'")
334     Config.register Config::ArrayValue.new('irc.ignore_users',
335       :default => [],
336       :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
337     Config.register Config::ArrayValue.new('irc.ignore_channels',
338       :default => [],
339       :desc => "Which channels to ignore input in. This is mainly to turn the bot into a logbot that doesn't interact with users in any way (in the specified channels)")
340
341     Config.register Config::IntegerValue.new('core.save_every',
342       :default => 60, :validate => Proc.new{|v| v >= 0},
343       :on_change => Proc.new { |bot, v|
344         if @save_timer
345           if v > 0
346             @timer.reschedule(@save_timer, v)
347             @timer.unblock(@save_timer)
348           else
349             @timer.block(@save_timer)
350           end
351         else
352           if v > 0
353             @save_timer = @timer.add(v) { bot.save }
354           end
355           # Nothing to do when v == 0
356         end
357       },
358       :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
359
360     Config.register Config::BooleanValue.new('core.run_as_daemon',
361       :default => false, :requires_restart => true,
362       :desc => "Should the bot run as a daemon?")
363
364     Config.register Config::StringValue.new('log.file',
365       :default => false, :requires_restart => true,
366       :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
367     Config.register Config::IntegerValue.new('log.level',
368       :default => 1, :requires_restart => false,
369       :validate => Proc.new { |v| (0..5).include?(v) },
370       :on_change => Proc.new { |bot, v|
371         $logger.level = v
372       },
373       :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
374     Config.register Config::IntegerValue.new('log.keep',
375       :default => 1, :requires_restart => true,
376       :validate => Proc.new { |v| v >= 0 },
377       :desc => "How many old console messages logfiles to keep")
378     Config.register Config::IntegerValue.new('log.max_size',
379       :default => 10, :requires_restart => true,
380       :validate => Proc.new { |v| v > 0 },
381       :desc => "Maximum console messages logfile size (in megabytes)")
382
383     Config.register Config::ArrayValue.new('plugins.path',
384       :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
385       :requires_restart => false,
386       :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
387       :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")
388
389     Config.register Config::EnumValue.new('send.newlines',
390       :values => ['split', 'join'], :default => 'split',
391       :on_change => Proc.new { |bot, v|
392         bot.set_default_send_options :newlines => v.to_sym
393       },
394       :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")
395     Config.register Config::StringValue.new('send.join_with',
396       :default => ' ',
397       :on_change => Proc.new { |bot, v|
398         bot.set_default_send_options :join_with => v.dup
399       },
400       :desc => "String used to replace newlines when send.newlines is set to join")
401     Config.register Config::IntegerValue.new('send.max_lines',
402       :default => 5,
403       :validate => Proc.new { |v| v >= 0 },
404       :on_change => Proc.new { |bot, v|
405         bot.set_default_send_options :max_lines => v
406       },
407       :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
408     Config.register Config::EnumValue.new('send.overlong',
409       :values => ['split', 'truncate'], :default => 'split',
410       :on_change => Proc.new { |bot, v|
411         bot.set_default_send_options :overlong => v.to_sym
412       },
413       :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")
414     Config.register Config::StringValue.new('send.split_at',
415       :default => '\s+',
416       :on_change => Proc.new { |bot, v|
417         bot.set_default_send_options :split_at => Regexp.new(v)
418       },
419       :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
420     Config.register Config::BooleanValue.new('send.purge_split',
421       :default => true,
422       :on_change => Proc.new { |bot, v|
423         bot.set_default_send_options :purge_split => v
424       },
425       :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
426     Config.register Config::StringValue.new('send.truncate_text',
427       :default => "#{Reverse}...#{Reverse}",
428       :on_change => Proc.new { |bot, v|
429         bot.set_default_send_options :truncate_text => v.dup
430       },
431       :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")
432     Config.register Config::IntegerValue.new('send.penalty_pct',
433       :default => 100,
434       :validate => Proc.new { |v| v >= 0 },
435       :on_change => Proc.new { |bot, v|
436         bot.socket.penalty_pct = v
437       },
438       :desc => "Percentage of IRC penalty to consider when sending messages to prevent being disconnected for excess flood. Set to 0 to disable penalty control.")
439     Config.register Config::StringValue.new('core.db',
440       :default => default_db, :store_default => true,
441       :wizard => true,
442       :validate => Proc.new { |v| Registry::formats.include? v },
443       :requires_restart => true,
444       :desc => "DB adaptor to use for storing the plugin data/registries. Options: " + Registry::formats.join(', '))
445
446     @argv = params[:argv]
447     @run_dir = params[:run_dir] || Dir.pwd
448
449     unless FileTest.directory? Config::coredir
450       error "core directory '#{Config::coredir}' not found, did you setup.rb?"
451       exit 2
452     end
453
454     unless FileTest.directory? Config::datadir
455       error "data directory '#{Config::datadir}' not found, did you setup.rb?"
456       exit 2
457     end
458
459     unless botclass and not botclass.empty?
460       # We want to find a sensible default.
461       # * On POSIX systems we prefer ~/.rbot for the effective uid of the process
462       # * On Windows (at least the NT versions) we want to put our stuff in the
463       #   Application Data folder.
464       # We don't use any particular O/S detection magic, exploiting the fact that
465       # Etc.getpwuid is nil on Windows
466       if Etc.getpwuid(Process::Sys.geteuid)
467         botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
468       else
469         if ENV.has_key?('APPDATA')
470           botclass = ENV['APPDATA'].dup
471           botclass.gsub!("\\","/")
472         end
473       end
474       botclass = File.join(botclass, ".rbot")
475     end
476     botclass = File.expand_path(botclass)
477     @botclass = botclass.gsub(/\/$/, "")
478
479     repopulate_botclass_directory
480
481     save_dir = File.join(@botclass, 'safe_save')
482     Dir.mkdir(save_dir) unless File.exist?(save_dir)
483     unless FileTest.directory? save_dir
484       error "safe save location #{save_dir} is not a directory"
485       exit 2
486     end
487
488     # Time at which the last PING was sent
489     @last_ping = nil
490     # Time at which the last line was RECV'd from the server
491     @last_rec = nil
492
493     @startup_time = Time.new
494
495     begin
496       @config = Config.manager
497       @config.bot_associate(self)
498     rescue Exception => e
499       fatal e
500       log_session_end
501       exit 2
502     end
503
504     if @config['core.run_as_daemon']
505       $daemonize = true
506     end
507
508     @registry_factory = Registry.new @config['core.db']
509     @registry_factory.migrate_registry_folder(path)
510
511     @logfile = @config['log.file']
512     if @logfile.class!=String || @logfile.empty?
513       logfname =  File.basename(botclass).gsub(/^\.+/,'')
514       logfname << ".log"
515       @logfile = File.join(botclass, logfname)
516       debug "Using `#{@logfile}' as debug log"
517     end
518
519     # See http://blog.humlab.umu.se/samuel/archives/000107.html
520     # for the backgrounding code
521     if $daemonize
522       begin
523         exit if fork
524         Process.setsid
525         exit if fork
526       rescue NotImplementedError
527         warning "Could not background, fork not supported"
528       rescue SystemExit
529         exit 0
530       rescue Exception => e
531         warning "Could not background. #{e.pretty_inspect}"
532       end
533       Dir.chdir botclass
534       # File.umask 0000                # Ensure sensible umask. Adjust as needed.
535     end
536
537     logger = Logger.new(@logfile,
538                         @config['log.keep'],
539                         @config['log.max_size']*1024*1024)
540     logger.datetime_format= $dateformat
541     logger.level = @config['log.level']
542     logger.level = $cl_loglevel if defined? $cl_loglevel
543     logger.level = 0 if $debug
544
545     restart_logger(logger)
546
547     log_session_start
548
549     if $daemonize
550       log "Redirecting standard input/output/error"
551       [$stdin, $stdout, $stderr].each do |fd|
552         begin
553           fd.reopen "/dev/null"
554         rescue Errno::ENOENT
555           # On Windows, there's not such thing as /dev/null
556           fd.reopen "NUL"
557         end
558       end
559
560       def $stdout.write(str=nil)
561         log str, 2
562         return str.to_s.size
563       end
564       def $stdout.write(str=nil)
565         if str.to_s.match(/:\d+: warning:/)
566           warning str, 2
567         else
568           error str, 2
569         end
570         return str.to_s.size
571       end
572     end
573
574     File.open($opts['pidfile'] || File.join(@botclass, 'rbot.pid'), 'w') do |pf|
575       pf << "#{$$}\n"
576     end
577
578     @timer = Timer.new
579     @save_mutex = Mutex.new
580     if @config['core.save_every'] > 0
581       @save_timer = @timer.add(@config['core.save_every']) { save }
582     else
583       @save_timer = nil
584     end
585     @quit_mutex = Mutex.new
586
587     @plugins = nil
588     @lang = Language.new(self, @config['core.language'])
589
590     begin
591       @auth = Auth::manager
592       @auth.bot_associate(self)
593       # @auth.load("#{botclass}/botusers.yaml")
594     rescue Exception => e
595       fatal e
596       log_session_end
597       exit 2
598     end
599     @auth.everyone.set_default_permission("*", true)
600     @auth.botowner.password= @config['auth.password']
601
602     @plugins = Plugins::manager
603     @plugins.bot_associate(self)
604     setup_plugins_path()
605
606     if @config['server.name']
607         debug "upgrading configuration (server.name => server.list)"
608         srv_uri = 'irc://' + @config['server.name']
609         srv_uri += ":#{@config['server.port']}" if @config['server.port']
610         @config.items['server.list'.to_sym].set_string(srv_uri)
611         @config.delete('server.name'.to_sym)
612         @config.delete('server.port'.to_sym)
613         debug "server.list is now #{@config['server.list'].inspect}"
614     end
615
616     @socket = Irc::Socket.new(@config['server.list'], @config['server.bindhost'], 
617                               :ssl => @config['server.ssl'],
618                               :ssl_verify => @config['server.ssl_verify'],
619                               :ssl_ca_file => @config['server.ssl_ca_file'],
620                               :ssl_ca_path => @config['server.ssl_ca_path'],
621                               :penalty_pct => @config['send.penalty_pct'])
622     @client = Client.new
623
624     @plugins.scan
625
626     # Channels where we are quiet
627     # Array of channels names where the bot should be quiet
628     # '*' means all channels
629     #
630     @quiet = Set.new
631     # but we always speak here
632     @not_quiet = Set.new
633
634     # the nick we want, if it's different from the irc.nick config value
635     # (e.g. as set by a !nick command)
636     @wanted_nick = nil
637
638     @client[:welcome] = proc {|data|
639       m = WelcomeMessage.new(self, server, data[:source], data[:target], data[:message])
640
641       @plugins.delegate("welcome", m)
642       @plugins.delegate("connect")
643     }
644
645     # TODO the next two @client should go into rfc2812.rb, probably
646     # Since capabs are two-steps processes, server.supports[:capab]
647     # should be a three-state: nil, [], [....]
648     asked_for = { :"identify-msg" => false }
649     @client[:isupport] = proc { |data|
650       if server.supports[:capab] and !asked_for[:"identify-msg"]
651         sendq "CAPAB IDENTIFY-MSG"
652         asked_for[:"identify-msg"] = true
653       end
654     }
655     @client[:datastr] = proc { |data|
656       if data[:text] == "IDENTIFY-MSG"
657         server.capabilities[:"identify-msg"] = true
658       else
659         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
660       end
661     }
662
663     @client[:privmsg] = proc { |data|
664       m = PrivMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
665       # debug "Message source is #{data[:source].inspect}"
666       # debug "Message target is #{data[:target].inspect}"
667       # debug "Bot is #{myself.inspect}"
668
669       @config['irc.ignore_channels'].each { |channel|
670         if m.target.downcase == channel.downcase
671           m.ignored = true
672           break
673         end
674       }
675       @config['irc.ignore_users'].each { |mask|
676         if m.source.matches?(server.new_netmask(mask))
677           m.ignored = true
678           break
679         end
680       } unless m.ignored
681
682       @plugins.irc_delegate('privmsg', m)
683     }
684     @client[:notice] = proc { |data|
685       message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message], :handle_id => true)
686       # pass it off to plugins that want to hear everything
687       @plugins.irc_delegate "notice", message
688     }
689     @client[:motd] = proc { |data|
690       m = MotdMessage.new(self, server, data[:source], data[:target], data[:motd])
691       @plugins.delegate "motd", m
692     }
693     @client[:nicktaken] = proc { |data|
694       new = "#{data[:nick]}_"
695       nickchg new
696       # If we're setting our nick at connection because our choice was taken,
697       # we have to fix our nick manually, because there will be no NICK message
698       # to inform us that our nick has been changed.
699       if data[:target] == '*'
700         debug "setting my connection nick to #{new}"
701         nick = new
702       end
703       @plugins.delegate "nicktaken", data[:nick]
704     }
705     @client[:badnick] = proc {|data|
706       warning "bad nick (#{data[:nick]})"
707     }
708     @client[:ping] = proc {|data|
709       sendq "PONG #{data[:pingid]}"
710     }
711     @client[:pong] = proc {|data|
712       @last_ping = nil
713     }
714     @client[:nick] = proc {|data|
715       # debug "Message source is #{data[:source].inspect}"
716       # debug "Bot is #{myself.inspect}"
717       source = data[:source]
718       old = data[:oldnick]
719       new = data[:newnick]
720       m = NickMessage.new(self, server, source, old, new)
721       m.is_on = data[:is_on]
722       if source == myself
723         debug "my nick is now #{new}"
724       end
725       @plugins.irc_delegate("nick", m)
726     }
727     @client[:quit] = proc {|data|
728       source = data[:source]
729       message = data[:message]
730       m = QuitMessage.new(self, server, source, source, message)
731       m.was_on = data[:was_on]
732       @plugins.irc_delegate("quit", m)
733     }
734     @client[:mode] = proc {|data|
735       m = ModeChangeMessage.new(self, server, data[:source], data[:target], data[:modestring])
736       m.modes = data[:modes]
737       @plugins.delegate "modechange", m
738     }
739     @client[:whois] = proc {|data|
740       source = data[:source]
741       target = server.get_user(data[:whois][:nick])
742       m = WhoisMessage.new(self, server, source, target, data[:whois])
743       @plugins.delegate "whois", m
744     }
745     @client[:list] = proc {|data|
746       source = data[:source]
747       m = ListMessage.new(self, server, source, source, data[:list])
748       @plugins.delegate "irclist", m
749     }
750     @client[:join] = proc {|data|
751       m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
752       sendq("MODE #{data[:channel]}", nil, 0) if m.address?
753       @plugins.irc_delegate("join", m)
754       sendq("WHO #{data[:channel]}", data[:channel], 2) if m.address?
755     }
756     @client[:part] = proc {|data|
757       m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
758       @plugins.irc_delegate("part", m)
759     }
760     @client[:kick] = proc {|data|
761       m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
762       @plugins.irc_delegate("kick", m)
763     }
764     @client[:invite] = proc {|data|
765       m = InviteMessage.new(self, server, data[:source], data[:target], data[:channel])
766       @plugins.irc_delegate("invite", m)
767     }
768     @client[:changetopic] = proc {|data|
769       m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
770       m.info_or_set = :set
771       @plugins.irc_delegate("topic", m)
772     }
773     # @client[:topic] = proc { |data|
774     #   irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
775     # }
776     @client[:topicinfo] = proc { |data|
777       channel = data[:channel]
778       topic = channel.topic
779       m = TopicMessage.new(self, server, data[:source], channel, topic)
780       m.info_or_set = :info
781       @plugins.irc_delegate("topic", m)
782     }
783     @client[:names] = proc { |data|
784       m = NamesMessage.new(self, server, server, data[:channel])
785       m.users = data[:users]
786       @plugins.delegate "names", m
787     }
788     @client[:banlist] = proc { |data|
789       m = BanlistMessage.new(self, server, server, data[:channel])
790       m.bans = data[:bans]
791       @plugins.delegate "banlist", m
792     }
793     @client[:nosuchtarget] = proc { |data|
794       m = NoSuchTargetMessage.new(self, server, server, data[:target], data[:message])
795       @plugins.delegate "nosuchtarget", m
796     }
797     @client[:error] = proc { |data|
798       raise ServerError, data[:message]
799     }
800     @client[:unknown] = proc { |data|
801       #debug "UNKNOWN: #{data[:serverstring]}"
802       m = UnknownMessage.new(self, server, server, nil, data[:serverstring])
803       @plugins.delegate "unknown_message", m
804     }
805
806     set_default_send_options :newlines => @config['send.newlines'].to_sym,
807       :join_with => @config['send.join_with'].dup,
808       :max_lines => @config['send.max_lines'],
809       :overlong => @config['send.overlong'].to_sym,
810       :split_at => Regexp.new(@config['send.split_at']),
811       :purge_split => @config['send.purge_split'],
812       :truncate_text => @config['send.truncate_text'].dup
813
814     trap_signals
815   end
816
817   # Determine (if possible) a valid path to a CA certificate bundle. 
818   def default_ssl_ca_file
819     [ '/etc/ssl/certs/ca-certificates.crt', # Ubuntu/Debian
820       '/etc/ssl/certs/ca-bundle.crt', # Amazon Linux
821       '/etc/ssl/ca-bundle.pem', # OpenSUSE
822       '/etc/pki/tls/certs/ca-bundle.crt' # Fedora/RHEL
823     ].find do |file|
824       File.readable? file
825     end
826   end
827
828   def default_ssl_ca_path
829     file = default_ssl_ca_file
830     File.dirname file if file
831   end
832
833   # Determine if tokyocabinet is installed, if it is use it as a default.
834   def default_db
835     begin
836       require 'tokyocabinet'
837       return 'tc'
838     rescue LoadError
839       return 'dbm'
840     end
841   end
842
843   def repopulate_botclass_directory
844     template_dir = File.join Config::datadir, 'templates'
845     if FileTest.directory? @botclass
846       # compare the templates dir with the current botclass dir, filling up the
847       # latter with any missing file. Sadly, FileUtils.cp_r doesn't have an
848       # :update option, so we have to do it manually.
849       # Note that we use the */** pattern because we don't want to match
850       # keywords.rbot, which gets deleted on load and would therefore be missing
851       # always
852       missing = Dir.chdir(template_dir) { Dir.glob('*/**') } - Dir.chdir(@botclass) { Dir.glob('*/**') }
853       missing.map do |f|
854         dest = File.join(@botclass, f)
855         FileUtils.mkdir_p(File.dirname(dest))
856         FileUtils.cp File.join(template_dir, f), dest
857       end
858     else
859       log "no #{@botclass} directory found, creating from templates..."
860       if FileTest.exist? @botclass
861         error "file #{@botclass} exists but isn't a directory"
862         exit 2
863       end
864       FileUtils.cp_r template_dir, @botclass
865     end
866   end
867
868   # Return a path under the current botclass by joining the mentioned
869   # components. The components are automatically converted to String
870   def path(*components)
871     File.join(@botclass, *(components.map {|c| c.to_s}))
872   end
873
874   def setup_plugins_path
875     plugdir_default = File.join(Config::datadir, 'plugins')
876     plugdir_local = File.join(@botclass, 'plugins')
877     Dir.mkdir(plugdir_local) unless File.exist?(plugdir_local)
878
879     @plugins.clear_botmodule_dirs
880     @plugins.add_core_module_dir(File.join(Config::coredir, 'utils'))
881     @plugins.add_core_module_dir(Config::coredir)
882     if FileTest.directory? plugdir_local
883       @plugins.add_plugin_dir(plugdir_local)
884     else
885       warning "local plugin location #{plugdir_local} is not a directory"
886     end
887
888     @config['plugins.path'].each do |_|
889         path = _.sub(/^\(default\)/, plugdir_default)
890         @plugins.add_plugin_dir(path)
891     end
892   end
893
894   def set_default_send_options(opts={})
895     # Default send options for NOTICE and PRIVMSG
896     unless defined? @default_send_options
897       @default_send_options = {
898         :queue_channel => nil,      # use default queue channel
899         :queue_ring => nil,         # use default queue ring
900         :newlines => :split,        # or :join
901         :join_with => ' ',          # by default, use a single space
902         :max_lines => 0,          # maximum number of lines to send with a single command
903         :overlong => :split,        # or :truncate
904         # TODO an array of splitpoints would be preferrable for this option:
905         :split_at => /\s+/,         # by default, split overlong lines at whitespace
906         :purge_split => true,       # should the split string be removed?
907         :truncate_text => "#{Reverse}...#{Reverse}"  # text to be appened when truncating
908       }
909     end
910     @default_send_options.update opts unless opts.empty?
911   end
912
913   # checks if we should be quiet on a channel
914   def quiet_on?(channel)
915     ch = channel.downcase
916     return (@quiet.include?('*') && !@not_quiet.include?(ch)) || @quiet.include?(ch)
917   end
918
919   def set_quiet(channel = nil)
920     if channel
921       ch = channel.downcase.dup
922       @not_quiet.delete(ch)
923       @quiet << ch
924     else
925       @quiet.clear
926       @not_quiet.clear
927       @quiet << '*'
928     end
929   end
930
931   def reset_quiet(channel = nil)
932     if channel
933       ch = channel.downcase.dup
934       @quiet.delete(ch)
935       @not_quiet << ch
936     else
937       @quiet.clear
938       @not_quiet.clear
939     end
940   end
941
942   # things to do when we receive a signal
943   def handle_signal(sig)
944     func = case sig
945            when 'SIGHUP'
946              :restart
947            when 'SIGUSR1'
948              :reconnect
949            else
950              :quit
951            end
952     debug "received #{sig}, queueing #{func}"
953     # this is not an interruption if we just need to reconnect
954     $interrupted += 1 unless func == :reconnect
955     self.send(func) unless @quit_mutex.locked?
956     debug "interrupted #{$interrupted} times"
957     if $interrupted >= 3
958       debug "drastic!"
959       log_session_end
960       exit 2
961     end
962   end
963
964   # trap signals
965   def trap_signals
966     begin
967       %w(SIGINT SIGTERM SIGHUP SIGUSR1).each do |sig|
968         trap(sig) { Thread.new { handle_signal sig } }
969       end
970     rescue ArgumentError => e
971       debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
972     rescue Exception => e
973       debug "failed to trap signals: #{e.pretty_inspect}"
974     end
975   end
976
977   # connect the bot to IRC
978   def connect
979     # make sure we don't have any spurious ping checks running
980     # (and initialize the vars if this is the first time we connect)
981     stop_server_pings
982     begin
983       quit if $interrupted > 0
984       @socket.connect
985       @last_rec = Time.now
986     rescue Exception => e
987       uri = @socket.server_uri || '<unknown>'
988       error "failed to connect to IRC server at #{uri}"
989       error e
990       raise
991     end
992     quit if $interrupted > 0
993
994     realname = @config['irc.name'].clone || 'Ruby bot'
995     realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright']
996
997     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
998     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
999     quit if $interrupted > 0
1000     myself.nick = @config['irc.nick']
1001     myself.user = @config['irc.user']
1002   end
1003
1004   # disconnect the bot from IRC, if connected, and then connect (again)
1005   def reconnect(message=nil, too_fast=0)
1006     # we will wait only if @last_rec was not nil, i.e. if we were connected or
1007     # got disconnected by a network error
1008     # if someone wants to manually call disconnect() _and_ reconnect(), they
1009     # will have to take care of the waiting themselves
1010     will_wait = !!@last_rec
1011
1012     if @socket.connected?
1013       disconnect(message)
1014     end
1015
1016     begin
1017       if will_wait
1018         log "\n\nDisconnected\n\n"
1019
1020         quit if $interrupted > 0
1021
1022         log "\n\nWaiting to reconnect\n\n"
1023         sleep @config['server.reconnect_wait']
1024         if too_fast > 0
1025           tf = too_fast*@config['server.reconnect_wait']
1026           tfu = Utils.secs_to_string(tf)
1027           log "Will sleep for an extra #{tf}s (#{tfu})"
1028           sleep tf
1029         end
1030       end
1031
1032       connect
1033     rescue SystemExit
1034       log_session_end
1035       exit 0
1036     rescue Exception => e
1037       error e
1038       will_wait = true
1039       retry
1040     end
1041   end
1042
1043   # begin event handling loop
1044   def mainloop
1045     while true
1046       too_fast = 0
1047       quit_msg = nil
1048       valid_recv = false # did we receive anything (valid) from the server yet?
1049       begin
1050         reconnect(quit_msg, too_fast)
1051         quit if $interrupted > 0
1052         valid_recv = false
1053         while @socket.connected?
1054           quit if $interrupted > 0
1055
1056           # Wait for messages and process them as they arrive. If nothing is
1057           # received, we call the ping_server() method that will PING the
1058           # server if appropriate, or raise a TimeoutError if no PONG has been
1059           # received in the user-chosen timeout since the last PING sent.
1060           if @socket.select(1)
1061             break unless reply = @socket.gets
1062             @last_rec = Time.now
1063             @client.process reply
1064             valid_recv = true
1065             too_fast = 0
1066           else
1067             ping_server
1068           end
1069         end
1070
1071       # I despair of this. Some of my users get "connection reset by peer"
1072       # exceptions that ARENT SocketError's. How am I supposed to handle
1073       # that?
1074       rescue SystemExit
1075         log_session_end
1076         exit 0
1077       rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
1078         error "network exception: #{e.pretty_inspect}"
1079         quit_msg = e.to_s
1080         too_fast += 10 if valid_recv
1081       rescue ServerMessageParseError => e
1082         # if the bot tried reconnecting too often, we can get forcefully
1083         # disconnected by the server, while still receiving an empty message
1084         # wait at least 10 minutes in this case
1085         if e.message.empty?
1086           oldtf = too_fast
1087           too_fast = [too_fast, 300].max
1088           too_fast*= 2
1089           log "Empty message from server, extra delay multiplier #{oldtf} -> #{too_fast}"
1090         end
1091         quit_msg = "Unparseable Server Message: #{e.message.inspect}"
1092         retry
1093       rescue ServerError => e
1094         quit_msg = "server ERROR: " + e.message
1095         debug quit_msg
1096         idx = e.message.index("connect too fast")
1097         debug "'connect too fast' @ #{idx}"
1098         if idx
1099           oldtf = too_fast
1100           too_fast += (idx+1)*2
1101           log "Reconnecting too fast, extra delay multiplier #{oldtf} -> #{too_fast}"
1102         end
1103         idx = e.message.index(/a(uto)kill/i)
1104         debug "'autokill' @ #{idx}"
1105         if idx
1106           # we got auto-killed. since we don't have an easy way to tell
1107           # if it's permanent or temporary, we just set a rather high
1108           # reconnection timeout
1109           oldtf = too_fast
1110           too_fast += (idx+1)*5
1111           log "Killed by server, extra delay multiplier #{oldtf} -> #{too_fast}"
1112         end
1113         retry
1114       rescue Exception => e
1115         error "non-net exception: #{e.pretty_inspect}"
1116         quit_msg = e.to_s
1117       rescue => e
1118         fatal "unexpected exception: #{e.pretty_inspect}"
1119         log_session_end
1120         exit 2
1121       end
1122     end
1123   end
1124
1125   # type:: message type
1126   # where:: message target
1127   # message:: message text
1128   # send message +message+ of type +type+ to target +where+
1129   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
1130   # relevant say() or notice() methods. This one should be used for IRCd
1131   # extensions you want to use in modules.
1132   def sendmsg(original_type, original_where, original_message, options={})
1133
1134     # filter message with sendmsg filters
1135     ds = DataStream.new original_message.to_s.dup,
1136       :type => original_type, :dest => original_where,
1137       :options => @default_send_options.merge(options)
1138     filters = filter_names(:sendmsg)
1139     filters.each do |fname|
1140       debug "filtering #{ds[:text]} with sendmsg filter #{fname}"
1141       ds.merge! filter(self.global_filter_name(fname, :sendmsg), ds)
1142     end
1143
1144     opts = ds[:options]
1145     type = ds[:type]
1146     where = ds[:dest]
1147     filtered = ds[:text]
1148
1149     if defined? WebServiceUser and where.instance_of? WebServiceUser
1150       debug 'sendmsg to web service!'
1151       where.response << filtered
1152       return
1153     end
1154
1155     # For starters, set up appropriate queue channels and rings
1156     mchan = opts[:queue_channel]
1157     mring = opts[:queue_ring]
1158     if mchan
1159       chan = mchan
1160     else
1161       chan = where
1162     end
1163     if mring
1164       ring = mring
1165     else
1166       case where
1167       when User
1168         ring = 1
1169       else
1170         ring = 2
1171       end
1172     end
1173
1174     multi_line = filtered.gsub(/[\r\n]+/, "\n")
1175
1176     # if target is a channel with nocolor modes, strip colours
1177     if where.kind_of?(Channel) and where.mode.any?(*config['server.nocolor_modes'])
1178       multi_line.replace BasicUserMessage.strip_formatting(multi_line)
1179     end
1180
1181     messages = Array.new
1182     case opts[:newlines]
1183     when :join
1184       messages << [multi_line.gsub("\n", opts[:join_with])]
1185     when :split
1186       multi_line.each_line { |line|
1187         line.chomp!
1188         next unless(line.size > 0)
1189         messages << line
1190       }
1191     else
1192       raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
1193     end
1194
1195     # The IRC protocol requires that each raw message must be not longer
1196     # than 512 characters. From this length with have to subtract the EOL
1197     # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
1198     # that will be prepended by the server to all of our messages.
1199
1200     # The maximum raw message length we can send is therefore 512 - 2 - 2
1201     # minus the length of our hostmask.
1202
1203     max_len = 508 - myself.fullform.size
1204
1205     # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
1206     # will have a + or - prepended
1207     if server.capabilities[:"identify-msg"]
1208       max_len -= 1
1209     end
1210
1211     # When splitting the message, we'll be prefixing the following string:
1212     # (e.g. "PRIVMSG #rbot :")
1213     fixed = "#{type} #{where} :"
1214
1215     # And this is what's left
1216     left = max_len - fixed.size
1217
1218     truncate = opts[:truncate_text]
1219     truncate = @default_send_options[:truncate_text] if truncate.size > left
1220     truncate = "" if truncate.size > left
1221
1222     all_lines = messages.map { |line|
1223       if line.size < left
1224         line
1225       else
1226         case opts[:overlong]
1227         when :split
1228           msg = line.dup
1229           sub_lines = Array.new
1230           begin
1231             sub_lines << msg.slice!(0, left)
1232             break if msg.empty?
1233             lastspace = sub_lines.last.rindex(opts[:split_at])
1234             if lastspace
1235               msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
1236               msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
1237             end
1238           end until msg.empty?
1239           sub_lines
1240         when :truncate
1241           line.slice(0, left - truncate.size) << truncate
1242         else
1243           raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
1244         end
1245       end
1246     }.flatten
1247
1248     if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
1249       lines = all_lines[0...opts[:max_lines]]
1250       new_last = lines.last.slice(0, left - truncate.size) << truncate
1251       lines.last.replace(new_last)
1252     else
1253       lines = all_lines
1254     end
1255
1256     lines.each { |line|
1257       sendq "#{fixed}#{line}", chan, ring
1258       delegate_sent(type, where, line)
1259     }
1260   end
1261
1262   # queue an arbitraty message for the server
1263   def sendq(message="", chan=nil, ring=0)
1264     # temporary
1265     @socket.queue(message, chan, ring)
1266   end
1267
1268   # send a notice message to channel/nick +where+
1269   def notice(where, message, options={})
1270     return if where.kind_of?(Channel) and quiet_on?(where)
1271     sendmsg "NOTICE", where, message, options
1272   end
1273
1274   # say something (PRIVMSG) to channel/nick +where+
1275   def say(where, message, options={})
1276     return if where.kind_of?(Channel) and quiet_on?(where)
1277     sendmsg "PRIVMSG", where, message, options
1278   end
1279
1280   def ctcp_notice(where, command, message, options={})
1281     return if where.kind_of?(Channel) and quiet_on?(where)
1282     sendmsg "NOTICE", where, "\001#{command} #{message}\001", options
1283   end
1284
1285   def ctcp_say(where, command, message, options={})
1286     return if where.kind_of?(Channel) and quiet_on?(where)
1287     sendmsg "PRIVMSG", where, "\001#{command} #{message}\001", options
1288   end
1289
1290   # perform a CTCP action with message +message+ to channel/nick +where+
1291   def action(where, message, options={})
1292     ctcp_say(where, 'ACTION', message, options)
1293   end
1294
1295   # quick way to say "okay" (or equivalent) to +where+
1296   def okay(where)
1297     say where, @lang.get("okay")
1298   end
1299
1300   # set topic of channel +where+ to +topic+
1301   # can also be used to retrieve the topic of channel +where+
1302   # by omitting the last argument
1303   def topic(where, topic=nil)
1304     if topic.nil?
1305       sendq "TOPIC #{where}", where, 2
1306     else
1307       sendq "TOPIC #{where} :#{topic}", where, 2
1308     end
1309   end
1310
1311   def disconnect(message=nil)
1312     message = @lang.get("quit") if (!message || message.empty?)
1313     if @socket.connected?
1314       begin
1315         debug "Clearing socket"
1316         @socket.clearq
1317         debug "Sending quit message"
1318         @socket.emergency_puts "QUIT :#{message}"
1319         debug "Logging quits"
1320         delegate_sent('QUIT', myself, message)
1321         debug "Flushing socket"
1322         @socket.flush
1323       rescue SocketError => e
1324         error "error while disconnecting socket: #{e.pretty_inspect}"
1325       end
1326       debug "Shutting down socket"
1327       @socket.shutdown
1328     end
1329     stop_server_pings
1330     @client.reset
1331   end
1332
1333   # disconnect from the server and cleanup all plugins and modules
1334   def shutdown(message=nil)
1335     @quit_mutex.synchronize do
1336       debug "Shutting down: #{message}"
1337       ## No we don't restore them ... let everything run through
1338       # begin
1339       #   trap("SIGINT", "DEFAULT")
1340       #   trap("SIGTERM", "DEFAULT")
1341       #   trap("SIGHUP", "DEFAULT")
1342       # rescue => e
1343       #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1344       # end
1345       debug "\tdisconnecting..."
1346       disconnect(message)
1347       debug "\tstopping timer..."
1348       @timer.stop
1349       debug "\tsaving ..."
1350       save
1351       debug "\tcleaning up ..."
1352       @save_mutex.synchronize do
1353         begin
1354           @plugins.cleanup
1355         rescue
1356           debug "\tignoring cleanup error: #{$!}"
1357         end
1358       end
1359       # debug "\tstopping timers ..."
1360       # @timer.stop
1361       # debug "Closing registries"
1362       # @registry.close
1363       log "rbot quit (#{message})"
1364     end
1365   end
1366
1367   # message:: optional IRC quit message
1368   # quit IRC, shutdown the bot
1369   def quit(message=nil)
1370     begin
1371       shutdown(message)
1372     ensure
1373       exit 0
1374     end
1375   end
1376
1377   # totally shutdown and respawn the bot
1378   def restart(message=nil)
1379     message = _("restarting, back in %{wait}...") % {
1380       :wait => @config['server.reconnect_wait']
1381     } if (!message || message.empty?)
1382     shutdown(message)
1383     sleep @config['server.reconnect_wait']
1384     begin
1385       # now we re-exec
1386       # Note, this fails on Windows
1387       debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1388       log_session_end
1389       Dir.chdir(@run_dir)
1390       exec($0, *@argv)
1391     rescue Errno::ENOENT
1392       log_session_end
1393       exec("ruby", *(@argv.unshift $0))
1394     rescue Exception => e
1395       $interrupted += 1
1396       raise e
1397     end
1398   end
1399
1400   # call the save method for all or the specified botmodule
1401   #
1402   # :botmodule ::
1403   #   optional botmodule to save
1404   def save(botmodule=nil)
1405     @save_mutex.synchronize do
1406       @plugins.save(botmodule)
1407     end
1408   end
1409
1410   # call the rescan method for all or just the specified botmodule
1411   #
1412   # :botmodule ::
1413   #   instance of the botmodule to rescan
1414   def rescan(botmodule=nil)
1415     debug "\tstopping timer..."
1416     @timer.stop
1417     @save_mutex.synchronize do
1418       # @lang.rescan
1419       @plugins.rescan(botmodule)
1420     end
1421     @timer.start
1422   end
1423
1424   # channel:: channel to join
1425   # key::     optional channel key if channel is +s
1426   # join a channel
1427   def join(channel, key=nil)
1428     if(key)
1429       sendq "JOIN #{channel} :#{key}", channel, 2
1430     else
1431       sendq "JOIN #{channel}", channel, 2
1432     end
1433   end
1434
1435   # part a channel
1436   def part(channel, message="")
1437     sendq "PART #{channel} :#{message}", channel, 2
1438   end
1439
1440   # attempt to change bot's nick to +name+
1441   def nickchg(name)
1442     sendq "NICK #{name}"
1443   end
1444
1445   # changing mode
1446   def mode(channel, mode, target=nil)
1447     sendq "MODE #{channel} #{mode} #{target}", channel, 2
1448   end
1449
1450   # asking whois
1451   def whois(nick, target=nil)
1452     sendq "WHOIS #{target} #{nick}", nil, 0
1453   end
1454
1455   # kicking a user
1456   def kick(channel, user, msg)
1457     sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1458   end
1459
1460   # m::     message asking for help
1461   # topic:: optional topic help is requested for
1462   # respond to online help requests
1463   def help(topic=nil)
1464     topic = nil if topic == ""
1465     case topic
1466     when nil
1467       helpstr = _("help topics: ")
1468       helpstr += @plugins.helptopics
1469       helpstr += _(" (help <topic> for more info)")
1470     else
1471       unless(helpstr = @plugins.help(topic))
1472         helpstr = _("no help for topic %{topic}") % { :topic => topic }
1473       end
1474     end
1475     return helpstr
1476   end
1477
1478   # returns a string describing the current status of the bot (uptime etc)
1479   def status
1480     secs_up = Time.new - @startup_time
1481     uptime = Utils.secs_to_string secs_up
1482     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1483     return (_("Uptime %{up}, %{plug} plugins active, %{sent} lines sent, %{recv} received.") %
1484              {
1485                :up => uptime, :plug => @plugins.length,
1486                :sent => @socket.lines_sent, :recv => @socket.lines_received
1487              })
1488   end
1489
1490   # We want to respond to a hung server in a timely manner. If nothing was received
1491   # in the user-selected timeout and we haven't PINGed the server yet, we PING
1492   # the server. If the PONG is not received within the user-defined timeout, we
1493   # assume we're in ping timeout and act accordingly.
1494   def ping_server
1495     act_timeout = @config['server.ping_timeout']
1496     return if act_timeout <= 0
1497     now = Time.now
1498     if @last_rec && now > @last_rec + act_timeout
1499       if @last_ping.nil?
1500         # No previous PING pending, send a new one
1501         sendq "PING :rbot"
1502         @last_ping = Time.now
1503       else
1504         diff = now - @last_ping
1505         if diff > act_timeout
1506           debug "no PONG from server in #{diff} seconds, reconnecting"
1507           # the actual reconnect is handled in the main loop:
1508           raise TimeoutError, "no PONG from server in #{diff} seconds"
1509         end
1510       end
1511     end
1512   end
1513
1514   def stop_server_pings
1515     # cancel previous PINGs and reset time of last RECV
1516     @last_ping = nil
1517     @last_rec = nil
1518   end
1519
1520   private
1521
1522   # delegate sent messages
1523   def delegate_sent(type, where, message)
1524     args = [self, server, myself, server.user_or_channel(where.to_s), message]
1525     case type
1526       when "NOTICE"
1527         m = NoticeMessage.new(*args)
1528       when "PRIVMSG"
1529         m = PrivMessage.new(*args)
1530       when "QUIT"
1531         m = QuitMessage.new(*args)
1532         m.was_on = myself.channels
1533     end
1534     @plugins.delegate('sent', m)
1535   end
1536
1537 end
1538
1539 end