publicscripts/multimime-pgp/multimime-pgp.rb

82 lines
2 KiB
Ruby
Executable file

#!/usr/bin/env ruby
# $Id$
# $URL$
#
# Copyright (c) 2007 Ward Wouts <ward@wouts.nl>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
message = Array.new
boundary = nil
boundaries = Array.new
pgpstart = nil
pgpend = nil
pgpblocks = Array.new
$stdin.each{|line|
message.push line
}
# Eerst uitzoeken wat de mime boundaries zijn
message.each{|line|
if line.match("Content-Type: multipart/mixed") && line.match(/boundary=\"(.*)\"/)
if !boundary.nil?
raise "More than one MIME boundary detected"
else
boundary=$1
end
end
}
message.each_index{|x|
if message[x].match(/^--#{Regexp.escape(boundary)}/)
boundaries.push x
end
if message[x].match(/^-----BEGIN PGP MESSAGE-----$/)
if !pgpstart.nil?
raise "Multiple PGP starts found in a row"
end
pgpstart = x
end
if message[x].match(/^-----END PGP MESSAGE-----$/)
if pgpstart.nil?
raise "PGP end, but no start found"
end
pgpblocks.push pgpstart
pgpstart = nil
end
}
# magic om uit te rekenen in welke blokken het Content-Type gefixed moet worden
# er vanuit gaande dat dat steeds tussen een mime-boundry en een pgp start moet
pgpblocks.reverse_each{|p|
boundaries.reverse_each{|b|
if b > p
next
else
(b...p).each{|x|
if message[x].match(/^Content-Type: .*/)
message[x] = "Content-Type: application/pgp; format=text; x-action=encrypt"
end
}
break
end
}
}
message.each{|line|
puts line
}