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