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