4 # Calculate the penalty which will be assigned to this message
7 # According to eggrdop, the initial penalty is
8 penalty = 1 + self.size/100
9 # on everything but UnderNET where it's
10 # penalty = 2 + self.size/120
12 cmd, pars = self.split($;,2)
13 debug "cmd: #{cmd}, pars: #{pars.inspect}"
16 chan, nick, msg = pars.split
17 chan = chan.split(',')
18 nick = nick.split(',')
22 chan, modes, argument = pars.split
27 extra += modes.split(/\+|-/).size
29 extra += 3 * modes.split(/\+|-/).size
33 extra += 2 * argument.split.size
35 penalty += extra * chan.split.size
38 penalty += 2 unless pars.split.size < 2
39 when :PRIVMSG, :NOTICE
40 dests = pars.split($;,2).first
41 penalty += dests.split(',').size
43 # I'm too lazy to implement this one correctly
45 when :AWAY, :JOIN, :VERSION, :TIME, :TRACE, :WHOIS, :DNS
51 else # Unknown messages
55 debug "Wow, more than 99 secs of penalty!"
59 debug "Wow, less than 2 secs of penalty!"
62 debug "penalty: #{penalty}"
73 # A QueueRing is implemented as an array with elements in the form
74 # [chan, [message1, message2, ...]
75 # Note that the channel +chan+ has no actual bearing with the channels
76 # to which messages will be sent
102 cmess = @storage.assoc(chan)
104 idx = @storage.index(cmess)
106 @storage[idx] = cmess
108 @storage << [chan, [mess]]
114 warning "trying to access empty ring"
118 @last_idx = (@last_idx + 1) % @storage.size
119 mess = @storage[@last_idx][1].first
126 warning "trying to access empty ring"
129 @last_idx = (@last_idx + 1) % @storage.size
130 mess = @storage[@last_idx][1].shift
131 @storage.delete(@storage[@last_idx]) if @storage[@last_idx][1] == []
140 # a MessageQueue is an array of QueueRings
141 # rings have decreasing priority, so messages in ring 0
142 # are more important than messages in ring 1, and so on
143 @rings = Array.new(3) { |i|
147 # ring 0 is special in that if it's not empty, it will
148 # be popped. IOW, ring 0 can starve the other rings
149 # ring 0 is strictly FIFO and is therefore implemented
154 # the other rings are satisfied round-robin
156 self.extend(MonitorMixin)
157 @non_empty = self.new_cond
162 @rings.each { |r| r.clear }
167 def push(mess, chan=nil, cring=0)
171 warning "message #{mess} at ring 0 has channel #{chan}: channel will be ignored" if !chan.nil?
174 error "message #{mess} at ring #{ring} must have a channel" if chan.nil?
175 @rings[ring].push mess, chan
181 def shift(tmout = nil)
183 @non_empty.wait(tmout) if self.empty?
191 !@rings.find { |r| !r.empty? }
195 @rings.inject(0) { |s, r| s + r.size }
201 return @rings[0].shift
203 (@rings.size - 1).times do
204 @last_ring = (@last_ring % (@rings.size - 1)) + 1
205 return @rings[@last_ring].shift unless @rings[@last_ring].empty?
207 warning "trying to access an empty message queue"
213 # wrapped TCPSocket for communication with the server.
214 # emulates a subset of TCPSocket functionality
217 MAX_IRC_SEND_PENALTY = 10
219 # total number of lines sent to the irc server
220 attr_reader :lines_sent
222 # total number of lines received from the irc server
223 attr_reader :lines_received
225 # total number of bytes sent to the irc server
226 attr_reader :bytes_sent
228 # total number of bytes received from the irc server
229 attr_reader :bytes_received
231 # accumulator for the throttle
232 attr_reader :throttle_bytes
234 # an optional filter object. we call @filter.in(data) for
235 # all incoming data and @filter.out(data) for all outgoing data
238 # normalized uri of the current server
239 attr_reader :server_uri
241 # default trivial filter class
252 # set filter to identity, not to nil
254 @filter = f || IdentityFilter.new
257 # server_list:: list of servers to connect to
258 # host:: optional local host to bind to (ruby 1.7+ required)
259 # create a new Irc::Socket
260 def initialize(server_list, host, opts={})
261 @server_list = server_list.dup
266 @filter = IdentityFilter.new
270 if opts.kind_of?(Hash) and opts.key?(:ssl)
281 # open a TCP connection to the server
284 warning "reconnecting while connected"
287 srv_uri = @server_list[@conn_count % @server_list.size].dup
288 srv_uri = 'irc://' + srv_uri if !(srv_uri =~ /:\/\//)
290 @server_uri = URI.parse(srv_uri)
291 @server_uri.port = 6667 if !@server_uri.port
292 debug "connection attempt \##{@conn_count} (#{@server_uri.host}:#{@server_uri.port})"
296 sock=TCPSocket.new(@server_uri.host, @server_uri.port, @host)
297 rescue ArgumentError => e
298 error "Your version of ruby does not support binding to a "
299 error "specific local address, please upgrade if you wish "
300 error "to use HOST = foo"
301 error "(this option has been disabled in order to continue)"
302 sock=TCPSocket.new(@server_uri.host, @server_uri.port)
305 sock=TCPSocket.new(@server_uri.host, @server_uri.port)
309 ssl_context = OpenSSL::SSL::SSLContext.new()
310 ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
311 sock = OpenSSL::SSL::SSLSocket.new(sock, ssl_context)
312 sock.sync_close = true
316 @last_send = Time.new
317 @flood_send = Time.new
319 @sock.extend(MonitorMixin)
320 @sendq = MessageQueue.new
321 @qthread = Thread.new { writer_loop }
324 # used to send lines to the remote IRCd by skipping the queue
325 # message: IRC message to send
326 # it should only be used for stuff that *must not* be queued,
327 # i.e. the initial PASS, NICK and USER command
328 # or the final QUIT message
329 def emergency_puts(message, penalty = false)
331 # debug "In puts - got @sock"
332 puts_critical(message, penalty)
336 def handle_socket_error(string, e)
337 error "#{string} failed: #{e.pretty_inspect}"
338 # We assume that an error means that there are connection
339 # problems and that we should reconnect, so we
341 raise SocketError.new(e.inspect)
344 # get the next line from the server (blocks)
347 warning "socket get attempted while closed"
351 reply = @filter.in(@sock.gets)
353 reply.strip! if reply
354 debug "RECV: #{reply.inspect}"
356 rescue Exception => e
357 handle_socket_error(:RECV, e)
361 def queue(msg, chan=nil, ring=0)
362 @sendq.push msg, chan, ring
369 # flush the TCPSocket
374 # Wraps Kernel.select on the socket
375 def select(timeout=nil)
376 Kernel.select([@sock], nil, nil, timeout)
379 # shutdown the connection to the server
381 return unless connected?
386 rescue Exception => e
387 error "error while shutting down: #{e.pretty_inspect}"
399 flood_delay = @flood_send - MAX_IRC_SEND_PENALTY - now
400 delay = [flood_delay, 0].max
402 debug "sleep(#{delay}) # (f: #{flood_delay})"
406 debug "got #{msg.inspect} from queue, sending"
407 emergency_puts(msg, true)
408 rescue Exception => e
409 error "Spooling failed: #{e.pretty_inspect}"
410 debug e.backtrace.join("\n")
416 # same as puts, but expects to be called with a lock held on @sock
417 def puts_critical(message, penalty=false)
418 # debug "in puts_critical"
420 debug "SEND: #{message.inspect}"
422 error "SEND attempted on closed socket"
424 # we use Socket#syswrite() instead of Socket#puts() because
425 # the latter is racy and can cause double message output in
427 actual = @filter.out(message) + "\n"
429 @sock.syswrite actual
431 @flood_send = now if @flood_send < now
432 @flood_send += message.irc_send_penalty if penalty
435 rescue Exception => e
436 handle_socket_error(:SEND, e)