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