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