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