]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
8249895b48f294af561c662811f90d0ece9175ce
[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 IrcBot
92   # the bot's IrcAuth data
93   attr_reader :auth
94
95   # the bot's BotConfig data
96   attr_reader :config
97
98   # the botclass for this bot (determines configdir among other things)
99   attr_reader :botclass
100
101   # used to perform actions periodically (saves configuration once per minute
102   # by default)
103   attr_reader :timer
104
105   # synchronize with this mutex while touching permanent data files:
106   # saving, flushing, cleaning up ...
107   attr_reader :save_mutex
108
109   # bot's Language data
110   attr_reader :lang
111
112   # bot's irc socket
113   # TODO multiserver
114   attr_reader :socket
115
116   # bot's object registry, plugins get an interface to this for persistant
117   # storage (hash interface tied to a bdb file, plugins use Accessors to store
118   # and restore objects in their own namespaces.)
119   attr_reader :registry
120
121   # bot's plugins. This is an instance of class Plugins
122   attr_reader :plugins
123
124   # bot's httputil help object, for fetching resources via http. Sets up
125   # proxies etc as defined by the bot configuration/environment
126   attr_reader :httputil
127
128   # server we are connected to
129   # TODO multiserver
130   def server
131     @client.server
132   end
133
134   # bot User in the client/server connection
135   # TODO multiserver
136   def myself
137     @client.client
138   end
139
140   # bot User in the client/server connection
141   def nick
142     myself.nick
143   end
144
145   # create a new IrcBot with botclass +botclass+
146   def initialize(botclass, params = {})
147     # BotConfig for the core bot
148     # TODO should we split socket stuff into ircsocket, etc?
149     BotConfig.register BotConfigStringValue.new('server.name',
150       :default => "localhost", :requires_restart => true,
151       :desc => "What server should the bot connect to?",
152       :wizard => true)
153     BotConfig.register BotConfigIntegerValue.new('server.port',
154       :default => 6667, :type => :integer, :requires_restart => true,
155       :desc => "What port should the bot connect to?",
156       :validate => Proc.new {|v| v > 0}, :wizard => true)
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 BotConfigStringValue.new('server.byterate',
177       :default => "400/2", :validate => Proc.new{|v| v.match(/\d+\/\d/)},
178       :desc => "(flood prevention) max bytes/seconds rate to send the server. Most ircd's have limits of 512 bytes/2 seconds",
179       :on_change => Proc.new {|bot, v| bot.socket.byterate = v })
180     BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
181       :default => 30, :validate => Proc.new{|v| v >= 0},
182       :on_change => Proc.new {|bot, v| bot.start_server_pings},
183       :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
184
185     BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
186       :desc => "IRC nickname the bot should attempt to use", :wizard => true,
187       :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
188     BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
189       :requires_restart => true,
190       :desc => "local user the bot should appear to be", :wizard => true)
191     BotConfig.register BotConfigArrayValue.new('irc.join_channels',
192       :default => [], :wizard => true,
193       :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'")
194     BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
195       :default => [], 
196       :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
197
198     BotConfig.register BotConfigIntegerValue.new('core.save_every',
199       :default => 60, :validate => Proc.new{|v| v >= 0},
200       # TODO change timer via on_change proc
201       :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
202
203     BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
204       :default => false, :requires_restart => true,
205       :desc => "Should the bot run as a daemon?")
206
207     BotConfig.register BotConfigStringValue.new('log.file',
208       :default => false, :requires_restart => true,
209       :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
210     BotConfig.register BotConfigIntegerValue.new('log.level',
211       :default => 1, :requires_restart => false,
212       :validate => Proc.new { |v| (0..5).include?(v) },
213       :on_change => Proc.new { |bot, v|
214         $logger.level = v
215       },
216       :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
217     BotConfig.register BotConfigIntegerValue.new('log.keep',
218       :default => 1, :requires_restart => true,
219       :validate => Proc.new { |v| v >= 0 },
220       :desc => "How many old console messages logfiles to keep")
221     BotConfig.register BotConfigIntegerValue.new('log.max_size',
222       :default => 10, :requires_restart => true,
223       :validate => Proc.new { |v| v > 0 },
224       :desc => "Maximum console messages logfile size (in megabytes)")
225
226     @argv = params[:argv]
227
228     unless FileTest.directory? Config::coredir
229       error "core directory '#{Config::coredir}' not found, did you setup.rb?"
230       exit 2
231     end
232
233     unless FileTest.directory? Config::datadir
234       error "data directory '#{Config::datadir}' not found, did you setup.rb?"
235       exit 2
236     end
237
238     unless botclass and not botclass.empty?
239       # We want to find a sensible default.
240       #  * On POSIX systems we prefer ~/.rbot for the effective uid of the process
241       #  * On Windows (at least the NT versions) we want to put our stuff in the
242       #    Application Data folder.
243       # We don't use any particular O/S detection magic, exploiting the fact that
244       # Etc.getpwuid is nil on Windows
245       if Etc.getpwuid(Process::Sys.geteuid)
246         botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
247       else
248         if ENV.has_key?('APPDATA')
249           botclass = ENV['APPDATA'].dup
250           botclass.gsub!("\\","/")
251         end
252       end
253       botclass += "/.rbot"
254     end
255     botclass = File.expand_path(botclass)
256     @botclass = botclass.gsub(/\/$/, "")
257
258     unless FileTest.directory? botclass
259       log "no #{botclass} directory found, creating from templates.."
260       if FileTest.exist? botclass
261         error "file #{botclass} exists but isn't a directory"
262         exit 2
263       end
264       FileUtils.cp_r Config::datadir+'/templates', botclass
265     end
266
267     Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
268     Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
269     Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
270     Utils.set_safe_save_dir("#{botclass}/safe_save")
271
272     @ping_timer = nil
273     @pong_timer = nil
274     @last_ping = nil
275     @startup_time = Time.new
276
277     begin
278       @config = BotConfig.configmanager
279       @config.bot_associate(self)
280     rescue => e
281       fatal e.inspect
282       fatal e.backtrace.join("\n")
283       log_session_end
284       exit 2
285     end
286
287     if @config['core.run_as_daemon']
288       $daemonize = true
289     end
290
291     @logfile = @config['log.file']
292     if @logfile.class!=String || @logfile.empty?
293       @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
294     end
295
296     # See http://blog.humlab.umu.se/samuel/archives/000107.html
297     # for the backgrounding code 
298     if $daemonize
299       begin
300         exit if fork
301         Process.setsid
302         exit if fork
303       rescue NotImplementedError
304         warning "Could not background, fork not supported"
305       rescue => e
306         warning "Could not background. #{e.inspect}"
307       end
308       Dir.chdir botclass
309       # File.umask 0000                # Ensure sensible umask. Adjust as needed.
310       log "Redirecting standard input/output/error"
311       begin
312         STDIN.reopen "/dev/null"
313       rescue Errno::ENOENT
314         # On Windows, there's not such thing as /dev/null
315         STDIN.reopen "NUL"
316       end
317       def STDOUT.write(str=nil)
318         log str, 2
319         return str.to_s.length
320       end
321       def STDERR.write(str=nil)
322         if str.to_s.match(/:\d+: warning:/)
323           warning str, 2
324         else
325           error str, 2
326         end
327         return str.to_s.length
328       end
329     end
330
331     # Set the new logfile and loglevel. This must be done after the daemonizing
332     $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
333     $logger.datetime_format= $dateformat
334     $logger.level = @config['log.level']
335     $logger.level = $cl_loglevel if $cl_loglevel
336     $logger.level = 0 if $debug
337
338     log_session_start
339
340     @registry = BotRegistry.new self
341
342     @timer = Timer::Timer.new(1.0) # only need per-second granularity
343     @save_mutex = Mutex.new
344     @timer.add(@config['core.save_every']) { save } if @config['core.save_every']
345     @quit_mutex = Mutex.new
346
347     @logs = Hash.new
348
349     @httputil = Utils::HttpUtil.new(self)
350
351     @plugins = nil
352     @lang = Language::Language.new(self, @config['core.language'])
353
354     begin
355       @auth = Auth::authmanager
356       @auth.bot_associate(self)
357       # @auth.load("#{botclass}/botusers.yaml")
358     rescue => e
359       fatal e.inspect
360       fatal e.backtrace.join("\n")
361       log_session_end
362       exit 2
363     end
364     @auth.everyone.set_default_permission("*", true)
365     @auth.botowner.password= @config['auth.password']
366
367     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
368     @plugins = Plugins::pluginmanager
369     @plugins.bot_associate(self)
370     @plugins.add_botmodule_dir(Config::coredir)
371     @plugins.add_botmodule_dir("#{botclass}/plugins")
372     @plugins.add_botmodule_dir(Config::datadir + "/plugins")
373     @plugins.scan
374
375     @socket = IrcSocket.new(@config['server.name'], @config['server.port'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'])
376     @client = IrcClient.new
377     myself.nick = @config['irc.nick']
378
379     # Channels where we are quiet
380     # It's nil when we are not quiet, an empty list when we are quiet
381     # in all channels, a list of channels otherwise
382     @quiet = nil
383
384     @client[:welcome] = proc {|data|
385       irclog "joined server #{@client.server} as #{myself}", "server"
386
387       @plugins.delegate("connect")
388
389       @config['irc.join_channels'].each { |c|
390         debug "autojoining channel #{c}"
391         if(c =~ /^(\S+)\s+(\S+)$/i)
392           join $1, $2
393         else
394           join c if(c)
395         end
396       }
397     }
398     @client[:isupport] = proc { |data|
399       # TODO this needs to go into rfc2812.rb
400       # Since capabs are two-steps processes, server.supports[:capab]
401       # should be a three-state: nil, [], [....]
402       sendq "CAPAB IDENTIFY-MSG" if server.supports[:capab]
403     }
404     @client[:datastr] = proc { |data|
405       # TODO this needs to go into rfc2812.rb
406       if data[:text] == "IDENTIFY-MSG"
407         server.capabilities["identify-msg".to_sym] = true
408       else
409         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
410       end
411     }
412     @client[:privmsg] = proc { |data|
413       m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
414       # debug "Message source is #{data[:source].inspect}"
415       # debug "Message target is #{data[:target].inspect}"
416       # debug "Bot is #{myself.inspect}"
417
418       # TODO use the new Netmask class
419       # @config['irc.ignore_users'].each { |mask| return if Irc.netmaskmatch(mask,m.source) }
420
421       irclogprivmsg(m)
422
423       @plugins.delegate "listen", m
424       @plugins.privmsg(m) if m.address?
425     }
426     @client[:notice] = proc { |data|
427       message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
428       # pass it off to plugins that want to hear everything
429       @plugins.delegate "listen", message
430     }
431     @client[:motd] = proc { |data|
432       data[:motd].each_line { |line|
433         irclog "MOTD: #{line}", "server"
434       }
435     }
436     @client[:nicktaken] = proc { |data|
437       nickchg "#{data[:nick]}_"
438       @plugins.delegate "nicktaken", data[:nick]
439     }
440     @client[:badnick] = proc {|data|
441       warning "bad nick (#{data[:nick]})"
442     }
443     @client[:ping] = proc {|data|
444       sendq "PONG #{data[:pingid]}"
445     }
446     @client[:pong] = proc {|data|
447       @last_ping = nil
448     }
449     @client[:nick] = proc {|data|
450       source = data[:source]
451       old = data[:oldnick]
452       new = data[:newnick]
453       m = NickMessage.new(self, server, source, old, new)
454       if source == myself
455         debug "my nick is now #{new}"
456       end
457       data[:is_on].each { |ch|
458           irclog "@ #{old} is now known as #{new}", ch
459       }
460       @plugins.delegate("listen", m)
461       @plugins.delegate("nick", m)
462     }
463     @client[:quit] = proc {|data|
464       source = data[:source]
465       message = data[:message]
466       m = QuitMessage.new(self, server, source, source, message)
467       data[:was_on].each { |ch|
468         irclog "@ Quit: #{source}: #{message}", ch
469       }
470       @plugins.delegate("listen", m)
471       @plugins.delegate("quit", m)
472     }
473     @client[:mode] = proc {|data|
474       irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
475     }
476     @client[:join] = proc {|data|
477       m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
478       irclogjoin(m)
479
480       @plugins.delegate("listen", m)
481       @plugins.delegate("join", m)
482     }
483     @client[:part] = proc {|data|
484       m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
485       irclogpart(m)
486
487       @plugins.delegate("listen", m)
488       @plugins.delegate("part", m)
489     }
490     @client[:kick] = proc {|data|
491       m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
492       irclogkick(m)
493
494       @plugins.delegate("listen", m)
495       @plugins.delegate("kick", m)
496     }
497     @client[:invite] = proc {|data|
498       if data[:target] == myself
499         join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
500       end
501     }
502     @client[:changetopic] = proc {|data|
503       m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
504       irclogtopic(m)
505
506       @plugins.delegate("listen", m)
507       @plugins.delegate("topic", m)
508     }
509     @client[:topic] = proc { |data|
510       irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
511     }
512     @client[:topicinfo] = proc { |data|
513       channel = data[:channel]
514       topic = channel.topic
515       irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
516       m = TopicMessage.new(self, server, data[:source], channel, topic)
517
518       @plugins.delegate("listen", m)
519       @plugins.delegate("topic", m)
520     }
521     @client[:names] = proc { |data|
522       @plugins.delegate "names", data[:channel], data[:users]
523     }
524     @client[:unknown] = proc { |data|
525       #debug "UNKNOWN: #{data[:serverstring]}"
526       irclog data[:serverstring], ".unknown"
527     }
528   end
529
530   # checks if we should be quiet on a channel
531   def quiet_on?(channel)
532     return false unless @quiet
533     return true if @quiet.empty?
534     return @quiet.include?(channel.to_s)
535   end
536
537   def set_quiet(channel=nil)
538     if channel
539       @quiet << channel.to_s unless @quiet.include?(channel.to_s)
540     else
541       @quiet = []
542     end
543   end
544
545   def reset_quiet(channel=nil)
546     if channel
547       @quiet.delete_if { |x| x == channel.to_s }
548     else
549       @quiet = nil
550     end
551   end
552
553   # things to do when we receive a signal
554   def got_sig(sig)
555     debug "received #{sig}, queueing quit"
556     $interrupted += 1
557     quit unless @quit_mutex.locked?
558     debug "interrupted #{$interrupted} times"
559     if $interrupted >= 3
560       debug "drastic!"
561       log_session_end
562       exit 2
563     end
564   end
565
566   # connect the bot to IRC
567   def connect
568     begin
569       trap("SIGINT") { got_sig("SIGINT") }
570       trap("SIGTERM") { got_sig("SIGTERM") }
571       trap("SIGHUP") { got_sig("SIGHUP") }
572     rescue ArgumentError => e
573       debug "failed to trap signals (#{e.inspect}): running on Windows?"
574     rescue => e
575       debug "failed to trap signals: #{e.inspect}"
576     end
577     begin
578       quit if $interrupted > 0
579       @socket.connect
580     rescue => e
581       raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
582     end
583     quit if $interrupted > 0
584     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
585     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
586     quit if $interrupted > 0
587     start_server_pings
588   end
589
590   # begin event handling loop
591   def mainloop
592     while true
593       begin
594         quit if $interrupted > 0
595         connect
596         @timer.start
597
598         while @socket.connected?
599           quit if $interrupted > 0
600           if @socket.select
601             break unless reply = @socket.gets
602             @client.process reply
603           end
604         end
605
606       # I despair of this. Some of my users get "connection reset by peer"
607       # exceptions that ARENT SocketError's. How am I supposed to handle
608       # that?
609       rescue SystemExit
610         log_session_end
611         exit 0
612       rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
613         error "network exception: #{e.class}: #{e}"
614         debug e.backtrace.join("\n")
615       rescue BDB::Fatal => e
616         fatal "fatal bdb error: #{e.class}: #{e}"
617         fatal e.backtrace.join("\n")
618         DBTree.stats
619         # Why restart? DB problems are serious stuff ...
620         # restart("Oops, we seem to have registry problems ...")
621         log_session_end
622         exit 2
623       rescue Exception => e
624         error "non-net exception: #{e.class}: #{e}"
625         error e.backtrace.join("\n")
626       rescue => e
627         fatal "unexpected exception: #{e.class}: #{e}"
628         fatal e.backtrace.join("\n")
629         log_session_end
630         exit 2
631       end
632
633       stop_server_pings
634       server.clear
635       if @socket.connected?
636         @socket.clearq
637         @socket.shutdown
638       end
639
640       log "disconnected"
641
642       quit if $interrupted > 0
643
644       log "waiting to reconnect"
645       sleep @config['server.reconnect_wait']
646     end
647   end
648
649   # type:: message type
650   # where:: message target
651   # message:: message text
652   # send message +message+ of type +type+ to target +where+
653   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
654   # relevant say() or notice() methods. This one should be used for IRCd
655   # extensions you want to use in modules.
656   def sendmsg(type, where, message, chan=nil, ring=0)
657     # limit it according to the byterate, splitting the message
658     # taking into consideration the actual message length
659     # and all the extra stuff
660     # TODO allow something to do for commands that produce too many messages
661     # TODO example: math 10**10000
662     left = @socket.bytes_per - type.length - where.to_s.length - 4
663     begin
664       if(left >= message.length)
665         sendq "#{type} #{where} :#{message}", chan, ring
666         log_sent(type, where, message)
667         return
668       end
669       line = message.slice!(0, left)
670       lastspace = line.rindex(/\s+/)
671       if(lastspace)
672         message = line.slice!(lastspace, line.length) + message
673         message.gsub!(/^\s+/, "")
674       end
675       sendq "#{type} #{where} :#{line}", chan, ring
676       log_sent(type, where, line)
677     end while(message.length > 0)
678   end
679
680   # queue an arbitraty message for the server
681   def sendq(message="", chan=nil, ring=0)
682     # temporary
683     @socket.queue(message, chan, ring)
684   end
685
686   # send a notice message to channel/nick +where+
687   def notice(where, message, mchan="", mring=-1)
688     if mchan == ""
689       chan = where
690     else
691       chan = mchan
692     end
693     if mring < 0
694       case where
695       when User
696         ring = 1
697       else
698         ring = 2
699       end
700     else
701       ring = mring
702     end
703     message.each_line { |line|
704       line.chomp!
705       next unless(line.length > 0)
706       sendmsg "NOTICE", where, line, chan, ring
707     }
708   end
709
710   # say something (PRIVMSG) to channel/nick +where+
711   def say(where, message, mchan="", mring=-1)
712     if mchan == ""
713       chan = where
714     else
715       chan = mchan
716     end
717     if mring < 0
718       case where
719       when User
720         ring = 1
721       else
722         ring = 2
723       end
724     else
725       ring = mring
726     end
727     message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
728       line.chomp!
729       next unless(line.length > 0)
730       unless quiet_on?(where)
731         sendmsg "PRIVMSG", where, line, chan, ring 
732       end
733     }
734   end
735
736   # perform a CTCP action with message +message+ to channel/nick +where+
737   def action(where, message, mchan="", mring=-1)
738     if mchan == ""
739       chan = where
740     else
741       chan = mchan
742     end
743     if mring < 0
744       case where
745       when Channel
746         ring = 2
747       else
748         ring = 1
749       end
750     else
751       ring = mring
752     end
753     sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
754     case where
755     when Channel
756       irclog "* #{myself} #{message}", where
757     else
758       irclog "* #{myself}[#{where}] #{message}", where
759     end
760   end
761
762   # quick way to say "okay" (or equivalent) to +where+
763   def okay(where)
764     say where, @lang.get("okay")
765   end
766
767   # log IRC-related message +message+ to a file determined by +where+.
768   # +where+ can be a channel name, or a nick for private message logging
769   def irclog(message, where="server")
770     message = message.chomp
771     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
772     where = where.to_s.gsub(/[:!?$*()\/\\<>|"']/, "_")
773     unless(@logs.has_key?(where))
774       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
775       @logs[where].sync = true
776     end
777     @logs[where].puts "[#{stamp}] #{message}"
778     #debug "[#{stamp}] <#{where}> #{message}"
779   end
780
781   # set topic of channel +where+ to +topic+
782   def topic(where, topic)
783     sendq "TOPIC #{where} :#{topic}", where, 2
784   end
785
786   # disconnect from the server and cleanup all plugins and modules
787   def shutdown(message = nil)
788     @quit_mutex.synchronize do
789       debug "Shutting down ..."
790       ## No we don't restore them ... let everything run through
791       # begin
792       #   trap("SIGINT", "DEFAULT")
793       #   trap("SIGTERM", "DEFAULT")
794       #   trap("SIGHUP", "DEFAULT")
795       # rescue => e
796       #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
797       # end
798       message = @lang.get("quit") if (message.nil? || message.empty?)
799       if @socket.connected?
800         debug "Clearing socket"
801         @socket.clearq
802         debug "Sending quit message"
803         @socket.emergency_puts "QUIT :#{message}"
804         debug "Flushing socket"
805         @socket.flush
806         debug "Shutting down socket"
807         @socket.shutdown
808       end
809       debug "Logging quits"
810       server.channels.each { |ch|
811         irclog "@ quit (#{message})", ch
812       }
813       debug "Saving"
814       save
815       debug "Cleaning up"
816       @save_mutex.synchronize do
817         @plugins.cleanup
818       end
819       # debug "Closing registries"
820       # @registry.close
821       debug "Cleaning up the db environment"
822       DBTree.cleanup_env
823       log "rbot quit (#{message})"
824     end
825   end
826
827   # message:: optional IRC quit message
828   # quit IRC, shutdown the bot
829   def quit(message=nil)
830     begin
831       shutdown(message)
832     ensure
833       exit 0
834     end
835   end
836
837   # totally shutdown and respawn the bot
838   def restart(message = false)
839     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
840     shutdown(msg)
841     sleep @config['server.reconnect_wait']
842     # now we re-exec
843     # Note, this fails on Windows
844     exec($0, *@argv)
845   end
846
847   # call the save method for all of the botmodules
848   def save
849     @save_mutex.synchronize do
850       @plugins.save
851       DBTree.cleanup_logs
852     end
853   end
854
855   # call the rescan method for all of the botmodules
856   def rescan
857     @save_mutex.synchronize do
858       @lang.rescan
859       @plugins.rescan
860     end
861   end
862
863   # channel:: channel to join
864   # key::     optional channel key if channel is +s
865   # join a channel
866   def join(channel, key=nil)
867     if(key)
868       sendq "JOIN #{channel} :#{key}", channel, 2
869     else
870       sendq "JOIN #{channel}", channel, 2
871     end
872   end
873
874   # part a channel
875   def part(channel, message="")
876     sendq "PART #{channel} :#{message}", channel, 2
877   end
878
879   # attempt to change bot's nick to +name+
880   def nickchg(name)
881       sendq "NICK #{name}"
882   end
883
884   # changing mode
885   def mode(channel, mode, target)
886       sendq "MODE #{channel} #{mode} #{target}", channel, 2
887   end
888
889   # kicking a user
890   def kick(channel, user, msg)
891       sendq "KICK #{channel} #{user} :#{msg}", channel, 2
892   end
893
894   # m::     message asking for help
895   # topic:: optional topic help is requested for
896   # respond to online help requests
897   def help(topic=nil)
898     topic = nil if topic == ""
899     case topic
900     when nil
901       helpstr = "help topics: "
902       helpstr += @plugins.helptopics
903       helpstr += " (help <topic> for more info)"
904     else
905       unless(helpstr = @plugins.help(topic))
906         helpstr = "no help for topic #{topic}"
907       end
908     end
909     return helpstr
910   end
911
912   # returns a string describing the current status of the bot (uptime etc)
913   def status
914     secs_up = Time.new - @startup_time
915     uptime = Utils.secs_to_string secs_up
916     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
917     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
918   end
919
920   # we'll ping the server every 30 seconds or so, and expect a response
921   # before the next one come around..
922   def start_server_pings
923     stop_server_pings
924     return unless @config['server.ping_timeout'] > 0
925     # we want to respond to a hung server within 30 secs or so
926     @ping_timer = @timer.add(30) {
927       @last_ping = Time.now
928       @socket.queue "PING :rbot"
929     }
930     @pong_timer = @timer.add(10) {
931       unless @last_ping.nil?
932         diff = Time.now - @last_ping
933         unless diff < @config['server.ping_timeout']
934           debug "no PONG from server for #{diff} seconds, reconnecting"
935           begin
936             @socket.shutdown
937           rescue
938             debug "couldn't shutdown connection (already shutdown?)"
939           end
940           @last_ping = nil
941           raise TimeoutError, "no PONG from server in #{diff} seconds"
942         end
943       end
944     }
945   end
946
947   def stop_server_pings
948     @last_ping = nil
949     # stop existing timers if running
950     unless @ping_timer.nil?
951       @timer.remove @ping_timer
952       @ping_timer = nil
953     end
954     unless @pong_timer.nil?
955       @timer.remove @pong_timer
956       @pong_timer = nil
957     end
958   end
959
960   private
961
962   def irclogprivmsg(m)
963     if(m.action?)
964       if(m.private?)
965         irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
966       else
967         irclog "* #{m.sourcenick} #{m.message}", m.target
968       end
969     else
970       if(m.public?)
971         irclog "<#{m.sourcenick}> #{m.message}", m.target
972       else
973         irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
974       end
975     end
976   end
977
978   # log a message. Internal use only.
979   def log_sent(type, where, message)
980     case type
981       when "NOTICE"
982         case where
983         when Channel
984           irclog "-=#{myself}=- #{message}", where
985         else
986              irclog "[-=#{where}=-] #{message}", where
987         end
988       when "PRIVMSG"
989         case where
990         when Channel
991           irclog "<#{myself}> #{message}", where
992         else
993           irclog "[msg(#{where})] #{message}", where
994         end
995     end
996   end
997
998   def irclogjoin(m)
999     if m.address?
1000       debug "joined channel #{m.channel}"
1001       irclog "@ Joined channel #{m.channel}", m.channel
1002     else
1003       irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1004     end
1005   end
1006
1007   def irclogpart(m)
1008     if(m.address?)
1009       debug "left channel #{m.channel}"
1010       irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1011     else
1012       irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1013     end
1014   end
1015
1016   def irclogkick(m)
1017     if(m.address?)
1018       debug "kicked from channel #{m.channel}"
1019       irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1020     else
1021       irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1022     end
1023   end
1024
1025   def irclogtopic(m)
1026     if m.source == myself
1027       irclog "@ I set topic \"#{m.topic}\"", m.channel
1028     else
1029       irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel
1030     end
1031   end
1032
1033 end
1034
1035 end