]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
Forgot a space
[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 BotConfigBooleanValue.new('server.ssl',
158       :default => false, :requires_restart => true, :wizard => true,
159       :desc => "Use SSL to connect to this server?")
160     BotConfig.register BotConfigStringValue.new('server.password',
161       :default => false, :requires_restart => true,
162       :desc => "Password for connecting to this server (if required)",
163       :wizard => true)
164     BotConfig.register BotConfigStringValue.new('server.bindhost',
165       :default => false, :requires_restart => true,
166       :desc => "Specific local host or IP for the bot to bind to (if required)",
167       :wizard => true)
168     BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
169       :default => 5, :validate => Proc.new{|v| v >= 0},
170       :desc => "Seconds to wait before attempting to reconnect, on disconnect")
171     BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
172       :default => 2.0, :validate => Proc.new{|v| v >= 0},
173       :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
174       :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
175     BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
176       :default => 4, :validate => Proc.new{|v| v >= 0},
177       :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
178       :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
179     BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
180       :default => 30, :validate => Proc.new{|v| v >= 0},
181       :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
182
183     BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
184       :desc => "IRC nickname the bot should attempt to use", :wizard => true,
185       :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
186     BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
187       :requires_restart => true,
188       :desc => "local user the bot should appear to be", :wizard => true)
189     BotConfig.register BotConfigArrayValue.new('irc.join_channels',
190       :default => [], :wizard => true,
191       :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'")
192     BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
193       :default => [], 
194       :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
195
196     BotConfig.register BotConfigIntegerValue.new('core.save_every',
197       :default => 60, :validate => Proc.new{|v| v >= 0},
198       # TODO change timer via on_change proc
199       :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
200
201     BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
202       :default => false, :requires_restart => true,
203       :desc => "Should the bot run as a daemon?")
204
205     BotConfig.register BotConfigStringValue.new('log.file',
206       :default => false, :requires_restart => true,
207       :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
208     BotConfig.register BotConfigIntegerValue.new('log.level',
209       :default => 1, :requires_restart => false,
210       :validate => Proc.new { |v| (0..5).include?(v) },
211       :on_change => Proc.new { |bot, v|
212         $logger.level = v
213       },
214       :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
215     BotConfig.register BotConfigIntegerValue.new('log.keep',
216       :default => 1, :requires_restart => true,
217       :validate => Proc.new { |v| v >= 0 },
218       :desc => "How many old console messages logfiles to keep")
219     BotConfig.register BotConfigIntegerValue.new('log.max_size',
220       :default => 10, :requires_restart => true,
221       :validate => Proc.new { |v| v > 0 },
222       :desc => "Maximum console messages logfile size (in megabytes)")
223
224     @argv = params[:argv]
225
226     unless FileTest.directory? Config::coredir
227       error "core directory '#{Config::coredir}' not found, did you setup.rb?"
228       exit 2
229     end
230
231     unless FileTest.directory? Config::datadir
232       error "data directory '#{Config::datadir}' not found, did you setup.rb?"
233       exit 2
234     end
235
236     unless botclass and not botclass.empty?
237       # We want to find a sensible default.
238       #  * On POSIX systems we prefer ~/.rbot for the effective uid of the process
239       #  * On Windows (at least the NT versions) we want to put our stuff in the
240       #    Application Data folder.
241       # We don't use any particular O/S detection magic, exploiting the fact that
242       # Etc.getpwuid is nil on Windows
243       if Etc.getpwuid(Process::Sys.geteuid)
244         botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
245       else
246         if ENV.has_key?('APPDATA')
247           botclass = ENV['APPDATA'].dup
248           botclass.gsub!("\\","/")
249         end
250       end
251       botclass += "/.rbot"
252     end
253     botclass = File.expand_path(botclass)
254     @botclass = botclass.gsub(/\/$/, "")
255
256     unless FileTest.directory? botclass
257       log "no #{botclass} directory found, creating from templates.."
258       if FileTest.exist? botclass
259         error "file #{botclass} exists but isn't a directory"
260         exit 2
261       end
262       FileUtils.cp_r Config::datadir+'/templates', botclass
263     end
264
265     Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
266     Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
267     Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
268     Utils.set_safe_save_dir("#{botclass}/safe_save")
269
270     # Time at which the last PING was sent
271     @last_ping = nil
272     # Time at which the last line was RECV'd from the server
273     @last_rec = nil
274
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'], :ssl => @config['server.ssl'])
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       ignored = false
419       @config['irc.ignore_users'].each { |mask|
420         if m.source.matches?(server.new_netmask(mask))
421           ignored = true
422           break
423         end
424       }
425
426       unless ignored
427         irclogprivmsg(m)
428
429         @plugins.delegate "listen", m
430         @plugins.privmsg(m) if m.address?
431       end
432     }
433     @client[:notice] = proc { |data|
434       message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
435       # pass it off to plugins that want to hear everything
436       @plugins.delegate "listen", message
437     }
438     @client[:motd] = proc { |data|
439       data[:motd].each_line { |line|
440         irclog "MOTD: #{line}", "server"
441       }
442     }
443     @client[:nicktaken] = proc { |data|
444       nickchg "#{data[:nick]}_"
445       @plugins.delegate "nicktaken", data[:nick]
446     }
447     @client[:badnick] = proc {|data|
448       warning "bad nick (#{data[:nick]})"
449     }
450     @client[:ping] = proc {|data|
451       sendq "PONG #{data[:pingid]}"
452     }
453     @client[:pong] = proc {|data|
454       @last_ping = nil
455     }
456     @client[:nick] = proc {|data|
457       source = data[:source]
458       old = data[:oldnick]
459       new = data[:newnick]
460       m = NickMessage.new(self, server, source, old, new)
461       if source == myself
462         debug "my nick is now #{new}"
463       end
464       data[:is_on].each { |ch|
465         irclog "@ #{old} is now known as #{new}", ch
466       }
467       @plugins.delegate("listen", m)
468       @plugins.delegate("nick", m)
469     }
470     @client[:quit] = proc {|data|
471       source = data[:source]
472       message = data[:message]
473       m = QuitMessage.new(self, server, source, source, message)
474       data[:was_on].each { |ch|
475         irclog "@ Quit: #{source}: #{message}", ch
476       }
477       @plugins.delegate("listen", m)
478       @plugins.delegate("quit", m)
479     }
480     @client[:mode] = proc {|data|
481       irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
482     }
483     @client[:join] = proc {|data|
484       m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
485       irclogjoin(m)
486
487       @plugins.delegate("listen", m)
488       @plugins.delegate("join", m)
489     }
490     @client[:part] = proc {|data|
491       m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
492       irclogpart(m)
493
494       @plugins.delegate("listen", m)
495       @plugins.delegate("part", m)
496     }
497     @client[:kick] = proc {|data|
498       m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
499       irclogkick(m)
500
501       @plugins.delegate("listen", m)
502       @plugins.delegate("kick", m)
503     }
504     @client[:invite] = proc {|data|
505       if data[:target] == myself
506         join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
507       end
508     }
509     @client[:changetopic] = proc {|data|
510       m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
511       irclogtopic(m)
512
513       @plugins.delegate("listen", m)
514       @plugins.delegate("topic", m)
515     }
516     @client[:topic] = proc { |data|
517       irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
518     }
519     @client[:topicinfo] = proc { |data|
520       channel = data[:channel]
521       topic = channel.topic
522       irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
523       m = TopicMessage.new(self, server, data[:source], channel, topic)
524
525       @plugins.delegate("listen", m)
526       @plugins.delegate("topic", m)
527     }
528     @client[:names] = proc { |data|
529       @plugins.delegate "names", data[:channel], data[:users]
530     }
531     @client[:unknown] = proc { |data|
532       #debug "UNKNOWN: #{data[:serverstring]}"
533       irclog data[:serverstring], ".unknown"
534     }
535   end
536
537   # checks if we should be quiet on a channel
538   def quiet_on?(channel)
539     return false unless @quiet
540     return true if @quiet.empty?
541     return @quiet.include?(channel.to_s)
542   end
543
544   def set_quiet(channel=nil)
545     if channel
546       @quiet << channel.to_s unless @quiet.include?(channel.to_s)
547     else
548       @quiet = []
549     end
550   end
551
552   def reset_quiet(channel=nil)
553     if channel
554       @quiet.delete_if { |x| x == channel.to_s }
555     else
556       @quiet = nil
557     end
558   end
559
560   # things to do when we receive a signal
561   def got_sig(sig)
562     debug "received #{sig}, queueing quit"
563     $interrupted += 1
564     quit unless @quit_mutex.locked?
565     debug "interrupted #{$interrupted} times"
566     if $interrupted >= 3
567       debug "drastic!"
568       log_session_end
569       exit 2
570     end
571   end
572
573   # connect the bot to IRC
574   def connect
575     begin
576       trap("SIGINT") { got_sig("SIGINT") }
577       trap("SIGTERM") { got_sig("SIGTERM") }
578       trap("SIGHUP") { got_sig("SIGHUP") }
579     rescue ArgumentError => e
580       debug "failed to trap signals (#{e.inspect}): running on Windows?"
581     rescue => e
582       debug "failed to trap signals: #{e.inspect}"
583     end
584     begin
585       quit if $interrupted > 0
586       @socket.connect
587     rescue => e
588       raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
589     end
590     quit if $interrupted > 0
591     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
592     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
593     quit if $interrupted > 0
594   end
595
596   # begin event handling loop
597   def mainloop
598     while true
599       begin
600         quit if $interrupted > 0
601         connect
602         @timer.start
603
604         while @socket.connected?
605           quit if $interrupted > 0
606
607           # Wait for messages and process them as they arrive. If nothing is
608           # received, we call the ping_server() method that will PING the
609           # server if appropriate, or raise a TimeoutError if no PONG has been
610           # received in the user-chosen timeout since the last PING sent.
611           if @socket.select(1)
612             break unless reply = @socket.gets
613             @last_rec = Time.now
614             @client.process reply
615           else
616             ping_server
617           end
618         end
619
620       # I despair of this. Some of my users get "connection reset by peer"
621       # exceptions that ARENT SocketError's. How am I supposed to handle
622       # that?
623       rescue SystemExit
624         log_session_end
625         exit 0
626       rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
627         error "network exception: #{e.class}: #{e}"
628         debug e.backtrace.join("\n")
629       rescue BDB::Fatal => e
630         fatal "fatal bdb error: #{e.class}: #{e}"
631         fatal e.backtrace.join("\n")
632         DBTree.stats
633         # Why restart? DB problems are serious stuff ...
634         # restart("Oops, we seem to have registry problems ...")
635         log_session_end
636         exit 2
637       rescue Exception => e
638         error "non-net exception: #{e.class}: #{e}"
639         error e.backtrace.join("\n")
640       rescue => e
641         fatal "unexpected exception: #{e.class}: #{e}"
642         fatal e.backtrace.join("\n")
643         log_session_end
644         exit 2
645       end
646
647       stop_server_pings
648       server.clear
649       if @socket.connected?
650         @socket.clearq
651         @socket.shutdown
652       end
653
654       log "disconnected"
655
656       quit if $interrupted > 0
657
658       log "waiting to reconnect"
659       sleep @config['server.reconnect_wait']
660     end
661   end
662
663   # type:: message type
664   # where:: message target
665   # message:: message text
666   # send message +message+ of type +type+ to target +where+
667   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
668   # relevant say() or notice() methods. This one should be used for IRCd
669   # extensions you want to use in modules.
670   def sendmsg(type, where, message, chan=nil, ring=0)
671     # Split the message so that each line sent is not longher than 400 bytes
672     # TODO allow something to do for commands that produce too many messages
673     # TODO example: math 10**10000
674     # TODO try to use the maximum line length allowed by the server, if there is
675     #      a way to know what it is
676     left = 400 - type.length - where.to_s.length - 3
677     begin
678       if(left >= message.length)
679         sendq "#{type} #{where} :#{message}", chan, ring
680         log_sent(type, where, message)
681         return
682       end
683       line = message.slice!(0, left)
684       lastspace = line.rindex(/\s+/)
685       if(lastspace)
686         message = line.slice!(lastspace, line.length) + message
687         message.gsub!(/^\s+/, "")
688       end
689       sendq "#{type} #{where} :#{line}", chan, ring
690       log_sent(type, where, line)
691     end while(message.length > 0)
692   end
693
694   # queue an arbitraty message for the server
695   def sendq(message="", chan=nil, ring=0)
696     # temporary
697     @socket.queue(message, chan, ring)
698   end
699
700   # send a notice message to channel/nick +where+
701   def notice(where, message, mchan="", mring=-1)
702     if mchan == ""
703       chan = where
704     else
705       chan = mchan
706     end
707     if mring < 0
708       case where
709       when User
710         ring = 1
711       else
712         ring = 2
713       end
714     else
715       ring = mring
716     end
717     message.each_line { |line|
718       line.chomp!
719       next unless(line.length > 0)
720       sendmsg "NOTICE", where, line, chan, ring
721     }
722   end
723
724   # say something (PRIVMSG) to channel/nick +where+
725   def say(where, message, mchan="", mring=-1)
726     if mchan == ""
727       chan = where
728     else
729       chan = mchan
730     end
731     if mring < 0
732       case where
733       when User
734         ring = 1
735       else
736         ring = 2
737       end
738     else
739       ring = mring
740     end
741     message.to_s.gsub(/[\r\n]+/, "\n").each_line { |line|
742       line.chomp!
743       next unless(line.length > 0)
744       unless quiet_on?(where)
745         sendmsg "PRIVMSG", where, line, chan, ring 
746       end
747     }
748   end
749
750   # perform a CTCP action with message +message+ to channel/nick +where+
751   def action(where, message, mchan="", mring=-1)
752     if mchan == ""
753       chan = where
754     else
755       chan = mchan
756     end
757     if mring < 0
758       case where
759       when Channel
760         ring = 2
761       else
762         ring = 1
763       end
764     else
765       ring = mring
766     end
767     sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
768     case where
769     when Channel
770       irclog "* #{myself} #{message}", where
771     else
772       irclog "* #{myself}[#{where}] #{message}", where
773     end
774   end
775
776   # quick way to say "okay" (or equivalent) to +where+
777   def okay(where)
778     say where, @lang.get("okay")
779   end
780
781   # log IRC-related message +message+ to a file determined by +where+.
782   # +where+ can be a channel name, or a nick for private message logging
783   def irclog(message, where="server")
784     message = message.chomp
785     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
786     where = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
787     unless(@logs.has_key?(where))
788       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
789       @logs[where].sync = true
790     end
791     @logs[where].puts "[#{stamp}] #{message}"
792     #debug "[#{stamp}] <#{where}> #{message}"
793   end
794
795   # set topic of channel +where+ to +topic+
796   def topic(where, topic)
797     sendq "TOPIC #{where} :#{topic}", where, 2
798   end
799
800   # disconnect from the server and cleanup all plugins and modules
801   def shutdown(message = nil)
802     @quit_mutex.synchronize do
803       debug "Shutting down ..."
804       ## No we don't restore them ... let everything run through
805       # begin
806       #   trap("SIGINT", "DEFAULT")
807       #   trap("SIGTERM", "DEFAULT")
808       #   trap("SIGHUP", "DEFAULT")
809       # rescue => e
810       #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
811       # end
812       message = @lang.get("quit") if (message.nil? || message.empty?)
813       if @socket.connected?
814         debug "Clearing socket"
815         @socket.clearq
816         debug "Sending quit message"
817         @socket.emergency_puts "QUIT :#{message}"
818         debug "Flushing socket"
819         @socket.flush
820         debug "Shutting down socket"
821         @socket.shutdown
822       end
823       debug "Logging quits"
824       server.channels.each { |ch|
825         irclog "@ quit (#{message})", ch
826       }
827       debug "Saving"
828       save
829       debug "Cleaning up"
830       @save_mutex.synchronize do
831         @plugins.cleanup
832       end
833       # debug "Closing registries"
834       # @registry.close
835       debug "Cleaning up the db environment"
836       DBTree.cleanup_env
837       log "rbot quit (#{message})"
838     end
839   end
840
841   # message:: optional IRC quit message
842   # quit IRC, shutdown the bot
843   def quit(message=nil)
844     begin
845       shutdown(message)
846     ensure
847       exit 0
848     end
849   end
850
851   # totally shutdown and respawn the bot
852   def restart(message = false)
853     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
854     shutdown(msg)
855     sleep @config['server.reconnect_wait']
856     # now we re-exec
857     # Note, this fails on Windows
858     exec($0, *@argv)
859   end
860
861   # call the save method for all of the botmodules
862   def save
863     @save_mutex.synchronize do
864       @plugins.save
865       DBTree.cleanup_logs
866     end
867   end
868
869   # call the rescan method for all of the botmodules
870   def rescan
871     @save_mutex.synchronize do
872       @lang.rescan
873       @plugins.rescan
874     end
875   end
876
877   # channel:: channel to join
878   # key::     optional channel key if channel is +s
879   # join a channel
880   def join(channel, key=nil)
881     if(key)
882       sendq "JOIN #{channel} :#{key}", channel, 2
883     else
884       sendq "JOIN #{channel}", channel, 2
885     end
886   end
887
888   # part a channel
889   def part(channel, message="")
890     sendq "PART #{channel} :#{message}", channel, 2
891   end
892
893   # attempt to change bot's nick to +name+
894   def nickchg(name)
895       sendq "NICK #{name}"
896   end
897
898   # changing mode
899   def mode(channel, mode, target)
900       sendq "MODE #{channel} #{mode} #{target}", channel, 2
901   end
902
903   # kicking a user
904   def kick(channel, user, msg)
905       sendq "KICK #{channel} #{user} :#{msg}", channel, 2
906   end
907
908   # m::     message asking for help
909   # topic:: optional topic help is requested for
910   # respond to online help requests
911   def help(topic=nil)
912     topic = nil if topic == ""
913     case topic
914     when nil
915       helpstr = "help topics: "
916       helpstr += @plugins.helptopics
917       helpstr += " (help <topic> for more info)"
918     else
919       unless(helpstr = @plugins.help(topic))
920         helpstr = "no help for topic #{topic}"
921       end
922     end
923     return helpstr
924   end
925
926   # returns a string describing the current status of the bot (uptime etc)
927   def status
928     secs_up = Time.new - @startup_time
929     uptime = Utils.secs_to_string secs_up
930     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
931     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
932   end
933
934   # We want to respond to a hung server in a timely manner. If nothing was received
935   # in the user-selected timeout and we haven't PINGed the server yet, we PING
936   # the server. If the PONG is not received within the user-defined timeout, we
937   # assume we're in ping timeout and act accordingly.
938   def ping_server
939     act_timeout = @config['server.ping_timeout']
940     return if act_timeout <= 0
941     now = Time.now
942     if @last_rec && now > @last_rec + act_timeout
943       if @last_ping.nil?
944         # No previous PING pending, send a new one
945         sendq "PING :rbot"
946         @last_ping = Time.now
947       else
948         diff = now - @last_ping
949         if diff > act_timeout
950           debug "no PONG from server in #{diff} seconds, reconnecting"
951           # the actual reconnect is handled in the main loop:
952           raise TimeoutError, "no PONG from server in #{diff} seconds"
953         end
954       end
955     end
956   end
957
958   def stop_server_pings
959     # cancel previous PINGs and reset time of last RECV
960     @last_ping = nil
961     @last_rec = nil
962   end
963
964   private
965
966   def irclogprivmsg(m)
967     if(m.action?)
968       if(m.private?)
969         irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
970       else
971         irclog "* #{m.sourcenick} #{m.message}", m.target
972       end
973     else
974       if(m.public?)
975         irclog "<#{m.sourcenick}> #{m.message}", m.target
976       else
977         irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
978       end
979     end
980   end
981
982   # log a message. Internal use only.
983   def log_sent(type, where, message)
984     case type
985       when "NOTICE"
986         case where
987         when Channel
988           irclog "-=#{myself}=- #{message}", where
989         else
990              irclog "[-=#{where}=-] #{message}", where
991         end
992       when "PRIVMSG"
993         case where
994         when Channel
995           irclog "<#{myself}> #{message}", where
996         else
997           irclog "[msg(#{where})] #{message}", where
998         end
999     end
1000   end
1001
1002   def irclogjoin(m)
1003     if m.address?
1004       debug "joined channel #{m.channel}"
1005       irclog "@ Joined channel #{m.channel}", m.channel
1006     else
1007       irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1008     end
1009   end
1010
1011   def irclogpart(m)
1012     if(m.address?)
1013       debug "left channel #{m.channel}"
1014       irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1015     else
1016       irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1017     end
1018   end
1019
1020   def irclogkick(m)
1021     if(m.address?)
1022       debug "kicked from channel #{m.channel}"
1023       irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1024     else
1025       irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1026     end
1027   end
1028
1029   def irclogtopic(m)
1030     if m.source == myself
1031       irclog "@ I set topic \"#{m.topic}\"", m.channel
1032     else
1033       irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel
1034     end
1035   end
1036
1037 end
1038
1039 end