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