6 # This module implements the IRC socket interface, including IRC message
7 # penalty computation and the message queue system
12 # Calculate the penalty which will be assigned to this message
15 # According to eggdrop, the initial penalty is
16 penalty = 1 + self.size/100
17 # on everything but UnderNET where it's
18 # penalty = 2 + self.size/120
20 cmd, pars = self.split($;,2)
21 debug "cmd: #{cmd}, pars: #{pars.inspect}"
24 chan, nick, msg = pars.split
25 chan = chan.split(',')
26 nick = nick.split(',')
30 chan, modes, argument = pars.split
35 extra += modes.split(/\+|-/).size
37 extra += 3 * modes.split(/\+|-/).size
41 extra += 2 * argument.split.size
43 penalty += extra * chan.split.size
46 penalty += 2 unless pars.split.size < 2
47 when :PRIVMSG, :NOTICE
48 dests = pars.split($;,2).first
49 penalty += dests.split(',').size
51 # I'm too lazy to implement this one correctly
53 when :AWAY, :JOIN, :VERSION, :TIME, :TRACE, :WHOIS, :DNS
59 else # Unknown messages
63 debug "Wow, more than 99 secs of penalty!"
67 debug "Wow, less than 2 secs of penalty!"
70 debug "penalty: #{penalty}"
81 # A QueueRing is implemented as an array with elements in the form
82 # [chan, [message1, message2, ...]
83 # Note that the channel +chan+ has no actual bearing with the channels
84 # to which messages will be sent
110 cmess = @storage.assoc(chan)
112 idx = @storage.index(cmess)
114 @storage[idx] = cmess
116 @storage << [chan, [mess]]
122 warning "trying to access empty ring"
126 @last_idx = (@last_idx + 1) % @storage.size
127 mess = @storage[@last_idx][1].first
134 warning "trying to access empty ring"
137 @last_idx = (@last_idx + 1) % @storage.size
138 mess = @storage[@last_idx][1].shift
139 @storage.delete(@storage[@last_idx]) if @storage[@last_idx][1] == []
148 # a MessageQueue is an array of QueueRings
149 # rings have decreasing priority, so messages in ring 0
150 # are more important than messages in ring 1, and so on
151 @rings = Array.new(3) { |i|
155 # ring 0 is special in that if it's not empty, it will
156 # be popped. IOW, ring 0 can starve the other rings
157 # ring 0 is strictly FIFO and is therefore implemented
162 # the other rings are satisfied round-robin
164 self.extend(MonitorMixin)
165 @non_empty = self.new_cond
170 @rings.each { |r| r.clear }
175 def push(mess, chan=nil, cring=0)
179 warning "message #{mess} at ring 0 has channel #{chan}: channel will be ignored" if !chan.nil?
182 error "message #{mess} at ring #{ring} must have a channel" if chan.nil?
183 @rings[ring].push mess, chan
189 def shift(tmout = nil)
191 @non_empty.wait(tmout) if self.empty?
199 !@rings.find { |r| !r.empty? }
203 @rings.inject(0) { |s, r| s + r.size }
209 return @rings[0].shift
211 (@rings.size - 1).times do
212 @last_ring = (@last_ring % (@rings.size - 1)) + 1
213 return @rings[@last_ring].shift unless @rings[@last_ring].empty?
215 warning "trying to access an empty message queue"
221 # wrapped TCPSocket for communication with the server.
222 # emulates a subset of TCPSocket functionality
225 MAX_IRC_SEND_PENALTY = 10
227 # total number of lines sent to the irc server
228 attr_reader :lines_sent
230 # total number of lines received from the irc server
231 attr_reader :lines_received
233 # total number of bytes sent to the irc server
234 attr_reader :bytes_sent
236 # total number of bytes received from the irc server
237 attr_reader :bytes_received
239 # accumulator for the throttle
240 attr_reader :throttle_bytes
242 # an optional filter object. we call @filter.in(data) for
243 # all incoming data and @filter.out(data) for all outgoing data
246 # normalized uri of the current server
247 attr_reader :server_uri
249 # default trivial filter class
260 # set filter to identity, not to nil
262 @filter = f || IdentityFilter.new
265 # server_list:: list of servers to connect to
266 # host:: optional local host to bind to (ruby 1.7+ required)
267 # create a new Irc::Socket
268 def initialize(server_list, host, opts={})
269 @server_list = server_list.dup
274 @filter = IdentityFilter.new
278 if opts.kind_of?(Hash) and opts.key?(:ssl)
289 # open a TCP connection to the server
292 warning "reconnecting while connected"
295 srv_uri = @server_list[@conn_count % @server_list.size].dup
296 srv_uri = 'irc://' + srv_uri if !(srv_uri =~ /:\/\//)
298 @server_uri = URI.parse(srv_uri)
299 @server_uri.port = 6667 if !@server_uri.port
300 debug "connection attempt \##{@conn_count} (#{@server_uri.host}:#{@server_uri.port})"
304 sock=TCPSocket.new(@server_uri.host, @server_uri.port, @host)
305 rescue ArgumentError => e
306 error "Your version of ruby does not support binding to a "
307 error "specific local address, please upgrade if you wish "
308 error "to use HOST = foo"
309 error "(this option has been disabled in order to continue)"
310 sock=TCPSocket.new(@server_uri.host, @server_uri.port)
313 sock=TCPSocket.new(@server_uri.host, @server_uri.port)
317 ssl_context = OpenSSL::SSL::SSLContext.new()
318 ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
319 sock = OpenSSL::SSL::SSLSocket.new(sock, ssl_context)
320 sock.sync_close = true
324 @last_send = Time.new
325 @flood_send = Time.new
327 @sock.extend(MonitorMixin)
328 @sendq = MessageQueue.new
329 @qthread = Thread.new { writer_loop }
332 # used to send lines to the remote IRCd by skipping the queue
333 # message: IRC message to send
334 # it should only be used for stuff that *must not* be queued,
335 # i.e. the initial PASS, NICK and USER command
336 # or the final QUIT message
337 def emergency_puts(message, penalty = false)
339 # debug "In puts - got @sock"
340 puts_critical(message, penalty)
344 def handle_socket_error(string, e)
345 error "#{string} failed: #{e.pretty_inspect}"
346 # We assume that an error means that there are connection
347 # problems and that we should reconnect, so we
349 raise SocketError.new(e.inspect)
352 # get the next line from the server (blocks)
355 warning "socket get attempted while closed"
359 reply = @filter.in(@sock.gets)
361 reply.strip! if reply
362 debug "RECV: #{reply.inspect}"
364 rescue Exception => e
365 handle_socket_error(:RECV, e)
369 def queue(msg, chan=nil, ring=0)
370 @sendq.push msg, chan, ring
377 # flush the TCPSocket
382 # Wraps Kernel.select on the socket
383 def select(timeout=nil)
384 Kernel.select([@sock], nil, nil, timeout)
387 # shutdown the connection to the server
389 return unless connected?
394 rescue Exception => e
395 error "error while shutting down: #{e.pretty_inspect}"
407 flood_delay = @flood_send - MAX_IRC_SEND_PENALTY - now
408 delay = [flood_delay, 0].max
410 debug "sleep(#{delay}) # (f: #{flood_delay})"
414 debug "got #{msg.inspect} from queue, sending"
415 emergency_puts(msg, true)
416 rescue Exception => e
417 error "Spooling failed: #{e.pretty_inspect}"
418 debug e.backtrace.join("\n")
424 # same as puts, but expects to be called with a lock held on @sock
425 def puts_critical(message, penalty=false)
426 # debug "in puts_critical"
428 debug "SEND: #{message.inspect}"
430 error "SEND attempted on closed socket"
432 # we use Socket#syswrite() instead of Socket#puts() because
433 # the latter is racy and can cause double message output in
435 actual = @filter.out(message) + "\n"
437 @sock.syswrite actual
439 @flood_send = now if @flood_send < now
440 @flood_send += message.irc_send_penalty if penalty
443 rescue Exception => e
444 handle_socket_error(:SEND, e)