Compare commits

...

No commits in common. "dev2" and "dev" have entirely different histories.
dev2 ... dev

151 changed files with 8613 additions and 6008 deletions

12
.drone.yml Normal file
View file

@ -0,0 +1,12 @@
---
kind: pipeline
type: docker
name: default
steps:
- name: build
image: rust
commands:
- cargo check --all
- cargo test --all

View file

@ -1,7 +1,4 @@
[*] [*.rs]
indent_size = 2
indent_style = space indent_style = space
indent_size = 2
[Makefile] max_line_length = 80
indent_size = 4
indent_style = tab

1
.envrc
View file

@ -1 +0,0 @@
export DATABASE_URL=sqlite://$(pwd)/test.db

19
.gitignore vendored
View file

@ -1,13 +1,8 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
/target /target
test.db /.env
/output.log
/config.toml
/public
/hellosu
/hellosu.db*

View file

@ -1 +0,0 @@
pnpm-lock.yaml

View file

@ -1,3 +0,0 @@
{
"recommendations": ["tauri-apps.tauri-vscode", "rust-lang.rust-analyzer"]
}

View file

@ -1,2 +0,0 @@
{
}

6275
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,2 +1,12 @@
workspace.resolver = "2" [workspace]
workspace.members = ["src-tauri", "core", "core/migration", "core/entity"] members = [
"daemon",
"imap",
# "mbsync",
"proto-common",
"smtp",
"tui",
]
[profile.release]
lto = true

32
Justfile Normal file
View file

@ -0,0 +1,32 @@
set dotenv-load := false
ct:
tokei
fmt:
cargo +nightly fmt --all
doc shouldOpen="":
#!/bin/bash
if [[ -n "{{shouldOpen}}" ]]; then
OPEN=--open
fi
cargo doc --workspace --document-private-items --no-deps $OPEN
test:
cargo test --all
watch:
cargo watch -c -x 'check --all'
afl-imap:
#!/bin/bash
cd imap/imap-parsing-fuzz-target
pwd
cargo afl build
cargo afl fuzz -i in -o out target/debug/imap-parsing-fuzz-target
fuzz-imap:
#!/bin/bash
cd imap
cargo +nightly fuzz run parse_response

675
LICENSE.md Normal file
View file

@ -0,0 +1,675 @@
### 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>.

43
README.md Normal file
View file

@ -0,0 +1,43 @@
panorama
========
Panorama is a terminal Personal Information Manager (PIM).
Status: **still writing the basics**
Join chat on Matrix at [#panorama:mozilla.org][3]
Goals:
- **Never have to actually close the application.** All errors should be
handled gracefully in a way that can be recovered or restarted without
needing to close the entire application.
- **Handles email, calendar, and address books using open standards.** IMAP for
email retrieval, SMTP for email sending, CalDAV for calendars, and CardDAV
for address books. Work should be saved locally prior to uploading to make
sure nothing is ever lost as a result of network failure.
- **Hot-reload on-disk config.** Configuration should be able to be reloaded so
that the user can keep the application open. Errors in config should be
reported to the user while the application is still running off the old
version.
- **Scriptable.** Built-in scripting language should allow for customization of
common functionality, including keybinds and colors.
Stretch goals:
- Full-text email/message search
- Unified "feed" that any app can submit to.
- Submit notifications to gotify-shaped notification servers.
- JMAP implementation.
- RSS aggregator.
- IRC client??
Credits
-------
IMAP library modified from [djc/tokio-imap][2], MIT licensed.
License: GPLv3 or later
[2]: https://github.com/djc/tokio-imap
[3]: https://matrix.to/#/!NSaHPfsflbEkjCZViX:mozilla.org?via=mozilla.org

View file

@ -1,31 +0,0 @@
{
"$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
"vcs": {
"enabled": false,
"clientKind": "git",
"useIgnoreFile": false
},
"files": {
"ignoreUnknown": false,
"ignore": []
},
"formatter": {
"enabled": true,
"indentStyle": "tab"
},
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"style": { "useConst": "warn" }
}
},
"javascript": {
"formatter": {
"quoteStyle": "double"
}
}
}

BIN
bun.lockb

Binary file not shown.

View file

@ -1,20 +0,0 @@
[package]
name = "panorama-core"
version = "0.1.0"
edition = "2021"
[dependencies]
entity = { path = "entity" }
migration = { path = "migration" }
prost = "0.13.3"
tonic = "0.12.3"
sea-orm = { version = "1.1.1", features = [
"sqlx-sqlite",
"runtime-tokio-rustls",
"macros",
] }
[build-dependencies]
tonic-build = "0.12.3"

View file

@ -1,4 +0,0 @@
fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::compile_protos("src/proto/panorama.proto")?;
Ok(())
}

View file

@ -1,11 +0,0 @@
[package]
name = "entity"
version = "0.1.0"
edition = "2021"
[dependencies]
sea-orm = { version = "1.1.1", features = [
"sqlx-sqlite",
"runtime-tokio-rustls",
"macros",
] }

View file

@ -1,5 +0,0 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.1
pub mod prelude;
pub mod node;

View file

@ -1,19 +0,0 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.1
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "node")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
pub id: String,
#[sea_orm(column_type = "custom(\"datetime\")")]
pub created_at: String,
#[sea_orm(column_type = "custom(\"datetime\")")]
pub updated_at: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}

View file

@ -1,3 +0,0 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.1
pub use super::node::Entity as Node;

View file

@ -1 +0,0 @@
mod generated;

View file

@ -1,16 +0,0 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "migration"
path = "src/lib.rs"
[dependencies]
async-std = { version = "1", features = ["attributes", "tokio1"] }
[dependencies.sea-orm-migration]
version = "1.1.0"
features = ["sqlx-sqlite", "runtime-tokio-rustls"]

View file

@ -1,10 +0,0 @@
pub use sea_orm_migration::prelude::*;
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![]
}
}

View file

@ -1,6 +0,0 @@
use sea_orm_migration::prelude::*;
#[async_std::main]
async fn main() {
cli::run_cli(migration::Migrator).await;
}

View file

@ -1,5 +0,0 @@
pub struct PanoramaDatabase();
impl PanoramaDatabase {
async fn ensure_mail_account() {}
}

View file

@ -1,6 +0,0 @@
mod server_proto {
tonic::include_proto!("panorama");
}
mod dal;
mod server;

View file

@ -1,13 +0,0 @@
syntax = "proto3";
package panorama;
service Panorama {
// Mail service
rpc EnsureMailAccount(EnsureMailAccountRequest) returns (EnsureMailAccountReply);
}
message EnsureMailAccountRequest {
string id = 1;
}
message EnsureMailAccountReply {}

View file

@ -1,21 +0,0 @@
use tonic::{Request, Response, Result};
use crate::dal::PanoramaDatabase;
use crate::server_proto::panorama_server::Panorama as PanoramaServerProto;
use crate::server_proto::{EnsureMailAccountReply, EnsureMailAccountRequest};
pub struct Panorama {
db: PanoramaDatabase,
}
impl Panorama {}
#[tonic::async_trait]
impl PanoramaServerProto for Panorama {
async fn ensure_mail_account(
&self,
req: Request<EnsureMailAccountRequest>,
) -> Result<Response<EnsureMailAccountReply>> {
todo!()
}
}

1
daemon/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/test.db*

33
daemon/Cargo.toml Normal file
View file

@ -0,0 +1,33 @@
[package]
name = "panorama-daemon"
version = "0.0.1"
edition = "2018"
license = "GPL-3.0-or-later"
[features]
default = ["config-watch"]
config-watch = ["notify"]
[dependencies]
anyhow = { version = "1.0.45", features = ["backtrace"] }
async-trait = "0.1.51"
clap = "3.0.0-beta.5"
derivative = "2.2.0"
futures = "0.3.17"
hyper = { version = "0.14.14", features = ["server", "http2", "stream"] }
log = "0.4.14"
panorama-imap = { path = "../imap" }
panorama-smtp = { path = "../smtp" }
serde = { version = "1.0.130", features = ["derive"] }
session_types = "0.3.1"
stderrlog = "0.5.1"
tokio = { version = "1.13.0", features = ["full"] }
tokio-rustls = "0.23.1"
toml = "0.5.8"
xdg = "2.4.0"
notify = { version = "5.0.0-pre.13", optional = true }
[dependencies.sqlx]
version = "0.5.9"
features = ["runtime-tokio-rustls", "sqlite", "json", "chrono"]

View file

@ -0,0 +1,3 @@
DROP TABLE "messages";
DROP TABLE "mailboxes";
DROP TABLE "accounts";

View file

@ -0,0 +1,33 @@
CREATE TABLE "accounts" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT
);
CREATE TABLE "mailboxes" (
"account" INTEGER NOT NULL,
"name" TEXT NOT NULL,
"uidvalidity" INTEGER NOT NULL,
PRIMARY KEY ("account", "name")
);
CREATE TABLE "messages" (
-- "id" TEXT PRIMARY KEY,
"id" INTEGER PRIMARY KEY,
"mailbox_acct" TEXT NOT NULL,
"mailbox" TEXT NOT NULL,
"uid" INTEGER NOT NULL,
"date" DATETIME,
"subject" TEXT,
"from" JSON,
"sender" JSON,
"reply_to" JSON,
"to" JSON,
"cc" JSON,
"bcc" JSON,
"in_reply_to" TEXT,
"message_id" TEXT,
"mbox" BLOB,
FOREIGN KEY ("mailbox_acct") REFERENCES "mailboxes" ("account"),
FOREIGN KEY ("mailbox") REFERENCES "mailboxes" ("name")
);

80
daemon/src/config/mod.rs Normal file
View file

@ -0,0 +1,80 @@
//! Everything related to config handling within the panorama daemon.
#[cfg(feature = "config-watch")]
mod watcher;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use anyhow::Result;
use panorama_imap::client::auth::ImapAuth;
#[cfg(feature = "config-watch")]
pub use self::watcher::{spawn_config_watcher_system, ConfigWatcher};
/// Configuration
#[derive(Default, Serialize, Deserialize, Clone, Debug)]
pub struct Config {
/// Version of the config to use
/// (potentially for migration later?)
pub version: String,
/// Directory to store panorama-related data in
pub data_dir: PathBuf,
/// Mail accounts
#[serde(rename = "mail")]
pub mail_accounts: HashMap<String, MailAccountConfig>,
}
impl Config {
pub async fn from_file(path: impl AsRef<Path>) -> Result<Self> {
let mut file = File::open(path.as_ref())?;
let mut contents = Vec::new();
file.read_to_end(&mut contents)?;
let config = toml::from_slice(&contents)?;
Ok(config)
}
}
/// Configuration for a single mail account
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct MailAccountConfig {
/// Imap
pub imap: ImapConfig,
}
/// Configuring an IMAP server
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ImapConfig {
/// Host of the IMAP server (needs to be hostname for TLS)
pub server: String,
/// Port of the IMAP server
pub port: u16,
/// TLS
pub tls: TlsMethod,
/// Auth
#[serde(flatten)]
pub auth: ImapAuth,
}
/// Describes when to perform the TLS handshake
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum TlsMethod {
/// Perform TLS handshake immediately upon connection
#[serde(rename = "on")]
On,
/// Perform TLS handshake after issuing the STARTTLS command
#[serde(rename = "starttls")]
Starttls,
/// Don't perform TLS handshake at all (unsecured)
#[serde(rename = "off")]
Off,
}

View file

@ -0,0 +1,105 @@
use std::fs;
use std::path::Path;
use std::sync::mpsc as stdmpsc;
use anyhow::{Context, Result};
use futures::future::TryFutureExt;
use notify::{
recommended_watcher, Event as NotifyEvent, RecommendedWatcher, RecursiveMode,
Watcher,
};
use tokio::{sync::watch, task::JoinHandle};
use xdg::BaseDirectories;
use super::Config;
pub type ConfigWatcher = watch::Receiver<Config>;
/// Start the entire config watcher system, and return a
/// [ConfigWatcher][self::ConfigWatcher], which is a cloneable receiver of
/// config update events.
pub fn spawn_config_watcher_system() -> Result<(JoinHandle<()>, ConfigWatcher)>
{
let (tx, rx) = stdmpsc::channel();
let mut dir_watcher = recommended_watcher(move |res| match res {
Ok(event) => {
tx.send(event).unwrap();
}
Err(_) => {}
})?;
let xdg = BaseDirectories::new()?;
let config_home = xdg.get_config_home().join("panorama");
if !config_home.exists() {
fs::create_dir_all(&config_home)?;
}
dir_watcher
.watch(&config_home, RecursiveMode::Recursive)
.context("adding watch for config home")?;
debug!("watching {:?}", config_home);
let (config_tx, config_update) = watch::channel(Config::default());
let handle = tokio::spawn(
start_notify_stream(dir_watcher, rx, config_home, config_tx)
.unwrap_or_else(|_err| todo!()),
);
Ok((handle, config_update))
}
async fn start_notify_stream(
_watcher: RecommendedWatcher,
rx: stdmpsc::Receiver<NotifyEvent>,
config_home: impl AsRef<Path>,
config_tx: watch::Sender<Config>,
) -> Result<()> {
let config_home = config_home.as_ref().to_path_buf();
let config_path = config_home.join("panorama.toml");
// first shot
{
let config = Config::from_file(&config_path).await?;
config_tx.send(config)?;
}
debug!("listening for inotify events");
loop {
use notify::EventKind;
let event = rx.recv()?;
debug!("notify event: {:?}", event);
match event.kind {
EventKind::Create(_) | EventKind::Modify(_) => {
let path_expect = config_home
.clone()
.join("panorama.toml")
.canonicalize()
.context("osu")?;
if !path_expect.exists() {
debug!("path {:?} doesn't exist", path_expect);
continue;
}
match event.paths.iter().find(|p| *p == &path_expect) {
Some(path) => path.to_path_buf(),
None => continue,
};
// TODO: any better way to do this?
let config_path_c = config_path.canonicalize().context("cfg_path")?;
if config_path_c != path_expect {
debug!("did not match {:?} {:?}", config_path_c, path_expect);
continue;
}
debug!("reading config from {:?}", path_expect);
let config = Config::from_file(path_expect).await.context("read")?;
// debug!("sending config {:?}", config);
config_tx.send(config)?;
}
_ => {}
}
}
}

15
daemon/src/exit.rs Normal file
View file

@ -0,0 +1,15 @@
use tokio::sync::oneshot;
/// Receiver whose sole purpose is to receive an "exit" notification.
///
/// This exit "pattern", along with message passing over channels, allows
/// panorama to introspect on running loops. For example, a server listen loop
/// would select over the `ExitListener`, and break the loop once it receives
/// something on that channel. Then it would perform any clean up it needs and
/// exit, returning any resources that can be reused.
///
/// This is useful, for example, during TLS upgrade with STARTTLS, where the
/// connection needs to stay open. We can send the existing loop an "exit"
/// notification, then it returns the open channel so we can perform TLS
/// negotiation and create a new tunneled connection.
pub type ExitListener = oneshot::Receiver<()>;

188
daemon/src/lib.rs Normal file
View file

@ -0,0 +1,188 @@
//! Library functions used by the panorama daemon.
// #![deny(missing_docs)]
#[macro_use]
extern crate serde;
#[macro_use]
extern crate anyhow;
#[macro_use]
extern crate futures;
#[macro_use]
extern crate log;
#[macro_use]
extern crate derivative;
pub mod config;
pub mod mail;
mod exit;
mod service;
use std::path::PathBuf;
use anyhow::{Context, Result};
use clap::Parser;
use futures::future::FutureExt;
use tokio::{
fs::{self, OpenOptions},
sync::{mpsc, oneshot},
};
use xdg::BaseDirectories;
use crate::config::{Config, MailAccountConfig};
pub use crate::exit::ExitListener;
use crate::mail::{mail_main, MailStore};
/// The panorama daemon runs in the background and communicates with other
/// panorama components over Unix sockets.
#[derive(Debug, Parser)]
pub struct Options {
/// Config file path (defaults to XDG)
#[clap(long = "config", short = 'c')]
pub config_file: Option<PathBuf>,
/// Verbose mode (-v, -vv, -vvv, etc)
#[clap(short = 'v', long = "verbose", parse(from_occurrences))]
pub verbose: usize,
}
/// Primary entrypoint; this is the function that is called by main.
///
/// The purpose of this function is to parse command line arguments
/// and set up config watching, then call [`run_with_config`] with the config.
pub async fn run(opt: Options) -> Result<()> {
// if we're using a config-watcher, then start the watcher system
#[cfg(feature = "config-watch")]
{
let (_, mut config_watcher) = config::spawn_config_watcher_system()?;
loop {
let (exit_tx, exit_rx) = oneshot::channel();
let new_config = config_watcher.borrow().clone();
tokio::spawn(run_with_config(new_config, exit_rx));
// wait till the config has changed, then tell the current thread to
// stop
config_watcher.changed().await?;
let _ = exit_tx.send(());
}
}
// TODO: handle SIGHUP on Unix? pretty common for systemd to send this when
// reloading config files
// if not, just read the config once and run the daemon
#[cfg(not(feature = "config-watch"))]
{
let xdg = BaseDirectories::new()?;
let config_home = xdg.get_config_home().join("panorama");
if !config_home.exists() {
fs::create_dir_all(&config_home).await?;
}
let config_path = config_home.join("panorama.toml");
let config_path_c = config_path.canonicalize().context("cfg_path")?;
let config = Config::from_file(config_path_c).await.context("read")?;
let (_, exit_rx) = oneshot::channel();
run_with_config(config, exit_rx).await
}
}
async fn run_with_config(config: Config, exit: ExitListener) -> Result<()> {
debug!("New config: {:?}", config);
// keep track of which threads need to be stopped when this function is
// stopped
let mut notify_mail_threads = Vec::new();
for (account_name, account) in config.mail_accounts {
let (exit_tx, exit_rx) = oneshot::channel();
tokio::spawn(async {
match run_single_mail_account(account_name, account, exit_rx).await {
Ok(_) => {}
Err(err) => panic!("failed: {:?}", err),
}
});
notify_mail_threads.push(exit_tx);
}
exit.await?;
for exit_tx in notify_mail_threads {
let _ = exit_tx.send(());
}
Ok(())
}
/// The main loop for a single mail account.
///
/// The exit listener may allow the loop to be interrupted by the outside. When
/// anything is received on the exit listener, the loop exits gracefully.
async fn run_single_mail_account(
account_name: String,
account: MailAccountConfig,
exit: ExitListener,
) -> Result<()> {
debug!("run_single_mail_account({}, {:?})", account_name, account);
let mut exit = exit.fuse();
let xdg = BaseDirectories::new()?;
let data_home = xdg.get_data_home().join("panorama");
if !data_home.exists() {
fs::create_dir_all(&data_home)
.await
.context("could not create config directory")?;
}
let db_path = data_home.join("db.sqlite3");
debug!("Opening database at path: {:?}", db_path);
if !db_path.exists() {
OpenOptions::new()
.create(true)
.write(true)
.open(&db_path)
.await
.context("could not touch db path")?;
}
let db_path = db_path
.canonicalize()
.context("could not canonicalize db path")?;
let store =
MailStore::open(format!("sqlite://{}", db_path.to_string_lossy()))
.await
.context("couldn't open mail store")?;
let (tx, mut rx) = mpsc::unbounded_channel();
let sync_fut = mail_main(&account_name, account, tx, store).fuse();
pin_mut!(sync_fut);
debug!("Mail account loop for {}.", account_name);
loop {
select! {
res = sync_fut => match res {
Ok(_) => {},
Err(err) => {
error!("mail_main died with: {:?}", err);
break;
}
},
evt_opt = rx.recv().fuse() => {
let evt = match evt_opt {
Some(evt) => evt,
None => break,
};
debug!("Event: {:?}", evt);
},
// we're being told to exit the loop
_ = exit => break,
}
}
debug!("disconnecting from account {}", account_name);
Ok(())
}

68
daemon/src/mail/mod.rs Normal file
View file

@ -0,0 +1,68 @@
#![allow(dead_code)]
mod sessions;
mod store;
mod sync;
use anyhow::Result;
use panorama_imap::{
client::ConfigBuilder,
pool::{ImapPool, PoolConfig},
};
use sqlx::migrate::Migrator;
use tokio::sync::mpsc::UnboundedSender;
use crate::{
config::{MailAccountConfig, TlsMethod},
mail::sync::run_sync_loop,
};
// pub use self::event::MailEvent;
#[derive(Debug)]
pub struct MailEvent;
pub use self::store::MailStore;
static MIGRATOR: Migrator = sqlx::migrate!();
/// The main function for the IMAP thread.
///
/// This spawns two processes:
/// - A background synchronization thread
/// - An event listener / handler
pub async fn mail_main(
acct_name: impl AsRef<str>,
acct: MailAccountConfig,
_mail2ui_tx: UnboundedSender<MailEvent>,
mail_store: MailStore,
) -> Result<()> {
let acct_name = acct_name.as_ref();
debug!(
"Starting main synchronization procedure for account '{}'",
acct_name
);
// create a connection pool
let client_config = ConfigBuilder::default()
.hostname(acct.imap.server.clone())
.port(acct.imap.port)
.tls(matches!(acct.imap.tls, TlsMethod::On))
.build()?;
let pool_config = PoolConfig {
auth_config: acct.imap.auth,
client_config,
max_connections: 10,
};
let pool = ImapPool::new(pool_config);
// grab one connection from that pool and start running a background
// synchronization thread
let sync_conn = pool.acquire().await?;
let sync_loop = run_sync_loop(acct_name, sync_conn, mail_store);
// let the rest of the pool respond to requests coming from the channel
// TODO:
sync_loop.await?;
Ok(())
}

View file

@ -0,0 +1 @@
// TODO: figure out what sessions I actually want

51
daemon/src/mail/store.rs Normal file
View file

@ -0,0 +1,51 @@
use anyhow::{Context, Result};
use panorama_imap::proto::response::{Mailbox, MessageAttribute};
use sqlx::sqlite::{SqlitePool, SqlitePoolOptions};
use super::MIGRATOR;
#[derive(Clone)]
pub struct MailStore {
pool: SqlitePool,
}
impl MailStore {
/// Creates a new store tied to a SQLite database.
pub async fn open(uri: impl AsRef<str>) -> Result<Self> {
let uri = uri.as_ref();
let pool = SqlitePoolOptions::new().connect(uri).await?;
// run migrations, if available
MIGRATOR.run(&pool).await.with_context(|| {
format!("could not run migrations on the pool at {}", uri)
})?;
Ok(MailStore { pool })
}
pub async fn store_email(
&self,
acct_name: impl AsRef<str>,
mailbox: &Mailbox,
uid: u32,
uidvalidity: u32,
attrs: Vec<MessageAttribute>,
) -> Result<()> {
let acct_name = acct_name.as_ref();
sqlx::query(
r#"
INSERT INTO messages
(mailbox_acct, mailbox, uid, uidvalidity)
VALUES ($1, $2, $3, $4)
"#,
)
.bind(acct_name)
.bind(mailbox.to_string())
.bind(uid)
.bind(uidvalidity)
.execute(&self.pool)
.await
.context("could not insert message into store")?;
Ok(())
}
}

165
daemon/src/mail/sync.rs Normal file
View file

@ -0,0 +1,165 @@
use anyhow::{Context, Result};
use futures::{StreamExt, TryStreamExt};
use panorama_imap::{
client::ClientAuthenticated,
proto::{
command::FetchItems,
response::{MailboxData, Response},
},
};
use super::MailStore;
pub async fn run_sync_loop(
acct_name: impl AsRef<str>,
mut conn: ClientAuthenticated,
mail_store: MailStore,
) -> Result<()> {
let acct_name = acct_name.as_ref();
// get the list of folders first
debug!("Retrieving folder list...");
let folder_list = conn.list().await?;
debug!("Mailbox list: {:?}", folder_list);
// let _ = mail2ui_tx.send(MailEvent::FolderList(
// acct_name.clone(),
// folder_list.clone(),
// ));
for folder in folder_list.iter() {
debug!("folder: {:?}", folder);
let select = conn.select("INBOX").await?;
debug!("select response: {:?}", select);
if let (Some(_exists), Some(uidvalidity)) =
(select.exists, select.uid_validity)
{
// figure out which uids don't exist locally yet
// let new_uids = vec![];
// let new_uids =
// stream::iter(1..exists).map(Ok).try_filter_map(|uid| {
// todo!()
// // mail_store.try_identify_email(&acct_name, &folder,
// uid, uidvalidity, None) // //
// invert the option to only select uids that
// haven't been downloaded //
// .map_ok(move |o| o.map_or_else(move || Some(uid), |v| None))
// // .map_err(|err| err.context("error checking if
// the email is already downloaded
// [try_identify_email]")) }).try_collect::
// <Vec<_>>().await?;
if true {
// !new_uids.is_empty() {
// debug!("fetching uids {:?}", new_uids);
let fetched = conn
.uid_fetch(&[], &[1..200], FetchItems::Envelope)
.await
.context("error fetching uids")?;
fetched
.map(Ok)
.try_for_each_concurrent(None, |(uid, attrs)| {
debug!("GOT MESSAGE {} {:?}", uid, attrs);
mail_store.store_email(&acct_name, folder, uid, uidvalidity, attrs)
})
.await
.context("error during fetch-store")?;
}
}
}
tokio::time::sleep(std::time::Duration::from_secs(50)).await;
// TODO: remove this later
// continue;
// let's just select INBOX for now, maybe have a config for default
// mailbox later?
debug!("selecting the INBOX mailbox");
let select = conn.select("INBOX").await?;
debug!("select result: {:?}", select);
loop {
let message_uids = conn.uid_search().await?;
let message_uids = message_uids.into_iter().take(30).collect::<Vec<_>>();
// let _ = mail2ui_tx.send(MailEvent::MessageUids(
// acct_name.clone(),
// message_uids.clone(),
// ));
// TODO: make this happen concurrently with the main loop?
let mut message_list = conn
.uid_fetch(&message_uids, &[], FetchItems::All)
.await
.unwrap();
while let Some((_uid, _attrs)) = message_list.next().await {
// let evt = MailEvent::UpdateUid(acct_name.clone(), uid,
// attrs); TODO: probably odn't care about this?
// let _ = mail2ui_tx.send(evt);
}
// TODO: check if IDLE is supported
let supports_idle = true; // authed.has_capability("IDLE").await?;
if supports_idle {
let mut idle_stream = conn.idle().await?;
loop {
let evt = match idle_stream.next().await {
Some(v) => v,
None => break,
};
debug!("got an event: {:?}", evt);
match evt {
Response::MailboxData(MailboxData::Exists(uid)) => {
debug!("NEW MESSAGE WITH UID {:?}, droping everything", uid);
// send DONE to stop the idle
std::mem::drop(idle_stream);
// let handle = Notification::new()
// .summary("New Email")
// .body("TODO")
// .icon("firefox")
// .timeout(Timeout::Milliseconds(6000))
// .show()?;
let message_uids = conn.uid_search().await?;
let message_uids =
message_uids.into_iter().take(20).collect::<Vec<_>>();
// let _ = mail2ui_tx.send(MailEvent::MessageUids(
// acct_name.clone(),
// message_uids.clone(),
// ));
// TODO: make this happen concurrently with the main
// loop?
let mut message_list = conn
.uid_fetch(&message_uids, &[], FetchItems::All)
.await
.unwrap();
while let Some((_uid, _attrs)) = message_list.next().await {
// let evt = MailEvent::UpdateUid(acct_name.
// clone(), uid, attrs);
// debug!("sent {:?}", evt);
// mail2ui_tx.send(evt);
}
idle_stream = conn.idle().await?;
}
_ => {}
}
}
} else {
loop {
tokio::time::sleep(std::time::Duration::from_secs(20)).await;
debug!("heartbeat");
}
}
if false {
break;
}
}
// wait a bit so we're not hitting the server really fast if the fail
// happens early on
//
// TODO: some kind of smart exponential backoff that considers some time
// threshold to be a failing case?
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
Ok(())
}

18
daemon/src/main.rs Normal file
View file

@ -0,0 +1,18 @@
use anyhow::Result;
use clap::Parser;
use panorama_daemon::Options;
#[tokio::main]
async fn main() -> Result<()> {
let opt = Options::parse();
stderrlog::new()
.module(module_path!())
.module("panorama_daemon")
.module("panorama_imap")
.verbosity(opt.verbose)
.init()
.unwrap();
panorama_daemon::run(opt).await
}

4
daemon/src/service.rs Normal file
View file

@ -0,0 +1,4 @@
pub trait Service<Request> {
type Response;
type Error;
}

23
deny.toml Normal file
View file

@ -0,0 +1,23 @@
targets = [ { triple = "x86_64-unknown-linux-gnu" }, ]
[advisories]
db-urls = ["https://github.com/rustsec/advisory-db"]
vulnerability = "deny"
unmaintained = "warn"
yanked = "deny"
notice = "warn"
[licenses]
unlicensed = "deny"
default = "deny"
copyleft = "allow"
allow-osi-fsf-free = "either"
[[licenses.clarify]]
name = "ring"
version = "*"
expression = "MIT AND ISC AND OpenSSL"
license-files = [ { path = "LICENSE", hash = 0xbd0eed23 } ]

13
docker-compose.yml Normal file
View file

@ -0,0 +1,13 @@
version: "3"
services:
mail:
image: greenmail/standalone
ports:
- "3025:3025" # SMTP
- "3143:3143" # IMAP
- "3465:3465" # SMTPS
- "3993:3993" # IMAPS
- "3080:8080" # Web
environment:
- "GREENMAIL_OPTS=-Dgreenmail.setup.test.all -Dgreenmail.users=user:pass -Dgreenmail.verbose"

11
docs/SUMMARY.md Normal file
View file

@ -0,0 +1,11 @@
# Summary
- [Front](./front.md)
---
# Daemon
- [Daemon](./daemon/index.md)
- [API](./daemon/api.md)
- [Hooks](./daemon/hooks.md)

View file

@ -2,5 +2,5 @@
authors = ["Michael Zhang"] authors = ["Michael Zhang"]
language = "en" language = "en"
multilingual = false multilingual = false
src = "src" src = "."
title = "panorama docs" title = "panorama"

56
docs/daemon/api.md Normal file
View file

@ -0,0 +1,56 @@
# Daemon API
To communicate with the daemon start by connecting to the socket it exposes.
This opens a long-lasting connection that can be used to send RPC messages.
## Authentication
If connecting over a network rather than a socket, the client should
authenticate in order to talk to panorama at all. The framework for this is _TLS
client authentication_.
### Namespace `panorama::auth`
TODO:
## Standard API
### Namespace `panorama::mail`
#### `listen-receive`
```
(account : Option<String>) -> Stream<MessageNotification>
```
Begin subscribing to when mail is received for a particular account if provided,
or all accounts by default.
#### `send`
```
(message : SendMessage) -> Result<()>
```
Send an email. If the send fails the result is returned immediately without
retry.
TODO: send with retry?
#### `search`
```
(query : StructuredQuery) -> Result<SearchResultPage>
```
Search for messages, returns a summary of messages + first sentence.
## Extensions
Since extensions may be separate processes, they must also communicate with the
daemon, but since the daemon is responsible for launching them, they don't have
to connect to the socket explicitly.
### Namespace `panorama::extensions`

1
docs/daemon/hooks.md Normal file
View file

@ -0,0 +1 @@
# Hooks

32
docs/daemon/index.md Normal file
View file

@ -0,0 +1,32 @@
# Daemon
The panorama daemon runs locally and serves as the primary controller of all of
panorama's functions. Since it needs to be ready to listen for clients at any
time, it should remain running in the background.
Planned functionality:
- Email
- Synchronizes with mail servers, aggregating a local database of messages.
- Build a comprehensive and full-text search index over all local messages.
- Send email by communicating with SMTP servers.
- Calendar
- Import ical files.
- Send reminders to various outputs.
- Contact book
- Birthday calendar? Gotta figure out how virtual calendars should work
Stretch goals:
- General
- Extensions by way of running a subprocess, should be able to register
namespaced message types.
- Email
- Expose a JMAP API, allowing other clients to connect to it.
- Massively configurable hooks.
- Chat???
- IRC / Matrix support possibly
- Arbitrary object storage?
- Probably gives extensions a good way of storing data. See y.js
- Recipe book, grocery list, fitness tracking from apps, etc.
- Synchronizing with other peers??? Great for shared grocery list

3
docs/front.md Normal file
View file

@ -0,0 +1,3 @@
# Front

View file

@ -1,3 +0,0 @@
# Summary
- [Chapter 1](./chapter_1.md)

View file

@ -1 +0,0 @@
# Chapter 1

View file

53
imap/Cargo.toml Normal file
View file

@ -0,0 +1,53 @@
[package]
name = "panorama-imap"
description = "IMAP protocol implementation with high-level async client."
version = "0.0.4"
edition = "2018"
authors = ["Michael Zhang <mail@mzhang.io>"]
keywords = ["imap", "email", "parser"]
license = "GPL-3.0-or-later"
categories = ["email"]
repository = "https://git.mzhang.io/michael/panorama"
documentation = "https://docs.rs/panorama-imap"
readme = "README.md"
workspace = ".."
[features]
default = ["serialize", "pool", "rfc2177", "rfc6154"]
low-level = []
serialize = ["serde/derive"]
pool = ["crossbeam"]
rfc2087 = [] # quota
rfc2177 = [] # idle
rfc4315 = [] # uidplus
rfc6154 = [] # list
fuzzing = ["arbitrary", "panorama-proto-common/fuzzing"]
[dependencies]
anyhow = { version = "1.0.45", features = ["backtrace"] }
async-trait = "0.1.51"
bitflags = "1.3.2"
bytes = "1.1.0"
chrono = "0.4.19"
derivative = "2.2.0"
derive_builder = "0.10.2"
format-bytes = "0.2.2"
futures = "0.3.17"
log = "0.4.14"
nom = "7.0.0"
stderrlog = { version = "0.5.1", optional = true }
tokio = { version = "1.13.0", features = ["full"] }
tokio-rustls = { version = "0.23.1", features = ["dangerous_configuration"] }
tokio-util = { version = "0.6.9", features = ["codec"] }
webpki-roots = "0.22.1"
panorama-proto-common = { path = "../proto-common" }
# for fuzzing
arbitrary = { version = "1.0.2", optional = true, features = ["derive"] }
crossbeam = { version = "0.8.1", optional = true }
serde = { version = "1.0.130", optional = true }
[dev-dependencies]
maplit = "1.0.2"

3
imap/README.md Normal file
View file

@ -0,0 +1,3 @@
panorama-imap
===

4
imap/fuzz/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
target
corpus
artifacts

943
imap/fuzz/Cargo.lock generated Normal file
View file

@ -0,0 +1,943 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "anyhow"
version = "1.0.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28ae2b3dec75a406790005a200b1bd89785afc02517a00ca99ecfe093ee9e6cf"
[[package]]
name = "arbitrary"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "237430fd6ed3740afe94eefcc278ae21e050285be882804e0d6e8695f0c94691"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "arrayvec"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b"
[[package]]
name = "async-trait"
version = "0.1.51"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44318e776df68115a881de9a8fd1b9e53368d7a4a5ce4cc48517da3393233a5e"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "autocfg"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "base64"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitvec"
version = "0.19.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8942c8d352ae1838c9dda0b0ca2ab657696ef2232a20147cf1b30ae1a9cb4321"
dependencies = [
"funty",
"radium",
"tap",
"wyz",
]
[[package]]
name = "bstr"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a40b47ad93e1a5404e6c18dec46b628214fee441c70f4ab5d6942142cc268a3d"
dependencies = [
"lazy_static",
"memchr",
"regex-automata",
]
[[package]]
name = "bumpalo"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c59e7af012c713f529e7a3ee57ce9b31ddd858d4b512923602f74608b009631"
[[package]]
name = "bytes"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b700ce4376041dcd0a327fd0097c41095743c4c8af8887265942faf1100bd040"
[[package]]
name = "cc"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e70cc2f62c6ce1868963827bd677764c62d07c3d9a3e1fb1177ee1a9ab199eb2"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73"
dependencies = [
"libc",
"num-integer",
"num-traits",
"time",
"winapi",
]
[[package]]
name = "darling"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f2c43f534ea4b0b049015d00269734195e6d3f0f6635cb692251aca6f9f8b3c"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e91455b86830a1c21799d94524df0845183fa55bafd9aa137b01c7d1065fa36"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn",
]
[[package]]
name = "darling_macro"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29b5acf0dea37a7f66f7b25d2c5e93fd46f8f6968b1a5d7a3e02e97768afc95a"
dependencies = [
"darling_core",
"quote",
"syn",
]
[[package]]
name = "derivative"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "derive_arbitrary"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f1281ee141df08871db9fe261ab5312179eac32d1e314134ceaa8dd7c042f5a"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "derive_builder"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d13202debe11181040ae9063d739fa32cfcaaebe2275fe387703460ae2365b30"
dependencies = [
"derive_builder_macro",
]
[[package]]
name = "derive_builder_core"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66e616858f6187ed828df7c64a6d71720d83767a7f19740b2d1b6fe6327b36e5"
dependencies = [
"darling",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "derive_builder_macro"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58a94ace95092c5acb1e97a7e846b310cfbd499652f72297da7493f618a98d73"
dependencies = [
"derive_builder_core",
"syn",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "format-bytes"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c4e89040c7fd7b4e6ba2820ac705a45def8a0c098ec78d170ae88f1ef1d5762"
dependencies = [
"format-bytes-macros",
"proc-macro-hack",
]
[[package]]
name = "format-bytes-macros"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05089e341a0460449e2210c3bf7b61597860b07f0deae58da38dbed0a4c6b6d"
dependencies = [
"proc-macro-hack",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "funty"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fed34cd105917e91daa4da6b3728c47b068749d6a62c59811f06ed2ac71d9da7"
[[package]]
name = "futures"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1adc00f486adfc9ce99f77d717836f0c5aa84965eb0b4f051f4e83f7cab53f8b"
dependencies = [
"futures-channel",
"futures-core",
"futures-executor",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-channel"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74ed2411805f6e4e3d9bc904c95d5d423b89b3b25dc0250aa74729de20629ff9"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
name = "futures-core"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af51b1b4a7fdff033703db39de8802c673eb91855f2e0d47dcf3bf2c0ef01f99"
[[package]]
name = "futures-executor"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d0d535a57b87e1ae31437b892713aee90cd2d7b0ee48727cd11fc72ef54761c"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b0e06c393068f3a6ef246c75cdca793d6a46347e75286933e5e75fd2fd11582"
[[package]]
name = "futures-macro"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c54913bae956fb8df7f4dc6fc90362aa72e69148e3f39041fbe8742d21e0ac57"
dependencies = [
"autocfg",
"proc-macro-hack",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "futures-sink"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0f30aaa67363d119812743aa5f33c201a7a66329f97d1a887022971feea4b53"
[[package]]
name = "futures-task"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbe54a98670017f3be909561f6ad13e810d9a51f3f061b902062ca3da80799f2"
[[package]]
name = "futures-util"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67eb846bfd58e44a8481a00049e82c43e0ccb5d61f8dc071057cb19249dd4d78"
dependencies = [
"autocfg",
"futures-channel",
"futures-core",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"memchr",
"pin-project-lite",
"pin-utils",
"proc-macro-hack",
"proc-macro-nested",
"slab",
]
[[package]]
name = "hermit-abi"
version = "0.1.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
dependencies = [
"libc",
]
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "instant"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bee0328b1209d157ef001c94dd85b4f8f64139adb0eac2659f4b08382b2f474d"
dependencies = [
"cfg-if",
]
[[package]]
name = "js-sys"
version = "0.3.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4bf49d50e2961077d9c99f4b7997d770a1114f087c3c2e0069b36c13fc2979d"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "lexical-core"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6607c62aa161d23d17a9072cc5da0be67cdfc89d3afb1e8d9c842bebc2525ffe"
dependencies = [
"arrayvec",
"bitflags",
"cfg-if",
"ryu",
"static_assertions",
]
[[package]]
name = "libc"
version = "0.2.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1fa8cddc8fbbee11227ef194b5317ed014b8acbf15139bd716a18ad3fe99ec5"
[[package]]
name = "libfuzzer-sys"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36a9a84a6e8b55dfefb04235e55edb2b9a2a18488fcae777a6bdaa6f06f1deb3"
dependencies = [
"arbitrary",
"cc",
"once_cell",
]
[[package]]
name = "lock_api"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0382880606dff6d15c9476c416d18690b72742aa7b605bb6dd6ec9030fbf07eb"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710"
dependencies = [
"cfg-if",
]
[[package]]
name = "memchr"
version = "2.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525"
[[package]]
name = "mio"
version = "0.7.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c2bdb6314ec10835cd3293dd268473a835c02b7b352e788be788b3c6ca6bb16"
dependencies = [
"libc",
"log",
"miow",
"ntapi",
"winapi",
]
[[package]]
name = "miow"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21"
dependencies = [
"winapi",
]
[[package]]
name = "nom"
version = "6.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c5c51b9083a3c620fa67a2a635d1ce7d95b897e957d6b28ff9a5da960a103a6"
dependencies = [
"bitvec",
"funty",
"lexical-core",
"memchr",
"version_check",
]
[[package]]
name = "ntapi"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6bb902e437b6d86e03cce10a7e2af662292c5dfef23b65899ea3ac9354ad44"
dependencies = [
"winapi",
]
[[package]]
name = "num-integer"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db"
dependencies = [
"autocfg",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290"
dependencies = [
"autocfg",
]
[[package]]
name = "num_cpus"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3"
dependencies = [
"hermit-abi",
"libc",
]
[[package]]
name = "once_cell"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56"
[[package]]
name = "panorama-imap"
version = "0.0.4"
dependencies = [
"anyhow",
"arbitrary",
"async-trait",
"bitflags",
"bytes",
"chrono",
"derivative",
"derive_builder",
"format-bytes",
"futures",
"log",
"nom",
"panorama-proto-common",
"tokio",
"tokio-rustls",
"tokio-util",
"webpki-roots",
]
[[package]]
name = "panorama-imap-fuzz"
version = "0.0.0"
dependencies = [
"format-bytes",
"libfuzzer-sys",
"panorama-imap",
"panorama-proto-common",
]
[[package]]
name = "panorama-proto-common"
version = "0.0.1"
dependencies = [
"anyhow",
"arbitrary",
"bstr",
"bytes",
"format-bytes",
"log",
"nom",
]
[[package]]
name = "parking_lot"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d7744ac029df22dca6284efe4e898991d28e3085c706c972bcd7da4a27a15eb"
dependencies = [
"instant",
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7a782938e745763fe6907fc6ba86946d72f49fe7e21de074e08128a99fb018"
dependencies = [
"cfg-if",
"instant",
"libc",
"redox_syscall",
"smallvec",
"winapi",
]
[[package]]
name = "pin-project-lite"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d31d11c69a6b52a174b42bdc0c30e5e11670f90788b2c471c31c1d17d449443"
[[package]]
name = "pin-utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "proc-macro-hack"
version = "0.5.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5"
[[package]]
name = "proc-macro-nested"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc881b2c22681370c6a780e47af9840ef841837bc98118431d4e1868bd0c1086"
[[package]]
name = "proc-macro2"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c7ed8b8c7b886ea3ed7dde405212185f423ab44682667c8c6dd14aa1d9f6612"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7"
dependencies = [
"proc-macro2",
]
[[package]]
name = "radium"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "941ba9d78d8e2f7ce474c015eea4d9c6d25b6a3327f9832ee29a4de27f91bbb8"
[[package]]
name = "redox_syscall"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff"
dependencies = [
"bitflags",
]
[[package]]
name = "regex-automata"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132"
[[package]]
name = "ring"
version = "0.16.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc"
dependencies = [
"cc",
"libc",
"once_cell",
"spin",
"untrusted",
"web-sys",
"winapi",
]
[[package]]
name = "rustls"
version = "0.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35edb675feee39aec9c99fa5ff985081995a06d594114ae14cbe797ad7b7a6d7"
dependencies = [
"base64",
"log",
"ring",
"sct",
"webpki",
]
[[package]]
name = "ryu"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
[[package]]
name = "scopeguard"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "sct"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b362b83898e0e69f38515b82ee15aa80636befe47c3b6d3d89a911e78fc228ce"
dependencies = [
"ring",
"untrusted",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0"
dependencies = [
"libc",
]
[[package]]
name = "slab"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c307a32c1c5c437f38c7fd45d753050587732ba8628319fbdf12a7e289ccc590"
[[package]]
name = "smallvec"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe0f37c9e8f3c5a4a66ad655a93c74daac4ad00c441533bf5c6e7990bb42604e"
[[package]]
name = "spin"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "syn"
version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f58f7e8eaa0009c5fec437aabf511bd9933e4b2d7407bd05273c01a8906ea7"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "tap"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "time"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255"
dependencies = [
"libc",
"wasi",
"winapi",
]
[[package]]
name = "tokio"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01cf844b23c6131f624accf65ce0e4e9956a8bb329400ea5bcc26ae3a5c20b0b"
dependencies = [
"autocfg",
"bytes",
"libc",
"memchr",
"mio",
"num_cpus",
"once_cell",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"tokio-macros",
"winapi",
]
[[package]]
name = "tokio-macros"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54473be61f4ebe4efd09cec9bd5d16fa51d70ea0192213d754d2d500457db110"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio-rustls"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc6844de72e57df1980054b38be3a9f4702aba4858be64dd700181a8a6d0e1b6"
dependencies = [
"rustls",
"tokio",
"webpki",
]
[[package]]
name = "tokio-util"
version = "0.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1caa0b0c8d94a049db56b5acf8cba99dc0623aab1b26d5b5f5e2d945846b3592"
dependencies = [
"bytes",
"futures-core",
"futures-sink",
"log",
"pin-project-lite",
"tokio",
]
[[package]]
name = "unicode-xid"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
[[package]]
name = "untrusted"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
[[package]]
name = "version_check"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe"
[[package]]
name = "wasi"
version = "0.10.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
[[package]]
name = "wasm-bindgen"
version = "0.2.76"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ce9b1b516211d33767048e5d47fa2a381ed8b76fc48d2ce4aa39877f9f183e0"
dependencies = [
"cfg-if",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.76"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe8dc78e2326ba5f845f4b5bf548401604fa20b1dd1d365fb73b6c1d6364041"
dependencies = [
"bumpalo",
"lazy_static",
"log",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.76"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44468aa53335841d9d6b6c023eaab07c0cd4bddbcfdee3e2bb1e8d2cb8069fef"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.76"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0195807922713af1e67dc66132c7328206ed9766af3858164fb583eedc25fbad"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.76"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acdb075a845574a1fa5f09fd77e43f7747599301ea3417a9fbffdeedfc1f4a29"
[[package]]
name = "web-sys"
version = "0.3.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224b2f6b67919060055ef1a67807367c2066ed520c3862cc013d26cf893a783c"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "webpki"
version = "0.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea"
dependencies = [
"ring",
"untrusted",
]
[[package]]
name = "webpki-roots"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aabe153544e473b775453675851ecc86863d2a81d786d741f6b76778f2a48940"
dependencies = [
"webpki",
]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "wyz"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85e60b0d1b5f99db2556934e21937020776a5d31520bf169e851ac44e6420214"

29
imap/fuzz/Cargo.toml Normal file
View file

@ -0,0 +1,29 @@
[package]
name = "panorama-imap-fuzz"
version = "0.0.0"
authors = ["Automatically generated"]
publish = false
edition = "2018"
[package.metadata]
cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.4"
format-bytes = "0.2.2"
panorama-proto-common = { path = "../../proto-common" }
[dependencies.panorama-imap]
path = ".."
features = ["fuzzing"]
# Prevent this from interfering with workspaces
[workspace]
members = ["."]
[[bin]]
name = "parse_response"
path = "fuzz_targets/parse_response.rs"
test = false
doc = false

View file

@ -0,0 +1,16 @@
#![no_main]
use std::io::Cursor;
use format_bytes::write_bytes;
use libfuzzer_sys::fuzz_target;
use panorama_imap::proto::{response::Response, rfc3501::response};
use panorama_proto_common::Bytes;
fuzz_target!(|resp: Response| {
let data = Vec::new();
let mut curs = Cursor::new(data);
write_bytes!(&mut curs, b"{}", resp).unwrap();
let data = curs.into_inner();
let data = Bytes::from(data);
let _ = response(data);
});

View file

@ -0,0 +1,2 @@
target
out

1033
imap/imap-parsing-fuzz-target/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,11 @@
[package]
name = "imap-parsing-fuzz-target"
version = "0.1.0"
edition = "2018"
[workspace]
[dependencies]
afl = "*"
panorama-imap = { path = ".." }
panorama-proto-common = { path = "../../proto-common" }

View file

@ -0,0 +1 @@
* 4544444444 444

View file

@ -0,0 +1 @@
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH2 AUTH=PLAIN AUTH=PLAIN-CLIENTTOKEN AUTH=OAUTHBEARER AUTH=XOAUTH

View file

@ -0,0 +1 @@
* 8211 FETCH (UID 8390 FLAGS (\Answered \Seen))

View file

@ -0,0 +1 @@
* 8045 FETCH (UID 8225 ENVELOPE ("Sun, 21 Mar 2021 18:44:10 -0700" "SUBJECT" (("SENDER" NIL "sender" "example.com")) (("SENDER" NIL "sender" "example.com")) (("noreply" NIL "noreply" "example.com")) (("NAME" NIL "user" "gmail.com")) NIL NIL NIL "<HASH-99c91810@example.com>") FLAGS () INTERNALDATE "22-Mar-2021 01:44:12 +0000" RFC822.SIZE 13503)

View file

@ -0,0 +1 @@
* OK [PERMANENTFLAGS (\Answered \Flagged \Draft \Deleted \Seen $NotPhishing $Phishing \*)] Flags permitted.

View file

@ -0,0 +1 @@
* OK [HIGHESTMODSEQ 694968]

View file

@ -0,0 +1,11 @@
#[macro_use]
extern crate afl;
fn main() {
fuzz!(|data: &[u8]| {
use panorama_imap::proto::rfc3501::response;
use panorama_proto_common::Bytes;
let data = Bytes::from(data.to_vec());
let _ = response(data);
});
}

84
imap/src/client/auth.rs Normal file
View file

@ -0,0 +1,84 @@
use tokio::io::{AsyncRead, AsyncWrite};
use anyhow::Result;
use panorama_proto_common::Bytes;
use crate::client::inner::Inner;
use crate::interface::ImapClient;
use crate::proto::command::{Command, CommandLogin};
/// Method of authentication for the IMAP server
#[cfg_attr(
feature = "serialize",
derive(Serialize, Deserialize, Clone, Derivative)
)]
#[derivative(Debug)]
#[serde(tag = "auth")]
pub enum ImapAuth {
/// Use plain username/password authentication
#[serde(rename = "plain")]
Plain {
username: String,
#[derivative(Debug = "ignore")]
password: String,
},
}
impl ImapAuth {
pub async fn perform_auth<C>(&self, inner: &mut Inner<C>) -> Result<()>
where
C: Client,
{
match self {
ImapAuth::Plain { username, password } => {
let command = Command::Login(CommandLogin {
userid: Bytes::from(username.clone()),
password: Bytes::from(password.clone()),
});
inner.execute(command).await?;
Ok(())
}
}
}
}
pub trait Client:
AsyncRead + AsyncWrite + Unpin + Sync + Send + 'static
{
}
impl<C> Client for C where
C: Send + Sync + Unpin + AsyncWrite + AsyncRead + 'static
{
}
#[async_trait]
pub trait AuthMethod {
async fn perform_auth<C>(&self, inner: &mut Inner<C>) -> Result<()>
where
C: Client;
}
pub struct Login {
pub username: String,
pub password: String,
}
#[async_trait]
impl AuthMethod for Login {
async fn perform_auth<C>(&self, inner: &mut Inner<C>) -> Result<()>
where
C: Client,
{
let command = Command::Login(CommandLogin {
userid: Bytes::from(self.username.clone()),
password: Bytes::from(self.password.clone()),
});
let result = inner.execute(command).await?;
info!("result: {:?}", result.wait().await?);
Ok(())
}
}

332
imap/src/client/client.rs Normal file
View file

@ -0,0 +1,332 @@
use std::ops::Range;
use std::pin::Pin;
use std::task::{Context, Poll};
use anyhow::Result;
use futures::{
future::{self, FutureExt},
stream::{Stream, StreamExt},
};
use panorama_proto_common::Bytes;
use tokio::net::TcpStream;
use tokio_rustls::client::TlsStream;
use crate::proto::{
command::{
Command, CommandFetch, CommandList, CommandSearch, CommandSelect,
FetchItems, SearchCriteria, Sequence,
},
response::{
Condition, Flag, Mailbox, MailboxData, MailboxList, MessageAttribute,
Response, ResponseCode, Status,
},
};
use super::auth::{AuthMethod, ImapAuth};
use super::inner::Inner;
use super::response_stream::ResponseStream;
use super::tls::wrap_tls;
/// An IMAP client that hasn't been connected yet.
#[derive(Builder, Clone, Debug)]
pub struct Config {
/// The hostname of the IMAP server. If using TLS, must be an address
pub hostname: String,
/// The port of the IMAP server.
pub port: u16,
/// Whether or not the client is using an encrypted stream.
///
/// To upgrade the connection later, use the upgrade method.
#[builder(default = "true")]
pub tls: bool,
/// Whether or not to verify hostname
#[builder(default = "true")]
pub verify_hostname: bool,
}
impl Config {
pub fn builder() -> ConfigBuilder { ConfigBuilder::default() }
}
impl ConfigBuilder {
pub async fn open(&self) -> Result<ClientUnauthenticated> {
let config = self.build()?;
let hostname = config.hostname.as_ref();
let port = config.port;
trace!(
"connecting to {}:{} {}...",
hostname,
port,
if config.tls { "(encrypted)" } else { "" }
);
let conn = TcpStream::connect((hostname, port)).await?;
trace!("connected.");
if config.tls {
let conn = wrap_tls(conn, hostname).await?;
let mut inner = Inner::new(conn, config).await?;
inner.wait_for_greeting().await?;
debug!("received greeting");
return Ok(ClientUnauthenticated::Encrypted(inner));
} else {
let mut inner = Inner::new(conn, config).await?;
inner.wait_for_greeting().await?;
debug!("received greeting");
return Ok(ClientUnauthenticated::Unencrypted(inner));
}
}
}
/// A client that hasn't been authenticated.
pub enum ClientUnauthenticated {
Encrypted(Inner<TlsStream<TcpStream>>),
Unencrypted(Inner<TcpStream>),
}
impl ClientUnauthenticated {
pub async fn upgrade(self) -> Result<ClientUnauthenticated> {
match self {
// this is a no-op, we don't need to upgrade
ClientUnauthenticated::Encrypted(_) => Ok(self),
ClientUnauthenticated::Unencrypted(e) => {
Ok(ClientUnauthenticated::Encrypted(e.upgrade().await?))
}
}
}
pub async fn auth(self, auth: &ImapAuth) -> Result<ClientAuthenticated> {
match self {
// this is a no-op, we don't need to upgrade
ClientUnauthenticated::Encrypted(mut inner) => {
auth.perform_auth(&mut inner).await?;
Ok(ClientAuthenticated::Encrypted(inner))
}
ClientUnauthenticated::Unencrypted(mut inner) => {
auth.perform_auth(&mut inner).await?;
Ok(ClientAuthenticated::Unencrypted(inner))
}
}
}
client_expose!(async execute(cmd: Command) -> Result<ResponseStream>);
client_expose!(async has_capability(cap: impl AsRef<str>) -> Result<bool>);
}
/// A client that has been authenticated.
pub enum ClientAuthenticated {
Encrypted(Inner<TlsStream<TcpStream>>),
Unencrypted(Inner<TcpStream>),
}
impl ClientAuthenticated {
client_expose!(async execute(cmd: Command) -> Result<ResponseStream>);
client_expose!(async has_capability(cap: impl AsRef<str>) -> Result<bool>);
pub async fn search(&mut self) -> Result<()> {
let cmd = Command::Examine;
let res = self.execute(cmd).await?;
let (done, data) = res.wait().await?;
println!("done = {:?}", done);
println!("data = {:?}", data);
Ok(())
}
/// Runs the LIST command
pub async fn list(&mut self) -> Result<Vec<Mailbox>> {
let cmd = Command::List(CommandList {
reference: Bytes::from(""),
mailbox: Bytes::from("*"),
});
let res = self.execute(cmd).await?;
let (_, data) = res.wait().await?;
let mut folders = Vec::new();
for resp in data {
if let Response::MailboxData(MailboxData::List(MailboxList {
mailbox,
..
})) = resp
{
folders.push(mailbox);
}
}
Ok(folders)
}
/// Runs the SELECT command
pub async fn select(
&mut self,
mailbox: impl AsRef<str>,
) -> Result<SelectResponse> {
let cmd = Command::Select(CommandSelect {
mailbox: Bytes::from(mailbox.as_ref().to_owned()),
});
let stream = self.execute(cmd).await?;
let (_, data) = stream.wait().await?;
let mut select = SelectResponse::default();
for resp in data {
match resp {
Response::MailboxData(MailboxData::Flags(flags)) => {
select.flags = flags
}
Response::MailboxData(MailboxData::Exists(exists)) => {
select.exists = Some(exists)
}
Response::MailboxData(MailboxData::Recent(recent)) => {
select.recent = Some(recent)
}
Response::Tagged(
_,
Condition {
status: Status::Ok,
code: Some(code),
..
},
)
| Response::Condition(Condition {
status: Status::Ok,
code: Some(code),
..
}) => match code {
ResponseCode::Unseen(value) => select.unseen = Some(value),
ResponseCode::UidNext(value) => select.uid_next = Some(value),
ResponseCode::UidValidity(value) => select.uid_validity = Some(value),
_ => {}
},
_ => warn!("unknown response {:?}", resp),
}
}
Ok(select)
}
/// Runs the SEARCH command
pub async fn uid_search(&mut self) -> Result<Vec<u32>> {
let cmd = Command::UidSearch(CommandSearch {
criteria: SearchCriteria::all(),
});
let stream = self.execute(cmd).await?;
let (_, data) = stream.wait().await?;
for resp in data {
if let Response::MailboxData(MailboxData::Search(uids)) = resp {
return Ok(uids);
}
}
bail!("could not find the SEARCH response")
}
/// Runs the FETCH command
pub async fn fetch(
&mut self,
uids: &[u32],
uid_seqs: &[Range<u32>],
items: FetchItems,
) -> Result<impl Stream<Item = (u32, Vec<MessageAttribute>)>> {
let mut ids = Vec::new();
for uid in uids {
ids.push(Sequence::Single(*uid));
}
for seq in uid_seqs {
ids.push(Sequence::Range(seq.start, seq.end));
}
let cmd = Command::Fetch(CommandFetch { ids, items });
debug!("fetch: {:?}", cmd);
let stream = self.execute(cmd).await?;
// let (done, data) = stream.wait().await?;
Ok(stream.filter_map(|resp| match resp {
Response::Fetch(n, attrs) => future::ready(Some((n, attrs))).boxed(),
Response::Done(_) => future::ready(None).boxed(),
_ => future::pending().boxed(),
}))
}
/// Runs the UID FETCH command
pub async fn uid_fetch(
&mut self,
uids: &[u32],
uid_seqs: &[Range<u32>],
items: FetchItems,
) -> Result<impl Stream<Item = (u32, Vec<MessageAttribute>)>> {
let mut ids = Vec::new();
for uid in uids {
ids.push(Sequence::Single(*uid));
}
for seq in uid_seqs {
ids.push(Sequence::Range(seq.start, seq.end));
}
let cmd = Command::UidFetch(CommandFetch { ids, items });
debug!("uid fetch: {:?}", cmd);
let stream = self.execute(cmd).await?;
// let (done, data) = stream.wait().await?;
Ok(stream.filter_map(|resp| match resp {
Response::Fetch(n, attrs) => future::ready(Some((n, attrs))).boxed(),
Response::Done(_) => future::ready(None).boxed(),
_ => future::pending().boxed(),
}))
}
/// Runs the IDLE command
#[cfg(feature = "rfc2177")]
#[cfg_attr(docsrs, doc(cfg(feature = "rfc2177")))]
pub async fn idle(&mut self) -> Result<IdleToken> {
let cmd = Command::Idle;
let stream = self.execute(cmd).await?;
Ok(IdleToken { stream })
}
}
#[derive(Debug, Default)]
pub struct SelectResponse {
pub flags: Vec<Flag>,
pub exists: Option<u32>,
pub recent: Option<u32>,
pub uid_next: Option<u32>,
pub uid_validity: Option<u32>,
pub unseen: Option<u32>,
}
/// A token that represents an idling connection.
///
/// Dropping this token indicates that the idling should be completed, and the
/// DONE command will be sent to the server as a result.
#[cfg(feature = "rfc2177")]
#[cfg_attr(docsrs, doc(cfg(feature = "rfc2177")))]
pub struct IdleToken {
pub stream: ResponseStream,
// sender: mpsc::UnboundedSender<TaggedCommand>,
}
#[cfg(feature = "rfc2177")]
#[cfg_attr(docsrs, doc(cfg(feature = "rfc2177")))]
impl Drop for IdleToken {
fn drop(&mut self) {
// TODO: put this into a channel instead
// tokio::spawn(self.client.execute(Command::Done));
}
}
#[cfg(feature = "rfc2177")]
#[cfg_attr(docsrs, doc(cfg(feature = "rfc2177")))]
impl Stream for IdleToken {
type Item = Response;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context,
) -> Poll<Option<Self::Item>> {
let stream = Pin::new(&mut self.stream);
Stream::poll_next(stream, cx)
}
}

120
imap/src/client/codec.rs Normal file
View file

@ -0,0 +1,120 @@
use std::io::{self};
use bytes::{BufMut, BytesMut};
use nom::Needed;
use panorama_proto_common::{convert_error, Bytes};
use tokio_util::codec::{Decoder, Encoder};
use crate::proto::{
command::Command,
response::{Response, Tag},
rfc3501::response as parse_response,
};
/// A codec that can be used for decoding `Response`s and encoding `Command`s.
#[derive(Default)]
pub struct ImapCodec {
decode_need_message_bytes: usize,
}
impl<'a> Decoder for ImapCodec {
type Item = Response;
type Error = io::Error;
fn decode(
&mut self,
buf: &mut BytesMut,
) -> Result<Option<Self::Item>, io::Error> {
use nom::Err;
if self.decode_need_message_bytes > buf.len() {
return Ok(None);
}
// this is a pretty hot mess so here's my best attempt at explaining
// buf, or buf1, is the original message
// "split" mutably removes all the bytes from the self, and returns a
// new BytesMut with the contents. so buf2 now has all the
// original contents and buf1 is now empty
let buf2 = buf.split();
// now we're going to clone buf2 here, calling "freeze" turns the
// BytesMut back into Bytes so we can manipulate it. remember,
// none of this should be actually copying anything
let buf3 = buf2.clone().freeze();
debug!("going to parse a response since buffer len: {}", buf3.len());
// trace!("buf: {:?}", buf3);
// we don't know how long the message is going to be yet, so parse it
// out of the Bytes right now, and since the buffer is being
// consumed, subtracting the remainder of the string from the
// original total (buf4_len) will tell us how long the payload
// was. this also avoids unnecessary cloning
let buf4: Bytes = buf3.clone().into();
let buf4_len = buf4.len();
let (response, len) = match parse_response(buf4) {
Ok((remaining, response)) => (response, buf4_len - remaining.len()),
// the incomplete cases: set the decoded bytes and quit early
Err(nom::Err::Incomplete(Needed::Size(min))) => {
self.decode_need_message_bytes = min.get();
return Ok(None);
}
Err(nom::Err::Incomplete(_)) => {
return Ok(None);
}
// shit
Err(Err::Error(err)) | Err(Err::Failure(err)) => {
let buf4 = buf3.clone().into();
error!("failed to parse: {:?}", buf4);
error!("code: {}", convert_error(buf4, &err));
return Err(io::Error::new(
io::ErrorKind::Other,
format!("error during parsing of {:?}", buf),
));
}
};
info!("success, parsed as {:?}", response);
// "unsplit" is the opposite of split, we're getting back the original
// data here
buf.unsplit(buf2);
// and then move to after the message we just parsed
let first_part = buf.split_to(len);
trace!("parsed from: {:?}", first_part);
// since we're done parsing a complete message, set this to zero
self.decode_need_message_bytes = 0;
Ok(Some(response))
}
}
/// A command with its accompanying tag.
#[derive(Debug)]
pub struct TaggedCommand(pub Tag, pub Command);
impl<'a> Encoder<&'a TaggedCommand> for ImapCodec {
type Error = io::Error;
fn encode(
&mut self,
tagged_cmd: &TaggedCommand,
dst: &mut BytesMut,
) -> Result<(), io::Error> {
let tag = &*tagged_cmd.0 .0;
let command = &tagged_cmd.1;
dst.put(tag);
dst.put_u8(b' ');
// TODO: don't allocate here! use a stream writer
let cmd_bytes = format_bytes!(b"{}", command);
dst.extend_from_slice(cmd_bytes.as_slice());
// debug!("C>>>S: {:?}", dst);
Ok(())
}
}

361
imap/src/client/inner.rs Normal file
View file

@ -0,0 +1,361 @@
use std::collections::HashSet;
use std::sync::{
atomic::{AtomicU32, Ordering},
Arc,
};
use anyhow::{Context, Result};
use futures::{
future::{self, FutureExt, TryFutureExt},
stream::StreamExt,
};
use panorama_proto_common::Bytes;
use tokio::{
io::{
split, AsyncRead, AsyncWrite, AsyncWriteExt, BufWriter, ReadHalf, WriteHalf,
},
sync::{mpsc, oneshot, RwLock},
task::JoinHandle,
};
use tokio_rustls::client::TlsStream;
use tokio_util::codec::FramedRead;
use crate::proto::{
command::Command,
response::{Capability, Condition, Response, Status, Tag},
rfc3501::capability as parse_capability,
};
use super::client::Config;
use super::codec::{ImapCodec, TaggedCommand};
use super::response_stream::ResponseStream;
use super::tls::wrap_tls;
const TAG_PREFIX: &str = "panotag";
type ExitSender = oneshot::Sender<()>;
type ExitListener = oneshot::Receiver<()>;
type GreetingSender = oneshot::Sender<()>;
type GreetingWaiter = oneshot::Receiver<()>;
/// Low-level client, can directly read from and write to the stream
/// without the additional type-safety of the higher-level state machine.
pub struct Inner<C> {
config: Config,
tag_number: AtomicU32,
command_tx: mpsc::UnboundedSender<CommandContainer>,
read_exit: ExitSender,
read_handle: JoinHandle<ReadHalf<C>>,
write_exit: ExitSender,
write_handle: JoinHandle<WriteHalf<C>>,
_write_tx: mpsc::UnboundedSender<TaggedCommand>,
greeting_rx: Option<GreetingWaiter>,
capabilities: Arc<RwLock<Option<HashSet<Capability>>>>,
}
#[derive(Debug)]
struct CommandContainer {
tag: Tag,
command: Command,
channel: mpsc::UnboundedSender<Response>,
}
impl<C> Inner<C>
where
C: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
pub async fn new(c: C, config: Config) -> Result<Self> {
let (command_tx, command_rx) = mpsc::unbounded_channel();
// break the stream of bytes into a reader and a writer
// the read_half represents the server->client connection
// the write_half represents the client->server connection
let (read_half, write_half) = split(c);
// this channel is used to inform clients when we receive the
// initial greeting from the server
let (greeting_tx, greeting_rx) = oneshot::channel();
// spawn the server->client loop
let (read_exit, exit_rx) = oneshot::channel();
let (write_tx, write_rx) = mpsc::unbounded_channel(); // TODO: maybe an arbitrary/configurable limit here would be better?
let read_handle = tokio::spawn(read_loop(
read_half,
exit_rx,
greeting_tx,
write_tx.clone(),
command_rx,
));
// spawn the client->server loop
let (write_exit, exit_rx) = oneshot::channel();
let write_handle = tokio::spawn(write_loop(write_half, exit_rx, write_rx));
let tag_number = AtomicU32::new(0);
let capabilities = Arc::new(RwLock::new(None));
Ok(Inner {
config,
tag_number,
command_tx,
read_exit,
read_handle,
write_exit,
write_handle,
_write_tx: write_tx,
greeting_rx: Some(greeting_rx),
capabilities,
})
}
pub async fn execute(&mut self, command: Command) -> Result<ResponseStream> {
let id = self.tag_number.fetch_add(1, Ordering::SeqCst);
let tag = Tag(Bytes::from(format!("{}{}", TAG_PREFIX, id)));
let (channel, rx) = mpsc::unbounded_channel();
self.command_tx.send(CommandContainer {
tag,
command,
channel,
})?;
let stream = ResponseStream { inner: rx };
Ok(stream)
}
pub async fn has_capability(&mut self, cap: impl AsRef<str>) -> Result<bool> {
let mut cap_slice = cap.as_ref().as_bytes().to_vec();
// since we're doing incremental parsing, we have to finish this off
// with something that's invalid
cap_slice.push(b'\n');
let cap_bytes = Bytes::from(cap_slice);
trace!("CAP_BYTES: {:?}", cap_bytes);
let (_, cap) =
parse_capability(cap_bytes).context("could not parse capability")?;
let contains = {
let read = self.capabilities.read().await;
if let Some(read) = &*read {
read.contains(&cap)
} else {
std::mem::drop(read);
let cmd = self.execute(Command::Capability).await?;
let (_, res) = cmd.wait().await?;
let mut capabilities = HashSet::new();
// todo!("done: {:?} {:?}", done, res);
for caps in res.iter().filter_map(|res| match res {
Response::Capabilities(caps) => Some(caps),
_ => None,
}) {
capabilities.extend(caps.clone());
}
let mut write = self.capabilities.write().await;
*write = Some(capabilities);
true
}
};
Ok(contains)
}
pub async fn upgrade(mut self) -> Result<Inner<TlsStream<C>>> {
debug!("preparing to upgrade using STARTTLS");
// check that this capability exists
// if it doesn't exist, then it's not an IMAP4-compliant server
if !self
.has_capability("STARTTLS")
.await
.context("could not check starttls capability")?
{
bail!("Server does not have the STARTTLS capability");
}
// issue the STARTTLS command to the server
let resp = self
.execute(Command::Starttls)
.await
.context("could not send starttls command")?;
resp
.wait()
.await
.context("could not receive starttls response")?;
debug!("received OK from server");
// issue exit to the read loop and retrieve the read half
let _ = self.read_exit.send(());
let read_half = self
.read_handle
.await
.context("could not retrieve read half of connection")?;
// issue exit to the write loop and retrieve the write half
let _ = self.write_exit.send(());
let write_half = self
.write_handle
.await
.context("could not retrieve write half of connection")?;
// put the read half and write half back together
let stream = read_half.unsplit(write_half);
let tls_stream = wrap_tls(stream, &self.config.hostname)
.await
.context("could not initialize tls stream")?;
Inner::new(tls_stream, self.config)
.await
.context("could not construct new client")
}
pub async fn wait_for_greeting(&mut self) -> Result<()> {
if let Some(greeting_rx) = self.greeting_rx.take() {
greeting_rx.await?;
}
Ok(())
}
}
// exit is a channel that will notify this loop when some external
// even requires this loop to stop (for example, TLS upgrade).
//
// when the loop exits, the read half of the stream will be returned
async fn read_loop<C>(
stream: ReadHalf<C>,
exit: ExitListener,
greeting_tx: GreetingSender,
write_tx: mpsc::UnboundedSender<TaggedCommand>,
mut command_rx: mpsc::UnboundedReceiver<CommandContainer>,
) -> ReadHalf<C>
where
C: AsyncRead,
{
// this lets us "use up" the greeting sender
let mut greeting_tx = Some(greeting_tx);
let mut curr_cmd: Option<CommandContainer> = None;
// set up framed communication
let codec = ImapCodec::default();
let mut framed = FramedRead::new(stream, codec);
let exit = exit.fuse();
pin_mut!(exit);
loop {
debug!("READ LOOP ITER");
let next = framed.next().fuse();
pin_mut!(next);
// only listen for a new command if there isn't one already
let mut cmd_fut = if let Some(ref cmd) = curr_cmd {
debug!("current command: {:?}", cmd);
// if there is one, just make a future that never resolves so it'll
// always pick the other options in the select.
future::pending().boxed().fuse()
} else {
command_rx.recv().boxed().fuse()
};
select! {
// read a command from the command list
command = cmd_fut => {
if curr_cmd.is_none() {
if let Some(CommandContainer { ref tag, ref command, .. }) = command {
let _ = write_tx.send(TaggedCommand(tag.clone(), command.clone()));
// let cmd_str = format!("{} {:?}\r\n", tag, cmd);
// write_tx.send(cmd_str);
}
curr_cmd = command;
debug!("new command: {:?}", curr_cmd);
}
}
// new message from the server
resp = next => {
let resp = match resp {
Some(Ok(v)) => v,
a => { error!("failed: {:?}", a); todo!("fuck"); },
};
trace!("S>>>C: {:?}", resp);
// if this is the very first response, then it's a greeting
if let Some(greeting_tx) = greeting_tx.take() {
greeting_tx.send(()).unwrap();
}
if let Response::Done(_) = resp {
// since this is the DONE message, clear curr_cmd so another one can be sent
if let Some(CommandContainer { channel, .. }) = curr_cmd.take() {
let _ = channel.send(resp);
// debug!("res0: {:?}", res);
}
} else if let Response::Tagged(_, Condition { status: Status::Ok, ..}) = resp {
// clear curr_cmd so another one can be sent
if let Some(CommandContainer { channel, .. }) = curr_cmd.take() {
let _ = channel.send(resp);
// debug!("res0: {:?}", res);
}
} else if let Some(CommandContainer { channel, .. }) = curr_cmd.as_mut() {
// we got a response from the server for this command, so send it over the
// channel
// debug!("sending {:?} to tag {}", resp, tag);
let _res = channel.send(resp);
// debug!("res1: {:?}", res);
}
}
_ = exit => break,
}
}
framed.into_inner()
}
async fn write_loop<C>(
stream: WriteHalf<C>,
exit_rx: ExitListener,
mut command_rx: mpsc::UnboundedReceiver<TaggedCommand>,
) -> WriteHalf<C>
where
C: AsyncWrite,
{
// set up framed communication
// let codec = ImapCodec::default();
let mut stream = BufWriter::new(stream);
// let mut framed = FramedWrite::new(stream, codec);
let mut exit_rx = exit_rx.map_err(|_| ()).shared();
loop {
let command_fut = command_rx.recv().fuse();
pin_mut!(command_fut);
select! {
command = command_fut => {
// TODO: handle errors here
if let Some(command) = command {
let cmd = format_bytes!(b"{} {}\r\n", &*command.0.0, command.1);
debug!("sending command: {:?}", String::from_utf8_lossy(&cmd));
let _ = stream.write_all(&cmd).await;
let _ = stream.flush().await;
// let _ = framed.send(&command).await;
// let _ = framed.flush().await;
}
// let _ = stream.write_all(line.as_bytes()).await;
// let _ = stream.flush().await;
}
_ = exit_rx => break,
}
}
// framed.into_inner()
stream.into_inner()
}

17
imap/src/client/macros.rs Normal file
View file

@ -0,0 +1,17 @@
macro_rules! client_expose {
(
async
$fn_name:ident
$(< $($lifetime:lifetime)* >)?
( $($arg_name:ident : $ty:ty),* $(,)? )
$(-> $ret:ty)?
) => {
#[allow(dead_code)]
async fn $fn_name $(< $($lifetime)* >)? (&mut self, $($arg_name : $ty,)*) $(-> $ret)? {
match self {
Self::Encrypted(inner) => inner.$fn_name($($arg_name,)*).await,
Self::Unencrypted(inner) => inner.$fn_name($($arg_name,)*).await,
}
}
};
}

32
imap/src/client/mod.rs Normal file
View file

@ -0,0 +1,32 @@
//! High-level IMAP Client
//! ---
//!
//! ```no_run
//! # use panorama_imap::client::Config;
//! # async fn client() -> anyhow::Result<()> {
//! let client = Config::builder()
//! .hostname("your.domain".to_owned())
//! .port(993)
//! .open().await?;
//! # Ok(())
//! # }
//! ```
#[macro_use]
mod macros;
pub mod auth;
pub mod response_stream;
mod client;
mod codec;
mod inner;
mod tls;
pub use self::client::{
ClientAuthenticated, ClientUnauthenticated, Config, ConfigBuilder,
};
pub use self::codec::{ImapCodec, TaggedCommand};
#[cfg(feature = "low-level")]
pub use self::inner::Inner;

View file

@ -0,0 +1,51 @@
use std::pin::Pin;
use std::task::{Context, Poll};
use anyhow::Result;
use futures::stream::Stream;
use tokio::sync::mpsc;
use crate::proto::response::{Response, ResponseDone};
/// A series of responses that follow an
pub struct ResponseStream {
pub(crate) inner: mpsc::UnboundedReceiver<Response>,
}
impl ResponseStream {
/// Retrieves just the DONE item in the stream, discarding the rest
pub async fn done(mut self) -> Result<Option<ResponseDone>> {
while let Some(resp) = self.inner.recv().await {
if let Response::Done(done) = resp {
return Ok(Some(done));
}
}
Ok(None)
}
/// Waits for the entire stream to finish, returning the DONE status and the
/// stream
pub async fn wait(mut self) -> Result<(Option<ResponseDone>, Vec<Response>)> {
let mut done = None;
let mut vec = Vec::new();
while let Some(resp) = self.inner.recv().await {
if let Response::Done(d) = resp {
done = Some(d);
break;
} else {
vec.push(resp);
}
}
Ok((done, vec))
}
}
impl Stream for ResponseStream {
type Item = Response;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context,
) -> Poll<Option<Self::Item>> {
self.inner.poll_recv(cx)
}
}

44
imap/src/client/tls.rs Normal file
View file

@ -0,0 +1,44 @@
use std::{convert::TryFrom, sync::Arc};
use anyhow::Result;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_rustls::{
client::TlsStream,
rustls::{
ClientConfig as RustlsConfig, OwnedTrustAnchor, RootCertStore, ServerName,
},
TlsConnector,
};
/// Wraps the given async stream in TLS with the given hostname (required)
pub async fn wrap_tls<C>(
c: C,
hostname: impl AsRef<str>,
) -> Result<TlsStream<C>>
where
C: AsyncRead + AsyncWrite + Unpin,
{
let server_name = hostname.as_ref();
let mut root_store = RootCertStore::empty();
root_store.add_server_trust_anchors(
webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}),
);
let tls_config = RustlsConfig::builder()
.with_safe_defaults()
.with_root_certificates(root_store)
.with_no_client_auth();
let tls_config = TlsConnector::from(Arc::new(tls_config));
let server_name = ServerName::try_from(server_name).unwrap();
let stream = tls_config.connect(server_name, c).await?;
Ok(stream)
}

5
imap/src/events.rs Normal file
View file

@ -0,0 +1,5 @@
bitflags! {
pub struct EventMask: u32 {
const NONE = 0;
}
}

13
imap/src/interface.rs Normal file
View file

@ -0,0 +1,13 @@
use anyhow::Result;
use crate::proto::{
command::Command,
response::{Envelope, Response},
};
#[async_trait]
pub trait ImapClient {
async fn list_messages(&self) -> Result<Vec<Envelope>>;
}
pub struct ListMessagesOptions {}

31
imap/src/lib.rs Normal file
View file

@ -0,0 +1,31 @@
#[macro_use]
extern crate anyhow;
#[macro_use]
extern crate async_trait;
#[macro_use]
extern crate derive_builder;
#[macro_use]
extern crate derivative;
#[macro_use]
extern crate format_bytes;
#[macro_use]
extern crate futures;
#[macro_use]
extern crate log;
#[macro_use]
extern crate panorama_proto_common;
#[cfg(feature = "serialize")]
#[macro_use]
extern crate serde;
#[cfg(test)]
#[macro_use]
extern crate maplit;
pub mod client;
pub mod interface;
pub mod proto;
#[cfg(feature = "pool")]
pub mod pool;

91
imap/src/pool/mod.rs Normal file
View file

@ -0,0 +1,91 @@
use std::{borrow::Borrow, ops::Deref, sync::Arc};
use anyhow::Result;
use crossbeam::queue::ArrayQueue;
use tokio::sync::Semaphore;
use crate::{
client::auth::{ImapAuth, Login},
interface::ImapClient,
proto::response::Envelope,
};
use super::client::{ClientAuthenticated, Config, ConfigBuilder};
#[derive(Debug)]
pub struct PoolConfig {
pub max_connections: usize,
pub client_config: Config,
pub auth_config: ImapAuth,
}
/// A pool of IMAP connections.
#[derive(Clone)]
pub struct ImapPool(Arc<InnerPool>);
impl Deref for ImapPool {
type Target = InnerPool;
fn deref(&self) -> &Self::Target { self.0.borrow() }
}
#[async_trait]
impl ImapClient for ImapPool {
async fn list_messages(&self) -> Result<Vec<Envelope>> {
let client = self.acquire();
todo!()
}
}
impl ImapPool {
pub fn new(pool_config: PoolConfig) -> Self {
debug!("Created new IMAP pool with config {:?}", pool_config);
let inner = InnerPool::init(pool_config);
ImapPool(Arc::new(inner))
}
}
pub struct InnerPool {
config: PoolConfig,
semaphore: Semaphore,
connections: ArrayQueue<ClientAuthenticated>,
}
impl InnerPool {
pub fn init(config: PoolConfig) -> Self {
let max_connections = config.max_connections;
InnerPool {
config,
semaphore: Semaphore::new(max_connections),
connections: ArrayQueue::new(max_connections),
}
}
pub async fn acquire(&self) -> Result<ClientAuthenticated> {
debug!("Trying to acquire a connection from the pool...");
// TODO: concurrency shit
match self.connections.pop() {
// we can reuse
Some(conn) => Ok(conn),
// no existing connection, time to make a new one
None => {
let client = ConfigBuilder::default()
.hostname(self.config.client_config.hostname.clone())
.port(self.config.client_config.port)
.tls(self.config.client_config.tls)
.open()
.await?;
debug!("Client connected to {}", self.config.client_config.hostname);
// authenticate
let client_auth = client.auth(&self.config.auth_config).await?;
debug!("Authenticated using {:?}", self.config.auth_config);
Ok(client_auth)
}
}
}
}

258
imap/src/proto/command.rs Normal file
View file

@ -0,0 +1,258 @@
use std::{
collections::HashSet,
io::{self, Write},
ops::{Bound, RangeBounds},
};
use format_bytes::DisplayBytes;
use panorama_proto_common::{quote_string, Bytes};
use super::rfc3501::is_quoted_specials;
#[derive(Clone, Debug)]
pub enum Command {
// Any state
Capability,
Noop,
Logout,
// Not authenticated
Login(CommandLogin),
Starttls,
Authenticate,
// Authenticated
Select(CommandSelect),
Examine,
Create,
Delete,
Rename,
Subscribe,
Unsubscribe,
List(CommandList),
Lsub,
Status,
Append,
// Selected
Check,
Close,
Expunge,
Search,
Copy,
Fetch(CommandFetch),
Store,
UidCopy,
UidFetch(CommandFetch),
UidStore,
UidSearch(CommandSearch),
// Extensions
#[cfg(feature = "rfc2177")]
Idle,
#[cfg(feature = "rfc2177")]
Done,
}
impl DisplayBytes for Command {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
let quote = quote_string(b'\x22', b'\\', is_quoted_specials);
match self {
// command-any
Command::Capability => write_bytes!(w, b"CAPABILITY"),
Command::Logout => write_bytes!(w, b"LOGOUT"),
Command::Noop => write_bytes!(w, b"NOOP"),
// command-nonauth
Command::Login(login) => {
write_bytes!(
w,
b"LOGIN {} {}",
quote(&login.userid),
quote(&login.password)
)
}
Command::Starttls => write_bytes!(w, b"STARTTLS"),
// command-auth
Command::List(list) => {
write_bytes!(
w,
b"LIST {} {}",
quote(&list.reference),
quote(&list.mailbox)
)
}
Command::Select(select) => {
write_bytes!(w, b"SELECT {}", quote(&select.mailbox))
}
// selected
Command::UidFetch(fetch) => write_bytes!(w, b"UID FETCH {}", fetch),
// extensions
#[cfg(feature = "rfc2177")]
Command::Idle => write_bytes!(w, b"IDLE"),
_ => todo!("unimplemented command: {:?}", self),
}
}
}
#[derive(Clone, Debug)]
pub struct CommandFetch {
pub ids: Vec<Sequence>,
pub items: FetchItems,
}
impl DisplayBytes for CommandFetch {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
for (i, seq) in self.ids.iter().enumerate() {
if i != 0 {
write_bytes!(w, b",")?;
}
match seq {
Sequence::Single(n) => write_bytes!(w, b"{}", n)?,
Sequence::Range(m, n) => write_bytes!(w, b"{}:{}", m, n)?,
}
}
write_bytes!(w, b" {}", self.items)
}
}
#[derive(Clone, Debug)]
pub enum Sequence {
Single(u32),
Range(u32, u32),
}
#[derive(Clone, Debug)]
pub struct CommandList {
pub reference: Bytes,
pub mailbox: Bytes,
}
#[derive(Clone, Derivative)]
#[derivative(Debug)]
pub struct CommandLogin {
pub userid: Bytes,
#[derivative(Debug = "ignore")]
pub password: Bytes,
}
#[derive(Clone, Debug)]
pub struct CommandSearch {
pub criteria: SearchCriteria,
}
#[derive(Clone, Debug)]
pub struct CommandSelect {
pub mailbox: Bytes,
}
//
#[derive(Clone, Debug)]
pub enum FetchItems {
All,
Fast,
Full,
Flags,
Envelope,
}
impl DisplayBytes for FetchItems {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
match self {
FetchItems::All => write_bytes!(w, b"ALL"),
FetchItems::Fast => write_bytes!(w, b"FAST"),
FetchItems::Full => write_bytes!(w, b"FULL"),
FetchItems::Flags => write_bytes!(w, b"FLAGS"),
FetchItems::Envelope => write_bytes!(w, b"ENVELOPE"),
}
}
}
#[derive(Clone, Debug)]
pub enum FetchAttr {}
// TODO: not the most efficient representation but I'll optimize if this ever
// actually becomes a problem
#[derive(Clone, Debug)]
pub struct SearchCriteria(Vec<(Bound<u32>, Bound<u32>)>);
impl SearchCriteria {
pub fn all() -> Self {
let mut set = Vec::new();
set.push((Bound::Unbounded, Bound::Unbounded));
SearchCriteria(set)
}
pub fn contains(&self, n: u32) -> bool {
for range in self.0.iter() {
if range.contains(&n) {
return true;
}
}
false
}
pub fn with_range(&mut self, range: impl RangeBounds<u32>) -> &mut Self {
let range = (range.start_bound().cloned(), range.end_bound().cloned());
self.0.push(range);
self
}
}
impl DisplayBytes for SearchCriteria {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
// TODO: is it faster to batch these up or not?
for (i, range) in self.0.iter().enumerate() {
if i != 0 {
write_bytes!(w, b",")?;
}
match range.0 {
Bound::Excluded(n) => write_bytes!(w, b"{}", &(n + 1))?,
Bound::Included(n) => write_bytes!(w, b"{}", &n)?,
Bound::Unbounded => write_bytes!(w, b"1")?,
}
write_bytes!(w, b":")?;
match range.1 {
Bound::Excluded(n) => write_bytes!(w, b"{}", &(n - 1))?,
Bound::Included(n) => write_bytes!(w, b"{}", &n)?,
Bound::Unbounded => write_bytes!(w, b"*")?,
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display_search_criteria() {
// TODO: is there a trivial case?
assert_eq!(format_bytes!(b"{}", SearchCriteria::all()), b"1:*");
assert_eq!(
format_bytes!(
b"{}",
SearchCriteria(vec![
(Bound::Unbounded, Bound::Included(4)),
(Bound::Excluded(5), Bound::Unbounded),
])
),
b"1:4,6:*"
);
}
}

15
imap/src/proto/mod.rs Normal file
View file

@ -0,0 +1,15 @@
//! Helper functions for manipulating the wire protocol.
#![allow(non_snake_case, dead_code)]
// data types
pub mod command;
pub mod response;
// parsers
pub mod rfc2234;
pub mod rfc3501;
pub mod rfc6154;
#[cfg(feature = "rfc2177")]
pub mod rfc2177;

402
imap/src/proto/response.rs Normal file
View file

@ -0,0 +1,402 @@
use std::fmt;
use std::io::{self, Write};
use std::ops::RangeInclusive;
use chrono::{DateTime, FixedOffset};
use format_bytes::DisplayBytes;
use panorama_proto_common::Bytes;
#[cfg(feature = "fuzzing")]
use arbitrary::{self, Arbitrary, Unstructured};
#[cfg(feature = "fuzzing")]
use chrono::TimeZone;
pub type Atom = Bytes;
#[derive(Clone, Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub struct Tag(pub Bytes);
impl DisplayBytes for Tag {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
write_bytes!(w, b"{}", self.0)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Timestamp(pub(crate) DateTime<FixedOffset>);
#[cfg(feature = "fuzzing")]
impl<'a> Arbitrary<'a> for Timestamp {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let (y, m, d, H, M, S) = (
// TODO: year range?
u.int_in_range(-4000..=4000i32)?,
u.int_in_range(1..=12u32)?,
u.int_in_range(1..=28u32)?,
u.int_in_range(0..=23u32)?,
u.int_in_range(0..=59u32)?,
u.int_in_range(0..=59u32)?,
);
println!("{:?}", (y, m, d, H, M, S));
Ok(Timestamp(
// TODO: introduce offset
FixedOffset::west(0).ymd(y, m, d).and_hms(H, M, S),
))
}
}
#[derive(Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub enum Response {
Capabilities(Vec<Capability>),
Continue(ResponseText),
Condition(Condition),
Done(ResponseDone),
MailboxData(MailboxData),
Fetch(u32, Vec<MessageAttribute>),
Expunge(u32),
Fatal(Condition),
Tagged(Tag, Condition),
}
impl DisplayBytes for Response {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
#[allow(unreachable_patterns)]
match self {
Response::Capabilities(caps) => {
write_bytes!(w, b"CAPABILITY")?;
for cap in caps {
write_bytes!(w, b" {}", cap)?;
}
Ok(())
}
Response::Continue(cont) => write_bytes!(w, b"+ {}\r\n", cont),
Response::Condition(cond) => write_bytes!(w, b"* {}\r\n", cond),
Response::Done(_) => write_bytes!(w, b""),
Response::MailboxData(data) => write_bytes!(w, b"* {}\r\n", data),
Response::Fetch(n, attrs) => {
write_bytes!(w, b"{} FETCH (", n)?;
for (i, attr) in attrs.iter().enumerate() {
if i != 0 {
write_bytes!(w, b" ")?;
}
write_bytes!(w, b"{}", attr)?;
}
write_bytes!(w, b")\r\n")
}
Response::Expunge(n) => write_bytes!(w, b"{} EXPUNGE\r\n", n),
Response::Fatal(cond) => write_bytes!(w, b"* {}\r\n", cond),
Response::Tagged(tag, cond) => {
write_bytes!(w, b"{} {}\r\n", tag, cond)
}
_ => todo!(),
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub struct ResponseText {
pub code: Option<ResponseCode>,
pub info: Bytes,
}
impl DisplayBytes for ResponseText {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
if let Some(code) = &self.code {
write_bytes!(w, b"[{}] ", code)?;
}
write_bytes!(w, b"{}", self.info)
}
}
#[derive(Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub enum MessageAttribute {
BodySection,
BodyStructure,
Envelope(Envelope),
Flags(Vec<Flag>),
InternalDate(Timestamp),
ModSeq(u64), // RFC 4551, section 3.3.2
Rfc822(Option<String>),
Rfc822Header(Option<String>),
Rfc822Size(u32),
Rfc822Text(Option<String>),
Uid(u32),
}
impl DisplayBytes for MessageAttribute {
fn display_bytes(&self, _: &mut dyn Write) -> io::Result<()> {
match self {
_ => todo!(),
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub struct Envelope {
pub date: Option<Bytes>,
pub subject: Option<Bytes>,
pub from: Option<Vec<Address>>,
pub sender: Option<Vec<Address>>,
pub reply_to: Option<Vec<Address>>,
pub to: Option<Vec<Address>>,
pub cc: Option<Vec<Address>>,
pub bcc: Option<Vec<Address>>,
pub in_reply_to: Option<Bytes>,
pub message_id: Option<Bytes>,
}
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub struct Address {
pub name: Option<Bytes>,
pub adl: Option<Bytes>,
pub mailbox: Option<Bytes>,
pub host: Option<Bytes>,
}
#[derive(Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub struct ResponseDone {
pub tag: Tag,
pub status: Status,
pub code: Option<ResponseCode>,
pub info: Option<Bytes>,
}
#[derive(Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub struct Condition {
pub status: Status,
pub code: Option<ResponseCode>,
pub info: Bytes,
}
impl DisplayBytes for Condition {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
write_bytes!(w, b"{} ", self.status)?;
if let Some(code) = &self.code {
write_bytes!(w, b"[{}] ", code)?;
}
write_bytes!(w, b"{}", self.info)
}
}
#[derive(Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub enum Status {
Ok,
No,
Bad,
PreAuth,
Bye,
}
impl DisplayBytes for Status {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
match self {
Status::Ok => write_bytes!(w, b"OK"),
Status::No => write_bytes!(w, b"NO"),
Status::Bad => write_bytes!(w, b"BAD"),
Status::PreAuth => write_bytes!(w, b"PREAUTH"),
Status::Bye => write_bytes!(w, b"BYE"),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub enum ResponseCode {
Alert,
BadCharset(Option<Vec<Bytes>>),
Capabilities(Vec<Capability>),
HighestModSeq(u64), // RFC 4551, section 3.1.1
Parse,
PermanentFlags(Vec<Flag>),
ReadOnly,
ReadWrite,
TryCreate,
UidNext(u32),
UidValidity(u32),
Unseen(u32),
AppendUid(u32, Vec<UidSetMember>),
CopyUid(u32, Vec<UidSetMember>, Vec<UidSetMember>),
UidNotSticky,
Other(Bytes, Option<Bytes>),
}
impl DisplayBytes for ResponseCode {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
match self {
ResponseCode::Alert => write_bytes!(w, b"ALERT"),
_ => todo!(),
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub enum UidSetMember {
UidRange(RangeInclusive<u32>),
Uid(u32),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub enum Capability {
Imap4rev1,
Auth(Atom),
Atom(Atom),
}
impl DisplayBytes for Capability {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
match self {
Capability::Imap4rev1 => write_bytes!(w, b"IMAP4rev1"),
Capability::Auth(a) => write_bytes!(w, b"AUTH={}", a),
Capability::Atom(a) => write_bytes!(w, b"{}", a),
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub enum MailboxData {
Flags(Vec<Flag>),
List(MailboxList),
Lsub(MailboxList),
Search(Vec<u32>),
Status,
Exists(u32),
Recent(u32),
}
impl DisplayBytes for MailboxData {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
match self {
MailboxData::Flags(flags) => {
write_bytes!(w, b"(")?;
for (i, flag) in flags.iter().enumerate() {
if i != 0 {
write_bytes!(w, b" ")?;
}
write_bytes!(w, b"{}", flag)?;
}
write_bytes!(w, b")")
}
MailboxData::List(list) => write_bytes!(w, b"{}", list),
MailboxData::Exists(n) => write_bytes!(w, b"{} EXISTS", n),
MailboxData::Recent(n) => write_bytes!(w, b"{} RECENT", n),
_ => todo!(),
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub enum Mailbox {
Inbox,
Name(Bytes),
}
impl fmt::Display for Mailbox {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Mailbox::Inbox => write!(f, "INBOX"),
Mailbox::Name(b) => write!(f, "{}", String::from_utf8_lossy(b)),
}
}
}
impl DisplayBytes for Mailbox {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
match self {
Mailbox::Inbox => write_bytes!(w, b"INBOX"),
Mailbox::Name(b) => write_bytes!(w, b"{}", b),
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub enum Flag {
Answered,
Flagged,
Deleted,
Seen,
Draft,
Recent,
Keyword(Atom),
Extension(Atom),
SpecialCreate,
}
impl DisplayBytes for Flag {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
match self {
Flag::Answered => write_bytes!(w, b"\\Answered"),
Flag::Flagged => write_bytes!(w, b"\\Flagged"),
Flag::Deleted => write_bytes!(w, b"\\Deleted"),
Flag::Seen => write_bytes!(w, b"\\Seen"),
Flag::Draft => write_bytes!(w, b"\\Draft"),
Flag::Recent => write_bytes!(w, b"\\Recent"),
Flag::Keyword(atom) => write_bytes!(w, b"{}", atom),
Flag::Extension(atom) => write_bytes!(w, b"\\{}", atom),
Flag::SpecialCreate => write_bytes!(w, b"\\*"),
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub struct MailboxList {
pub flags: Vec<MailboxListFlag>,
pub delimiter: Option<u8>,
pub mailbox: Mailbox,
}
impl DisplayBytes for MailboxList {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
write_bytes!(w, b"(")?;
for (i, flag) in self.flags.iter().enumerate() {
if i != 0 {
write_bytes!(w, b" ")?;
}
write_bytes!(w, b"{}", flag)?;
}
write_bytes!(w, b") ")?;
match self.delimiter {
Some(d) => write_bytes!(w, b"\"{}\"", d)?,
None => write_bytes!(w, b"NIL")?,
}
write_bytes!(w, b" {}", self.mailbox)
}
}
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
pub enum MailboxListFlag {
NoInferiors,
NoSelect,
Marked,
Unmarked,
Extension(Atom),
}
impl DisplayBytes for MailboxListFlag {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
match self {
MailboxListFlag::NoInferiors => write_bytes!(w, b"\\Noinferiors"),
MailboxListFlag::NoSelect => write_bytes!(w, b"\\NoSelect"),
MailboxListFlag::Marked => write_bytes!(w, b"\\Marked"),
MailboxListFlag::Unmarked => write_bytes!(w, b"\\Unmarked"),
MailboxListFlag::Extension(a) => write_bytes!(w, b"\\{}", a),
}
}
}

View file

@ -0,0 +1,4 @@
//! IMAP `IDLE` Command
//! ---
//!
//! Grammar from <https://datatracker.ietf.org/doc/html/rfc2177#section-4>

50
imap/src/proto/rfc2234.rs Normal file
View file

@ -0,0 +1,50 @@
//! ABNF Core Rules
//! ---
//!
//! Grammar from <https://tools.ietf.org/html/rfc2234#section-6.1>
use nom::{
branch::alt,
multi::many0,
sequence::{pair, preceded},
};
use panorama_proto_common::{byte, satisfy, skip};
rule!(pub ALPHA : u8 => satisfy(|c| (c >= b'a' && c <= b'z') || (c >= b'A' && c <= b'Z')));
rule!(pub BIT : u8 => satisfy(|c| c == b'0' || c == b'1'));
pub(crate) fn is_char(c: u8) -> bool { c != b'\0' }
rule!(pub CHAR : u8 => satisfy(is_char));
pub(crate) fn is_cr(c: u8) -> bool { c == b'\x0d' }
rule!(pub CR : u8 => satisfy(is_cr));
rule!(pub CRLF : (u8, u8) => pair(CR, LF));
pub(crate) fn is_ctl(c: u8) -> bool { c <= b'\x1f' || c == b'\x7f' }
rule!(pub CTL : u8 => satisfy(is_ctl));
pub(crate) fn is_digit(c: u8) -> bool { c >= b'\x30' && c <= b'\x39' }
rule!(pub DIGIT : u8 => satisfy(is_digit));
pub(crate) fn is_dquote(c: u8) -> bool { c == b'\x22' }
rule!(pub DQUOTE : u8 => satisfy(is_dquote));
rule!(pub HEXDIG : u8 => alt((DIGIT, satisfy(|c| c >= b'A' && c <= b'F'))));
rule!(pub HTAB : u8 => byte(b'\x09'));
pub(crate) fn is_lf(c: u8) -> bool { c == b'\x0a' }
rule!(pub LF : u8 => satisfy(is_lf));
rule!(pub LWSP : () => skip(many0(alt((WSP, preceded(CRLF, WSP))))));
// rule!(pub OCTET : char => anychar);
pub(crate) fn is_sp(c: u8) -> bool { c == b'\x20' }
rule!(pub SP : u8 => satisfy(is_sp));
rule!(pub VCHAR : u8 => satisfy(|c| c >= b'\x21' && c <= b'\x7e'));
rule!(pub WSP : u8 => alt((SP, HTAB)));

View file

@ -0,0 +1,400 @@
//! IMAP Specification
//! ---
//!
//! Grammar from <https://datatracker.ietf.org/doc/html/rfc3501#section-9>
#[cfg(test)]
pub mod tests;
use chrono::{FixedOffset, NaiveTime, TimeZone};
use nom::{
branch::alt,
combinator::{map, map_res, opt, verify},
multi::{count, many0, many1, many_m_n},
sequence::{delimited, pair, preceded, separated_pair, terminated, tuple},
};
use panorama_proto_common::{
byte, never, parse_num, satisfy, tagi, take, take_while1, Bytes, VResult,
};
use super::response::{
Address, Atom, Capability, Condition, Envelope, Flag, Mailbox, MailboxData,
MailboxList, MailboxListFlag, MessageAttribute, Response, ResponseCode,
ResponseText, Status, Tag, Timestamp,
};
use super::rfc2234::{
is_char, is_cr, is_ctl, is_digit, is_dquote, is_lf, is_sp, CRLF, DIGIT,
DQUOTE, SP,
};
/// Grammar rule `T / nil` produces `Option<T>`
macro_rules! opt_nil {
($t:expr) => {
alt((map($t, Some), map(crate::proto::rfc3501::nil, |_| None)))
};
}
rule!(pub address : Address => map(paren!(tuple((
terminated(addr_name, SP),
terminated(addr_adl, SP),
terminated(addr_mailbox, SP),
addr_host
))), |(name, adl, mailbox, host)| Address { name, adl, mailbox, host }));
rule!(pub addr_adl : Option<Bytes> => nstring);
rule!(pub addr_host : Option<Bytes> => nstring);
rule!(pub addr_mailbox : Option<Bytes> => nstring);
rule!(pub addr_name : Option<Bytes> => nstring);
rule!(pub astring : Bytes => alt((take_while1(is_astring_char), string)));
pub(crate) fn is_astring_char(c: u8) -> bool {
is_atom_char(c) || is_resp_specials(c)
}
rule!(pub ASTRING_CHAR : u8 => alt((ATOM_CHAR, resp_specials)));
// really odd behavior about take_while1 is that if there isn't a character
// that's not is_atom_char, then it's actually going to error out and require
// another character in case there's more. makes sense, just need to keep in
// mind that we need more content in order to satisfy this
rule!(pub atom : Bytes => take_while1(is_atom_char));
pub(crate) fn is_atom_char(c: u8) -> bool { is_char(c) && !is_atom_specials(c) }
rule!(pub ATOM_CHAR : u8 => satisfy(is_atom_char));
pub(crate) fn is_atom_specials(c: u8) -> bool {
c == b'('
|| c == b')'
|| c == b'{'
|| is_sp(c)
|| is_ctl(c)
|| is_list_wildcards(c)
|| is_quoted_specials(c)
|| is_resp_specials(c)
}
rule!(pub atom_specials : u8 => satisfy(is_atom_specials));
rule!(pub auth_type : Atom => atom);
rule!(pub capability : Capability => alt((
map(preceded(tagi(b"AUTH="), auth_type), Capability::Auth),
map(verify(atom, |s| &s[..] != b"IMAP4rev1"), Capability::Atom),
)));
rule!(pub capability_data : Vec<Capability> => preceded(tagi(b"CAPABILITY"), {
map(separated_pair(
many0(preceded(SP, capability)),
pair(SP, tagi(b"IMAP4rev1")),
many0(preceded(SP, capability)),
), |(mut a, b)| { a.extend(b); a })
}));
pub(crate) fn is_char8(c: u8) -> bool { c != b'\0' }
rule!(pub continue_req : Response => delimited(pair(byte(b'+'), SP),
// TODO: handle base64 case?
map(resp_text, Response::Continue),
CRLF));
rule!(pub date_day : u32 => map(many_m_n(1, 2, DIGIT), |s| match s.as_slice() {
&[x] => (x - b'0') as u32,
&[x, y] => (x - b'0') as u32 * 10 + (y - b'0') as u32,
_ => unreachable!("only up to two digits"),
}));
rule!(pub date_day_fixed : u32 => alt((
map(preceded(SP, DIGIT), |d| (d - b'0') as u32),
map(pair(DIGIT, DIGIT), |(x, y)| (x - b'0') as u32 * 10 + (y - b'0') as u32),
)));
rule!(pub date_month : u32 => alt((
map(tagi(b"Jan"), |_| 1),
map(tagi(b"Feb"), |_| 2),
map(tagi(b"Mar"), |_| 3),
map(tagi(b"Apr"), |_| 4),
map(tagi(b"May"), |_| 5),
map(tagi(b"Jun"), |_| 6),
map(tagi(b"Jul"), |_| 7),
map(tagi(b"Aug"), |_| 8),
map(tagi(b"Sep"), |_| 9),
map(tagi(b"Oct"), |_| 10),
map(tagi(b"Nov"), |_| 11),
map(tagi(b"Dec"), |_| 12),
)));
rule!(pub date_time : Timestamp => delimited(DQUOTE,
map_res(tuple((
date_day_fixed,
byte(b'-'),
date_month,
byte(b'-'),
date_year,
SP,
time,
SP,
zone,
)), |(d, _, m, _, y, _, time, _, zone)| {
// eprintln!("{}-{}-{} {:?} {:?}", y, m, d, time, zone);
zone.ymd_opt(y, m, d)
.and_time(time)
// TODO: what the hell
.earliest()
.map(Timestamp)
.ok_or_else(|| anyhow!("invalid time"))
}),
DQUOTE));
rule!(pub date_year : i32 => map_res(count(DIGIT, 4), parse_num::<_, i32>));
rule!(pub envelope : Envelope => map(paren!(tuple((
terminated(env_date, SP),
terminated(env_subject, SP),
terminated(env_from, SP),
terminated(env_sender, SP),
terminated(env_reply_to, SP),
terminated(env_to, SP),
terminated(env_cc, SP),
terminated(env_bcc, SP),
terminated(env_in_reply_to, SP),
env_message_id,
))), |(date, subject, from, sender, reply_to, to, cc, bcc, in_reply_to, message_id)|
Envelope { date, subject, from, sender, reply_to, to, cc, bcc, in_reply_to, message_id }));
rule!(pub env_bcc : Option<Vec<Address>> => opt_nil!(paren!(many1(address))));
rule!(pub env_cc : Option<Vec<Address>> => opt_nil!(paren!(many1(address))));
rule!(pub env_date : Option<Bytes> => nstring);
rule!(pub env_from : Option<Vec<Address>> => opt_nil!(paren!(many1(address))));
rule!(pub env_in_reply_to : Option<Bytes> => nstring);
rule!(pub env_message_id : Option<Bytes> => nstring);
rule!(pub env_reply_to : Option<Vec<Address>> => opt_nil!(paren!(many1(address))));
rule!(pub env_sender : Option<Vec<Address>> => opt_nil!(paren!(many1(address))));
rule!(pub env_subject : Option<Bytes> => nstring);
rule!(pub env_to : Option<Vec<Address>> => opt_nil!(paren!(many1(address))));
rule!(pub flag : Flag => alt((
map(tagi(b"\\Answered"), |_| Flag::Answered),
map(tagi(b"\\Flagged"), |_| Flag::Flagged),
map(tagi(b"\\Deleted"), |_| Flag::Deleted),
map(tagi(b"\\Seen"), |_| Flag::Seen),
map(tagi(b"\\Draft"), |_| Flag::Draft),
map(flag_keyword, Flag::Keyword),
map(flag_extension, Flag::Extension),
)));
rule!(pub flag_extension : Atom => preceded(byte(b'\\'), atom));
rule!(pub flag_fetch : Flag => alt((flag, map(tagi(b"\\Recent"), |_| Flag::Recent))));
rule!(pub flag_keyword : Atom => atom);
rule!(pub flag_list : Vec<Flag> => paren!(sep_list!(?flag)));
rule!(pub flag_perm : Flag => alt((
flag,
map(pair(byte(b'\\'), byte(b'*')), |_| Flag::SpecialCreate),
)));
pub(crate) fn is_list_wildcards(c: u8) -> bool { c == b'%' || c == b'*' }
rule!(pub list_wildcards : u8 => satisfy(is_list_wildcards));
// literal = "{" number "}" CRLF *CHAR8
// ; Number represents the number of CHAR8s
// TODO: Future work, could possibly initialize writing to file if the length is
// determined to exceed a certain threshold so we don't have insane amounts of
// data in memory
pub fn literal(i: Bytes) -> VResult<Bytes, Bytes> {
let mut length_of =
terminated(delimited(byte(b'{'), number, byte(b'}')), CRLF);
let (i, length) = length_of(i)?;
debug!("length is: {:?}", length);
map(take(length), Bytes::from)(i)
}
rule!(pub mailbox : Mailbox => alt((
map(tagi(b"INBOX"), |_| Mailbox::Inbox),
map(astring, Mailbox::Name),
)));
rule!(pub mailbox_data : MailboxData => alt((
map(preceded(pair(tagi(b"FLAGS"), SP), flag_list), MailboxData::Flags),
map(preceded(pair(tagi(b"LIST"), SP), mailbox_list), MailboxData::List),
map(preceded(pair(tagi(b"LSUB"), SP), mailbox_list), MailboxData::Lsub),
map(terminated(number, pair(SP, tagi(b"EXISTS"))), MailboxData::Exists),
map(terminated(number, pair(SP, tagi(b"RECENT"))), MailboxData::Recent),
)));
rule!(pub mailbox_list : MailboxList => map(separated_pair(
paren!(map(opt(mbx_list_flags), |opt| opt.unwrap_or_else(Vec::new))),
SP, separated_pair(
alt((
map(delimited(DQUOTE, QUOTED_CHAR, DQUOTE), Some),
map(nil, |_| None),
)),
SP, mailbox,
),
), |(flags, (delimiter, mailbox))| MailboxList { flags, delimiter, mailbox }));
rule!(pub mbx_list_flags : Vec<MailboxListFlag> => alt((
map(tuple((
many0(terminated(mbx_list_oflag, SP)),
mbx_list_sflag,
many0(preceded(SP, mbx_list_oflag)),
)), |(mut a, b, c)| { a.push(b); a.extend(c); a }),
sep_list!(mbx_list_oflag),
)));
rule!(pub mbx_list_oflag : MailboxListFlag => alt((
map(tagi(b"\\Noinferiors"), |_| MailboxListFlag::NoInferiors),
map(flag_extension, MailboxListFlag::Extension),
)));
rule!(pub mbx_list_sflag : MailboxListFlag => alt((
map(tagi(b"\\NoSelect"), |_| MailboxListFlag::NoSelect),
map(tagi(b"\\Marked"), |_| MailboxListFlag::Marked),
map(tagi(b"\\Unmarked"), |_| MailboxListFlag::Unmarked),
)));
rule!(pub message_data : Response => alt((
map(terminated(nz_number, pair(SP, tagi(b"EXPUNGE"))), Response::Expunge),
map(separated_pair(nz_number, SP, preceded(pair(tagi(b"FETCH"), SP), msg_att)),
|(n, attrs)| Response::Fetch(n, attrs)),
)));
rule!(pub msg_att : Vec<MessageAttribute> => paren!(sep_list!(alt((msg_att_dynamic, msg_att_static)))));
rule!(pub msg_att_dynamic : MessageAttribute => alt((
map(preceded(pair(tagi(b"FLAGS"), SP),
paren!(sep_list!(?flag_fetch))), MessageAttribute::Flags),
never,
)));
rule!(pub msg_att_static : MessageAttribute => alt((
map(preceded(pair(tagi(b"UID"), SP), uniqueid), MessageAttribute::Uid),
map(preceded(pair(tagi(b"ENVELOPE"), SP), envelope), MessageAttribute::Envelope),
map(preceded(pair(tagi(b"INTERNALDATE"), SP), date_time), MessageAttribute::InternalDate),
map(preceded(pair(tagi(b"RFC822.SIZE"), SP), number), MessageAttribute::Rfc822Size),
)));
rule!(pub nil : Bytes => tagi(b"NIL"));
rule!(pub nstring : Option<Bytes> => opt_nil!(string));
pub(crate) fn number(i: Bytes) -> VResult<Bytes, u32> {
map_res(take_while1(is_digit), parse_num::<_, u32>)(i)
}
rule!(pub nz_number : u32 => verify(number, |n| *n != 0));
rule!(pub quoted : Bytes => delimited(DQUOTE, take_while1(is_quoted_char), DQUOTE));
fn is_quoted_char(c: u8) -> bool { is_char(c) && !is_quoted_specials(c) }
rule!(pub QUOTED_CHAR : u8 => alt((satisfy(is_quoted_char), preceded(byte(b'\\'), quoted_specials))));
pub(crate) fn is_quoted_specials(c: u8) -> bool { is_dquote(c) || c == b'\\' }
rule!(pub quoted_specials : u8 => satisfy(is_quoted_specials));
// TODO: technically, this is supposed to be
rule!(pub response : Response => alt((continue_req, response_data, response_done)));
rule!(pub response_data : Response => delimited(pair(byte(b'*'), SP), alt((
map(resp_cond_state, Response::Condition),
map(resp_cond_bye, Response::Condition),
map(mailbox_data, Response::MailboxData),
message_data,
map(capability_data, Response::Capabilities),
)), CRLF));
rule!(pub response_done : Response => alt((response_tagged, response_fatal)));
rule!(pub response_fatal : Response => delimited(pair(byte(b'*'), SP),
map(resp_cond_bye, Response::Fatal), CRLF));
rule!(pub response_tagged : Response => map(terminated(separated_pair(tag, SP, resp_cond_state), CRLF),
|(tag, cond)| Response::Tagged(tag, cond)));
rule!(pub resp_cond_bye : Condition => preceded(pair(tagi(b"BYE"), SP),
map(resp_text, |ResponseText { code, info }| Condition { status: Status::Bye, code, info })));
rule!(pub resp_cond_state : Condition => map(
separated_pair(
alt((
map(tagi(b"OK"), |_| Status::Ok),
map(tagi(b"NO"), |_| Status::No),
map(tagi(b"BAD"), |_| Status::Bad),
)),
SP,
resp_text,
),
|(status, ResponseText { code, info })| Condition { status, code, info }
));
pub(crate) fn is_resp_specials(c: u8) -> bool { c == b']' }
rule!(pub resp_specials : u8 => satisfy(is_resp_specials));
rule!(pub resp_text : ResponseText => alt((
map(pair(
delimited(byte(b'['), resp_text_code, byte(b']')),
opt(preceded(SP, text)),
), |(code, info)| ResponseText { code: Some(code), info: info.unwrap_or_else(|| Bytes::from(b"")) }),
map(pair(
opt(terminated(delimited(byte(b'['), resp_text_code, byte(b']')), SP)),
text,
), |(code, info)| ResponseText { code, info }),
)));
rule!(pub resp_text_code : ResponseCode => alt((
map(tagi(b"ALERT"), |_| ResponseCode::Alert),
map(capability_data, ResponseCode::Capabilities),
map(tagi(b"PARSE"), |_| ResponseCode::Parse),
map(preceded(pair(tagi(b"PERMANENTFLAGS"), SP), paren!(sep_list!(flag_perm))), ResponseCode::PermanentFlags),
map(tagi(b"READ-ONLY"), |_| ResponseCode::ReadOnly),
map(tagi(b"READ-WRITE"), |_| ResponseCode::ReadWrite),
map(tagi(b"TRYCREATE"), |_| ResponseCode::TryCreate),
map(preceded(pair(tagi(b"UIDNEXT"), SP), nz_number), ResponseCode::UidNext),
map(preceded(pair(tagi(b"UIDVALIDITY"), SP), nz_number), ResponseCode::UidValidity),
map(preceded(pair(tagi(b"UNSEEN"), SP), nz_number), ResponseCode::Unseen),
map(pair(atom, opt(preceded(SP, map(take_while1(|c| is_text_char(c) && c != b']'), Bytes::from)))),
|(a, b)| ResponseCode::Other(a, b)),
)));
rule!(pub string : Bytes => alt((quoted, literal)));
pub(crate) fn is_tag_char(c: u8) -> bool { is_astring_char(c) && c != b'+' }
rule!(pub tag : Tag => map(take_while1(is_tag_char), Tag));
rule!(pub text : Bytes => map(take_while1(is_text_char), Bytes::from));
pub(crate) fn is_text_char(c: u8) -> bool {
is_char(c) && !is_cr(c) && !is_lf(c)
}
rule!(pub TEXT_CHAR : u8 => satisfy(is_text_char));
rule!(pub time : NaiveTime => map_res(
tuple((
map_res(count(DIGIT, 2), parse_num::<_, u32>),
byte(b':'),
map_res(count(DIGIT, 2), parse_num::<_, u32>),
byte(b':'),
map_res(count(DIGIT, 2), parse_num::<_, u32>),
)),
|(h, _, m, _, s)| NaiveTime::from_hms_opt(h, m, s).ok_or_else(|| anyhow!("invalid time"))));
rule!(pub uniqueid : u32 => nz_number);
rule!(pub zone : FixedOffset => map(pair(
alt((map(byte(b'+'), |_| true), map(byte(b'-'), |_| false), )),
map_res(count(DIGIT, 4), parse_num::<_, i32>),
), |(pos, value)| if pos { FixedOffset::east(value) } else { FixedOffset::west(value) }));

View file

@ -0,0 +1,123 @@
#![allow(unused_imports)]
use chrono::*;
use nom::{multi::*, sequence::*};
use panorama_proto_common::*;
use crate::proto::response::*;
use crate::proto::rfc2234::*;
use crate::proto::rfc3501::*;
#[test]
fn test_literal() {
assert_eq!(
literal(Bytes::from(b"{13}\r\nHello, world!"))
.unwrap()
.1
.as_ref(),
b"Hello, world!"
);
}
#[test]
fn from_afl() {
let _ = response(Bytes::from(b"* 4544444444 444 "));
let _ = response(Bytes::from(b"* 8045 FETCH (UID 8225 ENVELOPE (\"Sun, 21 Mar 2021 18:44:10 -0700\" \"SUBJECT\" ((\"SENDER\" NIL \"sender\" \"example.com\")) ((\"SENDER\" NIL \"sender\" \"example.com\")) ((\"norepjy\" NIL \"noreply\" \"example.com\")) ((\"NAME\" NIL \"user\" \"gmail.com\")) NIL NIL NIL \"<Hmple.com>\") FLAGS () INTERNALDATE \"22-Mar-2021 01:64:12 \x7f0000\" RFC822.SIZE 13503)".to_vec()));
}
#[test]
fn test_date() {
assert_eq!(date_year(Bytes::from(b"2021")).unwrap().1, 2021);
assert_eq!(
date_time(Bytes::from(b"\"22-Mar-2021 01:44:12 +0000\""))
.unwrap()
.1,
Timestamp(FixedOffset::east(0).ymd(2021, 3, 22).and_hms(1, 44, 12)),
);
}
#[test]
fn test_fetch() {
assert!(flag_list(Bytes::from(b"()")).unwrap().1.is_empty());
use nom::Err;
use panorama_proto_common::convert_error;
let buf = Bytes::from(b"* 8045 FETCH (UID 8225 ENVELOPE (\"Sun, 21 Mar 2021 18:44:10 -0700\" \"SUBJECT\" ((\"SENDER\" NIL \"sender\" \"example.com\")) ((\"SENDER\" NIL \"sender\" \"example.com\")) ((\"noreply\" NIL \"noreply\" \"example.com\")) ((\"NAME\" NIL \"user\" \"gmail.com\")) NIL NIL NIL \"<HASH-99c91810@example.com>\") FLAGS () INTERNALDATE \"22-Mar-2021 01:44:12 +0000\" RFC822.SIZE 13503)\r\n".to_vec());
let res = response(buf.clone());
println!("response: {:?}", res);
assert!(matches!(res.unwrap().1, Response::Fetch(8045, _)));
}
#[test]
fn test_capabilities() {
assert_eq!(
capability(Bytes::from(b"UNSELECT\r\n")).unwrap().1,
Capability::Atom(Bytes::from(b"UNSELECT"))
);
// trivial case
assert_eq!(
capability_data(Bytes::from(b"CAPABILITY IMAP4rev1\r\n"))
.unwrap()
.1,
vec![]
);
assert_eq!(
capability_data(Bytes::from(
b"CAPABILITY UNSELECT IMAP4rev1 NAMESPACE\r\n"
))
.unwrap()
.1,
vec![
Capability::Atom(Bytes::from(b"UNSELECT")),
Capability::Atom(Bytes::from(b"NAMESPACE"))
]
);
}
#[test]
fn test_list() {
assert!(matches!(
response(Bytes::from(
b"* LIST (\\HasChildren \\UnMarked \\Trash) \".\" Trash\r\n",
))
.unwrap()
.1,
Response::MailboxData(MailboxData::List(MailboxList {
flags,
delimiter: Some(b'.'),
mailbox: Mailbox::Name(mailbox),
}) ) if flags.len() == 3 &&
flags.contains(&MailboxListFlag::Extension(Atom::from(b"HasChildren"))) &&
flags.contains(&MailboxListFlag::Extension(Atom::from(b"UnMarked"))) &&
flags.contains(&MailboxListFlag::Extension(Atom::from(b"Trash"))) &&
&*mailbox == &b"Trash"[..]
));
}
#[test]
fn test_gmail_is_shit() {
// FUCK YOU GMAIL!
let res = response(Bytes::from(b"* OK [HIGHESTMODSEQ 694968]\r\n"))
.unwrap()
.1;
assert!(matches!(res,
Response::Condition(Condition {
status: Status::Ok,
code: Some(ResponseCode::Other(c, Some(d))),
info: e,
})
if c == Bytes::from(b"HIGHESTMODSEQ") && d == Bytes::from(b"694968") && e.is_empty()
));
let res = resp_text(Bytes::from(b"[PERMANENTFLAGS (\\Answered \\Flagged \\Draft \\Deleted \\Seen $NotPhishing $Phishing \\*)] Flags permitted.\r".to_vec())).unwrap().1;
eprintln!("{:?}", res);
eprintln!();
let res = response(Bytes::from(b"* OK [PERMANENTFLAGS (\\Answered \\Flagged \\Draft \\Deleted \\Seen $NotPhishing $Phishing \\*)] Flags permitted.\r\n".to_vec())).unwrap().1;
eprintln!("{:?}", res);
assert!(matches!(res, Response::Condition(_)));
}

View file

@ -0,0 +1,4 @@
//! IMAP `UIDPLUS` Extension
//! ---
//!
//! Grammar from <https://datatracker.ietf.org/doc/html/rfc4315#section-4>

View file

@ -0,0 +1,4 @@
//! IMAP `LIST` Extension
//! ---
//!
//! Grammar from <https://datatracker.ietf.org/doc/html/rfc6154#section-6>

25
mbsync/Cargo.toml Normal file
View file

@ -0,0 +1,25 @@
[package]
name = "panorama-mbsync"
version = "0.1.0"
edition = "2018"
description = "mbsync written using panorama's IMAP library"
authors = ["Michael Zhang <mail@mzhang.io>"]
keywords = ["imap", "email", "mbsync"]
license = "GPL-3.0-or-later"
categories = ["email"]
repository = "https://git.mzhang.io/michael/panorama"
readme = "README.md"
[dependencies]
anyhow = { version = "1.0.42", features = ["backtrace"] }
bitflags = "1.2.1"
clap = "3.0.0-beta.2"
derivative = "2.2.0"
derive_builder = "0.10.2"
panorama-imap = { path = "../imap" }
serde = { version = "1.0.127", features = ["derive"] }
tokio = { version = "1.9.0", features = ["full"] }
log = "0.4.14"
env_logger = "0.9.0"
futures = "0.3.16"
async-trait = "0.1.51"

2
mbsync/README.md Normal file
View file

@ -0,0 +1,2 @@
mbsync
===

333
mbsync/src/config.rs Normal file
View file

@ -0,0 +1,333 @@
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use anyhow::Result;
pub fn read_from_file(path: impl AsRef<Path>) -> Result<Config> {
let path = path.as_ref();
let file = File::open(path)?;
read_from_reader(file)
}
pub fn read_from_reader<R: Read>(r: R) -> Result<Config> {
let r = BufReader::new(r);
// store each element here
let mut accounts = HashMap::new();
let mut stores = HashMap::new();
let mut channels = HashMap::new();
enum Section {
ImapAccount(ImapAccountBuilder),
ImapStore(ImapStoreBuilder),
MaildirStore(MaildirStoreBuilder),
Channel(ChannelBuilder),
}
let mut current_section = None;
// this is called whenever we encounter a new section
// it wraps up the current builder and adds it to the appropriate table
let finish_section = |accounts: &mut HashMap<_, _>,
stores: &mut HashMap<_, _>,
channels: &mut HashMap<_, _>,
current_section: &mut Option<Section>|
-> Result<()> {
match current_section {
Some(Section::ImapAccount(builder)) => {
let account = builder.build()?;
accounts.insert(account.name.clone(), Account::Imap(account));
}
Some(Section::ImapStore(builder)) => {
let store = builder.build()?;
stores.insert(store.name.clone(), Store::Imap(store));
}
Some(Section::MaildirStore(builder)) => {
let store = builder.build()?;
stores.insert(store.name.clone(), Store::Maildir(store));
}
Some(Section::Channel(builder)) => {
let channel = builder.build()?;
channels.insert(channel.name.clone(), channel);
}
None => {}
};
*current_section = None;
Ok(())
};
for line in r.lines() {
let line = line?.trim().to_string();
// ignore empty lines and comments
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts = line.split(" ").collect::<Vec<_>>();
match parts[0].to_lowercase().as_str() {
"imapaccount" => {
finish_section(
&mut accounts,
&mut stores,
&mut channels,
&mut current_section,
)?;
let mut builder = ImapAccountBuilder::default();
builder.name(parts[1].to_string());
current_section = Some(Section::ImapAccount(builder));
}
"host" => match current_section.as_mut() {
Some(Section::ImapAccount(ref mut builder)) => {
builder.host(parts[1].to_string());
}
_ => panic!("unexpected host keyword"),
},
"user" => match current_section.as_mut() {
Some(Section::ImapAccount(ref mut builder)) => {
builder.user(parts[1].to_string());
}
_ => panic!("unexpected user keyword"),
},
"pass" => match current_section.as_mut() {
Some(Section::ImapAccount(ref mut builder)) => {
builder.pass(parts[1].to_string());
}
_ => panic!("unexpected pass keyword"),
},
"ssltype" => match current_section.as_mut() {
Some(Section::ImapAccount(ref mut builder)) => {
builder.ssltype(match parts[1].to_lowercase().as_str() {
"none" => SslType::None,
"starttls" => SslType::Starttls,
"imaps" => SslType::Imaps,
unknown => panic!("unknown ssl type '{}'", unknown),
});
}
_ => panic!("unexpected ssltype keyword"),
},
"imapstore" => {
finish_section(
&mut accounts,
&mut stores,
&mut channels,
&mut current_section,
)?;
let mut builder = ImapStoreBuilder::default();
builder.name(parts[1].to_string());
current_section = Some(Section::ImapStore(builder));
}
"account" => match current_section.as_mut() {
Some(Section::ImapStore(ref mut builder)) => {
builder.account(parts[1].to_string());
}
_ => panic!("unexpected account keyword"),
},
"maildirstore" => {
finish_section(
&mut accounts,
&mut stores,
&mut channels,
&mut current_section,
)?;
let mut builder = MaildirStoreBuilder::default();
builder.name(parts[1].to_string());
current_section = Some(Section::MaildirStore(builder));
}
"path" => match current_section.as_mut() {
Some(Section::MaildirStore(ref mut builder)) => {
builder.path(PathBuf::from(parts[1].to_string()));
}
_ => panic!("unexpected path keyword"),
},
"inbox" => match current_section.as_mut() {
Some(Section::MaildirStore(ref mut builder)) => {
builder.inbox(PathBuf::from(parts[1].to_string()));
}
_ => panic!("unexpected inbox keyword"),
},
"subfolders" => match current_section.as_mut() {
Some(Section::MaildirStore(ref mut builder)) => {
builder.subfolders(
match parts[1].to_lowercase().as_str() {
"verbatim" => MaildirSubfolderStyle::Verbatim,
"maildir++" => MaildirSubfolderStyle::Maildirpp,
"legacy" => MaildirSubfolderStyle::Legacy,
unknown => {
panic!("unknown subfolder style '{}'", unknown)
}
},
);
}
_ => panic!("unexpected subfolders keyword"),
},
"channel" => {
finish_section(
&mut accounts,
&mut stores,
&mut channels,
&mut current_section,
)?;
let mut builder = ChannelBuilder::default();
builder.name(parts[1].to_string());
current_section = Some(Section::Channel(builder));
}
"far" => match current_section.as_mut() {
Some(Section::Channel(ref mut builder)) => {
builder.far(parts[1].trim_matches(':').to_string());
}
_ => panic!("unexpected far keyword"),
},
"near" => match current_section.as_mut() {
Some(Section::Channel(ref mut builder)) => {
builder.near(parts[1].trim_matches(':').to_string());
}
_ => panic!("unexpected near keyword"),
},
"sync" => match current_section.as_mut() {
Some(Section::Channel(ref mut builder)) => {
builder.sync(parts[1..].iter().fold(
ChannelSyncOps::empty(),
|a, b| {
a | match b.to_lowercase().as_str() {
"none" => ChannelSyncOps::empty(),
"pull" => ChannelSyncOps::PULL,
"push" => ChannelSyncOps::PUSH,
"new" => ChannelSyncOps::NEW,
"renew" => ChannelSyncOps::RENEW,
"delete" => ChannelSyncOps::DELETE,
"flags" => ChannelSyncOps::FLAGS,
"all" => ChannelSyncOps::all(),
unknown => {
panic!("unknown sync op '{}'", unknown)
}
}
},
));
}
_ => panic!("unexpected near keyword"),
},
unknown => panic!("unknown keyword '{}'", unknown),
}
}
// finish again at the end
finish_section(
&mut accounts,
&mut stores,
&mut channels,
&mut current_section,
)?;
let config = Config {
accounts,
stores,
channels,
};
check_config(&config)?;
Ok(config)
}
/// Double check that all the names being referred to actually exist
fn check_config(config: &Config) -> Result<()> {
for store in config.stores.values() {
if let Store::Imap(store) = store {
ensure!(config.accounts.contains_key(&store.account));
}
}
for channel in config.channels.values() {
ensure!(config.stores.contains_key(&channel.near));
ensure!(config.stores.contains_key(&channel.far));
}
Ok(())
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub accounts: HashMap<String, Account>,
pub stores: HashMap<String, Store>,
pub channels: HashMap<String, Channel>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Account {
Imap(ImapAccount),
}
#[derive(Clone, Derivative, Builder, Serialize, Deserialize)]
#[derivative(Debug)]
pub struct ImapAccount {
pub name: String,
pub host: String,
#[builder(default)]
pub port: Option<u16>,
#[builder(default = "20")]
pub timeout: u32,
pub user: String,
pub ssltype: SslType,
#[derivative(Debug = "ignore")]
pub pass: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SslType {
None,
Starttls,
Imaps,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum Store {
Maildir(MaildirStore),
Imap(ImapStore),
}
#[derive(Debug, Clone, Builder, Serialize, Deserialize)]
pub struct MaildirStore {
pub name: String,
pub path: PathBuf,
pub inbox: PathBuf,
pub subfolders: MaildirSubfolderStyle,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MaildirSubfolderStyle {
Verbatim,
Maildirpp,
Legacy,
}
#[derive(Debug, Builder, Serialize, Deserialize)]
pub struct ImapStore {
pub name: String,
pub account: String,
}
#[derive(Debug, Builder, Serialize, Deserialize)]
pub struct Channel {
pub name: String,
pub far: String,
pub near: String,
pub sync: ChannelSyncOps,
}
bitflags! {
#[derive(Serialize, Deserialize)]
pub struct ChannelSyncOps: u32 {
const PULL = 1 << 1;
const PUSH = 1 << 2;
const NEW = 1 << 3;
const RENEW = 1 << 4;
const DELETE = 1 << 5;
const FLAGS = 1 << 6;
}
}

17
mbsync/src/lib.rs Normal file
View file

@ -0,0 +1,17 @@
#[macro_use]
extern crate anyhow;
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate derivative;
#[macro_use]
extern crate derive_builder;
#[macro_use]
extern crate serde;
#[macro_use]
extern crate log;
#[macro_use]
extern crate async_trait;
pub mod config;
pub mod store;

60
mbsync/src/main.rs Normal file
View file

@ -0,0 +1,60 @@
#[macro_use]
extern crate log;
use std::path::PathBuf;
use anyhow::Result;
use clap::Clap;
use futures::join;
use panorama_mbsync::{
config::{self, ChannelSyncOps},
store,
};
#[derive(Debug, Clap)]
struct Opt {
/// The path to the config file (defaults to ~/.mbsyncrc).
#[clap(name = "config", long = "config", short = 'c')]
config_path: Option<PathBuf>,
/// Verbose mode (-v, -vv, -vvv, etc)
#[clap(short = 'v', long = "verbose", parse(from_occurrences))]
verbose: usize,
}
#[tokio::main]
async fn main() -> Result<()> {
let opt = Opt::parse();
info!("opts: {:?}", opt);
env_logger::init();
let config_path = match opt.config_path {
Some(path) => path,
None => PathBuf::from(env!("HOME")).join(".mbsyncrc"),
};
info!("config path: {:?}", config_path);
let config = config::read_from_file(&config_path)?;
info!("config: {:?}", config);
for channel in config.channels.values() {
info!("beginning to sync {}", channel.name);
let mut far = store::create(&config, &channel.far);
let mut near = store::create(&config, &channel.near);
let (far_res, near_res) = join!(far.open(), near.open());
far_res?;
near_res?;
// let far = store::open(&config, &channel.far).await?;
// let near = store::open(&config, &channel.near).await?;
// if channel.sync.contains(ChannelSyncOps::PULL) {
// store::sync(&far, &near, channel.sync).await?;
// }
}
Ok(())
}

125
mbsync/src/store-old.rs Normal file
View file

@ -0,0 +1,125 @@
use std::path::PathBuf;
use anyhow::Result;
use panorama_imap::client::{auth::Login, ClientAuthenticated, ConfigBuilder};
use crate::config::{Account, ChannelSyncOps, Config, SslType, Store};
pub async fn open(config: &Config, store_name: impl AsRef<str>) -> Result<OpenedStore> {
let store = config
.stores
.get(store_name.as_ref())
.expect("already checked by config reader");
match store {
Store::Imap(store) => {
let account = config
.accounts
.get(&store.account)
.expect("already checked by config reader");
debug!("account: {:?}", account);
match account {
Account::Imap(account) => {
let port = account.port.unwrap_or_else(|| match account.ssltype {
SslType::None | SslType::Starttls => 143,
SslType::Imaps => 993,
});
let tls = match account.ssltype {
SslType::None | SslType::Starttls => false,
SslType::Imaps => true,
};
trace!("opening client...");
let mut client = ConfigBuilder::default()
.hostname(account.host.clone())
.port(port)
.tls(tls)
.open()
.await?;
trace!("opened.");
if let SslType::Starttls = account.ssltype {
trace!("upgrading client...");
client = client.upgrade().await?;
trace!("upgraded.");
}
println!("connected");
let login = Login {
username: account.user.clone(),
password: account.pass.clone(),
};
let mut client = client.auth(login).await?;
let select = client.select("INBOX").await?;
println!("select: {:?}", select);
use futures::stream::StreamExt;
use panorama_imap::proto::command::FetchItems;
let mut result = client.uid_fetch(&[8225], &[], FetchItems::All).await?;
while let Some(item) = result.next().await {
println!("epic: {:?}", item);
}
println!("authenticated");
Ok(OpenedStore::Imap(ImapStore {
name: account.name.clone(),
client,
}))
}
}
}
Store::Maildir(store) => {
let path = store.path.clone();
Ok(OpenedStore::Maildir(MaildirStore {
name: store.name.clone(),
path,
}))
}
}
}
pub enum OpenedStore {
Imap(ImapStore),
Maildir(MaildirStore),
}
pub async fn sync(from: &OpenedStore, to: &OpenedStore, flags: ChannelSyncOps) -> Result<()> {
println!("{} -> {}", from.name(), to.name());
let from_uid = from.uid();
let to_uid = to.uid();
Ok(())
}
impl OpenedStore {
fn name(&self) -> &str {
match self {
OpenedStore::Imap(store) => &store.name,
OpenedStore::Maildir(store) => &store.name,
}
}
async fn uid(&self) -> Result<u32> {
match self {
OpenedStore::Imap(store) => {
todo!()
}
OpenedStore::Maildir(store) => {
todo!()
}
}
}
}
pub struct ImapStore {
name: String,
client: ClientAuthenticated,
}
pub struct MaildirStore {
name: String,
path: PathBuf,
}

145
mbsync/src/store.rs Normal file
View file

@ -0,0 +1,145 @@
use anyhow::Result;
use panorama_imap::client::{
auth::Login, ClientAuthenticated, ClientUnauthenticated, ConfigBuilder,
};
use crate::config::{
Account as AccountConfig, Config, ImapAccount as ImapAccountConfig,
MaildirStore as MaildirStoreConfig, SslType, Store as StoreConfig,
};
pub fn create(config: &Config, store_name: impl AsRef<str>) -> Box<dyn IStore> {
let store = config
.stores
.get(store_name.as_ref())
.expect("already checked by config reader");
match store {
StoreConfig::Imap(store) => {
let account = config
.accounts
.get(&store.account)
.expect("already checked by config reader");
debug!("account: {:?}", account);
match account {
AccountConfig::Imap(account) => ImapStore::new(account.clone()),
}
}
StoreConfig::Maildir(store) => MaildirStore::new(store.clone()),
}
}
#[async_trait]
pub trait IStore {
async fn open(&mut self) -> Result<()>;
async fn get_uidnext(&self) -> Result<usize> { todo!() }
async fn create_mailbox(&mut self) -> Result<()> { todo!() }
async fn open_mailbox(&mut self) -> Result<()> { todo!() }
async fn delete_mailbox(&mut self) -> Result<()> { todo!() }
async fn prepare_load_mailbox(&mut self, opts: u32) -> Result<()> {
todo!()
}
async fn close_mailbox(&mut self) -> Result<()> { todo!() }
async fn load_mailbox(&mut self) -> Result<()> { todo!() }
async fn fetch_message(&mut self) -> Result<()> { todo!() }
async fn store_message(&mut self) -> Result<()> { todo!() }
async fn trash_message(&mut self) -> Result<()> { todo!() }
}
pub struct ImapStore {
config: ImapAccountConfig,
client: Option<ClientAuthenticated>,
}
impl ImapStore {
pub fn new(config: ImapAccountConfig) -> Box<dyn IStore> {
Box::new(ImapStore {
config,
client: None,
})
}
}
#[async_trait]
impl IStore for ImapStore {
async fn open(&mut self) -> Result<()> {
let account = &self.config;
let port = account.port.unwrap_or_else(|| match account.ssltype {
SslType::None | SslType::Starttls => 143,
SslType::Imaps => 993,
});
let tls = match account.ssltype {
SslType::None | SslType::Starttls => false,
SslType::Imaps => true,
};
trace!("opening client...");
let mut client = ConfigBuilder::default()
.hostname(account.host.clone())
.port(port)
.tls(tls)
.open()
.await?;
trace!("opened.");
if let SslType::Starttls = account.ssltype {
trace!("upgrading client...");
client = client.upgrade().await?;
trace!("upgraded.");
}
println!("connected");
let login = Login {
username: account.user.clone(),
password: account.pass.clone(),
};
let mut client = client.auth(login).await?;
let select = client.select("INBOX").await?;
println!("select: {:?}", select);
use futures::stream::StreamExt;
use panorama_imap::proto::command::FetchItems;
let mut result =
client.uid_fetch(&[8225], &[], FetchItems::All).await?;
while let Some(item) = result.next().await {
println!("epic: {:?}", item);
}
println!("authenticated");
self.client = Some(client);
Ok(())
}
}
pub struct MaildirStore {
config: MaildirStoreConfig,
}
impl MaildirStore {
pub fn new(config: MaildirStoreConfig) -> Box<dyn IStore> {
Box::new(MaildirStore { config })
}
}
#[async_trait]
impl IStore for MaildirStore {
async fn open(&mut self) -> Result<()> {
println!("Hellosu! {:?}", self.config);
Ok(())
}
}

View file

@ -1,47 +0,0 @@
{
"name": "panorama",
"version": "0.1.0",
"description": "",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"tauri": "tauri"
},
"license": "MIT",
"dependencies": {
"@fortawesome/free-brands-svg-icons": "^6.6.0",
"@fortawesome/free-solid-svg-icons": "^6.6.0",
"@iconify-json/mdi": "^1.2.1",
"@iconify/json": "^2.2.267",
"@iconify/svelte": "^4.0.2",
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-shell": "^2",
"@vanilla-extract/css": "^1.16.0",
"classnames": "^2.5.1",
"svelte-fa": "^4.0.3",
"unplugin-icons": "^0.20.0"
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@sveltejs/adapter-static": "^3.0.5",
"@sveltejs/kit": "^2.7.0",
"@sveltejs/vite-plugin-svelte": "^4.0.0",
"@tauri-apps/cli": "^2",
"@vanilla-extract/vite-plugin": "^4.0.17",
"sass-embedded": "^1.80.6",
"svelte": "^5.0.0",
"svelte-check": "^4.0.0",
"tslib": "^2.8.0",
"typescript": "^5.5.0",
"vite": "^5.4.10"
},
"trustedDependencies": [
"@biomejs/biome",
"@sveltejs/kit",
"esbuild"
]
}

25
proto-common/Cargo.toml Normal file
View file

@ -0,0 +1,25 @@
[package]
name = "panorama-proto-common"
description = "Common code between protocol implementations"
version = "0.0.1"
edition = "2018"
authors = ["Michael Zhang <mail@mzhang.io>"]
license = "GPL-3.0-or-later"
repository = "https://git.mzhang.io/michael/panorama"
workspace = ".."
[features]
default = []
fuzzing = ["arbitrary"]
[dependencies]
anyhow = { version = "1.0.45", features = ["backtrace"] }
bstr = "0.2.17"
bytes = "1.1.0"
format-bytes = "0.2.2"
log = "0.4.14"
nom = "7.0.0"
# for fuzzing
arbitrary = { version = "1.0.2", optional = true, features = ["derive"] }
num-traits = "0.2.14"

321
proto-common/src/bytes.rs Normal file
View file

@ -0,0 +1,321 @@
use std::io::{self, Write};
use std::ops::{Deref, RangeBounds};
use format_bytes::DisplayBytes;
use nom::{
error::{ErrorKind, ParseError},
CompareResult, Err, HexDisplay, IResult, InputLength, Needed,
};
#[cfg(feature = "fuzzing")]
use arbitrary::{self, Arbitrary, Unstructured};
/// Glue code between nom and Bytes so they work together.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Bytes(bytes::Bytes);
#[cfg(feature = "fuzzing")]
impl<'a> Arbitrary<'a> for Bytes {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Bytes::from(<Vec<u8>>::arbitrary(u)?))
}
}
impl Bytes {
/// Length of the internal `Bytes`.
///
/// # Example
///
/// ```
/// # use panorama_proto_common::Bytes;
/// // the &, [..] is needed since &[u8; N] doesn't coerce automatically to &[u8]
/// let b = Bytes::from(&b"hello"[..]);
/// assert_eq!(b.len(), 5);
/// ```
pub fn len(&self) -> usize { self.0.len() }
/// Consumes the wrapper, returning the original `Bytes`.
pub fn inner(self) -> bytes::Bytes { self.0 }
}
impl DisplayBytes for Bytes {
fn display_bytes(&self, w: &mut dyn Write) -> io::Result<()> {
w.write(&*self.0).map(|_| ())
}
}
static CHARS: &[u8] = b"0123456789abcdef";
impl HexDisplay for Bytes {
fn to_hex(&self, chunk_size: usize) -> String {
self.to_hex_from(chunk_size, 0)
}
fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {
let mut v = Vec::with_capacity(self.len() * 3);
let mut i = from;
for chunk in self.chunks(chunk_size) {
let s = format!("{:08x}", i);
for &ch in s.as_bytes().iter() {
v.push(ch);
}
v.push(b'\t');
i += chunk_size;
for &byte in chunk {
v.push(CHARS[(byte >> 4) as usize]);
v.push(CHARS[(byte & 0xf) as usize]);
v.push(b' ');
}
if chunk_size > chunk.len() {
for _ in 0..(chunk_size - chunk.len()) {
v.push(b' ');
v.push(b' ');
v.push(b' ');
}
}
v.push(b'\t');
for &byte in chunk {
if (byte >= 32 && byte <= 126) || byte >= 128 {
v.push(byte);
} else {
v.push(b'.');
}
}
v.push(b'\n');
}
String::from_utf8_lossy(&v[..]).into_owned()
}
}
impl From<bytes::Bytes> for Bytes {
fn from(b: bytes::Bytes) -> Self { Bytes(b) }
}
impl From<&'static [u8]> for Bytes {
fn from(slice: &'static [u8]) -> Self { Bytes(bytes::Bytes::from(slice)) }
}
impl From<Vec<u8>> for Bytes {
fn from(slice: Vec<u8>) -> Self { Bytes(bytes::Bytes::from(slice)) }
}
impl From<&'static str> for Bytes {
fn from(s: &'static str) -> Self { Bytes(bytes::Bytes::from(s.as_bytes())) }
}
impl From<String> for Bytes {
fn from(slice: String) -> Self { Bytes(bytes::Bytes::from(slice)) }
}
pub trait ShitNeededForParsing: Sized {
type Item;
type Sliced;
fn slice<R: RangeBounds<usize>>(&self, range: R) -> Self::Sliced;
fn first(&self) -> Option<Self::Item>;
fn slice_index(&self, count: usize) -> Result<usize, Needed>;
// InputTake
fn take(&self, count: usize) -> Self;
fn take_split(&self, count: usize) -> (Self, Self);
// InputTakeAtPosition
fn split_at_position<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
fn split_at_position1<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
fn split_at_position_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
fn split_at_position1_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool;
}
impl ShitNeededForParsing for Bytes {
type Item = u8;
type Sliced = Bytes;
fn slice<R: RangeBounds<usize>>(&self, range: R) -> Self::Sliced {
Self(self.0.slice(range))
}
fn first(&self) -> Option<Self::Item> { self.0.first().copied() }
fn slice_index(&self, count: usize) -> Result<usize, Needed> {
if self.len() >= count {
Ok(count)
} else {
Err(Needed::new(count - self.len()))
}
}
// InputTake
fn take(&self, count: usize) -> Self { self.slice(..count) }
fn take_split(&self, count: usize) -> (Self, Self) {
let mut prefix = self.clone();
let suffix = Self(prefix.0.split_off(count));
(suffix, prefix)
}
// InputTakeAtPosition
fn split_at_position<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match (0..self.len()).find(|b| predicate(self[*b])) {
Some(i) => Ok((self.slice(i..), self.slice(..i))),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position1<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match (0..self.len()).find(|b| predicate(self[*b])) {
Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))),
Some(i) => Ok((self.slice(i..), self.slice(..i))),
None => Err(Err::Incomplete(Needed::new(1))),
}
}
fn split_at_position_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match (0..self.len()).find(|b| predicate(self[*b])) {
Some(i) => Ok((self.slice(i..), self.slice(..i))),
None => Ok(self.take_split(self.input_len())),
}
}
fn split_at_position1_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match (0..self.len()).find(|b| predicate(self[*b])) {
Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))),
Some(i) => Ok((self.slice(i..), self.slice(..i))),
None => {
if self.is_empty() {
Err(Err::Error(E::from_error_kind(self.clone(), e)))
} else {
Ok(self.take_split(self.input_len()))
}
}
}
}
}
pub trait ShitCompare<T> {
fn compare(&self, t: T) -> CompareResult;
fn compare_no_case(&self, t: T) -> CompareResult;
}
impl ShitCompare<&[u8]> for Bytes {
fn compare(&self, other: &[u8]) -> CompareResult {
match self.iter().zip(other.iter()).any(|(a, b)| a != b) {
true => CompareResult::Error,
false if self.len() < other.len() => CompareResult::Incomplete,
false => CompareResult::Ok,
}
}
fn compare_no_case(&self, other: &[u8]) -> CompareResult {
match self
.iter()
.zip(other.iter())
.any(|(a, b)| (a | 0x20) != (b | 0x20))
{
true => CompareResult::Error,
false if self.len() < other.len() => CompareResult::Incomplete,
false => CompareResult::Ok,
}
}
}
macro_rules! array_impls {
($($N:expr)+) => { $(
impl ShitCompare<[u8; $N]> for Bytes {
#[inline(always)]
fn compare(&self, t: [u8; $N]) -> CompareResult {
self.compare(&t[..])
}
#[inline(always)]
fn compare_no_case(&self, t: [u8;$N]) -> CompareResult {
self.compare_no_case(&t[..])
}
}
impl ShitCompare<&[u8; $N]> for Bytes {
#[inline(always)]
fn compare(&self, t: &[u8; $N]) -> CompareResult {
self.compare(&t[..])
}
#[inline(always)]
fn compare_no_case(&self, t: &[u8;$N]) -> CompareResult {
self.compare_no_case(&t[..])
}
}
impl From<&'static [u8; $N]> for Bytes {
fn from(slice: &'static [u8; $N]) -> Self { Bytes(bytes::Bytes::from(&slice[..])) }
}
)* }
}
array_impls! {
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
}
impl Deref for Bytes {
type Target = [u8];
fn deref(&self) -> &Self::Target { &*self.0 }
}
impl AsRef<[u8]> for Bytes {
fn as_ref(&self) -> &[u8] { &*self.0 }
}
impl InputLength for Bytes {
fn input_len(&self) -> usize { self.0.len() }
}

Some files were not shown because too many files have changed in this diff Show more