Project

General

Profile

Download (7.25 KB) Statistics
| Branch: | Tag: | Revision:
#!/usr/bin/ruby -Ku

#--
# CyborgHood, a distributed system management software.
# Copyright (c) 2009-2010 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/>.
#++

# to allow in-place run for test
$: << File.join(File.dirname(__FILE__), "..", "lib")

#require 'socket'
require 'tempfile'
require 'shellwords'
require 'cyborghood'
require 'cyborghood/imap'
require 'cyborghood/mail'
require 'cyborghood/mail_order'
require 'cyborghood/command_runner'

#Socket.gethostname


module CyborgHood
module PostmanHome
include I18nTranslation
bindtextdomain("cyborghood_postman", {:path => Config::L10N_DIR, :charset => "UTF-8"})

# not yet ready to be a real Cyborg
class Postman #< Cyborg
include I18nTranslation

def initialize
# load config
Config.load(self.human_name.downcase)
@config = Config.instance

ldap_config = @config.ldap
ldap_config.logger = logger
ActiveLdap::Base.setup_connection(ldap_config.marshal_dump)

# setup logs
unless @config.log.nil?
logger.output_level(@config.log.console_level) unless @config.log.console_level.nil?
logger.log_to_file(@config.log.file) unless @config.log.file.nil?
end

@current_thread = Thread.current
@stop_asap = false

logger.info "Bot '#{self.human_name}' loaded"
end

def run
logger.info "Bot starting"
imap = IMAP.new(@config.imap, @config.imap.min_check_interval)
imap.check_mails do |msg|
process_message(msg)
end
logger.info "Bot terminating"
end

def ask_to_stop
@stop_asap = true
# wakeup sleeps
Process.kill("ALRM", $$)
end

private

def process_message(msg)
if @stop_asap
logger.info "Bot was asked to stop..."
return false
end

mail = Mail.new(msg.content)
logger.info "Received mail with ID '#{mail.message_id}': #{mail.from_pretty} -> #{mail.to_pretty} (#{mail.subject_pretty})"

# ignore mails not signed or encrypted
unless mail.is_pgp_signed? or mail.is_pgp_encrypted?
logger.info "Mail not signed/encrypted or not RFC3156 compliant, ignoring..."
msg.delete
return true
end

logger.debug "RFC3156 content detected"
begin
report = mail.process
rescue CyberError => e
case e.severity
when :grave
logger.fatal "Fatal processing error, exiting (#{e.message})"
exit 2
when :unrecoverable
logger.error "Internal processing error, skipping mail (#{e.message})"
return true
when :processable
logger.error "Untreated processing problem, skipping mail (#{e.message})"
return true
when :ignorable
logger.warn "Internal processing warning, continuing (#{e.message})"
end
end
result_tag = report.ok? ? "SUCCESS" : "FAILURE"
result_msg = "Processing result: #{result_tag}"
result_msg += " (#{report.error.untranslated})" unless report.ok?
logger.info result_msg

i18n = I18nController.instance
i18n.set_language_for_user(report.user)

unless report.ok?
if report.warn_sender
logger.info "Sending reply for rejected message"
reply_intro = report.user ? _("Hello %{cn},", :cn =>report.user.cn) : _("Hello,")
mail_reply = mail.create_simple_reject_reply(reply_intro.to_s + "\n\n" +
_("A message (ID: %{id}), apparently from you, was rejected for the following reason:",
:id => mail.message_id).to_s + "\n " + report.error.to_s + "\n")
mail_reply.deliver
end
msg.delete
return true
end

order = MailOrder.parse(report.user, report.message)
result_tag = order.valid? ? "SUCCESS" : "FAILURE"
result_msg = "Processing result: #{result_tag}"
result_msg += " (#{order.error.untranslated})" unless order.valid?
logger.info result_msg

reply_intro = _("Hello %{cn},", :cn => order.user.cn)

unless order.valid?
logger.info "Sending reply for rejected order"
mail_reply = mail.create_simple_reject_reply(reply_intro.to_s + "\n\n" +
_("An order, in a message (ID: %{id}) from you, was rejected for the following reason:",
:id => mail.message_id).to_s + "\n " + order.error.to_s + "\n")
mail_reply.sign_and_crypt(order.user.keyFingerPrint)
mail_reply.deliver
msg.delete
return true
end

logger.debug "Message accepted, processing orders..."
result_list = CommandRunner.run(order)

# create mail
logger.debug "Preparing mail"
mail_reply = mail.create_reply
if reply_attachments.empty?
transcript_part = mail_reply
else
mail_reply.to_multipart!

p = CyborgHood::Mail.blank
transcript_part = p
mail_reply.parts << p

reply_attachments.each do |attachment|
p = CyborgHood::Mail.blank
p.set_content_type("text", "plain", {'charset' => "utf-8"})
p.set_disposition("attachment", {'filename' => attachment.filename})
p.quoted_printable_body = attachment.content
mail_reply.parts << p
end
end

# create transcript
logger.debug "Preparing reply"
reply_txt = reply_intro.to_s + "\n\n"
reply_txt += _("Follows the transcript of your commands:").to_s + "\n"
reply_attachments = []
result_list.each do |result|
reply_txt += "> #{result.cmd}\n"
reply_txt += "#{result.message}\n"
reply_attachments += result.refs unless result.refs.nil?
end
reply_txt += "\n" + mail_reply.default_body_signature

# insert transcript
transcript_part.set_content_type("text", "plain", {'charset' => 'utf-8', 'format' => 'flowed'})
transcript_part.set_disposition("inline")
transcript_part.quoted_printable_body = reply_txt

# send reply
logger.debug "Sending mail"
mail_reply.sign_and_crypt(order.user.keyFingerPrint)
mail_reply.deliver

logger.info "Message processed completely, deleting"
msg.delete

true
end
end
end
end

bot = CyborgHood::PostmanHome::Postman.new

trap('INT') do
bot.ask_to_stop
end
trap('TERM') do
bot.ask_to_stop
end

bot.run
(2-2/3)