├── .github └── dependabot.yml ├── .gitignore ├── .gitmodules ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── librsync-sys ├── Cargo.toml ├── README.md ├── build.rs └── lib.rs └── src ├── job.rs ├── lib.rs ├── logfwd.rs ├── macros.rs └── whole.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | open-pull-requests-limit: 10 8 | - package-ecosystem: cargo 9 | directory: "/librsync-sys" 10 | schedule: 11 | interval: daily 12 | open-pull-requests-limit: 10 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled files 2 | *.o 3 | *.so 4 | *.rlib 5 | *.dll 6 | 7 | # Executables 8 | *.exe 9 | 10 | # Generated by Cargo 11 | target/ 12 | Cargo.lock 13 | 14 | # Vim 15 | *.swp 16 | *.rs.racertmp 17 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "librsync-sys/librsync"] 2 | path = librsync-sys/librsync 3 | url = https://github.com/mbrt/librsync.git 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | 4 | rust: 5 | - stable 6 | - beta 7 | - nightly 8 | 9 | os: 10 | - linux 11 | - osx 12 | 13 | env: 14 | - CARGO_FEATURES='--features default' 15 | - CARGO_FEATURES='--no-default-features' 16 | 17 | # necessary for `travis-cargo coveralls --no-sudo` 18 | addons: 19 | apt: 20 | packages: 21 | - libcurl4-openssl-dev 22 | - libelf-dev 23 | - libdw-dev 24 | 25 | cache: 26 | directories: 27 | - $HOME/.cargo 28 | 29 | matrix: 30 | allow_failures: 31 | - rust: nightly 32 | exclude: 33 | - os: osx 34 | env: CARGO_FEATURES='--no-default-features' 35 | 36 | before_script: 37 | - pip install 'travis-cargo<0.2' --user && export PATH=`python -m site --user-base`/bin:$PATH 38 | 39 | script: 40 | - travis-cargo build -- $CARGO_FEATURES 41 | - travis-cargo test -- $CARGO_FEATURES 42 | - rustdoc --test README.md -L target/debug -L target/debug/deps 43 | - cargo doc --no-deps 44 | 45 | after_success: 46 | - if [ "$TRAVIS_OS_NAME" == 'linux' ]; then 47 | travis-cargo coveralls --no-sudo; 48 | fi 49 | 50 | notifications: 51 | email: 52 | on_success: never 53 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "librsync" 3 | version = "0.2.3" 4 | authors = ["Michele Bertasi <@brt_device>"] 5 | edition = "2018" 6 | license = "MIT/Apache-2.0" 7 | readme = "README.md" 8 | keywords = ["librsync", "rsync", "backup"] 9 | repository = "https://github.com/mbrt/librsync-rs" 10 | homepage = "https://github.com/mbrt/librsync-rs" 11 | documentation = "https://docs.rs/librsync" 12 | description = """ 13 | Bindings to librsync for calculating and applying network 14 | deltas exposed as Reader/Writer streams. 15 | """ 16 | 17 | [features] 18 | default = ["log"] # forward logs to log crate, or disable them 19 | lints = ["clippy", "nightly"] 20 | nightly = [] # for building with nightly and unstable features 21 | unstable = ["lints", "nightly"] # for building with travis-cargo 22 | 23 | [dependencies] 24 | libc = "0.2" 25 | librsync-sys = { version = "0.1", path = "librsync-sys" } 26 | clippy = { version = "< 1", optional = true } 27 | log = { version = "0.4", optional = true } 28 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Michele Bertasi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # librsync-rs 2 | [![Build Status](https://travis-ci.org/mbrt/librsync-rs.svg?branch=master)](https://travis-ci.org/mbrt/librsync-rs) 3 | [![Coverage Status](https://coveralls.io/repos/github/mbrt/librsync-rs/badge.svg?branch=master)](https://coveralls.io/github/mbrt/librsync-rs?branch=master) 4 | [![](http://meritbadge.herokuapp.com/librsync)](https://crates.io/crates/librsync) 5 | 6 | Rust bindings to [librsync](https://github.com/librsync/librsync). 7 | 8 | [API Documentation](https://docs.rs/librsync) 9 | 10 | 11 | ## Introduction 12 | 13 | This library contains bindings to librsync [1], to support computation and application of 14 | network deltas, used in rsync and duplicity backup applications. This library encapsulates the 15 | algorithms of the rsync protocol, which computes differences between files efficiently. 16 | 17 | The rsync protocol, when computes differences, does not require the presence of both files. 18 | It needs instead the new file and a set of checksums of the first file (namely the signature). 19 | Computed differences can be stored in a delta file. The rsync protocol is then able to 20 | reproduce the new file, by having the old one and the delta. 21 | 22 | [1]: http://librsync.sourcefrog.net/ 23 | 24 | 25 | ## Installation 26 | 27 | Simply add a corresponding entry to your `Cargo.toml` dependency list: 28 | 29 | ```toml 30 | [dependencies] 31 | librsync = "0.2" 32 | ``` 33 | 34 | And add this to your crate root: 35 | 36 | ```rust 37 | extern crate librsync; 38 | ``` 39 | 40 | 41 | ## Overview of types and modules 42 | 43 | This crate provides the streaming operations to produce signatures, delta and patches in the 44 | top-level module, with `Signature`, `Delta` and `Patch` structs. Those structs take some input 45 | stream (`Read` or `Read + Seek` traits) and implement another stream (`Read` trait) from which 46 | the output can be read. 47 | 48 | Higher level operations are provided within the `whole` submodule. If the application does not 49 | need fine-grained control over IO operations, `sig`, `delta` and `patch` submodules can be 50 | used. Those functions apply the algorithms to an output stream (implementing the `Write` trait) 51 | in a single call. 52 | 53 | 54 | ## Example: streams 55 | 56 | This example shows how to go through the streaming APIs, starting from an input string and a 57 | modified string which act as old and new files. The example simulates a real world scenario, in 58 | which the signature of a base file is computed, used as input to compute differences between 59 | the base file and the new one, and finally the new file is reconstructed, by using the patch 60 | and the base file. 61 | 62 | ```rust 63 | extern crate librsync; 64 | 65 | use std::io::prelude::*; 66 | use std::io::Cursor; 67 | use librsync::{Delta, Patch, Signature}; 68 | 69 | fn main() { 70 | let base = "base file".as_bytes(); 71 | let new = "modified base file".as_bytes(); 72 | 73 | // create signature starting from base file 74 | let mut sig = Signature::new(base).unwrap(); 75 | // create delta from new file and the base signature 76 | let delta = Delta::new(new, &mut sig).unwrap(); 77 | // create and store the new file from the base one and the delta 78 | let mut patch = Patch::new(Cursor::new(base), delta).unwrap(); 79 | let mut computed_new = Vec::new(); 80 | patch.read_to_end(&mut computed_new).unwrap(); 81 | 82 | // test whether the computed file is exactly the new file, as expected 83 | assert_eq!(computed_new, new); 84 | } 85 | ``` 86 | 87 | Note that intermediate results are not stored in temporary containers. This is possible because 88 | the operations implement the `Read` trait. In this way the results does not need to be fully in 89 | memory, during computation. 90 | 91 | 92 | ## Example: whole file API 93 | 94 | This example shows how to go trough the whole file APIs, starting from an input string and a 95 | modified string which act as old and new files. Unlike the streaming example, here we call a 96 | single function, to get the computation result of signature, delta and patch operations. This 97 | is convenient when an output stream (like a network socket or a file) is used as output for an 98 | operation. 99 | 100 | ```rust 101 | extern crate librsync; 102 | 103 | use std::io::Cursor; 104 | use librsync::whole::*; 105 | 106 | fn main() { 107 | let base = "base file".as_bytes(); 108 | let new = "modified base file".as_bytes(); 109 | 110 | // signature 111 | let mut sig = Vec::new(); 112 | signature(&mut Cursor::new(base), &mut sig).unwrap(); 113 | 114 | // delta 115 | let mut dlt = Vec::new(); 116 | delta(&mut Cursor::new(new), &mut Cursor::new(sig), &mut dlt).unwrap(); 117 | 118 | // patch 119 | let mut out = Vec::new(); 120 | patch(&mut Cursor::new(base), &mut Cursor::new(dlt), &mut out).unwrap(); 121 | 122 | assert_eq!(out, new); 123 | } 124 | ``` 125 | 126 | ## License 127 | 128 | Licensed under either of 129 | 130 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 131 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 132 | 133 | at your option. 134 | 135 | This library uses [librsync](https://github.com/librsync/librsync), which comes with an 136 | [LGPL-2.0](https://github.com/librsync/librsync/blob/master/COPYING) license. Please, be sure to fulfill librsync 137 | licensing requirements before to use this library. 138 | 139 | ### Contribution 140 | 141 | Unless you explicitly state otherwise, any contribution intentionally 142 | submitted for inclusion in the work by you, as defined in the Apache-2.0 143 | license, shall be dual licensed as above, without any additional terms or 144 | conditions. 145 | -------------------------------------------------------------------------------- /librsync-sys/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "librsync-sys" 3 | version = "0.1.2" 4 | authors = ["Michele Bertasi <@brt_device>"] 5 | build = "build.rs" 6 | license = "MIT/Apache-2.0" 7 | repository = "https://github.com/mbrt/librsync-rs" 8 | homepage = "https://github.com/mbrt/librsync-rs" 9 | description = """ 10 | Bindings to librsync for calculating and applying network 11 | deltas exposed as Reader/Writer streams. 12 | """ 13 | 14 | [lib] 15 | name = "librsync_sys" 16 | path = "lib.rs" 17 | 18 | [dependencies] 19 | libc = "0.2" 20 | 21 | [build-dependencies] 22 | cc = "1.0" 23 | -------------------------------------------------------------------------------- /librsync-sys/README.md: -------------------------------------------------------------------------------- 1 | # librsync-sys 2 | Building and wrapping librsync native library. 3 | 4 | This library gets rid of librsync build system and provides static configurations for the most used platforms. In this way we can avoid CMake and Perl dependencies for the library users. 5 | 6 | ## Porting 7 | 8 | This library currently supports the following targets: 9 | 10 | * `i686-pc-windows-gnu`; 11 | * `i686-pc-windows-msvc`: 12 | * `i686-unknown-linux-gnu`; 13 | * `x86_64-apple-darwin`; 14 | * `x86_64-pc-windows-gnu`; 15 | * `x86_64-pc-windows-msvc`; 16 | * `x86_64-unknown-linux-gnu`. 17 | 18 | To port the library to another target, use the utility in [mbrt/librsync](https://github.com/mbrt/librsync/tree/static_config/gen). Run that utility with the Rust toolchain you want to use: 19 | 20 | ``` 21 | cd librsync/gen 22 | cargo run --target 23 | ``` 24 | 25 | To do so, you need to have CMake and Perl installed and available in your PATH. If all goes well you will find the specific configuration for your platform, under `static` folder in that repo. Please submit a PR against the `static_config` branch in [mbrt/librsync](https://github.com/mbrt/librsync) by committing only that folder. 26 | 27 | After that, `librsync-rs` will have the corresponding configuration available. 28 | -------------------------------------------------------------------------------- /librsync-sys/build.rs: -------------------------------------------------------------------------------- 1 | extern crate cc; 2 | 3 | use std::env; 4 | use std::path::Path; 5 | 6 | fn main() { 7 | let target = env::var("TARGET").unwrap(); 8 | let windows = target.contains("windows"); 9 | 10 | let mut cfg = cc::Build::new(); 11 | 12 | if windows { 13 | cfg.define("_WIN32", None); 14 | } 15 | 16 | let cfg_dir = { 17 | let mut p = Path::new("librsync/static").to_path_buf(); 18 | p.push(target); 19 | p 20 | }; 21 | 22 | cfg.include(cfg_dir) 23 | .include("librsync/static") 24 | .include("librsync/src") 25 | .include("librsync/src/blake2") 26 | .define("STDC_HEADERS", Some("1")) 27 | .define("LIBRSYNC_STATIC_DEFINE", Some("1")) 28 | .file("librsync/src/base64.c") 29 | .file("librsync/src/buf.c") 30 | .file("librsync/src/checksum.c") 31 | .file("librsync/src/command.c") 32 | .file("librsync/src/delta.c") 33 | .file("librsync/src/emit.c") 34 | .file("librsync/src/fileutil.c") 35 | .file("librsync/src/hashtable.c") 36 | .file("librsync/src/hex.c") 37 | .file("librsync/src/isprefix.c") 38 | .file("librsync/src/job.c") 39 | .file("librsync/src/mdfour.c") 40 | .file("librsync/src/mksum.c") 41 | .file("librsync/src/msg.c") 42 | .file("librsync/src/netint.c") 43 | .file("librsync/src/patch.c") 44 | .file("librsync/src/prototab.c") 45 | .file("librsync/src/readsums.c") 46 | .file("librsync/src/rollsum.c") 47 | .file("librsync/src/scoop.c") 48 | .file("librsync/src/stats.c") 49 | .file("librsync/src/stream.c") 50 | .file("librsync/src/sumset.c") 51 | .file("librsync/src/trace.c") 52 | .file("librsync/src/tube.c") 53 | .file("librsync/src/util.c") 54 | .file("librsync/src/version.c") 55 | .file("librsync/src/whole.c") 56 | .file("librsync/src/blake2/blake2b-ref.c") 57 | .compile("librsync.a"); 58 | } 59 | -------------------------------------------------------------------------------- /librsync-sys/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(bad_style)] 2 | 3 | extern crate libc; 4 | use libc::*; 5 | 6 | pub type rs_magic_number = c_int; 7 | pub const RS_DELTA_MAGIC: c_int = 0x7273_0236; 8 | pub const RS_MD4_SIG_MAGIC: c_int = 0x7273_0136; 9 | pub const RS_BLAKE2_SIG_MAGIC: c_int = 0x7273_0137; 10 | 11 | pub type rs_result = c_int; 12 | pub const RS_DONE: c_int = 0; 13 | pub const RS_BLOCKED: c_int = 1; 14 | pub const RS_RUNNING: c_int = 2; 15 | pub const RS_TEST_SKIPPED: c_int = 77; 16 | pub const RS_IO_ERROR: c_int = 100; 17 | pub const RS_SYNTAX_ERROR: c_int = 101; 18 | pub const RS_MEM_ERROR: c_int = 102; 19 | pub const RS_INPUT_ENDED: c_int = 103; 20 | pub const RS_BAD_MAGIC: c_int = 104; 21 | pub const RS_UNIMPLEMENTED: c_int = 105; 22 | pub const RS_CORRUPT: c_int = 106; 23 | pub const RS_INTERNAL_ERROR: c_int = 107; 24 | pub const RS_PARAM_ERROR: c_int = 108; 25 | 26 | pub type rs_loglevel = c_int; 27 | pub const RS_LOG_EMERG: c_int = 0; 28 | pub const RS_LOG_ALERT: c_int = 1; 29 | pub const RS_LOG_CRIT: c_int = 2; 30 | pub const RS_LOG_ERR: c_int = 3; 31 | pub const RS_LOG_WARNING: c_int = 4; 32 | pub const RS_LOG_NOTICE: c_int = 5; 33 | pub const RS_LOG_INFO: c_int = 6; 34 | pub const RS_LOG_DEBUG: c_int = 7; 35 | 36 | pub const RS_DEFAULT_BLOCK_LEN: size_t = 2048; 37 | 38 | pub type rs_long_t = c_longlong; 39 | 40 | pub enum rs_job_t {} 41 | pub enum rs_signature_t {} 42 | 43 | #[repr(C)] 44 | pub struct rs_buffers_t { 45 | pub next_in: *const c_char, 46 | pub avail_in: size_t, 47 | pub eof_in: c_int, 48 | pub next_out: *mut c_char, 49 | pub avail_out: size_t, 50 | } 51 | 52 | pub type rs_copy_cb = extern "C" fn( 53 | opaque: *mut c_void, 54 | pos: rs_long_t, 55 | len: *mut size_t, 56 | buf: *mut *mut c_void, 57 | ) -> rs_result; 58 | pub type rs_trace_fn_t = extern "C" fn(level: rs_loglevel, msg: *const c_char); 59 | 60 | extern "C" { 61 | pub fn rs_job_iter(job: *mut rs_job_t, buffers: *mut rs_buffers_t) -> rs_result; 62 | pub fn rs_job_free(job: *mut rs_job_t) -> rs_result; 63 | 64 | pub fn rs_sig_begin( 65 | new_block_len: size_t, 66 | strong_sum_len: size_t, 67 | sig_magic: rs_magic_number, 68 | ) -> *mut rs_job_t; 69 | pub fn rs_delta_begin(sig: *mut rs_signature_t) -> *mut rs_job_t; 70 | pub fn rs_loadsig_begin(sig: *mut *mut rs_signature_t) -> *mut rs_job_t; 71 | pub fn rs_build_hash_table(sums: *mut rs_signature_t) -> rs_result; 72 | pub fn rs_free_sumset(sums: *mut rs_signature_t); 73 | pub fn rs_patch_begin(copy_cb: rs_copy_cb, copy_arg: *mut c_void) -> *mut rs_job_t; 74 | 75 | pub fn rs_trace_set_level(level: rs_loglevel); 76 | pub fn rs_trace_to(f: rs_trace_fn_t); 77 | } 78 | -------------------------------------------------------------------------------- /src/job.rs: -------------------------------------------------------------------------------- 1 | use std::io::{self, BufRead, Read}; 2 | use std::marker::PhantomData; 3 | use std::ops::Deref; 4 | use std::ptr; 5 | 6 | use crate::{raw, Error}; 7 | 8 | pub struct JobDriver { 9 | input: R, 10 | job: Job, 11 | input_ended: bool, 12 | } 13 | 14 | pub struct Job(pub *mut raw::rs_job_t); 15 | 16 | // Wrapper around rs_buffers_t. 17 | struct Buffers<'a> { 18 | inner: raw::rs_buffers_t, 19 | _phantom: PhantomData<&'a u8>, 20 | } 21 | 22 | impl JobDriver { 23 | pub fn new(input: R, job: Job) -> Self { 24 | JobDriver { 25 | input, 26 | job, 27 | input_ended: false, 28 | } 29 | } 30 | 31 | pub fn into_inner(self) -> R { 32 | self.input 33 | } 34 | 35 | /// Complete the job by working without an output buffer. 36 | /// 37 | /// If the job needs to write some data, an `ErrorKind::WouldBlock` error is returned. 38 | pub fn consume_input(&mut self) -> io::Result<()> { 39 | loop { 40 | let (res, read, cap) = { 41 | let readbuf = self.input.fill_buf()?; 42 | let cap = readbuf.len(); 43 | if cap == 0 { 44 | self.input_ended = true; 45 | } 46 | 47 | // work 48 | let mut buffers = Buffers::with_no_out(readbuf, self.input_ended); 49 | let res = unsafe { raw::rs_job_iter(*self.job, buffers.as_raw()) }; 50 | let read = cap - buffers.available_input(); 51 | (res, read, cap - read) 52 | }; 53 | // update read size 54 | self.input.consume(read); 55 | 56 | // determine result 57 | // NOTE: this should be done here, after the input buffer update, because we need to 58 | // know if the possible RS_BLOCKED result is due to a full input, or to an empty output 59 | // buffer 60 | match res { 61 | raw::RS_DONE => (), 62 | raw::RS_BLOCKED => { 63 | if cap > 0 { 64 | // the block is due to a missing output buffer 65 | return Err(io::Error::new( 66 | io::ErrorKind::WouldBlock, 67 | "cannot consume input without an output buffer", 68 | )); 69 | } 70 | } 71 | _ => { 72 | let err = Error::from(res); 73 | return Err(io::Error::new(io::ErrorKind::Other, err)); 74 | } 75 | }; 76 | 77 | if self.input_ended { 78 | return Ok(()); 79 | } 80 | } 81 | } 82 | } 83 | 84 | impl Read for JobDriver { 85 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 86 | let mut out_pos = 0; 87 | let mut out_cap = buf.len(); 88 | 89 | loop { 90 | let (res, read, written) = { 91 | let readbuf = self.input.fill_buf()?; 92 | let cap = readbuf.len(); 93 | if cap == 0 { 94 | self.input_ended = true; 95 | } 96 | 97 | // work 98 | let mut buffers = Buffers::new(readbuf, &mut buf[out_pos..], self.input_ended); 99 | let res = unsafe { raw::rs_job_iter(*self.job, buffers.as_raw()) }; 100 | if res != raw::RS_DONE && res != raw::RS_BLOCKED { 101 | let err = Error::from(res); 102 | return Err(io::Error::new(io::ErrorKind::Other, err)); 103 | } 104 | let read = cap - buffers.available_input(); 105 | let written = out_cap - buffers.available_output(); 106 | (res, read, written) 107 | }; 108 | 109 | // update read size 110 | self.input.consume(read); 111 | // update write size 112 | out_pos += written; 113 | out_cap -= written; 114 | if out_cap == 0 || res == raw::RS_DONE { 115 | return Ok(out_pos); 116 | } 117 | } 118 | } 119 | } 120 | 121 | unsafe impl Send for Job {} 122 | 123 | impl Deref for Job { 124 | type Target = *mut raw::rs_job_t; 125 | fn deref(&self) -> &Self::Target { 126 | &self.0 127 | } 128 | } 129 | 130 | impl Drop for Job { 131 | fn drop(&mut self) { 132 | unsafe { 133 | if !self.0.is_null() { 134 | raw::rs_job_free(self.0); 135 | } 136 | } 137 | } 138 | } 139 | 140 | impl<'a> Buffers<'a> { 141 | pub fn new(in_buf: &'a [u8], out_buf: &'a mut [u8], eof_in: bool) -> Self { 142 | Buffers { 143 | inner: raw::rs_buffers_t { 144 | next_in: in_buf.as_ptr() as _, 145 | avail_in: in_buf.len(), 146 | eof_in: if eof_in { 1 } else { 0 }, 147 | next_out: out_buf.as_mut_ptr() as _, 148 | avail_out: out_buf.len(), 149 | }, 150 | _phantom: PhantomData, 151 | } 152 | } 153 | 154 | pub fn with_no_out(in_buf: &'a [u8], eof_in: bool) -> Self { 155 | Buffers { 156 | inner: raw::rs_buffers_t { 157 | next_in: in_buf.as_ptr() as _, 158 | avail_in: in_buf.len(), 159 | eof_in: if eof_in { 1 } else { 0 }, 160 | next_out: ptr::null_mut(), 161 | avail_out: 0, 162 | }, 163 | _phantom: PhantomData, 164 | } 165 | } 166 | 167 | pub fn as_raw(&mut self) -> *mut raw::rs_buffers_t { 168 | &mut self.inner 169 | } 170 | 171 | pub fn available_input(&self) -> usize { 172 | self.inner.avail_in 173 | } 174 | 175 | pub fn available_output(&self) -> usize { 176 | self.inner.avail_out 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! librsync bindings for Rust. 2 | //! 3 | //! This library contains bindings to librsync [1], encapsulating the algorithms of the rsync 4 | //! protocol, which computes differences between files efficiently. 5 | //! 6 | //! The rsync protocol, when computes differences, does not require the presence of both files. 7 | //! It needs instead the new file and a set of checksums of the first file (the signature). 8 | //! Computed differences can be stored in a delta file. The rsync protocol is then able to 9 | //! reproduce the new file, by having the old one and the delta. 10 | //! 11 | //! [1]: http://librsync.sourcefrog.net/ 12 | //! 13 | //! 14 | //! # Overview of types and modules 15 | //! 16 | //! This crate provides the streaming operations to produce signatures, delta and patches in the 17 | //! top-level module with `Signature`, `Delta` and `Patch` structs. Those structs take some input 18 | //! stream (`Read` or `Read + Seek` traits) and implement another stream (`Read` trait) from which 19 | //! the output can be read. 20 | //! 21 | //! Higher level operations are provided within the `whole` submodule. If the application does not 22 | //! need fine-grained control over IO operations, `signature`, `delta` and `patch` functions can be 23 | //! used. Those functions apply the results to an output stream (implementing the `Write` trait) 24 | //! in a single call. 25 | //! 26 | //! 27 | //! # Example: streams 28 | //! 29 | //! This example shows how to go trough the streaming APIs, starting from an input string and a 30 | //! modified string which act as old and new files. The example simulates a real world scenario, in 31 | //! which the signature of a base file is computed, used as input to compute differencies between 32 | //! the base file and the new one, and finally the new file is reconstructed, by using the base 33 | //! file and the delta. 34 | //! 35 | //! ```rust 36 | //! use std::io::prelude::*; 37 | //! use std::io::Cursor; 38 | //! use librsync::{Delta, Patch, Signature}; 39 | //! 40 | //! let base = "base file".as_bytes(); 41 | //! let new = "modified base file".as_bytes(); 42 | //! 43 | //! // create signature starting from base file 44 | //! let mut sig = Signature::new(base).unwrap(); 45 | //! // create delta from new file and the base signature 46 | //! let delta = Delta::new(new, &mut sig).unwrap(); 47 | //! // create and store the new file from the base one and the delta 48 | //! let mut patch = Patch::new(Cursor::new(base), delta).unwrap(); 49 | //! let mut computed_new = Vec::new(); 50 | //! patch.read_to_end(&mut computed_new).unwrap(); 51 | //! 52 | //! // test whether the computed file is exactly the new file, as expected 53 | //! assert_eq!(computed_new, new); 54 | //! ``` 55 | //! 56 | //! Note that intermediate results are not stored in temporary containers. This is possible because 57 | //! the operations implement the `Read` trait. In this way the results does not need to be fully in 58 | //! memory, during computation. 59 | //! 60 | //! 61 | //! # Example: whole file API 62 | //! 63 | //! This example shows how to go trough the whole file APIs, starting from an input string and a 64 | //! modified string which act as old and new files. Unlike the streaming example, here we call a 65 | //! single function, to get the computation result of signature, delta and patch operations. This 66 | //! is convenient when an output stream (like a network socket or a file) is used as output for an 67 | //! operation. 68 | //! 69 | //! ```rust 70 | //! use std::io::Cursor; 71 | //! use librsync::whole::*; 72 | //! 73 | //! let base = "base file".as_bytes(); 74 | //! let new = "modified base file".as_bytes(); 75 | //! 76 | //! // signature 77 | //! let mut sig = Vec::new(); 78 | //! signature(&mut Cursor::new(base), &mut sig).unwrap(); 79 | //! 80 | //! // delta 81 | //! let mut dlt = Vec::new(); 82 | //! delta(&mut Cursor::new(new), &mut Cursor::new(sig), &mut dlt).unwrap(); 83 | //! 84 | //! // patch 85 | //! let mut out = Vec::new(); 86 | //! patch(&mut Cursor::new(base), &mut Cursor::new(dlt), &mut out).unwrap(); 87 | //! 88 | //! assert_eq!(out, new); 89 | //! ``` 90 | 91 | #![deny( 92 | missing_copy_implementations, 93 | missing_docs, 94 | trivial_casts, 95 | trivial_numeric_casts, 96 | unstable_features, 97 | unused_import_braces, 98 | unused_qualifications 99 | )] 100 | #![cfg_attr(feature = "nightly", allow(unstable_features))] 101 | #![cfg_attr(feature = "lints", feature(plugin))] 102 | #![cfg_attr(feature = "lints", plugin(clippy))] 103 | 104 | extern crate libc; 105 | extern crate librsync_sys as raw; 106 | #[cfg(feature = "log")] 107 | #[macro_use] 108 | extern crate log; 109 | 110 | mod job; 111 | mod logfwd; 112 | mod macros; 113 | pub mod whole; 114 | 115 | use crate::job::{Job, JobDriver}; 116 | 117 | use std::cell::{RefCell, RefMut}; 118 | use std::error; 119 | use std::fmt::{self, Display, Formatter}; 120 | use std::io::{self, BufRead, BufReader, Read, Seek}; 121 | use std::mem; 122 | use std::ops::Deref; 123 | use std::ptr; 124 | use std::rc::Rc; 125 | use std::slice; 126 | 127 | /// The signature type. 128 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] 129 | pub enum SignatureType { 130 | /// A signature file with MD4 signatures. 131 | /// 132 | /// Backward compatible with librsync < 1.0, but deprecated because of a security 133 | /// vulnerability. 134 | MD4, 135 | /// A signature file using BLAKE2 hash. 136 | Blake2, 137 | } 138 | 139 | /// Enumeration of all possible errors in this crate. 140 | #[derive(Debug)] 141 | pub enum Error { 142 | /// An IO error. 143 | Io(io::Error), 144 | /// Out of memory. 145 | Mem, 146 | /// Bad magic number at start of stream. 147 | BadMagic, 148 | /// The feature is not available yet. 149 | Unimplemented, 150 | /// Probably a library bug. 151 | Internal, 152 | /// All the other error numbers. 153 | /// 154 | /// This error should never occur, as it is an indication of a bug. 155 | Unknown(i32), 156 | } 157 | 158 | /// A `Result` type alias for this crate's `Error` type. 159 | pub type Result = std::result::Result; 160 | 161 | /// A struct to generate a signature. 162 | /// 163 | /// This type takes a `Read` stream for the input from which compute the signatures, and implements 164 | /// another `Read` stream from which get the result. 165 | pub struct Signature { 166 | driver: JobDriver, 167 | } 168 | 169 | /// A struct to generate a delta between two files. 170 | /// 171 | /// This type takes two `Read` streams, one for the signature of the base file and one for the new 172 | /// file. It then provides another `Read` stream from which get the result. 173 | pub struct Delta { 174 | driver: JobDriver, 175 | _sumset: Sumset, 176 | } 177 | 178 | /// A struct to apply a delta to a basis file, to recreate the new file. 179 | /// 180 | /// This type takes a `Read + Seek` stream for the base file, and a `Read` stream for the delta 181 | /// file. It then provides another `Read` stream from which get the resulting patched file. 182 | pub struct Patch<'a, B: 'a, D> { 183 | driver: JobDriver, 184 | base: Rc>, 185 | raw: Box>>, 186 | } 187 | 188 | struct Sumset(*mut raw::rs_signature_t); 189 | 190 | // workaround for E0225 191 | trait ReadAndSeek: Read + Seek {} 192 | impl ReadAndSeek for T {} 193 | 194 | impl Signature> { 195 | /// Creates a new signature stream with default parameters. 196 | /// 197 | /// This constructor takes an input stream for the file from which compute the signatures. 198 | /// Default options are used for the signature format: BLAKE2 for the hashing, 2048 bytes for 199 | /// the block length and full length for the strong signature size. 200 | pub fn new(input: R) -> Result { 201 | Self::with_options(input, raw::RS_DEFAULT_BLOCK_LEN, 0, SignatureType::Blake2) 202 | } 203 | 204 | /// Creates a new signature stream by specifying custom parameters. 205 | /// 206 | /// This constructor takes the input stream for the file from which compute the signatures, the 207 | /// size of checksum blocks as `block_len` parameter (larger values make the signature shorter 208 | /// and the delta longer), and the size of strong signatures in bytes as `strong_len` 209 | /// parameter. If it is non-zero the signature will be truncated to that amount of bytes. 210 | /// The last parameter specifies which version of the signature format to be used. 211 | pub fn with_options( 212 | input: R, 213 | block_len: usize, 214 | strong_len: usize, 215 | sig_magic: SignatureType, 216 | ) -> Result { 217 | Self::with_buf_read(BufReader::new(input), block_len, strong_len, sig_magic) 218 | } 219 | } 220 | 221 | impl Signature { 222 | /// Creates a new signature stream by using a `BufRead`. 223 | /// 224 | /// This constructor takes an already built `BufRead` instance. Prefer this constructor if 225 | /// you already have a `BufRead` as input stream, since it avoids wrapping the input stream 226 | /// into another `BufRead` instance. See `with_options` constructor for details on the other 227 | /// parameters. 228 | pub fn with_buf_read( 229 | input: R, 230 | block_len: usize, 231 | strong_len: usize, 232 | sig_magic: SignatureType, 233 | ) -> Result { 234 | logfwd::init(); 235 | 236 | let job = unsafe { raw::rs_sig_begin(block_len, strong_len, sig_magic.as_raw()) }; 237 | if job.is_null() { 238 | return Err(Error::BadMagic); 239 | } 240 | Ok(Signature { 241 | driver: JobDriver::new(input, Job(job)), 242 | }) 243 | } 244 | 245 | /// Unwraps this stream, returning the underlying input stream. 246 | pub fn into_inner(self) -> R { 247 | self.driver.into_inner() 248 | } 249 | } 250 | 251 | impl Read for Signature { 252 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 253 | self.driver.read(buf) 254 | } 255 | } 256 | 257 | impl Delta> { 258 | /// Creates a new delta stream. 259 | /// 260 | /// This constructor takes two `Read` streams for the new file (`new` parameter) and for the 261 | /// signatures of the base file (`base_sig` parameter). It produces a delta stream from which 262 | /// read the resulting delta file. 263 | pub fn new(new: R, base_sig: &mut S) -> Result { 264 | Self::with_buf_read(BufReader::new(new), base_sig) 265 | } 266 | } 267 | 268 | impl Delta { 269 | /// Creates a new delta stream by using a `BufRead` as new file. 270 | /// 271 | /// This constructor specializes the `new` constructor by taking a `BufRead` instance as 272 | /// `new` parameter. Prefer this constructor if you already have a `BufRead` as input stream, 273 | /// since it avoids wrapping the input stream into another `BufRead` instance. See `new` 274 | /// constructor for more details on the parameters. 275 | pub fn with_buf_read(new: R, base_sig: &mut S) -> Result { 276 | logfwd::init(); 277 | 278 | // load the signature 279 | let sumset = unsafe { 280 | let mut sumset = ptr::null_mut(); 281 | let job = raw::rs_loadsig_begin(&mut sumset); 282 | assert!(!job.is_null()); 283 | let mut job = JobDriver::new(BufReader::new(base_sig), Job(job)); 284 | job.consume_input()?; 285 | let sumset = Sumset(sumset); 286 | let res = raw::rs_build_hash_table(*sumset); 287 | if res != raw::RS_DONE { 288 | return Err(Error::from(res)); 289 | } 290 | sumset 291 | }; 292 | let job = unsafe { raw::rs_delta_begin(*sumset) }; 293 | if job.is_null() { 294 | return Err(io_err( 295 | io::ErrorKind::InvalidData, 296 | "invalid signature given", 297 | )); 298 | } 299 | Ok(Delta { 300 | driver: JobDriver::new(new, Job(job)), 301 | _sumset: sumset, 302 | }) 303 | } 304 | 305 | /// Unwraps this stream, returning the underlying new file stream. 306 | pub fn into_inner(self) -> R { 307 | self.driver.into_inner() 308 | } 309 | } 310 | 311 | impl Read for Delta { 312 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 313 | self.driver.read(buf) 314 | } 315 | } 316 | 317 | impl<'a, B: Read + Seek + 'a, D: Read> Patch<'a, B, BufReader> { 318 | /// Creates a new patch stream. 319 | /// 320 | /// This constructor takes a `Read + Seek` stream for the basis file (`base` parameter), and a 321 | /// `Read` stream for the delta file (`delta` parameter). It produces a stream from which read 322 | /// the resulting patched file. 323 | pub fn new(base: B, delta: D) -> Result { 324 | Self::with_buf_read(base, BufReader::new(delta)) 325 | } 326 | } 327 | 328 | impl<'a, B: Read + Seek + 'a, D: BufRead> Patch<'a, B, D> { 329 | /// Creates a new patch stream by using a `BufRead` as delta stream. 330 | /// 331 | /// This constructor specializes the `new` constructor by taking a `BufRead` instance as 332 | /// `delta` parameter. Prefer this constructor if you already have a `BufRead` as input 333 | /// stream, since it avoids wrapping the input stream into another `BufRead` instance. See 334 | /// `new` constructor for more details on the parameters. 335 | pub fn with_buf_read(base: B, delta: D) -> Result { 336 | logfwd::init(); 337 | 338 | let base = Rc::new(RefCell::new(base)); 339 | let cb_data: Box>> = Box::new(base.clone()); 340 | let job = unsafe { raw::rs_patch_begin(patch_copy_cb, mem::transmute(&*cb_data)) }; 341 | assert!(!job.is_null()); 342 | Ok(Patch { 343 | driver: JobDriver::new(delta, Job(job)), 344 | base, 345 | raw: cb_data, 346 | }) 347 | } 348 | 349 | /// Unwraps this stream and returns the underlying streams. 350 | pub fn into_inner(self) -> (B, D) { 351 | // drop the secondary Rc before unwrapping the other 352 | { 353 | let _drop = self.raw; 354 | } 355 | let base = match Rc::try_unwrap(self.base) { 356 | Ok(base) => base, 357 | _ => unreachable!(), 358 | }; 359 | (base.into_inner(), self.driver.into_inner()) 360 | } 361 | } 362 | 363 | impl<'a, B, D: BufRead> Read for Patch<'a, B, D> { 364 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 365 | self.driver.read(buf) 366 | } 367 | } 368 | 369 | unsafe impl<'a, B: 'a, D> Send for Patch<'a, B, D> 370 | where 371 | B: Send, 372 | D: Send, 373 | { 374 | } 375 | 376 | impl error::Error for Error {} 377 | 378 | impl Display for Error { 379 | fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { 380 | match *self { 381 | Error::Io(ref e) => write!(fmt, "{}", e), 382 | Error::Mem => write!(fmt, "out of memory"), 383 | Error::BadMagic => write!(fmt, "bad magic number given"), 384 | Error::Unimplemented => write!(fmt, "unimplemented feature"), 385 | Error::Internal => write!(fmt, "internal error"), 386 | Error::Unknown(n) => write!(fmt, "unknown error {} from native library", n), 387 | } 388 | } 389 | } 390 | 391 | impl From for Error { 392 | fn from(err: io::Error) -> Error { 393 | Error::Io(err) 394 | } 395 | } 396 | 397 | impl From for Error { 398 | fn from(err: raw::rs_result) -> Error { 399 | match err { 400 | raw::RS_BLOCKED => io_err(io::ErrorKind::WouldBlock, "blocked waiting for more data"), 401 | raw::RS_IO_ERROR => io_err(io::ErrorKind::Other, "unknown IO error from librsync"), 402 | raw::RS_MEM_ERROR => Error::Mem, 403 | raw::RS_INPUT_ENDED => { 404 | io_err(io::ErrorKind::UnexpectedEof, "unexpected end of input file") 405 | } 406 | raw::RS_BAD_MAGIC => Error::BadMagic, 407 | raw::RS_UNIMPLEMENTED => Error::Unimplemented, 408 | raw::RS_CORRUPT => io_err(io::ErrorKind::InvalidData, "unbelievable value in stream"), 409 | raw::RS_INTERNAL_ERROR => Error::Internal, 410 | raw::RS_PARAM_ERROR => io_err(io::ErrorKind::InvalidInput, "bad parameter"), 411 | n => Error::Unknown(n), 412 | } 413 | } 414 | } 415 | 416 | impl SignatureType { 417 | fn as_raw(self) -> raw::rs_magic_number { 418 | match self { 419 | SignatureType::MD4 => raw::RS_MD4_SIG_MAGIC, 420 | SignatureType::Blake2 => raw::RS_BLAKE2_SIG_MAGIC, 421 | } 422 | } 423 | } 424 | 425 | impl Drop for Sumset { 426 | fn drop(&mut self) { 427 | unsafe { 428 | if !self.0.is_null() { 429 | raw::rs_free_sumset(self.0); 430 | } 431 | } 432 | } 433 | } 434 | 435 | impl Deref for Sumset { 436 | type Target = *mut raw::rs_signature_t; 437 | fn deref(&self) -> &Self::Target { 438 | &self.0 439 | } 440 | } 441 | 442 | unsafe impl Send for Sumset {} 443 | 444 | extern "C" fn patch_copy_cb( 445 | opaque: *mut libc::c_void, 446 | pos: raw::rs_long_t, 447 | len: *mut libc::size_t, 448 | buf: *mut *mut libc::c_void, 449 | ) -> raw::rs_result { 450 | let mut input: RefMut = unsafe { 451 | let h: *mut Rc> = mem::transmute(opaque); 452 | (*h).borrow_mut() 453 | }; 454 | let output = unsafe { 455 | let buf: *mut u8 = mem::transmute(*buf); 456 | slice::from_raw_parts_mut(buf, *len) 457 | }; 458 | try_or_rs_error!(input.seek(io::SeekFrom::Start(pos as u64))); 459 | try_or_rs_error!(input.read(output)); 460 | raw::RS_DONE 461 | } 462 | 463 | fn io_err(kind: io::ErrorKind, e: E) -> Error 464 | where 465 | E: Into>, 466 | { 467 | Error::Io(io::Error::new(kind, e)) 468 | } 469 | 470 | #[cfg(test)] 471 | mod test { 472 | use super::*; 473 | use std::io::{Cursor, Read}; 474 | use std::thread; 475 | 476 | const DATA: &'static str = "this is a string to be tested"; 477 | const DATA2: &'static str = "this is another string to be tested"; 478 | 479 | // generated with `rdiff signature -b 10 -S 5 data data.sig` 480 | fn data_signature() -> Vec { 481 | vec![ 482 | 0x72, 0x73, 0x01, 0x36, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x05, 0x1b, 0x21, 483 | 0x04, 0x8b, 0xad, 0x3c, 0xbd, 0x19, 0x09, 0x1d, 0x1b, 0x04, 0xf0, 0x9d, 0x1f, 0x64, 484 | 0x31, 0xde, 0x15, 0xf4, 0x04, 0x87, 0x60, 0x96, 0x19, 0x50, 0x39, 485 | ] 486 | } 487 | 488 | // generated with `rdiff delta data.sig data2 data2.delta` 489 | fn data2_delta() -> Vec { 490 | vec![ 491 | 0x72, 0x73, 0x02, 0x36, 0x10, 0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 492 | 0x6e, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x45, 0x0a, 0x13, 0x00, 493 | ] 494 | } 495 | 496 | #[test] 497 | fn signature() { 498 | let cursor = Cursor::new(DATA); 499 | let mut sig = Signature::with_options(cursor, 10, 5, SignatureType::MD4).unwrap(); 500 | let mut signature = Vec::new(); 501 | let read = sig.read_to_end(&mut signature).unwrap(); 502 | assert_eq!(read, signature.len()); 503 | assert_eq!(signature, data_signature()); 504 | sig.into_inner(); 505 | } 506 | 507 | #[test] 508 | fn delta() { 509 | let sig = data_signature(); 510 | let input = Cursor::new(DATA2); 511 | let mut job = Delta::new(input, &mut Cursor::new(sig)).unwrap(); 512 | let mut delta = Vec::new(); 513 | let read = job.read_to_end(&mut delta).unwrap(); 514 | assert_eq!(read, delta.len()); 515 | assert_eq!(delta, data2_delta()); 516 | job.into_inner(); 517 | } 518 | 519 | #[test] 520 | fn patch() { 521 | let base = Cursor::new(DATA); 522 | let delta = data2_delta(); 523 | let delta = Cursor::new(delta); 524 | let mut patch = Patch::new(base, delta).unwrap(); 525 | let mut computed_new = String::new(); 526 | patch.read_to_string(&mut computed_new).unwrap(); 527 | assert_eq!(computed_new, DATA2); 528 | patch.into_inner(); 529 | } 530 | 531 | #[test] 532 | fn integration() { 533 | let base = Cursor::new(DATA); 534 | let new = Cursor::new(DATA2); 535 | let mut sig = Signature::with_options(base, 10, 5, SignatureType::MD4).unwrap(); 536 | let delta = Delta::new(new, &mut sig).unwrap(); 537 | let base = Cursor::new(DATA); 538 | let mut patch = Patch::new(base, delta).unwrap(); 539 | let mut computed_new = String::new(); 540 | patch.read_to_string(&mut computed_new).unwrap(); 541 | assert_eq!(computed_new, DATA2); 542 | } 543 | 544 | #[test] 545 | fn send_sig() { 546 | let cursor = Cursor::new(DATA); 547 | let mut sig = Signature::new(cursor).unwrap(); 548 | let t = thread::spawn(move || { 549 | let mut signature = Vec::new(); 550 | sig.read_to_end(&mut signature).unwrap(); 551 | }); 552 | t.join().unwrap(); 553 | } 554 | 555 | #[test] 556 | fn send_delta() { 557 | let sig = data_signature(); 558 | let input = Cursor::new(DATA2); 559 | let mut job = Delta::new(input, &mut Cursor::new(sig)).unwrap(); 560 | let t = thread::spawn(move || { 561 | let mut delta = Vec::new(); 562 | job.read_to_end(&mut delta).unwrap(); 563 | }); 564 | t.join().unwrap(); 565 | } 566 | 567 | #[test] 568 | fn send_patch() { 569 | let base = Cursor::new(DATA); 570 | let delta = data2_delta(); 571 | let delta = Cursor::new(delta); 572 | let mut patch = Patch::new(base, delta).unwrap(); 573 | let t = thread::spawn(move || { 574 | let mut computed_new = String::new(); 575 | patch.read_to_string(&mut computed_new).unwrap(); 576 | }); 577 | t.join().unwrap(); 578 | } 579 | 580 | #[test] 581 | fn trivial_large_file() { 582 | let data = vec![0; 65536]; 583 | let mut sig = 584 | Signature::with_options(Cursor::new(&data), 16384, 5, SignatureType::MD4).unwrap(); 585 | let delta = Delta::new(Cursor::new(&data), &mut sig).unwrap(); 586 | let mut computed_new = vec![]; 587 | Patch::new(Cursor::new(&data), delta) 588 | .unwrap() 589 | .read_to_end(&mut computed_new) 590 | .unwrap(); 591 | assert_eq!(computed_new, data); 592 | } 593 | } 594 | -------------------------------------------------------------------------------- /src/logfwd.rs: -------------------------------------------------------------------------------- 1 | use libc::c_char; 2 | use std::sync::Once; 3 | 4 | use crate::raw; 5 | 6 | /// Manually initialize logging. 7 | /// 8 | /// It is optional to call this function, and safe to do so more than once. 9 | pub fn init() { 10 | static mut INIT: Once = Once::new(); 11 | 12 | unsafe { 13 | INIT.call_once(|| { 14 | init_impl(); 15 | }); 16 | } 17 | } 18 | 19 | #[cfg(feature = "log")] 20 | fn init_impl() { 21 | use log::LevelFilter; 22 | 23 | // trace to our callback 24 | unsafe { 25 | raw::rs_trace_to(trace); 26 | } 27 | 28 | // determine log level 29 | // this is useful because if the setted level is not Debug we can optimize librsync log 30 | // calls 31 | let level = match log::max_level() { 32 | LevelFilter::Info => raw::RS_LOG_NOTICE, 33 | LevelFilter::Debug | LevelFilter::Trace => raw::RS_LOG_DEBUG, 34 | _ => raw::RS_LOG_WARNING, 35 | }; 36 | unsafe { 37 | raw::rs_trace_set_level(level); 38 | } 39 | } 40 | 41 | #[cfg(feature = "log")] 42 | extern "C" fn trace(level: raw::rs_loglevel, msg: *const c_char) { 43 | use log::Level; 44 | use std::ffi::CStr; 45 | 46 | let level = match level { 47 | raw::RS_LOG_EMERG | raw::RS_LOG_ALERT | raw::RS_LOG_CRIT | raw::RS_LOG_ERR => Level::Error, 48 | raw::RS_LOG_WARNING => Level::Warn, 49 | raw::RS_LOG_NOTICE | raw::RS_LOG_INFO => Level::Info, 50 | raw::RS_LOG_DEBUG => Level::Debug, 51 | _ => Level::Error, 52 | }; 53 | let msg = unsafe { CStr::from_ptr(msg).to_string_lossy() }; 54 | log!(target: "librsync", level, "{}", msg); 55 | } 56 | 57 | #[cfg(not(feature = "log"))] 58 | fn init_impl() { 59 | unsafe { 60 | raw::rs_trace_to(trace); 61 | raw::rs_trace_set_level(raw::RS_LOG_EMERG); 62 | } 63 | 64 | extern "C" fn trace(_level: raw::rs_loglevel, _msg: *const c_char) {} 65 | } 66 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | #![macro_use] 2 | 3 | macro_rules! try_or_rs_error( 4 | ($e:expr) => ( 5 | match $e { 6 | Ok(v) => v, 7 | _ => { 8 | return raw::RS_IO_ERROR; 9 | } 10 | } 11 | ) 12 | ); 13 | -------------------------------------------------------------------------------- /src/whole.rs: -------------------------------------------------------------------------------- 1 | //! Process whole files in a single call. 2 | //! 3 | //! Provides functions to compute signatures, delta and patches with a single call. Those functions 4 | //! are useful if the application prefers to process whole files instead of using fine-grained APIs 5 | //! over IO. 6 | //! 7 | //! If fine-grained control over IO is necessary, it is provided by `Signature`, `Delta` and 8 | //! `Patch` structs. 9 | 10 | use super::*; 11 | use std::io::{self, BufRead, Read, Seek, Write}; 12 | 13 | /// Generates the signature of a basis input, and writes it out to an output stream. 14 | /// 15 | /// This function will consume the given input stream and attempt to write the resulting signature 16 | /// to the given output. In case of success, the number of bytes written is returned, otherwise 17 | /// an error is reported. 18 | /// 19 | /// The accepted arguments, among the input and output streams, are: 20 | /// 21 | /// * `block_len`: the block size for signature generation, in bytes; 22 | /// * `strong_len`: the truncated length of strong checksums, in bytes; 23 | /// * `sig_type`: the signature format to be used. 24 | pub fn signature_with_options( 25 | input: &mut R, 26 | output: &mut W, 27 | block_len: usize, 28 | strong_len: usize, 29 | sig_type: SignatureType, 30 | ) -> Result 31 | where 32 | R: BufRead, 33 | W: Write, 34 | { 35 | let mut sig = Signature::with_options(input, block_len, strong_len, sig_type)?; 36 | let written = io::copy(&mut sig, output)?; 37 | Ok(written) 38 | } 39 | 40 | /// Generates the signature of a basis input, by using default settings. 41 | /// 42 | /// This function will consume the given input stream and attempt to write the resulting signature 43 | /// to the given output. In case of success, the number of bytes written is returned, otherwise 44 | /// an error is reported. Default settings are used to produce the signature. BLAKE2 for the 45 | /// hashing, 2048 bytes for the block length and full length for the strong signature size. 46 | pub fn signature(input: &mut R, output: &mut W) -> Result 47 | where 48 | R: Read, 49 | W: Write, 50 | { 51 | let mut sig = Signature::new(input)?; 52 | let written = io::copy(&mut sig, output)?; 53 | Ok(written) 54 | } 55 | 56 | /// Generates a delta between a signature and a new file streams. 57 | /// 58 | /// This function will consume the new file and base signature inputs and writes to the given 59 | /// output the delta between them. In case of success, the number of bytes written is returned, 60 | /// otherwise an error is reported. The `new` parameter is the input stream representing a possibly 61 | /// modified file with respect to some base, for which its signature is provided as `base_sig` 62 | /// parameter. 63 | /// 64 | /// To generate a signature, see the `signature` function, or the `Signature` struct. 65 | pub fn delta( 66 | new: &mut R, 67 | base_sig: &mut S, 68 | output: &mut W, 69 | ) -> Result 70 | where 71 | R: Read, 72 | S: Read, 73 | W: Write, 74 | { 75 | let mut delta = Delta::new(new, base_sig)?; 76 | let written = io::copy(&mut delta, output)?; 77 | Ok(written) 78 | } 79 | 80 | /// Applies a patch, relative to a basis, into an output stream. 81 | /// 82 | /// This function will consume the base file and the new file delta inputs and writes to the given 83 | /// output the patched input. In case of success, the number of bytes written is returned, 84 | /// otherwise an error is reported. The `base` parameter is the input stream representing the base 85 | /// file from which apply the patch. This stream must be seekable. The `delta` parameter is a 86 | /// stream containing the delta between the base file and the new one. The output parameter will 87 | /// be used to write the output. 88 | /// 89 | /// To generate a delta, see the `delta` function, or the `Delta` struct. 90 | pub fn patch( 91 | base: &mut B, 92 | delta: &mut D, 93 | output: &mut W, 94 | ) -> Result 95 | where 96 | B: Read + Seek, 97 | D: Read, 98 | W: Write, 99 | { 100 | let mut patch = Patch::new(base, delta)?; 101 | let written = io::copy(&mut patch, output)?; 102 | Ok(written) 103 | } 104 | 105 | #[cfg(test)] 106 | mod test { 107 | use super::*; 108 | use crate::SignatureType; 109 | 110 | use std::io::Cursor; 111 | use std::str::from_utf8; 112 | 113 | const DATA: &'static str = "this is a string to be tested"; 114 | const DATA2: &'static str = "this is another string to be tested"; 115 | 116 | #[test] 117 | fn integration() { 118 | // signature 119 | let mut sig = Vec::new(); 120 | signature_with_options( 121 | &mut Cursor::new(DATA), 122 | &mut sig, 123 | 10, 124 | 5, 125 | SignatureType::Blake2, 126 | ) 127 | .unwrap(); 128 | 129 | // delta 130 | let mut dlt = Vec::new(); 131 | delta(&mut Cursor::new(DATA2), &mut Cursor::new(sig), &mut dlt).unwrap(); 132 | 133 | // patch 134 | let mut out = Vec::new(); 135 | patch(&mut Cursor::new(DATA), &mut Cursor::new(dlt), &mut out).unwrap(); 136 | 137 | // check that patched version is the same as DATA2 138 | let out_str = from_utf8(&out).unwrap(); 139 | assert_eq!(out_str, DATA2); 140 | } 141 | } 142 | --------------------------------------------------------------------------------