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