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