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