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