1 # Copyright (C) 2015-2021 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_escape MID_ESC
10 mids references mids_for_index mids_in $MID_EXTRACT);
11 use URI::Escape qw(uri_escape_utf8);
12 use Digest::SHA qw/sha1_hex/;
13 require PublicInbox::Address;
15 ID_MAX => 40, # SHA-1 hex length for HTML id anchors
16 MAX_MID_SIZE => 244, # max term size (Xapian limitation) - length('Q')
19 our $MID_EXTRACT = qr/<([^>]+)>/s;
23 defined($mid) or die "no Message-ID";
24 # MDA->precheck did more checking for us
25 if ($mid =~ $MID_EXTRACT) {
31 # this is idempotent, used for HTML anchor/ids and such
33 my ($id, $force) = @_;
35 if ($force || $id =~ /[^a-zA-Z0-9_\-]/ || length($id) > ID_MAX) {
44 my ($x2, $x38) = ($mid =~ /\A([a-f0-9]{2})([a-f0-9]{38})\z/);
46 unless (defined $x38) {
47 # compatibility with old links (or short Message-IDs :)
48 $mid = mid_clean($mid);
50 $mid = sha1_hex($mid);
51 ($x2, $x38) = ($mid =~ /\A([a-f0-9]{2})([a-f0-9]{38})\z/);
56 # only intended for Message-ID and X-Alt-Message-ID
60 my @cur = ($v =~ /$MID_EXTRACT/g);
72 my @mids = $hdr->header_raw('Message-ID');
73 uniq_mids(extract_mids(@mids));
76 # for Resent-Message-ID and maybe others
78 my ($eml, @headers) = @_;
79 uniq_mids(extract_mids(map { ($eml->header_raw($_)) } @headers));
82 # we allow searching on X-Alt-Message-ID since PublicInbox::NNTP uses them
83 # to placate some clients, and we want to ensure NNTP-only clients can
84 # import and index without relying on HTTP endpoints
85 sub mids_for_index ($) {
86 mids_in($_[0], qw(Message-ID X-Alt-Message-ID));
89 # last References should be IRT, but some mail clients do things
90 # out of order, so trust IRT over References iff IRT exists
94 foreach my $f (qw(References In-Reply-To)) {
95 my @v = $hdr->header_raw($f);
97 push(@mids, ($v =~ /$MID_EXTRACT/g));
101 # old versions of git-send-email would prompt users for
102 # In-Reply-To and users' muscle memory would use 'y' or 'n'
104 my %addr = ( y => 1, n => 1 );
106 foreach my $f (qw(To From Cc)) {
107 my @v = $hdr->header_raw($f);
109 $addr{$_} = 1 for (PublicInbox::Address::emails($v));
112 uniq_mids(\@mids, \%addr);
115 sub uniq_mids ($;$) {
116 my ($mids, $seen) = @_;
119 foreach my $mid (@$mids) {
120 $mid =~ tr/\n\t\r//d;
121 if (length($mid) > MAX_MID_SIZE) {
122 warn "Message-ID: <$mid> too long, truncating\n";
123 $mid = substr($mid, 0, MAX_MID_SIZE);
125 $seen->{$mid} //= push(@ret, $mid);
130 # RFC3986, section 3.3:
131 sub MID_ESC () { '^A-Za-z0-9\-\._~!\$\&\'\(\)\*\+,;=:@' }
132 sub mid_escape ($) { uri_escape_utf8($_[0], MID_ESC) }