Skip to content

Instantly share code, notes, and snippets.

@cowboyrushforth
Created June 24, 2014 18:23
Show Gist options
  • Save cowboyrushforth/c47ae4fd077c68104702 to your computer and use it in GitHub Desktop.
Save cowboyrushforth/c47ae4fd077c68104702 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
# sa-retrain.rb
# to be used to pipe mail into sa-lean, from postfix
# postfix master.cf can be setup like so:
#
# sa-retrain unix - n n - 10 pipe
# flags=Ru user=amavis argv=ruby /usr/local/bin/sa-retrain.rb $nexthop $sender $recipient
#
# then setup some transport like so in /etc/postfix/transport:
#
# spam@yourdomain.tld sa-retrain
# ham@yourdomain.tld sa-retrain
#
#
#
# author: scott@spotman.net
# license: MIT
require 'rubygems'
require 'mail'
@enable_logging = true
@log_file = '/tmp/sa_retrain.log'
if @enable_logging
require 'logger'
@logfile = File.new(@log_file, 'a+')
@log = Logger.new(@logfile)
end
def logthis(message)
if @enable_logging
@log.info(message)
end
end
# Get arguments
spam_class = ARGV[0]
sender = ARGV[1]
recip = ARGV[2]
logthis("sa-retrain Started. Arguments: #{spam_class}, #{sender}, #{recip}")
#see if we were passed spam-user@ or just user@
if match = recip.to_s.match(/^(spam|ham)-(\w+)@/)
user = recip.gsub(/#{match[1]}\-/, '')
elsif match = recip.to_s.match(/^(\w+)@/)
user = sender
else
logthis("\tCant't determine user")
exit 75
end
logthis("\tUser: #{user}")
message = String.new
$stdin.each do |line|
message << line
end
mode = "spam"
if recip.include?("ham")
mode = "ham"
end
mail = Mail.new(message)
if mail.multipart?
if mail.attachments.length == 1
msg = mail.attachments.first.body.decoded
tmp_path = "/tmp/sal_#{mode}_#{rand(100000)}.eml"
File.open(tmp_path, "w") do |f|
f.write msg
end
status = `/usr/bin/vendor_perl/sa-learn --#{mode} #{tmp_path}`
logthis("\t Attempted to retrain #{tmp_path} output: #{status} code: #{$?.exitstatus}")
else
logthis("\t attachment not detected, abort")
end
else
logthis("\t Multi part message not detected, abort")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment