Project

General

Profile

Download (7.2 KB) Statistics
| Branch: | Tag: | Revision:
#--
# CyborgHood, a distributed system management software.
# Copyright (c) 2009-2011 Marc Dequènes (Duck) <Duck@DuckCorp.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#++

require 'net/imap'
require 'thread'

# IMAP IDLE support
class Net::IMAP
def idle(&response_handler)
return if @idle_mode

@idle_response_handler = response_handler

synchronize do
@idle_tag = generate_tag
add_response_handler @idle_response_handler if @idle_response_handler
put_string "#{@idle_tag} IDLE#{CRLF}"
end

@idle_mode = true
end

def idle_done
return unless @idle_mode

synchronize do
remove_response_handler @idle_response_handler if @idle_response_handler
put_string "DONE#{CRLF}"
end

@idle_mode = false

begin
return get_tagged_response @idle_tag
rescue
end
end

def idle?
@idle_mode || false
end
end

module CyborgHood
class IMAP
def initialize(params, min_check_interval)
@params = params
@min_check_interval = min_check_interval

@config = Config.instance
@imap = nil
@is_loggued = false
@available_mails = 0
@available_mails_mutex = Mutex.new

if @config.debug.flags.include?('debug_imapverbose')
Net::IMAP.debug = true
end
end

class IMAPMessage
def initialize(imap, message_id)
@imap = imap
@message_id = message_id

@config = Config.instance
@content = nil
@stop_mail_check = false
end

def content
return @content unless @content.nil?

data = @imap.fetch(@message_id, ["RFC822"])[0]
@content = data.attr["RFC822"]
end

def delete
if not @config.debug.flags.include?('debug_nomaildeletion')
@imap.store(@message_id, "+FLAGS", [:Deleted])
end
end
end

def capabilities
return @imap_capab if @imap_capab
@imap_capab = @imap.capability
end

def connect
return true if @imap

# using SSL because TLS does not work in the NET::IMAP library in Ruby 1.8
# (but available in 1.9)
ssl = (not @params.ca_cert.nil?)
port = @params.port || (ssl ? 993 : 143)
check_ca = ssl
logger.debug "Connecting to the IMAP server..."
begin
@imap = Net::IMAP.new(@params.host, port, ssl, @params.ca_cert, check_ca)
rescue SocketError
logger.warn "Could not connect to the IMAP server"
return false
end
logger.debug "Connected (IMAP Capabilities: " + self.capabilities.join(", ") + ")"
#p @imap.getquotaroot("INBOX")

@stop_mail_check = false

true
end

def connected?
not @imap.nil?
end

def authenticate
raise CyberError.new(:unrecoverable, "fixme", "Trying to authenticate to the IMAP server, but we are not connected yet") unless @imap

logger.debug "Authenticating to the IMAP server..."
begin
@imap.authenticate('LOGIN', @params.login, @params.passwd)
rescue Net::IMAP::NoResponseError
logger.warn "Could not authenticate to the IMAP server"
disconnect
return false
end
logger.debug "Authenticated as '#{@params.login}'"
@is_loggued = true
true
end

def listen_to_events
@imap.add_response_handler do |resp|
logger.debug "IMAP event: " + resp.inspect if @config.debug.flags.include?('debug_imapverbose')
if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"
@available_mails_mutex.synchronize do
@available_mails = resp.data.to_i
logger.debug "*** Received new mails (#{@available_mails})" if @available_mails > 0
end
end
end
true
end

def check_mails_once(&message_handler)
connect &&
authenticate &&
listen_to_events &&
wait_and_read_mails(&message_handler)
rescue Net::IMAP::NoResponseError => e
logger.warn "IMAP error: " + e.message.strip
rescue Net::IMAP::Error => e
logger.error "IMAP error: " + e.message.strip
ensure
begin
disconnect
rescue
end
end

def remaining_mails
nb = nil
@available_mails_mutex.synchronize do
nb = @available_mails
end
nb
end

def waiting_mails?
remaining_mails > 0
end

def wait_and_read_mails(&message_handler)
until @stop_mail_check
begin
check_inbox(&message_handler)
# don't loop forever
return if @config.debug.flags.include?('debug_nomaildeletion')
end while waiting_mails?

if self.capabilities.include?("IDLE")
logger.debug "Waiting for new mails in idle mode"
@imap.idle
sleep(1) until @stop_mail_check or waiting_mails?
@imap.idle_done
end
end
end

def check_mails(&message_handler)
@stop_mail_check = false
until @stop_mail_check
begin
t = Time.now.to_i
r = check_mails_once(&message_handler)
t2 = Time.now.to_i

sleep_time = @min_check_interval - (t2 - t)
rescue SocketError, Errno::EPIPE, Errno::ECONNREFUSED, Errno::ETIMEDOUT, Errno::ENETUNREACH => e
logger.warn "Network error: " + e.message.strip
sleep_time = @min_check_interval
end

# wait before new check either if the IMAP server does not support IDLE mode
# or if an error occured
if sleep_time > 0 and not @stop_mail_check
logger.debug "Having a break before new check..."
t = Time.now.to_i
while Time.now.to_i - t < sleep_time and not @stop_mail_check
sleep(1)
end
end
end
end

def stop_mail_check
@stop_mail_check = true
end

def check_inbox(&message_handler)
logger.debug "Examining INBOX"
@imap.select('INBOX')

logger.debug "Starting mail check"
@imap.search(["ALL"], "UTF-8").each do |message_id|
break if @stop_mail_check

logger.debug "*** Fetched mail ##{message_id}"
unless message_handler.call IMAPMessage.new(@imap, message_id)
@stop_mail_check = true
break
end
end
logger.debug "Mail check finished"

@imap.expunge
end

def disconnect
return unless @imap

begin
@imap.logout if @is_loggued

logger.debug "Disconnecting from IMAP server..."
@imap.disconnect
logger.debug "Disconnected from IMAP server"
rescue IOError
logger.debug "Already diconnected from IMAP server"
ensure
@imap = nil
@is_loggued = false
@imap_capab = nil
end
end
end
end
(1-1/4)