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