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