Debian Codegraph @

lib/Qpsmtpd/Address.pm

raw
1 #!/usr/bin/perl -w
2 package Qpsmtpd::Address;
3 use strict;
4
5 =head1 NAME
6
7 Qpsmtpd::Address - Lightweight E-Mail address objects
8
9 =head1 DESCRIPTION
10
11 Based originally on cut and paste from Mail::Address and including
12 every jot and tittle from RFC-2821/2822 on what is a legal e-mail
13 address for use during the SMTP transaction.
14
15 =head1 USAGE
16
17 my $rcpt = Qpsmtpd::Address->new('<[email protected]>');
18
19 The objects created can be used as is, since they automatically
20 stringify to a standard form, and they have an overloaded comparison
21 for easy testing of values.
22
23 =head1 METHODS
24
25 =cut
26
27 use overload (
28 '""' => \&format,
29 'cmp' => \&_addr_cmp,
30 );
31
32 =head2 new()
33
34 Can be called two ways:
35
36 =over 4
37
38 =item * Qpsmtpd::Address->new('<[email protected]>')
39
40 The normal mode of operation is to pass the entire contents of the
41 RCPT TO: command from the SMTP transaction. The value will be fully
42 parsed via the L<canonify> method, using the full RFC 2821 rules.
43
44 =item * Qpsmtpd::Address->new("user", "host")
45
46 If the caller has already split the address from the domain/host,
47 this mode will not L<canonify> the input values. This is not
48 recommended in cases of user-generated input for that reason. This
49 can be used to generate Qpsmtpd::Address objects for accounts like
50 "<postmaster>" or indeed for the bounce address "<>".
51
52 =back
53
54 The resulting objects can be stored in arrays or used in plugins to
55 test for equality (like in badmailfrom).
56
57 =cut
58
59 sub new {
60 my ($class, $user, $host) = @_;
61 my $self = {};
62 if ($user =~ /^<(.*)>$/) {
63 ($user, $host) = $class->canonify($user);
64 return undef unless defined $user;
65 }
66 elsif (not defined $host) {
67 my $address = $user;
68 ($user, $host) = $address =~ m/(.*)(?:\@(.*))/;
69 }
70 $self->{_user} = $user;
71 $self->{_host} = $host;
72 return bless $self, $class;
73 }
74
75 # Definition of an address ("path") from RFC 2821:
76 #
77 # Path = "<" [ A-d-l ":" ] Mailbox ">"
78 #
79 # A-d-l = At-domain *( "," A-d-l )
80 # ; Note that this form, the so-called "source route",
81 # ; MUST BE accepted, SHOULD NOT be generated, and SHOULD be
82 # ; ignored.
83 #
84 # At-domain = "@" domain
85 #
86 # Mailbox = Local-part "@" Domain
87 #
88 # Local-part = Dot-string / Quoted-string
89 # ; MAY be case-sensitive
90 #
91 # Dot-string = Atom *("." Atom)
92 #
93 # Atom = 1*atext
94 #
95 # Quoted-string = DQUOTE *qcontent DQUOTE
96 #
97 # Domain = (sub-domain 1*("." sub-domain)) / address-literal
98 # sub-domain = Let-dig [Ldh-str]
99 #
100 # address-literal = "[" IPv4-address-literal /
101 # IPv6-address-literal /
102 # General-address-literal "]"
103 #
104 # IPv4-address-literal = Snum 3("." Snum)
105 # IPv6-address-literal = "IPv6:" IPv6-addr
106 # General-address-literal = Standardized-tag ":" 1*dcontent
107 # Standardized-tag = Ldh-str
108 # ; MUST be specified in a standards-track RFC
109 # ; and registered with IANA
110 #
111 # Snum = 1*3DIGIT ; representing a decimal integer
112 # ; value in the range 0 through 255
113 # Let-dig = ALPHA / DIGIT
114 # Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig
115 #
116 # IPv6-addr = IPv6-full / IPv6-comp / IPv6v4-full / IPv6v4-comp
117 # IPv6-hex = 1*4HEXDIG
118 # IPv6-full = IPv6-hex 7(":" IPv6-hex)
119 # IPv6-comp = [IPv6-hex *5(":" IPv6-hex)] "::" [IPv6-hex *5(":"
120 # IPv6-hex)]
121 # ; The "::" represents at least 2 16-bit groups of zeros
122 # ; No more than 6 groups in addition to the "::" may be
123 # ; present
124 # IPv6v4-full = IPv6-hex 5(":" IPv6-hex) ":" IPv4-address-literal
125 # IPv6v4-comp = [IPv6-hex *3(":" IPv6-hex)] "::"
126 # [IPv6-hex *3(":" IPv6-hex) ":"] IPv4-address-literal
127 # ; The "::" represents at least 2 16-bit groups of zeros
128 # ; No more than 4 groups in addition to the "::" and
129 # ; IPv4-address-literal may be present
130 #
131 #
132 #
133 # atext and qcontent are not defined in RFC 2821.
134 # From RFC 2822:
135 #
136 # atext = ALPHA / DIGIT / ; Any character except controls,
137 # "!" / "#" / ; SP, and specials.
138 # "$" / "%" / ; Used for atoms
139 # "&" / "'" /
140 # "*" / "+" /
141 # "-" / "/" /
142 # "=" / "?" /
143 # "^" / "_" /
144 # "`" / "{" /
145 # "|" / "}" /
146 # "~"
147 # qtext = NO-WS-CTL / ; Non white space controls
148 #
149 # %d33 / ; The rest of the US-ASCII
150 # %d35-91 / ; characters not including "\"
151 # %d93-126 ; or the quote character
152 #
153 # qcontent = qtext / quoted-pair
154 #
155 # NO-WS-CTL = %d1-8 / ; US-ASCII control characters
156 # %d11 / ; that do not include the
157 # %d12 / ; carriage return, line feed,
158 # %d14-31 / ; and white space characters
159 # %d127
160 #
161 # quoted-pair = ("\" text) / obs-qp
162 #
163 # text = %d1-9 / ; Characters excluding CR and LF
164 # %d11 /
165 # %d12 /
166 # %d14-127 /
167 # obs-text
168 #
169 #
170 # (We ignore all obs forms)
171
172 =head2 canonify()
173
174 Primarily an internal method, it is used only on the path portion of
175 an e-mail message, as defined in RFC-2821 (this is the part inside the
176 angle brackets and does not include the "human readable" portion of an
177 address). It returns a list of (local-part, domain).
178
179 =cut
180
181 # address components are defined as package variables so that they can
182 # be overriden (in hook_pre_connection, for example) if people have
183 # different needs.
184 our $atom_expr = '[a-zA-Z0-9!#%&*+=?^_`{|}~\$\x27\x2D\/]+';
185 our $address_literal_expr =
186 '(?:\[(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|IPv6:[0-9A-Fa-f:.]+)\])';
187 our $subdomain_expr = '(?:[a-zA-Z0-9](?:[-a-zA-Z0-9]*[a-zA-Z0-9])?)';
188 our $domain_expr;
189 our $qtext_expr = '[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]';
190 our $text_expr = '[\x01-\x09\x0B\x0C\x0E-\x7F]';
191
192 sub canonify {
193 my ($dummy, $path) = @_;
194
195 # strip delimiters
196 return undef unless ($path =~ /^<(.*)>$/);
197 $path = $1;
198
199 my $domain =
200 $domain_expr
201 ? $domain_expr
202 : "$subdomain_expr(?:\.$subdomain_expr)*";
203
204 # it is possible for $address_literal_expr to be empty, if a site
205 # doesn't want to allow them
206 $domain = "(?:$address_literal_expr|$domain)"
207 if !$domain_expr and $address_literal_expr;
208
209 # strip source route
210 $path =~ s/^\@$domain(?:,\@$domain)*://;
211
212 # empty path is ok
213 return "" if $path eq "";
214
215 # bare postmaster is permissible, perl RFC-2821 (4.5.1)
216 return ("postmaster", undef) if $path =~ m/^postmaster$/i;
217
218 my ($localpart, $domainpart) = ($path =~ /^(.*)\@($domain)$/);
219 return (undef) unless defined $localpart;
220
221 if ($localpart =~ /^$atom_expr(\.$atom_expr)*/) {
222
223 # simple case, we are done
224 return ($localpart, $domainpart);
225 }
226 if ($localpart =~ /^"(($qtext_expr|\\$text_expr)*)"$/) {
227 $localpart = $1;
228 $localpart =~ s/\\($text_expr)/$1/g;
229 return ($localpart, $domainpart);
230 }
231 return (undef);
232 }
233
234 =head2 parse()
235
236 Retained as a compatibility method, it is completely equivalent
237 to new() called with a single parameter.
238
239 =cut
240
241 sub parse { # retain for compatibility only
242 return shift->new(shift);
243 }
244
245 =head2 address()
246
247 Can be used to reset the value of an existing Q::A object, in which
248 case it takes a parameter with or without the angle brackets.
249
250 Returns the stringified representation of the address. NOTE: does
251 not escape any of the characters that need escaping, nor does it
252 include the surrounding angle brackets. For that purpose, see
253 L<format>.
254
255 =cut
256
257 sub address {
258 my ($self, $val) = @_;
259 if (defined($val)) {
260 $val = "<$val>" unless $val =~ /^<.+>$/;
261 my ($user, $host) = $self->canonify($val);
262 $self->{_user} = $user;
263 $self->{_host} = $host;
264 }
265 return (defined $self->{_user} ? $self->{_user} : '')
266 . (defined $self->{_host} ? '@' . $self->{_host} : '');
267 }
268
269 =head2 format()
270
271 Returns the canonical stringified representation of the address. It
272 does escape any characters requiring it (per RFC-2821/2822) and it
273 does include the surrounding angle brackets. It is also the default
274 stringification operator, so the following are equivalent:
275
276 print $rcpt->format();
277 print $rcpt;
278
279 =cut
280
281 sub format {
282 my ($self) = @_;
283 my $qchar = '[^a-zA-Z0-9!#\$\%\&\x27\*\+\x2D\/=\?\^_`{\|}~.]';
284 return '<>' unless defined $self->{_user};
285 if ((my $user = $self->{_user}) =~ s/($qchar)/\\$1/g) {
286 return
287 qq(<"$user")
288 . (defined $self->{_host} ? '@' . $self->{_host} : '') . ">";
289 }
290 return "<" . $self->address() . ">";
291 }
292
293 =head2 user([$user])
294
295 Returns the "localpart" of the address, per RFC-2821, or the portion
296 before the '@' sign.
297
298 If called with one parameter, the localpart is set and the new value is
299 returned.
300
301 =cut
302
303 sub user {
304 my ($self, $user) = @_;
305 $self->{_user} = $user if defined $user;
306 return $self->{_user};
307 }
308
309 =head2 host([$host])
310
311 Returns the "domain" part of the address, per RFC-2821, or the portion
312 after the '@' sign.
313
314 If called with one parameter, the domain is set and the new value is
315 returned.
316
317 =cut
318
319 sub host {
320 my ($self, $host) = @_;
321 $self->{_host} = $host if defined $host;
322 return $self->{_host};
323 }
324
325 =head2 notes($key[,$value])
326
327 Get or set a note on the address. This is a piece of data that you wish
328 to attach to the address and read somewhere else. For example you can
329 use this to pass data between plugins.
330
331 =cut
332
333 sub notes {
334 my ($self, $key) = (shift, shift);
335
336 # Check for any additional arguments passed by the caller -- including undef
337 return $self->{_notes}->{$key} unless @_;
338 return $self->{_notes}->{$key} = shift;
339 }
340
341 sub _addr_cmp {
342 require UNIVERSAL;
343 my ($left, $right, $swap) = @_;
344 my $class = ref($left);
345
346 unless (UNIVERSAL::isa($right, $class)) {
347 $right = $class->new($right);
348 }
349
350 #invert the address so we can sort by domain then user
351 ($left = join('=', reverse(split(/@/, $left->format)))) =~ tr/[<>]//d;
352 ($right = join('=', reverse(split(/@/, $right->format)))) =~ tr/[<>]//d;
353
354 if ($swap) {
355 ($right, $left) = ($left, $right);
356 }
357
358 return ($left cmp $right);
359 }
360
361 =head1 COPYRIGHT
362
363 Copyright 2004-2005 Peter J. Holzer. See the LICENSE file for more
364 information.
365
366 =cut
367
368 1;