blib/lib/Mail/Make/GPG.pm untested

filter: Statementstmt 0.0% 0 / 287 Branchbran 0.0% 0 / 68 Conditioncond 0.0% 0 / 115 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 41 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 537 CC 35 SCAR 30.2
CC
35
Cov
0%
_serialise_for_gpg
72.0
_entity_from_canonical
42.0
sign_encrypt
30.0
CRAP 20.5
1 ##----------------------------------------------------------------------------
2 ## MIME Email Builder - ~/lib/Mail/Make/GPG.pm
3 ## Version v0.1.4
4 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2026/03/05
7 ## Modified 2026/03/05
8 ## All rights reserved.
9 ##
10 ## This program is free software; you can redistribute it and/or modify it
11 ## under the same terms as Perl itself.
12 ##----------------------------------------------------------------------------
13 package Mail::Make::GPG;
14 BEGIN
15 {
16 use strict;
17 use warnings;
18 warnings::register_categories( 'Mail::Make' );
19 use parent qw( Module::Generic );
20 use vars qw( $VERSION $EXCEPTION_CLASS );
21 use Mail::Make::Exception;
22 our $EXCEPTION_CLASS = 'Mail::Make::Exception';
23 our $VERSION = 'v0.1.4';
24 };
25  
26 use strict;
27 use warnings;
28  
29 sub init
30 {
31 my $self = shift( @_ );
32 $self->{auto_fetch} = 0; # bool: fetch missing recipient keys from keyserver
33 $self->{digest} = 'SHA256';
34 $self->{gpg_bin} = undef; # explicit path to gpg binary; undef = search PATH
35 $self->{key_id} = undef; # default signing key fingerprint or ID
36 $self->{keyserver} = undef; # keyserver URL for auto-fetch
37 $self->{passphrase} = undef; # string or CODE ref; undef = use gpg-agent
38 $self->{_exception_class} = $EXCEPTION_CLASS;
39 $self->SUPER::init( @_ ) || return( $self->pass_error );
40 return( $self );
41 }
42  
43 sub auto_fetch { return( shift->_set_get_boolean( 'auto_fetch', @_ ) ); }
44  
45 sub digest { return( shift->_set_get_scalar( 'digest', @_ ) ); }
46  
47 # encrypt( entity => $entity, recipients => \@addrs [, %opts] )
48 # Signs $entity and returns a new Mail::Make object whose top-level MIME type is
49 # multipart/encrypted per RFC 3156 §4.
50 #
51 # The caller is responsible for supplying recipient public keys in the GnuPG keyring.
52 # When AutoFetch + KeyServer are set, we attempt key retrieval first.
53 sub encrypt
54 {
55 my $self = shift( @_ );
56 my $opts = $self->_get_args_as_hash( @_ );
57 my $entity = $opts->{entity} ||
58 return( $self->error( 'encrypt(): entity option is required.' ) );
59 my $recipients = $opts->{recipients} ||
60 return( $self->error( 'encrypt(): recipients option is required.' ) );
61 $recipients = [ $recipients ] unless( ref( $recipients ) eq 'ARRAY' );
62 unless( scalar( @$recipients ) )
63 {
64 return( $self->error( 'encrypt(): recipients must not be empty.' ) );
65 }
66  
67 $self->_maybe_fetch_keys( $recipients ) || return( $self->pass_error );
68  
69 # Serialise the original message body for gpg input
70 my $plaintext = $self->_serialise_for_gpg( $entity ) || return( $self->pass_error );
71  
72 my @args = ( $self->_base_gpg_args, '--encrypt', '--armor' );
73 push( @args, '--recipient', $_ ) for( @{ $recipients } );
74  
75 my $ciphertext = $self->_run_gpg( \@args, \$plaintext ) || return( $self->pass_error );
76  
77 return( $self->_build_encrypted_mail( $entity, \$ciphertext ) );
78 }
79  
80 sub gpg_bin { return( shift->_set_get_scalar( 'gpg_bin', @_ ) ); }
81  
82 sub key_id { return( shift->_set_get_scalar( 'key_id', @_ ) ); }
83  
84 sub keyserver { return( shift->_set_get_scalar( 'keyserver', @_ ) ); }
85  
86 sub passphrase { return( shift->_set_get_scalar( 'passphrase', @_ ) ); }
87  
88 # sign( entity => $entity [, %opts] )
89 # Signs $entity and returns a new Mail::Make object whose top-level MIME type is
90 # multipart/signed per RFC 3156 §5.
91 sub sign
92 {
93 my $self = shift( @_ );
94 my $opts = $self->_get_args_as_hash( @_ );
95 my $entity = $opts->{entity} ||
96 return( $self->error( 'sign(): entity option is required.' ) );
97  
98 my $key_id = $self->_resolve_key_id( $opts ) ||
99 return( $self->error( 'sign(): KeyId is required (set via option or gpg_sign() default).' ) );
100 my $digest = uc( $opts->{digest} // $self->{digest} );
101  
102 # Ensure Date and Message-ID are committed to the Mail::Make object's own _headers
103 # BEFORE serialising. This must happen without calling as_entity(), which would merge
104 # RFC 2822 headers onto $self->{_parts}[0].
105 $self->_ensure_envelope_headers( $entity ) || return( $self->pass_error );
106  
107 # Serialise the MIME body that will be signed - Part 1 of multipart/signed.
108 # Per RFC 3156 §5.1 this is the entity with CRLF line endings, exactly as it will
109 # appear on the wire.
110 my $canonical = $self->_serialise_for_gpg( $entity ) || return( $self->pass_error );
111  
112 my $passphrase = $self->_resolve_passphrase( $opts );
113 return( $self->pass_error ) if( $self->error ); # CODE ref may have thrown
114  
115 my @args = (
116 $self->_base_gpg_args,
117 '--detach-sign',
118 '--armor',
119 '--digest-algo', $digest,
120 '--local-user', $key_id,
121 );
122 if( defined( $passphrase ) )
123 {
124 push( @args, '--passphrase-fd', '0', '--pinentry-mode', 'loopback' );
125 }
126  
127 my $signature = $self->_run_gpg( \@args, \$canonical, passphrase => $passphrase ) || return( $self->pass_error );
128  
129 return( $self->_build_signed_mail( $entity, \$signature, $canonical, digest => $digest ) );
130 }
131  
132 # sign_encrypt( entity => $entity, recipients => \@addrs [, %opts] )
133 # Signs then encrypts $entity. The result is a multipart/encrypted message whose payload
134 # is a signed+encrypted OpenPGP message.
135 sub sign_encrypt
136 {
137 my $self = shift( @_ );
138 my $opts = $self->_get_args_as_hash( @_ );
139 my $entity = $opts->{entity} || return( $self->error( 'sign_encrypt(): entity option is required.' ) );
140 my $recipients = $opts->{recipients} || return( $self->error( 'sign_encrypt(): recipients option is required.' ) );
141 $recipients = [ $recipients ] unless( ref( $recipients ) eq 'ARRAY' );
142 unless( scalar( @$recipients ) )
143 {
144 return( $self->error( 'sign_encrypt(): recipients must not be empty.' ) );
145 }
146  
147 my $key_id = $self->_resolve_key_id( $opts ) || return( $self->error( 'sign_encrypt(): KeyId is required.' ) );
148 my $digest = uc( $opts->{digest} // $self->{digest} );
149  
150 $self->_maybe_fetch_keys( $recipients ) || return( $self->pass_error );
151  
152 my $plaintext = $self->_serialise_for_gpg( $entity ) || return( $self->pass_error );
153  
154 my $passphrase = $self->_resolve_passphrase( $opts );
155 return( $self->pass_error ) if( $self->error );
156  
157 my @args = (
158 $self->_base_gpg_args,
159 '--sign',
160 '--encrypt',
161 '--armor',
162 '--digest-algo', $digest,
163 '--local-user', $key_id,
164 );
165 push( @args, '--recipient', $_ ) for( @{ $recipients } );
166 if( defined( $passphrase ) )
167 {
168 push( @args, '--passphrase-fd', '0', '--pinentry-mode', 'loopback' );
169 }
170  
171 my $ciphertext = $self->_run_gpg( \@args, \$plaintext, passphrase => $passphrase ) || return( $self->pass_error );
172  
173 return( $self->_build_encrypted_mail( $entity, \$ciphertext ) );
174 }
175  
176 # _base_gpg_args() → list
177 # Returns args common to every gpg invocation.
178 sub _base_gpg_args
179 {
180 my $self = shift( @_ );
181 my $bin = $self->_find_gpg_bin || return( $self->pass_error );
182 return(
183 $bin,
184 '--batch',
185 '--no-tty',
186 '--status-fd', '2',
187 );
188 }
189  
190 # _build_encrypted_mail( $original_mail, \$ciphertext ) → Mail::Make object
191 # Constructs a new Mail::Make object whose body is a RFC 3156 §4
192 # multipart/encrypted structure.
193 #
194 # Structure:
195 # multipart/encrypted; protocol="application/pgp-encrypted"
196 # ├── application/pgp-encrypted ("Version: 1")
197 # └── application/octet-stream (ASCII-armoured ciphertext)
198 sub _build_encrypted_mail
199 {
200 my( $self, $original, $ciphertext_ref ) = @_;
201 require Mail::Make;
202 require Mail::Make::Entity;
203  
204 my $boundary = _random_boundary();
205  
206 # Build the two MIME parts
207 my $ver_part = Mail::Make::Entity->build(
208 type => 'application/pgp-encrypted',
209 encoding => '7bit',
210 data => "Version: 1\r\n",
211 ) || return( $self->pass_error( Mail::Make::Entity->error ) );
212 $ver_part->headers->set( 'Content-Disposition' => 'inline' );
213  
214 my $ct_part = Mail::Make::Entity->build(
215 type => 'application/octet-stream',
216 encoding => '7bit',
217 data => ${ $ciphertext_ref },
218 ) || return( $self->pass_error( Mail::Make::Entity->error ) );
219 $ct_part->headers->set( 'Content-Disposition' => 'inline; filename="encrypted.asc"' );
220  
221 # Assemble the multipart/encrypted container
222 my $top = Mail::Make::Entity->build(
223 type => sprintf(
224 'multipart/encrypted; protocol="application/pgp-encrypted"; boundary="%s"',
225 $boundary
226 ),
227 ) || return( $self->pass_error( Mail::Make::Entity->error ) );
228 $top->add_part( $ver_part );
229 $top->add_part( $ct_part );
230  
231 return( $self->_wrap_in_mail( $original, $top ) );
232 }
233  
234 # _build_signed_mail( $original_mail, \$signature, digest => $algo ) → Mail::Make object
235 # Constructs a new Mail::Make object whose body is a RFC 3156 §5
236 # multipart/signed structure.
237 #
238 # Structure:
239 # multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha256"
240 # ├── <original MIME body - the part that was signed>
241 # └── application/pgp-signature (ASCII-armoured detached signature)
242 sub _build_signed_mail
243 {
244 my $self = shift( @_ );
245 my $original = shift( @_ );
246 my $signature_ref = shift( @_ );
247 my $canonical = shift( @_ );
248 my $opts = $self->_get_args_as_hash( @_ );
249 my $digest = lc( $opts->{digest} // $self->{digest} );
250 require Mail::Make;
251 require Mail::Make::Entity;
252  
253 my $boundary = _random_boundary();
254  
255 # Part 1: a fresh entity whose content is exactly $canonical (the MIME-only bytes
256 # that gpg signed). Built via _entity_from_canonical() which parses the Content-* headers
257 # from $canonical and wraps the body in a Body::InCore.
258 # We never call as_entity() on $original here: for simple text/plain messages
259 # as_entity() would re-add RFC 2822 headers onto $self->{_parts}[0], corrupting the
260 # MIME-only Part 1.
261 my $body_entity = $self->_entity_from_canonical( $canonical ) || return( $self->pass_error );
262  
263 # Part 2: the detached signature
264 my $sig_part = Mail::Make::Entity->build(
265 type => 'application/pgp-signature',
266 encoding => '7bit',
267 data => ${ $signature_ref },
268 ) || return( $self->pass_error( Mail::Make::Entity->error ) );
269 $sig_part->headers->set( 'Content-Disposition' => 'inline; filename="signature.asc"' );
270  
271 # Multipart/signed container
272 my $top = Mail::Make::Entity->build(
273 type => sprintf(
274 'multipart/signed; protocol="application/pgp-signature"; micalg="pgp-%s"; boundary="%s"',
275 $digest, $boundary
276 ),
277 ) || return( $self->pass_error( Mail::Make::Entity->error ) );
278 $top->add_part( $body_entity );
279 $top->add_part( $sig_part );
280  
281 return( $self->_wrap_in_mail( $original, $top ) );
282 }
283  
284 # _ensure_envelope_headers( $mail_make_obj )
285 # Generates Date and Message-ID on $mail directly into its _headers object WITHOUT calling
286 # as_entity(). Called by sign() and sign_encrypt() before _serialise_for_gpg() so that
287 # those values exist when _wrap_in_mail() later copies _headers onto the outer multipart wrapper.
288 sub _ensure_envelope_headers
289 {
290 my $self = shift( @_ );
291 my $mail = shift( @_ ) ||
292 return( $self->error( "No Make::Mail instance was provided." ) );
293 if( !$self->_is_a( $mail => 'Mail::Make' ) )
294 {
295 return( $self->error( "Value provided is not a Mail::Make instance." ) );
296 }
297 elsif( !$self->_is_a( $mail->{_headers} => 'Mail::Make::Headers' ) )
298 {
299 return( $self->error( "No Mail::Make::Headers instance could be found on Mail::Make object!" ) );
300 }
301  
302 # Date
303 unless( $mail->{_headers}->exists( 'Date' ) )
304 {
305 $mail->{_headers}->init_header( Date => $mail->_format_date ) ||
306 return( $self->pass_error( $mail->{_headers}->error ) );
307 }
308  
309 # Message-ID
310 unless( $mail->{_headers}->exists( 'Message-ID' ) )
311 {
312 $mail->{_headers}->message_id(
313 { generate => 1, domain => $mail->_default_domain }
314 ) || return( $self->pass_error( $mail->{_headers}->error ) );
315 }
316  
317 return(1);
318 }
319  
320 # _entity_from_canonical( $canonical ) → Mail::Make::Entity
321 # Builds a fresh Mail::Make::Entity whose headers and body match $canonical exactly (the
322 # MIME-only string returned by _serialise_for_gpg). Used as Part 1 of the multipart/signed
323 # wrapper so that what Thunderbird verifies is byte-for-byte identical to what gpg signed.
324 sub _entity_from_canonical
325 {
326 my( $self, $canonical ) = @_;
327 require Mail::Make::Entity;
328 require Mail::Make::Headers;
329 require Mail::Make::Body::InCore;
330  
331 # Split on the first CRLF+CRLF blank-line separator.
332 my $pos = index( $canonical, "\015\012\015\012" );
333 if( $pos < 0 )
334 {
335 return( $self->error( '_entity_from_canonical(): no header/body separator.' ) );
336 }
337  
338 my $hdr_block = substr( $canonical, 0, $pos );
339 my $body = substr( $canonical, $pos + 4 ); # skip CRLFCRLF
340  
341 # Build a fresh entity with a fresh Headers object.
342 my $entity = Mail::Make::Entity->new || return( $self->pass_error( Mail::Make::Entity->error ) );
343 my $headers = Mail::Make::Headers->new || return( $self->pass_error( Mail::Make::Headers->error ) );
344 $entity->headers( $headers );
345  
346 # Parse MIME header lines from $hdr_block.
347 # Continuation lines (starting with whitespace) are folded onto the preceding field value.
348 my $cur_name = '';
349 my $cur_value = '';
350 for my $line ( split( /\015\012/, $hdr_block ) )
351 {
352 if( $line =~ /^[ \t]/ )
353 {
354 # Continuation: append stripped content to current value.
355 ( my $cont = $line ) =~ s/^[ \t]+//;
356 $cur_value .= ' ' . $cont;
357 }
358 elsif( $line =~ /^([\x21-\x39\x3B-\x7E]+):\s*(.*?)\s*$/ )
359 {
360 # New field: flush the previous one first.
361 if( CORE::length( $cur_name ) )
362 {
363 $headers->push_header( $cur_name => $cur_value ) ||
364 return( $self->pass_error( $headers->error ) );
365 }
366 ( $cur_name, $cur_value ) = ( $1, $2 );
367 }
368 }
369 # Flush the last header.
370 if( CORE::length( $cur_name ) )
371 {
372 $headers->push_header( $cur_name => $cur_value ) ||
373 return( $self->pass_error( $headers->error ) );
374 }
375  
376 # Attach the body verbatim; mark is_encoded so print_body skips re-encoding (the body
377 # in $canonical is already encoded).
378 my $body_obj = Mail::Make::Body::InCore->new( $body ) ||
379 return( $self->pass_error( Mail::Make::Body::InCore->error ) );
380 $entity->body( $body_obj );
381 $entity->{is_encoded} = 1;
382  
383 # Cache effective_type so is_multipart() and similar checks work.
384 my $ct = $headers->get( 'Content-Type' ) // '';
385 ( my $type = $ct ) =~ s/;.*//s;
386 $type =~ s/\s+$//;
387 $entity->effective_type( $type );
388  
389 return( $entity );
390 }
391  
392 # _find_gpg_bin() → $path
393 # Locates the gpg binary: explicit gpg_bin attribute wins; otherwise we search for gpg2
394 # then gpg in PATH via File::Which.
395 sub _find_gpg_bin
396 {
397 my $self = shift( @_ );
398 if( defined( $self->{gpg_bin} ) && length( $self->{gpg_bin} ) )
399 {
400 return( $self->{gpg_bin} );
401 }
402  
403 $self->_load_class( 'File::Which' ) ||
404 return( $self->error( 'File::Which is required to locate gpg. Install it with: cpan File::Which' ) );
405  
406 for my $candidate ( qw( gpg2 gpg ) )
407 {
408 my $path = File::Which::which( $candidate );
409 if( defined( $path ) && length( $path ) )
410 {
411 $self->{gpg_bin} = $path;
412 return( $path );
413 }
414 }
415 return( $self->error( 'gpg binary not found in PATH. Install GnuPG or set the GpgBin option.' ) );
416 }
417  
418 # _maybe_fetch_keys( \@recipients )
419 # When auto_fetch is enabled and a keyserver is configured, attempts to retrieve missing
420 # public keys for each recipient. Failures are silently ignored - the key may already be
421 # in the local keyring.
422 sub _maybe_fetch_keys
423 {
424 my( $self, $recipients ) = @_;
425 return(1) unless( $self->{auto_fetch} && defined( $self->{keyserver} ) && length( $self->{keyserver} ) );
426  
427 $self->_load_class( 'IPC::Run' ) ||
428 return( $self->error( 'IPC::Run is required for GPG operations. Install it with: cpan IPC::Run' ) );
429  
430 my $bin = $self->_find_gpg_bin || return( $self->pass_error );
431 local $@;
432 foreach my $r ( @$recipients )
433 {
434 my( $out, $err ) = ( '', '' );
435 eval
436 {
437 IPC::Run::run(
438 [ $bin, '--batch', '--no-tty',
439 '--keyserver', $self->{keyserver},
440 '--locate-keys', $r,
441 ],
442 \undef, \$out, \$err,
443 );
444 };
445 # Best-effort: do not propagate errors from key fetch
446 }
447 return(1);
448 }
449  
450 # _random_boundary() → $string
451 # Generates a random MIME boundary string.
452 sub _random_boundary
453 {
454 return( sprintf( '----=_NextPart_GPG_%08X%08X', int( rand(0xFFFFFFFF) ), int( rand(0xFFFFFFFF) ) ) );
455 }
456  
457 # _resolve_key_id( \%opts ) → $string
458 sub _resolve_key_id
459 {
460 my $self = shift( @_ );
461 my $opts = $self->_get_args_as_hash( @_ );
462 my $kid = $opts->{key_id} // $self->{key_id} // '';
463 return( $kid );
464 }
465  
466 # _resolve_passphrase( \%opts ) → $string | undef
467 # Resolves the passphrase from per-call option or instance default.
468 # CODE refs are called once here with no arguments.
469 # Returns undef when no passphrase is configured (gpg-agent will be used).
470 sub _resolve_passphrase
471 {
472 my $self = shift( @_ );
473 my $opts = $self->_get_args_as_hash( @_ );
474 my $pp = $opts->{passphrase} // $self->{passphrase};
475 return unless( defined( $pp ) );
476 if( ref( $pp ) eq 'CODE' )
477 {
478 local $@;
479 $pp = eval{ $pp->() };
480 if( $@ )
481 {
482 return( $self->error( "gpg_sign/encrypt: passphrase callback failed: $@" ) );
483 }
484 }
485 return( $pp );
486 }
487  
488 # _run_gpg( \@args, \$input, passphrase => $pp ) → $stdout_string | undef
489 #
490 # Executes gpg via IPC::Run. IPC::Run handles multiplexed I/O internally,
491 # avoiding the select()-loop complexity of a raw fork/pipe approach.
492 #
493 # Passphrase handling (--passphrase-fd 0 + --pinentry-mode loopback):
494 # We prepend the passphrase (followed by a newline) to the stdin payload.
495 # gpg reads exactly one line from fd 0 as the passphrase, then continues reading the same
496 # fd for the message data. This avoids opening a second file descriptor and is the standard
497 # approach for batch use of GnuPG 2.1+.
498 sub _run_gpg
499 {
500 my $self = shift( @_ );
501 my $args = shift( @_ );
502 my $input_ref = shift( @_ );
503 my $opts = $self->_get_args_as_hash( @_ );
504 my $passphrase = $opts->{passphrase};
505  
506 $self->_load_class( 'IPC::Run' ) ||
507 return( $self->error( 'IPC::Run is required for GPG operations. Install it with: cpan IPC::Run' ) );
508  
509 # Build the complete stdin blob
510 my $stdin = '';
511 $stdin .= $passphrase . "\n" if( defined( $passphrase ) );
512 $stdin .= ( ref( $input_ref ) ? ${ $input_ref } : $input_ref );
513  
514 my( $stdout, $stderr ) = ( '', '' );
515  
516 local $@;
517 local $SIG{PIPE} = 'IGNORE';
518 my $ok = eval
519 {
520 IPC::Run::run( $args, \$stdin, \$stdout, \$stderr );
521 };
522 if( $@ )
523 {
524 return( $self->error( "gpg execution error: $@" ) );
525 }
526 unless( $ok )
527 {
528 # Extract the most informative line from gpg's stderr output
529 my @lines = split( /\n/, $stderr );
530 my ($msg) = grep { /\bERROR\b|\berror\b|failed|No secret key|No public key|bad passphrase/i } @lines;
531 $msg //= $lines[-1] // $stderr;
532 $msg =~ s/^\s+|\s+$//g;
533 return( $self->error( "gpg failed: $msg" ) );
534 }
535  
536 return( $stdout );
537 }
538  
539 # _serialise_for_gpg( $mail_make_obj ) → $string
540 # Returns the MIME body of the Mail::Make object with CRLF line endings, suitable for
541 # feeding to gpg (signing) or for encrypting.
542 #
543 # For multipart/signed (RFC 3156 §5.1) the data fed to gpg must be identical to Part 1 as
544 # it will appear on the wire, i.e. with CRLF.
545 sub _serialise_for_gpg
546 {
547 my( $self, $mail ) = @_;
548 unless( defined( $mail ) )
549 {
550 return( $self->error( '_serialise_for_gpg(): no Mail::Make object supplied.' ) );
551 }
552  
553 unless( $mail->can( 'as_entity' ) )
554 {
555 return( $self->error( '_serialise_for_gpg(): argument must be a Mail::Make object.' ) );
556 }
557  
558 # RFC 3156 §5.1: Part 1 of multipart/signed must carry only MIME
559 # Content-* headers; RFC 2822 envelope fields belong on the outer wrapper.
560 #
561 # Root-cause: Mail::Make::as_entity() reuses $self->{_parts}[0] as $top_entity for
562 # simple text/plain messages and merges RFC 2822 headers directly onto it. Any call to
563 # as_entity() re-adds those headers to the same object. We therefore serialise to a
564 # string and filter the RFC 2822 header lines at string level, never mutating the entity.
565 my $entity = $mail->as_entity || return( $self->pass_error( $mail->error ) );
566  
567 my $full = $entity->as_string || return( $self->pass_error( $entity->error ) );
568  
569 # Canonicalise line endings to CRLF FIRST (RFC 3156 §5.1).
570 # Doing this before the separator search ensures we always find \015\012\015\012
571 # regardless of whether Entity::as_string used LF or CRLF.
572 $full =~ s/\015?\012/\015\012/g;
573  
574 # Locate the header / body separator (first blank line).
575 # After canonicalisation this is always \r\n\r\n.
576 my $pos = index( $full, "\015\012\015\012" );
577 if( $pos < 0 )
578 {
579 return( $self->error( '_serialise_for_gpg(): no header/body separator found.' ) );
580 }
581  
582 # Include the \r\n that terminates the last header in hdr_block,
583 # so that every kept line already carries its own EOL.
584 my $hdr_block = substr( $full, 0, $pos + 2 ); # up to and including last header \r\n
585 my $body_block = substr( $full, $pos + 4 ); # skip \r\n\r\n
586  
587 # Walk header lines and keep only Content-* headers.
588 # RFC 3156 §5.1: Part 1 carries Content-* headers only.
589 # MIME-Version belongs on the outer wrapper, not inside Part 1.
590 # Continuation lines (starting with whitespace) follow their field.
591 my $mime_hdr = '';
592 my $keep = 0;
593 for my $line ( split( /(?<=\015\012)/, $hdr_block ) )
594 {
595 if( $line =~ /^[ \t]/ )
596 {
597 $mime_hdr .= $line if( $keep );
598 }
599 else
600 {
601 $keep = ( $line =~ /^Content-/i ) ? 1 : 0;
602 $mime_hdr .= $line if( $keep );
603 }
604 }
605  
606 # Reassemble: kept MIME headers (each already ends with \r\n)
607 # + one \r\n blank line + body.
608 my $raw = $mime_hdr . "\015\012" . $body_block;
609  
610 # RFC 2046 §5.1.1: the \r\n immediately before a boundary delimiter belongs to the
611 # boundary, not to the body. Strip exactly one trailing \r\n.
612 $raw =~ s/\015\012$//;
613  
614 return( $raw );
615 }
616  
617 # _wrap_in_mail( $original_mail, $top_entity ) → Mail::Make object
618 # Creates a new Mail::Make object that carries $top_entity as its pre-built entity,
619 # copying envelope headers (From, To, Cc, Subject, etc.) from $original_mail.
620 sub _wrap_in_mail
621 {
622 my( $self, $original, $top_entity ) = @_;
623 require Mail::Make;
624  
625 # Ok, the check for error here is really semantic, because there is virtually zero chance of that happening.
626 my $new = Mail::Make->new || return( $self->pass_error( Mail::Make->error ) );
627  
628 # Date and Message-ID were generated by _ensure_envelope_headers() in
629 # sign() / sign_encrypt() before _serialise_for_gpg() was called, so
630 # $original->headers already has them. Do NOT call as_entity() here:
631 # for simple text/plain messages as_entity() reuses $self->{_parts}[0] as $top_entity
632 # and would merge RFC 2822 headers back onto it, which would corrupt Part 1 of the
633 # multipart/signed structure.
634  
635 # Merge envelope headers into BOTH the new Mail::Make object AND directly into
636 # $top_entity's headers. The hook in as_entity() returns _gpg_entity verbatim, so the
637 # standard header-merge logic never runs.
638 # We must therefore inject the RFC 2822 headers here.
639 my $ent_headers = $top_entity->headers;
640 $ent_headers->init_header( 'MIME-Version' => '1.0' );
641  
642 $original->headers->scan(sub
643 {
644 my( $name, $value ) = @_;
645 # Inject into top entity so the wire message carries all headers
646 $ent_headers->init_header( $name => $value );
647 # Also keep in the new Mail::Make object for introspection
648 $new->headers->set( $name => $value );
649 return(1);
650 });
651  
652 # Store the pre-assembled top entity so as_entity() returns it directly.
653 $new->{_gpg_entity} = $top_entity;
654  
655 return( $new );
656 }
657  
658 # NOTE: STORABLE support
659 sub STORABLE_freeze { CORE::return( CORE::shift->FREEZE( @_ ) ); }
660  
661 sub STORABLE_thaw { CORE::return( CORE::shift->THAW( @_ ) ); }
662  
663 1;
664 # NOTE: POD
665 __END__