charset-0.1.3/.cargo_vcs_info.json0000644000000001120000000000100124600ustar { "git": { "sha1": "8cc039527a4c286a5d73abfb0803e73b4288eb8c" } } charset-0.1.3/.gitignore000064400000000000000000000000360072674642500132750ustar 00000000000000/target **/*.rs.bk Cargo.lock charset-0.1.3/CONTRIBUTING.md000064400000000000000000000027250072674642500135450ustar 00000000000000If you send a pull request / patch, please observe the following. ## Licensing Since this crate is dual-licensed, [section 5 of the Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0#contributions) is considered to apply in the sense of Contributions being automatically under the Apache License 2.0 or MIT dual license (see the `COPYRIGHT` file). That is, by the act of offering a Contribution, you place your Contribution under the Apache License 2.0 or MIT dual license stated in the `COPYRIGHT` file. Please do not contribute if you aren't willing or allowed to license your contributions in this manner. You are encouraged to dedicate test code that you contribute to the Public Domain using the CC0 dedication. If you contribute test code that is not dedicated to the Public Domain, please be sure not to put it in a part of source code that the comments designate as being dedicated to the Public Domain. ## Copyright Notices If you require the addition of your copyright notice, it's up to you to edit in your notice as part of your Contribution. Not adding a copyright notice is taken as a waiver of copyright notice. ## Compatibility with Stable Rust Please ensure that your Contribution compiles with the latest stable-channel rustc. ## rustfmt The `rustfmt` version used for this code is `rustfmt-nightly`. Please either use that version or avoid using `rustfmt` (so as not to reformat all the code). ## Unit tests Please ensure that `cargo test` succeeds. charset-0.1.3/COPYRIGHT000064400000000000000000000010040072674642500125740ustar 00000000000000charset is copyright 2013-2016 Mozilla Foundation. Licensed under the Apache License, Version 2.0 or the MIT license , at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. Test code within encoding_rs is dedicated to the Public Domain when so designated (see the individual files for PD/CC0-dedicated sections). charset-0.1.3/Cargo.toml0000644000000024070000000000100104670ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "charset" version = "0.1.3" authors = ["Henri Sivonen "] description = "Thunderbird-compatible character encoding decoding for email" homepage = "https://docs.rs/charset/" documentation = "https://docs.rs/charset/" readme = "README.md" keywords = ["encoding", "email", "unicode", "charset", "utf-7"] categories = ["text-processing", "encoding", "email"] license = "MIT/Apache-2.0" repository = "https://github.com/hsivonen/charset" [dependencies.base64] version = "0.13" [dependencies.encoding_rs] version = "0.8.22" [dependencies.serde] version = "1.0" optional = true [dev-dependencies.bincode] version = "1.2.1" [dev-dependencies.serde_derive] version = "1.0" [dev-dependencies.serde_json] version = "1.0" [badges.travis-ci] repository = "hsivonen/charset" charset-0.1.3/Cargo.toml.orig000064400000000000000000000013240072674642500141750ustar 00000000000000[package] name = "charset" description = "Thunderbird-compatible character encoding decoding for email" version = "0.1.3" authors = ["Henri Sivonen "] edition = "2018" license = "MIT/Apache-2.0" readme = "README.md" documentation = "https://docs.rs/charset/" homepage = "https://docs.rs/charset/" repository = "https://github.com/hsivonen/charset" keywords = ["encoding", "email", "unicode", "charset", "utf-7"] categories = ["text-processing", "encoding", "email"] [badges] travis-ci = { repository = "hsivonen/charset" } [dependencies] encoding_rs = "0.8.22" base64 = "0.13" serde = { version = "1.0", optional = true } [dev-dependencies] serde_derive = "1.0" bincode = "1.2.1" serde_json = "1.0" charset-0.1.3/LICENSE-APACHE000064400000000000000000000261360072674642500132420ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. charset-0.1.3/LICENSE-MIT000064400000000000000000000020530072674642500127420ustar 00000000000000Copyright (c) 2013-2016 Mozilla Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. charset-0.1.3/README.md000064400000000000000000000106210072674642500125650ustar 00000000000000# charset [![crates.io](https://meritbadge.herokuapp.com/charset)](https://crates.io/crates/charset) [![docs.rs](https://docs.rs/charset/badge.svg)](https://docs.rs/charset/) [![Apache-2.0 OR MIT dual-licensed](https://img.shields.io/badge/license-Apache%202%20%2F%20MIT-blue.svg)](https://github.com/hsivonen/charset/blob/master/COPYRIGHT) `charset` is a wrapper around [`encoding_rs`][1] that provides (non-streaming) decoding for character encodings that occur in _email_ by providing decoding for [UTF-7][2] in addition to the encodings defined by the [Encoding Standard][3] (and provided by `encoding_rs`). _Note:_ Do _not_ use this crate for consuming _Web_ content. For security reasons, consumers of Web content are [_prohibited_][4] from supporting UTF-7. Use `encoding_rs` directly when consuming Web content. The set of encodings consisting of UTF-7 and the encodings defined in the Encoding Standard is believed to be appropriate for consuming email, because that's the set of encodings supported by [Thunderbird][5]. Furthermore, UTF-7 support is believed to be necessary based on the experience of the Firefox OS email client. In fact, while the UTF-7 implementation in this crate is independent of Thunderbird's UTF-7 implementation, Thunderbird uses `encoding_rs` to decode the other encodings. The set of _labels_/_aliases_ recognized by this crate matches those recognized by Thunderbird 60.0. Prior versions of Thunderbird as well as version 60.4 and later recognize more labels. Support for those is a TODO item for this crate. Known compatibility limitations (shared with Thunderbird and known from Thunderbird bug reports): * JavaMail may use non-standard labels for legacy encodings such that the labels aren't recognized by this crate even if the encodings themselves would be supported. (Fixed in Thunderbird 60.4 but not in this crate.) * Some ancient Usenet posting in Chinese may not be decodable, because this crate does not support HZ. * Some emails sent in Chinese by Sun's email client for CDE on Solaris around the turn of the millennium may not decodable, because this crate does not support ISO-2022-CN. * Some emails sent in Korean by IBM/Lotus Notes may not be decodable, because this crate does not support ISO-2022-KR. This crate intentionally does not support encoding content into legacy encodings. When sending email, _always_ use UTF-8. This is, just call `.as_bytes()` on `&str` and label the content as `UTF-8`. [1]: https://crates.io/crates/encoding_rs/ [2]: https://tools.ietf.org/html/rfc2152 [3]: https://encoding.spec.whatwg.org/ [4]: https://html.spec.whatwg.org/#character-encodings [5]: https://thunderbird.net/ ## Licensing Apache-2.0 OR MIT; please see the file named [COPYRIGHT](https://github.com/hsivonen/charset/blob/master/COPYRIGHT). ## API Documentation Generated [API documentation](https://docs.rs/charset/) is available online. ## Security Considerations Again, this crate is for _email_. Please do _NOT_ use it for _Web_ content. Never try to perform any security analysis on the undecoded data in ASCII-incompatible encodings and in UTF-7 in particular. Always decode first and analyze after. UTF-7 allows even characters that don't have to be represented as base64 to be represented as base64. Also, for consistency with Thunderbird, the UTF-7 decoder in this crate allows e.g. ASCII controls to be represented without base64 encoding even when the spec says they should be base64-encoded. This implementation is non-constant-time by design. An attacker who can observe input length and the time it takes to decode it can make guesses about relative proportions of characters from different ranges. Guessing the proportion of ASCII vs. non-ASCII should be particularly feasible. ## Serde support The cargo features `serde` enables Serde support for `Charset`. ## Minimum Rust Version The MSRV depends on the `encoding_rs` and `base64` dependencies; not on this crate. This crate does not undergo semver bumps for `base64` semver bumps. ## Disclaimer This is a personal project. It has a Mozilla copyright notice, because I copied and pasted from encoding_rs. You should not try to read anything more into Mozilla's name appearing. ## Release Notes ### 0.1.3 * Update `base64` to 0.13.0. ### 0.1.2 * Implemented `From<&'static Encoding>` for `Charset`. * Added optional Serde support. ### 0.1.1 * Added `decode_ascii()`. * Added `decode_latin1()`. ### 0.1.0 Initial release.charset-0.1.3/src/lib.rs000064400000000000000000000766310072674642500132260ustar 00000000000000// Copyright 2015-2016 Mozilla Foundation. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! `charset` is a wrapper around [`encoding_rs`][1] that provides //! (non-streaming) decoding for character encodings that occur in _email_ by //! providing decoding for [UTF-7][2] in addition to the encodings defined by //! the [Encoding Standard][3] (and provided by `encoding_rs`). //! //! _Note:_ Do _not_ use this crate for consuming _Web_ content. For security //! reasons, consumers of Web content are [_prohibited_][4] from supporting //! UTF-7. Use `encoding_rs` directly when consuming Web content. //! //! The set of encodings consisting of UTF-7 and the encodings defined in the //! Encoding Standard is believed to be appropriate for consuming email, //! because that's the set of encodings supported by [Thunderbird][5]. //! Furthermore, UTF-7 support is believed to be necessary based on the //! experience of the Firefox OS email client. In fact, while the UTF-7 //! implementation in this crate is independent of Thunderbird's UTF-7 //! implementation, Thunderbird uses `encoding_rs` to decode the other //! encodings. The set of _labels_/_aliases_ recognized by this crate matches //! those recognized by Thunderbird. //! //! Known compatibility limitations (shared with Thunderbird and known from //! Thunderbird bug reports): //! //! * JavaMail may use non-standard labels for legacy encodings such that //! the labels aren't recognized by this crate even if the encodings //! themselves would be supported. //! * Some ancient Usenet posting in Chinese may not be decodable, because //! this crate does not support HZ. //! * Some emails sent in Chinese by Sun's email client for CDE on Solaris //! around the turn of the millennium may not decodable, because this //! crate does not support ISO-2022-CN. //! * Some emails sent in Korean by IBM/Lotus Notes may not be decodable, //! because this crate does not support ISO-2022-KR. //! //! This crate intentionally does not support encoding content into legacy //! encodings. When sending email, _always_ use UTF-8. This is, just call //! `.as_bytes()` on `&str` and label the content as `UTF-8`. //! //! [1]: https://crates.io/crates/encoding_rs/ //! [2]: https://tools.ietf.org/html/rfc2152 //! [3]: https://encoding.spec.whatwg.org/ //! [4]: https://html.spec.whatwg.org/#character-encodings //! [5]: https://thunderbird.net/ //! //! # Security considerations //! //! Again, this crate is for _email_. Please do _NOT_ use it for _Web_ //! content. //! //! Never try to perform any security analysis on the undecoded data in //! ASCII-incompatible encodings and in UTF-7 in particular. Always decode //! first and analyze after. UTF-7 allows even characters that don't have to //! be represeted as base64 to be represented as base64. Also, for consistency //! with Thunderbird, the UTF-7 decoder in this crate allows e.g. ASCII //! controls to be represented without base64 encoding even when the spec //! says they should be base64-encoded. //! //! This implementation is non-constant-time by design. An attacker who //! can observe input length and the time it takes to decode it can make //! guesses about relative proportions of characters from different ranges. //! Guessing the proportion of ASCII vs. non-ASCII should be particularly //! feasible. extern crate base64; extern crate encoding_rs; #[cfg(feature = "serde")] extern crate serde; #[cfg(all(test, feature = "serde"))] extern crate bincode; #[cfg(all(test, feature = "serde"))] #[macro_use] extern crate serde_derive; #[cfg(all(test, feature = "serde"))] extern crate serde_json; use encoding_rs::CoderResult; use encoding_rs::Encoding; use encoding_rs::GB18030; use encoding_rs::GBK; use encoding_rs::UTF_16BE; use std::borrow::Cow; #[cfg(feature = "serde")] use serde::de::Visitor; #[cfg(feature = "serde")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// The UTF-7 encoding. pub const UTF_7: Charset = Charset { variant: VariantCharset::Utf7, }; /// Converts bytes whose unsigned value is interpreted as Unicode code point /// (i.e. U+0000 to U+00FF, inclusive) to UTF-8. /// /// This is useful for decoding non-conforming header names such that the /// names stay unique and the decoding cannot fail (except for allocation /// failure). /// /// Borrows if input is ASCII-only. Performs a single heap allocation /// otherwise. pub fn decode_latin1<'a>(bytes: &'a [u8]) -> Cow<'a, str> { encoding_rs::mem::decode_latin1(bytes) } /// Converts ASCII to UTF-8 with non-ASCII bytes replaced with the /// REPLACEMENT CHARACTER. /// /// This is can be used for strict MIME compliance when there is no declared /// encoding. /// /// Borrows if input is ASCII-only. Performs a single heap allocation /// otherwise. pub fn decode_ascii<'a>(bytes: &'a [u8]) -> Cow<'a, str> { let up_to = Encoding::ascii_valid_up_to(bytes); // >= makes later things optimize better than == if up_to >= bytes.len() { debug_assert_eq!(up_to, bytes.len()); let s: &str = unsafe { ::std::str::from_utf8_unchecked(bytes) }; return Cow::Borrowed(s); } let (head, tail) = bytes.split_at(up_to); let capacity = head.len() + tail.len() * 3; let mut vec = Vec::with_capacity(capacity); vec.extend_from_slice(head); for &b in tail.into_iter() { if b < 0x80 { vec.push(b); } else { vec.extend_from_slice("\u{FFFD}".as_bytes()); } } Cow::Owned(unsafe { String::from_utf8_unchecked(vec) }) } /// A character encoding suitable for decoding _email_. /// /// This is either an encoding as defined in the [Encoding Standard][1] /// or UTF-7 as defined in [RFC 2152][2]. /// /// [1]: https://encoding.spec.whatwg.org/ /// [2]: https://tools.ietf.org/html/rfc2152 /// /// Each `Charset` has one or more _labels_ that are used to identify /// the `Charset` in protocol text. In MIME/IANA terminology, these are /// called _names_ and _aliases_, but for consistency with the Encoding /// Standard and the encoding_rs crate, they are called labels in this /// crate. What this crate calls the _name_ (again, for consistency /// with the Encoding Standard and the encoding_rs crate) is known as /// _preferred name_ in MIME/IANA terminology. /// /// Instances of `Charset` can be compared with `==`. `Charset` is /// `Copy` and is meant to be passed by value. /// /// _Note:_ It is wrong to use this for decoding Web content. Use /// `encoding_rs::Encoding` instead! #[derive(PartialEq, Debug, Copy, Clone, Hash)] pub struct Charset { variant: VariantCharset, } impl Charset { /// Implements the /// [_get an encoding_](https://encoding.spec.whatwg.org/#concept-encoding-get) /// algorithm with the label "UTF-7" added to the set of labels recognized. /// GBK is unified with gb18030, since they decode the same and `Charset` /// only supports decoding. /// /// If, after ASCII-lowercasing and removing leading and trailing /// whitespace, the argument matches a label defined in the Encoding /// Standard or "utf-7", `Some(Charset)` representing the corresponding /// encoding is returned. If there is no match, `None` is returned. /// /// This is the right method to use if the action upon the method returning /// `None` is to use a fallback encoding (e.g. `WINDOWS_1252`) instead. /// When the action upon the method returning `None` is not to proceed with /// a fallback but to refuse processing, `for_label_no_replacement()` is more /// appropriate. /// /// The argument is of type `&[u8]` instead of `&str` to save callers /// that are extracting the label from a non-UTF-8 protocol the trouble /// of conversion to UTF-8. (If you have a `&str`, just call `.as_bytes()` /// on it.) #[inline] pub fn for_label(label: &[u8]) -> Option { if let Some(encoding) = Encoding::for_label(label) { Some(Charset::for_encoding(encoding)) } else if is_utf7_label(label) { Some(UTF_7) } else { None } } /// This method behaves the same as `for_label()`, except when `for_label()` /// would return `Some(Charset::for_encoding(encoding_rs::REPLACEMENT))`, /// this method returns `None` instead. /// /// This method is useful in scenarios where a fatal error is required /// upon invalid label, because in those cases the caller typically wishes /// to treat the labels that map to the replacement encoding as fatal /// errors, too. /// /// It is not OK to use this method when the action upon the method returning /// `None` is to use a fallback encoding (e.g. `WINDOWS_1252`) with `text/html` /// email. In such a case, the `for_label()` method should be used instead in /// order to avoid unsafe fallback for labels that `for_label()` maps to /// `Some(REPLACEMENT)`. Such fallback might be safe, though not particularly /// useful for `text/plain` email, though. #[inline] pub fn for_label_no_replacement(label: &[u8]) -> Option { if let Some(encoding) = Encoding::for_label_no_replacement(label) { Some(Charset::for_encoding(encoding)) } else if is_utf7_label(label) { Some(UTF_7) } else { None } } /// Returns the `Charset` corresponding to an `&'static Encoding`. /// /// `GBK` is unified with `GB18030`, since those two decode the same /// and `Charset` only supports decoding. #[inline] pub fn for_encoding(encoding: &'static Encoding) -> Charset { let enc = if encoding == GBK { GB18030 } else { encoding }; Charset { variant: VariantCharset::Encoding(enc), } } /// Performs non-incremental BOM sniffing. /// /// The argument must either be a buffer representing the entire input /// stream (non-streaming case) or a buffer representing at least the first /// three bytes of the input stream (streaming case). /// /// Returns `Some((Charset::for_encoding(encoding_rs::UTF_8), 3))`, /// `Some((Charset::for_encoding(encoding_rs::UTF_16LE), 2))` or /// `Some((Charset::for_encoding(encoding_rs::UTF_16BE), 2))` if the /// argument starts with the UTF-8, UTF-16LE or UTF-16BE BOM or `None` /// otherwise. #[inline] pub fn for_bom(buffer: &[u8]) -> Option<(Charset, usize)> { if let Some((encoding, length)) = Encoding::for_bom(buffer) { Some((Charset::for_encoding(encoding), length)) } else { None } } /// Returns the name of this encoding. /// /// Mostly useful for debugging pub fn name(self) -> &'static str { match self.variant { VariantCharset::Encoding(encoding) => encoding.name(), VariantCharset::Utf7 => "UTF-7", } } /// Checks whether the bytes 0x00...0x7F map exclusively to the characters /// U+0000...U+007F and vice versa. #[inline] pub fn is_ascii_compatible(self) -> bool { match self.variant { VariantCharset::Encoding(encoding) => encoding.is_ascii_compatible(), VariantCharset::Utf7 => false, } } /// Decode complete input to `Cow<'a, str>` _with BOM sniffing_ and with /// malformed sequences replaced with the REPLACEMENT CHARACTER when the /// entire input is available as a single buffer (i.e. the end of the /// buffer marks the end of the stream). /// /// This method implements the (non-streaming version of) the /// [_decode_](https://encoding.spec.whatwg.org/#decode) spec concept. /// /// The second item in the returned tuple is the encoding that was actually /// used (which may differ from this encoding thanks to BOM sniffing). /// /// The third item in the returned tuple indicates whether there were /// malformed sequences (that were replaced with the REPLACEMENT CHARACTER). /// /// _Note:_ It is wrong to use this when the input buffer represents only /// a segment of the input instead of the whole input. /// /// # Panics /// /// If the size calculation for a heap-allocated backing buffer overflows /// `usize`. #[inline] pub fn decode<'a>(self, bytes: &'a [u8]) -> (Cow<'a, str>, Charset, bool) { let (charset, without_bom) = match Charset::for_bom(bytes) { Some((charset, bom_length)) => (charset, &bytes[bom_length..]), None => (self, bytes), }; let (cow, had_errors) = charset.decode_without_bom_handling(without_bom); (cow, charset, had_errors) } /// Decode complete input to `Cow<'a, str>` _with BOM removal_ and with /// malformed sequences replaced with the REPLACEMENT CHARACTER when the /// entire input is available as a single buffer (i.e. the end of the /// buffer marks the end of the stream). /// /// When invoked on `UTF_8`, this method implements the (non-streaming /// version of) the /// [_UTF-8 decode_](https://encoding.spec.whatwg.org/#utf-8-decode) spec /// concept. /// /// The second item in the returned pair indicates whether there were /// malformed sequences (that were replaced with the REPLACEMENT CHARACTER). /// /// _Note:_ It is wrong to use this when the input buffer represents only /// a segment of the input instead of the whole input. /// /// # Panics /// /// If the size calculation for a heap-allocated backing buffer overflows /// `usize`. #[inline] pub fn decode_with_bom_removal<'a>(self, bytes: &'a [u8]) -> (Cow<'a, str>, bool) { match self.variant { VariantCharset::Encoding(encoding) => encoding.decode_with_bom_removal(bytes), VariantCharset::Utf7 => decode_utf7(bytes), } } /// Decode complete input to `Cow<'a, str>` _without BOM handling_ and /// with malformed sequences replaced with the REPLACEMENT CHARACTER when /// the entire input is available as a single buffer (i.e. the end of the /// buffer marks the end of the stream). /// /// When invoked on `UTF_8`, this method implements the (non-streaming /// version of) the /// [_UTF-8 decode without BOM_](https://encoding.spec.whatwg.org/#utf-8-decode-without-bom) /// spec concept. /// /// The second item in the returned pair indicates whether there were /// malformed sequences (that were replaced with the REPLACEMENT CHARACTER). /// /// _Note:_ It is wrong to use this when the input buffer represents only /// a segment of the input instead of the whole input. /// /// # Panics /// /// If the size calculation for a heap-allocated backing buffer overflows /// `usize`. #[inline] pub fn decode_without_bom_handling<'a>(self, bytes: &'a [u8]) -> (Cow<'a, str>, bool) { match self.variant { VariantCharset::Encoding(encoding) => encoding.decode_without_bom_handling(bytes), VariantCharset::Utf7 => decode_utf7(bytes), } } } impl From<&'static Encoding> for Charset { fn from(encoding: &'static Encoding) -> Self { Charset::for_encoding(encoding) } } #[cfg(feature = "serde")] impl Serialize for Charset { #[inline] fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(self.name()) } } #[cfg(feature = "serde")] struct CharsetVisitor; #[cfg(feature = "serde")] impl<'de> Visitor<'de> for CharsetVisitor { type Value = Charset; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("a valid charset label") } fn visit_str(self, value: &str) -> Result where E: serde::de::Error, { if let Some(charset) = Charset::for_label(value.as_bytes()) { Ok(charset) } else { Err(E::custom(format!("invalid charset label: {}", value))) } } } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for Charset { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_str(CharsetVisitor) } } #[inline(never)] fn is_utf7_label(label: &[u8]) -> bool { let mut iter = label.into_iter(); // before loop { match iter.next() { None => { return false; } Some(&byte) => match byte { 0x09u8 | 0x0Au8 | 0x0Cu8 | 0x0Du8 | 0x20u8 => { continue; } b'u' | b'U' => { break; } _ => { return false; } }, } } // inside let tail = iter.as_slice(); if tail.len() < 4 { return false; } match (tail[0] | 0x20, tail[1] | 0x20, tail[2], tail[3]) { (b't', b'f', b'-', b'7') => {} _ => { return false; } } iter = (&tail[4..]).into_iter(); // after loop { match iter.next() { None => { return true; } Some(&byte) => match byte { 0x09u8 | 0x0Au8 | 0x0Cu8 | 0x0Du8 | 0x20u8 => { continue; } _ => { return false; } }, } } } #[inline] fn utf7_ascii_up_to(bytes: &[u8]) -> usize { for (i, &byte) in bytes.into_iter().enumerate() { if byte == b'+' || byte >= 0x80 { return i; } } bytes.len() } #[inline] fn utf7_base64_up_to(bytes: &[u8]) -> usize { for (i, &byte) in bytes.into_iter().enumerate() { match byte { b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'+' | b'/' => {} _ => { return i; } } } bytes.len() } #[inline] fn utf7_base64_decode(bytes: &[u8], string: &mut String) -> bool { // The intermediate buffer should be long enough to fit a line // of 80 base64 bytes and should also be a multiple of 3. This // way, normal email lines will be handled in one go, but // longer sequences won't get split between base64 groups of // 4 input / 3 output bytes. let mut decoder = UTF_16BE.new_decoder_without_bom_handling(); let mut buf = [0u8; 60]; let mut tail = bytes; let mut had_errors = false; let mut trailing_error = false; loop { let (last, mut cap) = if tail.len() <= 80 { (true, tail.len()) } else { (false, 80) }; let len; loop { match base64::decode_config_slice(&tail[..cap], base64::STANDARD_NO_PAD, &mut buf[..]) { Ok(l) => { len = l; break; } Err(_) => { assert!(last); had_errors = true; trailing_error = true; tail = &tail[..tail.len() - 1]; cap -= 1; } } } let mut total_read = 0; loop { let (result, read, err) = decoder.decode_to_string(&buf[total_read..len], string, last); total_read += read; had_errors |= err; match result { CoderResult::InputEmpty => { if last { if trailing_error { string.push_str("\u{FFFD}"); } return had_errors; } break; } CoderResult::OutputFull => { let left = len - total_read; let needed = decoder.max_utf8_buffer_length(left).unwrap(); string.reserve(needed); } } } tail = &tail[80..]; } } #[inline(never)] fn decode_utf7<'a>(bytes: &'a [u8]) -> (Cow<'a, str>, bool) { let up_to = utf7_ascii_up_to(bytes); if up_to == bytes.len() { let s: &str = unsafe { std::str::from_utf8_unchecked(bytes) }; return (Cow::Borrowed(s), false); } let mut had_errors = false; let mut out = String::with_capacity(bytes.len()); out.push_str(unsafe { std::str::from_utf8_unchecked(&bytes[..up_to]) }); let mut tail = &bytes[up_to..]; loop { // `tail[0]` is now either a plus sign or non-ASCII let first = tail[0]; tail = &tail[1..]; if first == b'+' { let up_to = utf7_base64_up_to(tail); had_errors |= utf7_base64_decode(&tail[..up_to], &mut out); if up_to == tail.len() { if up_to == 0 { // Plus sign didn't start a base64 run and also // wasn't followed by a minus. had_errors = true; out.push_str("\u{FFFD}"); } return (Cow::Owned(out), had_errors); } if up_to == 0 { if tail[up_to] == b'-' { // There was no base64 data between // plus and minus, so we had the sequence // meaning the plus sign itself. out.push_str("+"); tail = &tail[up_to + 1..]; } else { // Plus sign didn't start a base64 run and also // wasn't followed by a minus. had_errors = true; out.push_str("\u{FFFD}"); } } else if tail[up_to] == b'-' { tail = &tail[up_to + 1..]; } else { tail = &tail[up_to..]; } } else { had_errors = true; out.push_str("\u{FFFD}"); } let up_to = utf7_ascii_up_to(tail); out.push_str(unsafe { std::str::from_utf8_unchecked(&tail[..up_to]) }); if up_to == tail.len() { return (Cow::Owned(out), had_errors); } tail = &tail[up_to..]; } } #[derive(PartialEq, Debug, Copy, Clone, Hash)] enum VariantCharset { Utf7, Encoding(&'static Encoding), } #[cfg(all(test, feature = "serde"))] #[derive(Serialize, Deserialize, Debug, PartialEq)] struct Demo { num: u32, name: String, charset: Charset, } #[cfg(test)] mod tests { use super::*; fn utf7_no_err(bytes: &[u8]) -> String { let (cow, had_errors) = UTF_7.decode_without_bom_handling(bytes); assert!(!had_errors); cow.into() } fn utf7_err(bytes: &[u8]) -> String { let (cow, had_errors) = UTF_7.decode_without_bom_handling(bytes); assert!(had_errors); cow.into() } // Any copyright to the test code below this comment is dedicated to the // Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ #[test] fn test_for_label() { assert_eq!(Charset::for_label(b" uTf-7\t "), Some(UTF_7)); assert_eq!( Charset::for_label(b" uTf-8\t "), Some(Charset::for_encoding(encoding_rs::UTF_8)) ); assert_eq!( Charset::for_label(b" iSo-8859-1\t "), Some(Charset::for_encoding(encoding_rs::WINDOWS_1252)) ); assert_eq!( Charset::for_label(b" gb2312\t "), Some(Charset::for_encoding(encoding_rs::GB18030)) ); assert_eq!( Charset::for_label(b" ISO-2022-KR\t "), Some(Charset::for_encoding(encoding_rs::REPLACEMENT)) ); assert_eq!(Charset::for_label(b"u"), None); assert_eq!(Charset::for_label(b"ut"), None); assert_eq!(Charset::for_label(b"utf"), None); assert_eq!(Charset::for_label(b"utf-"), None); } #[test] fn test_for_label_no_replacement() { assert_eq!( Charset::for_label_no_replacement(b" uTf-7\t "), Some(UTF_7) ); assert_eq!( Charset::for_label_no_replacement(b" uTf-8\t "), Some(Charset::for_encoding(encoding_rs::UTF_8)) ); assert_eq!( Charset::for_label_no_replacement(b" iSo-8859-1\t "), Some(Charset::for_encoding(encoding_rs::WINDOWS_1252)) ); assert_eq!( Charset::for_label_no_replacement(b" Gb2312\t "), Some(Charset::for_encoding(encoding_rs::GB18030)) ); assert_eq!(Charset::for_label_no_replacement(b" ISO-2022-KR\t "), None); assert_eq!(Charset::for_label_no_replacement(b"u"), None); assert_eq!(Charset::for_label_no_replacement(b"ut"), None); assert_eq!(Charset::for_label_no_replacement(b"utf"), None); assert_eq!(Charset::for_label_no_replacement(b"utf-"), None); } #[test] fn test_for_label_and_name() { assert_eq!(Charset::for_label(b" uTf-7\t ").unwrap().name(), "UTF-7"); assert_eq!(Charset::for_label(b" uTf-8\t ").unwrap().name(), "UTF-8"); assert_eq!( Charset::for_label(b" Gb2312\t ").unwrap().name(), "gb18030" ); } #[test] fn test_utf7_decode() { assert_eq!(utf7_no_err(b""), ""); assert_eq!(utf7_no_err(b"ab"), "ab"); assert_eq!(utf7_no_err(b"+-"), "+"); assert_eq!(utf7_no_err(b"a+-b"), "a+b"); assert_eq!(utf7_no_err(b"+ACs-"), "+"); assert_eq!(utf7_no_err(b"+AGEAKwBi-"), "a+b"); assert_eq!(utf7_no_err(b"+JgM-"), "\u{2603}"); assert_eq!(utf7_no_err(b"+JgM."), "\u{2603}."); assert_eq!(utf7_no_err(b"+JgM "), "\u{2603} "); assert_eq!(utf7_no_err(b"+JgM--"), "\u{2603}-"); assert_eq!(utf7_no_err(b"+JgM"), "\u{2603}"); assert_eq!(utf7_no_err(b"+JgMmAw-"), "\u{2603}\u{2603}"); assert_eq!(utf7_no_err(b"+JgMmAw."), "\u{2603}\u{2603}."); assert_eq!(utf7_no_err(b"+JgMmAw "), "\u{2603}\u{2603} "); assert_eq!(utf7_no_err(b"+JgMmAw--"), "\u{2603}\u{2603}-"); assert_eq!(utf7_no_err(b"+JgMmAw"), "\u{2603}\u{2603}"); assert_eq!(utf7_no_err(b"+2D3cqQ-"), "\u{1F4A9}"); assert_eq!(utf7_no_err(b"+2D3cqQ."), "\u{1F4A9}."); assert_eq!(utf7_no_err(b"+2D3cqQ "), "\u{1F4A9} "); assert_eq!(utf7_no_err(b"+2D3cqQ--"), "\u{1F4A9}-"); assert_eq!(utf7_no_err(b"+2D3cqQ"), "\u{1F4A9}"); assert_eq!(utf7_no_err(b"+JgPYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp2D3cqdg93KnYPdyp"), "\u{2603}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}\u{1F4A9}"); assert_eq!(utf7_err(b"+"), "\u{FFFD}"); assert_eq!(utf7_err(b"+J-"), "\u{FFFD}"); assert_eq!(utf7_err(b"+Jg-"), "\u{FFFD}"); assert_eq!(utf7_err(b"+J"), "\u{FFFD}"); assert_eq!(utf7_err(b"+Jg"), "\u{FFFD}"); assert_eq!(utf7_err(b"+."), "\u{FFFD}."); assert_eq!(utf7_err(b"+J."), "\u{FFFD}."); assert_eq!(utf7_err(b"+Jg."), "\u{FFFD}."); assert_eq!(utf7_err(b"+ "), "\u{FFFD} "); assert_eq!(utf7_err(b"+J "), "\u{FFFD} "); assert_eq!(utf7_err(b"+Jg "), "\u{FFFD} "); assert_eq!(utf7_err(b"+JgMmA-"), "\u{2603}\u{FFFD}\u{FFFD}"); assert_eq!(utf7_err(b"+JgMmA"), "\u{2603}\u{FFFD}\u{FFFD}"); assert_eq!(utf7_err(b"+JgMmA."), "\u{2603}\u{FFFD}\u{FFFD}."); assert_eq!(utf7_err(b"+JgMmA "), "\u{2603}\u{FFFD}\u{FFFD} "); assert_eq!(utf7_err(b"+JgMm-"), "\u{2603}\u{FFFD}"); assert_eq!(utf7_err(b"+JgMm"), "\u{2603}\u{FFFD}"); assert_eq!(utf7_err(b"+JgMm."), "\u{2603}\u{FFFD}."); assert_eq!(utf7_err(b"+JgMm "), "\u{2603}\u{FFFD} "); assert_eq!(utf7_err(b"+2D3cq-"), "\u{FFFD}\u{FFFD}"); assert_eq!(utf7_err(b"+2D3cq"), "\u{FFFD}\u{FFFD}"); assert_eq!(utf7_err(b"+2D3cq."), "\u{FFFD}\u{FFFD}."); assert_eq!(utf7_err(b"+2D3cq "), "\u{FFFD}\u{FFFD} "); assert_eq!(utf7_err(b"+2D3c-"), "\u{FFFD}"); assert_eq!(utf7_err(b"+2D3c"), "\u{FFFD}"); assert_eq!(utf7_err(b"+2D3c."), "\u{FFFD}."); assert_eq!(utf7_err(b"+2D3c "), "\u{FFFD} "); assert_eq!(utf7_err(b"+2D3-"), "\u{FFFD}"); assert_eq!(utf7_err(b"+2D3"), "\u{FFFD}"); assert_eq!(utf7_err(b"+2D3."), "\u{FFFD}."); assert_eq!(utf7_err(b"+2D3 "), "\u{FFFD} "); assert_eq!(utf7_err(b"+2D-"), "\u{FFFD}"); assert_eq!(utf7_err(b"+2D"), "\u{FFFD}"); assert_eq!(utf7_err(b"+2D."), "\u{FFFD}."); assert_eq!(utf7_err(b"+2D "), "\u{FFFD} "); assert_eq!(utf7_err(b"+2-"), "\u{FFFD}"); assert_eq!(utf7_err(b"+2"), "\u{FFFD}"); assert_eq!(utf7_err(b"+2."), "\u{FFFD}."); assert_eq!(utf7_err(b"+2 "), "\u{FFFD} "); // Lone high surrogate assert_eq!(utf7_err(b"+2D0-"), "\u{FFFD}"); assert_eq!(utf7_err(b"+2D0"), "\u{FFFD}"); assert_eq!(utf7_err(b"+2D0."), "\u{FFFD}."); assert_eq!(utf7_err(b"+2D0 "), "\u{FFFD} "); assert_eq!(utf7_err(b"+2D0AYQ-"), "\u{FFFD}a"); assert_eq!(utf7_err(b"+2D0AYQ"), "\u{FFFD}a"); assert_eq!(utf7_err(b"+2D0AYQ."), "\u{FFFD}a."); assert_eq!(utf7_err(b"+2D0AYQ "), "\u{FFFD}a "); assert_eq!(utf7_err(b"+2D3/QQ-"), "\u{FFFD}\u{FF41}"); assert_eq!(utf7_err(b"+2D3/QQ"), "\u{FFFD}\u{FF41}"); assert_eq!(utf7_err(b"+2D3/QQ."), "\u{FFFD}\u{FF41}."); assert_eq!(utf7_err(b"+2D3/QQ "), "\u{FFFD}\u{FF41} "); // Lone low surrogate assert_eq!(utf7_err(b"+AGHcqQ-"), "a\u{FFFD}"); assert_eq!(utf7_err(b"+AGHcqQ"), "a\u{FFFD}"); assert_eq!(utf7_err(b"+AGHcqQ."), "a\u{FFFD}."); assert_eq!(utf7_err(b"+AGHcqQ "), "a\u{FFFD} "); } #[test] fn test_decode_ascii() { assert_eq!(decode_ascii(b"aa\x80bb\xFFcc"), "aa\u{FFFD}bb\u{FFFD}cc"); } #[test] fn test_from() { let _: Charset = encoding_rs::UTF_8.into(); } #[cfg(feature = "serde")] #[test] fn test_serde_utf7() { let demo = Demo { num: 42, name: "foo".into(), charset: UTF_7, }; let serialized = serde_json::to_string(&demo).unwrap(); let deserialized: Demo = serde_json::from_str(&serialized).unwrap(); assert_eq!(deserialized, demo); let bincoded = bincode::serialize(&demo, bincode::Infinite).unwrap(); let debincoded: Demo = bincode::deserialize(&bincoded[..]).unwrap(); assert_eq!(debincoded, demo); } #[cfg(feature = "serde")] #[test] fn test_serde_utf8() { let demo = Demo { num: 42, name: "foo".into(), charset: encoding_rs::UTF_8.into(), }; let serialized = serde_json::to_string(&demo).unwrap(); let deserialized: Demo = serde_json::from_str(&serialized).unwrap(); assert_eq!(deserialized, demo); let bincoded = bincode::serialize(&demo, bincode::Infinite).unwrap(); let debincoded: Demo = bincode::deserialize(&bincoded[..]).unwrap(); assert_eq!(debincoded, demo); } }