]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/irc.rb
use m.thread.nil? rather than longer m.thread == nil
[user/henk/code/ruby/rbot.git] / lib / rbot / irc.rb
1 #-- vim:sw=2:et
2 # General TODO list
3 # * do we want to handle a Channel list for each User telling which
4 #   Channels is the User on (of those the client is on too)?
5 #   We may want this so that when a User leaves all Channels and he hasn't
6 #   sent us privmsgs, we know we can remove him from the Server @users list
7 # * Maybe ChannelList and UserList should be HashesOf instead of ArrayOf?
8 #   See items marked as TODO Ho.
9 #   The framework to do this is now in place, thanks to the new [] method
10 #   for NetmaskList, which allows retrieval by Netmask or String
11 #++
12 # :title: IRC module
13 #
14 # Basic IRC stuff
15 #
16 # This module defines the fundamental building blocks for IRC
17 #
18 # Author:: Giuseppe Bilotta (giuseppe.bilotta@gmail.com)
19
20 require 'singleton'
21
22 class Object
23
24   # We extend the Object class with a method that
25   # checks if the receiver is nil or empty
26   def nil_or_empty?
27     return true unless self
28     return true if self.respond_to? :empty? and self.empty?
29     return false
30   end
31
32   # We alias the to_s method to __to_s__ to make
33   # it accessible in all classes
34   alias :__to_s__ :to_s 
35 end
36
37 # The Irc module is used to keep all IRC-related classes
38 # in the same namespace
39 #
40 module Irc
41
42
43   # Due to its Scandinavian origins, IRC has strange case mappings, which
44   # consider the characters <tt>{}|^</tt> as the uppercase
45   # equivalents of # <tt>[]\~</tt>.
46   #
47   # This is however not the same on all IRC servers: some use standard ASCII
48   # casemapping, other do not consider <tt>^</tt> as the uppercase of
49   # <tt>~</tt>
50   #
51   class Casemap
52     @@casemaps = {}
53
54     # Create a new casemap with name _name_, uppercase characters _upper_ and
55     # lowercase characters _lower_
56     #
57     def initialize(name, upper, lower)
58       @key = name.to_sym
59       raise "Casemap #{name.inspect} already exists!" if @@casemaps.has_key?(@key)
60       @@casemaps[@key] = {
61         :upper => upper,
62         :lower => lower,
63         :casemap => self
64       }
65     end
66
67     # Returns the Casemap with the given name
68     #
69     def Casemap.get(name)
70       @@casemaps[name.to_sym][:casemap]
71     end
72
73     # Retrieve the 'uppercase characters' of this Casemap
74     #
75     def upper
76       @@casemaps[@key][:upper]
77     end
78
79     # Retrieve the 'lowercase characters' of this Casemap
80     #
81     def lower
82       @@casemaps[@key][:lower]
83     end
84
85     # Return a Casemap based on the receiver
86     #
87     def to_irc_casemap
88       self
89     end
90
91     # A Casemap is represented by its lower/upper mappings
92     #
93     def inspect
94       self.__to_s__[0..-2] + " #{upper.inspect} ~(#{self})~ #{lower.inspect}>"
95     end
96
97     # As a String we return our name
98     #
99     def to_s
100       @key.to_s
101     end
102
103     # Two Casemaps are equal if they have the same upper and lower ranges
104     #
105     def ==(arg)
106       other = arg.to_irc_casemap
107       return self.upper == other.upper && self.lower == other.lower
108     end
109
110     # Give a warning if _arg_ and self are not the same Casemap
111     #
112     def must_be(arg)
113       other = arg.to_irc_casemap
114       if self == other
115         return true
116       else
117         warn "Casemap mismatch (#{self.inspect} != #{other.inspect})"
118         return false
119       end
120     end
121
122   end
123
124   # The rfc1459 casemap
125   #
126   class RfcCasemap < Casemap
127     include Singleton
128
129     def initialize
130       super('rfc1459', "\x41-\x5e", "\x61-\x7e")
131     end
132
133   end
134   RfcCasemap.instance
135
136   # The strict-rfc1459 Casemap
137   #
138   class StrictRfcCasemap < Casemap
139     include Singleton
140
141     def initialize
142       super('strict-rfc1459', "\x41-\x5d", "\x61-\x7d")
143     end
144
145   end
146   StrictRfcCasemap.instance
147
148   # The ascii Casemap
149   #
150   class AsciiCasemap < Casemap
151     include Singleton
152
153     def initialize
154       super('ascii', "\x41-\x5a", "\x61-\x7a")
155     end
156
157   end
158   AsciiCasemap.instance
159
160
161   # This module is included by all classes that are either bound to a server
162   # or should have a casemap.
163   #
164   module ServerOrCasemap
165
166     attr_reader :server
167
168     # This method initializes the instance variables @server and @casemap
169     # according to the values of the hash keys :server and :casemap in _opts_
170     #
171     def init_server_or_casemap(opts={})
172       @server = opts.fetch(:server, nil)
173       raise TypeError, "#{@server} is not a valid Irc::Server" if @server and not @server.kind_of?(Server)
174
175       @casemap = opts.fetch(:casemap, nil)
176       if @server
177         if @casemap
178           @server.casemap.must_be(@casemap)
179           @casemap = nil
180         end
181       else
182         @casemap = (@casemap || 'rfc1459').to_irc_casemap
183       end
184     end
185
186     # This is an auxiliary method: it returns true if the receiver fits the
187     # server and casemap specified in _opts_, false otherwise.
188     #
189     def fits_with_server_and_casemap?(opts={})
190       srv = opts.fetch(:server, nil)
191       cmap = opts.fetch(:casemap, nil)
192       cmap = cmap.to_irc_casemap unless cmap.nil?
193
194       if srv.nil?
195         return true if cmap.nil? or cmap == casemap
196       else
197         return true if srv == @server and (cmap.nil? or cmap == casemap)
198       end
199       return false
200     end
201
202     # Returns the casemap of the receiver, by looking at the bound
203     # @server (if possible) or at the @casemap otherwise
204     #
205     def casemap
206       return @server.casemap if defined?(@server) and @server
207       return @casemap
208     end
209
210     # Returns a hash with the current @server and @casemap as values of
211     # :server and :casemap
212     #
213     def server_and_casemap
214       h = {}
215       h[:server] = @server if defined?(@server) and @server
216       h[:casemap] = @casemap if defined?(@casemap) and @casemap
217       return h
218     end
219
220     # We allow up/downcasing with a different casemap
221     #
222     def irc_downcase(cmap=casemap)
223       self.to_s.irc_downcase(cmap)
224     end
225
226     # Up/downcasing something that includes this module returns its
227     # Up/downcased to_s form
228     #
229     def downcase
230       self.irc_downcase
231     end
232
233     # We allow up/downcasing with a different casemap
234     #
235     def irc_upcase(cmap=casemap)
236       self.to_s.irc_upcase(cmap)
237     end
238
239     # Up/downcasing something that includes this module returns its
240     # Up/downcased to_s form
241     #
242     def upcase
243       self.irc_upcase
244     end
245
246   end
247
248 end
249
250
251 # We start by extending the String class
252 # with some IRC-specific methods
253 #
254 class String
255
256   # This method returns the Irc::Casemap whose name is the receiver
257   #
258   def to_irc_casemap
259     Irc::Casemap.get(self) rescue raise TypeError, "Unkown Irc::Casemap #{self.inspect}"
260   end
261
262   # This method returns a string which is the downcased version of the
263   # receiver, according to the given _casemap_
264   #
265   #
266   def irc_downcase(casemap='rfc1459')
267     cmap = casemap.to_irc_casemap
268     self.tr(cmap.upper, cmap.lower)
269   end
270
271   # This is the same as the above, except that the string is altered in place
272   #
273   # See also the discussion about irc_downcase
274   #
275   def irc_downcase!(casemap='rfc1459')
276     cmap = casemap.to_irc_casemap
277     self.tr!(cmap.upper, cmap.lower)
278   end
279
280   # Upcasing functions are provided too
281   #
282   # See also the discussion about irc_downcase
283   #
284   def irc_upcase(casemap='rfc1459')
285     cmap = casemap.to_irc_casemap
286     self.tr(cmap.lower, cmap.upper)
287   end
288
289   # In-place upcasing
290   #
291   # See also the discussion about irc_downcase
292   #
293   def irc_upcase!(casemap='rfc1459')
294     cmap = casemap.to_irc_casemap
295     self.tr!(cmap.lower, cmap.upper)
296   end
297
298   # This method checks if the receiver contains IRC glob characters
299   #
300   # IRC has a very primitive concept of globs: a <tt>*</tt> stands for "any
301   # number of arbitrary characters", a <tt>?</tt> stands for "one and exactly
302   # one arbitrary character". These characters can be escaped by prefixing them
303   # with a slash (<tt>\\</tt>).
304   #
305   # A known limitation of this glob syntax is that there is no way to escape
306   # the escape character itself, so it's not possible to build a glob pattern
307   # where the escape character precedes a glob.
308   #
309   def has_irc_glob?
310     self =~ /^[*?]|[^\\][*?]/
311   end
312
313   # This method is used to convert the receiver into a Regular Expression
314   # that matches according to the IRC glob syntax
315   #
316   def to_irc_regexp
317     regmask = Regexp.escape(self)
318     regmask.gsub!(/(\\\\)?\\[*?]/) { |m|
319       case m
320       when /\\(\\[*?])/
321         $1
322       when /\\\*/
323         '.*'
324       when /\\\?/
325         '.'
326       else
327         raise "Unexpected match #{m} when converting #{self}"
328       end
329     }
330     Regexp.new("^#{regmask}$")
331   end
332
333 end
334
335
336 # ArrayOf is a subclass of Array whose elements are supposed to be all
337 # of the same class. This is not intended to be used directly, but rather
338 # to be subclassed as needed (see for example Irc::UserList and Irc::NetmaskList)
339 #
340 # Presently, only very few selected methods from Array are overloaded to check
341 # if the new elements are the correct class. An orthodox? method is provided
342 # to check the entire ArrayOf against the appropriate class.
343 #
344 class ArrayOf < Array
345
346   attr_reader :element_class
347
348   # Create a new ArrayOf whose elements are supposed to be all of type _kl_,
349   # optionally filling it with the elements from the Array argument.
350   #
351   def initialize(kl, ar=[])
352     raise TypeError, "#{kl.inspect} must be a class name" unless kl.kind_of?(Class)
353     super()
354     @element_class = kl
355     case ar
356     when Array
357       insert(0, *ar)
358     else
359       raise TypeError, "#{self.class} can only be initialized from an Array"
360     end
361   end
362
363   def inspect
364     self.__to_s__[0..-2].sub(/:[^:]+$/,"[#{@element_class}]\\0") + " #{super}>"
365   end
366
367   # Private method to check the validity of the elements passed to it
368   # and optionally raise an error
369   #
370   # TODO should it accept nils as valid?
371   #
372   def internal_will_accept?(raising, *els)
373     els.each { |el|
374       unless el.kind_of?(@element_class)
375         raise TypeError, "#{el.inspect} is not of class #{@element_class}" if raising
376         return false
377       end
378     }
379     return true
380   end
381   private :internal_will_accept?
382
383   # This method checks if the passed arguments are acceptable for our ArrayOf
384   #
385   def will_accept?(*els)
386     internal_will_accept?(false, *els)
387   end
388
389   # This method checks that all elements are of the appropriate class
390   #
391   def valid?
392     will_accept?(*self)
393   end
394
395   # This method is similar to the above, except that it raises an exception
396   # if the receiver is not valid
397   #
398   def validate
399     raise TypeError unless valid?
400   end
401
402   # Overloaded from Array#<<, checks for appropriate class of argument
403   #
404   def <<(el)
405     super(el) if internal_will_accept?(true, el)
406   end
407
408   # Overloaded from Array#&, checks for appropriate class of argument elements
409   #
410   def &(ar)
411     r = super(ar)
412     ArrayOf.new(@element_class, r) if internal_will_accept?(true, *r)
413   end
414
415   # Overloaded from Array#+, checks for appropriate class of argument elements
416   #
417   def +(ar)
418     ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)
419   end
420
421   # Overloaded from Array#-, so that an ArrayOf is returned. There is no need
422   # to check the validity of the elements in the argument
423   #
424   def -(ar)
425     ArrayOf.new(@element_class, super(ar)) # if internal_will_accept?(true, *ar)
426   end
427
428   # Overloaded from Array#|, checks for appropriate class of argument elements
429   #
430   def |(ar)
431     ArrayOf.new(@element_class, super(ar)) if internal_will_accept?(true, *ar)
432   end
433
434   # Overloaded from Array#concat, checks for appropriate class of argument
435   # elements
436   #
437   def concat(ar)
438     super(ar) if internal_will_accept?(true, *ar)
439   end
440
441   # Overloaded from Array#insert, checks for appropriate class of argument
442   # elements
443   #
444   def insert(idx, *ar)
445     super(idx, *ar) if internal_will_accept?(true, *ar)
446   end
447
448   # Overloaded from Array#replace, checks for appropriate class of argument
449   # elements
450   #
451   def replace(ar)
452     super(ar) if (ar.kind_of?(ArrayOf) && ar.element_class <= @element_class) or internal_will_accept?(true, *ar)
453   end
454
455   # Overloaded from Array#push, checks for appropriate class of argument
456   # elements
457   #
458   def push(*ar)
459     super(*ar) if internal_will_accept?(true, *ar)
460   end
461
462   # Overloaded from Array#unshift, checks for appropriate class of argument(s)
463   #
464   def unshift(*els)
465     els.each { |el|
466       super(el) if internal_will_accept?(true, *els)
467     }
468   end
469
470   # We introduce the 'downcase' method, which maps downcase() to all the Array
471   # elements, properly failing when the elements don't have a downcase method
472   #
473   def downcase
474     self.map { |el| el.downcase }
475   end
476
477   # Modifying methods which we don't handle yet are made private
478   #
479   private :[]=, :collect!, :map!, :fill, :flatten!
480
481 end
482
483
484 # We extend the Regexp class with an Irc module which will contain some
485 # Irc-specific regexps
486 #
487 class Regexp
488
489   # We start with some general-purpose ones which will be used in the
490   # Irc module too, but are useful regardless
491   DIGITS = /\d+/
492   HEX_DIGIT = /[0-9A-Fa-f]/
493   HEX_DIGITS = /#{HEX_DIGIT}+/
494   HEX_OCTET = /#{HEX_DIGIT}#{HEX_DIGIT}?/
495   DEC_OCTET = /[01]?\d?\d|2[0-4]\d|25[0-5]/
496   DEC_IP_ADDR = /#{DEC_OCTET}.#{DEC_OCTET}.#{DEC_OCTET}.#{DEC_OCTET}/
497   HEX_IP_ADDR = /#{HEX_OCTET}.#{HEX_OCTET}.#{HEX_OCTET}.#{HEX_OCTET}/
498   IP_ADDR = /#{DEC_IP_ADDR}|#{HEX_IP_ADDR}/
499
500   # IPv6, from Resolv::IPv6, without the \A..\z anchors
501   HEX_16BIT = /#{HEX_DIGIT}{1,4}/
502   IP6_8Hex = /(?:#{HEX_16BIT}:){7}#{HEX_16BIT}/
503   IP6_CompressedHex = /((?:#{HEX_16BIT}(?::#{HEX_16BIT})*)?)::((?:#{HEX_16BIT}(?::#{HEX_16BIT})*)?)/
504   IP6_6Hex4Dec = /((?:#{HEX_16BIT}:){6,6})#{DEC_IP_ADDR}/
505   IP6_CompressedHex4Dec = /((?:#{HEX_16BIT}(?::#{HEX_16BIT})*)?)::((?:#{HEX_16BIT}:)*)#{DEC_IP_ADDR}/
506   IP6_ADDR = /(?:#{IP6_8Hex})|(?:#{IP6_CompressedHex})|(?:#{IP6_6Hex4Dec})|(?:#{IP6_CompressedHex4Dec})/
507
508   # We start with some IRC related regular expressions, used to match
509   # Irc::User nicks and users and Irc::Channel names
510   #
511   # For each of them we define two versions of the regular expression:
512   # * a generic one, which should match for any server but may turn out to
513   #   match more than a specific server would accept
514   # * an RFC-compliant matcher
515   #
516   module Irc
517
518     # Channel-name-matching regexps
519     CHAN_FIRST = /[#&+]/
520     CHAN_SAFE = /![A-Z0-9]{5}/
521     CHAN_ANY = /[^\x00\x07\x0A\x0D ,:]/
522     GEN_CHAN = /(?:#{CHAN_FIRST}|#{CHAN_SAFE})#{CHAN_ANY}+/
523     RFC_CHAN = /#{CHAN_FIRST}#{CHAN_ANY}{1,49}|#{CHAN_SAFE}#{CHAN_ANY}{1,44}/
524
525     # Nick-matching regexps
526     SPECIAL_CHAR = /[\x5b-\x60\x7b-\x7d]/
527     NICK_FIRST = /#{SPECIAL_CHAR}|[[:alpha:]]/
528     NICK_ANY = /#{SPECIAL_CHAR}|[[:alnum:]]|-/
529     GEN_NICK = /#{NICK_FIRST}#{NICK_ANY}+/
530     RFC_NICK = /#{NICK_FIRST}#{NICK_ANY}{0,8}/
531
532     USER_CHAR = /[^\x00\x0a\x0d @]/
533     GEN_USER = /#{USER_CHAR}+/
534
535     # Host-matching regexps
536     HOSTNAME_COMPONENT = /[[:alnum:]](?:[[:alnum:]]|-)*[[:alnum:]]*/
537     HOSTNAME = /#{HOSTNAME_COMPONENT}(?:\.#{HOSTNAME_COMPONENT})*/
538     HOSTADDR = /#{IP_ADDR}|#{IP6_ADDR}/
539
540     GEN_HOST = /#{HOSTNAME}|#{HOSTADDR}/
541
542     # # FreeNode network replaces the host of affiliated users with
543     # # 'virtual hosts' 
544     # # FIXME we need the true syntax to match it properly ...
545     # PDPC_HOST_PART = /[0-9A-Za-z.-]+/
546     # PDPC_HOST = /#{PDPC_HOST_PART}(?:\/#{PDPC_HOST_PART})+/
547
548     # # NOTE: the final optional and non-greedy dot is needed because some
549     # # servers (e.g. FreeNode) send the hostname of the services as "services."
550     # # which is not RFC compliant, but sadly done.
551     # GEN_HOST_EXT = /#{PDPC_HOST}|#{GEN_HOST}\.??/ 
552
553     # Sadly, different networks have different, RFC-breaking ways of cloaking
554     # the actualy host address: see above for an example to handle FreeNode.
555     # Another example would be Azzurra, wich also inserts a "=" in the
556     # cloacked host. So let's just not care about this and go with the simplest
557     # thing:
558     GEN_HOST_EXT = /\S+/
559
560     # User-matching Regexp
561     GEN_USER_ID = /(#{GEN_NICK})(?:(?:!(#{GEN_USER}))?@(#{GEN_HOST_EXT}))?/
562
563     # Things such has the BIP proxy send invalid nicks in a complete netmask,
564     # so we want to match this, rather: this matches either a compliant nick
565     # or a a string with a very generic nick, a very generic hostname after an
566     # @ sign, and an optional user after a !
567     BANG_AT = /#{GEN_NICK}|\S+?(?:!\S+?)?@\S+?/
568
569     # # For Netmask, we want to allow wildcards * and ? in the nick
570     # # (they are already allowed in the user and host part
571     # GEN_NICK_MASK = /(?:#{NICK_FIRST}|[?*])?(?:#{NICK_ANY}|[?*])+/
572
573     # # Netmask-matching Regexp
574     # GEN_MASK = /(#{GEN_NICK_MASK})(?:(?:!(#{GEN_USER}))?@(#{GEN_HOST_EXT}))?/
575
576   end
577
578 end
579
580
581 module Irc
582
583
584   # A Netmask identifies each user by collecting its nick, username and
585   # hostname in the form <tt>nick!user@host</tt>
586   #
587   # Netmasks can also contain glob patterns in any of their components; in
588   # this form they are used to refer to more than a user or to a user
589   # appearing under different forms.
590   #
591   # Example:
592   # * <tt>*!*@*</tt> refers to everybody
593   # * <tt>*!someuser@somehost</tt> refers to user +someuser+ on host +somehost+
594   #   regardless of the nick used.
595   #
596   class Netmask
597
598     # Netmasks have an associated casemap unless they are bound to a server
599     #
600     include ServerOrCasemap
601
602     attr_reader :nick, :user, :host
603     alias :ident :user
604
605     # Create a new Netmask from string _str_, which must be in the form
606     # _nick_!_user_@_host_
607     #
608     # It is possible to specify a server or a casemap in the optional Hash:
609     # these are used to associate the Netmask with the given server and to set
610     # its casemap: if a server is specified and a casemap is not, the server's
611     # casemap is used. If both a server and a casemap are specified, the
612     # casemap must match the server's casemap or an exception will be raised.
613     #
614     # Empty +nick+, +user+ or +host+ are converted to the generic glob pattern
615     #
616     def initialize(str="", opts={})
617       # First of all, check for server/casemap option
618       #
619       init_server_or_casemap(opts)
620
621       # Now we can see if the given string _str_ is an actual Netmask
622       if str.respond_to?(:to_str)
623         case str.to_str
624           # We match a pretty generic string, to work around non-compliant
625           # servers
626         when /^(?:(\S+?)(?:(?:!(\S+?))?@(\S+))?)?$/
627           # We do assignment using our internal methods
628           self.nick = $1
629           self.user = $2
630           self.host = $3
631         else
632           raise ArgumentError, "#{str.to_str.inspect} does not represent a valid #{self.class}"
633         end
634       else
635         raise TypeError, "#{str} cannot be converted to a #{self.class}"
636       end
637     end
638
639     # A Netmask is easily converted to a String for the usual representation.
640     # We skip the user or host parts if they are "*", unless we've been asked
641     # for the full form
642     #
643     def to_s
644       ret = nick.dup
645       ret << "!" << user unless user == "*"
646       ret << "@" << host unless host == "*"
647       return ret
648     end
649
650     def fullform
651       "#{nick}!#{user}@#{host}"
652     end
653
654     alias :to_str :fullform
655
656     # This method downcases the fullform of the netmask. While this may not be
657     # significantly different from the #downcase() method provided by the
658     # ServerOrCasemap mixin, it's significantly different for Netmask
659     # subclasses such as User whose simple downcasing uses the nick only.
660     #
661     def full_irc_downcase(cmap=casemap)
662       self.fullform.irc_downcase(cmap)
663     end
664
665     # full_downcase() will return the fullform downcased according to the
666     # User's own casemap
667     #
668     def full_downcase
669       self.full_irc_downcase
670     end
671
672     # This method returns a new Netmask which is the fully downcased version
673     # of the receiver
674     def downcased
675       return self.full_downcase.to_irc_netmask(server_and_casemap)
676     end
677
678     # Converts the receiver into a Netmask with the given (optional)
679     # server/casemap association. We return self unless a conversion
680     # is needed (different casemap/server)
681     #
682     # Subclasses of Netmask will return a new Netmask, using full_downcase
683     #
684     def to_irc_netmask(opts={})
685       if self.class == Netmask
686         return self if fits_with_server_and_casemap?(opts)
687       end
688       return self.full_downcase.to_irc_netmask(server_and_casemap.merge(opts))
689     end
690
691     # Converts the receiver into a User with the given (optional)
692     # server/casemap association. We return self unless a conversion
693     # is needed (different casemap/server)
694     #
695     def to_irc_user(opts={})
696       self.fullform.to_irc_user(server_and_casemap.merge(opts))
697     end
698
699     # Inspection of a Netmask reveals the server it's bound to (if there is
700     # one), its casemap and the nick, user and host part
701     #
702     def inspect
703       str = self.__to_s__[0..-2]
704       str << " @server=#{@server}" if defined?(@server) and @server
705       str << " @nick=#{@nick.inspect} @user=#{@user.inspect}"
706       str << " @host=#{@host.inspect} casemap=#{casemap.inspect}"
707       str << ">"
708     end
709
710     # Equality: two Netmasks are equal if they downcase to the same thing
711     #
712     # TODO we may want it to try other.to_irc_netmask
713     #
714     def ==(other)
715       return false unless other.kind_of?(self.class)
716       self.downcase == other.downcase
717     end
718
719     # This method changes the nick of the Netmask, defaulting to the generic
720     # glob pattern if the result is the null string.
721     #
722     def nick=(newnick)
723       @nick = newnick.to_s
724       @nick = "*" if @nick.empty?
725     end
726
727     # This method changes the user of the Netmask, defaulting to the generic
728     # glob pattern if the result is the null string.
729     #
730     def user=(newuser)
731       @user = newuser.to_s
732       @user = "*" if @user.empty?
733     end
734     alias :ident= :user=
735
736     # This method changes the hostname of the Netmask, defaulting to the generic
737     # glob pattern if the result is the null string.
738     #
739     def host=(newhost)
740       @host = newhost.to_s
741       @host = "*" if @host.empty?
742     end
743
744     # We can replace everything at once with data from another Netmask
745     #
746     def replace(other)
747       case other
748       when Netmask
749         nick = other.nick
750         user = other.user
751         host = other.host
752         @server = other.server
753         @casemap = other.casemap unless @server
754       else
755         replace(other.to_irc_netmask(server_and_casemap))
756       end
757     end
758
759     # This method checks if a Netmask is definite or not, by seeing if
760     # any of its components are defined by globs
761     #
762     def has_irc_glob?
763       return @nick.has_irc_glob? || @user.has_irc_glob? || @host.has_irc_glob?
764     end
765
766     def generalize
767       u = user.dup
768       unless u.has_irc_glob?
769         u.sub!(/^[in]=/, '=') or u.sub!(/^\W(\w+)/, '\1')
770         u = '*' + u
771       end
772
773       h = host.dup
774       unless h.has_irc_glob?
775         if h.include? '/'
776           h.sub!(/x-\w+$/, 'x-*')
777         else
778           h.match(/^[^\.]+\.[^\.]+$/) or
779           h.sub!(/azzurra[=-][0-9a-f]+/i, '*') or # hello, azzurra, you suck!
780           h.sub!(/^(\d+\.\d+\.\d+\.)\d+$/, '\1*') or
781           h.sub!(/^[^\.]+\./, '*.')
782         end
783       end
784       return Netmask.new("*!#{u}@#{h}", server_and_casemap)
785     end
786
787     # This method is used to match the current Netmask against another one
788     #
789     # The method returns true if each component of the receiver matches the
790     # corresponding component of the argument. By _matching_ here we mean
791     # that any netmask described by the receiver is also described by the
792     # argument.
793     #
794     # In this sense, matching is rather simple to define in the case when the
795     # receiver has no globs: it is just necessary to check if the argument
796     # describes the receiver, which can be done by matching it against the
797     # argument converted into an IRC Regexp (see String#to_irc_regexp).
798     #
799     # The situation is also easy when the receiver has globs and the argument
800     # doesn't, since in this case the result is false.
801     #
802     # The more complex case in which both the receiver and the argument have
803     # globs is not handled yet.
804     #
805     def matches?(arg)
806       cmp = arg.to_irc_netmask(:casemap => casemap)
807       debug "Matching #{self.fullform} against #{arg.inspect} (#{cmp.fullform})"
808       [:nick, :user, :host].each { |component|
809         us = self.send(component).irc_downcase(casemap)
810         them = cmp.send(component).irc_downcase(casemap)
811         if us.has_irc_glob? && them.has_irc_glob?
812           next if us == them
813           warn NotImplementedError
814           return false
815         end
816         return false if us.has_irc_glob? && !them.has_irc_glob?
817         return false unless us =~ them.to_irc_regexp
818       }
819       return true
820     end
821
822     # Case equality. Checks if arg matches self
823     #
824     def ===(arg)
825       arg.to_irc_netmask(:casemap => casemap).matches?(self)
826     end
827
828     # Sorting is done via the fullform
829     #
830     def <=>(arg)
831       case arg
832       when Netmask
833         self.fullform.irc_downcase(casemap) <=> arg.fullform.irc_downcase(casemap)
834       else
835         self.downcase <=> arg.downcase
836       end
837     end
838
839   end
840
841
842   # A NetmaskList is an ArrayOf <code>Netmask</code>s
843   #
844   class NetmaskList < ArrayOf
845
846     # Create a new NetmaskList, optionally filling it with the elements from
847     # the Array argument fed to it.
848     #
849     def initialize(ar=[])
850       super(Netmask, ar)
851     end
852
853     # We enhance the [] method by allowing it to pick an element that matches
854     # a given Netmask, a String or a Regexp
855     # TODO take into consideration the opportunity to use select() instead of
856     # find(), and/or a way to let the user choose which one to take (second
857     # argument?)
858     #
859     def [](*args)
860       if args.length == 1
861         case args[0]
862         when Netmask
863           self.find { |mask|
864             mask.matches?(args[0])
865           }
866         when String
867           self.find { |mask|
868             mask.matches?(args[0].to_irc_netmask(:casemap => mask.casemap))
869           }
870         when Regexp
871           self.find { |mask|
872             mask.fullform =~ args[0]
873           }
874         else
875           super(*args)
876         end
877       else
878         super(*args)
879       end
880     end
881
882   end
883
884 end
885
886
887 class String
888
889   # We keep extending String, this time adding a method that converts a
890   # String into an Irc::Netmask object
891   #
892   def to_irc_netmask(opts={})
893     Irc::Netmask.new(self, opts)
894   end
895
896 end
897
898
899 module Irc
900
901
902   # An IRC User is identified by his/her Netmask (which must not have globs).
903   # In fact, User is just a subclass of Netmask.
904   #
905   # Ideally, the user and host information of an IRC User should never
906   # change, and it shouldn't contain glob patterns. However, IRC is somewhat
907   # idiosincratic and it may be possible to know the nick of a User much before
908   # its user and host are known. Moreover, some networks (namely Freenode) may
909   # change the hostname of a User when (s)he identifies with Nickserv.
910   #
911   # As a consequence, we must allow changes to a User host and user attributes.
912   # We impose a restriction, though: they may not contain glob patterns, except
913   # for the special case of an unknown user/host which is represented by a *.
914   #
915   # It is possible to create a totally unknown User (e.g. for initializations)
916   # by setting the nick to * too.
917   #
918   # TODO list:
919   # * see if it's worth to add the other USER data
920   # * see if it's worth to add NICKSERV status
921   #
922   class User < Netmask
923     alias :to_s :nick
924
925     attr_accessor :real_name
926
927     # Create a new IRC User from a given Netmask (or anything that can be converted
928     # into a Netmask) provided that the given Netmask does not have globs.
929     #
930     def initialize(str="", opts={})
931       super
932       raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if nick.has_irc_glob? && nick != "*"
933       raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if user.has_irc_glob? && user != "*"
934       raise ArgumentError, "#{str.inspect} must not have globs (unescaped * or ?)" if host.has_irc_glob? && host != "*"
935       @away = false
936       @real_name = String.new
937     end
938
939     # The nick of a User may be changed freely, but it must not contain glob patterns.
940     #
941     def nick=(newnick)
942       raise "Can't change the nick to #{newnick}" if defined?(@nick) and newnick.has_irc_glob?
943       super
944     end
945
946     # We have to allow changing the user of an Irc User due to some networks
947     # (e.g. Freenode) changing hostmasks on the fly. We still check if the new
948     # user data has glob patterns though.
949     #
950     def user=(newuser)
951       raise "Can't change the username to #{newuser}" if defined?(@user) and newuser.has_irc_glob?
952       super
953     end
954
955     # We have to allow changing the host of an Irc User due to some networks
956     # (e.g. Freenode) changing hostmasks on the fly. We still check if the new
957     # host data has glob patterns though.
958     #
959     def host=(newhost)
960       raise "Can't change the hostname to #{newhost}" if defined?(@host) and newhost.has_irc_glob?
961       super
962     end
963
964     # Checks if a User is well-known or not by looking at the hostname and user
965     #
966     def known?
967       return nick != "*" && user != "*" && host != "*"
968     end
969
970     # Is the user away?
971     #
972     def away?
973       return @away
974     end
975
976     # Set the away status of the user. Use away=(nil) or away=(false)
977     # to unset away
978     #
979     def away=(msg="")
980       if msg
981         @away = msg
982       else
983         @away = false
984       end
985     end
986
987     # Since to_irc_user runs the same checks on server and channel as
988     # to_irc_netmask, we just try that and return self if it works.
989     #
990     # Subclasses of User will return self if possible.
991     #
992     def to_irc_user(opts={})
993       return self if fits_with_server_and_casemap?(opts)
994       return self.full_downcase.to_irc_user(opts)
995     end
996
997     # We can replace everything at once with data from another User
998     #
999     def replace(other)
1000       case other
1001       when User
1002         self.nick = other.nick
1003         self.user = other.user
1004         self.host = other.host
1005         @server = other.server
1006         @casemap = other.casemap unless @server
1007         @away = other.away?
1008       else
1009         self.replace(other.to_irc_user(server_and_casemap))
1010       end
1011     end
1012
1013     def modes_on(channel)
1014       case channel
1015       when Channel
1016         channel.modes_of(self)
1017       else
1018         return @server.channel(channel).modes_of(self) if @server
1019         raise "Can't resolve channel #{channel}"
1020       end
1021     end
1022
1023     def is_op?(channel)
1024       case channel
1025       when Channel
1026         channel.has_op?(self)
1027       else
1028         return @server.channel(channel).has_op?(self) if @server
1029         raise "Can't resolve channel #{channel}"
1030       end
1031     end
1032
1033     def is_voice?(channel)
1034       case channel
1035       when Channel
1036         channel.has_voice?(self)
1037       else
1038         return @server.channel(channel).has_voice?(self) if @server
1039         raise "Can't resolve channel #{channel}"
1040       end
1041     end
1042   end
1043
1044
1045   # A UserList is an ArrayOf <code>User</code>s
1046   # We derive it from NetmaskList, which allows us to inherit any special
1047   # NetmaskList method
1048   #
1049   class UserList < NetmaskList
1050
1051     # Create a new UserList, optionally filling it with the elements from
1052     # the Array argument fed to it.
1053     #
1054     def initialize(ar=[])
1055       super(ar)
1056       @element_class = User
1057     end
1058
1059     # Convenience method: convert the UserList to a list of nicks. The indices
1060     # are preserved
1061     #
1062     def nicks
1063       self.map { |user| user.nick }
1064     end
1065
1066   end
1067
1068 end
1069
1070 class String
1071
1072   # We keep extending String, this time adding a method that converts a
1073   # String into an Irc::User object
1074   #
1075   def to_irc_user(opts={})
1076     Irc::User.new(self, opts)
1077   end
1078
1079 end
1080
1081 module Irc
1082
1083   # An IRC Channel is identified by its name, and it has a set of properties:
1084   # * a Channel::Topic
1085   # * a UserList
1086   # * a set of Channel::Modes
1087   #
1088   # The Channel::Topic and Channel::Mode classes are defined within the
1089   # Channel namespace because they only make sense there
1090   #
1091   class Channel
1092
1093
1094     # Mode on a Channel
1095     #
1096     class Mode
1097       attr_reader :channel
1098       def initialize(ch)
1099         @channel = ch
1100       end
1101
1102     end
1103
1104
1105     # Channel modes of type A manipulate lists
1106     #
1107     # Example: b (banlist)
1108     #
1109     class ModeTypeA < Mode
1110       attr_reader :list
1111       def initialize(ch)
1112         super
1113         @list = NetmaskList.new
1114       end
1115
1116       def set(val)
1117         nm = @channel.server.new_netmask(val)
1118         @list << nm unless @list.include?(nm)
1119       end
1120
1121       def reset(val)
1122         nm = @channel.server.new_netmask(val)
1123         @list.delete(nm)
1124       end
1125
1126     end
1127
1128
1129     # Channel modes of type B need an argument
1130     #
1131     # Example: k (key)
1132     #
1133     class ModeTypeB < Mode
1134       def initialize(ch)
1135         super
1136         @arg = nil
1137       end
1138
1139       def status
1140         @arg
1141       end
1142       alias :value :status
1143
1144       def set(val)
1145         @arg = val
1146       end
1147
1148       def reset(val)
1149         @arg = nil if @arg == val
1150       end
1151
1152     end
1153
1154
1155     # Channel modes that change the User prefixes are like
1156     # Channel modes of type B, except that they manipulate
1157     # lists of Users, so they are somewhat similar to channel
1158     # modes of type A
1159     #
1160     class UserMode < ModeTypeB
1161       attr_reader :list
1162       alias :users :list
1163       def initialize(ch)
1164         super
1165         @list = UserList.new
1166       end
1167
1168       def set(val)
1169         u = @channel.server.user(val)
1170         @list << u unless @list.include?(u)
1171       end
1172
1173       def reset(val)
1174         u = @channel.server.user(val)
1175         @list.delete(u)
1176       end
1177
1178     end
1179
1180
1181     # Channel modes of type C need an argument when set,
1182     # but not when they get reset
1183     #
1184     # Example: l (limit)
1185     #
1186     class ModeTypeC < Mode
1187       def initialize(ch)
1188         super
1189         @arg = nil
1190       end
1191
1192       def status
1193         @arg
1194       end
1195       alias :value :status
1196
1197       def set(val)
1198         @arg = val
1199       end
1200
1201       def reset
1202         @arg = nil
1203       end
1204
1205     end
1206
1207
1208     # Channel modes of type D are basically booleans
1209     #
1210     # Example: m (moderate)
1211     #
1212     class ModeTypeD < Mode
1213       def initialize(ch)
1214         super
1215         @set = false
1216       end
1217
1218       def set?
1219         return @set
1220       end
1221
1222       def set
1223         @set = true
1224       end
1225
1226       def reset
1227         @set = false
1228       end
1229
1230     end
1231
1232
1233     # A Topic represents the topic of a channel. It consists of
1234     # the topic itself, who set it and when
1235     #
1236     class Topic
1237       attr_accessor :text, :set_by, :set_on
1238       alias :to_s :text
1239
1240       # Create a new Topic setting the text, the creator and
1241       # the creation time
1242       #
1243       def initialize(text="", set_by="", set_on=Time.new)
1244         @text = text
1245         @set_by = set_by.to_irc_netmask
1246         @set_on = set_on
1247       end
1248
1249       # Replace a Topic with another one
1250       #
1251       def replace(topic)
1252         raise TypeError, "#{topic.inspect} is not of class #{self.class}" unless topic.kind_of?(self.class)
1253         @text = topic.text.dup
1254         @set_by = topic.set_by.dup
1255         @set_on = topic.set_on.dup
1256       end
1257
1258       # Returns self
1259       #
1260       def to_irc_channel_topic
1261         self
1262       end
1263
1264     end
1265
1266   end
1267
1268 end
1269
1270
1271 class String
1272
1273   # Returns an Irc::Channel::Topic with self as text
1274   #
1275   def to_irc_channel_topic
1276     Irc::Channel::Topic.new(self)
1277   end
1278
1279 end
1280
1281
1282 module Irc
1283
1284
1285   # Here we start with the actual Channel class
1286   #
1287   class Channel
1288
1289     include ServerOrCasemap
1290     attr_reader :name, :topic, :mode, :users
1291     alias :to_s :name
1292
1293     def inspect
1294       str = self.__to_s__[0..-2]
1295       str << " on server #{server}" if server
1296       str << " @name=#{@name.inspect} @topic=#{@topic.text.inspect}"
1297       str << " @users=[#{user_nicks.sort.join(', ')}]"
1298       str << ">"
1299     end
1300
1301     # Returns self
1302     #
1303     def to_irc_channel
1304       self
1305     end
1306
1307     # TODO Ho
1308     def user_nicks
1309       @users.map { |u| u.downcase }
1310     end
1311
1312     # Checks if the receiver already has a user with the given _nick_
1313     #
1314     def has_user?(nick)
1315       @users.index(nick.to_irc_user(server_and_casemap))
1316     end
1317
1318     # Returns the user with nick _nick_, if available
1319     #
1320     def get_user(nick)
1321       idx = has_user?(nick)
1322       @users[idx] if idx
1323     end
1324
1325     # Adds a user to the channel
1326     #
1327     def add_user(user, opts={})
1328       silent = opts.fetch(:silent, false) 
1329       if has_user?(user)
1330         warn "Trying to add user #{user} to channel #{self} again" unless silent
1331       else
1332         @users << user.to_irc_user(server_and_casemap)
1333       end
1334     end
1335
1336     # Creates a new channel with the given name, optionally setting the topic
1337     # and an initial users list.
1338     #
1339     # No additional info is created here, because the channel flags and userlists
1340     # allowed depend on the server.
1341     #
1342     def initialize(name, topic=nil, users=[], opts={})
1343       raise ArgumentError, "Channel name cannot be empty" if name.to_s.empty?
1344       warn "Unknown channel prefix #{name[0].chr}" if name !~ /^[&#+!]/
1345       raise ArgumentError, "Invalid character in #{name.inspect}" if name =~ /[ \x07,]/
1346
1347       init_server_or_casemap(opts)
1348
1349       @name = name
1350
1351       @topic = topic ? topic.to_irc_channel_topic : Channel::Topic.new
1352
1353       @users = UserList.new
1354
1355       users.each { |u|
1356         add_user(u)
1357       }
1358
1359       # Flags
1360       @mode = {}
1361     end
1362
1363     # Removes a user from the channel
1364     #
1365     def delete_user(user)
1366       @mode.each { |sym, mode|
1367         mode.reset(user) if mode.kind_of?(UserMode)
1368       }
1369       @users.delete(user)
1370     end
1371
1372     # The channel prefix
1373     #
1374     def prefix
1375       name[0].chr
1376     end
1377
1378     # A channel is local to a server if it has the '&' prefix
1379     #
1380     def local?
1381       name[0] == 0x26
1382     end
1383
1384     # A channel is modeless if it has the '+' prefix
1385     #
1386     def modeless?
1387       name[0] == 0x2b
1388     end
1389
1390     # A channel is safe if it has the '!' prefix
1391     #
1392     def safe?
1393       name[0] == 0x21
1394     end
1395
1396     # A channel is normal if it has the '#' prefix
1397     #
1398     def normal?
1399       name[0] == 0x23
1400     end
1401
1402     # Create a new mode
1403     #
1404     def create_mode(sym, kl)
1405       @mode[sym.to_sym] = kl.new(self)
1406     end
1407
1408     def modes_of(user)
1409       l = []
1410       @mode.map { |s, m|
1411         l << s if (m.class <= UserMode and m.list[user])
1412       }
1413       l
1414     end
1415
1416     def has_op?(user)
1417       @mode.has_key?(:o) and @mode[:o].list[user]
1418     end
1419
1420     def has_voice?(user)
1421       @mode.has_key?(:v) and @mode[:v].list[user]
1422     end
1423   end
1424
1425
1426   # A ChannelList is an ArrayOf <code>Channel</code>s
1427   #
1428   class ChannelList < ArrayOf
1429
1430     # Create a new ChannelList, optionally filling it with the elements from
1431     # the Array argument fed to it.
1432     #
1433     def initialize(ar=[])
1434       super(Channel, ar)
1435     end
1436
1437     # Convenience method: convert the ChannelList to a list of channel names.
1438     # The indices are preserved
1439     #
1440     def names
1441       self.map { |chan| chan.name }
1442     end
1443
1444   end
1445
1446 end
1447
1448
1449 class String
1450
1451   # We keep extending String, this time adding a method that converts a
1452   # String into an Irc::Channel object
1453   #
1454   def to_irc_channel(opts={})
1455     Irc::Channel.new(self, opts)
1456   end
1457
1458 end
1459
1460
1461 module Irc
1462
1463
1464   # An IRC Server represents the Server the client is connected to.
1465   #
1466   class Server
1467
1468     attr_reader :hostname, :version, :usermodes, :chanmodes
1469     alias :to_s :hostname
1470     attr_reader :supports, :capabilities
1471
1472     attr_reader :channels, :users
1473
1474     # TODO Ho
1475     def channel_names
1476       @channels.map { |ch| ch.downcase }
1477     end
1478
1479     # TODO Ho
1480     def user_nicks
1481       @users.map { |u| u.downcase }
1482     end
1483
1484     def inspect
1485       chans, users = [@channels, @users].map {|d|
1486         d.sort { |a, b|
1487           a.downcase <=> b.downcase
1488         }.map { |x|
1489           x.inspect
1490         }
1491       }
1492
1493       str = self.__to_s__[0..-2]
1494       str << " @hostname=#{hostname}"
1495       str << " @channels=#{chans}"
1496       str << " @users=#{users}"
1497       str << ">"
1498     end
1499
1500     # Create a new Server, with all instance variables reset to nil (for
1501     # scalar variables), empty channel and user lists and @supports
1502     # initialized to the default values for all known supported features.
1503     #
1504     def initialize
1505       @hostname = @version = @usermodes = @chanmodes = nil
1506
1507       @channels = ChannelList.new
1508
1509       @users = UserList.new
1510
1511       reset_capabilities
1512     end
1513
1514     # Resets the server capabilities
1515     #
1516     def reset_capabilities
1517       @supports = {
1518         :casemapping => 'rfc1459'.to_irc_casemap,
1519         :chanlimit => {},
1520         :chanmodes => {
1521           :typea => nil, # Type A: address lists
1522           :typeb => nil, # Type B: needs a parameter
1523           :typec => nil, # Type C: needs a parameter when set
1524           :typed => nil  # Type D: must not have a parameter
1525         },
1526         :channellen => 50,
1527         :chantypes => "#&!+",
1528         :excepts => nil,
1529         :idchan => {},
1530         :invex => nil,
1531         :kicklen => nil,
1532         :maxlist => {},
1533         :modes => 3,
1534         :network => nil,
1535         :nicklen => 9,
1536         :prefix => {
1537           :modes => [:o, :v],
1538           :prefixes => [:"@", :+]
1539         },
1540         :safelist => nil,
1541         :statusmsg => nil,
1542         :std => nil,
1543         :targmax => {},
1544         :topiclen => nil
1545       }
1546       @capabilities = {}
1547     end
1548
1549     # Convert a mode (o, v, h, ...) to the corresponding
1550     # prefix (@, +, %, ...). See also mode_for_prefix
1551     def prefix_for_mode(mode)
1552       return @supports[:prefix][:prefixes][
1553         @supports[:prefix][:modes].index(mode.to_sym)
1554       ]
1555     end
1556
1557     # Convert a prefix (@, +, %, ...) to the corresponding
1558     # mode (o, v, h, ...). See also prefix_for_mode
1559     def mode_for_prefix(pfx)
1560       return @supports[:prefix][:modes][
1561         @supports[:prefix][:prefixes].index(pfx.to_sym)
1562       ]
1563     end
1564
1565     # Resets the Channel and User list
1566     #
1567     def reset_lists
1568       @users.reverse_each { |u|
1569         delete_user(u)
1570       }
1571       @channels.reverse_each { |u|
1572         delete_channel(u)
1573       }
1574     end
1575
1576     # Clears the server
1577     #
1578     def clear
1579       reset_lists
1580       reset_capabilities
1581       @hostname = @version = @usermodes = @chanmodes = nil
1582     end
1583
1584     # This method is used to parse a 004 RPL_MY_INFO line
1585     #
1586     def parse_my_info(line)
1587       ar = line.split(' ')
1588       @hostname = ar[0]
1589       @version = ar[1]
1590       @usermodes = ar[2]
1591       @chanmodes = ar[3]
1592     end
1593
1594     def noval_warn(key, val, &block)
1595       if val
1596         yield if block_given?
1597       else
1598         warn "No #{key.to_s.upcase} value"
1599       end
1600     end
1601
1602     def val_warn(key, val, &block)
1603       if val == true or val == false or val.nil?
1604         yield if block_given?
1605       else
1606         warn "No #{key.to_s.upcase} value must be specified, got #{val}"
1607       end
1608     end
1609     private :noval_warn, :val_warn
1610
1611     # This method is used to parse a 005 RPL_ISUPPORT line
1612     #
1613     # See the RPL_ISUPPORT draft[http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt]
1614     #
1615     def parse_isupport(line)
1616       debug "Parsing ISUPPORT #{line.inspect}"
1617       ar = line.split(' ')
1618       reparse = ""
1619       ar.each { |en|
1620         prekey, val = en.split('=', 2)
1621         if prekey =~ /^-(.*)/
1622           key = $1.downcase.to_sym
1623           val = false
1624         else
1625           key = prekey.downcase.to_sym
1626         end
1627         case key
1628         when :casemapping
1629           noval_warn(key, val) {
1630             @supports[key] = val.to_irc_casemap
1631           }
1632         when :chanlimit, :idchan, :maxlist, :targmax
1633           noval_warn(key, val) {
1634             groups = val.split(',')
1635             groups.each { |g|
1636               k, v = g.split(':')
1637               @supports[key][k] = v.to_i || 0
1638               if @supports[key][k] == 0
1639                 warn "Deleting #{key} limit of 0 for #{k}"
1640                 @supports[key].delete(k)
1641               end
1642             }
1643           }
1644         when :chanmodes
1645           noval_warn(key, val) {
1646             groups = val.split(',')
1647             @supports[key][:typea] = groups[0].scan(/./).map { |x| x.to_sym}
1648             @supports[key][:typeb] = groups[1].scan(/./).map { |x| x.to_sym}
1649             @supports[key][:typec] = groups[2].scan(/./).map { |x| x.to_sym}
1650             @supports[key][:typed] = groups[3].scan(/./).map { |x| x.to_sym}
1651           }
1652         when :channellen, :kicklen, :modes, :topiclen
1653           if val
1654             @supports[key] = val.to_i
1655           else
1656             @supports[key] = nil
1657           end
1658         when :chantypes
1659           @supports[key] = val # can also be nil
1660         when :excepts
1661           val ||= 'e'
1662           @supports[key] = val
1663         when :invex
1664           val ||= 'I'
1665           @supports[key] = val
1666         when :maxchannels
1667           noval_warn(key, val) {
1668             reparse += "CHANLIMIT=(chantypes):#{val} "
1669           }
1670         when :maxtargets
1671           noval_warn(key, val) {
1672             @supports[:targmax]['PRIVMSG'] = val.to_i
1673             @supports[:targmax]['NOTICE'] = val.to_i
1674           }
1675         when :network
1676           noval_warn(key, val) {
1677             @supports[key] = val
1678           }
1679         when :nicklen
1680           noval_warn(key, val) {
1681             @supports[key] = val.to_i
1682           }
1683         when :prefix
1684           if val
1685             val.scan(/\((.*)\)(.*)/) { |m, p|
1686               @supports[key][:modes] = m.scan(/./).map { |x| x.to_sym}
1687               @supports[key][:prefixes] = p.scan(/./).map { |x| x.to_sym}
1688             }
1689           else
1690             @supports[key][:modes] = nil
1691             @supports[key][:prefixes] = nil
1692           end
1693         when :safelist
1694           val_warn(key, val) {
1695             @supports[key] = val.nil? ? true : val
1696           }
1697         when :statusmsg
1698           noval_warn(key, val) {
1699             @supports[key] = val.scan(/./)
1700           }
1701         when :std
1702           noval_warn(key, val) {
1703             @supports[key] = val.split(',')
1704           }
1705         else
1706           @supports[key] =  val.nil? ? true : val
1707         end
1708       }
1709       reparse.gsub!("(chantypes)",@supports[:chantypes])
1710       parse_isupport(reparse) unless reparse.empty?
1711     end
1712
1713     # Returns the casemap of the server.
1714     #
1715     def casemap
1716       @supports[:casemapping]
1717     end
1718
1719     # Returns User or Channel depending on what _name_ can be
1720     # a name of
1721     #
1722     def user_or_channel?(name)
1723       if supports[:chantypes].include?(name[0])
1724         return Channel
1725       else
1726         return User
1727       end
1728     end
1729
1730     # Returns the actual User or Channel object matching _name_
1731     #
1732     def user_or_channel(name)
1733       if supports[:chantypes].include?(name[0])
1734         return channel(name)
1735       else
1736         return user(name)
1737       end
1738     end
1739
1740     # Checks if the receiver already has a channel with the given _name_
1741     #
1742     def has_channel?(name)
1743       return false if name.nil_or_empty?
1744       channel_names.index(name.irc_downcase(casemap))
1745     end
1746     alias :has_chan? :has_channel?
1747
1748     # Returns the channel with name _name_, if available
1749     #
1750     def get_channel(name)
1751       return nil if name.nil_or_empty?
1752       idx = has_channel?(name)
1753       channels[idx] if idx
1754     end
1755     alias :get_chan :get_channel
1756
1757     # Create a new Channel object bound to the receiver and add it to the
1758     # list of <code>Channel</code>s on the receiver, unless the channel was
1759     # present already. In this case, the default action is to raise an
1760     # exception, unless _fails_ is set to false.  An exception can also be
1761     # raised if _str_ is nil or empty, again only if _fails_ is set to true;
1762     # otherwise, the method just returns nil
1763     #
1764     def new_channel(name, topic=nil, users=[], fails=true)
1765       if name.nil_or_empty?
1766         raise "Tried to look for empty or nil channel name #{name.inspect}" if fails
1767         return nil
1768       end
1769       ex = get_chan(name)
1770       if ex
1771         raise "Channel #{name} already exists on server #{self}" if fails
1772         return ex
1773       else
1774
1775         prefix = name[0].chr
1776
1777         # Give a warning if the new Channel goes over some server limits.
1778         #
1779         # FIXME might need to raise an exception
1780         #
1781         warn "#{self} doesn't support channel prefix #{prefix}" unless @supports[:chantypes].include?(prefix)
1782         warn "#{self} doesn't support channel names this long (#{name.length} > #{@supports[:channellen]})" unless name.length <= @supports[:channellen]
1783
1784         # Next, we check if we hit the limit for channels of type +prefix+
1785         # if the server supports +chanlimit+
1786         #
1787         @supports[:chanlimit].keys.each { |k|
1788           next unless k.include?(prefix)
1789           count = 0
1790           channel_names.each { |n|
1791             count += 1 if k.include?(n[0])
1792           }
1793           # raise IndexError, "Already joined #{count} channels with prefix #{k}" if count == @supports[:chanlimit][k]
1794           warn "Already joined #{count}/#{@supports[:chanlimit][k]} channels with prefix #{k}, we may be going over server limits" if count >= @supports[:chanlimit][k]
1795         }
1796
1797         # So far, everything is fine. Now create the actual Channel
1798         #
1799         chan = Channel.new(name, topic, users, :server => self)
1800
1801         # We wade through +prefix+ and +chanmodes+ to create appropriate
1802         # lists and flags for this channel
1803
1804         @supports[:prefix][:modes].each { |mode|
1805           chan.create_mode(mode, Channel::UserMode)
1806         } if @supports[:prefix][:modes]
1807
1808         @supports[:chanmodes].each { |k, val|
1809           if val
1810             case k
1811             when :typea
1812               val.each { |mode|
1813                 chan.create_mode(mode, Channel::ModeTypeA)
1814               }
1815             when :typeb
1816               val.each { |mode|
1817                 chan.create_mode(mode, Channel::ModeTypeB)
1818               }
1819             when :typec
1820               val.each { |mode|
1821                 chan.create_mode(mode, Channel::ModeTypeC)
1822               }
1823             when :typed
1824               val.each { |mode|
1825                 chan.create_mode(mode, Channel::ModeTypeD)
1826               }
1827             end
1828           end
1829         }
1830
1831         @channels << chan
1832         # debug "Created channel #{chan.inspect}"
1833         return chan
1834       end
1835     end
1836
1837     # Returns the Channel with the given _name_ on the server,
1838     # creating it if necessary. This is a short form for
1839     # new_channel(_str_, nil, [], +false+)
1840     #
1841     def channel(str)
1842       new_channel(str,nil,[],false)
1843     end
1844
1845     # Remove Channel _name_ from the list of <code>Channel</code>s
1846     #
1847     def delete_channel(name)
1848       idx = has_channel?(name)
1849       raise "Tried to remove unmanaged channel #{name}" unless idx
1850       @channels.delete_at(idx)
1851     end
1852
1853     # Checks if the receiver already has a user with the given _nick_
1854     #
1855     def has_user?(nick)
1856       return false if nick.nil_or_empty?
1857       user_nicks.index(nick.irc_downcase(casemap))
1858     end
1859
1860     # Returns the user with nick _nick_, if available
1861     #
1862     def get_user(nick)
1863       idx = has_user?(nick)
1864       @users[idx] if idx
1865     end
1866
1867     # Create a new User object bound to the receiver and add it to the list
1868     # of <code>User</code>s on the receiver, unless the User was present
1869     # already. In this case, the default action is to raise an exception,
1870     # unless _fails_ is set to false. An exception can also be raised
1871     # if _str_ is nil or empty, again only if _fails_ is set to true;
1872     # otherwise, the method just returns nil
1873     #
1874     def new_user(str, fails=true)
1875       if str.nil_or_empty?
1876         raise "Tried to look for empty or nil user name #{str.inspect}" if fails
1877         return nil
1878       end
1879       tmp = str.to_irc_user(:server => self)
1880       old = get_user(tmp.nick)
1881       # debug "Tmp: #{tmp.inspect}"
1882       # debug "Old: #{old.inspect}"
1883       if old
1884         # debug "User already existed as #{old.inspect}"
1885         if tmp.known?
1886           if old.known?
1887             # debug "Both were known"
1888             # Do not raise an error: things like Freenode change the hostname after identification
1889             warning "User #{tmp.nick} has inconsistent Netmasks! #{self} knows #{old.inspect} but access was tried with #{tmp.inspect}" if old != tmp
1890             raise "User #{tmp} already exists on server #{self}" if fails
1891           end
1892           if old.fullform.downcase != tmp.fullform.downcase
1893             old.replace(tmp)
1894             # debug "Known user now #{old.inspect}"
1895           end
1896         end
1897         return old
1898       else
1899         warn "#{self} doesn't support nicknames this long (#{tmp.nick.length} > #{@supports[:nicklen]})" unless tmp.nick.length <= @supports[:nicklen]
1900         @users << tmp
1901         return @users.last
1902       end
1903     end
1904
1905     # Returns the User with the given Netmask on the server,
1906     # creating it if necessary. This is a short form for
1907     # new_user(_str_, +false+)
1908     #
1909     def user(str)
1910       new_user(str, false)
1911     end
1912
1913     # Deletes User _user_ from Channel _channel_
1914     #
1915     def delete_user_from_channel(user, channel)
1916       channel.delete_user(user)
1917     end
1918
1919     # Remove User _someuser_ from the list of <code>User</code>s.
1920     # _someuser_ must be specified with the full Netmask.
1921     #
1922     def delete_user(someuser)
1923       idx = has_user?(someuser)
1924       raise "Tried to remove unmanaged user #{user}" unless idx
1925       have = self.user(someuser)
1926       @channels.each { |ch|
1927         delete_user_from_channel(have, ch)
1928       }
1929       @users.delete_at(idx)
1930     end
1931
1932     # Create a new Netmask object with the appropriate casemap
1933     #
1934     def new_netmask(str)
1935       str.to_irc_netmask(:server => self)
1936     end
1937
1938     # Finds all <code>User</code>s on server whose Netmask matches _mask_
1939     #
1940     def find_users(mask)
1941       nm = new_netmask(mask)
1942       @users.inject(UserList.new) {
1943         |list, user|
1944         if user.user == "*" or user.host == "*"
1945           list << user if user.nick.irc_downcase(casemap) =~ nm.nick.irc_downcase(casemap).to_irc_regexp
1946         else
1947           list << user if user.matches?(nm)
1948         end
1949         list
1950       }
1951     end
1952
1953   end
1954
1955 end
1956