Compare commits

..

137 commits

Author SHA1 Message Date
a7bd3c475a
fix mime() method 2023-09-18 18:08:07 +02:00
df0c6fa34f Merge pull request 'expose naive fields' (#27) from fetch-mime-from-anypart into main
Reviewed-on: #27
2023-09-18 16:07:16 +00:00
7920955ee5 Merge branch 'main' into fetch-mime-from-anypart 2023-09-18 16:07:07 +00:00
0a7179a17c
expose naive fields 2023-09-18 18:06:37 +02:00
303fdc3e91 Merge pull request 'attach to child' (#26) from header2 into main
Reviewed-on: #26
2023-09-18 15:25:55 +00:00
f5f8b8e018
attach to child 2023-09-18 17:24:58 +02:00
8b17af73fa Merge pull request 'always attach headers to naivemime' (#25) from headers_kv2 into main
Reviewed-on: #25
2023-09-18 14:38:47 +00:00
9eb44b03f7
always attach headers to naivemime 2023-09-18 16:38:04 +02:00
5ccc212d15 Merge pull request 'Access headers as key/values' (#24) from headers_map into main
Reviewed-on: #24
2023-08-30 17:50:25 +00:00
d9285c9ddf
format code 2023-08-30 19:49:04 +02:00
2529b0145e
fixed tests! 2023-08-30 19:48:23 +02:00
9b828ad6ad
better debug 2023-08-30 19:30:10 +02:00
18bb04340a
refactor headers 2023-08-30 19:00:08 +02:00
d9cf6b225d
fix raw mime test 2/2 2023-08-30 13:31:24 +02:00
628fbc507d
fix raw mime test 1/2 2023-08-30 11:46:23 +02:00
dfb5b9fe0f
refactor imf parsing 2023-08-30 11:35:46 +02:00
ba59b037ef
add an header kv function 2023-08-30 11:35:29 +02:00
5cff5510ac Merge pull request 'add a raw field to mime' (#22) from better_access_to_bytes into main
Reviewed-on: #22
2023-08-16 14:18:51 +00:00
8aa23ac5f2
add a raw field to mime 2023-08-16 16:15:57 +02:00
32ca628358
prepare v0.1.1 release 2023-07-25 18:33:00 +02:00
b64c032bff
add compatibility for \r\r\n 2023-07-25 18:27:19 +02:00
987024430b
collect raw stuff 2023-07-25 16:20:36 +02:00
91fa0d38c3
implement to_string for some types 2023-07-25 14:39:30 +02:00
64407b6bee
Add a to_string for mechanism 2023-07-25 14:06:40 +02:00
6e3b12c11a
add info about deductible fields 2023-07-25 14:00:01 +02:00
7b7d9de92d
improve cargo.toml 2023-07-24 22:14:51 +02:00
6ce280151b
report all parsed data 2023-07-24 22:08:13 +02:00
07f969d109
Refactor how headers are handled 2023-07-24 19:19:49 +02:00
7db49875ea
capture preamble and epilogue 2023-07-24 18:32:26 +02:00
606d3f7494
returns the remaining bytes 2023-07-24 18:10:44 +02:00
4a46faa670
support multipart/digest parsing 2023-07-24 18:01:37 +02:00
9ddd480b0f
add more limitations 2023-07-24 15:55:58 +02:00
c3d273ed00
improve sota 2023-07-24 15:50:20 +02:00
df31b25b13
publish my sota 2023-07-24 15:48:48 +02:00
99725815af
Document a little bit the code 2023-07-24 14:41:21 +02:00
b330745e43
improve example 2023-07-24 14:05:47 +02:00
40ab7e33b6
refactor mime 2023-07-24 13:53:59 +02:00
16006781d0
fix typo 2023-07-24 13:46:00 +02:00
14e4c95fe7
Add a diagram of class 2023-07-24 13:44:52 +02:00
bcb5a81d32
Improve README 2023-07-24 13:05:13 +02:00
6af2e38ae3
Remove a warning 2023-07-24 12:45:31 +02:00
b50c60b7af
Add a support logo 2023-07-24 12:44:21 +02:00
efe3e85bd2
Clearly state that this project use GPLv3.0 or later 2023-07-24 12:41:10 +02:00
d42062ce48
reformat code again 2023-07-24 12:37:30 +02:00
5cfa06dbf8
split part mod in multiple files 2023-07-24 12:26:53 +02:00
e76cd78e4f
add an example 2023-07-24 11:17:47 +02:00
4ad0aad8be
refactor imf::message::Message 2023-07-24 11:09:21 +02:00
63892af012
refactor, mod rfc5322 to imf 2023-07-24 11:02:49 +02:00
28873ce073
improve boundary management 2023-07-24 10:27:32 +02:00
6c74860f82
apply clippy --fix 2023-07-24 09:24:38 +02:00
5f449714f5
add debug logic for MessageID 2023-07-23 19:14:42 +02:00
58f491ab85
fix test email 2023-07-23 19:00:21 +02:00
5da5172c27
remove debugging 2023-07-23 18:35:13 +02:00
80c0f6b5b9
no more warnings 2023-07-23 18:33:20 +02:00
755a095743
improve encoded word compatibility 2023-07-23 18:27:03 +02:00
971bbc6945
fix a bug 2023-07-23 17:37:24 +02:00
56fea0d869
Remove development status 2023-07-23 17:15:41 +02:00
0fb77ea831
update rfc implem 2023-07-23 17:14:58 +02:00
b4e8b99b22
more debug 2023-07-23 17:14:16 +02:00
c97595c128
format code 2023-07-23 16:37:47 +02:00
6e2b29ec57
try high level fx 2023-07-23 16:36:01 +02:00
efe037aa25
add a imf::message fx 2023-07-23 16:29:42 +02:00
e963965e77
working message parsing! 2023-07-23 16:20:38 +02:00
c7e8764c3a
multipart test 2023-07-23 13:25:33 +02:00
dd285dd7c0
fix tests 2023-07-23 12:38:39 +02:00
bdc5d19a1f
update readme 2023-07-23 12:35:38 +02:00
d0f346c92f
compiling part/part.rs 2023-07-23 12:24:46 +02:00
18b081cb9a
some refactor 2023-07-23 09:46:57 +02:00
00d36fd498
new approach to build mimeheader 2023-07-22 20:52:35 +02:00
7195e5f661
refactor mime logic 2023-07-22 17:40:32 +02:00
6c8e738d43
move boundary to text 2023-07-22 16:46:36 +02:00
5df9b253ec
simplify content type structs 2023-07-22 14:38:43 +02:00
a8ae9c3714
to_mime works 2023-07-22 14:23:37 +02:00
39d6847da7
mime section 2023-07-22 14:17:44 +02:00
59f550b439
generic header support 2023-07-22 13:51:19 +02:00
4baa976283
parse mime fields 2023-07-22 12:55:27 +02:00
d8363d70e8
more tests for content type 2023-07-22 12:14:37 +02:00
0d4e472d41
implement content-type 2023-07-22 11:53:26 +02:00
8fff581fb4
add back mime::version tests 2023-07-22 10:10:26 +02:00
75780c232b
fix mime atom 2023-07-22 09:47:20 +02:00
d4b1853513
wip type 2023-07-21 18:31:56 +02:00
42a5f928f6
change how mechanism work 2023-07-20 17:21:35 +02:00
6eba9d4033
parse mechanism 2023-07-20 17:07:18 +02:00
b444281729
reintroduce charset 2023-07-20 16:49:22 +02:00
ec937bf11d
extract common field logic to header 2023-07-20 16:26:59 +02:00
e2d9d03ef2
parse rfc5322 headers! 2023-07-20 15:51:13 +02:00
46dacb62c3
message compile 2023-07-20 15:05:54 +02:00
83a527b618
wip fields 2023-07-20 14:52:54 +02:00
b7ad47b41e
working field parsing 2023-07-20 09:41:10 +02:00
cd5289c8c1
wip, still broken 2023-07-19 22:27:59 +02:00
b3bec8656d
mime part of rfc5322 2023-07-19 19:30:07 +02:00
4d86afaacf
identification tests 2023-07-19 18:30:43 +02:00
b998aec37d
trace 2023-07-19 17:40:00 +02:00
54f6ce82a3
fix datetime tests 2023-07-19 16:28:24 +02:00
56166018a5
fix datetime code for bytes 2023-07-19 16:23:37 +02:00
6e7cb5500c
fix address 2023-07-19 15:56:03 +02:00
fd0794fe6e
fix mailbox tests 2023-07-19 15:28:17 +02:00
3c8d851ce6
compile rfc5322/mailbox 2023-07-19 12:09:23 +02:00
f98b43aaba
fixed tests 2023-07-19 11:03:40 +02:00
50b837438e
compile subset 2023-07-19 10:41:51 +02:00
a503eb1de6
wip refactor 2023-07-18 23:25:10 +02:00
23c663b943
wip refacto broken 2023-07-18 15:00:38 +02:00
16a5897f4e
wip parts 2023-07-17 17:14:08 +02:00
aa2c741921
add a preamble test 2023-07-17 11:44:55 +02:00
337d1a47c4
test boundary 2023-07-16 10:09:22 +02:00
52dc154616
fix compilation 2023-07-16 09:55:47 +02:00
a95095ed5d
wip 2023-07-14 19:12:34 +02:00
662d82aee9
update readme 2023-07-14 10:44:03 +02:00
6b3343f137
implement mime headers 2023-07-14 10:43:31 +02:00
4e82941fd0
decode base64 headers 2023-07-13 09:56:24 +02:00
76b921c9a3
successfully decode q encoding in header 2023-07-10 17:52:18 +02:00
d9471f443e
ptext test 2023-07-10 15:27:46 +02:00
decb4209d9
wip encoding 2023-07-10 11:16:39 +02:00
80f1fc9bb8
add tests to lazy parser 2023-07-10 11:14:49 +02:00
9b5ceafa5d
mime header fields 2023-07-04 15:50:45 +02:00
766eef71c7
reference multipart report 2023-07-04 15:32:08 +02:00
dc799f8677
add an ascii test 2023-07-04 15:02:01 +02:00
539f264d44
test message rfc822 2023-07-04 15:01:11 +02:00
3e8f374723
test multipart 2023-07-04 14:47:28 +02:00
cb7b767271
content type header 2023-07-04 14:37:53 +02:00
e3b10a994b
implement own charset system 2023-07-03 18:25:51 +02:00
f3dbf79927
parse version header 2023-07-03 17:05:17 +02:00
d64b7a0bbc
WIP mime headers 2023-07-03 11:40:02 +02:00
541c92f088
update todo list 2023-06-22 15:11:11 +02:00
5fda64477c
cargo fmt 2023-06-22 15:08:50 +02:00
99c6490eb2
remove obsolete fragments/header.rs 2023-06-22 15:05:52 +02:00
d30d38f124
fix enron test 2023-06-22 14:10:50 +02:00
14bcf119a7
re-enable parser 2023-06-22 12:21:18 +02:00
f7972f8fa5
move some tests from src/ to tests/ 2023-06-22 12:10:25 +02:00
39773d03ba
fix warnings 2023-06-22 11:15:01 +02:00
9d14868491
refactor parser! 2023-06-22 10:48:07 +02:00
34334398d8
Implement new parser in parse.rs 2023-06-20 18:58:07 +02:00
8e67af6c2c
borrow parsers (when it's possible) 2023-06-20 18:48:49 +02:00
2b7b5664c1
final section parser 2023-06-20 18:12:16 +02:00
458d6517d1
write an eager parser 2023-06-20 17:03:18 +02:00
e9c7da850e
refactor of lazy header parser 2023-06-20 15:56:06 +02:00
972ce658eb
new pass: field names 2023-06-20 11:49:00 +02:00
60 changed files with 5900 additions and 2642 deletions

39
Cargo.lock generated
View file

@ -23,6 +23,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "base64"
version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
[[package]] [[package]]
name = "bumpalo" name = "bumpalo"
version = "3.13.0" version = "3.13.0"
@ -41,17 +47,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chardetng"
version = "0.1.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14b8f0b65b7b08ae3c8187e8d77174de20cb6777864c6b832d8ad365999cf1ea"
dependencies = [
"cfg-if",
"encoding_rs",
"memchr",
]
[[package]] [[package]]
name = "chrono" name = "chrono"
version = "0.4.26" version = "0.4.26"
@ -73,6 +68,17 @@ version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa"
[[package]]
name = "eml-codec"
version = "0.1.2"
dependencies = [
"base64",
"chrono",
"encoding_rs",
"nom",
"walkdir",
]
[[package]] [[package]]
name = "encoding_rs" name = "encoding_rs"
version = "0.8.32" version = "0.8.32"
@ -105,17 +111,6 @@ dependencies = [
"cc", "cc",
] ]
[[package]]
name = "imf-codec"
version = "0.1.0"
dependencies = [
"chardetng",
"chrono",
"encoding_rs",
"nom",
"walkdir",
]
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.63" version = "0.3.63"

View file

@ -1,25 +1,33 @@
[package] [package]
name = "imf-codec" name = "eml-codec"
version = "0.1.0" version = "0.1.2"
edition = "2021" edition = "2021"
license = "GPL-3.0-or-later" license = "GPL-3.0-or-later"
repository = "https://git.deuxfleurs.fr/Deuxfleurs/eml-codec"
description = "Email enCOder DECoder in Rust. Support Internet Message Format and MIME (RFC 822, 5322, 2045, 2046, 2047, 2048, 2049)."
documentation = "https://docs.rs/eml-codec"
readme = "README.md"
exclude = [
"doc/",
"resources/",
]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib] [lib]
name = "imf_codec" name = "eml_codec"
path = "src/lib.rs" path = "src/lib.rs"
[[bin]] [[bin]]
name = "imf_parse" name = "eml_parse"
path = "src/parse.rs" path = "src/parse.rs"
[dependencies] [dependencies]
nom = "7" nom = "7"
chrono = "0.4" chrono = "0.4"
chardetng = "0.1" base64 = "0.21"
encoding_rs = "0.8" encoding_rs = "0.8"
[dev-dependencies] [dev-dependencies]
walkdir = "2" walkdir = "2"

674
LICENSE.txt Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

187
README.md
View file

@ -1,105 +1,144 @@
# imf-codec # eml-codec
**Work in progress, do not use in production** **⚠️ This is currently only a decoder (ie. a parser), encoding is not yet implemented.**
**This is currently only a decoder (parser), encoding is not supported.**
`eml-codec` is a child project of [Aerogramme](https://aerogramme.deuxfleurs.fr), a distributed and encrypted IMAP server developped by the non-profit organization [Deuxfleurs](https://deuxfleurs.fr).
Its aim is to be a swiss army knife to handle emails, whether it is to build an IMAP/JMAP server, a mail filter (like an antispam), or a mail client.
## Example
```rust
let input = br#"Date: 7 Mar 2023 08:00:00 +0200
From: deuxfleurs@example.com
To: someone_else@example.com
Subject: An RFC 822 formatted message
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
This is the plain text body of the message. Note the blank line
between the header information and the body of the message."#;
let (_, email) = eml_codec::parse_message(input).unwrap();
println!(
"{} just sent you an email with subject \"{}\"",
email.imf.from[0].to_string(),
email.imf.subject.unwrap().to_string(),
);
```
[See more examples in the examples/ folder](./examples/)
## About the name
This library does not aim at implementing a specific RFC, but to be a swiss-army knife to decode and encode ("codec") what is generaly considered an email (generally abbreviated "eml"), hence the name: **eml-codec**.
## Goals ## Goals
- Correctness: do no deviate from the RFC, support edge and obsolete cases - Maintainability - modifying the code does not create regression and is possible for someone exterior to the project.
- Straightforward/maintainable: implement the RFCs as close as possible, minimizing the amount of clever tricks and optimizations - Compatibility - always try to parse something, do not panic or return an error.
- Multiple syntax: Write the parser so it's easy to alternate between the strict and obsolete/compatible syntax - Exhaustivity - serve as a common project to encode knowledge about emails (existing mime types, existing headers, etc.).
- Never fail: Provide as many fallbacks as possible - Type safe - do not manipulate only strings/bytes but leverage Rust type system instead so you benefit from its safety checks at compile time.
## Non goals [See more about this library goals in the doc/ folder](./doc/goals.md)
- Parsing optimization (greedy parser, etc.) as it would require to significantly deviate from the RFC ABNF syntax (would consider this case if we could prove that the transformation we make are equivalent)
- Pipelining/streaming/buffering as the parser can arbitrarily backtrack + our result contains reference to the whole buffer, imf-codec must keep the whole buffer in memory. Avoiding the sequential approach would certainly speed-up a little bit the parsing, but it's too much work to implement currently.
- Zerocopy. It might be implementable in the future, but to quickly bootstrap this project, I avoided it for now.
## Missing / known bugs ## Missing / known bugs
Current known limitations/bugs: Current known limitations/bugs:
- **Part transfer-decoding is not implemented yet**
- **Internationalized headers (UTF-8) is not implemented yet**
- Resent Header Fields are not implemented - Resent Header Fields are not implemented
- Return-Path/Received headers might be hard to use as their order is important, and it's currently lost in the final datastructure. - Return-Path/Received headers might be hard to use as their order is important, and it's currently lost in the final datastructure.
- Datetime parsing of invalid date might return `None` instead of falling back to the `bad_body` field - Datetime parsing of invalid date might return `None` instead of falling back to the `bad_body` field
- Comments are dropped - Comments contained in the email headers are dropped during parsing
- No support is provided for message/external-body (read data from local computer) and message/partial (aggregate multiple fragmented emails) as they seem obsolete and dangerous to implement.
## Design ## Design
Based on nom, a parser combinator lib in Rust. High-level overview of the datastructures (inspired by the UML class diagram conventions):
multipass parser
- extract header block: `&[u8]` (find \r\n\r\n OR \n\n OR \r\r OR \r\n)
- decode/convert it with chardet + encoding\_rs to support latin-1: Cow<&str>
- extract header lines iter::&str (requires only to search for FWS + obs\_CRLF)
- extract header names iter::Name::From(&str)
- extract header body iter::Body::From(Vec<MailboxRef>)
- extract header section Section
recovery ![Diagram of class made on Draw.io](./doc/class-uml.png)
- based on multipass, equivalent to sentinel / synchronization tokens
## Testing strategy ## Testing strategy
imf-codec aims to be as much tested as possible against reald Currently this crate has some unit tests on most of its parsing functions.
It is also tested as part of Aerogramme, its parent project where it handles email parsing.
In this project, `eml-codec` parsing capabilities are compared to Dovecot, Cyrus, Maddy and other IMAP servers.
### Unit testing: parser combinator independently (done) It is planned to test it on large email datasets (like Enron, jpbush, mailing lists, etc.) but it's not done yet.
Fuzzing the library would also be interesting, probably to detect crashing due to stack overflow for example
due to the infinite recursivity of MIME.
### Selected full emails (expected) ## RFC and IANA references
### Existing datasets RFC
**Enron 500k** - Took 20 minutes to parse ~517k emails and check that
RFC5322 headers (From, To, Cc, etc.) are correctly parsed.
From this list, we had to exclude ~50 emails on which
the From/To/Cc fields were simply completely wrong, but while
some fields failed to parse, the parser did not crash and
parsed the other fields of the email correctly.
Run it on your machine:
```bash
cargo test -- --ignored --nocapture enron500k
```
Planned: jpbush, my inbox, etc.
### Fuzzing (expected)
### Across reference IMAP servers (dovevot, cyrus) (expected)
## Development status
Early development. Not ready.
Do not use it in production or any software at all.
Todo:
- [X] test over the enron dataset
- [ ] convert to multipass parser
- [ ] implement mime part 3 (encoded headers)
- [ ] implement mime part 1 (new headers)
- [ ] review part 2 (media types) and part 4 (registration procedure) but might be out of scope
- [ ] implement some targeted testing as part of mime part 5
- [ ] implement fuzzing through cargo fuzz
- [ ] test over other datasets (jpbush, ml, my inbox)
- [ ] backport to aerogramme
- [ ] fix warnings, put examples, document the public API a little bit
## Targeted RFC
| 🚩 | # | Name | | 🚩 | # | Name |
|----|---|------| |----|---|------|
| 🟩 |822 | ARPA INTERNET TEXT MESSAGES| | 🟩 |822 | ARPA INTERNET TEXT MESSAGES|
| 🟩 |2822 | Internet Message Format (2001) | | 🟩 |2822 | Internet Message Format (2001) |
| 🟩 |5322 | Internet Message Format (2008) | | 🟩 |5322 | Internet Message Format (2008) |
| 🔴 |2045 | ↳ Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies | | 🟩 |2045 | ↳ Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies |
| 🔴 |2046 | ↳ Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types | | 🟩 |2046 | ↳ Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types |
| 🔴 |2047 | ↳ MIME (Multipurpose Internet Mail Extensions) Part Three: Message Header Extensions for Non-ASCII Text | | 🟩 |2047 | ↳ MIME (Multipurpose Internet Mail Extensions) Part Three: Message Header Extensions for Non-ASCII Text |
| 🔴 |2048 | ↳ Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures | | 🟩 |2048 | ↳ Multipurpose Internet Mail Extensions (MIME) Part Four: Registration Procedures |
| 🔴 |2049 | ↳ Multipurpose Internet Mail Extensions (MIME) Part Five: Conformance Criteria and Examples | | 🟩 |2049 | ↳ Multipurpose Internet Mail Extensions (MIME) Part Five: Conformance Criteria and Examples |
| 🟩 |6532 | Internationalized Email Headers | | | | **Headers extensions** |
| 🔴 |9228 | Delivered-To Email Header Field | | 🔴 |2183 | ↳ Communicating Presentation Information in Internet Messages: The Content-Disposition Header Field |
| 🔴 |6532 | ↳ Internationalized Email Headers |
| 🔴 |9228 | ↳ Delivered-To Email Header Field |
| | | **MIME extensions** |
| 🔴 |1847 | ↳ Security Multiparts for MIME: Multipart/Signed and Multipart/Encrypted |
| 🔴 |2387 | ↳ The MIME Multipart/Related Content-type |
| 🔴 |3462 | ↳ The Multipart/Report Content Type for the Reporting of Mail System Administrative Messages |
| 🔴 |3798 | ↳ Message Disposition Notification |
| 🔴 |6838 | ↳ Media Type Specifications and Registration Procedures |
## Alternatives IANA
`stalwartlab/mail_parser` | Name | Description | Note |
|------|-------------|------|
| [Media Types](https://www.iana.org/assignments/media-types/media-types.xhtml) | Registered media types for the Content-Type field | Currently only the media types in the MIME RFC have dedicated support in `eml-codec`. |
| [Character sets](https://www.iana.org/assignments/character-sets/character-sets.xhtml) | Supported character sets for the `charset` parameter | They should all be supported through the `encoding_rs` crate |
## State of the art / alternatives
The following review is not an objective, neutral, impartial review. Instead, it's a temptative
to explain why I wrote this library. If you find something outdated or objectively wrong, feel free to open a PR or an issue to fix it.
In no case, I think `eml-codec` is superior, it's just another approach to the problem, and I see it as another stone to the edifice.
[mail\_parser](https://github.com/stalwartlabs/mail-parser), [mailparse](https://github.com/staktrace/mailparse) and [rust-email](https://github.com/deltachat/rust-email)
are 3 handwritten parsers. Such handwritten parsers do not encourage separation of concerns: `mail_parser` and `mailparse` feature large functions with hundreds of lines
with a high cylomatic complexity. Due to this complex logic, I have failed to debug/patch such code in the past.
`rust-email` code is easier to read but its mime part implementation is marked as unstable. `mail_parser` is used in the IMAP/JMAP/SMTP server project [stalwartlabs/mail-server](https://github.com/stalwartlabs/mail-server) and `rust-email` is used in the email-based chat application [Deltachat](https://github.com/deltachat) (however `rust-email` MIME parsed is not used, a custom MIME parser is reimplemented in Delta Chat instead). It must be noted that `mail_parser` supports a large amount of extensions (UTF-8 headers, UTF-7 encoding, continuation, many custom fields, etc.) and would better cope with malformed emails than other libraries. **A goal of `eml_codec` is to be open to contribution and maintainable over time, which is made possible trough the parser combinator pattern that encourages writing small, reusable, independently testable functions.**
[rustyknife](https://github.com/jothan/rustyknife) uses the same design pattern (parser combinator) and the same library ([nom](https://github.com/rust-bakery/nom)) as `eml_codec`. However, `rustyknife` is more targeted to SMTP servers (MTA) than IMAP (MDA) and email clients (MUA).
It thus only supports parsing headers and not emails' body. Also, an acquaintance warned me that this library is a bit slow,
it might be due to the fact that the library does some processing while parsing the email (like rebuilding and allocating strings).
If it happens that this part is not used later, the allocation/processing has been wasted.
**A goal of `eml_codec` is to produce an AST of the email with as few processing as possible, so that the parsing remains efficient,
and then the allocation/processing is made lazily, on demand, when the corresponding function is called. It is often referred as zero-copy.**
## Support
`eml-codec`, as part of the [Aerogramme project](https://nlnet.nl/project/Aerogramme/), was funded through the NGI Assure Fund, a fund established by NLnet with financial support from the European Commission's Next Generation Internet programme, under the aegis of DG Communications Networks, Content and Technology under grant agreement No 957073.
![NLnet logo](https://aerogramme.deuxfleurs.fr/images/nlnet.svg)
## License
eml-codec
Copyright (C) The eml-codec Contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

BIN
doc/class-uml.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

14
doc/goals.md Normal file
View file

@ -0,0 +1,14 @@
## Goals
- Maintainability - modifying the code does not create regression and is possible for someone exterior to the project. Keep cyclomatic complexity low.
- Composability - build your own parser by picking the relevant passes, avoid work that is not needed.
- Compatibility - always try to parse something, do not panic or return an error.
- Exhaustivity - serve as a common project to encode knowledge about emails (existing mime types, existing headers, etc.).
## Non goals
- Parsing optimization that would make more complicated to understand the logic.
- Optimization for a specific use case, to the detriment of other use cases.
- Pipelining/streaming/buffering as the parser can arbitrarily backtrack + our result contains reference to the whole buffer, eml-codec must keep the whole buffer in memory. Avoiding the sequential approach would certainly speed-up a little bit the parsing, but it's too much work to implement currently.

27
examples/simple.rs Normal file
View file

@ -0,0 +1,27 @@
pub fn main() {
let input = br#"Date: 7 Mar 2023 08:00:00 +0200
From: deuxfleurs@example.com
To: someone_else@example.com
Subject: An RFC 822 formatted message
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
This is the plain text body of the message. Note the blank line
between the header information and the body of the message."#;
// if you are only interested in email metadata/headers
let (_, imf) = eml_codec::parse_imf(input).unwrap();
println!(
"{} just sent you an email with subject \"{}\"",
imf.from[0].to_string(),
imf.subject.unwrap().to_string(),
);
// if you like to also parse the body/content
let (_, email) = eml_codec::parse_message(input).unwrap();
println!(
"{} raw message is:\n{}",
email.imf.from[0].to_string(),
String::from_utf8_lossy(email.child.as_text().unwrap().body),
);
}

View file

@ -1,8 +0,0 @@
Test enron files:
```
cd resources/enron
./restore.sh
cd -
(set -euo pipefail; find resources/enron/maildir/ -type f | while read f; do echo $f; ./target/debug/imf_parse < $f > /dev/null; done)
```

View file

@ -1,5 +1,5 @@
From: Art Vandelay <art@vandelay.com> (Vandelay Industries) From: Art Vandelay <art@vandelay.com> (Vandelay Industries)
To: "Colleagues": "James Smythe" <james@vandelay.com>; Friends: To: "Colleagues": "James Smythe" <james@vandelay.com>;, Friends:
jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>; jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;
Date: Sat, 20 Nov 2021 14:22:01 -0800 Date: Sat, 20 Nov 2021 14:22:01 -0800
Subject: Why not both importing AND exporting? Subject: Why not both importing AND exporting?

View file

@ -1,6 +0,0 @@
From: someone@example.com
To: someone_else@example.com
Subject: An RFC 822 formatted message
This is the plain text body of the message. Note the blank line
between the header information and the body of the message.

View file

@ -1,7 +0,0 @@
use nom;
#[derive(Debug, PartialEq)]
pub enum IMFError<'a> {
Segment(nom::Err<nom::error::Error<&'a [u8]>>),
ExtractFields(nom::Err<nom::error::Error<&'a str>>),
}

View file

@ -1,124 +0,0 @@
use nom::{
IResult,
branch::alt,
bytes::complete::tag,
combinator::{into, opt, map_res},
multi::separated_list1,
sequence::tuple,
};
use crate::fragments::model::{GroupRef, AddressRef, MailboxRef};
use crate::fragments::mailbox::{addr_spec, mailbox};
use crate::fragments::misc_token::phrase;
use crate::fragments::whitespace::{cfws};
/// Address (section 3.4 of RFC5322)
///
/// ```abnf
/// address = mailbox / group
/// ```
pub fn address(input: &str) -> IResult<&str, AddressRef> {
alt((into(mailbox), into(group)))(input)
}
/// Group
///
/// ```abnf
/// group = display-name ":" [group-list] ";" [CFWS]
/// display-name = phrase
/// ```
pub fn group(input: &str) -> IResult<&str, GroupRef> {
let (input, (grp_name, _, grp_list, _, _)) =
tuple((phrase, tag(":"), opt(group_list), tag(";"), opt(cfws)))(input)?;
Ok((input, GroupRef {
name: grp_name,
participants: grp_list.unwrap_or(vec![]),
}))
}
/// Group list
///
/// ```abnf
/// group-list = mailbox-list / CFWS / obs-group-list
/// ```
pub fn group_list(input: &str) -> IResult<&str, Vec<MailboxRef>> {
alt((mailbox_list, mailbox_cfws))(input)
}
fn mailbox_cfws(input: &str) -> IResult<&str, Vec<MailboxRef>> {
let (input, _) = cfws(input)?;
Ok((input, vec![]))
}
/// Mailbox list
///
/// ```abnf
/// mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
/// ```
pub fn mailbox_list(input: &str) -> IResult<&str, Vec<MailboxRef>> {
separated_list1(tag(","), mailbox)(input)
}
/// Address list
///
/// ```abnf
/// address-list = (address *("," address)) / obs-addr-list
/// ```
pub fn address_list(input: &str) -> IResult<&str, Vec<AddressRef>> {
separated_list1(tag(","), address)(input)
}
pub fn address_list_cfws(input: &str) -> IResult<&str, Vec<AddressRef>> {
let (input, _) = cfws(input)?;
Ok((input, vec![]))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fragments::model::AddrSpec;
#[test]
fn test_mailbox_list() {
match mailbox_list(r#"Pete(A nice \) chap) <pete(his account)@silly.test(his host)>"#) {
Ok(("", _)) => (),
_ => panic!(),
};
match mailbox_list(r#"Mary Smith <mary@x.test>, jdoe@example.org, Who? <one@y.test>, <boss@nil.test>, "Giant; \"Big\" Box" <sysservices@example.net>"#) {
Ok(("", _)) => (),
_ => panic!(),
};
}
#[test]
fn test_address_list() {
assert_eq!(
address_list(r#"A Group:Ed Jones <c@a.test>,joe@where.test,John <jdoe@one.test>;, Mary Smith <mary@x.test>"#),
Ok(("", vec![
AddressRef::Many(GroupRef {
name: "A Group".to_string(),
participants: vec![
MailboxRef {
name: Some("Ed Jones".into()),
addrspec: AddrSpec { local_part: "c".into(), domain: "a.test".into() },
},
MailboxRef {
name: None,
addrspec: AddrSpec { local_part: "joe".into(), domain: "where.test".into() },
},
MailboxRef {
name: Some("John".into()),
addrspec: AddrSpec { local_part: "jdoe".into(), domain: "one.test".into() },
},
],
}),
AddressRef::Single(MailboxRef {
name: Some("Mary Smith".into()),
addrspec: AddrSpec { local_part: "mary".into(), domain: "x.test".into() },
}),
]))
);
}
}

View file

@ -1,393 +0,0 @@
use chrono::{DateTime, FixedOffset, NaiveDate, NaiveTime, TimeZone};
use nom::{
IResult,
AsChar,
branch::alt,
bytes::complete::{tag, tag_no_case, take_while, take_while1, take_while_m_n, is_a},
character,
character::is_digit,
character::complete::{one_of, alphanumeric1, digit0},
combinator::{map, opt, value},
sequence::{preceded, terminated, tuple, delimited },
};
use crate::fragments::misc_token;
use crate::fragments::whitespace::{fws, cfws};
const MIN: i32 = 60;
const HOUR: i32 = 60 * MIN;
/// Read datetime
///
/// ```abnf
/// date-time = [ day-of-week "," ] date time [CFWS]
/// time = time-of-day zone
/// ```
///
/// ## @FIXME - known bugs
///
/// - if chrono fails, Option::None is silently returned instead of failing the parser
/// - `-0000` means NaiveDateTime, a date without a timezone
/// while this library interprets it as +0000 aka UTC.
/// - Obsolete military zones should be considered as NaiveTime
/// due to an error in RFC0822 but are interpreted as their respective
/// timezone according to the RFC5322 definition
pub fn section(input: &str) -> IResult<&str, Option<DateTime<FixedOffset>>> {
map(terminated(
alt((
tuple((opt(terminated(strict_day_of_week, tag(","))), strict_date, strict_time_of_day, strict_zone )),
tuple((opt(terminated(obs_day_of_week, tag(","))), obs_date, obs_time_of_day, alt((strict_zone, obs_zone)) )),
)),
opt(cfws)
), |res| {
match res {
(_, Some(date), Some(time), Some(tz)) => {
date.and_time(time).and_local_timezone(tz).earliest()
},
_ => None,
}
})(input)
}
/// day-of-week = ([FWS] day-name) / obs-day-of-week
fn strict_day_of_week(input: &str) -> IResult<&str, &str> {
preceded(opt(fws), day_name)(input)
}
/// obs-day-of-week = [CFWS] day-name [CFWS]
fn obs_day_of_week(input: &str) -> IResult<&str, &str> {
delimited(opt(cfws), day_name, opt(cfws))(input)
}
/// day-name = "Mon" / "Tue" / "Wed" / "Thu" /
/// "Fri" / "Sat" / "Sun"
fn day_name(input: &str) -> IResult<&str, &str> {
alt((
tag_no_case("Mon"),
tag_no_case("Tue"),
tag_no_case("Wed"),
tag_no_case("Thu"),
tag_no_case("Fri"),
tag_no_case("Sat"),
tag_no_case("Sun"),
))(input)
}
/// date = day month year
fn strict_date(input: &str) -> IResult<&str, Option<NaiveDate>> {
map(
tuple((strict_day, month, strict_year)),
|(d, m, y)| NaiveDate::from_ymd_opt(y, m, d)
)(input)
}
/// date = day month year
fn obs_date(input: &str) -> IResult<&str, Option<NaiveDate>> {
map(
tuple((obs_day, month, obs_year)),
|(d, m, y)| NaiveDate::from_ymd_opt(y, m, d)
)(input)
}
/// day = ([FWS] 1*2DIGIT FWS) / obs-day
fn strict_day(input: &str) -> IResult<&str, u32> {
delimited(opt(fws), character::complete::u32, fws)(input)
}
/// obs-day = [CFWS] 1*2DIGIT [CFWS]
fn obs_day(input: &str) -> IResult<&str, u32> {
delimited(opt(cfws), character::complete::u32, opt(cfws))(input)
}
/// month = "Jan" / "Feb" / "Mar" / "Apr" /
/// "May" / "Jun" / "Jul" / "Aug" /
/// "Sep" / "Oct" / "Nov" / "Dec"
fn month(input: &str) -> IResult<&str, u32> {
alt((
value(1, tag_no_case("Jan")),
value(2, tag_no_case("Feb")),
value(3, tag_no_case("Mar")),
value(4, tag_no_case("Apr")),
value(5, tag_no_case("May")),
value(6, tag_no_case("Jun")),
value(7, tag_no_case("Jul")),
value(8, tag_no_case("Aug")),
value(9, tag_no_case("Sep")),
value(10, tag_no_case("Oct")),
value(11, tag_no_case("Nov")),
value(12, tag_no_case("Dec")),
))(input)
}
/// year = (FWS 4*DIGIT FWS) / obs-year
fn strict_year(input: &str) -> IResult<&str, i32> {
delimited(
fws,
map(
terminated(take_while_m_n(4,9,|c| c >= '\x30' && c <= '\x39'), digit0),
|d: &str| d.parse::<i32>().unwrap()),
fws,
)(input)
}
/// obs-year = [CFWS] 2*DIGIT [CFWS]
fn obs_year(input: &str) -> IResult<&str, i32> {
map(delimited(
opt(cfws),
terminated(take_while_m_n(2,7,|c| c >= '\x30' && c <= '\x39'), digit0),
opt(cfws)
), |cap: &str| {
let d = cap.parse::<i32>().unwrap();
if d >= 0 && d <= 49 {
2000 + d
} else if d >= 50 && d <= 999 {
1900 + d
} else {
d
}
})(input)
}
/// time-of-day = hour ":" minute [ ":" second ]
fn strict_time_of_day(input: &str) -> IResult<&str, Option<NaiveTime>> {
map(
tuple((strict_time_digit, tag(":"), strict_time_digit, opt(preceded(tag(":"), strict_time_digit)))),
|(hour, _, minute, maybe_sec)| NaiveTime::from_hms_opt(hour, minute, maybe_sec.unwrap_or(0)),
)(input)
}
/// time-of-day = hour ":" minute [ ":" second ]
fn obs_time_of_day(input: &str) -> IResult<&str, Option<NaiveTime>> {
map(
tuple((obs_time_digit, tag(":"), obs_time_digit, opt(preceded(tag(":"), obs_time_digit)))),
|(hour, _, minute, maybe_sec)| NaiveTime::from_hms_opt(hour, minute, maybe_sec.unwrap_or(0)),
)(input)
}
fn strict_time_digit(input: &str) -> IResult<&str, u32> {
character::complete::u32(input)
}
fn obs_time_digit(input: &str) -> IResult<&str, u32> {
delimited(opt(cfws), character::complete::u32, opt(cfws))(input)
}
/// Obsolete zones
///
/// ```abnf
/// zone = (FWS ( "+" / "-" ) 4DIGIT) / (FWS obs-zone)
/// ```
fn strict_zone(input: &str) -> IResult<&str, Option<FixedOffset>> {
map(
tuple((opt(fws), is_a("+-"), take_while_m_n(2,2,|c| c >= '\x30' && c <= '\x39'), take_while_m_n(2,2,|c| c >= '\x30' && c <= '\x39'))),
|(_, op, dig_zone_hour, dig_zone_min)| {
let zone_hour = dig_zone_hour.parse::<i32>().unwrap() * HOUR;
let zone_min = dig_zone_min.parse::<i32>().unwrap() * MIN;
match op {
"+" => FixedOffset::east_opt(zone_hour + zone_min),
"-" => FixedOffset::west_opt(zone_hour + zone_min),
_ => unreachable!(), }
}
)(input)
}
/// obsole zone
///
/// obs-zone = "UT" / "GMT" / ; Universal Time
/// ; North American UT
/// ; offsets
/// "EST" / "EDT" / ; Eastern: - 5/ - 4
/// "CST" / "CDT" / ; Central: - 6/ - 5
/// "MST" / "MDT" / ; Mountain: - 7/ - 6
/// "PST" / "PDT" / ; Pacific: - 8/ - 7
/// ;
/// %d65-73 / ; Military zones - "A"
/// %d75-90 / ; through "I" and "K"
/// %d97-105 / ; through "Z", both
/// %d107-122 / ; upper and lower case
/// ;
/// 1*(ALPHA / DIGIT) ; Unknown legacy timezones
fn obs_zone(input: &str) -> IResult<&str, Option<FixedOffset>> {
// The writing of this function is volontarily verbose
// to keep it straightforward to understand.
// @FIXME: Could return a TimeZone and not an Option<TimeZone>
// as it could be determined at compile time if values are correct
// and panic at this time if not. But not sure how to do it without unwrap.
preceded(
opt(fws),
alt((
// Legacy UTC/GMT
value(FixedOffset::west_opt(0 * HOUR), alt((tag("UTC"), tag("UT"), tag("GMT")))),
// USA Timezones
value(FixedOffset::west_opt(4 * HOUR), tag("EDT")),
value(FixedOffset::west_opt(5 * HOUR), alt((tag("EST"), tag("CDT")))),
value(FixedOffset::west_opt(6 * HOUR), alt((tag("CST"), tag("MDT")))),
value(FixedOffset::west_opt(7 * HOUR), alt((tag("MST"), tag("PDT")))),
value(FixedOffset::west_opt(8 * HOUR), tag("PST")),
// Military Timezone UTC
value(FixedOffset::west_opt(0 * HOUR), tag("Z")),
// Military Timezones East
map(one_of("ABCDEFGHIKLMabcdefghiklm"), |c| match c {
'A' | 'a' => FixedOffset::east_opt(1 * HOUR),
'B' | 'b' => FixedOffset::east_opt(2 * HOUR),
'C' | 'c' => FixedOffset::east_opt(3 * HOUR),
'D' | 'd' => FixedOffset::east_opt(4 * HOUR),
'E' | 'e' => FixedOffset::east_opt(5 * HOUR),
'F' | 'f' => FixedOffset::east_opt(6 * HOUR),
'G' | 'g' => FixedOffset::east_opt(7 * HOUR),
'H' | 'h' => FixedOffset::east_opt(8 * HOUR),
'I' | 'i' => FixedOffset::east_opt(9 * HOUR),
'K' | 'k' => FixedOffset::east_opt(10 * HOUR),
'L' | 'l' => FixedOffset::east_opt(11 * HOUR),
'M' | 'm' => FixedOffset::east_opt(12 * HOUR),
_ => unreachable!(),
}),
// Military Timezones West
map(one_of("nopqrstuvwxyNOPQRSTUVWXY"), |c| match c {
'N' | 'n' => FixedOffset::west_opt(1 * HOUR),
'O' | 'o' => FixedOffset::west_opt(2 * HOUR),
'P' | 'p' => FixedOffset::west_opt(3 * HOUR),
'Q' | 'q' => FixedOffset::west_opt(4 * HOUR),
'R' | 'r' => FixedOffset::west_opt(5 * HOUR),
'S' | 's' => FixedOffset::west_opt(6 * HOUR),
'T' | 't' => FixedOffset::west_opt(7 * HOUR),
'U' | 'u' => FixedOffset::west_opt(8 * HOUR),
'V' | 'v' => FixedOffset::west_opt(9 * HOUR),
'W' | 'w' => FixedOffset::west_opt(10 * HOUR),
'X' | 'x' => FixedOffset::west_opt(11 * HOUR),
'Y' | 'y' => FixedOffset::west_opt(12 * HOUR),
_ => unreachable!(),
}),
// Unknown timezone
value(FixedOffset::west_opt(0 * HOUR), alphanumeric1),
)),
)(input)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_section_rfc_strict() {
assert_eq!(
section("Fri, 21 Nov 1997 09:55:06 -0600"),
Ok(("", Some(FixedOffset::west_opt(6 * HOUR).unwrap().with_ymd_and_hms(1997, 11, 21, 9, 55, 6).unwrap()))),
);
}
#[test]
fn test_section_received() {
assert_eq!(
section("Sun, 18 Jun 2023 15:39:08 +0200 (CEST)"),
Ok(("", Some(FixedOffset::east_opt(2 * HOUR).unwrap().with_ymd_and_hms(2023, 6, 18, 15, 39, 8).unwrap()))),
);
}
#[test]
fn test_section_rfc_ws() {
assert_eq!(
section(
r#"Thu,
13
Feb
1969
23:32
-0330 (Newfoundland Time)"#),
Ok(("", Some(FixedOffset::west_opt(3 * HOUR + 30 * MIN).unwrap().with_ymd_and_hms(1969, 2, 13, 23, 32, 00).unwrap()))),
);
}
#[test]
fn test_section_rfc_obs() {
assert_eq!(
section("21 Nov 97 09:55:06 GMT"),
Ok(("", Some(FixedOffset::east_opt(0).unwrap().with_ymd_and_hms(1997, 11, 21, 9, 55, 6).unwrap()))),
);
}
#[test]
fn test_section_3digit_year() {
assert_eq!(
section("21 Nov 103 09:55:06 UT"),
Ok(("", Some(FixedOffset::east_opt(0).unwrap().with_ymd_and_hms(2003, 11, 21, 9, 55, 6).unwrap()))),
);
}
#[test]
fn test_section_rfc_obs_ws() {
assert_eq!(
section("Fri, 21 Nov 1997 09(comment): 55 : 06 -0600"),
Ok(("", Some(FixedOffset::west_opt(6 * HOUR).unwrap().with_ymd_and_hms(1997, 11, 21, 9, 55, 6).unwrap()))),
);
}
#[test]
fn test_section_2digit_year() {
assert_eq!(
section("21 Nov 23 09:55:06Z"),
Ok(("", Some(FixedOffset::east_opt(0).unwrap().with_ymd_and_hms(2023, 11, 21, 9, 55, 6).unwrap()))),
);
}
#[test]
fn test_section_military_zone_east() {
["a", "B", "c", "D", "e", "F", "g", "H", "i", "K", "l", "M"].iter().enumerate().for_each(|(i, x)| {
assert_eq!(
section(format!("1 Jan 22 08:00:00 {}", x).as_str()),
Ok(("", Some(FixedOffset::east_opt((i as i32 + 1) * HOUR).unwrap().with_ymd_and_hms(2022, 01, 01, 8, 0, 0).unwrap())))
);
});
}
#[test]
fn test_section_military_zone_west() {
["N", "O", "P", "q", "r", "s", "T", "U", "V", "w", "x", "y"].iter().enumerate().for_each(|(i, x)| {
assert_eq!(
section(format!("1 Jan 22 08:00:00 {}", x).as_str()),
Ok(("", Some(FixedOffset::west_opt((i as i32 + 1) * HOUR).unwrap().with_ymd_and_hms(2022, 01, 01, 8, 0, 0).unwrap())))
);
});
}
#[test]
fn test_section_gmt() {
assert_eq!(
section("21 Nov 2023 07:07:07 +0000"),
Ok(("", Some(FixedOffset::east_opt(0).unwrap().with_ymd_and_hms(2023, 11, 21, 7, 7, 7).unwrap()))),
);
assert_eq!(
section("21 Nov 2023 07:07:07 -0000"),
Ok(("", Some(FixedOffset::east_opt(0).unwrap().with_ymd_and_hms(2023, 11, 21, 7, 7, 7).unwrap()))),
);
assert_eq!(
section("21 Nov 2023 07:07:07 Z"),
Ok(("", Some(FixedOffset::east_opt(0).unwrap().with_ymd_and_hms(2023, 11, 21, 7, 7, 7).unwrap()))),
);
assert_eq!(
section("21 Nov 2023 07:07:07 GMT"),
Ok(("", Some(FixedOffset::east_opt(0).unwrap().with_ymd_and_hms(2023, 11, 21, 7, 7, 7).unwrap()))),
);
assert_eq!(
section("21 Nov 2023 07:07:07 UT"),
Ok(("", Some(FixedOffset::east_opt(0).unwrap().with_ymd_and_hms(2023, 11, 21, 7, 7, 7).unwrap()))),
);
assert_eq!(
section("21 Nov 2023 07:07:07 UTC"),
Ok(("", Some(FixedOffset::east_opt(0).unwrap().with_ymd_and_hms(2023, 11, 21, 7, 7, 7).unwrap()))),
);
}
#[test]
fn test_section_usa() {
assert_eq!(
section("21 Nov 2023 4:4:4 CST"),
Ok(("", Some(FixedOffset::west_opt(6 * HOUR).unwrap().with_ymd_and_hms(2023, 11, 21, 4, 4, 4).unwrap()))),
);
}
}

View file

@ -1,650 +0,0 @@
use std::borrow::Cow;
use chrono::{DateTime, FixedOffset};
use nom::{
IResult,
Parser,
branch::alt,
bytes::complete::{is_not, take_while1, take_while, tag, tag_no_case},
character::complete::space0,
combinator::{map, opt, recognize},
multi::{many0, many1, fold_many0, separated_list1},
sequence::{terminated, preceded, pair, tuple},
};
use chardetng::EncodingDetector;
use encoding_rs::Encoding;
use crate::fragments::whitespace::{fws, perm_crlf};
use crate::fragments::words::vchar_seq;
use crate::fragments::misc_token::{phrase, unstructured};
use crate::fragments::model::{HeaderSection, MailboxRef, AddressRef, Field, FieldBody};
use crate::fragments::mailbox::mailbox;
use crate::fragments::address::{mailbox_list, address_list, address_list_cfws};
use crate::fragments::identification::msg_id;
use crate::fragments::{datetime, trace, model};
/// HEADERS
///
pub fn from_bytes<'a>(rawmail: &'a [u8]) -> (Cow<'a, str>, &Encoding, bool) {
// Create detector
let mut detector = EncodingDetector::new();
detector.feed(&rawmail, true);
// Get encoding
let enc: &Encoding = detector.guess(None, true);
enc.decode(&rawmail)
}
/// Internal header section
///
/// See: https://www.rfc-editor.org/rfc/rfc5322.html#section-2.2
pub fn section<'a>(input: &'a str) -> IResult<&'a str, HeaderSection> {
let (input, headers) = fold_many0(
alt((known_field, unknown_field, rescue_field)),
HeaderSection::default,
|mut section, head| {
match head {
//@FIXME min and max limits are not enforced,
// it may result in missing data or silently overriden data.
// 3.6.1. The Origination Date Field
// | orig-date | 1 | 1 | |
Field::Date(FieldBody::Correct(d)) => {
section.date = d;
}
// 3.6.2. Originator Fields
Field::From(FieldBody::Correct(v)) => {
// | from | 1 | 1 | See sender and 3.6.2 |
section.from = v;
}
Field::Sender(FieldBody::Correct(mbx)) => {
// | sender | 0* | 1 | MUST occur with multi-address from - see 3.6.2 |
section.sender = Some(mbx);
}
Field::ReplyTo(FieldBody::Correct(addr_list)) => {
// | reply-to | 0 | 1 | |
section.reply_to = addr_list;
}
// 3.6.3. Destination Address Fields
Field::To(FieldBody::Correct(addr_list)) => {
// | to | 0 | 1 | |
section.to = addr_list;
}
Field::Cc(FieldBody::Correct(addr_list)) => {
// | cc | 0 | 1 | |
section.cc = addr_list;
}
Field::Bcc(FieldBody::Correct(addr_list)) => {
// | bcc | 0 | 1 | |
section.bcc = addr_list;
}
// 3.6.4. Identification Fields
Field::MessageID(FieldBody::Correct(msg_id)) => {
// | message-id | 0* | 1 | SHOULD be present - see 3.6.4 |
section.msg_id = Some(msg_id);
}
Field::InReplyTo(FieldBody::Correct(id_list)) => {
// | in-reply-to | 0* | 1 | SHOULD occur in some replies - see 3.6.4 |
section.in_reply_to = id_list;
}
Field::References(FieldBody::Correct(id_list)) => {
// | in-reply-to | 0* | 1 | SHOULD occur in some replies - see 3.6.4 |
section.references = id_list;
}
// 3.6.5. Informational Fields
Field::Subject(FieldBody::Correct(title)) => {
// | subject | 0 | 1 | |
section.subject = Some(title);
}
Field::Comments(FieldBody::Correct(coms)) => {
// | comments | 0 | unlimited | |
section.comments.push(coms);
}
Field::Keywords(FieldBody::Correct(mut kws)) => {
// | keywords | 0 | unlimited | |
section.keywords.append(&mut kws);
}
// 3.6.6 Resent Fields are not implemented
// 3.6.7 Trace Fields
Field::ReturnPath(FieldBody::Correct(maybe_mbx)) => {
if let Some(mbx) = maybe_mbx {
section.return_path.push(mbx);
}
}
Field::Received(FieldBody::Correct(log)) => {
section.received.push(log);
}
// 3.6.8. Optional Fields
Field::Optional(name, body) => {
section.optional.insert(name, body);
}
// Rescue
Field::Rescue(x) => {
section.unparsed.push(x);
}
bad_field => {
section.bad_fields.push(bad_field);
}
};
section
}
)(input)?;
let (input, _) = perm_crlf(input)?;
Ok((input, headers))
}
/// Parse one known header field
///
/// RFC5322 optional-field seems to be a generalization of the field terminology.
/// We use it to parse all header names:
pub fn known_field(input: &str) -> IResult<&str, Field> {
terminated(
alt((
// 3.6.1. The Origination Date Field
date,
// 3.6.2. Originator Fields
alt((from, sender, reply_to)),
// 3.6.3. Destination Address Fields
alt((to, cc, bcc)),
// 3.6.4. Identification Fields
alt((msg_id_field, in_reply_to, references)),
// 3.6.5. Informational Fields
alt((subject, comments, keywords)),
// 3.6.7 Trace field
alt((return_path, received)),
)),
perm_crlf,
)(input)
}
/// A high-level function to match more easily a field name
fn field_name_tag(field_name: &str) -> impl FnMut(&str) -> IResult<&str, &str> + '_ {
move |input: &str| {
recognize(tuple((tag_no_case(field_name), space0, tag(":"), space0)))(input)
}
}
// 3.6.1. The Origination Date Field
fn date(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("Date"), alt((
map(datetime::section, |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::Date(b))(input)
}
// 3.6.2. Originator Fields
fn from(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("From"), alt((
map(mailbox_list, |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::From(b))(input)
}
fn sender(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("Sender"), alt((
map(mailbox, |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::Sender(b))(input)
}
fn reply_to(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("Reply-To"), alt((
map(address_list, |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::ReplyTo(b))(input)
}
// 3.6.3. Destination Address Fields
fn to(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("To"), alt((
map(address_list, |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::To(b))(input)
}
fn cc(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("Cc"), alt((
map(address_list, |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::Cc(b))(input)
}
fn bcc(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("Bcc"), alt((
map(opt(alt((address_list, address_list_cfws))), |dt| FieldBody::Correct(dt.unwrap_or(vec![]))),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::Bcc(b))(input)
}
// 3.6.4. Identification Fields
fn msg_id_field(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("Message-ID"), alt((
map(msg_id, |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::MessageID(b))(input)
}
fn in_reply_to(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("In-Reply-To"), alt((
map(many1(msg_id), |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::InReplyTo(b))(input)
}
fn references(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("References"), alt((
map(many1(msg_id), |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::References(b))(input)
}
// 3.6.5. Informational Fields
fn subject(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("Subject"), alt((
map(unstructured, |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::Subject(b))(input)
}
fn comments(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("Comments"), alt((
map(unstructured, |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::Comments(b))(input)
}
fn keywords(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("Keywords"), alt((
map(separated_list1(tag(","), phrase), |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::Keywords(b))(input)
}
// 3.6.6 Resent fields
// Not implemented
// 3.6.7 Trace fields
fn return_path(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("Return-Path"), alt((
map(trace::return_path_body, |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::ReturnPath(b))(input)
}
fn received(input: &str) -> IResult<&str, Field> {
map(preceded(field_name_tag("Received"), alt((
map(trace::received_body, |dt| FieldBody::Correct(dt)),
map(rescue, |r| FieldBody::Failed(r))))),
|b| Field::Received(b))(input)
}
/// Optional field
///
/// ```abnf
/// field = field-name ":" unstructured CRLF
/// field-name = 1*ftext
/// ftext = %d33-57 / ; Printable US-ASCII
/// %d59-126 ; characters not including
/// ; ":".
/// ```
fn unknown_field(input: &str) -> IResult<&str, Field> {
// Extract field name
let (input, field_name) = field_name(input)?;
let (input, body) = unstructured(input)?;
let (input, _) = perm_crlf(input)?;
Ok((input, Field::Optional(field_name, body)))
}
fn field_name(input: &str) -> IResult<&str, &str> {
terminated(
take_while1(|c| c >= '\x21' && c <= '\x7E' && c != '\x3A'),
tuple((space0, tag(":"), space0))
)(input)
}
/// Rescue rule
///
/// Something went wrong while parsing headers,
/// trying to fix parsing by consuming
/// one unfolded header line.
///
/// ```abnf
/// rescue = *(*any FWS) *any CRLF
fn rescue(input: &str) -> IResult<&str, &str> {
recognize(pair(
many0(pair(is_not("\r\n"), fws)),
is_not("\r\n"),
))(input)
}
fn rescue_field(input: &str) -> IResult<&str, Field> {
map(terminated(rescue, perm_crlf), |r| Field::Rescue(r))(input)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fragments::model::{GroupRef, AddrSpec};
// 3.6.1. The Origination Date Field
/* #[test]
fn test_datetime() {
let datefield = "Date: Thu,\r\n 13\r\n Feb\r\n 1969\r\n 23:32\r\n -0330 (Newfoundland Time)\r\n";
let (input, v) = known_field(datefield).unwrap();
assert_eq!(input, "");
match v {
Field::Date(HeaderDate::Parsed(_)) => (),
_ => panic!("Date has not been parsed"),
};
}*/
// 3.6.2. Originator Fields
#[test]
fn test_from() {
assert_eq!(
known_field("From: \"Joe Q. Public\" <john.q.public@example.com>\r\n"),
Ok(("", Field::From(FieldBody::Correct(vec![MailboxRef {
name: Some("Joe Q. Public".into()),
addrspec: AddrSpec {
local_part: "john.q.public".into(),
domain: "example.com".into(),
}
}])))),
);
}
#[test]
fn test_sender() {
assert_eq!(
known_field("Sender: Michael Jones <mjones@machine.example>\r\n"),
Ok(("", Field::Sender(FieldBody::Correct(MailboxRef {
name: Some("Michael Jones".into()),
addrspec: AddrSpec {
local_part: "mjones".into(),
domain: "machine.example".into(),
},
})))),
);
}
#[test]
fn test_reply_to() {
assert_eq!(
known_field("Reply-To: \"Mary Smith: Personal Account\" <smith@home.example>\r\n"),
Ok(("", Field::ReplyTo(FieldBody::Correct(vec![AddressRef::Single(MailboxRef {
name: Some("Mary Smith: Personal Account".into()),
addrspec: AddrSpec {
local_part: "smith".into(),
domain: "home.example".into(),
},
})]))))
);
}
// 3.6.3. Destination Address Fields
#[test]
fn test_to() {
assert_eq!(
known_field("To: A Group:Ed Jones <c@a.test>,joe@where.test,John <jdoe@one.test>;\r\n"),
Ok(("", Field::To(FieldBody::Correct(vec![AddressRef::Many(GroupRef {
name: "A Group".into(),
participants: vec![
MailboxRef {
name: Some("Ed Jones".into()),
addrspec: AddrSpec { local_part: "c".into(), domain: "a.test".into() },
},
MailboxRef {
name: None,
addrspec: AddrSpec { local_part: "joe".into(), domain: "where.test".into() },
},
MailboxRef {
name: Some("John".into()),
addrspec: AddrSpec { local_part: "jdoe".into(), domain: "one.test".into() },
},
]
})]))))
);
}
#[test]
fn test_cc() {
assert_eq!(
known_field("Cc: Undisclosed recipients:;\r\n"),
Ok(("", Field::Cc(FieldBody::Correct(vec![AddressRef::Many(GroupRef {
name: "Undisclosed recipients".into(),
participants: vec![],
})]))))
);
}
#[test]
fn test_bcc() {
assert_eq!(
known_field("Bcc: (empty)\r\n"),
Ok(("", Field::Bcc(FieldBody::Correct(vec![]))))
);
assert_eq!(
known_field("Bcc: \r\n"),
Ok(("", Field::Bcc(FieldBody::Correct(vec![]))))
);
}
// 3.6.4. Identification Fields
#[test]
fn test_message_id() {
assert_eq!(
known_field("Message-ID: <310@[127.0.0.1]>\r\n"),
Ok(("", Field::MessageID(FieldBody::Correct(model::MessageId { left: "310", right: "127.0.0.1" }))))
);
}
#[test]
fn test_in_reply_to() {
assert_eq!(
known_field("In-Reply-To: <a@b> <c@example.com>\r\n"),
Ok(("", Field::InReplyTo(FieldBody::Correct(vec![
model::MessageId { left: "a", right: "b" },
model::MessageId { left: "c", right: "example.com" },
]))))
);
}
#[test]
fn test_references() {
assert_eq!(
known_field("References: <1234@local.machine.example> <3456@example.net>\r\n"),
Ok(("", Field::References(FieldBody::Correct(vec![
model::MessageId { left: "1234", right: "local.machine.example" },
model::MessageId { left: "3456", right: "example.net" },
]))))
);
}
// 3.6.5. Informational Fields
#[test]
fn test_subject() {
assert_eq!(
known_field("Subject: Aérogramme\r\n"),
Ok(("", Field::Subject(FieldBody::Correct("Aérogramme".into()))))
);
}
#[test]
fn test_comments() {
assert_eq!(
known_field("Comments: 😛 easter egg!\r\n"),
Ok(("", Field::Comments(FieldBody::Correct("😛 easter egg!".into()))))
);
}
#[test]
fn test_keywords() {
assert_eq!(
known_field("Keywords: fantasque, farfelu, fanfreluche\r\n"),
Ok(("", Field::Keywords(FieldBody::Correct(vec!["fantasque".into(), "farfelu".into(), "fanfreluche".into()]))))
);
}
// Test invalid field name
#[test]
fn test_invalid_field_name() {
assert!(known_field("Unknown: unknown\r\n").is_err());
}
#[test]
fn test_rescue_field() {
assert_eq!(
rescue_field("Héron: élan\r\n\tnoël: test\r\nFrom: ..."),
Ok(("From: ...", Field::Rescue("Héron: élan\r\n\tnoël: test"))),
);
}
#[test]
fn test_wrong_fields() {
let fullmail = r#"Return-Path: xoxo
From: !!!!
Hello world"#;
assert_eq!(
section(fullmail),
Ok(("Hello world", HeaderSection {
bad_fields: vec![
Field::ReturnPath(FieldBody::Failed("xoxo")),
Field::From(FieldBody::Failed("!!!!")),
],
..Default::default()
}))
);
}
#[test]
fn test_section() {
use chrono::{FixedOffset, TimeZone};
use std::collections::HashMap;
let fullmail = r#"Return-Path: <gitlab@example.com>
Delivered-To: quentin@example.com
Received: from smtp.example.com ([10.83.2.2])
by doradille with LMTP
id xyzabcd
(envelope-from <gitlab@example.com>)
for <quentin@example.com>; Tue, 13 Jun 2023 19:01:08 +0000
Date: Tue, 13 Jun 2023 10:01:10 +0200
From: Mary Smith
<mary@example.net>, "A\lan" <alan@example>
Sender: imf@example.com
Reply-To: "Mary Smith: Personal Account" <smith@home.example>
To: John Doe <jdoe@machine.example>
Cc: imf2@example.com
Bcc: (hidden)
Subject: Re: Saying Hello
Comments: A simple message
Comments: Not that complicated
comments : not valid header name but should be accepted
by the parser.
Keywords: hello, world
Héron: Raté
Raté raté
Keywords: salut, le, monde
Not a real header but should still recover
Message-ID: <3456@example.net>
In-Reply-To: <1234@local.machine.example>
References: <1234@local.machine.example>
Unknown: unknown
This is a reply to your hello.
"#;
assert_eq!(
section(fullmail),
Ok(("This is a reply to your hello.\n", HeaderSection {
date: Some(FixedOffset::east_opt(2 * 3600).unwrap().with_ymd_and_hms(2023, 06, 13, 10, 01, 10).unwrap()),
from: vec![MailboxRef {
name: Some("Mary Smith".into()),
addrspec: AddrSpec {
local_part: "mary".into(),
domain: "example.net".into(),
}
}, MailboxRef {
name: Some("Alan".into()),
addrspec: AddrSpec {
local_part: "alan".into(),
domain: "example".into(),
}
}],
sender: Some(MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: "imf".into(),
domain: "example.com".into(),
}
}),
reply_to: vec![AddressRef::Single(MailboxRef {
name: Some("Mary Smith: Personal Account".into()),
addrspec: AddrSpec {
local_part: "smith".into(),
domain: "home.example".into(),
}
})],
to: vec![AddressRef::Single(MailboxRef {
name: Some("John Doe".into()),
addrspec: AddrSpec {
local_part: "jdoe".into(),
domain: "machine.example".into(),
}
})],
cc: vec![AddressRef::Single(MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: "imf2".into(),
domain: "example.com".into(),
}
})],
bcc: vec![],
msg_id: Some(model::MessageId { left: "3456", right: "example.net" }),
in_reply_to: vec![model::MessageId { left: "1234", right: "local.machine.example" }],
references: vec![model::MessageId { left: "1234", right: "local.machine.example" }],
subject: Some("Re: Saying Hello".into()),
comments: vec![
"A simple message".into(),
"Not that complicated".into(),
"not valid header name but should be accepted by the parser.".into(),
],
keywords: vec![
"hello".into(), "world".into(), "salut".into(), "le".into(), "monde".into()
],
received: vec![
"from smtp.example.com ([10.83.2.2])\n\tby doradille with LMTP\n\tid xyzabcd\n\t(envelope-from <gitlab@example.com>)\n\tfor <quentin@example.com>"
],
return_path: vec![MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: "gitlab".into(),
domain: "example.com".into(),
}
}],
optional: HashMap::from([
("Delivered-To", "quentin@example.com".into()),
("Unknown", "unknown".into()),
]),
unparsed: vec![
"Héron: Raté\n Raté raté",
"Not a real header but should still recover",
],
bad_fields: vec![],
}))
);
}
}

View file

@ -1,54 +0,0 @@
use std::borrow::Cow;
use nom::{
IResult,
branch::alt,
bytes::complete::{take_while, tag},
combinator::opt,
sequence::{delimited, pair, tuple},
};
use crate::fragments::whitespace::cfws;
use crate::fragments::words::dot_atom_text;
use crate::fragments::mailbox::is_dtext;
use crate::fragments::model::MessageId;
/// Message identifier
///
/// ```abnf
/// msg-id = [CFWS] "<" id-left "@" id-right ">" [CFWS]
/// ```
pub fn msg_id(input: &str) -> IResult<&str, MessageId> {
let (input, (left, _, right)) = delimited(
pair(opt(cfws), tag("<")),
tuple((id_left, tag("@"), id_right)),
pair(tag(">"), opt(cfws)),
)(input)?;
Ok((input, MessageId{ left, right }))
}
// Missing obsolete
fn id_left(input: &str) -> IResult<&str, &str> {
dot_atom_text(input)
}
// Missing obsolete
fn id_right(input: &str) -> IResult<&str, &str> {
alt((dot_atom_text, no_fold_litteral))(input)
}
fn no_fold_litteral(input: &str) -> IResult<&str, &str> {
delimited(tag("["), take_while(is_dtext), tag("]"))(input)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_msg_id() {
assert_eq!(
msg_id("<5678.21-Nov-1997@example.com>"),
Ok(("", MessageId{left: "5678.21-Nov-1997", right: "example.com"})),
);
}
}

View file

@ -1,333 +0,0 @@
use std::borrow::Cow;
use nom::{
IResult,
Parser,
branch::alt,
bytes::complete::{tag, is_a},
character::complete::satisfy,
combinator::{into,map,opt,recognize},
multi::{separated_list1, fold_many0, many0, many1},
sequence::{delimited,pair,preceded,terminated,tuple},
};
use crate::fragments::model::{MailboxRef, AddrSpec};
use crate::fragments::misc_token::{phrase, word};
use crate::fragments::whitespace::{cfws, fws, is_obs_no_ws_ctl};
use crate::fragments::words::{atom, dot_atom};
use crate::fragments::quoted::quoted_string;
/// Mailbox
///
/// ```abnf
/// mailbox = name-addr / addr-spec
/// ```
pub fn mailbox(input: &str) -> IResult<&str, MailboxRef> {
alt((name_addr, into(addr_spec)))(input)
}
/// Name of the email address
///
/// ```abnf
/// name-addr = [display-name] angle-addr
/// ```
fn name_addr(input: &str) -> IResult<&str, MailboxRef> {
let (input, name) = opt(phrase)(input)?;
let (input, mut mbox) = angle_addr(input)?;
mbox.name = name;
Ok((input, mbox))
}
/// Enclosed addr-spec with < and >
///
/// ```abnf
/// angle-addr = [CFWS] "<" addr-spec ">" [CFWS] /
/// obs-angle-addr
/// ```
pub fn angle_addr(input: &str) -> IResult<&str, MailboxRef> {
delimited(
tuple((opt(cfws), tag("<"), opt(obs_route))),
into(addr_spec),
pair(tag(">"), opt(cfws)),
)(input)
}
/// obs-route = obs-domain-list ":"
fn obs_route(input: &str) -> IResult<&str, Vec<String>> {
terminated(obs_domain_list, tag(":"))(input)
}
/// ```abnf
/// obs-domain-list = *(CFWS / ",") "@" domain
/// *("," [CFWS] ["@" domain])
/// ```
fn obs_domain_list(input: &str) -> IResult<&str, Vec<String>> {
//@FIXME complexity is O(n) in term of domains here.
let (input, head) = preceded(pair(many0(alt((recognize(cfws), tag(",")))), tag("@")), obs_domain)(input)?;
let (input, mut rest) = obs_domain_list_rest(input)?;
rest.insert(0, head);
Ok((input, rest))
}
fn obs_domain_list_rest(input: &str) -> IResult<&str, Vec<String>> {
map(
many0(preceded(
pair(tag(","), opt(cfws)),
opt(preceded(tag("@"), obs_domain)),
)),
|v: Vec<Option<String>>| v.into_iter().flatten().collect()
)(input)
}
/// AddrSpec
///
/// ```abnf
/// addr-spec = local-part "@" domain
/// ```
/// @FIXME: this system does not work to alternate between strict and obsolete
/// so I force obsolete for now...
pub fn addr_spec(input: &str) -> IResult<&str, AddrSpec> {
map(
tuple((obs_local_part, tag("@"), obs_domain, many0(pair(tag("@"), obs_domain)))),
|(local_part, _, domain, _)|
AddrSpec { local_part, domain },
)(input)
}
/// Local part
///
/// ```abnf
/// local-part = dot-atom / quoted-string / obs-local-part
/// ```
fn strict_local_part(input: &str) -> IResult<&str, String> {
alt((into(dot_atom), quoted_string))(input)
}
/// Obsolete local part
///
/// Compared to the RFC, we allow multiple dots.
/// This is found in Enron emails and supported by Gmail.
///
/// Obsolete local part is a superset of strict_local_part:
/// anything that is parsed by strict_local_part will be parsed by
/// obs_local_part.
///
/// ```abnf
/// obs-local-part = *("." / word)
/// ```
fn obs_local_part(input: &str) -> IResult<&str, String> {
fold_many0(
alt((map(is_a("."), Cow::Borrowed), word)),
String::new,
|acc, chunk| acc + &chunk)(input)
}
/// Domain
///
/// ```abnf
/// domain = dot-atom / domain-literal
/// ```
pub fn strict_domain(input: &str) -> IResult<&str, String> {
alt((into(dot_atom), domain_litteral))(input)
}
/// Obsolete domain
///
/// Rewritten so that obs_domain is a superset
/// of strict_domain.
///
/// ```abnf
/// obs-domain = atom *("." atom) / domain-literal
/// ```
pub fn obs_domain(input: &str) -> IResult<&str, String> {
alt((map(separated_list1(tag("."), atom), |v| v.join(".")), domain_litteral))(input)
}
/// Domain litteral
///
/// ```abnf
/// domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
/// ```
fn domain_litteral(input: &str) -> IResult<&str, String> {
delimited(
pair(opt(cfws), tag("[")),
inner_domain_litteral,
pair(tag("]"), opt(cfws))
)(input)
}
fn inner_domain_litteral(input: &str) -> IResult<&str, String> {
let (input, (cvec, maybe_wsp)) = pair(many0(pair(opt(fws), satisfy(is_dtext))), opt(fws))(input)?;
let mut domain = cvec.iter().fold(
String::with_capacity(16),
|mut acc, (maybe_wsp, c)| {
if let Some(wsp) = maybe_wsp {
acc.push(*wsp);
}
acc.push(*c);
acc
});
if let Some(wsp) = maybe_wsp {
domain.push(wsp);
}
Ok((input, domain))
}
fn is_strict_dtext(c: char) -> bool {
(c >= '\x21' && c <= '\x5A') || (c >= '\x5E' && c <= '\x7E') || !c.is_ascii()
}
/// Is domain text
///
/// ```abnf
/// dtext = %d33-90 / ; Printable US-ASCII
/// %d94-126 / ; characters not including
/// obs-dtext ; "[", "]", or "\"
/// obs-dtext = obs-NO-WS-CTL / quoted-pair
/// ```
pub fn is_dtext(c: char) -> bool {
is_strict_dtext(c) || is_obs_no_ws_ctl(c)
//@FIXME does not support quoted pair yet while RFC requires it
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_addr_spec() {
assert_eq!(addr_spec("alice@example.com"), Ok(("", AddrSpec{local_part: "alice".into(), domain: "example.com".into() })));
assert_eq!(addr_spec("jsmith@[192.168.2.1]"), Ok(("", AddrSpec{local_part: "jsmith".into(), domain: "192.168.2.1".into() })));
assert_eq!(addr_spec("jsmith@[IPv6:2001:db8::1]"), Ok(("", AddrSpec{local_part: "jsmith".into(), domain: "IPv6:2001:db8::1".into() })));
// UTF-8
assert_eq!(addr_spec("用户@例子.广告"), Ok(("", AddrSpec{local_part: "用户".into(), domain: "例子.广告".into()})));
// ASCII Edge cases
assert_eq!(
addr_spec("user+mailbox/department=shipping@example.com"),
Ok(("", AddrSpec{local_part: "user+mailbox/department=shipping".into(), domain: "example.com".into()})));
assert_eq!(
addr_spec("!#$%&'*+-/=?^_`.{|}~@example.com"),
Ok(("", AddrSpec{local_part: "!#$%&'*+-/=?^_`.{|}~".into(), domain: "example.com".into()})));
assert_eq!(
addr_spec(r#""Abc@def"@example.com"#),
Ok(("", AddrSpec{local_part: "Abc@def".into(), domain: "example.com".into()})));
assert_eq!(addr_spec(r#""Fred\ Bloggs"@example.com"#), Ok(("", AddrSpec{local_part: "Fred Bloggs".into(), domain: "example.com".into()})));
assert_eq!(addr_spec(r#""Joe.\\Blow"@example.com"#), Ok(("", AddrSpec{local_part: r#"Joe.\Blow"#.into(), domain: "example.com".into()})));
}
#[test]
fn test_mailbox() {
assert_eq!(mailbox(r#""Joe Q. Public" <john.q.public@example.com>"#), Ok(("", MailboxRef {
name: Some("Joe Q. Public".into()),
addrspec: AddrSpec {
local_part: "john.q.public".into(),
domain: "example.com".into(),
}
})));
assert_eq!(mailbox(r#"Mary Smith <mary@x.test>"#), Ok(("", MailboxRef {
name: Some("Mary Smith".into()),
addrspec: AddrSpec {
local_part: "mary".into(),
domain: "x.test".into(),
}
})));
assert_eq!(mailbox(r#"jdoe@example.org"#), Ok(("", MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: "jdoe".into(),
domain: "example.org".into(),
}
})));
assert_eq!(mailbox(r#"Who? <one@y.test>"#), Ok(("", MailboxRef {
name: Some("Who?".into()),
addrspec: AddrSpec {
local_part: "one".into(),
domain: "y.test".into(),
}
})));
assert_eq!(mailbox(r#"<boss@nil.test>"#), Ok(("", MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: "boss".into(),
domain: "nil.test".into(),
}
})));
assert_eq!(mailbox(r#""Giant; \"Big\" Box" <sysservices@example.net>"#), Ok(("", MailboxRef {
name: Some(r#"Giant; "Big" Box"#.into()),
addrspec: AddrSpec {
local_part: "sysservices".into(),
domain: "example.net".into(),
}
})));
}
#[test]
fn test_obs_domain_list() {
assert_eq!(obs_domain_list(r#"(shhh it's coming)
,
(not yet)
@33+4.com,,,,
,,,,
(again)
@example.com,@yep.com,@a,@b,,,@c"#),
Ok(("", vec!["33+4.com".into(), "example.com".into(), "yep.com".into(), "a".into(), "b".into(), "c".into()]))
);
}
#[test]
fn test_enron1() {
assert_eq!(
addr_spec("a..howard@enron.com"),
Ok(("", AddrSpec {
local_part: "a..howard".into(),
domain: "enron.com".into(),
}))
);
}
#[test]
fn test_enron2() {
assert_eq!(
addr_spec(".nelson@enron.com"),
Ok(("", AddrSpec {
local_part: ".nelson".into(),
domain: "enron.com".into(),
}))
);
}
#[test]
fn test_enron3() {
assert_eq!(
addr_spec("ecn2760.conf.@enron.com"),
Ok(("", AddrSpec {
local_part: "ecn2760.conf.".into(),
domain: "enron.com".into(),
}))
);
}
#[test]
fn test_enron4() {
assert_eq!(
mailbox(r#"<"mark_kopinski/intl/acim/americancentury"@americancentury.com@enron.com>"#),
Ok(("", MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: "mark_kopinski/intl/acim/americancentury".into(),
domain: "americancentury.com".into(),
}
}))
);
}
}

View file

@ -1,79 +0,0 @@
use std::borrow::Cow;
use nom::{
IResult,
branch::alt,
bytes::complete::take_while1,
character::complete::space0,
combinator::{into, opt},
multi::{many0, many1},
sequence::{pair, tuple},
};
use crate::fragments::quoted::quoted_string;
use crate::fragments::whitespace::{fws, is_obs_no_ws_ctl};
use crate::fragments::words::{atom, is_vchar};
/// Word
///
/// ```abnf
/// word = atom / quoted-string
/// ```
pub fn word(input: &str) -> IResult<&str, Cow<str>> {
alt((into(quoted_string), into(atom)))(input)
}
/// Phrase
///
/// ```abnf
/// phrase = 1*word / obs-phrase
/// ```
pub fn phrase(input: &str) -> IResult<&str, String> {
let (input, words) = many1(word)(input)?;
let phrase = words.join(" ");
Ok((input, phrase))
}
/// Compatible unstructured input
///
/// ```abnf
/// obs-utext = %d0 / obs-NO-WS-CTL / VCHAR
/// ```
fn is_unstructured(c: char) -> bool {
is_vchar(c) || is_obs_no_ws_ctl(c) || c == '\x00'
}
/// Unstructured header field body
///
/// ```abnf
/// unstructured = (*([FWS] VCHAR_SEQ) *WSP) / obs-unstruct
/// ```
pub fn unstructured(input: &str) -> IResult<&str, String> {
let (input, r) = many0(tuple((opt(fws), take_while1(is_unstructured))))(input)?;
let (input, _) = space0(input)?;
// Try to optimize for the most common cases
let body = match r.as_slice() {
[(None, content)] => content.to_string(),
[(Some(_), content)] => " ".to_string() + content,
lines => lines.iter().fold(String::with_capacity(255), |acc, item| {
let (may_ws, content) = item;
match may_ws {
Some(_) => acc + " " + content,
None => acc + content,
}
}),
};
Ok((input, body))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_phrase() {
assert_eq!(phrase("hello world"), Ok(("", "hello world".into())));
assert_eq!(phrase("salut \"le\" monde"), Ok(("", "salut le monde".into())));
assert_eq!(phrase("fin\r\n du\r\nmonde"), Ok(("\r\nmonde", "fin du".into())));
}
}

View file

@ -1,18 +0,0 @@
// Model
pub mod model;
// Generic
pub mod whitespace;
mod words;
mod quoted;
mod misc_token;
// Header specific
mod mailbox;
mod address;
mod identification;
mod trace;
mod datetime;
// Header blocks
pub mod header;

View file

@ -1,143 +0,0 @@
use std::collections::HashMap;
use chrono::{DateTime,FixedOffset,ParseError};
#[derive(Debug, PartialEq)]
pub struct AddrSpec {
pub local_part: String,
pub domain: String,
}
impl AddrSpec {
pub fn fully_qualified(&self) -> String {
format!("{}@{}", self.local_part, self.domain)
}
}
#[derive(Debug, PartialEq)]
pub struct MailboxRef {
// The actual "email address" like hello@example.com
pub addrspec: AddrSpec,
pub name: Option<String>,
}
impl From<AddrSpec> for MailboxRef {
fn from(addr: AddrSpec) -> Self {
MailboxRef {
name: None,
addrspec: addr,
}
}
}
#[derive(Debug, PartialEq)]
pub struct GroupRef {
pub name: String,
pub participants: Vec<MailboxRef>,
}
#[derive(Debug, PartialEq)]
pub enum AddressRef {
Single(MailboxRef),
Many(GroupRef),
}
impl From<MailboxRef> for AddressRef {
fn from(mx: MailboxRef) -> Self {
AddressRef::Single(mx)
}
}
impl From<GroupRef> for AddressRef {
fn from(grp: GroupRef) -> Self {
AddressRef::Many(grp)
}
}
#[derive(Debug, PartialEq)]
pub struct MessageId<'a> {
pub left: &'a str,
pub right: &'a str,
}
#[derive(Debug, PartialEq)]
pub enum FieldBody<'a, T> {
Correct(T),
Failed(&'a str),
}
#[derive(Debug, PartialEq)]
pub enum Field<'a> {
// 3.6.1. The Origination Date Field
Date(FieldBody<'a, Option<DateTime<FixedOffset>>>),
// 3.6.2. Originator Fields
From(FieldBody<'a, Vec<MailboxRef>>),
Sender(FieldBody<'a, MailboxRef>),
ReplyTo(FieldBody<'a, Vec<AddressRef>>),
// 3.6.3. Destination Address Fields
To(FieldBody<'a, Vec<AddressRef>>),
Cc(FieldBody<'a, Vec<AddressRef>>),
Bcc(FieldBody<'a, Vec<AddressRef>>),
// 3.6.4. Identification Fields
MessageID(FieldBody<'a, MessageId<'a>>),
InReplyTo(FieldBody<'a, Vec<MessageId<'a>>>),
References(FieldBody<'a, Vec<MessageId<'a>>>),
// 3.6.5. Informational Fields
Subject(FieldBody<'a, String>),
Comments(FieldBody<'a, String>),
Keywords(FieldBody<'a, Vec<String>>),
// 3.6.6 Resent Fields (not implemented)
// 3.6.7 Trace Fields
Received(FieldBody<'a, &'a str>),
ReturnPath(FieldBody<'a, Option<MailboxRef>>),
// 3.6.8. Optional Fields
Optional(&'a str, String),
// None
Rescue(&'a str),
}
/// Permissive Header Section
///
/// This is a structure intended for parsing/decoding,
/// hence it's support cases where the email is considered
/// as invalid according to RFC5322 but for which we can
/// still extract some data.
#[derive(Debug, PartialEq, Default)]
pub struct HeaderSection<'a> {
// 3.6.1. The Origination Date Field
pub date: Option<DateTime<FixedOffset>>,
// 3.6.2. Originator Fields
pub from: Vec<MailboxRef>,
pub sender: Option<MailboxRef>,
pub reply_to: Vec<AddressRef>,
// 3.6.3. Destination Address Fields
pub to: Vec<AddressRef>,
pub cc: Vec<AddressRef>,
pub bcc: Vec<AddressRef>,
// 3.6.4. Identification Fields
pub msg_id: Option<MessageId<'a>>,
pub in_reply_to: Vec<MessageId<'a>>,
pub references: Vec<MessageId<'a>>,
// 3.6.5. Informational Fields
pub subject: Option<String>,
pub comments: Vec<String>,
pub keywords: Vec<String>,
// 3.6.6 Not implemented
// 3.6.7 Trace Fields
pub return_path: Vec<MailboxRef>,
pub received: Vec<&'a str>,
// 3.6.8. Optional Fields
pub optional: HashMap<&'a str, String>,
// Recovery
pub bad_fields: Vec<Field<'a>>,
pub unparsed: Vec<&'a str>,
}

View file

@ -1,91 +0,0 @@
use nom::{
IResult,
branch::alt,
bytes::complete::tag,
character::complete::{anychar, satisfy},
combinator::opt,
multi::many0,
sequence::{pair, preceded},
};
use crate::fragments::words::is_vchar;
use crate::fragments::whitespace::{fws, cfws, is_obs_no_ws_ctl};
/// Quoted pair
///
/// ```abnf
/// quoted-pair = ("\" (VCHAR / WSP)) / obs-qp
/// obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR)
/// ```
pub fn quoted_pair(input: &str) -> IResult<&str, char> {
preceded(tag("\\"), anychar)(input)
}
/// Allowed characters in quote
///
/// ```abnf
/// qtext = %d33 / ; Printable US-ASCII
/// %d35-91 / ; characters not including
/// %d93-126 / ; "\" or the quote character
/// obs-qtext
/// ```
fn is_restr_qtext(c: char) -> bool {
c == '\x21' || (c >= '\x23' && c <= '\x5B') || (c >= '\x5D' && c <= '\x7E')
}
fn is_qtext(c: char) -> bool {
is_restr_qtext(c) || is_obs_no_ws_ctl(c)
}
/// Quoted pair content
///
/// ```abnf
/// qcontent = qtext / quoted-pair
/// ```
fn qcontent(input: &str) -> IResult<&str, char> {
alt((satisfy(is_qtext), quoted_pair))(input)
}
/// Quoted string
///
/// ```abnf
/// quoted-string = [CFWS]
/// DQUOTE *([FWS] qcontent) [FWS] DQUOTE
/// [CFWS]
/// ```
pub fn quoted_string(input: &str) -> IResult<&str, String> {
let (input, _) = opt(cfws)(input)?;
let (input, _) = tag("\"")(input)?;
let (input, content) = many0(pair(opt(fws), qcontent))(input)?;
// Rebuild string
let mut qstring = content.iter().fold(
String::with_capacity(16),
|mut acc, (maybe_wsp, c)| {
if let Some(wsp) = maybe_wsp {
acc.push(*wsp);
}
acc.push(*c);
acc
});
let (input, maybe_wsp) = opt(fws)(input)?;
if let Some(wsp) = maybe_wsp {
qstring.push(wsp);
}
let (input, _) = tag("\"")(input)?;
let (input, _) = opt(cfws)(input)?;
Ok((input, qstring))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_quoted_string() {
assert_eq!(quoted_string(" \"hello\\\"world\" "), Ok(("", "hello\"world".to_string())));
assert_eq!(quoted_string("\"hello\r\n world\""), Ok(("", "hello world".to_string())));
}
}

View file

@ -1,75 +0,0 @@
use std::collections::HashMap;
use nom::{
IResult,
branch::alt,
bytes::complete::tag,
character::complete::space0,
combinator::{map, opt, recognize},
multi::many0,
sequence::{delimited, pair, tuple},
};
use crate::fragments::{datetime, mailbox, model, misc_token, whitespace};
pub fn received_body(input: &str) -> IResult<&str, &str> {
map(
tuple((
recognize(many0(received_tokens)),
tag(";"),
datetime::section,
)),
|(tokens, _, _)| tokens,
)(input)
}
pub fn return_path_body(input: &str) -> IResult<&str, Option<model::MailboxRef>> {
alt((
map(mailbox::angle_addr, |a| Some(a)),
empty_path
))(input)
}
fn empty_path(input: &str) -> IResult<&str, Option<model::MailboxRef>> {
let (input, _) = tuple((
opt(whitespace::cfws),
tag("<"),
opt(whitespace::cfws),
tag(">"),
opt(whitespace::cfws),
))(input)?;
Ok((input, None))
}
// @FIXME use obs_domain as it is a superset of domain
fn received_tokens(input: &str) -> IResult<&str, &str> {
alt((
recognize(mailbox::angle_addr),
recognize(mailbox::addr_spec),
recognize(mailbox::obs_domain),
recognize(misc_token::word),
))(input)
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{FixedOffset, TimeZone};
#[test]
fn test_received_body() {
let hdrs = r#"from smtp.example.com ([10.83.2.2])
by server with LMTP
id xxxxxxxxx
(envelope-from <gitlab@example.com>)
for <me@example.com>; Tue, 13 Jun 2023 19:01:08 +0000"#;
assert_eq!(
received_body(hdrs),
Ok(("", r#"from smtp.example.com ([10.83.2.2])
by server with LMTP
id xxxxxxxxx
(envelope-from <gitlab@example.com>)
for <me@example.com>"#))
);
}
}

View file

@ -1,140 +0,0 @@
use nom::{
IResult,
branch::alt,
bytes::complete::tag,
character::complete::{crlf, satisfy, space0, space1},
combinator::{recognize, opt},
multi::{many0, many1},
sequence::{pair, tuple},
};
use crate::fragments::quoted::quoted_pair;
// --- whitespaces and comments
// Note: WSP = SP / HTAB = %x20 / %x09
// nom::*::space0 = *WSP
// nom::*::space1 = 1*WSP
/// Permissive CRLF
///
/// Theoretically, all lines must end with \r\n
/// but some mail servers like Dovecot support malformated emails,
/// for example with only \n eol. It works because
/// \r or \n is allowed nowhere else, so we also add this support.
pub fn perm_crlf(input: &str) -> IResult<&str, &str> {
alt((crlf, tag("\r"), tag("\n")))(input)
}
/// Permissive foldable white space
///
/// Folding white space are used for long headers splitted on multiple lines.
/// The obsolete syntax allowes multiple lines without content; implemented for compatibility
/// reasons
pub fn fws(input: &str) -> IResult<&str, char> {
let (input, _) = alt((recognize(many1(fold_marker)), space1))(input)?;
Ok((input, ' '))
}
fn fold_marker(input: &str) -> IResult<&str, &str> {
let (input, _) = space0(input)?;
let (input, _) = perm_crlf(input)?;
space1(input)
}
/// Folding White Space with Comment
///
/// Note: we drop the comments for now...
///
/// ```abnf
/// ctext = %d33-39 / ; Printable US-ASCII
/// %d42-91 / ; characters not including
/// %d93-126 / ; "(", ")", or "\"
/// obs-ctext
///
/// ccontent = ctext / quoted-pair / comment
///
/// comment = "(" *([FWS] ccontent) [FWS] ")"
///
/// CFWS = (1*([FWS] comment) [FWS]) / FWS
/// ```
pub fn cfws(input: &str) -> IResult<&str, &str> {
alt((recognize(comments), recognize(fws)))(input)
}
pub fn comments(input: &str) -> IResult<&str, ()> {
let (input, _) = many1(tuple((opt(fws), comment)))(input)?;
let (input, _) = opt(fws)(input)?;
Ok((input, ()))
}
pub fn comment(input: &str) -> IResult<&str, ()> {
let (input, _) = tag("(")(input)?;
let (input, _) = many0(tuple((opt(fws), ccontent)))(input)?;
let (input, _) = opt(fws)(input)?;
let (input, _) = tag(")")(input)?;
Ok((input, ()))
}
pub fn ccontent(input: &str) -> IResult<&str, &str> {
alt((recognize(ctext), recognize(quoted_pair), recognize(comment)))(input)
}
pub fn ctext(input: &str) -> IResult<&str, char> {
satisfy(is_ctext)(input)
}
/// Check if it's a comment text character
///
/// ```abnf
/// ctext = %d33-39 / ; Printable US-ASCII
/// %d42-91 / ; characters not including
/// %d93-126 / ; "(", ")", or "\"
/// obs-ctext
///```
pub fn is_restr_ctext(c: char) -> bool {
(c >= '\x21' && c <= '\x27') || (c >= '\x2A' && c <= '\x5B') || (c >= '\x5D' && c <= '\x7E') || !c.is_ascii()
}
pub fn is_ctext(c: char) -> bool {
is_restr_ctext(c) || is_obs_no_ws_ctl(c)
}
/// US ASCII control characters without effect
///
/// ```abnf
/// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
/// %d11 / ; characters that do not
/// %d12 / ; include the carriage
/// %d14-31 / ; return, line feed, and
/// %d127 ; white space characters
/// ```
pub fn is_obs_no_ws_ctl(c: char) -> bool {
(c >= '\x01' && c <= '\x08') || c == '\x0b' || c == '\x0b' || (c >= '\x0e' && c<= '\x1f') || c == '\x7F'
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_perm_crlf() {
assert_eq!(perm_crlf("\rworld"), Ok(("world", "\r")));
assert_eq!(perm_crlf("\r\nworld"), Ok(("world", "\r\n")));
assert_eq!(perm_crlf("\nworld"), Ok(("world", "\n")));
}
#[test]
fn test_fws() {
assert_eq!(fws("\r\n world"), Ok(("world", ' ')));
assert_eq!(fws(" \r\n \r\n world"), Ok(("world", ' ')));
assert_eq!(fws(" world"), Ok(("world", ' ')));
assert!(fws("\r\nFrom: test").is_err());
}
#[test]
fn test_cfws() {
assert_eq!(cfws("(A nice \\) chap) <pete(his account)@silly.test(his host)>"), Ok(("<pete(his account)@silly.test(his host)>", "(A nice \\) chap) ")));
assert_eq!(cfws("(Chris's host.)public.example>,"), Ok(("public.example>,", "(Chris's host.)")));
assert_eq!(cfws("(double (comment) is fun) wouch"), Ok(("wouch", "(double (comment) is fun) ")));
}
}

View file

@ -1,97 +0,0 @@
use nom::{
IResult,
bytes::complete::{tag, take_while1},
combinator::{recognize, opt},
multi::many0,
sequence::{delimited, pair},
};
use crate::fragments::whitespace::cfws;
/// VCHAR definition
pub fn is_vchar(c: char) -> bool {
(c >= '\x21' && c <= '\x7E') || !c.is_ascii()
}
/// Sequence of visible chars with the UTF-8 extension
///
/// ```abnf
/// VCHAR = %x21-7E
/// ; visible (printing) characters
/// VCHAR =/ UTF8-non-ascii
/// SEQ = 1*VCHAR
///```
pub fn vchar_seq(input: &str) -> IResult<&str, &str> {
take_while1(is_vchar)(input)
}
/// Atom allowed characters
fn is_atext(c: char) -> bool {
c.is_ascii_alphanumeric() || "!#$%&'*+-/=?^_`{|}~".contains(c) || !c.is_ascii()
}
/// Atom
///
/// `[CFWS] 1*atext [CFWS]`
pub fn atom(input: &str) -> IResult<&str, &str> {
delimited(opt(cfws), take_while1(is_atext), opt(cfws))(input)
}
/// dot-atom-text
///
/// `1*atext *("." 1*atext)`
pub fn dot_atom_text(input: &str) -> IResult<&str, &str> {
recognize(pair(take_while1(is_atext), many0(pair(tag("."), take_while1(is_atext)))))(input)
}
/// dot-atom
///
/// `[CFWS] dot-atom-text [CFWS]`
pub fn dot_atom(input: &str) -> IResult<&str, &str> {
delimited(opt(cfws), dot_atom_text, opt(cfws))(input)
}
pub fn is_special(c: char) -> bool {
c == '(' || c == ')' ||
c == '<' || c == '>' ||
c == '[' || c == ']' ||
c == ':' || c == ';' ||
c == '@' || c == '\\' ||
c == ',' || c == '.' ||
c == '"'
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vchar_seq() {
assert_eq!(vchar_seq("hello world"), Ok((" world", "hello")));
assert_eq!(vchar_seq("hello👋 world"), Ok((" world", "hello👋")));
}
#[test]
fn test_atext() {
assert!(is_atext('='));
assert!(is_atext('5'));
assert!(is_atext('Q'));
assert!(!is_atext(' '));
assert!(is_atext('É')); // support utf8
}
#[test]
fn test_atom() {
assert_eq!(atom("(skip) imf_codec (hidden) aerogramme"), Ok(("aerogramme", "imf_codec")));
}
#[test]
fn test_dot_atom_text() {
assert_eq!(dot_atom_text("quentin.dufour.io abcdef"), Ok((" abcdef", "quentin.dufour.io")));
}
#[test]
fn test_dot_atom() {
assert_eq!(dot_atom(" (skip) quentin.dufour.io abcdef"), Ok(("abcdef", "quentin.dufour.io")));
}
}

73
src/header.rs Normal file
View file

@ -0,0 +1,73 @@
use nom::{
branch::alt,
bytes::complete::{tag, take_while1},
character::complete::space0,
combinator::{into, recognize},
multi::many0,
sequence::{pair, terminated, tuple},
IResult,
};
use std::fmt;
use crate::text::misc_token::unstructured;
use crate::text::whitespace::{foldable_line, obs_crlf};
#[derive(PartialEq, Clone)]
pub struct Kv2<'a>(pub &'a [u8], pub &'a [u8]);
impl<'a> From<(&'a [u8], &'a [u8])> for Kv2<'a> {
fn from(pair: (&'a [u8], &'a [u8])) -> Self {
Self(pair.0, pair.1)
}
}
impl<'a> fmt::Debug for Kv2<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple("header::Kv2")
.field(&String::from_utf8_lossy(self.0))
.field(&String::from_utf8_lossy(self.1))
.finish()
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum Field<'a> {
Good(Kv2<'a>),
Bad(&'a [u8]),
}
impl<'a> From<Kv2<'a>> for Field<'a> {
fn from(kv: Kv2<'a>) -> Self {
Self::Good(kv)
}
}
impl<'a> From<&'a [u8]> for Field<'a> {
fn from(bad: &'a [u8]) -> Self {
Self::Bad(bad)
}
}
/// Parse headers as key/values
pub fn header_kv(input: &[u8]) -> IResult<&[u8], Vec<Field>> {
terminated(
many0(alt((into(correct_field), into(foldable_line)))),
obs_crlf,
)(input)
}
pub fn field_any(input: &[u8]) -> IResult<&[u8], &[u8]> {
terminated(
take_while1(|c| (0x21..=0x7E).contains(&c) && c != 0x3A),
tuple((space0, tag(b":"), space0)),
)(input)
}
/// Optional field
///
/// ```abnf
/// field = field-name ":" unstructured CRLF
/// field-name = 1*ftext
/// ftext = %d33-57 / ; Printable US-ASCII
/// %d59-126 ; characters not including
/// ; ":".
/// ```
pub fn correct_field(input: &[u8]) -> IResult<&[u8], Kv2> {
terminated(into(pair(field_any, recognize(unstructured))), obs_crlf)(input)
}

246
src/imf/address.rs Normal file
View file

@ -0,0 +1,246 @@
use nom::{
branch::alt,
bytes::complete::tag,
combinator::{into, map, opt},
multi::separated_list1,
sequence::tuple,
IResult,
};
//use crate::error::IMFError;
use crate::imf::mailbox::{mailbox, MailboxRef};
use crate::text::misc_token::{phrase, Phrase};
use crate::text::whitespace::cfws;
#[derive(Debug, PartialEq)]
pub struct GroupRef<'a> {
pub name: Phrase<'a>,
pub participants: Vec<MailboxRef<'a>>,
}
#[derive(Debug, PartialEq)]
pub enum AddressRef<'a> {
Single(MailboxRef<'a>),
Many(GroupRef<'a>),
}
impl<'a> From<MailboxRef<'a>> for AddressRef<'a> {
fn from(mx: MailboxRef<'a>) -> Self {
AddressRef::Single(mx)
}
}
impl<'a> From<GroupRef<'a>> for AddressRef<'a> {
fn from(grp: GroupRef<'a>) -> Self {
AddressRef::Many(grp)
}
}
pub type AddressList<'a> = Vec<AddressRef<'a>>;
/// Address (section 3.4 of RFC5322)
///
/// ```abnf
/// address = mailbox / group
/// ```
pub fn address(input: &[u8]) -> IResult<&[u8], AddressRef> {
alt((into(mailbox), into(group)))(input)
}
/// Group
///
/// ```abnf
/// group = display-name ":" [group-list] ";" [CFWS]
/// display-name = phrase
/// ```
pub fn group(input: &[u8]) -> IResult<&[u8], GroupRef> {
let (input, (grp_name, _, grp_list, _, _)) =
tuple((phrase, tag(":"), opt(group_list), tag(";"), opt(cfws)))(input)?;
Ok((
input,
GroupRef {
name: grp_name,
participants: grp_list.unwrap_or(vec![]),
},
))
}
/// Group list
///
/// ```abnf
/// group-list = mailbox-list / CFWS / obs-group-list
/// ```
pub fn group_list(input: &[u8]) -> IResult<&[u8], Vec<MailboxRef>> {
alt((mailbox_list, mailbox_cfws))(input)
}
fn mailbox_cfws(input: &[u8]) -> IResult<&[u8], Vec<MailboxRef>> {
let (input, _) = cfws(input)?;
Ok((input, vec![]))
}
/// Mailbox list
///
/// ```abnf
/// mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
/// ```
pub fn mailbox_list(input: &[u8]) -> IResult<&[u8], Vec<MailboxRef>> {
separated_list1(tag(","), mailbox)(input)
}
/// Address list
///
/// ```abnf
/// address-list = (address *("," address)) / obs-addr-list
/// ```
pub fn address_list(input: &[u8]) -> IResult<&[u8], Vec<AddressRef>> {
separated_list1(tag(","), address)(input)
}
pub fn address_list_cfws(input: &[u8]) -> IResult<&[u8], Vec<AddressRef>> {
let (input, _) = cfws(input)?;
Ok((input, vec![]))
}
pub fn nullable_address_list(input: &[u8]) -> IResult<&[u8], Vec<AddressRef>> {
map(opt(alt((address_list, address_list_cfws))), |v| {
v.unwrap_or(vec![])
})(input)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::imf::mailbox::{AddrSpec, Domain, LocalPart, LocalPartToken};
use crate::text::misc_token::{Phrase, Word};
#[test]
fn test_mailbox_list() {
match mailbox_list(
r#"Pete(A nice \) chap) <pete(his account)@silly.test(his host)>"#.as_bytes(),
) {
Ok((rest, _)) => assert_eq!(&b""[..], rest),
_ => panic!(),
};
match mailbox_list(
r#"Mary Smith <mary@x.test>, jdoe@example.org, Who? <one@y.test>, <boss@nil.test>, "Giant; \"Big\" Box" <sysservices@example.net>"#.as_bytes(),
) {
Ok((rest, _)) => assert_eq!(&b""[..], rest),
_ => panic!(),
};
}
#[test]
fn test_address_list() {
assert_eq!(
address_list(
r#"A Group:Ed Jones <c@a.test>,joe@where.test,John <jdoe@one.test>;, Mary Smith <mary@x.test>"#.as_bytes()
),
Ok((
&b""[..],
vec![
AddressRef::Many(GroupRef {
name: Phrase(vec![Word::Atom(&b"A"[..]), Word::Atom(&b"Group"[..])]),
participants: vec![
MailboxRef {
name: Some(Phrase(vec![Word::Atom(&b"Ed"[..]), Word::Atom(&b"Jones"[..])])),
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(&b"c"[..]))]),
domain: Domain::Atoms(vec![&b"a"[..], &b"test"[..]]),
},
},
MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(&b"joe"[..]))]),
domain: Domain::Atoms(vec![&b"where"[..], &b"test"[..]])
},
},
MailboxRef {
name: Some(Phrase(vec![Word::Atom(&b"John"[..])])),
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(&b"jdoe"[..]))]),
domain: Domain::Atoms(vec![&b"one"[..], &b"test"[..]])
},
},
],
}),
AddressRef::Single(MailboxRef {
name: Some(Phrase(vec![Word::Atom(&b"Mary"[..]), Word::Atom(&b"Smith"[..])])),
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(&b"mary"[..]))]),
domain: Domain::Atoms(vec![&b"x"[..], &b"test"[..]])
},
}),
]
))
);
}
use crate::text::encoding::{EncodedWord, QuotedChunk, QuotedWord};
use crate::text::quoted::QuotedString;
#[test]
fn test_strange_groups() {
assert_eq!(
address_list(
br#""Colleagues": "James Smythe" <james@vandelay.com>;, Friends:
jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;"#
),
Ok((
&b""[..],
vec![
AddressRef::Many(GroupRef {
name: Phrase(vec![Word::Quoted(QuotedString(vec![&b"Colleagues"[..]]))]),
participants: vec![MailboxRef {
name: Some(Phrase(vec![Word::Quoted(QuotedString(vec![
&b"James"[..],
&b" "[..],
&b"Smythe"[..]
]))])),
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(
&b"james"[..]
))]),
domain: Domain::Atoms(vec![&b"vandelay"[..], &b"com"[..]]),
}
},],
}),
AddressRef::Many(GroupRef {
name: Phrase(vec![Word::Atom(&b"Friends"[..])]),
participants: vec![
MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(
&b"jane"[..]
))]),
domain: Domain::Atoms(vec![&b"example"[..], &b"com"[..]]),
}
},
MailboxRef {
name: Some(Phrase(vec![Word::Encoded(EncodedWord::Quoted(
QuotedWord {
enc: encoding_rs::UTF_8,
chunks: vec![
QuotedChunk::Safe(&b"John"[..]),
QuotedChunk::Space,
QuotedChunk::Safe(&b"Sm"[..]),
QuotedChunk::Encoded(vec![0xc3, 0xae]),
QuotedChunk::Safe(&b"th"[..]),
]
}
))])),
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(
&b"john"[..]
))]),
domain: Domain::Atoms(vec![&b"example"[..], &b"com"[..]]),
}
},
]
}),
]
))
);
}
}

588
src/imf/datetime.rs Normal file
View file

@ -0,0 +1,588 @@
use chrono::{DateTime, FixedOffset, NaiveDate, NaiveTime};
use nom::{
branch::alt,
bytes::complete::{is_a, tag, tag_no_case, take_while_m_n},
character,
character::complete::{alphanumeric1, digit0},
combinator::{map, opt, value},
sequence::{delimited, preceded, terminated, tuple},
IResult,
};
use crate::text::whitespace::{cfws, fws};
//use crate::error::IMFError;
const MIN: i32 = 60;
const HOUR: i32 = 60 * MIN;
/*
impl<'a> TryFrom<&'a lazy::DateTime<'a>> for DateTime<FixedOffset> {
type Error = IMFError<'a>;
fn try_from(value: &'a lazy::DateTime<'a>) -> Result<Self, Self::Error> {
match section(value.0) {
Ok((_, Some(dt))) => Ok(dt),
Err(e) => Err(IMFError::DateTimeParse(e)),
_ => Err(IMFError::DateTimeLogic),
}
}
}*/
/// Read datetime
///
/// ```abnf
/// date-time = [ day-of-week "," ] date time [CFWS]
/// time = time-of-day zone
/// ```
///
/// ## @FIXME - known bugs
///
/// - if chrono fails, Option::None is silently returned instead of failing the parser
/// - `-0000` means NaiveDateTime, a date without a timezone
/// while this library interprets it as +0000 aka UTC.
/// - Obsolete military zones should be considered as NaiveTime
/// due to an error in RFC0822 but are interpreted as their respective
/// timezone according to the RFC5322 definition
pub fn section(input: &[u8]) -> IResult<&[u8], Option<DateTime<FixedOffset>>> {
map(
terminated(
alt((
tuple((
opt(terminated(strict_day_of_week, tag(","))),
strict_date,
strict_time_of_day,
strict_zone,
)),
tuple((
opt(terminated(obs_day_of_week, tag(","))),
obs_date,
obs_time_of_day,
alt((strict_zone, obs_zone)),
)),
)),
opt(cfws),
),
|res| match res {
(_, Some(date), Some(time), Some(tz)) => {
date.and_time(time).and_local_timezone(tz).earliest()
}
_ => None,
},
)(input)
}
/// day-of-week = ([FWS] day-name) / obs-day-of-week
fn strict_day_of_week(input: &[u8]) -> IResult<&[u8], &[u8]> {
preceded(opt(fws), day_name)(input)
}
/// obs-day-of-week = [CFWS] day-name [CFWS]
fn obs_day_of_week(input: &[u8]) -> IResult<&[u8], &[u8]> {
delimited(opt(cfws), day_name, opt(cfws))(input)
}
/// day-name = "Mon" / "Tue" / "Wed" / "Thu" /
/// "Fri" / "Sat" / "Sun"
fn day_name(input: &[u8]) -> IResult<&[u8], &[u8]> {
alt((
tag_no_case(b"Mon"),
tag_no_case(b"Tue"),
tag_no_case(b"Wed"),
tag_no_case(b"Thu"),
tag_no_case(b"Fri"),
tag_no_case(b"Sat"),
tag_no_case(b"Sun"),
))(input)
}
/// date = day month year
fn strict_date(input: &[u8]) -> IResult<&[u8], Option<NaiveDate>> {
map(tuple((strict_day, month, strict_year)), |(d, m, y)| {
NaiveDate::from_ymd_opt(y, m, d)
})(input)
}
/// date = day month year
fn obs_date(input: &[u8]) -> IResult<&[u8], Option<NaiveDate>> {
map(tuple((obs_day, month, obs_year)), |(d, m, y)| {
NaiveDate::from_ymd_opt(y, m, d)
})(input)
}
/// day = ([FWS] 1*2DIGIT FWS) / obs-day
fn strict_day(input: &[u8]) -> IResult<&[u8], u32> {
delimited(opt(fws), character::complete::u32, fws)(input)
}
/// obs-day = [CFWS] 1*2DIGIT [CFWS]
fn obs_day(input: &[u8]) -> IResult<&[u8], u32> {
delimited(opt(cfws), character::complete::u32, opt(cfws))(input)
}
/// month = "Jan" / "Feb" / "Mar" / "Apr" /
/// "May" / "Jun" / "Jul" / "Aug" /
/// "Sep" / "Oct" / "Nov" / "Dec"
fn month(input: &[u8]) -> IResult<&[u8], u32> {
alt((
value(1, tag_no_case(b"Jan")),
value(2, tag_no_case(b"Feb")),
value(3, tag_no_case(b"Mar")),
value(4, tag_no_case(b"Apr")),
value(5, tag_no_case(b"May")),
value(6, tag_no_case(b"Jun")),
value(7, tag_no_case(b"Jul")),
value(8, tag_no_case(b"Aug")),
value(9, tag_no_case(b"Sep")),
value(10, tag_no_case(b"Oct")),
value(11, tag_no_case(b"Nov")),
value(12, tag_no_case(b"Dec")),
))(input)
}
/// year = (FWS 4*DIGIT FWS) / obs-year
fn strict_year(input: &[u8]) -> IResult<&[u8], i32> {
delimited(
fws,
map(
terminated(take_while_m_n(4, 9, |c| (0x30..=0x39).contains(&c)), digit0),
|d: &[u8]| {
encoding_rs::UTF_8
.decode_without_bom_handling(d)
.0
.parse::<i32>()
.unwrap_or(0)
},
),
fws,
)(input)
}
/// obs-year = [CFWS] 2*DIGIT [CFWS]
fn obs_year(input: &[u8]) -> IResult<&[u8], i32> {
map(
delimited(
opt(cfws),
terminated(take_while_m_n(2, 7, |c| (0x30..=0x39).contains(&c)), digit0),
opt(cfws),
),
|cap: &[u8]| {
let year_txt = encoding_rs::UTF_8.decode_without_bom_handling(cap).0;
let d = year_txt.parse::<i32>().unwrap_or(0);
if (0..=49).contains(&d) {
2000 + d
} else if (50..=999).contains(&d) {
1900 + d
} else {
d
}
},
)(input)
}
/// time-of-day = hour ":" minute [ ":" second ]
fn strict_time_of_day(input: &[u8]) -> IResult<&[u8], Option<NaiveTime>> {
map(
tuple((
strict_time_digit,
tag(":"),
strict_time_digit,
opt(preceded(tag(":"), strict_time_digit)),
)),
|(hour, _, minute, maybe_sec)| {
NaiveTime::from_hms_opt(hour, minute, maybe_sec.unwrap_or(0))
},
)(input)
}
/// time-of-day = hour ":" minute [ ":" second ]
fn obs_time_of_day(input: &[u8]) -> IResult<&[u8], Option<NaiveTime>> {
map(
tuple((
obs_time_digit,
tag(":"),
obs_time_digit,
opt(preceded(tag(":"), obs_time_digit)),
)),
|(hour, _, minute, maybe_sec)| {
NaiveTime::from_hms_opt(hour, minute, maybe_sec.unwrap_or(0))
},
)(input)
}
fn strict_time_digit(input: &[u8]) -> IResult<&[u8], u32> {
character::complete::u32(input)
}
fn obs_time_digit(input: &[u8]) -> IResult<&[u8], u32> {
delimited(opt(cfws), character::complete::u32, opt(cfws))(input)
}
/// Obsolete zones
///
/// ```abnf
/// zone = (FWS ( "+" / "-" ) 4DIGIT) / (FWS obs-zone)
/// ```
fn strict_zone(input: &[u8]) -> IResult<&[u8], Option<FixedOffset>> {
map(
tuple((
opt(fws),
is_a("+-"),
take_while_m_n(2, 2, |c| (0x30..=0x39).contains(&c)),
take_while_m_n(2, 2, |c| (0x30..=0x39).contains(&c)),
)),
|(_, op, dig_zone_hour, dig_zone_min)| {
let zone_hour: i32 =
((dig_zone_hour[0] - 0x30) * 10 + (dig_zone_hour[1] - 0x30)) as i32 * HOUR;
let zone_min: i32 =
((dig_zone_min[0] - 0x30) * 10 + (dig_zone_min[1] - 0x30)) as i32 * MIN;
match op {
b"+" => FixedOffset::east_opt(zone_hour + zone_min),
b"-" => FixedOffset::west_opt(zone_hour + zone_min),
_ => unreachable!(),
}
},
)(input)
}
/// obsole zone
///
/// obs-zone = "UT" / "GMT" / ; Universal Time
/// ; North American UT
/// ; offsets
/// "EST" / "EDT" / ; Eastern: - 5/ - 4
/// "CST" / "CDT" / ; Central: - 6/ - 5
/// "MST" / "MDT" / ; Mountain: - 7/ - 6
/// "PST" / "PDT" / ; Pacific: - 8/ - 7
/// ;
/// %d65-73 / ; Military zones - "A"
/// %d75-90 / ; through "I" and "K"
/// %d97-105 / ; through "Z", both
/// %d107-122 / ; upper and lower case
/// ;
/// 1*(ALPHA / DIGIT) ; Unknown legacy timezones
fn obs_zone(input: &[u8]) -> IResult<&[u8], Option<FixedOffset>> {
// The writing of this function is volontarily verbose
// to keep it straightforward to understand.
// @FIXME: Could return a TimeZone and not an Option<TimeZone>
// as it could be determined at compile time if values are correct
// and panic at this time if not. But not sure how to do it without unwrap.
preceded(
opt(fws),
alt((
// Legacy UTC/GMT
value(
FixedOffset::west_opt(0 * HOUR),
alt((tag_no_case(b"UTC"), tag_no_case(b"UT"), tag_no_case(b"GMT"))),
),
// USA Timezones
value(FixedOffset::west_opt(4 * HOUR), tag_no_case(b"EDT")),
value(
FixedOffset::west_opt(5 * HOUR),
alt((tag_no_case(b"EST"), tag_no_case(b"CDT"))),
),
value(
FixedOffset::west_opt(6 * HOUR),
alt((tag_no_case(b"CST"), tag_no_case(b"MDT"))),
),
value(
FixedOffset::west_opt(7 * HOUR),
alt((tag_no_case(b"MST"), tag_no_case(b"PDT"))),
),
value(FixedOffset::west_opt(8 * HOUR), tag_no_case(b"PST")),
// Military Timezone UTC
value(FixedOffset::west_opt(0 * HOUR), tag_no_case(b"Z")),
// Military Timezones East
alt((
value(FixedOffset::east_opt(HOUR), tag_no_case(b"A")),
value(FixedOffset::east_opt(2 * HOUR), tag_no_case(b"B")),
value(FixedOffset::east_opt(3 * HOUR), tag_no_case(b"C")),
value(FixedOffset::east_opt(4 * HOUR), tag_no_case(b"D")),
value(FixedOffset::east_opt(5 * HOUR), tag_no_case(b"E")),
value(FixedOffset::east_opt(6 * HOUR), tag_no_case(b"F")),
value(FixedOffset::east_opt(7 * HOUR), tag_no_case(b"G")),
value(FixedOffset::east_opt(8 * HOUR), tag_no_case(b"H")),
value(FixedOffset::east_opt(9 * HOUR), tag_no_case(b"I")),
value(FixedOffset::east_opt(10 * HOUR), tag_no_case(b"K")),
value(FixedOffset::east_opt(11 * HOUR), tag_no_case(b"L")),
value(FixedOffset::east_opt(12 * HOUR), tag_no_case(b"M")),
)),
// Military Timezones West
alt((
value(FixedOffset::west_opt(HOUR), tag_no_case(b"N")),
value(FixedOffset::west_opt(2 * HOUR), tag_no_case(b"O")),
value(FixedOffset::west_opt(3 * HOUR), tag_no_case(b"P")),
value(FixedOffset::west_opt(4 * HOUR), tag_no_case(b"Q")),
value(FixedOffset::west_opt(5 * HOUR), tag_no_case(b"R")),
value(FixedOffset::west_opt(6 * HOUR), tag_no_case(b"S")),
value(FixedOffset::west_opt(7 * HOUR), tag_no_case(b"T")),
value(FixedOffset::west_opt(8 * HOUR), tag_no_case(b"U")),
value(FixedOffset::west_opt(9 * HOUR), tag_no_case(b"V")),
value(FixedOffset::west_opt(10 * HOUR), tag_no_case(b"W")),
value(FixedOffset::west_opt(11 * HOUR), tag_no_case(b"X")),
value(FixedOffset::west_opt(12 * HOUR), tag_no_case(b"Y")),
)),
// Unknown timezone
value(FixedOffset::west_opt(0 * HOUR), alphanumeric1),
)),
)(input)
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
#[test]
fn test_section_rfc_strict() {
assert_eq!(
section(b"Fri, 21 Nov 1997 09:55:06 -0600"),
Ok((
&b""[..],
Some(
FixedOffset::west_opt(6 * HOUR)
.unwrap()
.with_ymd_and_hms(1997, 11, 21, 9, 55, 6)
.unwrap()
)
)),
);
}
#[test]
fn test_section_received() {
assert_eq!(
section(b"Sun, 18 Jun 2023 15:39:08 +0200 (CEST)"),
Ok((
&b""[..],
Some(
FixedOffset::east_opt(2 * HOUR)
.unwrap()
.with_ymd_and_hms(2023, 6, 18, 15, 39, 8)
.unwrap()
)
)),
);
}
#[test]
fn test_section_rfc_ws() {
assert_eq!(
section(
r#"Thu,
13
Feb
1969
23:32
-0330 (Newfoundland Time)"#
.as_bytes()
),
Ok((
&b""[..],
Some(
FixedOffset::west_opt(3 * HOUR + 30 * MIN)
.unwrap()
.with_ymd_and_hms(1969, 2, 13, 23, 32, 00)
.unwrap()
)
)),
);
}
#[test]
fn test_section_rfc_obs() {
assert_eq!(
section(b"21 Nov 97 09:55:06 GMT"),
Ok((
&b""[..],
Some(
FixedOffset::east_opt(0)
.unwrap()
.with_ymd_and_hms(1997, 11, 21, 9, 55, 6)
.unwrap()
)
)),
);
}
#[test]
fn test_section_3digit_year() {
assert_eq!(
section(b"21 Nov 103 09:55:06 UT"),
Ok((
&b""[..],
Some(
FixedOffset::east_opt(0)
.unwrap()
.with_ymd_and_hms(2003, 11, 21, 9, 55, 6)
.unwrap()
)
)),
);
}
#[test]
fn test_section_rfc_obs_ws() {
assert_eq!(
section(b"Fri, 21 Nov 1997 09(comment): 55 : 06 -0600"),
Ok((
&b""[..],
Some(
FixedOffset::west_opt(6 * HOUR)
.unwrap()
.with_ymd_and_hms(1997, 11, 21, 9, 55, 6)
.unwrap()
)
)),
);
}
#[test]
fn test_section_2digit_year() {
assert_eq!(
section(b"21 Nov 23 09:55:06Z"),
Ok((
&b""[..],
Some(
FixedOffset::east_opt(0)
.unwrap()
.with_ymd_and_hms(2023, 11, 21, 9, 55, 6)
.unwrap()
)
)),
);
}
#[test]
fn test_section_military_zone_east() {
["a", "B", "c", "D", "e", "F", "g", "H", "i", "K", "l", "M"]
.iter()
.enumerate()
.for_each(|(i, x)| {
assert_eq!(
section(format!("1 Jan 22 08:00:00 {}", x).as_bytes()),
Ok((
&b""[..],
Some(
FixedOffset::east_opt((i as i32 + 1) * HOUR)
.unwrap()
.with_ymd_and_hms(2022, 01, 01, 8, 0, 0)
.unwrap()
)
))
);
});
}
#[test]
fn test_section_military_zone_west() {
["N", "O", "P", "q", "r", "s", "T", "U", "V", "w", "x", "y"]
.iter()
.enumerate()
.for_each(|(i, x)| {
assert_eq!(
section(format!("1 Jan 22 08:00:00 {}", x).as_bytes()),
Ok((
&b""[..],
Some(
FixedOffset::west_opt((i as i32 + 1) * HOUR)
.unwrap()
.with_ymd_and_hms(2022, 01, 01, 8, 0, 0)
.unwrap()
)
))
);
});
}
#[test]
fn test_section_gmt() {
assert_eq!(
section(b"21 Nov 2023 07:07:07 +0000"),
Ok((
&b""[..],
Some(
FixedOffset::east_opt(0)
.unwrap()
.with_ymd_and_hms(2023, 11, 21, 7, 7, 7)
.unwrap()
)
)),
);
assert_eq!(
section(b"21 Nov 2023 07:07:07 -0000"),
Ok((
&b""[..],
Some(
FixedOffset::east_opt(0)
.unwrap()
.with_ymd_and_hms(2023, 11, 21, 7, 7, 7)
.unwrap()
)
)),
);
assert_eq!(
section(b"21 Nov 2023 07:07:07 Z"),
Ok((
&b""[..],
Some(
FixedOffset::east_opt(0)
.unwrap()
.with_ymd_and_hms(2023, 11, 21, 7, 7, 7)
.unwrap()
)
)),
);
assert_eq!(
section(b"21 Nov 2023 07:07:07 GMT"),
Ok((
&b""[..],
Some(
FixedOffset::east_opt(0)
.unwrap()
.with_ymd_and_hms(2023, 11, 21, 7, 7, 7)
.unwrap()
)
)),
);
assert_eq!(
section(b"21 Nov 2023 07:07:07 UT"),
Ok((
&b""[..],
Some(
FixedOffset::east_opt(0)
.unwrap()
.with_ymd_and_hms(2023, 11, 21, 7, 7, 7)
.unwrap()
)
)),
);
assert_eq!(
section(b"21 Nov 2023 07:07:07 UTC"),
Ok((
&b""[..],
Some(
FixedOffset::east_opt(0)
.unwrap()
.with_ymd_and_hms(2023, 11, 21, 7, 7, 7)
.unwrap()
)
)),
);
}
#[test]
fn test_section_usa() {
assert_eq!(
section(b"21 Nov 2023 4:4:4 CST"),
Ok((
&b""[..],
Some(
FixedOffset::west_opt(6 * HOUR)
.unwrap()
.with_ymd_and_hms(2023, 11, 21, 4, 4, 4)
.unwrap()
)
)),
);
}
}

75
src/imf/field.rs Normal file
View file

@ -0,0 +1,75 @@
use chrono::{DateTime, FixedOffset};
use nom::combinator::map;
use crate::header;
use crate::imf::address::{address_list, mailbox_list, nullable_address_list, AddressList};
use crate::imf::datetime::section as date;
use crate::imf::identification::{msg_id, msg_list, MessageID, MessageIDList};
use crate::imf::mailbox::{mailbox, AddrSpec, MailboxList, MailboxRef};
use crate::imf::mime::{version, Version};
use crate::imf::trace::{received_log, return_path, ReceivedLog};
use crate::text::misc_token::{phrase_list, unstructured, PhraseList, Unstructured};
#[derive(Debug, PartialEq)]
pub enum Field<'a> {
// 3.6.1. The Origination Date Field
Date(Option<DateTime<FixedOffset>>),
// 3.6.2. Originator Fields
From(MailboxList<'a>),
Sender(MailboxRef<'a>),
ReplyTo(AddressList<'a>),
// 3.6.3. Destination Address Fields
To(AddressList<'a>),
Cc(AddressList<'a>),
Bcc(AddressList<'a>),
// 3.6.4. Identification Fields
MessageID(MessageID<'a>),
InReplyTo(MessageIDList<'a>),
References(MessageIDList<'a>),
// 3.6.5. Informational Fields
Subject(Unstructured<'a>),
Comments(Unstructured<'a>),
Keywords(PhraseList<'a>),
// 3.6.6 Resent Fields (not implemented)
// 3.6.7 Trace Fields
Received(ReceivedLog<'a>),
ReturnPath(Option<AddrSpec<'a>>),
MIMEVersion(Version),
}
impl<'a> TryFrom<&header::Field<'a>> for Field<'a> {
type Error = ();
fn try_from(f: &header::Field<'a>) -> Result<Self, Self::Error> {
let content = match f {
header::Field::Good(header::Kv2(key, value)) => {
match key.to_ascii_lowercase().as_slice() {
b"date" => map(date, Field::Date)(value),
b"from" => map(mailbox_list, Field::From)(value),
b"sender" => map(mailbox, Field::Sender)(value),
b"reply-to" => map(address_list, Field::ReplyTo)(value),
b"to" => map(address_list, Field::To)(value),
b"cc" => map(address_list, Field::Cc)(value),
b"bcc" => map(nullable_address_list, Field::Bcc)(value),
b"message-id" => map(msg_id, Field::MessageID)(value),
b"in-reply-to" => map(msg_list, Field::InReplyTo)(value),
b"references" => map(msg_list, Field::References)(value),
b"subject" => map(unstructured, Field::Subject)(value),
b"comments" => map(unstructured, Field::Comments)(value),
b"keywords" => map(phrase_list, Field::Keywords)(value),
b"return-path" => map(return_path, Field::ReturnPath)(value),
b"received" => map(received_log, Field::Received)(value),
b"mime-version" => map(version, Field::MIMEVersion)(value),
_ => return Err(()),
}
}
_ => return Err(()),
};
content.map(|(_, content)| content).or(Err(()))
}
}

87
src/imf/identification.rs Normal file
View file

@ -0,0 +1,87 @@
use nom::{
branch::alt,
bytes::complete::{tag, take_while},
combinator::opt,
multi::many1,
sequence::{delimited, pair, tuple},
IResult,
};
use std::fmt;
use crate::imf::mailbox::is_dtext;
use crate::text::whitespace::cfws;
use crate::text::words::dot_atom_text;
#[derive(PartialEq, Clone)]
pub struct MessageID<'a> {
pub left: &'a [u8],
pub right: &'a [u8],
}
impl<'a> ToString for MessageID<'a> {
fn to_string(&self) -> String {
format!(
"{}@{}",
String::from_utf8_lossy(self.left),
String::from_utf8_lossy(self.right)
)
}
}
impl<'a> fmt::Debug for MessageID<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple("MessageID")
.field(&format_args!("\"{}\"", self.to_string()))
.finish()
}
}
pub type MessageIDList<'a> = Vec<MessageID<'a>>;
/// Message identifier
///
/// ```abnf
/// msg-id = [CFWS] "<" id-left "@" id-right ">" [CFWS]
/// ```
pub fn msg_id(input: &[u8]) -> IResult<&[u8], MessageID> {
let (input, (left, _, right)) = delimited(
pair(opt(cfws), tag("<")),
tuple((id_left, tag("@"), id_right)),
pair(tag(">"), opt(cfws)),
)(input)?;
Ok((input, MessageID { left, right }))
}
pub fn msg_list(input: &[u8]) -> IResult<&[u8], MessageIDList> {
many1(msg_id)(input)
}
// @FIXME Missing obsolete
fn id_left(input: &[u8]) -> IResult<&[u8], &[u8]> {
dot_atom_text(input)
}
// @FIXME Missing obsolete
fn id_right(input: &[u8]) -> IResult<&[u8], &[u8]> {
alt((dot_atom_text, no_fold_litteral))(input)
}
fn no_fold_litteral(input: &[u8]) -> IResult<&[u8], &[u8]> {
delimited(tag("["), take_while(is_dtext), tag("]"))(input)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_msg_id() {
assert_eq!(
msg_id(b"<5678.21-Nov-1997@example.com>"),
Ok((
&b""[..],
MessageID {
left: &b"5678.21-Nov-1997"[..],
right: &b"example.com"[..],
}
)),
);
}
}

595
src/imf/mailbox.rs Normal file
View file

@ -0,0 +1,595 @@
use nom::{
branch::alt,
bytes::complete::{tag, take_while1},
combinator::{into, map, opt},
multi::{many0, separated_list1},
sequence::{delimited, pair, preceded, terminated, tuple},
IResult,
};
use std::fmt;
use crate::text::ascii;
use crate::text::misc_token::{phrase, word, Phrase, Word};
use crate::text::whitespace::{cfws, fws, is_obs_no_ws_ctl};
use crate::text::words::atom;
#[derive(PartialEq)]
pub struct AddrSpec<'a> {
pub local_part: LocalPart<'a>,
pub domain: Domain<'a>,
}
impl<'a> ToString for AddrSpec<'a> {
fn to_string(&self) -> String {
format!(
"{}@{}",
self.local_part.to_string(),
self.domain.to_string()
)
}
}
impl<'a> fmt::Debug for AddrSpec<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple("AddrSpec")
.field(&format_args!("\"{}\"", self.to_string()))
.finish()
}
}
#[derive(Debug, PartialEq)]
pub struct MailboxRef<'a> {
// The actual "email address" like hello@example.com
pub addrspec: AddrSpec<'a>,
pub name: Option<Phrase<'a>>,
}
impl<'a> ToString for MailboxRef<'a> {
fn to_string(&self) -> String {
match &self.name {
Some(n) => format!("{} <{}>", n.to_string(), self.addrspec.to_string()),
None => self.addrspec.to_string(),
}
}
}
impl<'a> From<AddrSpec<'a>> for MailboxRef<'a> {
fn from(addr: AddrSpec<'a>) -> Self {
MailboxRef {
name: None,
addrspec: addr,
}
}
}
pub type MailboxList<'a> = Vec<MailboxRef<'a>>;
/// Mailbox
///
/// ```abnf
/// mailbox = name-addr / addr-spec
/// ```
pub fn mailbox(input: &[u8]) -> IResult<&[u8], MailboxRef> {
alt((name_addr, into(addr_spec)))(input)
}
/// Name of the email address
///
/// ```abnf
/// name-addr = [display-name] angle-addr
/// ```
fn name_addr(input: &[u8]) -> IResult<&[u8], MailboxRef> {
let (input, name) = opt(phrase)(input)?;
let (input, addrspec) = angle_addr(input)?;
Ok((input, MailboxRef { name, addrspec }))
}
/// Enclosed addr-spec with < and >
///
/// ```abnf
/// angle-addr = [CFWS] "<" addr-spec ">" [CFWS] /
/// obs-angle-addr
/// ```
pub fn angle_addr(input: &[u8]) -> IResult<&[u8], AddrSpec> {
delimited(
tuple((opt(cfws), tag(&[ascii::LT]), opt(obs_route))),
addr_spec,
pair(tag(&[ascii::GT]), opt(cfws)),
)(input)
}
/// obs-route = obs-domain-list ":"
fn obs_route(input: &[u8]) -> IResult<&[u8], Vec<Option<Domain>>> {
terminated(obs_domain_list, tag(&[ascii::COL]))(input)
}
/// ```abnf
/// obs-domain-list = *(CFWS / ",") "@" domain
/// *("," [CFWS] ["@" domain])
/// ```
fn obs_domain_list(input: &[u8]) -> IResult<&[u8], Vec<Option<Domain>>> {
preceded(
many0(cfws),
separated_list1(
tag(&[ascii::COMMA]),
preceded(many0(cfws), opt(preceded(tag(&[ascii::AT]), obs_domain))),
),
)(input)
}
/// AddrSpec
///
/// ```abnf
/// addr-spec = local-part "@" domain
/// ```
/// @FIXME: this system does not work to alternate between strict and obsolete
/// so I force obsolete for now...
pub fn addr_spec(input: &[u8]) -> IResult<&[u8], AddrSpec> {
map(
tuple((
obs_local_part,
tag(&[ascii::AT]),
obs_domain,
many0(pair(tag(&[ascii::AT]), obs_domain)), // for compatibility reasons with ENRON
)),
|(local_part, _, domain, _)| AddrSpec { local_part, domain },
)(input)
}
#[derive(Debug, PartialEq)]
pub enum LocalPartToken<'a> {
Dot,
Word(Word<'a>),
}
#[derive(Debug, PartialEq)]
pub struct LocalPart<'a>(pub Vec<LocalPartToken<'a>>);
impl<'a> LocalPart<'a> {
pub fn to_string(&self) -> String {
self.0.iter().fold(String::new(), |mut acc, token| {
match token {
LocalPartToken::Dot => acc.push('.'),
LocalPartToken::Word(v) => acc.push_str(v.to_string().as_ref()),
}
acc
})
}
}
/// Obsolete local part
///
/// Compared to the RFC, we allow multiple dots.
/// This is found in Enron emails and supported by Gmail.
///
/// Obsolete local part is a superset of strict_local_part:
/// anything that is parsed by strict_local_part will be parsed by
/// obs_local_part.
///
/// ```abnf
/// obs-local-part = *("." / word)
/// ```
fn obs_local_part(input: &[u8]) -> IResult<&[u8], LocalPart> {
map(
many0(alt((
map(tag(&[ascii::PERIOD]), |_| LocalPartToken::Dot),
map(word, LocalPartToken::Word),
))),
LocalPart,
)(input)
}
#[derive(PartialEq)]
pub enum Domain<'a> {
Atoms(Vec<&'a [u8]>),
Litteral(Vec<&'a [u8]>),
}
impl<'a> ToString for Domain<'a> {
fn to_string(&self) -> String {
match self {
Domain::Atoms(v) => v
.iter()
.map(|v| {
encoding_rs::UTF_8
.decode_without_bom_handling(v)
.0
.to_string()
})
.collect::<Vec<String>>()
.join("."),
Domain::Litteral(v) => {
let inner = v
.iter()
.map(|v| {
encoding_rs::UTF_8
.decode_without_bom_handling(v)
.0
.to_string()
})
.collect::<Vec<String>>()
.join(" ");
format!("[{}]", inner)
}
}
}
}
impl<'a> fmt::Debug for Domain<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple("Domain")
.field(&format_args!("\"{}\"", self.to_string()))
.finish()
}
}
/// Obsolete domain
///
/// Rewritten so that obs_domain is a superset
/// of strict_domain.
///
/// ```abnf
/// obs-domain = atom *("." atom) / domain-literal
/// ```
pub fn obs_domain(input: &[u8]) -> IResult<&[u8], Domain> {
alt((
map(separated_list1(tag("."), atom), Domain::Atoms),
domain_litteral,
))(input)
}
/// Domain litteral
///
/// ```abnf
/// domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
/// ```
fn domain_litteral(input: &[u8]) -> IResult<&[u8], Domain> {
delimited(
pair(opt(cfws), tag(&[ascii::LEFT_BRACKET])),
inner_domain_litteral,
pair(tag(&[ascii::RIGHT_BRACKET]), opt(cfws)),
)(input)
}
fn inner_domain_litteral(input: &[u8]) -> IResult<&[u8], Domain> {
map(
terminated(many0(preceded(opt(fws), take_while1(is_dtext))), opt(fws)),
Domain::Litteral,
)(input)
}
fn is_strict_dtext(c: u8) -> bool {
(0x21..=0x5A).contains(&c) || (0x5E..=0x7E).contains(&c)
}
/// Is domain text
///
/// ```abnf
/// dtext = %d33-90 / ; Printable US-ASCII
/// %d94-126 / ; characters not including
/// obs-dtext ; "[", "]", or "\"
/// obs-dtext = obs-NO-WS-CTL / quoted-pair
/// ```
pub fn is_dtext(c: u8) -> bool {
is_strict_dtext(c) || is_obs_no_ws_ctl(c)
//@FIXME does not support quoted pair yet while RFC requires it
}
#[cfg(test)]
mod tests {
use super::*;
use crate::text::quoted::QuotedString;
#[test]
fn test_addr_spec() {
assert_eq!(
addr_spec(b"alice@example.com"),
Ok((
&b""[..],
AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(&b"alice"[..]))]),
domain: Domain::Atoms(vec![&b"example"[..], &b"com"[..]]),
}
))
);
assert_eq!(
addr_spec(b"jsmith@[192.168.2.1]").unwrap().1.to_string(),
"jsmith@[192.168.2.1]".to_string(),
);
assert_eq!(
addr_spec(b"jsmith@[IPv6:2001:db8::1]")
.unwrap()
.1
.to_string(),
"jsmith@[IPv6:2001:db8::1]".to_string(),
);
// UTF-8
// @FIXME ASCII SUPPORT IS BROKEN
/*assert_eq!(
addr_spec("用户@例子.广告"),
Ok((
"",
AddrSpec {
local_part: "用户".into(),
domain: "例子.广告".into()
}
))
);*/
// ASCII Edge cases
assert_eq!(
addr_spec(b"user+mailbox/department=shipping@example.com")
.unwrap()
.1
.to_string(),
"user+mailbox/department=shipping@example.com".to_string(),
);
assert_eq!(
addr_spec(b"!#$%&'*+-/=?^_`.{|}~@example.com")
.unwrap()
.1
.to_string(),
"!#$%&'*+-/=?^_`.{|}~@example.com".to_string(),
);
assert_eq!(
addr_spec(r#""Abc@def"@example.com"#.as_bytes()),
Ok((
&b""[..],
AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Quoted(QuotedString(
vec![b"Abc@def"]
)))]),
domain: Domain::Atoms(vec![&b"example"[..], &b"com"[..]]),
}
))
);
assert_eq!(
addr_spec(r#""Fred\ Bloggs"@example.com"#.as_bytes()),
Ok((
&b""[..],
AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Quoted(QuotedString(
vec![b"Fred", b" ", b"Bloggs"]
)))]),
domain: Domain::Atoms(vec![&b"example"[..], &b"com"[..]]),
}
))
);
assert_eq!(
addr_spec(r#""Joe.\\Blow"@example.com"#.as_bytes()),
Ok((
&b""[..],
AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Quoted(QuotedString(
vec![b"Joe.", &[ascii::BACKSLASH], b"Blow"]
)))]),
domain: Domain::Atoms(vec![&b"example"[..], &b"com"[..]]),
}
))
);
}
#[test]
fn test_mailbox() {
assert_eq!(
mailbox(r#""Joe Q. Public" <john.q.public@example.com>"#.as_bytes()),
Ok((
&b""[..],
MailboxRef {
name: Some(Phrase(vec![Word::Quoted(QuotedString(vec![
&b"Joe"[..],
&[ascii::SP],
&b"Q."[..],
&[ascii::SP],
&b"Public"[..]
]))])),
addrspec: AddrSpec {
local_part: LocalPart(vec![
LocalPartToken::Word(Word::Atom(&b"john"[..])),
LocalPartToken::Dot,
LocalPartToken::Word(Word::Atom(&b"q"[..])),
LocalPartToken::Dot,
LocalPartToken::Word(Word::Atom(&b"public"[..])),
]),
domain: Domain::Atoms(vec![&b"example"[..], &b"com"[..]]),
}
}
))
);
assert_eq!(
mailbox(r#"Mary Smith <mary@x.test>"#.as_bytes()),
Ok((
&b""[..],
MailboxRef {
name: Some(Phrase(vec![
Word::Atom(&b"Mary"[..]),
Word::Atom(&b"Smith"[..])
])),
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(&b"mary"[..]))]),
domain: Domain::Atoms(vec![&b"x"[..], &b"test"[..]]),
}
}
))
);
assert_eq!(
mailbox(r#"jdoe@example.org"#.as_bytes()),
Ok((
&b""[..],
MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(&b"jdoe"[..]))]),
domain: Domain::Atoms(vec![&b"example"[..], &b"org"[..]]),
}
}
))
);
assert_eq!(
mailbox(r#"Who? <one@y.test>"#.as_bytes()),
Ok((
&b""[..],
MailboxRef {
name: Some(Phrase(vec![Word::Atom(&b"Who?"[..])])),
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(&b"one"[..]))]),
domain: Domain::Atoms(vec![&b"y"[..], &b"test"[..]]),
}
}
))
);
assert_eq!(
mailbox(r#"<boss@nil.test>"#.as_bytes()),
Ok((
&b""[..],
MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(&b"boss"[..]))]),
domain: Domain::Atoms(vec![&b"nil"[..], &b"test"[..]]),
}
}
))
);
assert_eq!(
mailbox(r#""Giant; \"Big\" Box" <sysservices@example.net>"#.as_bytes()),
Ok((
&b""[..],
MailboxRef {
name: Some(Phrase(vec![Word::Quoted(QuotedString(vec![
&b"Giant;"[..],
&[ascii::SP],
&[ascii::DQUOTE],
&b"Big"[..],
&[ascii::DQUOTE],
&[ascii::SP],
&b"Box"[..]
]))])),
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(
&b"sysservices"[..]
))]),
domain: Domain::Atoms(vec![&b"example"[..], &b"net"[..]]),
}
}
))
);
}
#[test]
fn test_obs_domain_list() {
assert_eq!(
obs_domain_list(
r#"(shhh it's coming)
,
(not yet)
@33+4.com,,,,
,,,,
(again)
@example.com,@yep.com,@a,@b,,,@c"#
.as_bytes()
),
Ok((
&b""[..],
vec![
None,
Some(Domain::Atoms(vec![&b"33+4"[..], &b"com"[..]])),
None,
None,
None,
None,
None,
None,
None,
Some(Domain::Atoms(vec![&b"example"[..], &b"com"[..]])),
Some(Domain::Atoms(vec![&b"yep"[..], &b"com"[..]])),
Some(Domain::Atoms(vec![&b"a"[..]])),
Some(Domain::Atoms(vec![&b"b"[..]])),
None,
None,
Some(Domain::Atoms(vec![&b"c"[..]])),
]
))
);
}
#[test]
fn test_enron1() {
assert_eq!(
addr_spec("a..howard@enron.com".as_bytes()),
Ok((
&b""[..],
AddrSpec {
local_part: LocalPart(vec![
LocalPartToken::Word(Word::Atom(&b"a"[..])),
LocalPartToken::Dot,
LocalPartToken::Dot,
LocalPartToken::Word(Word::Atom(&b"howard"[..])),
]),
domain: Domain::Atoms(vec![&b"enron"[..], &b"com"[..]]),
}
))
);
}
#[test]
fn test_enron2() {
assert_eq!(
addr_spec(".nelson@enron.com".as_bytes()),
Ok((
&b""[..],
AddrSpec {
local_part: LocalPart(vec![
LocalPartToken::Dot,
LocalPartToken::Word(Word::Atom(&b"nelson"[..])),
]),
domain: Domain::Atoms(vec![&b"enron"[..], &b"com"[..]]),
}
))
);
}
#[test]
fn test_enron3() {
assert_eq!(
addr_spec("ecn2760.conf.@enron.com".as_bytes()),
Ok((
&b""[..],
AddrSpec {
local_part: LocalPart(vec![
LocalPartToken::Word(Word::Atom(&b"ecn2760"[..])),
LocalPartToken::Dot,
LocalPartToken::Word(Word::Atom(&b"conf"[..])),
LocalPartToken::Dot,
]),
domain: Domain::Atoms(vec![&b"enron"[..], &b"com"[..]]),
}
))
);
}
#[test]
fn test_enron4() {
assert_eq!(
mailbox(
r#"<"mark_kopinski/intl/acim/americancentury"@americancentury.com@enron.com>"#
.as_bytes()
),
Ok((
&b""[..],
MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Quoted(
QuotedString(vec![&b"mark_kopinski/intl/acim/americancentury"[..],])
))]),
domain: Domain::Atoms(vec![&b"americancentury"[..], &b"com"[..]]),
}
}
))
);
}
}

64
src/imf/mime.rs Normal file
View file

@ -0,0 +1,64 @@
use nom::{
bytes::complete::{tag, take},
combinator::{map, opt, verify},
sequence::tuple,
IResult,
};
use crate::text::ascii;
use crate::text::whitespace::cfws;
#[derive(Debug, PartialEq)]
pub struct Version {
pub major: u8,
pub minor: u8,
}
pub fn version(input: &[u8]) -> IResult<&[u8], Version> {
let (rest, (_, major, _, _, _, minor, _)) = tuple((
opt(cfws),
map(verify(take(1usize), is_digit), ascii_to_u8),
opt(cfws),
tag(b"."),
opt(cfws),
map(verify(take(1usize), is_digit), ascii_to_u8),
opt(cfws),
))(input)?;
Ok((rest, Version { major, minor }))
}
fn is_digit(c: &[u8]) -> bool {
c[0] >= ascii::N0 && c[0] <= ascii::N9
}
fn ascii_to_u8(c: &[u8]) -> u8 {
c[0] - ascii::N0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_version() {
assert_eq!(
version(b"1.0"),
Ok((&b""[..], Version { major: 1, minor: 0 })),
);
assert_eq!(
version(b" 1.0 (produced by MetaSend Vx.x)"),
Ok((&b""[..], Version { major: 1, minor: 0 })),
);
assert_eq!(
version(b"(produced by MetaSend Vx.x) 1.0"),
Ok((&b""[..], Version { major: 1, minor: 0 })),
);
assert_eq!(
version(b"1.(produced by MetaSend Vx.x)0"),
Ok((&b""[..], Version { major: 1, minor: 0 })),
);
}
}

144
src/imf/mod.rs Normal file
View file

@ -0,0 +1,144 @@
/// Parse and represent IMF (Internet Message Format) headers (RFC822, RFC5322)
pub mod address;
pub mod datetime;
pub mod field;
pub mod identification;
pub mod mailbox;
pub mod mime;
pub mod trace;
use nom::{combinator::map, IResult};
use crate::header;
use crate::imf::address::AddressRef;
use crate::imf::field::Field;
use crate::imf::identification::MessageID;
use crate::imf::mailbox::{AddrSpec, MailboxRef};
use crate::imf::mime::Version;
use crate::imf::trace::ReceivedLog;
use crate::text::misc_token::{PhraseList, Unstructured};
use chrono::{DateTime, FixedOffset};
#[derive(Debug, PartialEq, Default)]
pub struct Imf<'a> {
// 3.6.1. The Origination Date Field
pub date: Option<DateTime<FixedOffset>>,
// 3.6.2. Originator Fields
pub from: Vec<MailboxRef<'a>>,
pub sender: Option<MailboxRef<'a>>,
pub reply_to: Vec<AddressRef<'a>>,
// 3.6.3. Destination Address Fields
pub to: Vec<AddressRef<'a>>,
pub cc: Vec<AddressRef<'a>>,
pub bcc: Vec<AddressRef<'a>>,
// 3.6.4. Identification Fields
pub msg_id: Option<MessageID<'a>>,
pub in_reply_to: Vec<MessageID<'a>>,
pub references: Vec<MessageID<'a>>,
// 3.6.5. Informational Fields
pub subject: Option<Unstructured<'a>>,
pub comments: Vec<Unstructured<'a>>,
pub keywords: Vec<PhraseList<'a>>,
// 3.6.6 Not implemented
// 3.6.7 Trace Fields
pub return_path: Vec<AddrSpec<'a>>,
pub received: Vec<ReceivedLog<'a>>,
// MIME
pub mime_version: Option<Version>,
}
//@FIXME min and max limits are not enforced,
// it may result in missing data or silently overriden data.
impl<'a> FromIterator<Field<'a>> for Imf<'a> {
fn from_iter<I: IntoIterator<Item = Field<'a>>>(iter: I) -> Self {
iter.into_iter().fold(Imf::default(), |mut section, field| {
match field {
Field::Date(v) => section.date = v,
Field::From(v) => section.from.extend(v),
Field::Sender(v) => section.sender = Some(v),
Field::ReplyTo(v) => section.reply_to.extend(v),
Field::To(v) => section.to.extend(v),
Field::Cc(v) => section.cc.extend(v),
Field::Bcc(v) => section.bcc.extend(v),
Field::MessageID(v) => section.msg_id = Some(v),
Field::InReplyTo(v) => section.in_reply_to.extend(v),
Field::References(v) => section.references.extend(v),
Field::Subject(v) => section.subject = Some(v),
Field::Comments(v) => section.comments.push(v),
Field::Keywords(v) => section.keywords.push(v),
Field::ReturnPath(v) => v.map(|x| section.return_path.push(x)).unwrap_or(()),
Field::Received(v) => section.received.push(v),
Field::MIMEVersion(v) => section.mime_version = Some(v),
};
section
})
}
}
pub fn imf(input: &[u8]) -> IResult<&[u8], Imf> {
map(header::header_kv, |fields| {
fields
.iter()
.flat_map(Field::try_from)
.into_iter()
.collect::<Imf>()
})(input)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::imf::address::*;
use crate::imf::mailbox::*;
use crate::text::misc_token::*;
use chrono::{FixedOffset, TimeZone};
#[test]
fn test_header() {
let fullmail = b"Date: 7 Mar 2023 08:00:00 +0200
From: someone@example.com
To: someone_else@example.com
Subject: An RFC 822 formatted message
This is the plain text body of the message. Note the blank line
between the header information and the body of the message.";
assert_eq!(
imf(fullmail),
Ok((
&b"This is the plain text body of the message. Note the blank line\nbetween the header information and the body of the message."[..],
Imf {
date: Some(FixedOffset::east_opt(2 * 3600).unwrap().with_ymd_and_hms(2023, 3, 7, 8, 0, 0).unwrap()),
from: vec![MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(&b"someone"[..]))]),
domain: Domain::Atoms(vec![&b"example"[..], &b"com"[..]]),
}
}],
to: vec![AddressRef::Single(MailboxRef {
name: None,
addrspec: AddrSpec {
local_part: LocalPart(vec![LocalPartToken::Word(Word::Atom(&b"someone_else"[..]))]),
domain: Domain::Atoms(vec![&b"example"[..], &b"com"[..]]),
}
})],
subject: Some(Unstructured(vec![
UnstrToken::Plain(&b"An"[..]),
UnstrToken::Plain(&b"RFC"[..]),
UnstrToken::Plain(&b"822"[..]),
UnstrToken::Plain(&b"formatted"[..]),
UnstrToken::Plain(&b"message"[..]),
])),
..Imf::default()
}
)),
)
}
}

126
src/imf/trace.rs Normal file
View file

@ -0,0 +1,126 @@
use chrono::{DateTime, FixedOffset};
use nom::{
branch::alt,
bytes::complete::{is_a, tag},
combinator::{map, not, opt},
multi::many0,
sequence::{terminated, tuple},
IResult,
};
use crate::imf::{datetime, mailbox};
use crate::text::{ascii, misc_token, whitespace};
#[derive(Debug, PartialEq)]
pub enum ReceivedLogToken<'a> {
Addr(mailbox::AddrSpec<'a>),
Domain(mailbox::Domain<'a>),
Word(misc_token::Word<'a>),
}
#[derive(Debug, PartialEq)]
pub struct ReceivedLog<'a> {
pub log: Vec<ReceivedLogToken<'a>>,
pub date: Option<DateTime<FixedOffset>>,
}
/*
impl<'a> TryFrom<&'a lazy::ReceivedLog<'a>> for ReceivedLog<'a> {
type Error = IMFError<'a>;
fn try_from(input: &'a lazy::ReceivedLog<'a>) -> Result<Self, Self::Error> {
received_body(input.0)
.map_err(|e| IMFError::ReceivedLog(e))
.map(|(_, v)| ReceivedLog(v))
}
}*/
pub fn received_log(input: &[u8]) -> IResult<&[u8], ReceivedLog> {
map(
tuple((many0(received_tokens), tag(";"), datetime::section)),
|(tokens, _, dt)| ReceivedLog {
log: tokens,
date: dt,
},
)(input)
}
pub fn return_path(input: &[u8]) -> IResult<&[u8], Option<mailbox::AddrSpec>> {
alt((map(mailbox::angle_addr, Some), empty_path))(input)
}
fn empty_path(input: &[u8]) -> IResult<&[u8], Option<mailbox::AddrSpec>> {
let (input, _) = tuple((
opt(whitespace::cfws),
tag(&[ascii::LT]),
opt(whitespace::cfws),
tag(&[ascii::GT]),
opt(whitespace::cfws),
))(input)?;
Ok((input, None))
}
fn received_tokens(input: &[u8]) -> IResult<&[u8], ReceivedLogToken> {
alt((
terminated(
map(misc_token::word, ReceivedLogToken::Word),
not(is_a([ascii::PERIOD, ascii::AT])),
),
map(mailbox::angle_addr, ReceivedLogToken::Addr),
map(mailbox::addr_spec, ReceivedLogToken::Addr),
map(mailbox::obs_domain, ReceivedLogToken::Domain),
))(input)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::imf::trace::misc_token::Word;
use chrono::TimeZone;
#[test]
fn test_received_body() {
let hdrs = r#"from smtp.example.com ([10.83.2.2])
by server with LMTP
id xxxxxxxxx
(envelope-from <gitlab@example.com>)
for <me@example.com>; Tue, 13 Jun 2023 19:01:08 +0000"#
.as_bytes();
assert_eq!(
received_log(hdrs),
Ok((
&b""[..],
ReceivedLog {
date: Some(
FixedOffset::east_opt(0)
.unwrap()
.with_ymd_and_hms(2023, 06, 13, 19, 1, 8)
.unwrap()
),
log: vec![
ReceivedLogToken::Word(Word::Atom(&b"from"[..])),
ReceivedLogToken::Domain(mailbox::Domain::Atoms(vec![
&b"smtp"[..],
&b"example"[..],
&b"com"[..]
])),
ReceivedLogToken::Word(Word::Atom(&b"by"[..])),
ReceivedLogToken::Word(Word::Atom(&b"server"[..])),
ReceivedLogToken::Word(Word::Atom(&b"with"[..])),
ReceivedLogToken::Word(Word::Atom(&b"LMTP"[..])),
ReceivedLogToken::Word(Word::Atom(&b"id"[..])),
ReceivedLogToken::Word(Word::Atom(&b"xxxxxxxxx"[..])),
ReceivedLogToken::Word(Word::Atom(&b"for"[..])),
ReceivedLogToken::Addr(mailbox::AddrSpec {
local_part: mailbox::LocalPart(vec![mailbox::LocalPartToken::Word(
Word::Atom(&b"me"[..])
)]),
domain: mailbox::Domain::Atoms(vec![&b"example"[..], &b"com"[..]]),
})
],
}
))
);
}
}

View file

@ -1,3 +1,104 @@
pub mod error; #![doc = include_str!("../README.md")]
pub mod fragments;
pub mod multipass; /// Parse and represent full emails as "parts" as defined by MIME (RFC 2046)
pub mod part;
/// Parse and represent IMF (Internet Message Format) headers (RFC 822, RFC 5322)
pub mod imf;
/// Parse and represent MIME headers (RFC 2045, RFC 2047)
pub mod mime;
/// MIME and IMF represent headers the same way: module contains their commong logic
pub mod header;
/// Low-level email-specific text-based representation for data
pub mod text;
/// Manipulate buffer of bytes
mod pointers;
use nom::{combinator::into, IResult};
/// Parse a whole email including its (MIME) body
///
/// Returns the parsed content, but also the remaining bytes
/// if the parser stopped before arriving to the end (for example
/// due to a multipart delimiter).
///
/// # Arguments
///
/// * `input` - A buffer of bytes containing your full email
///
/// # Returns
///
/// * `rest` - The rest of the buffer, the part that is not parsed as the email ended before the
/// end of the data
/// * `msg` - The parsed message
///
/// # Examples
///
/// ```
/// let input = br#"Date: 7 Mar 2023 08:00:00 +0200
/// From: deuxfleurs@example.com
/// To: someone_else@example.com
/// Subject: An RFC 822 formatted message
/// MIME-Version: 1.0
/// Content-Type: text/plain; charset=us-ascii
///
/// This is the plain text body of the message. Note the blank line
/// between the header information and the body of the message."#;
///
/// let (_, email) = eml_codec::parse_message(input).unwrap();
/// println!(
/// "{} raw message is:\n{}",
/// email.imf.from[0].to_string(),
/// String::from_utf8_lossy(email.child.as_text().unwrap().body),
/// );
/// ```
pub fn parse_message(input: &[u8]) -> IResult<&[u8], part::composite::Message> {
into(part::composite::message(mime::MIME::<
mime::r#type::DeductibleMessage,
>::default()))(input)
}
/// Only extract the headers of the email that are part of the Internet Message Format spec
///
/// Emails headers contain MIME and IMF (Internet Message Format) headers.
/// Sometimes you only need to know the recipient or the sender of an email,
/// and are not interested in its content. In this case, you only need to parse the IMF
/// fields and can ignore the MIME headers + the body. This is what this function does.
///
/// # Arguments
///
/// * `input` - A buffer of bytes containing either only the headers of your email or your full
/// email (in both cases, the body will be ignored)
///
/// # Returns
///
/// * `rest` - The rest of the buffer, ie. the body of your email as raw bytes
/// * `imf` - The parsed IMF headers of your email
///
/// # Examples
///
/// ```
/// let input = br#"Date: 7 Mar 2023 08:00:00 +0200
/// From: deuxfleurs@example.com
/// To: someone_else@example.com
/// Subject: An RFC 822 formatted message
/// MIME-Version: 1.0
/// Content-Type: text/plain; charset=us-ascii
///
/// This is the plain text body of the message. Note the blank line
/// between the header information and the body of the message."#;
///
/// let (_, imf) = eml_codec::parse_imf(input).unwrap();
/// println!(
/// "{} just sent you an email with subject \"{}\"",
/// imf.from[0].to_string(),
/// imf.subject.unwrap().to_string(),
/// );
/// ```
pub fn parse_imf(input: &[u8]) -> IResult<&[u8], imf::Imf> {
imf::imf(input)
}

151
src/mime/charset.rs Normal file
View file

@ -0,0 +1,151 @@
use encoding_rs::Encoding;
/// Specific implementation of charset
///
/// imf_codec has its own charset list to follow IANA's one.
/// encoding_rs implements a different standard that does not know US_ASCII.
/// using encoding_rs datastructures directly would lead to a loss of information.
/// https://www.iana.org/assignments/character-sets/character-sets.xhtml
#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Default, Clone)]
pub enum EmailCharset {
#[default]
US_ASCII,
ISO_8859_1,
ISO_8859_2,
ISO_8859_3,
ISO_8859_4,
ISO_8859_5,
ISO_8859_6,
ISO_8859_7,
ISO_8859_8,
ISO_8859_9,
ISO_8859_10,
Shift_JIS,
EUC_JP,
ISO_2022_KR,
EUC_KR,
ISO_2022_JP,
ISO_2022_JP_2,
ISO_8859_6_E,
ISO_8859_6_I,
ISO_8859_8_E,
ISO_8859_8_I,
GB2312,
Big5,
KOI8_R,
UTF_8,
Unknown,
}
impl<'a> From<&'a str> for EmailCharset {
fn from(s: &'a str) -> Self {
Self::from(s.as_bytes())
}
}
impl<'a> From<&'a [u8]> for EmailCharset {
fn from(s: &'a [u8]) -> Self {
match s.to_ascii_lowercase().as_slice() {
b"us-ascii" | b"ascii" => EmailCharset::US_ASCII,
b"iso-8859-1" => EmailCharset::ISO_8859_1,
b"iso-8859-2" => EmailCharset::ISO_8859_2,
b"iso-8859-3" => EmailCharset::ISO_8859_3,
b"iso-8859-4" => EmailCharset::ISO_8859_4,
b"iso-8859-5" => EmailCharset::ISO_8859_5,
b"iso-8859-6" => EmailCharset::ISO_8859_6,
b"iso-8859-7" => EmailCharset::ISO_8859_7,
b"iso-8859-8" => EmailCharset::ISO_8859_8,
b"iso-8859-9" => EmailCharset::ISO_8859_9,
b"iso-8859-10" => EmailCharset::ISO_8859_10,
b"shift_jis" => EmailCharset::Shift_JIS,
b"euc-jp" => EmailCharset::EUC_JP,
b"iso-2022-kr" => EmailCharset::ISO_2022_KR,
b"euc-kr" => EmailCharset::EUC_KR,
b"iso-2022-jp" => EmailCharset::ISO_2022_JP,
b"iso-2022-jp-2" => EmailCharset::ISO_2022_JP_2,
b"iso-8859-6-e" => EmailCharset::ISO_8859_6_E,
b"iso-8859-6-i" => EmailCharset::ISO_8859_6_I,
b"iso-8859-8-e" => EmailCharset::ISO_8859_8_E,
b"iso-8859-8-i" => EmailCharset::ISO_8859_8_I,
b"gb2312" => EmailCharset::GB2312,
b"big5" => EmailCharset::Big5,
b"koi8-r" => EmailCharset::KOI8_R,
b"utf-8" | b"utf8" => EmailCharset::UTF_8,
_ => EmailCharset::Unknown,
}
}
}
impl ToString for EmailCharset {
fn to_string(&self) -> String {
self.as_str().into()
}
}
impl EmailCharset {
pub fn as_str(&self) -> &'static str {
use EmailCharset::*;
match self {
US_ASCII => "US-ASCII",
ISO_8859_1 => "ISO-8859-1",
ISO_8859_2 => "ISO-8859-2",
ISO_8859_3 => "ISO-8859-3",
ISO_8859_4 => "ISO-8859-4",
ISO_8859_5 => "ISO-8859-5",
ISO_8859_6 => "ISO-8859-6",
ISO_8859_7 => "ISO-8859-7",
ISO_8859_8 => "ISO-8859-8",
ISO_8859_9 => "ISO-8859-9",
ISO_8859_10 => "ISO-8859-10",
Shift_JIS => "Shift_JIS",
EUC_JP => "EUC-JP",
ISO_2022_KR => "ISO-2022-KR",
EUC_KR => "EUC-KR",
ISO_2022_JP => "ISO-2022-JP",
ISO_2022_JP_2 => "ISO-2022-JP-2",
ISO_8859_6_E => "ISO-8859-6-E",
ISO_8859_6_I => "ISO-8859-6-I",
ISO_8859_8_E => "ISO-8859-8-E",
ISO_8859_8_I => "ISO-8859-8-I",
GB2312 => "GB2312",
Big5 => "Big5",
KOI8_R => "KOI8-R",
UTF_8 => "UTF-8",
Unknown => "UTF-8",
}
}
pub fn as_encoding(&self) -> &'static Encoding {
Encoding::for_label(self.as_str().as_bytes()).unwrap_or(encoding_rs::WINDOWS_1252)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_charset() {
assert_eq!(EmailCharset::from(&b"Us-Ascii"[..]).as_str(), "US-ASCII",);
assert_eq!(
EmailCharset::from(&b"Us-Ascii"[..]).as_encoding(),
encoding_rs::WINDOWS_1252,
);
assert_eq!(
EmailCharset::from(&b"ISO-8859-1"[..]).as_encoding(),
encoding_rs::WINDOWS_1252,
);
assert_eq!(
EmailCharset::from(&b"utf-8"[..]).as_encoding(),
encoding_rs::UTF_8,
);
assert_eq!(
EmailCharset::from(&b"utf8"[..]).as_encoding(),
encoding_rs::UTF_8,
);
}
}

135
src/mime/field.rs Normal file
View file

@ -0,0 +1,135 @@
use nom::combinator::map;
use crate::header;
use crate::imf::identification::{msg_id, MessageID};
use crate::mime::mechanism::{mechanism, Mechanism};
use crate::mime::r#type::{naive_type, NaiveType};
use crate::text::misc_token::{unstructured, Unstructured};
#[derive(Debug, PartialEq)]
pub enum Content<'a> {
Type(NaiveType<'a>),
TransferEncoding(Mechanism<'a>),
ID(MessageID<'a>),
Description(Unstructured<'a>),
}
#[allow(dead_code)]
impl<'a> Content<'a> {
pub fn ctype(&'a self) -> Option<&'a NaiveType<'a>> {
match self {
Content::Type(v) => Some(v),
_ => None,
}
}
pub fn transfer_encoding(&'a self) -> Option<&'a Mechanism<'a>> {
match self {
Content::TransferEncoding(v) => Some(v),
_ => None,
}
}
pub fn id(&'a self) -> Option<&'a MessageID<'a>> {
match self {
Content::ID(v) => Some(v),
_ => None,
}
}
pub fn description(&'a self) -> Option<&'a Unstructured<'a>> {
match self {
Content::Description(v) => Some(v),
_ => None,
}
}
}
impl<'a> TryFrom<&header::Field<'a>> for Content<'a> {
type Error = ();
fn try_from(f: &header::Field<'a>) -> Result<Self, Self::Error> {
let content = match f {
header::Field::Good(header::Kv2(key, value)) => match key
.to_ascii_lowercase()
.as_slice()
{
b"content-type" => map(naive_type, Content::Type)(value),
b"content-transfer-encoding" => map(mechanism, Content::TransferEncoding)(value),
b"content-id" => map(msg_id, Content::ID)(value),
b"content-description" => map(unstructured, Content::Description)(value),
_ => return Err(()),
},
_ => return Err(()),
};
//@TODO check that the full value is parsed, otherwise maybe log an error ?!
content.map(|(_, content)| content).or(Err(()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::header;
//use crate::mime::charset::EmailCharset;
use crate::mime::r#type::*;
use crate::text::misc_token::MIMEWord;
use crate::text::quoted::QuotedString;
/*
#[test]
fn test_content_type() {
let (rest, content) =
content(b"Content-Type: text/plain; charset=UTF-8; format=flowed\r\n").unwrap();
assert_eq!(&b""[..], rest);
if let Content::Type(nt) = content {
assert_eq!(
nt.to_type(),
AnyType::Text(Deductible::Explicit(Text {
charset: Deductible::Explicit(EmailCharset::UTF_8),
subtype: TextSubtype::Plain,
})),
);
} else {
panic!("Expected Content::Type, got {:?}", content);
}
}*/
#[test]
fn test_header() {
let fullmail: &[u8] = r#"Date: Sat, 8 Jul 2023 07:14:29 +0200
From: Grrrnd Zero <grrrndzero@example.org>
To: John Doe <jdoe@machine.example>
Subject: Re: Saying Hello
Message-ID: <NTAxNzA2AC47634Y366BAMTY4ODc5MzQyODY0ODY5@www.grrrndzero.org>
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="b1_e376dc71bafc953c0b0fdeb9983a9956"
Content-Transfer-Encoding: 7bit
This is a multipart message.
"#
.as_bytes();
assert_eq!(
map(header::header_kv, |k| k
.iter()
.flat_map(Content::try_from)
.collect())(fullmail),
Ok((
&b"This is a multipart message.\n\n"[..],
vec![
Content::Type(NaiveType {
main: &b"multipart"[..],
sub: &b"alternative"[..],
params: vec![Parameter {
name: &b"boundary"[..],
value: MIMEWord::Quoted(QuotedString(vec![
&b"b1_e376dc71bafc953c0b0fdeb9983a9956"[..]
])),
}]
}),
Content::TransferEncoding(Mechanism::_7Bit),
],
)),
);
}
}

79
src/mime/mechanism.rs Normal file
View file

@ -0,0 +1,79 @@
use crate::text::whitespace::cfws;
use crate::text::words::mime_atom as token;
use nom::{
branch::alt,
bytes::complete::tag_no_case,
combinator::{map, opt, value},
sequence::delimited,
IResult,
};
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Mechanism<'a> {
#[default]
_7Bit,
_8Bit,
Binary,
QuotedPrintable,
Base64,
Other(&'a [u8]),
}
impl<'a> ToString for Mechanism<'a> {
fn to_string(&self) -> String {
use Mechanism::*;
let buf: &[u8] = match self {
_7Bit => b"7bit",
_8Bit => b"8bit",
Binary => b"binary",
QuotedPrintable => b"quoted-printable",
Base64 => b"base64",
Other(x) => x,
};
String::from_utf8_lossy(buf).to_string()
}
}
pub fn mechanism(input: &[u8]) -> IResult<&[u8], Mechanism> {
use Mechanism::*;
alt((
delimited(
opt(cfws),
alt((
value(_7Bit, tag_no_case("7bit")),
value(_8Bit, tag_no_case("8bit")),
value(Binary, tag_no_case("binary")),
value(QuotedPrintable, tag_no_case("quoted-printable")),
value(Base64, tag_no_case("base64")),
)),
opt(cfws),
),
map(token, Other),
))(input)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mechanism() {
assert_eq!(mechanism(b"7bit"), Ok((&b""[..], Mechanism::_7Bit)),);
assert_eq!(
mechanism(b"(youhou) 8bit"),
Ok((&b""[..], Mechanism::_8Bit)),
);
assert_eq!(
mechanism(b"(blip) bInArY (blip blip)"),
Ok((&b""[..], Mechanism::Binary)),
);
assert_eq!(mechanism(b" base64 "), Ok((&b""[..], Mechanism::Base64)),);
assert_eq!(
mechanism(b" Quoted-Printable "),
Ok((&b""[..], Mechanism::QuotedPrintable)),
);
}
}

149
src/mime/mod.rs Normal file
View file

@ -0,0 +1,149 @@
/// Parsed and represent an email character set
pub mod charset;
/// MIME specific headers
pub mod field;
/// Transfer-Encoding representation
pub mod mechanism;
/// Content-Type representation
pub mod r#type;
use std::fmt;
use std::marker::PhantomData;
use crate::header;
use crate::imf::identification::MessageID;
use crate::mime::field::Content;
use crate::mime::mechanism::Mechanism;
use crate::mime::r#type::{AnyType, NaiveType};
use crate::text::misc_token::Unstructured; //Multipart, Message, Text, Binary};
#[derive(Debug, PartialEq, Clone)]
pub struct MIME<'a, T> {
pub interpreted_type: T,
pub fields: NaiveMIME<'a>,
}
impl<'a> Default for MIME<'a, r#type::DeductibleText> {
fn default() -> Self {
Self {
interpreted_type: r#type::DeductibleText::default(),
fields: NaiveMIME::default(),
}
}
}
impl<'a> Default for MIME<'a, r#type::DeductibleMessage> {
fn default() -> Self {
Self {
interpreted_type: r#type::DeductibleMessage::default(),
fields: NaiveMIME::default(),
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum AnyMIME<'a> {
Mult(MIME<'a, r#type::Multipart>),
Msg(MIME<'a, r#type::DeductibleMessage>),
Txt(MIME<'a, r#type::DeductibleText>),
Bin(MIME<'a, r#type::Binary>),
}
impl<'a> AnyMIME<'a> {
pub fn fields(&self) -> &NaiveMIME<'a> {
match self {
Self::Mult(v) => &v.fields,
Self::Msg(v) => &v.fields,
Self::Txt(v) => &v.fields,
Self::Bin(v) => &v.fields,
}
}
}
impl<'a, T: WithDefaultType> From<AnyMIMEWithDefault<'a, T>> for AnyMIME<'a> {
fn from(a: AnyMIMEWithDefault<'a, T>) -> Self {
a.0
}
}
#[derive(PartialEq, Default, Clone)]
pub struct NaiveMIME<'a> {
pub ctype: Option<NaiveType<'a>>,
pub transfer_encoding: Mechanism<'a>,
pub id: Option<MessageID<'a>>,
pub description: Option<Unstructured<'a>>,
pub kv: Vec<header::Field<'a>>,
pub raw: &'a [u8],
}
impl<'a> fmt::Debug for NaiveMIME<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("NaiveMime")
.field("ctype", &self.ctype)
.field("transfer_encoding", &self.transfer_encoding)
.field("id", &self.id)
.field("description", &self.description)
.field("kv", &self.kv)
.field("raw", &String::from_utf8_lossy(self.raw))
.finish()
}
}
impl<'a> FromIterator<Content<'a>> for NaiveMIME<'a> {
fn from_iter<I: IntoIterator<Item = Content<'a>>>(it: I) -> Self {
it.into_iter()
.fold(NaiveMIME::default(), |mut section, field| {
match field {
Content::Type(v) => section.ctype = Some(v),
Content::TransferEncoding(v) => section.transfer_encoding = v,
Content::ID(v) => section.id = Some(v),
Content::Description(v) => section.description = Some(v),
};
section
})
}
}
impl<'a> NaiveMIME<'a> {
pub fn with_kv(mut self, fields: Vec<header::Field<'a>>) -> Self {
self.kv = fields;
self
}
pub fn with_raw(mut self, raw: &'a [u8]) -> Self {
self.raw = raw;
self
}
pub fn to_interpreted<T: WithDefaultType>(self) -> AnyMIME<'a> {
self.ctype
.as_ref()
.map(|c| c.to_type())
.unwrap_or(T::default_type())
.to_mime(self)
.into()
}
}
pub trait WithDefaultType {
fn default_type() -> AnyType;
}
pub struct WithGenericDefault {}
impl WithDefaultType for WithGenericDefault {
fn default_type() -> AnyType {
AnyType::Text(r#type::DeductibleText::default())
}
}
pub struct WithDigestDefault {}
impl WithDefaultType for WithDigestDefault {
fn default_type() -> AnyType {
AnyType::Message(r#type::DeductibleMessage::default())
}
}
#[derive(Debug, PartialEq)]
pub struct AnyMIMEWithDefault<'a, T: WithDefaultType>(pub AnyMIME<'a>, PhantomData<T>);
impl<'a, T: WithDefaultType> Default for AnyMIMEWithDefault<'a, T> {
fn default() -> Self {
Self(T::default_type().to_mime(NaiveMIME::default()), PhantomData)
}
}

394
src/mime/type.rs Normal file
View file

@ -0,0 +1,394 @@
use nom::{
bytes::complete::tag,
combinator::{map, opt},
multi::many0,
sequence::{preceded, terminated, tuple},
IResult,
};
use std::fmt;
use crate::mime::charset::EmailCharset;
use crate::mime::{AnyMIME, NaiveMIME, MIME};
use crate::text::misc_token::{mime_word, MIMEWord};
use crate::text::words::mime_atom;
// --------- NAIVE TYPE
#[derive(PartialEq, Clone)]
pub struct NaiveType<'a> {
pub main: &'a [u8],
pub sub: &'a [u8],
pub params: Vec<Parameter<'a>>,
}
impl<'a> fmt::Debug for NaiveType<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("mime::NaiveType")
.field("main", &String::from_utf8_lossy(self.main))
.field("sub", &String::from_utf8_lossy(self.sub))
.field("params", &self.params)
.finish()
}
}
impl<'a> NaiveType<'a> {
pub fn to_type(&self) -> AnyType {
self.into()
}
}
pub fn naive_type(input: &[u8]) -> IResult<&[u8], NaiveType> {
map(
tuple((mime_atom, tag("/"), mime_atom, parameter_list)),
|(main, _, sub, params)| NaiveType { main, sub, params },
)(input)
}
#[derive(PartialEq, Clone)]
pub struct Parameter<'a> {
pub name: &'a [u8],
pub value: MIMEWord<'a>,
}
impl<'a> fmt::Debug for Parameter<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("mime::Parameter")
.field("name", &String::from_utf8_lossy(self.name))
.field("value", &self.value)
.finish()
}
}
pub fn parameter(input: &[u8]) -> IResult<&[u8], Parameter> {
map(
tuple((mime_atom, tag(b"="), mime_word)),
|(name, _, value)| Parameter { name, value },
)(input)
}
pub fn parameter_list(input: &[u8]) -> IResult<&[u8], Vec<Parameter>> {
terminated(many0(preceded(tag(";"), parameter)), opt(tag(";")))(input)
}
// MIME TYPES TRANSLATED TO RUST TYPING SYSTEM
#[derive(Debug, PartialEq)]
pub enum AnyType {
// Composite types
Multipart(Multipart),
Message(Deductible<Message>),
// Discrete types
Text(Deductible<Text>),
Binary(Binary),
}
impl<'a> From<&'a NaiveType<'a>> for AnyType {
fn from(nt: &'a NaiveType<'a>) -> Self {
match nt.main.to_ascii_lowercase().as_slice() {
b"multipart" => Multipart::try_from(nt)
.map(Self::Multipart)
.unwrap_or(Self::Text(DeductibleText::default())),
b"message" => Self::Message(DeductibleMessage::Explicit(Message::from(nt))),
b"text" => Self::Text(DeductibleText::Explicit(Text::from(nt))),
_ => Self::Binary(Binary::default()),
}
}
}
impl<'a> AnyType {
pub fn to_mime(self, fields: NaiveMIME<'a>) -> AnyMIME<'a> {
match self {
Self::Multipart(interpreted_type) => AnyMIME::Mult(MIME::<Multipart> {
interpreted_type,
fields,
}),
Self::Message(interpreted_type) => AnyMIME::Msg(MIME::<DeductibleMessage> {
interpreted_type,
fields,
}),
Self::Text(interpreted_type) => AnyMIME::Txt(MIME::<DeductibleText> {
interpreted_type,
fields,
}),
Self::Binary(interpreted_type) => AnyMIME::Bin(MIME::<Binary> {
interpreted_type,
fields,
}),
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum Deductible<T: Default> {
Inferred(T),
Explicit(T),
}
impl<T: Default> Default for Deductible<T> {
fn default() -> Self {
Self::Inferred(T::default())
}
}
// REAL PARTS
#[derive(Debug, PartialEq, Clone)]
pub struct Multipart {
pub subtype: MultipartSubtype,
pub boundary: String,
}
impl Multipart {
pub fn main_type(&self) -> String {
"multipart".into()
}
}
impl<'a> TryFrom<&'a NaiveType<'a>> for Multipart {
type Error = ();
fn try_from(nt: &'a NaiveType<'a>) -> Result<Self, Self::Error> {
nt.params
.iter()
.find(|x| x.name.to_ascii_lowercase().as_slice() == b"boundary")
.map(|boundary| Multipart {
subtype: MultipartSubtype::from(nt),
boundary: boundary.value.to_string(),
})
.ok_or(())
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum MultipartSubtype {
Alternative,
Mixed,
Digest,
Parallel,
Report,
Unknown,
}
impl ToString for MultipartSubtype {
fn to_string(&self) -> String {
match self {
Self::Alternative => "alternative",
Self::Mixed => "mixed",
Self::Digest => "digest",
Self::Parallel => "parallel",
Self::Report => "report",
Self::Unknown => "mixed",
}
.into()
}
}
impl<'a> From<&NaiveType<'a>> for MultipartSubtype {
fn from(nt: &NaiveType<'a>) -> Self {
match nt.sub.to_ascii_lowercase().as_slice() {
b"alternative" => Self::Alternative,
b"mixed" => Self::Mixed,
b"digest" => Self::Digest,
b"parallel" => Self::Parallel,
b"report" => Self::Report,
_ => Self::Unknown,
}
}
}
#[derive(Debug, PartialEq, Default, Clone)]
pub enum MessageSubtype {
#[default]
RFC822,
Partial,
External,
Unknown,
}
impl ToString for MessageSubtype {
fn to_string(&self) -> String {
match self {
Self::RFC822 => "rfc822",
Self::Partial => "partial",
Self::External => "external",
Self::Unknown => "rfc822",
}
.into()
}
}
pub type DeductibleMessage = Deductible<Message>;
#[derive(Debug, PartialEq, Default, Clone)]
pub struct Message {
pub subtype: MessageSubtype,
}
impl<'a> From<&NaiveType<'a>> for Message {
fn from(nt: &NaiveType<'a>) -> Self {
match nt.sub.to_ascii_lowercase().as_slice() {
b"rfc822" => Self {
subtype: MessageSubtype::RFC822,
},
b"partial" => Self {
subtype: MessageSubtype::Partial,
},
b"external" => Self {
subtype: MessageSubtype::External,
},
_ => Self {
subtype: MessageSubtype::Unknown,
},
}
}
}
impl From<Deductible<Message>> for Message {
fn from(d: Deductible<Message>) -> Self {
match d {
Deductible::Inferred(t) | Deductible::Explicit(t) => t,
}
}
}
pub type DeductibleText = Deductible<Text>;
#[derive(Debug, PartialEq, Default, Clone)]
pub struct Text {
pub subtype: TextSubtype,
pub charset: Deductible<EmailCharset>,
}
impl<'a> From<&NaiveType<'a>> for Text {
fn from(nt: &NaiveType<'a>) -> Self {
Self {
subtype: TextSubtype::from(nt),
charset: nt
.params
.iter()
.find(|x| x.name.to_ascii_lowercase().as_slice() == b"charset")
.map(|x| Deductible::Explicit(EmailCharset::from(x.value.to_string().as_bytes())))
.unwrap_or(Deductible::Inferred(EmailCharset::US_ASCII)),
}
}
}
impl From<Deductible<Text>> for Text {
fn from(d: Deductible<Text>) -> Self {
match d {
Deductible::Inferred(t) | Deductible::Explicit(t) => t,
}
}
}
#[derive(Debug, PartialEq, Default, Clone)]
pub enum TextSubtype {
#[default]
Plain,
Html,
Unknown,
}
impl ToString for TextSubtype {
fn to_string(&self) -> String {
match self {
Self::Plain | Self::Unknown => "plain",
Self::Html => "html",
}
.into()
}
}
impl<'a> From<&NaiveType<'a>> for TextSubtype {
fn from(nt: &NaiveType<'a>) -> Self {
match nt.sub.to_ascii_lowercase().as_slice() {
b"plain" => Self::Plain,
b"html" => Self::Html,
_ => Self::Unknown,
}
}
}
#[derive(Debug, PartialEq, Default, Clone)]
pub struct Binary {}
#[cfg(test)]
mod tests {
use super::*;
use crate::mime::charset::EmailCharset;
use crate::mime::r#type::Deductible;
use crate::text::quoted::QuotedString;
#[test]
fn test_parameter() {
assert_eq!(
parameter(b"charset=utf-8"),
Ok((
&b""[..],
Parameter {
name: &b"charset"[..],
value: MIMEWord::Atom(&b"utf-8"[..]),
}
)),
);
assert_eq!(
parameter(b"charset=\"utf-8\""),
Ok((
&b""[..],
Parameter {
name: &b"charset"[..],
value: MIMEWord::Quoted(QuotedString(vec![&b"utf-8"[..]])),
}
)),
);
}
#[test]
fn test_content_type_plaintext() {
let (rest, nt) = naive_type(b"text/plain;\r\n charset=utf-8").unwrap();
assert_eq!(rest, &b""[..]);
assert_eq!(
nt.to_type(),
AnyType::Text(Deductible::Explicit(Text {
charset: Deductible::Explicit(EmailCharset::UTF_8),
subtype: TextSubtype::Plain,
}))
);
}
#[test]
fn test_content_type_multipart() {
let (rest, nt) = naive_type(b"multipart/mixed;\r\n\tboundary=\"--==_mimepart_64a3f2c69114f_2a13d020975fe\";\r\n\tcharset=UTF-8").unwrap();
assert_eq!(rest, &[]);
assert_eq!(
nt.to_type(),
AnyType::Multipart(Multipart {
subtype: MultipartSubtype::Mixed,
boundary: "--==_mimepart_64a3f2c69114f_2a13d020975fe".into(),
})
);
}
#[test]
fn test_content_type_message() {
let (rest, nt) = naive_type(b"message/rfc822").unwrap();
assert_eq!(rest, &[]);
assert_eq!(
nt.to_type(),
AnyType::Message(Deductible::Explicit(Message {
subtype: MessageSubtype::RFC822
}))
);
}
#[test]
fn test_parameter_ascii() {
assert_eq!(
parameter(b"charset = (simple) us-ascii (Plain text)"),
Ok((
&b""[..],
Parameter {
name: &b"charset"[..],
value: MIMEWord::Atom(&b"us-ascii"[..]),
}
))
);
}
#[test]
fn test_parameter_terminated_with_semi_colon() {
assert_eq!(
parameter_list(b";boundary=\"festivus\";"),
Ok((
&b""[..],
vec![Parameter {
name: &b"boundary"[..],
value: MIMEWord::Quoted(QuotedString(vec![&b"festivus"[..]])),
}],
))
);
}
}

View file

@ -1,66 +0,0 @@
use std::borrow::Cow;
use nom::{
IResult,
character::complete::space1,
bytes::complete::is_not,
combinator::{all_consuming, recognize},
multi::{fold_many0, many0, many1},
sequence::{pair, tuple},
};
use crate::multipass::guess_charset::GuessCharset;
use crate::error::IMFError;
use crate::fragments::whitespace;
#[derive(Debug, PartialEq)]
pub struct ExtractFields<'a> {
pub fields: Vec<&'a str>,
pub body: &'a [u8],
}
impl<'a> TryFrom<&'a GuessCharset<'a>> for ExtractFields<'a> {
type Error = IMFError<'a>;
fn try_from(gcha: &'a GuessCharset<'a>) -> Result<Self, Self::Error> {
all_consuming(many0(foldable_line))(&gcha.header)
.map_err(|e| IMFError::ExtractFields(e))
.map(|(_, fields)| ExtractFields { fields, body: gcha.body })
}
}
/// ```abnf
/// fold_line = any *(1*(crlf WS) any) crlf
/// ```
fn foldable_line(input: &str) -> IResult<&str, &str> {
recognize(tuple((
is_not("\r\n"),
many0(pair(
many1(pair(whitespace::perm_crlf, space1)),
is_not("\r\n"))),
whitespace::perm_crlf
)))(input)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_extract() {
assert_eq!(
ExtractFields::try_from(&GuessCharset {
header: "From: hello@world.com,\r\n\talice@wonderlands.com\r\nDate: 12 Mar 1997 07:33:25 Z\r\n".into(),
encoding: encoding_rs::UTF_8,
malformed: false,
body: b"Hello world!",
}),
Ok(ExtractFields {
fields: vec![
"From: hello@world.com,\r\n\talice@wonderlands.com\r\n",
"Date: 12 Mar 1997 07:33:25 Z\r\n",
],
body: b"Hello world!",
})
);
}
}

View file

@ -1,51 +0,0 @@
use std::borrow::Cow;
use chardetng::EncodingDetector;
use encoding_rs::Encoding;
use crate::multipass::segment::Segment;
#[derive(Debug, PartialEq)]
pub struct GuessCharset<'a> {
pub header: Cow<'a, str>,
pub encoding: &'static Encoding,
pub malformed: bool,
pub body: &'a [u8],
}
const IS_LAST_BUFFER: bool = true;
const ALLOW_UTF8: bool = true;
const NO_TLD: Option<&[u8]> = None;
impl<'a> From<&'a Segment<'a>> for GuessCharset<'a> {
fn from(seg: &'a Segment<'a>) -> Self {
// Create detector
let mut detector = EncodingDetector::new();
detector.feed(&seg.header, IS_LAST_BUFFER);
// Get encoding
let enc: &Encoding = detector.guess(NO_TLD, ALLOW_UTF8);
let (header, encoding, malformed) = enc.decode(&seg.header);
GuessCharset { header, encoding, malformed, body: seg.body }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_charset() {
assert_eq!(
GuessCharset::from(&Segment {
body: b"Hello world!",
header: b"From: hello@world.com\r\nDate: 12 Mar 1997 07:33:25 Z\r\n",
}),
GuessCharset {
header: "From: hello@world.com\r\nDate: 12 Mar 1997 07:33:25 Z\r\n".into(),
encoding: encoding_rs::UTF_8,
malformed: false,
body: b"Hello world!",
});
}
}

View file

@ -1,3 +0,0 @@
pub mod segment;
pub mod guess_charset;
pub mod extract_fields;

View file

@ -1,61 +0,0 @@
use std::convert::TryFrom;
use nom::{
IResult,
branch::alt,
bytes::complete::{is_not, tag},
combinator::recognize,
sequence::{pair, terminated},
multi::many0,
};
use crate::error::IMFError;
#[derive(Debug, PartialEq)]
pub struct Segment<'a> {
pub header: &'a [u8],
pub body: &'a [u8],
}
const cr: u8 = 0x0D;
const lf: u8 = 0x0A;
const crlf: &[u8] = &[cr, lf];
impl<'a> TryFrom<&'a [u8]> for Segment<'a> {
type Error = IMFError<'a>;
fn try_from(buffer: &'a [u8]) -> Result<Self, Self::Error> {
terminated(
recognize(many0(line)),
obs_crlf
)(buffer)
.map_err(|e| IMFError::Segment(e))
.map(|(body, header)| Segment { header, body })
}
}
fn line(input: &[u8]) -> IResult<&[u8], (&[u8], &[u8])> {
pair(
is_not(crlf),
obs_crlf,
)(input)
}
fn obs_crlf(input: &[u8]) -> IResult<&[u8], &[u8]> {
alt((tag(crlf), tag(&[cr]), tag(&[lf])))(input)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_segment() {
assert_eq!(
Segment::try_from(&b"From: hello@world.com\r\nDate: 12 Mar 1997 07:33:25 Z\r\n\r\nHello world!"[..]),
Ok(Segment {
body: b"Hello world!",
header: b"From: hello@world.com\r\nDate: 12 Mar 1997 07:33:25 Z\r\n",
})
);
}
}

View file

@ -1,22 +1,15 @@
use imf_codec::fragments::header; //use imf_codec::fragments::section::Section;
//use imf_codec::multipass::segment;
use std::io; use std::io;
use std::io::Read; use std::io::Read;
fn main() { fn main() {
// Read full mail in memory // Read full mail in memory
let mut rawmail = Vec::new(); let mut rawmail = Vec::new();
io::stdin().lock().read_to_end(&mut rawmail).unwrap(); io::stdin().lock().read_to_end(&mut rawmail).unwrap();
// Parse it let (_, eml) = eml_codec::parse_message(&rawmail).unwrap();
let (email, encoding, malformed) = header::from_bytes(&rawmail); println!("{:#?}", eml);
println!("Encoding: {:?}, Malformed: {:?}", encoding, malformed); assert!(eml.imf.date.is_some());
assert!(!eml.imf.from.is_empty());
let (input, hdrs) = header::section(&email).unwrap();
// Checks/debug
println!("{:?}", hdrs);
assert!(hdrs.date.is_some());
assert!(hdrs.from.len() > 0);
assert!(hdrs.bad_fields.len() == 0);
} }

617
src/part/composite.rs Normal file
View file

@ -0,0 +1,617 @@
use nom::IResult;
use std::fmt;
use crate::header;
use crate::imf;
use crate::mime;
use crate::part::{self, AnyPart};
use crate::pointers;
use crate::text::boundary::{boundary, Delimiter};
//--- Multipart
#[derive(PartialEq)]
pub struct Multipart<'a> {
pub mime: mime::MIME<'a, mime::r#type::Multipart>,
pub children: Vec<AnyPart<'a>>,
pub raw_part_inner: &'a [u8],
pub raw_part_outer: &'a [u8],
}
impl<'a> fmt::Debug for Multipart<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("part::Multipart")
.field("mime", &self.mime)
.field("children", &self.children)
.field(
"raw_part_inner",
&String::from_utf8_lossy(self.raw_part_inner),
)
.field(
"raw_part_outer",
&String::from_utf8_lossy(self.raw_part_outer),
)
.finish()
}
}
impl<'a> Multipart<'a> {
pub fn preamble(&self) -> &'a [u8] {
pointers::parsed(self.raw_part_outer, self.raw_part_inner)
}
pub fn epilogue(&self) -> &'a [u8] {
pointers::rest(self.raw_part_outer, self.raw_part_inner)
}
pub fn preamble_and_body(&self) -> &'a [u8] {
pointers::with_preamble(self.raw_part_outer, self.raw_part_inner)
}
pub fn body_and_epilogue(&self) -> &'a [u8] {
pointers::with_epilogue(self.raw_part_outer, self.raw_part_inner)
}
}
pub fn multipart<'a>(
m: mime::MIME<'a, mime::r#type::Multipart>,
) -> impl Fn(&'a [u8]) -> IResult<&'a [u8], Multipart<'a>> {
let m = m.clone();
move |input| {
// init
let outer_orig = input;
let bound = m.interpreted_type.boundary.as_bytes();
let mut mparts: Vec<AnyPart> = vec![];
// skip preamble
let (mut input_loop, _) = part::part_raw(bound)(input)?;
let inner_orig = input_loop;
loop {
let input = match boundary(bound)(input_loop) {
Err(_) => {
return Ok((
input_loop,
Multipart {
mime: m.clone(),
children: mparts,
raw_part_inner: pointers::parsed(inner_orig, input_loop),
raw_part_outer: pointers::parsed(outer_orig, input_loop),
},
))
}
Ok((inp, Delimiter::Last)) => {
return Ok((
inp,
Multipart {
mime: m.clone(),
children: mparts,
raw_part_inner: pointers::parsed(inner_orig, inp),
raw_part_outer: pointers::parsed(
outer_orig,
&outer_orig[outer_orig.len()..],
),
},
))
}
Ok((inp, Delimiter::Next)) => inp,
};
// parse mime headers, otherwise pick default mime
let (input, naive_mime) = match header::header_kv(input) {
Ok((input_eom, fields)) => {
let raw_hdrs = pointers::parsed(input, input_eom);
let mime = fields
.iter()
.flat_map(mime::field::Content::try_from)
.into_iter()
.collect::<mime::NaiveMIME>();
let mime = mime.with_kv(fields).with_raw(raw_hdrs);
(input_eom, mime)
}
Err(_) => (input, mime::NaiveMIME::default()),
};
// interpret mime according to context
let mime = match m.interpreted_type.subtype {
mime::r#type::MultipartSubtype::Digest => naive_mime
.to_interpreted::<mime::WithDigestDefault>()
.into(),
_ => naive_mime
.to_interpreted::<mime::WithGenericDefault>()
.into(),
};
// parse raw part
let (input, rpart) = part::part_raw(bound)(input)?;
// parse mime body
// -- we do not keep the input as we are using the
// part_raw function as our cursor here.
let (_, part) = part::anypart(mime)(rpart)?;
mparts.push(part);
input_loop = input;
}
}
}
//--- Message
#[derive(PartialEq)]
pub struct Message<'a> {
pub mime: mime::MIME<'a, mime::r#type::DeductibleMessage>,
pub imf: imf::Imf<'a>,
pub child: Box<AnyPart<'a>>,
pub raw_part: &'a [u8],
pub raw_headers: &'a [u8],
pub raw_body: &'a [u8],
}
impl<'a> fmt::Debug for Message<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("part::Message")
.field("mime", &self.mime)
.field("imf", &self.imf)
.field("child", &self.child)
.field("raw_part", &String::from_utf8_lossy(self.raw_part))
.field("raw_headers", &String::from_utf8_lossy(self.raw_headers))
.field("raw_body", &String::from_utf8_lossy(self.raw_body))
.finish()
}
}
pub fn message<'a>(
m: mime::MIME<'a, mime::r#type::DeductibleMessage>,
) -> impl Fn(&'a [u8]) -> IResult<&'a [u8], Message<'a>> {
move |input: &[u8]| {
let orig = input;
// parse header fields
let (input, headers) = header::header_kv(input)?;
// extract raw parts 1/2
let raw_headers = pointers::parsed(orig, input);
let body_orig = input;
//---------------
// aggregate header fields
let (naive_mime, imf) = part::field::split_and_build(&headers);
// Bind headers to mime
let naive_mime = naive_mime.with_kv(headers);
// interpret headers to choose the child mime type
let in_mime = naive_mime
.with_raw(raw_headers)
.to_interpreted::<mime::WithGenericDefault>()
.into();
//---------------
// parse a part following this mime specification
let (input, part) = part::anypart(in_mime)(input)?;
// extract raw parts 2/2
let raw_body = pointers::parsed(body_orig, input);
let raw_part = pointers::parsed(orig, input);
Ok((
input,
Message {
mime: m.clone(),
imf,
raw_part,
raw_headers,
raw_body,
child: Box::new(part),
},
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::part::discrete::Text;
use crate::part::AnyPart;
use crate::text::encoding::{Base64Word, EncodedWord, QuotedChunk, QuotedWord};
use crate::text::misc_token::{MIMEWord, Phrase, UnstrToken, Unstructured, Word};
use crate::text::quoted::QuotedString;
use chrono::{FixedOffset, TimeZone};
#[test]
fn test_multipart() {
let base_mime = mime::MIME {
interpreted_type: mime::r#type::Multipart {
subtype: mime::r#type::MultipartSubtype::Alternative,
boundary: "simple boundary".to_string(),
},
fields: mime::NaiveMIME::default(),
};
let input = b"This is the preamble. It is to be ignored, though it
is a handy place for composition agents to include an
explanatory note to non-MIME conformant readers.
--simple boundary
This is implicitly typed plain US-ASCII text.
It does NOT end with a linebreak.
--simple boundary
Content-type: text/plain; charset=us-ascii
This is explicitly typed plain US-ASCII text.
It DOES end with a linebreak.
--simple boundary--
This is the epilogue. It is also to be ignored.
";
let inner = b"
--simple boundary
This is implicitly typed plain US-ASCII text.
It does NOT end with a linebreak.
--simple boundary
Content-type: text/plain; charset=us-ascii
This is explicitly typed plain US-ASCII text.
It DOES end with a linebreak.
--simple boundary--
";
assert_eq!(
multipart(base_mime.clone())(input),
Ok((&b"\nThis is the epilogue. It is also to be ignored.\n"[..],
Multipart {
mime: base_mime,
raw_part_outer: input,
raw_part_inner: inner,
children: vec![
AnyPart::Txt(Text {
mime: mime::MIME {
interpreted_type: mime::r#type::Deductible::Inferred(mime::r#type::Text {
subtype: mime::r#type::TextSubtype::Plain,
charset: mime::r#type::Deductible::Inferred(mime::charset::EmailCharset::US_ASCII),
}),
fields: mime::NaiveMIME {
raw: &b"\n"[..],
..mime::NaiveMIME::default()
},
},
body: &b"This is implicitly typed plain US-ASCII text.\nIt does NOT end with a linebreak."[..],
}),
AnyPart::Txt(Text {
mime: mime::MIME {
interpreted_type: mime::r#type::Deductible::Explicit(mime::r#type::Text {
subtype: mime::r#type::TextSubtype::Plain,
charset: mime::r#type::Deductible::Explicit(mime::charset::EmailCharset::US_ASCII),
}),
fields: mime::NaiveMIME {
ctype: Some(mime::r#type::NaiveType {
main: &b"text"[..],
sub: &b"plain"[..],
params: vec![
mime::r#type::Parameter {
name: &b"charset"[..],
value: MIMEWord::Atom(&b"us-ascii"[..]),
}
]
}),
raw: &b"Content-type: text/plain; charset=us-ascii\n\n"[..],
kv: vec![
header::Field::Good(header::Kv2(&b"Content-type"[..], &b"text/plain; charset=us-ascii"[..]))
],
..mime::NaiveMIME::default()
},
},
body: &b"This is explicitly typed plain US-ASCII text.\nIt DOES end with a linebreak.\n"[..],
}),
],
},
))
);
}
#[test]
fn test_message() {
let fullmail: &[u8] = r#"Date: Sat, 8 Jul 2023 07:14:29 +0200
From: Grrrnd Zero <grrrndzero@example.org>
To: John Doe <jdoe@machine.example>
CC: =?ISO-8859-1?Q?Andr=E9?= Pirard <PIRARD@vm1.ulg.ac.be>
Subject: =?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=
=?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=
X-Unknown: something something
Bad entry
on multiple lines
Message-ID: <NTAxNzA2AC47634Y366BAMTY4ODc5MzQyODY0ODY5@www.grrrndzero.org>
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="b1_e376dc71bafc953c0b0fdeb9983a9956"
Content-Transfer-Encoding: 7bit
This is a multi-part message in MIME format.
--b1_e376dc71bafc953c0b0fdeb9983a9956
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
GZ
OoOoO
oOoOoOoOo
oOoOoOoOoOoOoOoOo
oOoOoOoOoOoOoOoOoOoOoOo
oOoOoOoOoOoOoOoOoOoOoOoOoOoOo
OoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO
--b1_e376dc71bafc953c0b0fdeb9983a9956
Content-Type: text/html; charset=us-ascii
<div style="text-align: center;"><strong>GZ</strong><br />
OoOoO<br />
oOoOoOoOo<br />
oOoOoOoOoOoOoOoOo<br />
oOoOoOoOoOoOoOoOoOoOoOo<br />
oOoOoOoOoOoOoOoOoOoOoOoOoOoOo<br />
OoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO<br />
</div>
--b1_e376dc71bafc953c0b0fdeb9983a9956--
"#
.as_bytes();
let hdrs = br#"Date: Sat, 8 Jul 2023 07:14:29 +0200
From: Grrrnd Zero <grrrndzero@example.org>
To: John Doe <jdoe@machine.example>
CC: =?ISO-8859-1?Q?Andr=E9?= Pirard <PIRARD@vm1.ulg.ac.be>
Subject: =?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=
=?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=
X-Unknown: something something
Bad entry
on multiple lines
Message-ID: <NTAxNzA2AC47634Y366BAMTY4ODc5MzQyODY0ODY5@www.grrrndzero.org>
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="b1_e376dc71bafc953c0b0fdeb9983a9956"
Content-Transfer-Encoding: 7bit
"#;
let body = br#"This is a multi-part message in MIME format.
--b1_e376dc71bafc953c0b0fdeb9983a9956
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
GZ
OoOoO
oOoOoOoOo
oOoOoOoOoOoOoOoOo
oOoOoOoOoOoOoOoOoOoOoOo
oOoOoOoOoOoOoOoOoOoOoOoOoOoOo
OoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO
--b1_e376dc71bafc953c0b0fdeb9983a9956
Content-Type: text/html; charset=us-ascii
<div style="text-align: center;"><strong>GZ</strong><br />
OoOoO<br />
oOoOoOoOo<br />
oOoOoOoOoOoOoOoOo<br />
oOoOoOoOoOoOoOoOoOoOoOo<br />
oOoOoOoOoOoOoOoOoOoOoOoOoOoOo<br />
OoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO<br />
</div>
--b1_e376dc71bafc953c0b0fdeb9983a9956--
"#;
let inner = br#"
--b1_e376dc71bafc953c0b0fdeb9983a9956
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
GZ
OoOoO
oOoOoOoOo
oOoOoOoOoOoOoOoOo
oOoOoOoOoOoOoOoOoOoOoOo
oOoOoOoOoOoOoOoOoOoOoOoOoOoOo
OoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO
--b1_e376dc71bafc953c0b0fdeb9983a9956
Content-Type: text/html; charset=us-ascii
<div style="text-align: center;"><strong>GZ</strong><br />
OoOoO<br />
oOoOoOoOo<br />
oOoOoOoOoOoOoOoOo<br />
oOoOoOoOoOoOoOoOoOoOoOo<br />
oOoOoOoOoOoOoOoOoOoOoOoOoOoOo<br />
OoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO<br />
</div>
--b1_e376dc71bafc953c0b0fdeb9983a9956--
"#;
let base_mime = mime::MIME::<mime::r#type::DeductibleMessage>::default();
assert_eq!(
message(base_mime.clone())(fullmail),
Ok((
&[][..],
Message {
mime: base_mime,
raw_part: fullmail,
raw_headers: hdrs,
raw_body: body,
imf: imf::Imf {
date: Some(FixedOffset::east_opt(2 * 3600)
.unwrap()
.with_ymd_and_hms(2023, 07, 8, 7, 14, 29)
.unwrap()),
from: vec![
imf::mailbox::MailboxRef {
name: Some(Phrase(vec![Word::Atom(&b"Grrrnd"[..]), Word::Atom(&b"Zero"[..])])),
addrspec: imf::mailbox::AddrSpec {
local_part: imf::mailbox::LocalPart(vec![
imf::mailbox::LocalPartToken::Word(Word::Atom(&b"grrrndzero"[..]))
]),
domain: imf::mailbox::Domain::Atoms(vec![&b"example"[..], &b"org"[..]]),
}
},
],
to: vec![imf::address::AddressRef::Single(imf::mailbox::MailboxRef {
name: Some(Phrase(vec![Word::Atom(&b"John"[..]), Word::Atom(&b"Doe"[..])])),
addrspec: imf::mailbox::AddrSpec {
local_part: imf::mailbox::LocalPart(vec![
imf::mailbox::LocalPartToken::Word(Word::Atom(&b"jdoe"[..]))
]),
domain: imf::mailbox::Domain::Atoms(vec![&b"machine"[..], &b"example"[..]]),
}
})],
cc: vec![imf::address::AddressRef::Single(imf::mailbox::MailboxRef {
name: Some(Phrase(vec![
Word::Encoded(EncodedWord::Quoted(QuotedWord {
enc: encoding_rs::WINDOWS_1252,
chunks: vec![
QuotedChunk::Safe(&b"Andr"[..]),
QuotedChunk::Encoded(vec![0xE9]),
],
})),
Word::Atom(&b"Pirard"[..])
])),
addrspec: imf::mailbox::AddrSpec {
local_part: imf::mailbox::LocalPart(vec![
imf::mailbox::LocalPartToken::Word(Word::Atom(&b"PIRARD"[..]))
]),
domain: imf::mailbox::Domain::Atoms(vec![
&b"vm1"[..], &b"ulg"[..], &b"ac"[..], &b"be"[..],
]),
}
})],
subject: Some(Unstructured(vec![
UnstrToken::Encoded(EncodedWord::Base64(Base64Word{
enc: encoding_rs::WINDOWS_1252,
content: &b"SWYgeW91IGNhbiByZWFkIHRoaXMgeW8"[..],
})),
UnstrToken::Encoded(EncodedWord::Base64(Base64Word{
enc: encoding_rs::ISO_8859_2,
content: &b"dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg"[..],
})),
])),
msg_id: Some(imf::identification::MessageID {
left: &b"NTAxNzA2AC47634Y366BAMTY4ODc5MzQyODY0ODY5"[..],
right: &b"www.grrrndzero.org"[..],
}),
mime_version: Some(imf::mime::Version { major: 1, minor: 0}),
..imf::Imf::default()
},
child: Box::new(AnyPart::Mult(Multipart {
mime: mime::MIME {
interpreted_type: mime::r#type::Multipart {
subtype: mime::r#type::MultipartSubtype::Alternative,
boundary: "b1_e376dc71bafc953c0b0fdeb9983a9956".to_string(),
},
fields: mime::NaiveMIME {
ctype: Some(mime::r#type::NaiveType {
main: &b"multipart"[..],
sub: &b"alternative"[..],
params: vec![
mime::r#type::Parameter {
name: &b"boundary"[..],
value: MIMEWord::Quoted(QuotedString(vec![&b"b1_e376dc71bafc953c0b0fdeb9983a9956"[..]])),
}
]
}),
raw: hdrs,
kv: vec![
header::Field::Good(header::Kv2(&b"Date"[..], &b"Sat, 8 Jul 2023 07:14:29 +0200"[..])),
header::Field::Good(header::Kv2(&b"From"[..], &b"Grrrnd Zero <grrrndzero@example.org>"[..])),
header::Field::Good(header::Kv2(&b"To"[..], &b"John Doe <jdoe@machine.example>"[..])),
header::Field::Good(header::Kv2(&b"CC"[..], &b"=?ISO-8859-1?Q?Andr=E9?= Pirard <PIRARD@vm1.ulg.ac.be>"[..])),
header::Field::Good(header::Kv2(&b"Subject"[..], &b"=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=\n =?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?="[..])),
header::Field::Good(header::Kv2(&b"X-Unknown"[..], &b"something something"[..])),
header::Field::Bad(&b"Bad entry\n on multiple lines\n"[..]),
header::Field::Good(header::Kv2(&b"Message-ID"[..], &b"<NTAxNzA2AC47634Y366BAMTY4ODc5MzQyODY0ODY5@www.grrrndzero.org>"[..])),
header::Field::Good(header::Kv2(&b"MIME-Version"[..], &b"1.0"[..])),
header::Field::Good(header::Kv2(&b"Content-Type"[..], &b"multipart/alternative;\n boundary=\"b1_e376dc71bafc953c0b0fdeb9983a9956\""[..])),
header::Field::Good(header::Kv2(&b"Content-Transfer-Encoding"[..], &b"7bit"[..])),
],
..mime::NaiveMIME::default()
},
},
raw_part_inner: inner,
raw_part_outer: body,
children: vec![
AnyPart::Txt(Text {
mime: mime::MIME {
interpreted_type: mime::r#type::Deductible::Explicit(mime::r#type::Text {
subtype: mime::r#type::TextSubtype::Plain,
charset: mime::r#type::Deductible::Explicit(mime::charset::EmailCharset::UTF_8),
}),
fields: mime::NaiveMIME {
ctype: Some(mime::r#type::NaiveType {
main: &b"text"[..],
sub: &b"plain"[..],
params: vec![
mime::r#type::Parameter {
name: &b"charset"[..],
value: MIMEWord::Atom(&b"utf-8"[..]),
}
]
}),
transfer_encoding: mime::mechanism::Mechanism::QuotedPrintable,
kv: vec![
header::Field::Good(header::Kv2(&b"Content-Type"[..], &b"text/plain; charset=utf-8"[..])),
header::Field::Good(header::Kv2(&b"Content-Transfer-Encoding"[..], &b"quoted-printable"[..])),
],
raw: &b"Content-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: quoted-printable\n\n"[..],
..mime::NaiveMIME::default()
}
},
body: &b"GZ\nOoOoO\noOoOoOoOo\noOoOoOoOoOoOoOoOo\noOoOoOoOoOoOoOoOoOoOoOo\noOoOoOoOoOoOoOoOoOoOoOoOoOoOo\nOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO\n"[..],
}),
AnyPart::Txt(Text {
mime: mime::MIME {
interpreted_type: mime::r#type::Deductible::Explicit(mime::r#type::Text {
subtype: mime::r#type::TextSubtype::Html,
charset: mime::r#type::Deductible::Explicit(mime::charset::EmailCharset::US_ASCII),
}),
fields: mime::NaiveMIME {
ctype: Some(mime::r#type::NaiveType {
main: &b"text"[..],
sub: &b"html"[..],
params: vec![
mime::r#type::Parameter {
name: &b"charset"[..],
value: MIMEWord::Atom(&b"us-ascii"[..]),
}
]
}),
kv: vec![
header::Field::Good(header::Kv2(&b"Content-Type"[..], &b"text/html; charset=us-ascii"[..])),
],
raw: &b"Content-Type: text/html; charset=us-ascii\n\n"[..],
..mime::NaiveMIME::default()
},
},
body: &br#"<div style="text-align: center;"><strong>GZ</strong><br />
OoOoO<br />
oOoOoOoOo<br />
oOoOoOoOoOoOoOoOo<br />
oOoOoOoOoOoOoOoOoOoOoOo<br />
oOoOoOoOoOoOoOoOoOoOoOoOoOoOo<br />
OoOoOoOoOoOoOoOoOoOoOoOoOoOoOoOoO<br />
</div>
"#[..],
}),
],
})),
},
))
);
}
}

33
src/part/discrete.rs Normal file
View file

@ -0,0 +1,33 @@
use std::fmt;
use crate::mime;
#[derive(PartialEq)]
pub struct Text<'a> {
pub mime: mime::MIME<'a, mime::r#type::DeductibleText>,
pub body: &'a [u8],
}
impl<'a> fmt::Debug for Text<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("part::Text")
.field("mime", &self.mime)
.field("body", &String::from_utf8_lossy(self.body))
.finish()
}
}
#[derive(PartialEq)]
pub struct Binary<'a> {
pub mime: mime::MIME<'a, mime::r#type::Binary>,
pub body: &'a [u8],
}
impl<'a> fmt::Debug for Binary<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("part::Binary")
.field("mime", &self.mime)
.field("body", &String::from_utf8_lossy(self.body))
.finish()
}
}

24
src/part/field.rs Normal file
View file

@ -0,0 +1,24 @@
use crate::header;
use crate::imf;
use crate::mime;
pub fn split_and_build<'a>(v: &Vec<header::Field<'a>>) -> (mime::NaiveMIME<'a>, imf::Imf<'a>) {
let (mimev, imfv) = v.iter().fold(
(
Vec::<mime::field::Content>::new(),
Vec::<imf::field::Field>::new(),
),
|(mut mime, mut imf), f| {
if let Ok(m) = mime::field::Content::try_from(f) {
mime.push(m);
} else if let Ok(i) = imf::field::Field::try_from(f) {
imf.push(i);
}
(mime, imf)
},
);
let fmime = mimev.into_iter().collect::<mime::NaiveMIME>();
let fimf = imfv.into_iter().collect::<imf::Imf>();
(fmime, fimf)
}

171
src/part/mod.rs Normal file
View file

@ -0,0 +1,171 @@
/// Parts that contain other parts inside them
pub mod composite;
/// Parts that have a body and no child parts
pub mod discrete;
/// IMF + MIME fields parsed at once
pub mod field;
use nom::{
branch::alt,
bytes::complete::is_not,
combinator::{not, recognize},
multi::many0,
sequence::pair,
IResult,
};
use crate::mime;
use crate::mime::{AnyMIME, NaiveMIME};
use crate::part::{
composite::{message, multipart, Message, Multipart},
discrete::{Binary, Text},
};
use crate::text::ascii::CRLF;
use crate::text::boundary::boundary;
use crate::text::whitespace::obs_crlf;
#[derive(Debug, PartialEq)]
pub enum AnyPart<'a> {
Mult(Multipart<'a>),
Msg(Message<'a>),
Txt(Text<'a>),
Bin(Binary<'a>),
}
impl<'a> AnyPart<'a> {
pub fn as_multipart(&self) -> Option<&Multipart<'a>> {
match self {
Self::Mult(x) => Some(x),
_ => None,
}
}
pub fn as_message(&self) -> Option<&Message<'a>> {
match self {
Self::Msg(x) => Some(x),
_ => None,
}
}
pub fn as_text(&self) -> Option<&Text<'a>> {
match self {
Self::Txt(x) => Some(x),
_ => None,
}
}
pub fn as_binary(&self) -> Option<&Binary<'a>> {
match self {
Self::Bin(x) => Some(x),
_ => None,
}
}
pub fn mime(&self) -> &NaiveMIME<'a> {
match self {
Self::Mult(v) => &v.mime.fields,
Self::Msg(v) => &v.mime.fields,
Self::Txt(v) => &v.mime.fields,
Self::Bin(v) => &v.mime.fields,
}
}
}
impl<'a> From<Multipart<'a>> for AnyPart<'a> {
fn from(m: Multipart<'a>) -> Self {
Self::Mult(m)
}
}
impl<'a> From<Message<'a>> for AnyPart<'a> {
fn from(m: Message<'a>) -> Self {
Self::Msg(m)
}
}
/// Parse any type of part
///
/// ## Note
///
/// Multiparts are a bit special as they have a clearly delimited beginning
/// and end contrary to all the other parts that are going up to the end of the buffer
pub fn anypart<'a>(m: AnyMIME<'a>) -> impl FnOnce(&'a [u8]) -> IResult<&'a [u8], AnyPart<'a>> {
move |input| {
let part = match m {
AnyMIME::Mult(a) => multipart(a)(input)
.map(|(_, multi)| multi.into())
.unwrap_or(AnyPart::Txt(Text {
mime: mime::MIME::<mime::r#type::DeductibleText>::default(),
body: input,
})),
AnyMIME::Msg(a) => {
message(a)(input)
.map(|(_, msg)| msg.into())
.unwrap_or(AnyPart::Txt(Text {
mime: mime::MIME::<mime::r#type::DeductibleText>::default(),
body: input,
}))
}
AnyMIME::Txt(a) => AnyPart::Txt(Text {
mime: a,
body: input,
}),
AnyMIME::Bin(a) => AnyPart::Bin(Binary {
mime: a,
body: input,
}),
};
// This function always consumes the whole input
Ok((&input[input.len()..], part))
}
}
pub fn part_raw<'a>(bound: &[u8]) -> impl Fn(&'a [u8]) -> IResult<&'a [u8], &'a [u8]> + '_ {
move |input| {
recognize(many0(pair(
not(boundary(bound)),
alt((is_not(CRLF), obs_crlf)),
)))(input)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_preamble() {
assert_eq!(
part_raw(b"hello")(
b"blip
bloup
blip
bloup--
--bim
--bim--
--hello
Field: Body
"
),
Ok((
&b"\n--hello\nField: Body\n"[..],
&b"blip\nbloup\n\nblip\nbloup--\n--bim\n--bim--\n"[..],
))
);
}
#[test]
fn test_part_raw() {
assert_eq!(
part_raw(b"simple boundary")(b"Content-type: text/plain; charset=us-ascii
This is explicitly typed plain US-ASCII text.
It DOES end with a linebreak.
--simple boundary--
"),
Ok((
&b"\n--simple boundary--\n"[..],
&b"Content-type: text/plain; charset=us-ascii\n\nThis is explicitly typed plain US-ASCII text.\nIt DOES end with a linebreak.\n"[..],
))
);
}
}

55
src/pointers.rs Normal file
View file

@ -0,0 +1,55 @@
pub fn parsed<'a>(input: &'a [u8], rest: &'a [u8]) -> &'a [u8] {
let start = input.as_ptr();
let offset = rest.as_ptr();
let idx = (offset as usize - start as usize) / std::mem::size_of::<u8>();
assert!(idx <= input.len());
&input[..idx]
}
pub fn rest<'a>(input: &'a [u8], parsed: &'a [u8]) -> &'a [u8] {
let start = input.as_ptr();
let offset = (&parsed[parsed.len()..]).as_ptr();
let idx = (offset as usize - start as usize) / std::mem::size_of::<u8>();
assert!(idx <= input.len());
&input[idx..]
}
pub fn with_preamble<'a>(input: &'a [u8], parsed: &'a [u8]) -> &'a [u8] {
let start = input.as_ptr();
let offset = (&parsed[parsed.len()..]).as_ptr();
let idx = (offset as usize - start as usize) / std::mem::size_of::<u8>();
assert!(idx <= input.len());
&input[..idx]
}
pub fn with_epilogue<'a>(input: &'a [u8], rest: &'a [u8]) -> &'a [u8] {
let start = input.as_ptr();
let offset = rest.as_ptr();
let idx = (offset as usize - start as usize) / std::mem::size_of::<u8>();
assert!(idx <= input.len());
&input[idx..]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_all() {
let outer = b"aa bb cc";
let inner = &outer[3..5];
assert_eq!(inner, b"bb");
let p = parsed(outer, inner);
assert_eq!(p, b"aa ");
let r = rest(outer, inner);
assert_eq!(r, b" cc");
let wp = with_preamble(outer, inner);
assert_eq!(wp, b"aa bb");
let we = with_epilogue(outer, inner);
assert_eq!(we, b"bb cc");
}
}

149
src/text/ascii.rs Normal file
View file

@ -0,0 +1,149 @@
#![allow(dead_code)]
// ASCII
// -- CONTROL CHARACTERS
pub const NULL: u8 = 0x00; // NULL
pub const SOH: u8 = 0x01; // START OF HEADER
pub const STX: u8 = 0x02; // START OF TEXT
pub const ETX: u8 = 0x03; // END OF TEXT
pub const EOT: u8 = 0x04; //
pub const ANQ: u8 = 0x05;
pub const ACK: u8 = 0x06;
pub const BEL: u8 = 0x07;
pub const BS: u8 = 0x08; // BACKSPACE
pub const HT: u8 = 0x09; // horizontal tab
pub const LF: u8 = 0x0A;
pub const VT: u8 = 0x0B;
pub const FF: u8 = 0x0C;
pub const CR: u8 = 0x0D;
pub const SO: u8 = 0x0E;
pub const SI: u8 = 0x0F;
pub const DLE: u8 = 0x10;
pub const DC1: u8 = 0x11;
pub const DC2: u8 = 0x12;
pub const DC3: u8 = 0x13;
pub const DC4: u8 = 0x14;
pub const NAK: u8 = 0x15;
pub const SYN: u8 = 0x16;
pub const ETB: u8 = 0x17;
pub const CAN: u8 = 0x18;
pub const EM: u8 = 0x19;
pub const SUB: u8 = 0x1A;
pub const ESC: u8 = 0x1B;
pub const FS: u8 = 0x1C;
pub const GS: u8 = 0x1D;
pub const RS: u8 = 0x1E;
pub const US: u8 = 0x1F;
pub const DEL: u8 = 0x7F;
// -- GRAPHIC CHARACTERS
pub const SP: u8 = 0x20; // space
pub const EXCLAMATION: u8 = 0x21; // !
pub const DQUOTE: u8 = 0x22; // "
pub const NUM: u8 = 0x23; // #
pub const DOLLAR: u8 = 0x24; // $
pub const PERCENT: u8 = 0x25; // %
pub const AMPERSAND: u8 = 0x26; // &
pub const SQUOTE: u8 = 0x27; // '
pub const LEFT_PAR: u8 = 0x28; // (
pub const RIGHT_PAR: u8 = 0x29; // )
pub const ASTERISK: u8 = 0x2A; // *
pub const PLUS: u8 = 0x2B; // +
pub const COMMA: u8 = 0x2C; // ,
pub const MINUS: u8 = 0x2D; // -
pub const PERIOD: u8 = 0x2E; // .
pub const SLASH: u8 = 0x2F; // /
pub const N0: u8 = 0x30; // 0
pub const N1: u8 = 0x31; // 1
pub const N2: u8 = 0x32; // 2
pub const N3: u8 = 0x33; // 3
pub const N4: u8 = 0x34; // 4
pub const N5: u8 = 0x35; // 5
pub const N6: u8 = 0x36; // 6
pub const N7: u8 = 0x37; // 7
pub const N8: u8 = 0x38; // 8
pub const N9: u8 = 0x39; // 9
pub const COL: u8 = 0x3A; // :
pub const SEM_COL: u8 = 0x3B; // ;
pub const LT: u8 = 0x3C; // <
pub const EQ: u8 = 0x3D; // =
pub const GT: u8 = 0x3E; // >
pub const QUESTION: u8 = 0x3F; // ?
pub const AT: u8 = 0x40; // @
pub const LCA: u8 = 0x41; // A
pub const LCB: u8 = 0x42; // B
pub const LCC: u8 = 0x43; // C
pub const LCD: u8 = 0x44; // D
pub const LCE: u8 = 0x45; // E
pub const LCF: u8 = 0x46; // F
pub const LCG: u8 = 0x47; // G
pub const LCH: u8 = 0x48; // H
pub const LCI: u8 = 0x49; // I
pub const LCJ: u8 = 0x4A; // J
pub const LCK: u8 = 0x4B; // K
pub const LCL: u8 = 0x4C; // L
pub const LCM: u8 = 0x4D; // M
pub const LCN: u8 = 0x4E; // N
pub const LCO: u8 = 0x4F; // O
pub const LCP: u8 = 0x50; // P
pub const LCQ: u8 = 0x51; // Q
pub const LCR: u8 = 0x52; // R
pub const LCS: u8 = 0x53; // S
pub const LCT: u8 = 0x54; // T
pub const LCU: u8 = 0x55; // U
pub const LCV: u8 = 0x56; // V
pub const LCW: u8 = 0x57; // W
pub const LCX: u8 = 0x58; // X
pub const LCY: u8 = 0x59; // Y
pub const LCZ: u8 = 0x5A; // Z
pub const LEFT_BRACKET: u8 = 0x5B; // [
pub const BACKSLASH: u8 = 0x5C; // \
pub const RIGHT_BRACKET: u8 = 0x5D; // ]
pub const CARRET: u8 = 0x5E; // ^
pub const UNDERSCORE: u8 = 0x5F; // _
pub const GRAVE: u8 = 0x60; // `
pub const LSA: u8 = 0x61; // a
pub const LSB: u8 = 0x62; // b
pub const LSC: u8 = 0x63; // c
pub const LSD: u8 = 0x64; // d
pub const LSE: u8 = 0x65; // e
pub const LSF: u8 = 0x66; // f
pub const LSG: u8 = 0x67; // g
pub const LSH: u8 = 0x68; // h
pub const LSI: u8 = 0x69; // i
pub const LSJ: u8 = 0x6A; // j
pub const LSK: u8 = 0x6B; // k
pub const LSL: u8 = 0x6C; // l
pub const LSM: u8 = 0x6D; // m
pub const LSN: u8 = 0x6E; // n
pub const LSO: u8 = 0x6F; // o
pub const LSP: u8 = 0x70; // p
pub const LSQ: u8 = 0x71; // q
pub const LSR: u8 = 0x72; // r
pub const LSS: u8 = 0x73; // s
pub const LST: u8 = 0x74; // t
pub const LSU: u8 = 0x75; // u
pub const LSV: u8 = 0x76; // v
pub const LSW: u8 = 0x77; // w
pub const LSX: u8 = 0x78; // x
pub const LSY: u8 = 0x79; // y
pub const LSZ: u8 = 0x7A; // z
pub const LEFT_CURLY: u8 = 0x7B; // {
pub const PIPE: u8 = 0x7C; // |
pub const RIGHT_CURLY: u8 = 0x7D; // }
pub const TILDE: u8 = 0x7E; // ~
// GROUP OF CHARACTERS
// -- CRLF
pub const CRLF: &[u8] = &[CR, LF];
// -- CRCRLF
// Sometimes portable libraries replace transparently
// the "\n" with "\r\n" on Windows. When developpers
// explicitly write "\r\n", the library generates "\r\r\n".
pub const CRCRLF: &[u8] = &[CR, CR, LF];
// -- WHITESPACE
pub const WS: &[u8] = &[HT, SP];
pub const GRAPHIC_BEGIN: u8 = SP;
pub const GRAPHIC_END: u8 = TILDE;

52
src/text/boundary.rs Normal file
View file

@ -0,0 +1,52 @@
use nom::{
branch::alt,
bytes::complete::tag,
combinator::{eof, opt},
sequence::tuple,
IResult,
};
use crate::text::whitespace::obs_crlf;
#[derive(Debug, PartialEq)]
pub enum Delimiter {
Next,
Last,
}
pub fn boundary<'a>(boundary: &[u8]) -> impl Fn(&'a [u8]) -> IResult<&'a [u8], Delimiter> + '_ {
move |input: &[u8]| {
let (rest, (_, _, _, last, _)) = tuple((
opt(obs_crlf),
tag(b"--"),
tag(boundary),
opt(tag(b"--")),
alt((obs_crlf, eof)),
))(input)?;
match last {
Some(_) => Ok((rest, Delimiter::Last)),
None => Ok((rest, Delimiter::Next)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_boundary_next() {
assert_eq!(
boundary(b"hello")(b"\r\n--hello\r\n"),
Ok((&b""[..], Delimiter::Next))
);
}
#[test]
fn test_boundary_last() {
assert_eq!(
boundary(b"hello")(b"\r\n--hello--\r\n"),
Ok((&b""[..], Delimiter::Last))
);
}
}

232
src/text/encoding.rs Normal file
View file

@ -0,0 +1,232 @@
use encoding_rs::Encoding;
use base64::{engine::general_purpose, Engine as _};
use nom::{
branch::alt,
bytes::complete::{tag, take, take_while, take_while1},
character::complete::one_of,
character::is_alphanumeric,
combinator::{map, opt},
multi::{many0, many1},
sequence::{preceded, terminated, tuple},
IResult,
};
use crate::text::ascii;
use crate::text::whitespace::cfws;
use crate::text::words;
pub fn encoded_word(input: &[u8]) -> IResult<&[u8], EncodedWord> {
alt((encoded_word_quoted, encoded_word_base64))(input)
}
pub fn encoded_word_quoted(input: &[u8]) -> IResult<&[u8], EncodedWord> {
let (rest, (_, _, charset, _, _, _, txt, _, _)) = tuple((
opt(cfws),
tag("=?"),
words::mime_atom,
tag("?"),
one_of("Qq"),
tag("?"),
ptext,
tag("?="),
opt(cfws),
))(input)?;
let renc = Encoding::for_label(charset).unwrap_or(encoding_rs::WINDOWS_1252);
let parsed = EncodedWord::Quoted(QuotedWord {
enc: renc,
chunks: txt,
});
Ok((rest, parsed))
}
pub fn encoded_word_base64(input: &[u8]) -> IResult<&[u8], EncodedWord> {
let (rest, (_, charset, _, _, _, txt, _)) = tuple((
tag("=?"),
words::mime_atom,
tag("?"),
one_of("Bb"),
tag("?"),
btext,
tag("?="),
))(input)?;
let renc = Encoding::for_label(charset).unwrap_or(encoding_rs::WINDOWS_1252);
let parsed = EncodedWord::Base64(Base64Word {
enc: renc,
content: txt,
});
Ok((rest, parsed))
}
#[derive(PartialEq, Debug, Clone)]
pub enum EncodedWord<'a> {
Quoted(QuotedWord<'a>),
Base64(Base64Word<'a>),
}
impl<'a> EncodedWord<'a> {
pub fn to_string(&self) -> String {
match self {
EncodedWord::Quoted(v) => v.to_string(),
EncodedWord::Base64(v) => v.to_string(),
}
}
}
#[derive(PartialEq, Debug, Clone)]
pub struct Base64Word<'a> {
pub enc: &'static Encoding,
pub content: &'a [u8],
}
impl<'a> Base64Word<'a> {
pub fn to_string(&self) -> String {
general_purpose::STANDARD_NO_PAD
.decode(self.content)
.map(|d| self.enc.decode(d.as_slice()).0.to_string())
.unwrap_or("".into())
}
}
#[derive(PartialEq, Debug, Clone)]
pub struct QuotedWord<'a> {
pub enc: &'static Encoding,
pub chunks: Vec<QuotedChunk<'a>>,
}
impl<'a> QuotedWord<'a> {
pub fn to_string(&self) -> String {
self.chunks.iter().fold(String::new(), |mut acc, c| {
match c {
QuotedChunk::Safe(v) => {
let (content, _) = encoding_rs::UTF_8.decode_without_bom_handling(v);
acc.push_str(content.as_ref());
}
QuotedChunk::Space => acc.push(' '),
QuotedChunk::Encoded(v) => {
let (d, _) = self.enc.decode_without_bom_handling(v.as_slice());
acc.push_str(d.as_ref());
}
};
acc
})
}
}
#[derive(PartialEq, Debug, Clone)]
pub enum QuotedChunk<'a> {
Safe(&'a [u8]),
Encoded(Vec<u8>),
Space,
}
//quoted_printable
pub fn ptext(input: &[u8]) -> IResult<&[u8], Vec<QuotedChunk>> {
many0(alt((safe_char2, encoded_space, many_hex_octet)))(input)
}
fn safe_char2(input: &[u8]) -> IResult<&[u8], QuotedChunk> {
map(take_while1(is_safe_char2), QuotedChunk::Safe)(input)
}
/// RFC2047 section 4.2
/// 8-bit values which correspond to printable ASCII characters other
/// than "=", "?", and "_" (underscore), MAY be represented as those
/// characters.
fn is_safe_char2(c: u8) -> bool {
c >= ascii::SP && c != ascii::UNDERSCORE && c != ascii::QUESTION && c != ascii::EQ
}
fn encoded_space(input: &[u8]) -> IResult<&[u8], QuotedChunk> {
map(tag("_"), |_| QuotedChunk::Space)(input)
}
fn hex_octet(input: &[u8]) -> IResult<&[u8], u8> {
use nom::error::*;
let (rest, hbytes) = preceded(tag("="), take(2usize))(input)?;
let hstr = String::from_utf8_lossy(hbytes);
let parsed = u8::from_str_radix(hstr.as_ref(), 16)
.map_err(|_| nom::Err::Error(Error::new(input, ErrorKind::Verify)))?;
Ok((rest, parsed))
}
fn many_hex_octet(input: &[u8]) -> IResult<&[u8], QuotedChunk> {
map(many1(hex_octet), QuotedChunk::Encoded)(input)
}
//base64 (maybe use a crate)
pub fn btext(input: &[u8]) -> IResult<&[u8], &[u8]> {
terminated(take_while(is_bchar), many0(tag("=")))(input)
}
fn is_bchar(c: u8) -> bool {
is_alphanumeric(c) || c == ascii::PLUS || c == ascii::SLASH
}
#[cfg(test)]
mod tests {
use super::*;
// =?iso8859-1?Q?Accus=E9_de_r=E9ception_(affich=E9)?=
#[test]
fn test_ptext() {
assert_eq!(
ptext(b"Accus=E9_de_r=E9ception_(affich=E9)"),
Ok((
&b""[..],
vec![
QuotedChunk::Safe(&b"Accus"[..]),
QuotedChunk::Encoded(vec![0xe9]),
QuotedChunk::Space,
QuotedChunk::Safe(&b"de"[..]),
QuotedChunk::Space,
QuotedChunk::Safe(&b"r"[..]),
QuotedChunk::Encoded(vec![0xe9]),
QuotedChunk::Safe(&b"ception"[..]),
QuotedChunk::Space,
QuotedChunk::Safe(&b"(affich"[..]),
QuotedChunk::Encoded(vec![0xe9]),
QuotedChunk::Safe(&b")"[..]),
]
))
);
}
#[test]
fn test_decode_word() {
assert_eq!(
encoded_word(b"=?iso8859-1?Q?Accus=E9_de_r=E9ception_(affich=E9)?=")
.unwrap()
.1
.to_string(),
"Accusé de réception (affiché)".to_string(),
);
}
// =?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=
#[test]
fn test_decode_word_b64() {
assert_eq!(
encoded_word(b"=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=")
.unwrap()
.1
.to_string(),
"If you can read this yo".to_string(),
);
}
#[test]
fn test_strange_quoted() {
assert_eq!(
encoded_word(b"=?UTF-8?Q?John_Sm=C3=AEth?=")
.unwrap()
.1
.to_string(),
"John Smîth".to_string(),
);
}
}

224
src/text/misc_token.rs Normal file
View file

@ -0,0 +1,224 @@
use nom::{
branch::alt,
bytes::complete::{tag, take_while1},
character::complete::space0,
combinator::{map, opt},
multi::{many0, many1, separated_list1},
sequence::preceded,
IResult,
};
use std::fmt;
use crate::text::{
ascii,
encoding::{self, encoded_word},
quoted::{quoted_string, QuotedString},
whitespace::{fws, is_obs_no_ws_ctl},
words::{atom, is_vchar, mime_atom},
};
#[derive(Debug, PartialEq, Default)]
pub struct PhraseList<'a>(pub Vec<Phrase<'a>>);
pub fn phrase_list(input: &[u8]) -> IResult<&[u8], PhraseList> {
map(separated_list1(tag(","), phrase), PhraseList)(input)
}
#[derive(Debug, PartialEq, Clone)]
pub enum MIMEWord<'a> {
Quoted(QuotedString<'a>),
Atom(&'a [u8]),
}
impl Default for MIMEWord<'static> {
fn default() -> Self {
Self::Atom(&[])
}
}
impl<'a> MIMEWord<'a> {
pub fn to_string(&self) -> String {
match self {
Self::Quoted(v) => v.to_string(),
Self::Atom(v) => encoding_rs::UTF_8
.decode_without_bom_handling(v)
.0
.to_string(),
}
}
}
pub fn mime_word(input: &[u8]) -> IResult<&[u8], MIMEWord> {
alt((
map(quoted_string, MIMEWord::Quoted),
map(mime_atom, MIMEWord::Atom),
))(input)
}
#[derive(PartialEq)]
pub enum Word<'a> {
Quoted(QuotedString<'a>),
Encoded(encoding::EncodedWord<'a>),
Atom(&'a [u8]),
}
impl<'a> ToString for Word<'a> {
fn to_string(&self) -> String {
match self {
Word::Quoted(v) => v.to_string(),
Word::Encoded(v) => v.to_string(),
Word::Atom(v) => encoding_rs::UTF_8
.decode_without_bom_handling(v)
.0
.to_string(),
}
}
}
impl<'a> fmt::Debug for Word<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple("Word")
.field(&format_args!("\"{}\"", self.to_string()))
.finish()
}
}
/// Word
///
/// ```abnf
/// word = atom / quoted-string
/// ```
pub fn word(input: &[u8]) -> IResult<&[u8], Word> {
alt((
map(quoted_string, Word::Quoted),
map(encoded_word, Word::Encoded),
map(atom, Word::Atom),
))(input)
}
#[derive(PartialEq)]
pub struct Phrase<'a>(pub Vec<Word<'a>>);
impl<'a> ToString for Phrase<'a> {
fn to_string(&self) -> String {
self.0
.iter()
.map(|v| v.to_string())
.collect::<Vec<String>>()
.join(" ")
}
}
impl<'a> fmt::Debug for Phrase<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple("Phrase")
.field(&format_args!("\"{}\"", self.to_string()))
.finish()
}
}
/// Phrase
///
/// ```abnf
/// phrase = 1*word / obs-phrase
/// ```
pub fn phrase(input: &[u8]) -> IResult<&[u8], Phrase> {
let (input, phrase) = map(many1(word), Phrase)(input)?;
Ok((input, phrase))
}
/// Compatible unstructured input
///
/// ```abnf
/// obs-utext = %d0 / obs-NO-WS-CTL / VCHAR
/// ```
fn is_unstructured(c: u8) -> bool {
is_vchar(c) || is_obs_no_ws_ctl(c) || c == ascii::NULL
}
#[derive(Debug, PartialEq, Clone)]
pub enum UnstrToken<'a> {
Init,
Encoded(encoding::EncodedWord<'a>),
Plain(&'a [u8]),
}
impl<'a> ToString for UnstrToken<'a> {
fn to_string(&self) -> String {
match self {
UnstrToken::Init => "".into(),
UnstrToken::Encoded(e) => e.to_string(),
UnstrToken::Plain(e) => encoding_rs::UTF_8
.decode_without_bom_handling(e)
.0
.into_owned(),
}
}
}
#[derive(PartialEq, Clone)]
pub struct Unstructured<'a>(pub Vec<UnstrToken<'a>>);
impl<'a> ToString for Unstructured<'a> {
fn to_string(&self) -> String {
self.0
.iter()
.fold(
(&UnstrToken::Init, String::new()),
|(prev_token, mut result), current_token| {
match (prev_token, current_token) {
(UnstrToken::Init, v) => result.push_str(v.to_string().as_ref()),
(UnstrToken::Encoded(_), UnstrToken::Encoded(v)) => {
result.push_str(v.to_string().as_ref())
}
(_, v) => {
result.push(' ');
result.push_str(v.to_string().as_ref())
}
};
(current_token, result)
},
)
.1
}
}
impl<'a> fmt::Debug for Unstructured<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple("Unstructured")
.field(&format_args!("\"{}\"", self.to_string()))
.finish()
}
}
/// Unstructured header field body
///
/// ```abnf
/// unstructured = (*([FWS] VCHAR_SEQ) *WSP) / obs-unstruct
/// ```
pub fn unstructured(input: &[u8]) -> IResult<&[u8], Unstructured> {
let (input, r) = many0(preceded(
opt(fws),
alt((
map(encoded_word, UnstrToken::Encoded),
map(take_while1(is_unstructured), UnstrToken::Plain),
)),
))(input)?;
let (input, _) = space0(input)?;
Ok((input, Unstructured(r)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_phrase() {
assert_eq!(
phrase(b"hello world").unwrap().1.to_string(),
"hello world".to_string(),
);
assert_eq!(
phrase(b"salut \"le\" monde").unwrap().1.to_string(),
"salut le monde".to_string(),
);
let (rest, parsed) = phrase(b"fin\r\n du\r\nmonde").unwrap();
assert_eq!(rest, &b"\r\nmonde"[..]);
assert_eq!(parsed.to_string(), "fin du".to_string());
}
}

7
src/text/mod.rs Normal file
View file

@ -0,0 +1,7 @@
pub mod ascii;
pub mod boundary;
pub mod encoding;
pub mod misc_token;
pub mod quoted;
pub mod whitespace;
pub mod words;

134
src/text/quoted.rs Normal file
View file

@ -0,0 +1,134 @@
use nom::{
branch::alt,
bytes::complete::{tag, take, take_while1},
combinator::opt,
multi::many0,
sequence::{pair, preceded},
IResult,
};
use crate::text::ascii;
use crate::text::whitespace::{cfws, fws, is_obs_no_ws_ctl};
#[derive(Debug, PartialEq, Default, Clone)]
pub struct QuotedString<'a>(pub Vec<&'a [u8]>);
impl<'a> QuotedString<'a> {
pub fn push(&mut self, e: &'a [u8]) {
self.0.push(e)
}
pub fn to_string(&self) -> String {
let enc = encoding_rs::UTF_8;
let size = self.0.iter().fold(0, |acc, v| acc + v.len());
self.0
.iter()
.fold(String::with_capacity(size), |mut acc, v| {
let (content, _) = enc.decode_without_bom_handling(v);
acc.push_str(content.as_ref());
acc
})
}
}
/// Quoted pair
///
/// ```abnf
/// quoted-pair = ("\" (VCHAR / WSP)) / obs-qp
/// obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR)
/// ```
pub fn quoted_pair(input: &[u8]) -> IResult<&[u8], &[u8]> {
preceded(tag(&[ascii::BACKSLASH]), take(1usize))(input)
}
/// Allowed characters in quote
///
/// ```abnf
/// qtext = %d33 / ; Printable US-ASCII
/// %d35-91 / ; characters not including
/// %d93-126 / ; "\" or the quote character
/// obs-qtext
/// ```
fn is_restr_qtext(c: u8) -> bool {
c == ascii::EXCLAMATION
|| (ascii::NUM..=ascii::LEFT_BRACKET).contains(&c)
|| (ascii::RIGHT_BRACKET..=ascii::TILDE).contains(&c)
}
fn is_qtext(c: u8) -> bool {
is_restr_qtext(c) || is_obs_no_ws_ctl(c)
}
/// Quoted pair content
///
/// ```abnf
/// qcontent = qtext / quoted-pair
/// ```
fn qcontent(input: &[u8]) -> IResult<&[u8], &[u8]> {
alt((take_while1(is_qtext), quoted_pair))(input)
}
/// Quoted string
///
/// ```abnf
/// quoted-string = [CFWS]
/// DQUOTE *([FWS] qcontent) [FWS] DQUOTE
/// [CFWS]
/// ```
pub fn quoted_string(input: &[u8]) -> IResult<&[u8], QuotedString> {
let (input, _) = opt(cfws)(input)?;
let (input, _) = tag("\"")(input)?;
let (input, content) = many0(pair(opt(fws), qcontent))(input)?;
// Rebuild string
let mut qstring = content
.iter()
.fold(QuotedString::default(), |mut acc, (maybe_wsp, c)| {
if maybe_wsp.is_some() {
acc.push(&[ascii::SP]);
}
acc.push(c);
acc
});
let (input, maybe_wsp) = opt(fws)(input)?;
if maybe_wsp.is_some() {
qstring.push(&[ascii::SP]);
}
let (input, _) = tag("\"")(input)?;
let (input, _) = opt(cfws)(input)?;
Ok((input, qstring))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_quoted_string_parser() {
assert_eq!(
quoted_string(b" \"hello\\\"world\" ").unwrap().1,
QuotedString(vec![b"hello", &[ascii::DQUOTE], b"world"])
);
assert_eq!(
quoted_string(b"\"hello\r\n world\""),
Ok((
&b""[..],
QuotedString(vec![b"hello", &[ascii::SP], b"world"])
)),
);
}
use crate::text::ascii;
#[test]
fn test_quoted_string_object() {
assert_eq!(
QuotedString(vec![b"hello", &[ascii::SP], b"world"]).to_string(),
"hello world".to_string(),
);
}
}

192
src/text/whitespace.rs Normal file
View file

@ -0,0 +1,192 @@
use crate::text::ascii;
use crate::text::encoding::encoded_word;
use crate::text::quoted::quoted_pair;
use nom::{
branch::alt,
bytes::complete::{is_not, tag, take_while1},
character::complete::{space0, space1},
combinator::{opt, recognize},
multi::{many0, many1},
sequence::{pair, tuple},
IResult,
};
/// Whitespace (space, new line, tab) content and
/// delimited content (eg. comment, line, sections, etc.)
/// Obsolete/Compatible CRLF
///
/// Theoretically, all lines must end with \r\n
/// but some mail servers like Dovecot support malformated emails,
/// for example with only \n eol. It works because
/// \r or \n is allowed nowhere else, so we also add this support.
pub fn obs_crlf(input: &[u8]) -> IResult<&[u8], &[u8]> {
alt((
tag(ascii::CRLF),
tag(ascii::CRCRLF),
tag(&[ascii::CR]),
tag(&[ascii::LF]),
))(input)
}
/// ```abnf
/// fold_line = any *(1*(crlf WS) any) crlf
/// ```
pub fn foldable_line(input: &[u8]) -> IResult<&[u8], &[u8]> {
recognize(tuple((
is_not(ascii::CRLF),
many0(pair(many1(pair(obs_crlf, space1)), is_not(ascii::CRLF))),
obs_crlf,
)))(input)
}
// --- whitespaces and comments
// Note: WSP = SP / HTAB = %x20 / %x09
// nom::*::space0 = *WSP
// nom::*::space1 = 1*WSP
/// Permissive foldable white space
///
/// Folding white space are used for long headers splitted on multiple lines.
/// The obsolete syntax allowes multiple lines without content; implemented for compatibility
/// reasons
pub fn fws(input: &[u8]) -> IResult<&[u8], u8> {
let (input, _) = alt((recognize(many1(fold_marker)), space1))(input)?;
Ok((input, ascii::SP))
}
fn fold_marker(input: &[u8]) -> IResult<&[u8], &[u8]> {
let (input, _) = space0(input)?;
let (input, _) = obs_crlf(input)?;
space1(input)
}
/// Folding White Space with Comment
///
/// Note: we drop the comments for now...
///
/// ```abnf
/// ctext = %d33-39 / ; Printable US-ASCII
/// %d42-91 / ; characters not including
/// %d93-126 / ; "(", ")", or "\"
/// obs-ctext
///
/// ccontent = ctext / quoted-pair / comment
///
/// comment = "(" *([FWS] ccontent) [FWS] ")"
///
/// CFWS = (1*([FWS] comment) [FWS]) / FWS
/// ```
pub fn cfws(input: &[u8]) -> IResult<&[u8], &[u8]> {
alt((recognize(comments), recognize(fws)))(input)
}
pub fn comments(input: &[u8]) -> IResult<&[u8], ()> {
let (input, _) = many1(tuple((opt(fws), comment)))(input)?;
let (input, _) = opt(fws)(input)?;
Ok((input, ()))
}
pub fn comment(input: &[u8]) -> IResult<&[u8], ()> {
let (input, _) = tag("(")(input)?;
let (input, _) = many0(tuple((opt(fws), ccontent)))(input)?;
let (input, _) = opt(fws)(input)?;
let (input, _) = tag(")")(input)?;
Ok((input, ()))
}
pub fn ccontent(input: &[u8]) -> IResult<&[u8], &[u8]> {
alt((
ctext,
recognize(quoted_pair),
recognize(encoded_word),
recognize(comment),
))(input)
}
pub fn ctext(input: &[u8]) -> IResult<&[u8], &[u8]> {
take_while1(is_ctext)(input)
}
pub fn is_ctext(c: u8) -> bool {
is_restr_ctext(c) || is_obs_no_ws_ctl(c)
}
/// Check if it's a comment text character
///
/// ```abnf
/// ctext = %d33-39 / ; Printable US-ASCII
/// %d42-91 / ; characters not including
/// %d93-126 / ; "(", ")", or "\"
/// obs-ctext
///```
pub fn is_restr_ctext(c: u8) -> bool {
(ascii::EXCLAMATION..=ascii::SQUOTE).contains(&c)
|| (ascii::ASTERISK..=ascii::LEFT_BRACKET).contains(&c)
|| (ascii::RIGHT_BRACKET..=ascii::TILDE).contains(&c)
}
/// US ASCII control characters without effect
///
/// ```abnf
/// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
/// %d11 / ; characters that do not
/// %d12 / ; include the carriage
/// %d14-31 / ; return, line feed, and
/// %d127 ; white space characters
/// ```
pub fn is_obs_no_ws_ctl(c: u8) -> bool {
(ascii::SOH..=ascii::BS).contains(&c)
|| c == ascii::VT
|| c == ascii::FF
|| (ascii::SO..=ascii::US).contains(&c)
|| c == ascii::DEL
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_obs_crlf() {
assert_eq!(obs_crlf(b"\rworld"), Ok((&b"world"[..], &b"\r"[..])));
assert_eq!(obs_crlf(b"\r\nworld"), Ok((&b"world"[..], &b"\r\n"[..])));
assert_eq!(obs_crlf(b"\nworld"), Ok((&b"world"[..], &b"\n"[..])));
}
#[test]
fn test_fws() {
assert_eq!(fws(b"\r\n world"), Ok((&b"world"[..], ascii::SP)));
assert_eq!(fws(b" \r\n \r\n world"), Ok((&b"world"[..], ascii::SP)));
assert_eq!(fws(b" world"), Ok((&b"world"[..], ascii::SP)));
assert!(fws(b"\r\nFrom: test").is_err());
}
#[test]
fn test_cfws() {
assert_eq!(
cfws(b"(A nice \\) chap) <pete(his account)@silly.test(his host)>"),
Ok((
&b"<pete(his account)@silly.test(his host)>"[..],
&b"(A nice \\) chap) "[..]
))
);
assert_eq!(
cfws(b"(Chris's host.)public.example>,"),
Ok((&b"public.example>,"[..], &b"(Chris's host.)"[..]))
);
assert_eq!(
cfws(b"(double (comment) is fun) wouch"),
Ok((&b"wouch"[..], &b"(double (comment) is fun) "[..]))
);
}
#[test]
fn test_cfws_encoded_word() {
assert_eq!(
cfws(b"(=?US-ASCII?Q?Keith_Moore?=)"),
Ok((&b""[..], &b"(=?US-ASCII?Q?Keith_Moore?=)"[..])),
);
}
}

134
src/text/words.rs Normal file
View file

@ -0,0 +1,134 @@
use crate::text::ascii;
use crate::text::whitespace::cfws;
use nom::{
bytes::complete::{tag, take_while1},
character::is_alphanumeric,
combinator::{opt, recognize},
multi::many0,
sequence::{delimited, pair},
IResult,
};
pub fn is_vchar(c: u8) -> bool {
(ascii::EXCLAMATION..=ascii::TILDE).contains(&c)
}
/// MIME Token allowed characters
///
/// forbidden: ()<>@,;:\"/[]?=
fn is_mime_atom_text(c: u8) -> bool {
is_alphanumeric(c)
|| c == ascii::EXCLAMATION
|| c == ascii::NUM
|| c == ascii::DOLLAR
|| c == ascii::PERCENT
|| c == ascii::AMPERSAND
|| c == ascii::SQUOTE
|| c == ascii::ASTERISK
|| c == ascii::PLUS
|| c == ascii::MINUS
|| c == ascii::PERIOD
|| c == ascii::CARRET
|| c == ascii::UNDERSCORE
|| c == ascii::GRAVE
|| c == ascii::LEFT_CURLY
|| c == ascii::PIPE
|| c == ascii::RIGHT_CURLY
|| c == ascii::TILDE
}
/// MIME Token
///
/// `[CFWS] 1*token_text [CFWS]`
pub fn mime_atom(input: &[u8]) -> IResult<&[u8], &[u8]> {
delimited(opt(cfws), take_while1(is_mime_atom_text), opt(cfws))(input)
}
/// Atom allowed characters
///
/// authorized: !#$%&'*+-/=?^_`{|}~
fn is_atext(c: u8) -> bool {
is_alphanumeric(c)
|| c == ascii::EXCLAMATION
|| c == ascii::NUM
|| c == ascii::DOLLAR
|| c == ascii::PERCENT
|| c == ascii::AMPERSAND
|| c == ascii::SQUOTE
|| c == ascii::ASTERISK
|| c == ascii::PLUS
|| c == ascii::MINUS
|| c == ascii::SLASH
|| c == ascii::EQ
|| c == ascii::QUESTION
|| c == ascii::CARRET
|| c == ascii::UNDERSCORE
|| c == ascii::GRAVE
|| c == ascii::LEFT_CURLY
|| c == ascii::PIPE
|| c == ascii::RIGHT_CURLY
|| c == ascii::TILDE
}
/// Atom
///
/// `[CFWS] 1*atext [CFWS]`
pub fn atom(input: &[u8]) -> IResult<&[u8], &[u8]> {
delimited(opt(cfws), take_while1(is_atext), opt(cfws))(input)
}
/// dot-atom-text
///
/// `1*atext *("." 1*atext)`
pub fn dot_atom_text(input: &[u8]) -> IResult<&[u8], &[u8]> {
recognize(pair(
take_while1(is_atext),
many0(pair(tag("."), take_while1(is_atext))),
))(input)
}
/// dot-atom
///
/// `[CFWS] dot-atom-text [CFWS]`
#[allow(dead_code)]
pub fn dot_atom(input: &[u8]) -> IResult<&[u8], &[u8]> {
delimited(opt(cfws), dot_atom_text, opt(cfws))(input)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_atext() {
assert!(is_atext(b'='));
assert!(is_atext(b'5'));
assert!(is_atext(b'Q'));
assert!(!is_atext(b' '));
//assert!(is_atext('É')); // support utf8
}
#[test]
fn test_atom() {
assert_eq!(
atom(b"(skip) imf_codec (hidden) aerogramme"),
Ok((&b"aerogramme"[..], &b"imf_codec"[..]))
);
}
#[test]
fn test_dot_atom_text() {
assert_eq!(
dot_atom_text(b"quentin.dufour.io abcdef"),
Ok((&b" abcdef"[..], &b"quentin.dufour.io"[..]))
);
}
#[test]
fn test_dot_atom() {
assert_eq!(
dot_atom(b" (skip) quentin.dufour.io abcdef"),
Ok((&b"abcdef"[..], &b"quentin.dufour.io"[..]))
);
}
}

View file

@ -1,124 +0,0 @@
use std::collections::HashSet;
use std::path::PathBuf;
use std::fs::File;
use std::io::Read;
use imf_codec::fragments::header;
use walkdir::WalkDir;
#[test]
#[ignore]
fn test_enron500k() {
let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("resources/enron/maildir/");
let prefix_sz = d.as_path().to_str().unwrap().len();
//d.push("williams-w3/");
let known_bad_fields = HashSet::from([
"white-s/calendar/113.", // To: east <7..>
"skilling-j/inbox/223.", // From: pep <performance.>
"jones-t/all_documents/9806.", // To: <"tibor.vizkelety":@enron.com>
"jones-t/notes_inbox/3303.", // To: <"tibor.vizkelety":@enron.com>
"lokey-t/calendar/33.", // A second Date entry for the calendar containing
// Date: Monday, March 12
"zipper-a/inbox/199.", // To: e-mail <mari.>
"dasovich-j/deleted_items/128.", // To: f62489 <g>
"dasovich-j/all_documents/677.", // To: w/assts <govt.>
"dasovich-j/all_documents/8984.", // To: <"ft.com.users":@enron.com>
"dasovich-j/all_documents/3514.", // To: <"ft.com.users":@enron.com>
"dasovich-j/all_documents/4467.", // To: <"ft.com.users":@enron.com>
"dasovich-j/all_documents/578.", // To: w/assts <govt.>
"dasovich-j/all_documents/3148.", // To: <"economist.com.readers":@enron.com>
"dasovich-j/all_documents/9953.", // To: <"economist.com.reader":@enron.com>
"dasovich-j/risk_analytics/3.", // To: w/assts <govt.>
"dasovich-j/notes_inbox/5391.", // To: <"ft.com.users":@enron.com>
"dasovich-j/notes_inbox/4952.", // To: <"economist.com.reader":@enron.com>
"dasovich-j/notes_inbox/2386.", // To: <"ft.com.users":@enron.com>
"dasovich-j/notes_inbox/1706.", // To: <"ft.com.users":@enron.com>
"dasovich-j/notes_inbox/1489.", // To: <"economist.com.readers":@enron.com>
"dasovich-j/notes_inbox/5.", // To: w/assts <govt.>
"kaminski-v/sites/19.", // To: <"the.desk":@enron.com>
"kaminski-v/sites/1.", // To: <"the.desk":@enron.com>
"kaminski-v/discussion_threads/5082.", // To: <"ft.com.users":@enron.com>
"kaminski-v/discussion_threads/4046.", // To: <"the.desk":@enron.com>
"kaminski-v/discussion_threads/4187.", // To: <"the.desk":@enron.com>
"kaminski-v/discussion_threads/8068.", // To: cats <breaktkhrough.>, risk <breakthrough.>, leaders <breaktkhrough.>
"kaminski-v/discussion_threads/7980.", // To: dogs <breakthrough.>, cats <breaktkhrough.>, risk <breakthrough.>,\r\n\tleaders <breaktkhrough.>
"kaminski-v/all_documents/5970.", //To: dogs <breakthrough.>, cats <breaktkhrough.>, risk <breakthrough.>,\r\n\tleaders <breaktkhrough.>
"kaminski-v/all_documents/5838.", // To + Cc: dogs <breakthrough.>, breakthrough.adm@enron.com, breakthrough.adm@enron.com,\r\n\tbreakthrough.adm@enron.com
"kaminski-v/all_documents/10070.", // To: <"ft.com.users":@enron.com>
"kaminski-v/all_documents/92.", // To: <"the.desk":@enron.com>
"kaminski-v/all_documents/276.", // To: <"the.desk":@enron.com>
"kaminski-v/technical/1.", // To: <"the.desk":@enron.com>
"kaminski-v/technical/7.", // To: <"the.desk":@enron.com>
"kaminski-v/notes_inbox/140.", // To: dogs <breakthrough.>, cats <breaktkhrough.>, risk <breakthrough.>,\r\n\tleaders <breaktkhrough.>
"kaminski-v/notes_inbox/95.", // To + CC failed: cats <breaktkhrough.>, risk <breakthrough.>, leaders <breaktkhrough.>
"kean-s/archiving/untitled/1232.", // To: w/assts <govt.>, mark.palmer@enron.com, karen.denne@enron.com
"kean-s/archiving/untitled/1688.", // To: w/assts <govt.>
"kean-s/sent/198.", // To: w/assts <govt.>, mark.palmer@enron.com, karen.denne@enron.com
"kean-s/reg_risk/9.", // To: w/assts <govt.>
"kean-s/discussion_threads/950.", // To: w/assts <govt.>, mark.palmer@enron.com, karen.denne@enron.com
"kean-s/discussion_threads/577.", // To: w/assts <govt.>
"kean-s/calendar/untitled/1096.", // To: w/assts <govt.>, mark.palmer@enron.com, karen.denne@enron.com
"kean-s/calendar/untitled/640.", // To: w/assts <govt.>
"kean-s/all_documents/640.", // To: w/assts <govt.>
"kean-s/all_documents/1095.", // To: w/assts <govt.>
"kean-s/attachments/2030.", // To: w/assts <govt.>
"williams-w3/operations_committee_isas/10.", // To: z34655 <m>
]);
let known_bad_from = HashSet::from([
"skilling-j/inbox/223.", // From: pep <performance.>
]);
let mut i = 0;
for entry in WalkDir::new(d.as_path()).into_iter().filter_map(|file| file.ok()) {
if entry.metadata().unwrap().is_file() {
let mail_path = entry.path();
let suffix = &mail_path.to_str().unwrap()[prefix_sz..];
// read file
let mut raw = Vec::new();
let mut f = File::open(mail_path).unwrap();
f.read_to_end(&mut raw).unwrap();
// parse
let (email, encoding, malformed) = header::from_bytes(&raw);
//println!("Encoding: {:?}, Malformed: {:?}", encoding, malformed);
let (input, hdrs) = header::section(&email).unwrap();
//println!("{:?}", hdrs);
let ok_date = hdrs.date.is_some();
let ok_from = hdrs.from.len() > 0;
let ok_fields = hdrs.bad_fields.len() == 0;
let p = entry.path();
if !ok_date || !ok_from || !ok_fields {
println!("Issue with: {}", suffix);
}
assert!(ok_date);
if !known_bad_from.contains(suffix) {
assert!(ok_from);
}
if !known_bad_fields.contains(suffix) {
assert!(ok_fields);
}
i += 1;
if i % 1000 == 0 {
println!("Analyzed emails: {}", i);
}
}
}
}