1 # Copyright (C) 2015-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Various Message-ID-related functions.
5 package PublicInbox::MID;
9 our @EXPORT_OK = qw/mid_clean id_compress mid2path mid_mime mid_escape MID_ESC
11 use URI::Escape qw(uri_escape_utf8);
12 use Digest::SHA qw/sha1_hex/;
13 require PublicInbox::Address;
15 MID_MAX => 40, # SHA-1 hex length # TODO: get rid of this
16 MAX_MID_SIZE => 244, # max term size (Xapian limitation) - length('Q')
21 defined($mid) or die "no Message-ID";
22 # MDA->precheck did more checking for us
23 if ($mid =~ /<([^>]+)>/) {
29 # this is idempotent, used for HTML anchor/ids and such
31 my ($id, $force) = @_;
33 if ($force || $id =~ /[^a-zA-Z0-9_\-]/ || length($id) > MID_MAX) {
42 my ($x2, $x38) = ($mid =~ /\A([a-f0-9]{2})([a-f0-9]{38})\z/);
44 unless (defined $x38) {
45 # compatibility with old links (or short Message-IDs :)
46 $mid = mid_clean($mid);
48 $mid = sha1_hex($mid);
49 ($x2, $x38) = ($mid =~ /\A([a-f0-9]{2})([a-f0-9]{38})\z/);
54 # Only for v1 code paths:
55 sub mid_mime ($) { mids($_[0]->header_obj)->[0] }
60 my @v = $hdr->header_raw('Message-Id');
62 my @cur = ($v =~ /<([^>]+)>/sg);
72 # last References should be IRT, but some mail clients do things
73 # out of order, so trust IRT over References iff IRT exists
77 foreach my $f (qw(References In-Reply-To)) {
78 my @v = $hdr->header_raw($f);
80 push(@mids, ($v =~ /<([^>]+)>/sg));
84 # old versions of git-send-email would prompt users for
85 # In-Reply-To and users' muscle memory would use 'y' or 'n'
87 my %addr = ( y => 1, n => 1 );
89 foreach my $f (qw(To From Cc)) {
90 my @v = $hdr->header_raw($f);
92 $addr{$_} = 1 for (PublicInbox::Address::emails($v));
95 uniq_mids(\@mids, \%addr);
99 my ($mids, $seen) = @_;
102 foreach my $mid (@$mids) {
103 $mid =~ tr/\n\t\r//d;
104 if (length($mid) > MAX_MID_SIZE) {
105 warn "Message-ID: <$mid> too long, truncating\n";
106 $mid = substr($mid, 0, MAX_MID_SIZE);
108 next if $seen->{$mid};
115 # RFC3986, section 3.3:
116 sub MID_ESC () { '^A-Za-z0-9\-\._~!\$\&\';\(\)\*\+,;=:@' }
117 sub mid_escape ($) { uri_escape_utf8($_[0], MID_ESC) }