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