]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
New unreplied() method for plugins that want to handle PRIVMSGs unreplied by any...
[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     myself.nick = @config['irc.nick']
442
443     # Channels where we are quiet
444     # Array of channels names where the bot should be quiet
445     # '*' means all channels
446     #
447     @quiet = []
448
449     @client[:welcome] = proc {|data|
450       irclog "joined server #{@client.server} as #{myself}", "server"
451
452       @plugins.delegate("connect")
453
454       @config['irc.join_channels'].each { |c|
455         debug "autojoining channel #{c}"
456         if(c =~ /^(\S+)\s+(\S+)$/i)
457           join $1, $2
458         else
459           join c if(c)
460         end
461       }
462     }
463
464     # TODO the next two @client should go into rfc2812.rb, probably
465     # Since capabs are two-steps processes, server.supports[:capab]
466     # should be a three-state: nil, [], [....]
467     asked_for = { :"identify-msg" => false }
468     @client[:isupport] = proc { |data|
469       if server.supports[:capab] and !asked_for[:"identify-msg"]
470         sendq "CAPAB IDENTIFY-MSG"
471         asked_for[:"identify-msg"] = true
472       end
473     }
474     @client[:datastr] = proc { |data|
475       if data[:text] == "IDENTIFY-MSG"
476         server.capabilities[:"identify-msg"] = true
477       else
478         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
479       end
480     }
481
482     @client[:privmsg] = proc { |data|
483       m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
484       # debug "Message source is #{data[:source].inspect}"
485       # debug "Message target is #{data[:target].inspect}"
486       # debug "Bot is #{myself.inspect}"
487
488       ignored = false
489       @config['irc.ignore_users'].each { |mask|
490         if m.source.matches?(server.new_netmask(mask))
491           ignored = true
492           break
493         end
494       }
495
496       irclogprivmsg(m)
497
498       unless ignored
499         @plugins.delegate "listen", m
500         @plugins.privmsg(m) if m.address?
501         if not m.replied
502           @plugins.delegate "unreplied", m
503         end
504       end
505     }
506     @client[:notice] = proc { |data|
507       message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
508       # pass it off to plugins that want to hear everything
509       @plugins.delegate "listen", message
510     }
511     @client[:motd] = proc { |data|
512       data[:motd].each_line { |line|
513         irclog "MOTD: #{line}", "server"
514       }
515     }
516     @client[:nicktaken] = proc { |data|
517       nickchg "#{data[:nick]}_"
518       @plugins.delegate "nicktaken", data[:nick]
519     }
520     @client[:badnick] = proc {|data|
521       warning "bad nick (#{data[:nick]})"
522     }
523     @client[:ping] = proc {|data|
524       sendq "PONG #{data[:pingid]}"
525     }
526     @client[:pong] = proc {|data|
527       @last_ping = nil
528     }
529     @client[:nick] = proc {|data|
530       source = data[:source]
531       old = data[:oldnick]
532       new = data[:newnick]
533       m = NickMessage.new(self, server, source, old, new)
534       if source == myself
535         debug "my nick is now #{new}"
536       end
537       data[:is_on].each { |ch|
538         irclog "@ #{old} is now known as #{new}", ch
539       }
540       @plugins.delegate("listen", m)
541       @plugins.delegate("nick", m)
542     }
543     @client[:quit] = proc {|data|
544       source = data[:source]
545       message = data[:message]
546       m = QuitMessage.new(self, server, source, source, message)
547       data[:was_on].each { |ch|
548         irclog "@ Quit: #{source}: #{message}", ch
549       }
550       @plugins.delegate("listen", m)
551       @plugins.delegate("quit", m)
552     }
553     @client[:mode] = proc {|data|
554       irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
555     }
556     @client[:join] = proc {|data|
557       m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
558       irclogjoin(m)
559
560       @plugins.delegate("listen", m)
561       @plugins.delegate("join", m)
562     }
563     @client[:part] = proc {|data|
564       m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
565       irclogpart(m)
566
567       @plugins.delegate("listen", m)
568       @plugins.delegate("part", m)
569     }
570     @client[:kick] = proc {|data|
571       m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
572       irclogkick(m)
573
574       @plugins.delegate("listen", m)
575       @plugins.delegate("kick", m)
576     }
577     @client[:invite] = proc {|data|
578       if data[:target] == myself
579         join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
580       end
581     }
582     @client[:changetopic] = proc {|data|
583       m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
584       irclogtopic(m)
585
586       @plugins.delegate("listen", m)
587       @plugins.delegate("topic", m)
588     }
589     @client[:topic] = proc { |data|
590       irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
591     }
592     @client[:topicinfo] = proc { |data|
593       channel = data[:channel]
594       topic = channel.topic
595       irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
596       m = TopicMessage.new(self, server, data[:source], channel, topic)
597
598       @plugins.delegate("listen", m)
599       @plugins.delegate("topic", m)
600     }
601     @client[:names] = proc { |data|
602       @plugins.delegate "names", data[:channel], data[:users]
603     }
604     @client[:unknown] = proc { |data|
605       #debug "UNKNOWN: #{data[:serverstring]}"
606       irclog data[:serverstring], ".unknown"
607     }
608
609     set_default_send_options :newlines => @config['send.newlines'].to_sym,
610       :join_with => @config['send.join_with'].dup,
611       :max_lines => @config['send.max_lines'],
612       :overlong => @config['send.overlong'].to_sym,
613       :split_at => Regexp.new(@config['send.split_at']),
614       :purge_split => @config['send.purge_split'],
615       :truncate_text => @config['send.truncate_text'].dup
616   end
617
618   def set_default_send_options(opts={})
619     # Default send options for NOTICE and PRIVMSG
620     unless defined? @default_send_options
621       @default_send_options = {
622         :queue_channel => nil,      # use default queue channel
623         :queue_ring => nil,         # use default queue ring
624         :newlines => :split,        # or :join
625         :join_with => ' ',          # by default, use a single space
626         :max_lines => 0,          # maximum number of lines to send with a single command
627         :overlong => :split,        # or :truncate
628         # TODO an array of splitpoints would be preferrable for this option:
629         :split_at => /\s+/,         # by default, split overlong lines at whitespace
630         :purge_split => true,       # should the split string be removed?
631         :truncate_text => "#{Reverse}...#{Reverse}"  # text to be appened when truncating
632       }
633     end
634     @default_send_options.update opts unless opts.empty?
635     end
636
637   # checks if we should be quiet on a channel
638   def quiet_on?(channel)
639     return @quiet.include?('*') || @quiet.include?(channel.downcase)
640   end
641
642   def set_quiet(channel)
643     if channel
644       ch = channel.downcase.dup
645       @quiet << ch unless @quiet.include?(ch)
646     else
647       @quiet.clear
648       @quiet << '*'
649     end
650   end
651
652   def reset_quiet(channel)
653     if channel
654       @quiet.delete channel.downcase
655     else
656       @quiet.clear
657     end
658   end
659
660   # things to do when we receive a signal
661   def got_sig(sig)
662     debug "received #{sig}, queueing quit"
663     $interrupted += 1
664     quit unless @quit_mutex.locked?
665     debug "interrupted #{$interrupted} times"
666     if $interrupted >= 3
667       debug "drastic!"
668       log_session_end
669       exit 2
670     end
671   end
672
673   # connect the bot to IRC
674   def connect
675     begin
676       trap("SIGINT") { got_sig("SIGINT") }
677       trap("SIGTERM") { got_sig("SIGTERM") }
678       trap("SIGHUP") { got_sig("SIGHUP") }
679     rescue ArgumentError => e
680       debug "failed to trap signals (#{e.inspect}): running on Windows?"
681     rescue => e
682       debug "failed to trap signals: #{e.inspect}"
683     end
684     begin
685       quit if $interrupted > 0
686       @socket.connect
687     rescue => e
688       raise e.class, "failed to connect to IRC server at #{@config['server.name']} #{@config['server.port']}: " + e
689     end
690     quit if $interrupted > 0
691     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
692     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@config['server.name']} :Ruby bot. (c) Tom Gilbert"
693     quit if $interrupted > 0
694   end
695
696   # begin event handling loop
697   def mainloop
698     while true
699       begin
700         quit if $interrupted > 0
701         connect
702         @timer.start
703
704         while @socket.connected?
705           quit if $interrupted > 0
706
707           # Wait for messages and process them as they arrive. If nothing is
708           # received, we call the ping_server() method that will PING the
709           # server if appropriate, or raise a TimeoutError if no PONG has been
710           # received in the user-chosen timeout since the last PING sent.
711           if @socket.select(1)
712             break unless reply = @socket.gets
713             @last_rec = Time.now
714             @client.process reply
715           else
716             ping_server
717           end
718         end
719
720       # I despair of this. Some of my users get "connection reset by peer"
721       # exceptions that ARENT SocketError's. How am I supposed to handle
722       # that?
723       rescue SystemExit
724         log_session_end
725         exit 0
726       rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
727         error "network exception: #{e.class}: #{e}"
728         debug e.backtrace.join("\n")
729       rescue BDB::Fatal => e
730         fatal "fatal bdb error: #{e.class}: #{e}"
731         fatal e.backtrace.join("\n")
732         DBTree.stats
733         # Why restart? DB problems are serious stuff ...
734         # restart("Oops, we seem to have registry problems ...")
735         log_session_end
736         exit 2
737       rescue Exception => e
738         error "non-net exception: #{e.class}: #{e}"
739         error e.backtrace.join("\n")
740       rescue => e
741         fatal "unexpected exception: #{e.class}: #{e}"
742         fatal e.backtrace.join("\n")
743         log_session_end
744         exit 2
745       end
746
747       stop_server_pings
748       server.clear
749       if @socket.connected?
750         @socket.clearq
751         @socket.shutdown
752       end
753
754       log "disconnected"
755
756       quit if $interrupted > 0
757
758       log "waiting to reconnect"
759       sleep @config['server.reconnect_wait']
760     end
761   end
762
763   # type:: message type
764   # where:: message target
765   # message:: message text
766   # send message +message+ of type +type+ to target +where+
767   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
768   # relevant say() or notice() methods. This one should be used for IRCd
769   # extensions you want to use in modules.
770   def sendmsg(type, where, original_message, options={})
771     opts = @default_send_options.merge(options)
772
773     # For starters, set up appropriate queue channels and rings
774     mchan = opts[:queue_channel]
775     mring = opts[:queue_ring]
776     if mchan
777       chan = mchan
778     else
779       chan = where
780     end
781     if mring
782       ring = mring
783     else
784       case where
785       when User
786         ring = 1
787       else
788         ring = 2
789       end
790     end
791
792     message = original_message.to_s.gsub(/[\r\n]+/, "\n")
793     case opts[:newlines]
794     when :join
795       lines = [message.gsub("\n", opts[:join_with])]
796     when :split
797       lines = Array.new
798       message.each_line { |line|
799         line.chomp!
800         next unless(line.size > 0)
801         lines << line
802       }
803     else
804       raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
805     end
806
807     # The IRC protocol requires that each raw message must be not longer
808     # than 512 characters. From this length with have to subtract the EOL
809     # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
810     # that will be prepended by the server to all of our messages.
811
812     # The maximum raw message length we can send is therefore 512 - 2 - 2
813     # minus the length of our hostmask.
814
815     max_len = 508 - myself.fullform.size
816
817     # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
818     # will have a + or - prepended
819     if server.capabilities[:"identify-msg"]
820       max_len -= 1
821     end
822
823     # When splitting the message, we'll be prefixing the following string:
824     # (e.g. "PRIVMSG #rbot :")
825     fixed = "#{type} #{where} :"
826
827     # And this is what's left
828     left = max_len - fixed.size
829
830     case opts[:overlong]
831     when :split
832       truncate = false
833       split_at = opts[:split_at]
834     when :truncate
835       truncate = opts[:truncate_text]
836       truncate = @default_send_options[:truncate_text] if truncate.size > left
837       truncate = "" if truncate.size > left
838     else
839       raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
840     end
841
842     # Counter to check the number of lines sent by this command
843     cmd_lines = 0
844     max_lines = opts[:max_lines]
845     maxed = false
846     line = String.new
847     lines.each { |msg|
848       begin
849         if max_lines > 0 and cmd_lines == max_lines - 1
850           truncate = opts[:truncate_text]
851           truncate = @default_send_options[:truncate_text] if truncate.size > left
852           truncate = "" if truncate.size > left
853           maxed = true
854         end
855         if(left >= msg.size) and not maxed
856           sendq "#{fixed}#{msg}", chan, ring
857           log_sent(type, where, msg)
858           cmd_lines += 1
859           break
860         end
861         if truncate
862           line.replace msg.slice(0, left-truncate.size)
863           # line.sub!(/\s+\S*$/, truncate)
864           line << truncate
865           raise "PROGRAMMER ERROR! #{line.inspect} of size #{line.size} > #{left}" if line.size > left
866           sendq "#{fixed}#{line}", chan, ring
867           log_sent(type, where, line)
868           return
869         end
870         line.replace msg.slice!(0, left)
871         lastspace = line.rindex(opts[:split_at])
872         if(lastspace)
873           msg.replace line.slice!(lastspace, line.size) + msg
874           msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
875         end
876         sendq "#{fixed}#{line}", chan, ring
877         log_sent(type, where, line)
878         cmd_lines += 1
879       end while(msg.size > 0)
880     }
881   end
882
883   # queue an arbitraty message for the server
884   def sendq(message="", chan=nil, ring=0)
885     # temporary
886     @socket.queue(message, chan, ring)
887   end
888
889   # send a notice message to channel/nick +where+
890   def notice(where, message, options={})
891     return if where.kind_of?(Channel) and quiet_on?(where)
892     sendmsg "NOTICE", where, message, options
893   end
894
895   # say something (PRIVMSG) to channel/nick +where+
896   def say(where, message, options={})
897     return if where.kind_of?(Channel) and quiet_on?(where)
898     sendmsg "PRIVMSG", where, message, options
899   end
900
901   # perform a CTCP action with message +message+ to channel/nick +where+
902   def action(where, message, options={})
903     return if where.kind_of?(Channel) and quiet_on?(where)
904     mchan = options.fetch(:queue_channel, nil)
905     mring = options.fetch(:queue_ring, nil)
906     if mchan
907       chan = mchan
908     else
909       chan = where
910     end
911     if mring
912       ring = mring
913     else
914       case where
915       when User
916         ring = 1
917       else
918         ring = 2
919       end
920     end
921     # FIXME doesn't check message length. Can we make this exploit sendmsg?
922     sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
923     case where
924     when Channel
925       irclog "* #{myself} #{message}", where
926     else
927       irclog "* #{myself}[#{where}] #{message}", where
928     end
929   end
930
931   # quick way to say "okay" (or equivalent) to +where+
932   def okay(where)
933     say where, @lang.get("okay")
934   end
935
936   # log IRC-related message +message+ to a file determined by +where+.
937   # +where+ can be a channel name, or a nick for private message logging
938   def irclog(message, where="server")
939     message = message.chomp
940     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
941     where = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
942     unless(@logs.has_key?(where))
943       @logs[where] = File.new("#{@botclass}/logs/#{where}", "a")
944       @logs[where].sync = true
945     end
946     @logs[where].puts "[#{stamp}] #{message}"
947     #debug "[#{stamp}] <#{where}> #{message}"
948   end
949
950   # set topic of channel +where+ to +topic+
951   def topic(where, topic)
952     sendq "TOPIC #{where} :#{topic}", where, 2
953   end
954
955   # disconnect from the server and cleanup all plugins and modules
956   def shutdown(message = nil)
957     @quit_mutex.synchronize do
958       debug "Shutting down ..."
959       ## No we don't restore them ... let everything run through
960       # begin
961       #   trap("SIGINT", "DEFAULT")
962       #   trap("SIGTERM", "DEFAULT")
963       #   trap("SIGHUP", "DEFAULT")
964       # rescue => e
965       #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
966       # end
967       message = @lang.get("quit") if (message.nil? || message.empty?)
968       if @socket.connected?
969         debug "Clearing socket"
970         @socket.clearq
971         debug "Sending quit message"
972         @socket.emergency_puts "QUIT :#{message}"
973         debug "Flushing socket"
974         @socket.flush
975         debug "Shutting down socket"
976         @socket.shutdown
977       end
978       debug "Logging quits"
979       server.channels.each { |ch|
980         irclog "@ quit (#{message})", ch
981       }
982       debug "Saving"
983       save
984       debug "Cleaning up"
985       @save_mutex.synchronize do
986         @plugins.cleanup
987       end
988       # debug "Closing registries"
989       # @registry.close
990       debug "Cleaning up the db environment"
991       DBTree.cleanup_env
992       log "rbot quit (#{message})"
993     end
994   end
995
996   # message:: optional IRC quit message
997   # quit IRC, shutdown the bot
998   def quit(message=nil)
999     begin
1000       shutdown(message)
1001     ensure
1002       exit 0
1003     end
1004   end
1005
1006   # totally shutdown and respawn the bot
1007   def restart(message = false)
1008     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
1009     shutdown(msg)
1010     sleep @config['server.reconnect_wait']
1011     # now we re-exec
1012     # Note, this fails on Windows
1013     exec($0, *@argv)
1014   end
1015
1016   # call the save method for all of the botmodules
1017   def save
1018     @save_mutex.synchronize do
1019       @plugins.save
1020       DBTree.cleanup_logs
1021     end
1022   end
1023
1024   # call the rescan method for all of the botmodules
1025   def rescan
1026     @save_mutex.synchronize do
1027       @lang.rescan
1028       @plugins.rescan
1029     end
1030   end
1031
1032   # channel:: channel to join
1033   # key::     optional channel key if channel is +s
1034   # join a channel
1035   def join(channel, key=nil)
1036     if(key)
1037       sendq "JOIN #{channel} :#{key}", channel, 2
1038     else
1039       sendq "JOIN #{channel}", channel, 2
1040     end
1041   end
1042
1043   # part a channel
1044   def part(channel, message="")
1045     sendq "PART #{channel} :#{message}", channel, 2
1046   end
1047
1048   # attempt to change bot's nick to +name+
1049   def nickchg(name)
1050     sendq "NICK #{name}"
1051   end
1052
1053   # changing mode
1054   def mode(channel, mode, target)
1055     sendq "MODE #{channel} #{mode} #{target}", channel, 2
1056   end
1057
1058   # kicking a user
1059   def kick(channel, user, msg)
1060     sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1061   end
1062
1063   # m::     message asking for help
1064   # topic:: optional topic help is requested for
1065   # respond to online help requests
1066   def help(topic=nil)
1067     topic = nil if topic == ""
1068     case topic
1069     when nil
1070       helpstr = "help topics: "
1071       helpstr += @plugins.helptopics
1072       helpstr += " (help <topic> for more info)"
1073     else
1074       unless(helpstr = @plugins.help(topic))
1075         helpstr = "no help for topic #{topic}"
1076       end
1077     end
1078     return helpstr
1079   end
1080
1081   # returns a string describing the current status of the bot (uptime etc)
1082   def status
1083     secs_up = Time.new - @startup_time
1084     uptime = Utils.secs_to_string secs_up
1085     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1086     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1087   end
1088
1089   # We want to respond to a hung server in a timely manner. If nothing was received
1090   # in the user-selected timeout and we haven't PINGed the server yet, we PING
1091   # the server. If the PONG is not received within the user-defined timeout, we
1092   # assume we're in ping timeout and act accordingly.
1093   def ping_server
1094     act_timeout = @config['server.ping_timeout']
1095     return if act_timeout <= 0
1096     now = Time.now
1097     if @last_rec && now > @last_rec + act_timeout
1098       if @last_ping.nil?
1099         # No previous PING pending, send a new one
1100         sendq "PING :rbot"
1101         @last_ping = Time.now
1102       else
1103         diff = now - @last_ping
1104         if diff > act_timeout
1105           debug "no PONG from server in #{diff} seconds, reconnecting"
1106           # the actual reconnect is handled in the main loop:
1107           raise TimeoutError, "no PONG from server in #{diff} seconds"
1108         end
1109       end
1110     end
1111   end
1112
1113   def stop_server_pings
1114     # cancel previous PINGs and reset time of last RECV
1115     @last_ping = nil
1116     @last_rec = nil
1117   end
1118
1119   private
1120
1121   def irclogprivmsg(m)
1122     if(m.action?)
1123       if(m.private?)
1124         irclog "* [#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
1125       else
1126         irclog "* #{m.sourcenick} #{m.message}", m.target
1127       end
1128     else
1129       if(m.public?)
1130         irclog "<#{m.sourcenick}> #{m.message}", m.target
1131       else
1132         irclog "[#{m.sourcenick}(#{m.sourceaddress})] #{m.message}", m.sourcenick
1133       end
1134     end
1135   end
1136
1137   # log a message. Internal use only.
1138   def log_sent(type, where, message)
1139     case type
1140       when "NOTICE"
1141         case where
1142         when Channel
1143           irclog "-=#{myself}=- #{message}", where
1144         else
1145           irclog "[-=#{where}=-] #{message}", where
1146         end
1147       when "PRIVMSG"
1148         case where
1149         when Channel
1150           irclog "<#{myself}> #{message}", where
1151         else
1152           irclog "[msg(#{where})] #{message}", where
1153         end
1154     end
1155   end
1156
1157   def irclogjoin(m)
1158     if m.address?
1159       debug "joined channel #{m.channel}"
1160       irclog "@ Joined channel #{m.channel}", m.channel
1161     else
1162       irclog "@ #{m.sourcenick} joined channel #{m.channel}", m.channel
1163     end
1164   end
1165
1166   def irclogpart(m)
1167     if(m.address?)
1168       debug "left channel #{m.channel}"
1169       irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1170     else
1171       irclog "@ #{m.sourcenick} left channel #{m.channel} (#{m.message})", m.channel
1172     end
1173   end
1174
1175   def irclogkick(m)
1176     if(m.address?)
1177       debug "kicked from channel #{m.channel}"
1178       irclog "@ You have been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1179     else
1180       irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.sourcenick} (#{m.message})", m.channel
1181     end
1182   end
1183
1184   def irclogtopic(m)
1185     if m.source == myself
1186       irclog "@ I set topic \"#{m.topic}\"", m.channel
1187     else
1188       irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel
1189     end
1190   end
1191
1192 end
1193
1194 end