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