]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/ircbot.rb
+ pidfile support + command line option for pid file name
[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 require 'pp'
17
18 unless Kernel.instance_methods.include?("pretty_inspect")
19   def pretty_inspect
20     PP.pp(self, '')
21   end
22   public :pretty_inspect
23 end
24
25 class Exception
26   def pretty_print(q)
27     q.group(1, "#<%s: %s" % [self.class, self.message], ">") {
28       q.seplist(self.backtrace, lambda { "\n" }) { |v| v } if self.backtrace
29     }
30   end
31 end
32
33 def rawlog(level, message=nil, who_pos=1)
34   call_stack = caller
35   if call_stack.length > who_pos
36     who = call_stack[who_pos].sub(%r{(?:.+)/([^/]+):(\d+)(:in .*)?}) { "#{$1}:#{$2}#{$3}" }
37   else
38     who = "(unknown)"
39   end
40   # Output each line. To distinguish between separate messages and multi-line
41   # messages originating at the same time, we blank #{who} after the first message
42   # is output.
43   # Also, we output strings as-is but for other objects we use pretty_inspect
44   case message
45   when String
46     str = message
47   else
48     str = message.pretty_inspect
49   end
50   str.each_line { |l|
51     $logger.add(level, l.chomp, who)
52     who.gsub!(/./," ")
53   }
54 end
55
56 def log_session_start
57   $logger << "\n\n=== #{botclass} session started on #{Time.now.strftime($dateformat)} ===\n\n"
58 end
59
60 def log_session_end
61   $logger << "\n\n=== #{botclass} session ended on #{Time.now.strftime($dateformat)} ===\n\n"
62 end
63
64 def debug(message=nil, who_pos=1)
65   rawlog(Logger::Severity::DEBUG, message, who_pos)
66 end
67
68 def log(message=nil, who_pos=1)
69   rawlog(Logger::Severity::INFO, message, who_pos)
70 end
71
72 def warning(message=nil, who_pos=1)
73   rawlog(Logger::Severity::WARN, message, who_pos)
74 end
75
76 def error(message=nil, who_pos=1)
77   rawlog(Logger::Severity::ERROR, message, who_pos)
78 end
79
80 def fatal(message=nil, who_pos=1)
81   rawlog(Logger::Severity::FATAL, message, who_pos)
82 end
83
84 debug "debug test"
85 log "log test"
86 warning "warning test"
87 error "error test"
88 fatal "fatal test"
89
90 # The following global is used for the improved signal handling.
91 $interrupted = 0
92
93 # these first
94 require 'rbot/rbotconfig'
95 require 'rbot/config'
96 # require 'rbot/utils'
97
98 require 'rbot/irc'
99 require 'rbot/rfc2812'
100 require 'rbot/ircsocket'
101 require 'rbot/botuser'
102 require 'rbot/timer'
103 require 'rbot/plugins'
104 # require 'rbot/channel'
105 require 'rbot/message'
106 require 'rbot/language'
107 require 'rbot/dbhash'
108 require 'rbot/registry'
109 # require 'rbot/httputil'
110
111 module Irc
112
113 # Main bot class, which manages the various components, receives messages,
114 # handles them or passes them to plugins, and contains core functionality.
115 class Bot
116   COPYRIGHT_NOTICE = "(c) Tom Gilbert and the rbot development team"
117   # the bot's Auth data
118   attr_reader :auth
119
120   # the bot's BotConfig data
121   attr_reader :config
122
123   # the botclass for this bot (determines configdir among other things)
124   attr_reader :botclass
125
126   # used to perform actions periodically (saves configuration once per minute
127   # by default)
128   attr_reader :timer
129
130   # synchronize with this mutex while touching permanent data files:
131   # saving, flushing, cleaning up ...
132   attr_reader :save_mutex
133
134   # bot's Language data
135   attr_reader :lang
136
137   # bot's irc socket
138   # TODO multiserver
139   attr_reader :socket
140
141   # bot's object registry, plugins get an interface to this for persistant
142   # storage (hash interface tied to a bdb file, plugins use Accessors to store
143   # and restore objects in their own namespaces.)
144   attr_reader :registry
145
146   # bot's plugins. This is an instance of class Plugins
147   attr_reader :plugins
148
149   # bot's httputil help object, for fetching resources via http. Sets up
150   # proxies etc as defined by the bot configuration/environment
151   attr_accessor :httputil
152
153   # server we are connected to
154   # TODO multiserver
155   def server
156     @client.server
157   end
158
159   # bot User in the client/server connection
160   # TODO multiserver
161   def myself
162     @client.user
163   end
164
165   # bot User in the client/server connection
166   def nick
167     myself.nick
168   end
169
170   # create a new Bot with botclass +botclass+
171   def initialize(botclass, params = {})
172     # BotConfig for the core bot
173     # TODO should we split socket stuff into ircsocket, etc?
174     BotConfig.register BotConfigArrayValue.new('server.list',
175       :default => ['irc://localhost'], :wizard => true,
176       :requires_restart => true,
177       :desc => "List of irc servers rbot should try to connect to. Use comma to separate values. Servers are in format 'server.doma.in:port'. If port is not specified, default value (6667) is used.")
178     BotConfig.register BotConfigBooleanValue.new('server.ssl',
179       :default => false, :requires_restart => true, :wizard => true,
180       :desc => "Use SSL to connect to this server?")
181     BotConfig.register BotConfigStringValue.new('server.password',
182       :default => false, :requires_restart => true,
183       :desc => "Password for connecting to this server (if required)",
184       :wizard => true)
185     BotConfig.register BotConfigStringValue.new('server.bindhost',
186       :default => false, :requires_restart => true,
187       :desc => "Specific local host or IP for the bot to bind to (if required)",
188       :wizard => true)
189     BotConfig.register BotConfigIntegerValue.new('server.reconnect_wait',
190       :default => 5, :validate => Proc.new{|v| v >= 0},
191       :desc => "Seconds to wait before attempting to reconnect, on disconnect")
192     BotConfig.register BotConfigFloatValue.new('server.sendq_delay',
193       :default => 2.0, :validate => Proc.new{|v| v >= 0},
194       :desc => "(flood prevention) the delay between sending messages to the server (in seconds)",
195       :on_change => Proc.new {|bot, v| bot.socket.sendq_delay = v })
196     BotConfig.register BotConfigIntegerValue.new('server.sendq_burst',
197       :default => 4, :validate => Proc.new{|v| v >= 0},
198       :desc => "(flood prevention) max lines to burst to the server before throttling. Most ircd's allow bursts of up 5 lines",
199       :on_change => Proc.new {|bot, v| bot.socket.sendq_burst = v })
200     BotConfig.register BotConfigIntegerValue.new('server.ping_timeout',
201       :default => 30, :validate => Proc.new{|v| v >= 0},
202       :desc => "reconnect if server doesn't respond to PING within this many seconds (set to 0 to disable)")
203
204     BotConfig.register BotConfigStringValue.new('irc.nick', :default => "rbot",
205       :desc => "IRC nickname the bot should attempt to use", :wizard => true,
206       :on_change => Proc.new{|bot, v| bot.sendq "NICK #{v}" })
207     BotConfig.register BotConfigStringValue.new('irc.name',
208       :default => "Ruby bot", :requires_restart => true,
209       :desc => "IRC realname the bot should use")
210     BotConfig.register BotConfigBooleanValue.new('irc.name_copyright',
211       :default => true, :requires_restart => true,
212       :desc => "Append copyright notice to bot realname? (please don't disable unless it's really necessary)")
213     BotConfig.register BotConfigStringValue.new('irc.user', :default => "rbot",
214       :requires_restart => true,
215       :desc => "local user the bot should appear to be", :wizard => true)
216     BotConfig.register BotConfigArrayValue.new('irc.join_channels',
217       :default => [], :wizard => true,
218       :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'")
219     BotConfig.register BotConfigArrayValue.new('irc.ignore_users',
220       :default => [], 
221       :desc => "Which users to ignore input from. This is mainly to avoid bot-wars triggered by creative people")
222
223     BotConfig.register BotConfigIntegerValue.new('core.save_every',
224       :default => 60, :validate => Proc.new{|v| v >= 0},
225       :on_change => Proc.new { |bot, v|
226         if @save_timer
227           if v > 0
228             @timer.reschedule(@save_timer, v)
229             @timer.unblock(@save_timer)
230           else
231             @timer.block(@save_timer)
232           end
233         else
234           if v > 0
235             @save_timer = @timer.add(v) { bot.save }
236           end
237           # Nothing to do when v == 0
238         end
239       },
240       :desc => "How often the bot should persist all configuration to disk (in case of a server crash, for example)")
241
242     BotConfig.register BotConfigBooleanValue.new('core.run_as_daemon',
243       :default => false, :requires_restart => true,
244       :desc => "Should the bot run as a daemon?")
245
246     BotConfig.register BotConfigStringValue.new('log.file',
247       :default => false, :requires_restart => true,
248       :desc => "Name of the logfile to which console messages will be redirected when the bot is run as a daemon")
249     BotConfig.register BotConfigIntegerValue.new('log.level',
250       :default => 1, :requires_restart => false,
251       :validate => Proc.new { |v| (0..5).include?(v) },
252       :on_change => Proc.new { |bot, v|
253         $logger.level = v
254       },
255       :desc => "The minimum logging level (0=DEBUG,1=INFO,2=WARN,3=ERROR,4=FATAL) for console messages")
256     BotConfig.register BotConfigIntegerValue.new('log.keep',
257       :default => 1, :requires_restart => true,
258       :validate => Proc.new { |v| v >= 0 },
259       :desc => "How many old console messages logfiles to keep")
260     BotConfig.register BotConfigIntegerValue.new('log.max_size',
261       :default => 10, :requires_restart => true,
262       :validate => Proc.new { |v| v > 0 },
263       :desc => "Maximum console messages logfile size (in megabytes)")
264
265     BotConfig.register BotConfigArrayValue.new('plugins.path',
266       :wizard => true, :default => ['(default)', '(default)/games', '(default)/contrib'],
267       :requires_restart => false,
268       :on_change => Proc.new { |bot, v| bot.setup_plugins_path },
269       :desc => "Where the bot should look for plugins. List multiple directories using commas to separate. Use '(default)' for default prepackaged plugins collection, '(default)/contrib' for prepackaged unsupported plugins collection")
270
271     BotConfig.register BotConfigEnumValue.new('send.newlines',
272       :values => ['split', 'join'], :default => 'split',
273       :on_change => Proc.new { |bot, v|
274         bot.set_default_send_options :newlines => v.to_sym
275       },
276       :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")
277     BotConfig.register BotConfigStringValue.new('send.join_with',
278       :default => ' ',
279       :on_change => Proc.new { |bot, v|
280         bot.set_default_send_options :join_with => v.dup
281       },
282       :desc => "String used to replace newlines when send.newlines is set to join")
283     BotConfig.register BotConfigIntegerValue.new('send.max_lines',
284       :default => 5,
285       :validate => Proc.new { |v| v >= 0 },
286       :on_change => Proc.new { |bot, v|
287         bot.set_default_send_options :max_lines => v
288       },
289       :desc => "Maximum number of IRC lines to send for each message (set to 0 for no limit)")
290     BotConfig.register BotConfigEnumValue.new('send.overlong',
291       :values => ['split', 'truncate'], :default => 'split',
292       :on_change => Proc.new { |bot, v|
293         bot.set_default_send_options :overlong => v.to_sym
294       },
295       :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")
296     BotConfig.register BotConfigStringValue.new('send.split_at',
297       :default => '\s+',
298       :on_change => Proc.new { |bot, v|
299         bot.set_default_send_options :split_at => Regexp.new(v)
300       },
301       :desc => "A regular expression that should match the split points for overlong messages (see send.overlong)")
302     BotConfig.register BotConfigBooleanValue.new('send.purge_split',
303       :default => true,
304       :on_change => Proc.new { |bot, v|
305         bot.set_default_send_options :purge_split => v
306       },
307       :desc => "Set to true if the splitting boundary (set in send.split_at) should be removed when splitting overlong messages (see send.overlong)")
308     BotConfig.register BotConfigStringValue.new('send.truncate_text',
309       :default => "#{Reverse}...#{Reverse}",
310       :on_change => Proc.new { |bot, v|
311         bot.set_default_send_options :truncate_text => v.dup
312       },
313       :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")
314
315     @argv = params[:argv]
316     @run_dir = params[:run_dir] || Dir.pwd
317
318     unless FileTest.directory? Config::coredir
319       error "core directory '#{Config::coredir}' not found, did you setup.rb?"
320       exit 2
321     end
322
323     unless FileTest.directory? Config::datadir
324       error "data directory '#{Config::datadir}' not found, did you setup.rb?"
325       exit 2
326     end
327
328     unless botclass and not botclass.empty?
329       # We want to find a sensible default.
330       #  * On POSIX systems we prefer ~/.rbot for the effective uid of the process
331       #  * On Windows (at least the NT versions) we want to put our stuff in the
332       #    Application Data folder.
333       # We don't use any particular O/S detection magic, exploiting the fact that
334       # Etc.getpwuid is nil on Windows
335       if Etc.getpwuid(Process::Sys.geteuid)
336         botclass = Etc.getpwuid(Process::Sys.geteuid)[:dir].dup
337       else
338         if ENV.has_key?('APPDATA')
339           botclass = ENV['APPDATA'].dup
340           botclass.gsub!("\\","/")
341         end
342       end
343       botclass += "/.rbot"
344     end
345     botclass = File.expand_path(botclass)
346     @botclass = botclass.gsub(/\/$/, "")
347
348     unless FileTest.directory? botclass
349       log "no #{botclass} directory found, creating from templates.."
350       if FileTest.exist? botclass
351         error "file #{botclass} exists but isn't a directory"
352         exit 2
353       end
354       FileUtils.cp_r Config::datadir+'/templates', botclass
355     end
356
357     Dir.mkdir("#{botclass}/logs") unless File.exist?("#{botclass}/logs")
358     Dir.mkdir("#{botclass}/registry") unless File.exist?("#{botclass}/registry")
359     Dir.mkdir("#{botclass}/safe_save") unless File.exist?("#{botclass}/safe_save")
360
361     # Time at which the last PING was sent
362     @last_ping = nil
363     # Time at which the last line was RECV'd from the server
364     @last_rec = nil
365
366     @startup_time = Time.new
367
368     begin
369       @config = BotConfig.configmanager
370       @config.bot_associate(self)
371     rescue Exception => e
372       fatal e
373       log_session_end
374       exit 2
375     end
376
377     if @config['core.run_as_daemon']
378       $daemonize = true
379     end
380
381     @logfile = @config['log.file']
382     if @logfile.class!=String || @logfile.empty?
383       @logfile = "#{botclass}/#{File.basename(botclass).gsub(/^\.+/,'')}.log"
384     end
385
386     # See http://blog.humlab.umu.se/samuel/archives/000107.html
387     # for the backgrounding code 
388     if $daemonize
389       begin
390         exit if fork
391         Process.setsid
392         exit if fork
393       rescue NotImplementedError
394         warning "Could not background, fork not supported"
395       rescue SystemExit
396         exit 0
397       rescue Exception => e
398         warning "Could not background. #{e.pretty_inspect}"
399       end
400       Dir.chdir botclass
401       # File.umask 0000                # Ensure sensible umask. Adjust as needed.
402       log "Redirecting standard input/output/error"
403       begin
404         STDIN.reopen "/dev/null"
405       rescue Errno::ENOENT
406         # On Windows, there's not such thing as /dev/null
407         STDIN.reopen "NUL"
408       end
409       def STDOUT.write(str=nil)
410         log str, 2
411         return str.to_s.size
412       end
413       def STDERR.write(str=nil)
414         if str.to_s.match(/:\d+: warning:/)
415           warning str, 2
416         else
417           error str, 2
418         end
419         return str.to_s.size
420       end
421     end
422
423     # Set the new logfile and loglevel. This must be done after the daemonizing
424     $logger = Logger.new(@logfile, @config['log.keep'], @config['log.max_size']*1024*1024)
425     $logger.datetime_format= $dateformat
426     $logger.level = @config['log.level']
427     $logger.level = $cl_loglevel if $cl_loglevel
428     $logger.level = 0 if $debug
429
430     log_session_start
431
432     File.open($opts['pidfile'] || "#{@botclass}/rbot.pid", 'w') do |pf|
433       pf << "#{$$}\n"
434     end
435
436     @registry = BotRegistry.new self
437
438     @timer = Timer::Timer.new(1.0) # only need per-second granularity
439     @save_mutex = Mutex.new
440     if @config['core.save_every'] > 0
441       @save_timer = @timer.add(@config['core.save_every']) { save }
442     else
443       @save_timer = nil
444     end
445     @quit_mutex = Mutex.new
446
447     @logs = Hash.new
448
449     @plugins = nil
450     @lang = Language::Language.new(self, @config['core.language'])
451
452     begin
453       @auth = Auth::authmanager
454       @auth.bot_associate(self)
455       # @auth.load("#{botclass}/botusers.yaml")
456     rescue Exception => e
457       fatal e
458       log_session_end
459       exit 2
460     end
461     @auth.everyone.set_default_permission("*", true)
462     @auth.botowner.password= @config['auth.password']
463
464     Dir.mkdir("#{botclass}/plugins") unless File.exist?("#{botclass}/plugins")
465     @plugins = Plugins::manager
466     @plugins.bot_associate(self)
467     setup_plugins_path()
468
469     if @config['server.name']
470         debug "upgrading configuration (server.name => server.list)"
471         srv_uri = 'irc://' + @config['server.name']
472         srv_uri += ":#{@config['server.port']}" if @config['server.port']
473         @config.items['server.list'.to_sym].set_string(srv_uri)
474         @config.delete('server.name'.to_sym)
475         @config.delete('server.port'.to_sym)
476         debug "server.list is now #{@config['server.list'].inspect}"
477     end
478
479     @socket = IrcSocket.new(@config['server.list'], @config['server.bindhost'], @config['server.sendq_delay'], @config['server.sendq_burst'], :ssl => @config['server.ssl'])
480     @client = Client.new
481
482     @plugins.scan
483
484     # Channels where we are quiet
485     # Array of channels names where the bot should be quiet
486     # '*' means all channels
487     #
488     @quiet = []
489
490     @client[:welcome] = proc {|data|
491       irclog "joined server #{@client.server} as #{myself}", "server"
492
493       @plugins.delegate("connect")
494
495       @config['irc.join_channels'].each { |c|
496         debug "autojoining channel #{c}"
497         if(c =~ /^(\S+)\s+(\S+)$/i)
498           join $1, $2
499         else
500           join c if(c)
501         end
502       }
503     }
504
505     # TODO the next two @client should go into rfc2812.rb, probably
506     # Since capabs are two-steps processes, server.supports[:capab]
507     # should be a three-state: nil, [], [....]
508     asked_for = { :"identify-msg" => false }
509     @client[:isupport] = proc { |data|
510       if server.supports[:capab] and !asked_for[:"identify-msg"]
511         sendq "CAPAB IDENTIFY-MSG"
512         asked_for[:"identify-msg"] = true
513       end
514     }
515     @client[:datastr] = proc { |data|
516       if data[:text] == "IDENTIFY-MSG"
517         server.capabilities[:"identify-msg"] = true
518       else
519         debug "Not handling RPL_DATASTR #{data[:servermessage]}"
520       end
521     }
522
523     @client[:privmsg] = proc { |data|
524       m = PrivMessage.new(self, server, data[:source], data[:target], data[:message])
525       # debug "Message source is #{data[:source].inspect}"
526       # debug "Message target is #{data[:target].inspect}"
527       # debug "Bot is #{myself.inspect}"
528
529       ignored = false
530       @config['irc.ignore_users'].each { |mask|
531         if m.source.matches?(server.new_netmask(mask))
532           ignored = true
533           break
534         end
535       }
536
537       irclogprivmsg(m)
538
539       unless ignored
540         @plugins.delegate "listen", m
541         @plugins.privmsg(m) if m.address?
542         if not m.replied
543           @plugins.delegate "unreplied", m
544         end
545       end
546     }
547     @client[:notice] = proc { |data|
548       message = NoticeMessage.new(self, server, data[:source], data[:target], data[:message])
549       # pass it off to plugins that want to hear everything
550       @plugins.delegate "listen", message
551     }
552     @client[:motd] = proc { |data|
553       data[:motd].each_line { |line|
554         irclog "MOTD: #{line}", "server"
555       }
556     }
557     @client[:nicktaken] = proc { |data|
558       new = "#{data[:nick]}_" 
559       nickchg new
560       # If we're setting our nick at connection because our choice was taken,
561       # we have to fix our nick manually, because there will be no NICK message
562       # to inform us that our nick has been changed.
563       if data[:target] == '*'
564         debug "setting my connection nick to #{new}"
565         nick = new
566       end
567       @plugins.delegate "nicktaken", data[:nick]
568     }
569     @client[:badnick] = proc {|data|
570       arning "bad nick (#{data[:nick]})"
571     }
572     @client[:ping] = proc {|data|
573       sendq "PONG #{data[:pingid]}"
574     }
575     @client[:pong] = proc {|data|
576       @last_ping = nil
577     }
578     @client[:nick] = proc {|data|
579       # debug "Message source is #{data[:source].inspect}"
580       # debug "Bot is #{myself.inspect}"
581       source = data[:source]
582       old = data[:oldnick]
583       new = data[:newnick]
584       m = NickMessage.new(self, server, source, old, new)
585       if source == myself
586         debug "my nick is now #{new}"
587       end
588       data[:is_on].each { |ch|
589         irclog "@ #{old} is now known as #{new}", ch
590       }
591       @plugins.delegate("listen", m)
592       @plugins.delegate("nick", m)
593     }
594     @client[:quit] = proc {|data|
595       source = data[:source]
596       message = data[:message]
597       m = QuitMessage.new(self, server, source, source, message)
598       data[:was_on].each { |ch|
599         irclog "@ Quit: #{source}: #{message}", ch
600       }
601       @plugins.delegate("listen", m)
602       @plugins.delegate("quit", m)
603     }
604     @client[:mode] = proc {|data|
605       irclog "@ Mode #{data[:modestring]} by #{data[:source]}", data[:channel]
606     }
607     @client[:join] = proc {|data|
608       m = JoinMessage.new(self, server, data[:source], data[:channel], data[:message])
609       irclogjoin(m)
610
611       @plugins.delegate("listen", m)
612       @plugins.delegate("join", m)
613     }
614     @client[:part] = proc {|data|
615       m = PartMessage.new(self, server, data[:source], data[:channel], data[:message])
616       irclogpart(m)
617
618       @plugins.delegate("listen", m)
619       @plugins.delegate("part", m)
620     }
621     @client[:kick] = proc {|data|
622       m = KickMessage.new(self, server, data[:source], data[:target], data[:channel],data[:message])
623       irclogkick(m)
624
625       @plugins.delegate("listen", m)
626       @plugins.delegate("kick", m)
627     }
628     @client[:invite] = proc {|data|
629       if data[:target] == myself
630         join data[:channel] if @auth.allow?("join", data[:source], data[:source].nick)
631       end
632     }
633     @client[:changetopic] = proc {|data|
634       m = TopicMessage.new(self, server, data[:source], data[:channel], data[:topic])
635       irclogtopic(m)
636
637       @plugins.delegate("listen", m)
638       @plugins.delegate("topic", m)
639     }
640     @client[:topic] = proc { |data|
641       irclog "@ Topic is \"#{data[:topic]}\"", data[:channel]
642     }
643     @client[:topicinfo] = proc { |data|
644       channel = data[:channel]
645       topic = channel.topic
646       irclog "@ Topic set by #{topic.set_by} on #{topic.set_on}", channel
647       m = TopicMessage.new(self, server, data[:source], channel, topic)
648
649       @plugins.delegate("listen", m)
650       @plugins.delegate("topic", m)
651     }
652     @client[:names] = proc { |data|
653       @plugins.delegate "names", data[:channel], data[:users]
654     }
655     @client[:unknown] = proc { |data|
656       #debug "UNKNOWN: #{data[:serverstring]}"
657       irclog data[:serverstring], ".unknown"
658     }
659
660     set_default_send_options :newlines => @config['send.newlines'].to_sym,
661       :join_with => @config['send.join_with'].dup,
662       :max_lines => @config['send.max_lines'],
663       :overlong => @config['send.overlong'].to_sym,
664       :split_at => Regexp.new(@config['send.split_at']),
665       :purge_split => @config['send.purge_split'],
666       :truncate_text => @config['send.truncate_text'].dup
667   end
668
669   def setup_plugins_path
670     @plugins.clear_botmodule_dirs
671     @plugins.add_botmodule_dir(Config::coredir + "/utils")
672     @plugins.add_botmodule_dir(Config::coredir)
673     @plugins.add_botmodule_dir("#{botclass}/plugins")
674
675     @config['plugins.path'].each do |_|
676         path = _.sub(/^\(default\)/, Config::datadir + '/plugins')
677         @plugins.add_botmodule_dir(path)
678     end
679   end
680
681   def set_default_send_options(opts={})
682     # Default send options for NOTICE and PRIVMSG
683     unless defined? @default_send_options
684       @default_send_options = {
685         :queue_channel => nil,      # use default queue channel
686         :queue_ring => nil,         # use default queue ring
687         :newlines => :split,        # or :join
688         :join_with => ' ',          # by default, use a single space
689         :max_lines => 0,          # maximum number of lines to send with a single command
690         :overlong => :split,        # or :truncate
691         # TODO an array of splitpoints would be preferrable for this option:
692         :split_at => /\s+/,         # by default, split overlong lines at whitespace
693         :purge_split => true,       # should the split string be removed?
694         :truncate_text => "#{Reverse}...#{Reverse}"  # text to be appened when truncating
695       }
696     end
697     @default_send_options.update opts unless opts.empty?
698     end
699
700   # checks if we should be quiet on a channel
701   def quiet_on?(channel)
702     return @quiet.include?('*') || @quiet.include?(channel.downcase)
703   end
704
705   def set_quiet(channel)
706     if channel
707       ch = channel.downcase.dup
708       @quiet << ch unless @quiet.include?(ch)
709     else
710       @quiet.clear
711       @quiet << '*'
712     end
713   end
714
715   def reset_quiet(channel)
716     if channel
717       @quiet.delete channel.downcase
718     else
719       @quiet.clear
720     end
721   end
722
723   # things to do when we receive a signal
724   def got_sig(sig)
725     debug "received #{sig}, queueing quit"
726     $interrupted += 1
727     quit unless @quit_mutex.locked?
728     debug "interrupted #{$interrupted} times"
729     if $interrupted >= 3
730       debug "drastic!"
731       log_session_end
732       exit 2
733     end
734   end
735
736   # connect the bot to IRC
737   def connect
738     begin
739       trap("SIGINT") { got_sig("SIGINT") }
740       trap("SIGTERM") { got_sig("SIGTERM") }
741       trap("SIGHUP") { got_sig("SIGHUP") }
742     rescue ArgumentError => e
743       debug "failed to trap signals (#{e.pretty_inspect}): running on Windows?"
744     rescue Exception => e
745       debug "failed to trap signals: #{e.pretty_inspect}"
746     end
747     begin
748       quit if $interrupted > 0
749       @socket.connect
750     rescue => e
751       raise e.class, "failed to connect to IRC server at #{@socket.server_uri}: " + e
752     end
753     quit if $interrupted > 0
754
755     realname = @config['irc.name'].clone || 'Ruby bot'
756     realname << ' ' + COPYRIGHT_NOTICE if @config['irc.name_copyright'] 
757
758     @socket.emergency_puts "PASS " + @config['server.password'] if @config['server.password']
759     @socket.emergency_puts "NICK #{@config['irc.nick']}\nUSER #{@config['irc.user']} 4 #{@socket.server_uri.host} :#{realname}"
760     quit if $interrupted > 0
761     myself.nick = @config['irc.nick']
762     myself.user = @config['irc.user']
763   end
764
765   # begin event handling loop
766   def mainloop
767     while true
768       begin
769         quit if $interrupted > 0
770         connect
771         @timer.start
772
773         quit_msg = nil
774         while @socket.connected?
775           quit if $interrupted > 0
776
777           # Wait for messages and process them as they arrive. If nothing is
778           # received, we call the ping_server() method that will PING the
779           # server if appropriate, or raise a TimeoutError if no PONG has been
780           # received in the user-chosen timeout since the last PING sent.
781           if @socket.select(1)
782             break unless reply = @socket.gets
783             @last_rec = Time.now
784             @client.process reply
785           else
786             ping_server
787           end
788         end
789
790       # I despair of this. Some of my users get "connection reset by peer"
791       # exceptions that ARENT SocketError's. How am I supposed to handle
792       # that?
793       rescue SystemExit
794         log_session_end
795         exit 0
796       rescue Errno::ETIMEDOUT, Errno::ECONNABORTED, TimeoutError, SocketError => e
797         error "network exception: #{e.pretty_inspect}"
798         quit_msg = e.to_s
799       rescue BDB::Fatal => e
800         fatal "fatal bdb error: #{e.pretty_inspect}"
801         DBTree.stats
802         # Why restart? DB problems are serious stuff ...
803         # restart("Oops, we seem to have registry problems ...")
804         log_session_end
805         exit 2
806       rescue Exception => e
807         error "non-net exception: #{e.pretty_inspect}"
808         quit_msg = e.to_s
809       rescue => e
810         fatal "unexpected exception: #{e.pretty_inspect}"
811         log_session_end
812         exit 2
813       end
814
815       disconnect(quit_msg)
816
817       log "\n\nDisconnected\n\n"
818
819       quit if $interrupted > 0
820
821       log "\n\nWaiting to reconnect\n\n"
822       sleep @config['server.reconnect_wait']
823     end
824   end
825
826   # type:: message type
827   # where:: message target
828   # message:: message text
829   # send message +message+ of type +type+ to target +where+
830   # Type can be PRIVMSG, NOTICE, etc, but those you should really use the
831   # relevant say() or notice() methods. This one should be used for IRCd
832   # extensions you want to use in modules.
833   def sendmsg(type, where, original_message, options={})
834     opts = @default_send_options.merge(options)
835
836     # For starters, set up appropriate queue channels and rings
837     mchan = opts[:queue_channel]
838     mring = opts[:queue_ring]
839     if mchan
840       chan = mchan
841     else
842       chan = where
843     end
844     if mring
845       ring = mring
846     else
847       case where
848       when User
849         ring = 1
850       else
851         ring = 2
852       end
853     end
854
855     multi_line = original_message.to_s.gsub(/[\r\n]+/, "\n")
856     messages = Array.new
857     case opts[:newlines]
858     when :join
859       messages << [multi_line.gsub("\n", opts[:join_with])]
860     when :split
861       multi_line.each_line { |line|
862         line.chomp!
863         next unless(line.size > 0)
864         messages << line
865       }
866     else
867       raise "Unknown :newlines option #{opts[:newlines]} while sending #{original_message.inspect}"
868     end
869
870     # The IRC protocol requires that each raw message must be not longer
871     # than 512 characters. From this length with have to subtract the EOL
872     # terminators (CR+LF) and the length of ":botnick!botuser@bothost "
873     # that will be prepended by the server to all of our messages.
874
875     # The maximum raw message length we can send is therefore 512 - 2 - 2
876     # minus the length of our hostmask.
877
878     max_len = 508 - myself.fullform.size
879
880     # On servers that support IDENTIFY-MSG, we have to subtract 1, because messages
881     # will have a + or - prepended
882     if server.capabilities[:"identify-msg"]
883       max_len -= 1
884     end
885
886     # When splitting the message, we'll be prefixing the following string:
887     # (e.g. "PRIVMSG #rbot :")
888     fixed = "#{type} #{where} :"
889
890     # And this is what's left
891     left = max_len - fixed.size
892
893     truncate = opts[:truncate_text]
894     truncate = @default_send_options[:truncate_text] if truncate.size > left
895     truncate = "" if truncate.size > left
896
897     all_lines = messages.map { |line|
898       if line.size < left
899         line
900       else
901         case opts[:overlong]
902         when :split
903           msg = line.dup
904           sub_lines = Array.new
905           begin
906             sub_lines << msg.slice!(0, left)
907             break if msg.empty?
908             lastspace = sub_lines.last.rindex(opts[:split_at])
909             if lastspace
910               msg.replace sub_lines.last.slice!(lastspace, sub_lines.last.size) + msg
911               msg.gsub!(/^#{opts[:split_at]}/, "") if opts[:purge_split]
912             end
913           end until msg.empty?
914           sub_lines
915         when :truncate
916           line.slice(0, left - truncate.size) << truncate
917         else
918           raise "Unknown :overlong option #{opts[:overlong]} while sending #{original_message.inspect}"
919         end
920       end
921     }.flatten
922
923     if opts[:max_lines] > 0 and all_lines.length > opts[:max_lines]
924       lines = all_lines[0...opts[:max_lines]]
925       new_last = lines.last.slice(0, left - truncate.size) << truncate
926       lines.last.replace(new_last)
927     else
928       lines = all_lines
929     end
930
931     lines.each { |line|
932       sendq "#{fixed}#{line}", chan, ring
933       log_sent(type, where, line)
934     }
935   end
936
937   # queue an arbitraty message for the server
938   def sendq(message="", chan=nil, ring=0)
939     # temporary
940     @socket.queue(message, chan, ring)
941   end
942
943   # send a notice message to channel/nick +where+
944   def notice(where, message, options={})
945     return if where.kind_of?(Channel) and quiet_on?(where)
946     sendmsg "NOTICE", where, message, options
947   end
948
949   # say something (PRIVMSG) to channel/nick +where+
950   def say(where, message, options={})
951     return if where.kind_of?(Channel) and quiet_on?(where)
952     sendmsg "PRIVMSG", where, message, options
953   end
954
955   # perform a CTCP action with message +message+ to channel/nick +where+
956   def action(where, message, options={})
957     return if where.kind_of?(Channel) and quiet_on?(where)
958     mchan = options.fetch(:queue_channel, nil)
959     mring = options.fetch(:queue_ring, nil)
960     if mchan
961       chan = mchan
962     else
963       chan = where
964     end
965     if mring
966       ring = mring
967     else
968       case where
969       when User
970         ring = 1
971       else
972         ring = 2
973       end
974     end
975     # FIXME doesn't check message length. Can we make this exploit sendmsg?
976     sendq "PRIVMSG #{where} :\001ACTION #{message}\001", chan, ring
977     case where
978     when Channel
979       irclog "* #{myself} #{message}", where
980     else
981       irclog "* #{myself}[#{where}] #{message}", where
982     end
983   end
984
985   # quick way to say "okay" (or equivalent) to +where+
986   def okay(where)
987     say where, @lang.get("okay")
988   end
989
990   # log IRC-related message +message+ to a file determined by +where+.
991   # +where+ can be a channel name, or a nick for private message logging
992   def irclog(message, where="server")
993     message = message.chomp
994     stamp = Time.now.strftime("%Y/%m/%d %H:%M:%S")
995     if where.class <= Server
996       where_str = "server"
997     else
998       where_str = where.downcase.gsub(/[:!?$*()\/\\<>|"']/, "_")
999     end
1000     unless(@logs.has_key?(where_str))
1001       @logs[where_str] = File.new("#{@botclass}/logs/#{where_str}", "a")
1002       @logs[where_str].sync = true
1003     end
1004     @logs[where_str].puts "[#{stamp}] #{message}"
1005     #debug "[#{stamp}] <#{where}> #{message}"
1006   end
1007
1008   # set topic of channel +where+ to +topic+
1009   def topic(where, topic)
1010     sendq "TOPIC #{where} :#{topic}", where, 2
1011   end
1012
1013   def disconnect(message = nil)
1014     message = @lang.get("quit") if (message.nil? || message.empty?)
1015     if @socket.connected?
1016       debug "Clearing socket"
1017       @socket.clearq
1018       debug "Sending quit message"
1019       @socket.emergency_puts "QUIT :#{message}"
1020       debug "Flushing socket"
1021       @socket.flush
1022       debug "Shutting down socket"
1023       @socket.shutdown
1024     end
1025     debug "Logging quits"
1026     server.channels.each { |ch|
1027       irclog "@ quit (#{message})", ch
1028     }
1029     stop_server_pings
1030     @client.reset
1031   end
1032
1033   # disconnect from the server and cleanup all plugins and modules
1034   def shutdown(message = nil)
1035     @quit_mutex.synchronize do
1036       debug "Shutting down:"
1037       ## No we don't restore them ... let everything run through
1038       # begin
1039       #   trap("SIGINT", "DEFAULT")
1040       #   trap("SIGTERM", "DEFAULT")
1041       #   trap("SIGHUP", "DEFAULT")
1042       # rescue => e
1043       #   debug "failed to restore signals: #{e.inspect}\nProbably running on windows?"
1044       # end
1045       debug "\tdisconnecting..."
1046       disconnect
1047       debug "\tsaving ..."
1048       save
1049       debug "\tcleaning up ..."
1050       @save_mutex.synchronize do
1051         @plugins.cleanup
1052       end
1053       debug "\tstopping timers ..."
1054       @timer.stop
1055       # debug "Closing registries"
1056       # @registry.close
1057       debug "\t\tcleaning up the db environment ..."
1058       DBTree.cleanup_env
1059       log "rbot quit (#{message})"
1060     end
1061   end
1062
1063   # message:: optional IRC quit message
1064   # quit IRC, shutdown the bot
1065   def quit(message=nil)
1066     begin
1067       shutdown(message)
1068     ensure
1069       exit 0
1070     end
1071   end
1072
1073   # totally shutdown and respawn the bot
1074   def restart(message = false)
1075     msg = message ? message : "restarting, back in #{@config['server.reconnect_wait']}..."
1076     shutdown(msg)
1077     sleep @config['server.reconnect_wait']
1078     begin
1079       # now we re-exec
1080       # Note, this fails on Windows
1081       debug "going to exec #{$0} #{@argv.inspect} from #{@run_dir}"
1082       Dir.chdir(@run_dir)
1083       exec($0, *@argv)
1084     rescue Errno::ENOENT
1085       exec("ruby", *(@argv.unshift $0))
1086     rescue Exception => e
1087       $interrupted += 1
1088       raise e
1089     end
1090   end
1091
1092   # call the save method for all of the botmodules
1093   def save
1094     @save_mutex.synchronize do
1095       @plugins.save
1096       DBTree.cleanup_logs
1097     end
1098   end
1099
1100   # call the rescan method for all of the botmodules
1101   def rescan
1102     @save_mutex.synchronize do
1103       @lang.rescan
1104       @plugins.rescan
1105     end
1106   end
1107
1108   # channel:: channel to join
1109   # key::     optional channel key if channel is +s
1110   # join a channel
1111   def join(channel, key=nil)
1112     if(key)
1113       sendq "JOIN #{channel} :#{key}", channel, 2
1114     else
1115       sendq "JOIN #{channel}", channel, 2
1116     end
1117   end
1118
1119   # part a channel
1120   def part(channel, message="")
1121     sendq "PART #{channel} :#{message}", channel, 2
1122   end
1123
1124   # attempt to change bot's nick to +name+
1125   def nickchg(name)
1126     sendq "NICK #{name}"
1127   end
1128
1129   # changing mode
1130   def mode(channel, mode, target)
1131     sendq "MODE #{channel} #{mode} #{target}", channel, 2
1132   end
1133
1134   # kicking a user
1135   def kick(channel, user, msg)
1136     sendq "KICK #{channel} #{user} :#{msg}", channel, 2
1137   end
1138
1139   # m::     message asking for help
1140   # topic:: optional topic help is requested for
1141   # respond to online help requests
1142   def help(topic=nil)
1143     topic = nil if topic == ""
1144     case topic
1145     when nil
1146       helpstr = "help topics: "
1147       helpstr += @plugins.helptopics
1148       helpstr += " (help <topic> for more info)"
1149     else
1150       unless(helpstr = @plugins.help(topic))
1151         helpstr = "no help for topic #{topic}"
1152       end
1153     end
1154     return helpstr
1155   end
1156
1157   # returns a string describing the current status of the bot (uptime etc)
1158   def status
1159     secs_up = Time.new - @startup_time
1160     uptime = Utils.secs_to_string secs_up
1161     # return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@registry.length} items stored in registry, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1162     return "Uptime #{uptime}, #{@plugins.length} plugins active, #{@socket.lines_sent} lines sent, #{@socket.lines_received} received."
1163   end
1164
1165   # We want to respond to a hung server in a timely manner. If nothing was received
1166   # in the user-selected timeout and we haven't PINGed the server yet, we PING
1167   # the server. If the PONG is not received within the user-defined timeout, we
1168   # assume we're in ping timeout and act accordingly.
1169   def ping_server
1170     act_timeout = @config['server.ping_timeout']
1171     return if act_timeout <= 0
1172     now = Time.now
1173     if @last_rec && now > @last_rec + act_timeout
1174       if @last_ping.nil?
1175         # No previous PING pending, send a new one
1176         sendq "PING :rbot"
1177         @last_ping = Time.now
1178       else
1179         diff = now - @last_ping
1180         if diff > act_timeout
1181           debug "no PONG from server in #{diff} seconds, reconnecting"
1182           # the actual reconnect is handled in the main loop:
1183           raise TimeoutError, "no PONG from server in #{diff} seconds"
1184         end
1185       end
1186     end
1187   end
1188
1189   def stop_server_pings
1190     # cancel previous PINGs and reset time of last RECV
1191     @last_ping = nil
1192     @last_rec = nil
1193   end
1194
1195   private
1196
1197   def irclogprivmsg(m)
1198     if(m.action?)
1199       if(m.private?)
1200         irclog "* [#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1201       else
1202         irclog "* #{m.source} #{m.message}", m.target
1203       end
1204     else
1205       if(m.public?)
1206         irclog "<#{m.source}> #{m.message}", m.target
1207       else
1208         irclog "[#{m.source}(#{m.sourceaddress})] #{m.message}", m.source
1209       end
1210     end
1211   end
1212
1213   # log a message. Internal use only.
1214   def log_sent(type, where, message)
1215     case type
1216       when "NOTICE"
1217         case where
1218         when Channel
1219           irclog "-=#{myself}=- #{message}", where
1220         else
1221           irclog "[-=#{where}=-] #{message}", where
1222         end
1223       when "PRIVMSG"
1224         case where
1225         when Channel
1226           irclog "<#{myself}> #{message}", where
1227         else
1228           irclog "[msg(#{where})] #{message}", where
1229         end
1230     end
1231   end
1232
1233   def irclogjoin(m)
1234     if m.address?
1235       debug "joined channel #{m.channel}"
1236       irclog "@ Joined channel #{m.channel}", m.channel
1237     else
1238       irclog "@ #{m.source} joined channel #{m.channel}", m.channel
1239     end
1240   end
1241
1242   def irclogpart(m)
1243     if(m.address?)
1244       debug "left channel #{m.channel}"
1245       irclog "@ Left channel #{m.channel} (#{m.message})", m.channel
1246     else
1247       irclog "@ #{m.source} left channel #{m.channel} (#{m.message})", m.channel
1248     end
1249   end
1250
1251   def irclogkick(m)
1252     if(m.address?)
1253       debug "kicked from channel #{m.channel}"
1254       irclog "@ You have been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1255     else
1256       irclog "@ #{m.target} has been kicked from #{m.channel} by #{m.source} (#{m.message})", m.channel
1257     end
1258   end
1259
1260   def irclogtopic(m)
1261     if m.source == myself
1262       irclog "@ I set topic \"#{m.topic}\"", m.channel
1263     else
1264       irclog "@ #{m.source} set topic \"#{m.topic}\"", m.channel
1265     end
1266   end
1267
1268 end
1269
1270 end