]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/MID.pm
www: do not mangle characters from search queries
[public-inbox.git] / lib / PublicInbox / MID.pm
1 # Copyright (C) 2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 #
4 # Various Message-ID-related functions.
5 package PublicInbox::MID;
6 use strict;
7 use warnings;
8 use base qw/Exporter/;
9 our @EXPORT_OK = qw/mid_clean id_compress mid2path mid_mime mid_escape MID_ESC/;
10 use URI::Escape qw(uri_escape_utf8);
11 use Digest::SHA qw/sha1_hex/;
12 use constant MID_MAX => 40; # SHA-1 hex length
13
14 sub mid_clean {
15         my ($mid) = @_;
16         defined($mid) or die "no Message-ID";
17         # MDA->precheck did more checking for us
18         if ($mid =~ /<([^>]+)>/) {
19                 $mid = $1;
20         }
21         $mid;
22 }
23
24 # this is idempotent
25 sub id_compress {
26         my ($id, $force) = @_;
27
28         if ($force || $id =~ /[^\w\-]/ || length($id) > MID_MAX) {
29                 utf8::encode($id);
30                 return sha1_hex($id);
31         }
32         $id;
33 }
34
35 sub mid2path {
36         my ($mid) = @_;
37         my ($x2, $x38) = ($mid =~ /\A([a-f0-9]{2})([a-f0-9]{38})\z/);
38
39         unless (defined $x38) {
40                 # compatibility with old links (or short Message-IDs :)
41                 $mid = mid_clean($mid);
42                 utf8::encode($mid);
43                 $mid = sha1_hex($mid);
44                 ($x2, $x38) = ($mid =~ /\A([a-f0-9]{2})([a-f0-9]{38})\z/);
45         }
46         "$x2/$x38";
47 }
48
49 sub mid_mime ($) { $_[0]->header_obj->header_raw('Message-ID') }
50
51 # RFC3986, section 3.3:
52 sub MID_ESC () { '^A-Za-z0-9\-\._~!\$\&\';\(\)\*\+,;=:@' }
53 sub mid_escape ($) { uri_escape_utf8($_[0], MID_ESC) }
54
55 1;