├── .gitattributes ├── .rustfmt.toml ├── .githooks └── pre-commit ├── .gitignore ├── meson_options.txt ├── AUTHORS ├── macros ├── Cargo.toml └── src │ └── lib.rs ├── .editorconfig ├── meson.build ├── man ├── meson.build └── fjp.1.rst.in ├── CONTRIBUTING.md ├── Cargo.toml ├── .github └── workflows │ └── rust.yml ├── src ├── rm.rs ├── has.rs ├── meson.build ├── list.rs ├── enable.rs ├── main.rs ├── disable.rs ├── location.rs ├── diff.rs ├── generate_standalone.rs ├── cli.rs ├── cat.rs ├── edit.rs ├── utils.rs ├── profile.rs └── profile_stream.rs ├── TODO.md ├── CHANGELOG.md ├── README.md ├── Cargo.lock └── COPYING /.gitattributes: -------------------------------------------------------------------------------- 1 | Cargo.lock binary 2 | 3 | *.rst.in linguist-language=rst 4 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2018" 2 | use_try_shorthand = true 3 | use_field_init_shorthand = true 4 | -------------------------------------------------------------------------------- /.githooks/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | [[ "$(git branch --show-current)" == "gh-pages" ]] && exit 0 3 | exec cargo fmt -- --check 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /_builddir 2 | /macros/Cargo.lock 3 | /macros/target 4 | /outdir 5 | /target 6 | /vendor 7 | 8 | *.log 9 | *.rpm 10 | -------------------------------------------------------------------------------- /meson_options.txt: -------------------------------------------------------------------------------- 1 | option('manpage', type: 'boolean', value: false, 2 | description: 'Build and install a manpage for fjp.') 3 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | fjp authors 2 | =========== 3 | 4 | Maintainer: 5 | - rusty-snake (https://github.com/rusty-snake) 6 | 7 | Committers: 8 | 9 | Contributors: 10 | - Usairim Isani (https://github.com/UsairimIsani) 11 | -------------------------------------------------------------------------------- /macros/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "macros" 3 | version = "0.4.0-dev" 4 | description = "Procedural Macros for fjp" 5 | authors = ["rusty-snake"] 6 | edition = "2018" 7 | license = "GPL-3.0-or-later" 8 | 9 | [lib] 10 | proc-macro = true 11 | 12 | [dependencies] 13 | syn = "1" 14 | quote = "1" 15 | proc-macro2 = "1" 16 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | trim_trailing_whitespace = true 6 | insert_final_newline = true 7 | 8 | [*.md] 9 | trim_trailing_whitespace = false 10 | 11 | [*.sh] 12 | indent_style = tab 13 | tab_width = 8 14 | 15 | [*.rs] 16 | indent_style = space 17 | indent_size = 4 18 | 19 | [meson.build] 20 | indent_style = space 21 | indent_size = 2 22 | -------------------------------------------------------------------------------- /meson.build: -------------------------------------------------------------------------------- 1 | project('fjp', 2 | # Remebmer to change version in Cargo.toml and macros/Cargo.toml too. 3 | version: '0.4.0-dev', 4 | license: 'GPL-3.0-or-later', 5 | meson_version: '>= 0.57.0', 6 | default_options: [ 'strip=true' ], 7 | ) 8 | 9 | docdir = get_option('datadir') / 'doc' / meson.project_name() 10 | 11 | subdir('src') 12 | 13 | if get_option('manpage') 14 | subdir('man') 15 | endif 16 | 17 | install_data( 18 | 'CHANGELOG.md', 'README.md', 'COPYING', 'AUTHORS', 19 | install_dir: docdir 20 | ) 21 | -------------------------------------------------------------------------------- /man/meson.build: -------------------------------------------------------------------------------- 1 | rst2man = find_program('rst2man') 2 | rst2html5 = find_program('rst2html5') 3 | 4 | fjp1rst = configure_file( 5 | input: 'fjp.1.rst.in', 6 | output: 'fjp.1.rst', 7 | configuration: { 8 | 'VERSION': meson.project_version(), 9 | }, 10 | ) 11 | 12 | custom_target( 13 | 'manpage', 14 | build_by_default: true, 15 | install: true, 16 | install_dir: get_option('mandir') / 'man1', 17 | input: fjp1rst, 18 | output: 'fjp.1', 19 | command: [ 20 | rst2man, 21 | '@INPUT@', 22 | '@OUTPUT@', 23 | ], 24 | ) 25 | 26 | custom_target( 27 | 'manpage-html', 28 | build_by_default: true, 29 | install: true, 30 | install_dir: docdir, 31 | input: fjp1rst, 32 | output: 'fjp.1.html5', 33 | command: [ 34 | rst2html5, 35 | '@INPUT@', 36 | '@OUTPUT@', 37 | ], 38 | ) 39 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute to firejail-profile 2 | 3 | First of all, thanks for contibuting. 4 | 5 | ## Issues 6 | 7 | You can and should open an issue if you … 8 | 9 | - … have an idea for new features. 10 | - … have a question. 11 | - … found a bug. 12 | 13 | You should do a quick search to avoid duplicated issues. 14 | 15 | ### Bugs 16 | 17 | Please include the following informations: 18 | 19 | - Distripution (e.g. Arch Linux) 20 | - firejail-profile version (`fjp --version`) 21 | - rust version (`rustc --version`) 22 | 23 | ## Pull Requests 24 | 25 | If you contibute code, please use rustfmt to format it. 26 | 27 | New documentation comments must use rustdocs [intra-doc] feature. 28 | [intra-doc]: https://doc.rust-lang.org/rustdoc/linking-to-items-by-name.html 29 | 30 | ### Dependency Specification Rules 31 | 32 | - Omit patch versions. 33 | - If features are specified, the [dependencies.foo] syntax is used. 34 | - Features dependencies are ordered alphabetically with following Ordering. 35 | - Ordering: 36 | - [dependencies]; 37 | - [dependencies.foo]; 38 | - [dependencies.bar] 39 | -- optional=true; 40 | - path; 41 | - build; 42 | - dev; 43 | 44 | ### use Structs,functions,Traits etc in function body. 45 | 46 | - macros/src/lib.rs 47 | - src/utils.rs 48 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "fjp" 3 | # Remebmer to change version in meson.build and macros/Cargo.toml too. 4 | version = "0.4.0-dev" 5 | description = "A handy command line program to work fast and straightforward with firejail profiles." 6 | authors = ["rusty-snake"] 7 | edition = "2021" 8 | rust-version = "1.57" 9 | readme = "README.md" 10 | homepage = "https://rusty-snake.github.io/fjp" 11 | repository = "https://github.com/rusty-snake/fjp" 12 | license = "GPL-3.0-or-later" 13 | build = "build.rs" 14 | categories = ["command-line-utilities"] 15 | keywords = ["firejail"] 16 | 17 | [features] 18 | default = [] 19 | full = ["color-backtrace"] 20 | 21 | [dependencies] 22 | anyhow = "1.0" 23 | bitflags = "1.3" 24 | lazy_static = "1" 25 | libc = "0.2" 26 | log = "0.4" 27 | nix = "0.25" 28 | termcolor = "1.1" 29 | thiserror = "1.0" 30 | 31 | [dependencies.clap] 32 | version = "3" 33 | features = [ "derive", "wrap_help" ] 34 | 35 | [dependencies.env_logger] 36 | version = "0.9" 37 | default-features = false 38 | features = ["termcolor", "atty"] 39 | 40 | [dependencies.color-backtrace] 41 | version = "0.5" 42 | optional = true 43 | 44 | [dependencies.macros] 45 | path = "macros" 46 | 47 | [build-dependencies] 48 | clap_complete = "3" 49 | 50 | [build-dependencies.clap] 51 | version = "3" 52 | default-features = false 53 | features = [ "derive" ] 54 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust CI 2 | 3 | on: 4 | push: 5 | branches-ignore: [ "dependabot/**" ] 6 | paths: 7 | - .github/workflows/rust.yml 8 | - macros/src/* 9 | - macros/Cargo.toml 10 | - src/* 11 | - Cargo.lock 12 | - Cargo.toml 13 | - build.rs 14 | pull_request: 15 | branches: [master] 16 | paths: 17 | - .github/workflows/rust.yml 18 | - macros/src/* 19 | - macros/Cargo.toml 20 | - src/* 21 | - Cargo.lock 22 | - Cargo.toml 23 | - build.rs 24 | 25 | permissions: 26 | contents: read 27 | 28 | env: 29 | CARGO_TERM_COLOR: always 30 | 31 | jobs: 32 | check: 33 | name: Rust ${{ matrix.rust }} 34 | runs-on: ubuntu-20.04 35 | strategy: 36 | matrix: 37 | rust: [1.57.0, stable] 38 | steps: 39 | - uses: actions/checkout@v3 40 | - name: Install ${{ matrix.rust }} rust 41 | uses: dtolnay/rust-toolchain@master 42 | with: 43 | toolchain: ${{ matrix.rust }} 44 | - run: cargo -Vv && rustc -Vv 45 | - run: cargo check 46 | - run: cargo check --all-features 47 | - run: cargo clippy -- -Dwarnings -Dclippy::dbg_macro 48 | if: ${{ matrix.rust == 'stable' }} 49 | - run: cargo fmt --all -- --check 50 | if: ${{ matrix.rust == 'stable' }} 51 | - run: cargo test 52 | if: ${{ matrix.rust == 'stable' }} 53 | -------------------------------------------------------------------------------- /src/rm.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | use crate::profile::{Profile, ProfileFlags}; 21 | use log::{debug, error, trace}; 22 | use std::fs::remove_file; 23 | 24 | pub fn start(cli: &crate::cli::CliRm) { 25 | debug!("subcommand: rm"); 26 | 27 | for profile in &cli.profile_names { 28 | let profile = Profile::new( 29 | profile, 30 | ProfileFlags::LOOKUP_USER | ProfileFlags::DENY_BY_PATH | ProfileFlags::ASSUME_EXISTENCE, 31 | ) 32 | .unwrap(); 33 | trace!("Deleting '{}'.", profile.full_name()); 34 | remove_file(profile.path().unwrap()) 35 | .unwrap_or_else(|err| error!("Failed to delete '{}': {}", profile.full_name(), err)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/has.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | use crate::profile::{Profile, ProfileFlags}; 21 | use crate::utils::ColoredText; 22 | use log::debug; 23 | use std::process::exit; 24 | use termcolor::Color; 25 | 26 | pub fn start(cli: &crate::cli::CliHas) { 27 | debug!("subcommand: has"); 28 | 29 | let profile = Profile::new(&cli.profile_name, ProfileFlags::default()).unwrap(); 30 | if let Some(path) = profile.path() { 31 | println!( 32 | "Profile found for {} at {}", 33 | profile.raw_name(), 34 | ColoredText::new(Color::Green, path.to_string_lossy()) 35 | ); 36 | exit(0); 37 | } else { 38 | println!("Could not find a Profile for {}.", &cli.profile_name); 39 | exit(100); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /macros/src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate proc_macro; 2 | 3 | use std::env; 4 | use std::process; 5 | 6 | /// Create a [`&str`](std::str) containing the version of fjp. 7 | /// 8 | /// ### Format: 9 | /// - `VERSION[+COMMIT[-dirty]]` 10 | /// - VERSION: `0.2.0` or `0.2.0-dev` 11 | /// - COMMIT: `0616df2` if VERSION has a pre-release identifier 12 | /// and `FJP_COMMIT` (env-var) is set or `.git` (dir) exists. 13 | /// - `-dirty`: if a dirty state could be determined 14 | #[proc_macro] 15 | pub fn fjp_version(_: proc_macro::TokenStream) -> proc_macro::TokenStream { 16 | use env::var; 17 | use process::Command; 18 | 19 | fn git_commit() -> Option { 20 | Command::new("git") 21 | .args(&["rev-parse", "--short", "HEAD"]) 22 | .output() 23 | .ok() 24 | .and_then(|output| String::from_utf8(output.stdout).ok()) 25 | .map(|commit| commit.trim().to_string()) 26 | } 27 | 28 | fn is_dirty() -> bool { 29 | Command::new("git") 30 | .args(&["diff-index", "--quiet", "HEAD", "--"]) 31 | .status() 32 | .ok() 33 | .and_then(|st_code| st_code.code()) 34 | .map_or(false, |code| code == 1) 35 | } 36 | 37 | let mut version = env!("CARGO_PKG_VERSION").to_string(); 38 | 39 | if !env!("CARGO_PKG_VERSION_PRE").is_empty() { 40 | let commit = var("FJP_COMMIT").ok().or_else(git_commit); 41 | if let Some(commit) = commit { 42 | version.push('+'); 43 | version.push_str(&commit); 44 | 45 | if is_dirty() { 46 | version.push_str("-dirty"); 47 | } 48 | } 49 | } 50 | 51 | proc_macro::TokenStream::from(proc_macro::TokenTree::from(proc_macro::Literal::string( 52 | &version, 53 | ))) 54 | } 55 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | 2 | + more unit-tests for `utils` 3 | + Integration tests (possible crates: assert-cmd & assert-fs) 4 | + improve zsh-completion 5 | + user editable shortcuts 6 | + aliases like git or cargo 7 | + rethink the syntax for profile::Profile::complete_name 8 | + Path::to_string_lossy -> Path::display 9 | 10 | edit 11 | ---- 12 | 13 | - warn/reject `edit abc.local` if no `include abc.local` in `abc.profile` 14 | - open local instead 15 | 16 | cat 17 | --- 18 | 19 | disable/enable 20 | -------------- 21 | 22 | - profile devel option: disable *.inc locals + gloabls.local 23 | - enable/disable support for /etc/firejail by touching in USER & symln in disabled-dir 24 | 25 | grep 26 | ---- 27 | 28 | Like `git grep`, a grep for /etc/firejail/* and ~/.config/firejail/*. 29 | 30 | sed 31 | --- 32 | 33 | Simple mass edit. 34 | 35 | check/lint 36 | ---------- 37 | 38 | Check synatx, blacklist, …. 39 | Lints for ordering/sorting, suggest options, check for inconsistents, …. 40 | check-blacklist 41 | 42 | fix 43 | --- 44 | 45 | fix some auto-fixable lints 46 | 47 | trash 48 | ----- 49 | 50 | 51 | 52 | mv 53 | -- 54 | 55 | 56 | 57 | cp 58 | -- 59 | 60 | 61 | 62 | list 63 | ---- 64 | 65 | build 66 | ----- 67 | 68 | Reimplement firejail --build 69 | 70 | diff 71 | ---- 72 | 73 | - Handel `include *.{local,profile}` 74 | - implement some config-file support to set a default format for it 75 | - show files side-by-side with `--format=color` 76 | - format=color: `private-etc foo,bar`, `private-etc foo` should only highligt `,bar` 77 | 78 | merge 79 | ----- 80 | 81 | Merging two profile. 82 | Keep noblacklist, ignore, ... 83 | Remove no*, ... if not set in both. 84 | 85 | scan 86 | ---- 87 | 88 | Scan for common mistakes and outdated options in ~/.config/firejail. 89 | 90 | query 91 | ----- 92 | 93 | Some kind of higherlevel grep (e.g. exist a blacklist for foo/bar; list all redirect profiles; ...) 94 | 95 | gui 96 | --- 97 | 98 | A gui for all of this. 99 | -------------------------------------------------------------------------------- /src/meson.build: -------------------------------------------------------------------------------- 1 | fs = import('fs') 2 | 3 | cargo_target_dir = meson.project_build_root() / 'cargo-target-dir' 4 | sources = [ 5 | '../build.rs', 6 | '../Cargo.lock', 7 | '../Cargo.toml', 8 | '../macros/Cargo.toml', 9 | '../macros/src/lib.rs', 10 | 'cat.rs', 11 | 'cli.rs', 12 | 'diff.rs', 13 | 'disable.rs', 14 | 'edit.rs', 15 | 'enable.rs', 16 | 'generate_standalone.rs', 17 | 'has.rs', 18 | 'list.rs', 19 | 'location.rs', 20 | 'main.rs', 21 | 'profile.rs', 22 | 'profile_stream.rs', 23 | 'rm.rs', 24 | 'utils.rs', 25 | ] 26 | 27 | cargo = find_program( 28 | 'cargo', 29 | fs.expanduser('~/.cargo/bin/cargo'), 30 | version: '>=1.57', 31 | ) 32 | 33 | cargo_build_cmd = [ 34 | cargo, 35 | 'build', 36 | '--manifest-path=' + meson.project_source_root() + '/Cargo.toml', 37 | ] 38 | 39 | if get_option('buildtype') == 'release' 40 | cargo_build_cmd += ['--release', '--features=color-backtrace'] 41 | endif 42 | 43 | cargo_build = custom_target( 44 | 'cargo-build', 45 | console: true, 46 | build_by_default: true, 47 | input: sources, 48 | output: [meson.project_name()], 49 | env: { 50 | 'FJP_SHELLCOMP_DIR': meson.current_build_dir(), 51 | 'CARGO_TARGET_DIR': cargo_target_dir, 52 | }, 53 | command: cargo_build_cmd, 54 | ) 55 | 56 | meson.add_install_script( 57 | '/usr/bin/env', 58 | 'CARGO_TARGET_DIR=' + cargo_target_dir, 59 | 'MESON_CURRENT_BUILD_DIR=' + meson.current_build_dir(), 60 | 'buildtype=' + get_option('buildtype'), 61 | 'bindir=' + get_option('prefix') / get_option('bindir'), 62 | 'datadir=' + get_option('prefix') / get_option('datadir'), 63 | '/bin/sh', 64 | '-e', 65 | '-u', 66 | '-c', 67 | ''' 68 | install -Dm0755 "$CARGO_TARGET_DIR"/"$buildtype"/fjp "$DESTDIR$bindir"/fjp 69 | install -Dm0644 "$MESON_CURRENT_BUILD_DIR"/fjp.bash "$DESTDIR$datadir"/bash-completion/completions/fjp 70 | install -Dm0644 "$MESON_CURRENT_BUILD_DIR"/fjp.fish "$DESTDIR$datadir"/fish/completions/fjp.fish 71 | install -Dm0644 "$MESON_CURRENT_BUILD_DIR"/fjp.zsh "$DESTDIR$datadir"/zsh/site-functions/_fjp 72 | ''' 73 | ) 74 | -------------------------------------------------------------------------------- /src/list.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | use crate::{fatal, USER_PROFILE_DIR}; 21 | use log::{debug, warn}; 22 | use std::ffi::OsStr; 23 | use std::fs::read_dir; 24 | use std::io::{stdout, Write}; 25 | use std::os::unix::ffi::OsStrExt; 26 | use std::path::Path; 27 | 28 | pub fn start(cli: &crate::cli::CliList) { 29 | debug!("subcommand: list"); 30 | 31 | let mut user_profiles = read_dir(&*USER_PROFILE_DIR) 32 | .unwrap_or_else(|err| fatal!("Failed to open the user profile directory: {}", err)) 33 | .filter_map(|readdir_result| match readdir_result { 34 | Ok(direntry) => Some(direntry), 35 | Err(e) => { 36 | warn!("{}", e); 37 | None 38 | } 39 | }) 40 | .filter(|direntry| direntry.file_type().unwrap().is_file()) 41 | .map(|file| file.file_name()) 42 | .filter(|file| !cli.incs || Path::new(file).extension() == Some(OsStr::new("inc"))) 43 | .filter(|file| !cli.locals || Path::new(file).extension() == Some(OsStr::new("local"))) 44 | .filter(|file| !cli.profiles || Path::new(file).extension() == Some(OsStr::new("profile"))) 45 | .collect::>(); 46 | user_profiles.sort_unstable(); 47 | let stdout = stdout(); 48 | let mut stdout = stdout.lock(); 49 | for user_profile in user_profiles { 50 | stdout.write_all(user_profile.as_bytes()).unwrap(); 51 | stdout.write_all(b"\n").unwrap(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | ### Changed 9 | - clap to v3 10 | - MSRV: 1.57 11 | - Rust 2021 edition 12 | 13 | ## [0.3.0] – 2021-09-25 14 | ### Added 15 | - New flags for list: `--incs`, `--locals` and `--profiles` 16 | 17 | ### Changed 18 | - Rewrite man-page in reStructuredText 19 | - MSRV: 1.52.0 20 | - generate-standalones: rename --keep-inc to --keep-incs (for consistent naming) 21 | - updated shortnames 22 | 23 | ## [0.2.0] – 2021-02-07 24 | ### Added 25 | - CI using GitHub Actions 26 | - MSRV: 1.45 27 | - new sub-commands: list, generate-standalone 28 | - new experimental sub-command: diff 29 | - ~~make.sh: more control about the installation paths~~ 30 | - ~~make.sh: support striping binaries~~ 31 | - ~~make.sh: can build rpms~~ 32 | - add short options to disable, enable and edit 33 | - shortnames for profiles on supported sub-commands. 34 | (e.g. `dc` expands to `disable-common.inc`) 35 | - edit: If a profile is only found in the system-location ask if it should be copied. 36 | 37 | ### Changed 38 | - cat: no-globals in now default 39 | - edit \--tmp: consistent behavior: always start editing with the current profile. 40 | Previously profiles were copied from /etc/firejail if they don't exists in ~/.config/firejail, 41 | and renamed if the exists (now they will be copied inside ~/.config/firejail). 42 | - has: exit with 100 if no profile could we found. 43 | - Switch from self written make.sh to meson as build-system 44 | 45 | ### Removed 46 | - edit: `--no-create` has been removed. If you don't want to create the profile, 47 | just close your editor without saving. 48 | - edit: `--no-copy` has been removed. It is now interactive. 49 | 50 | ## [0.1.0] – 2020-05-04 51 | ### Added 52 | - subcommands: cat, disable, edit, enable, has, rm 53 | - shell completion 54 | - build system make.sh 55 | - manpage (incomplete) 56 | 57 | 58 | [Unreleased]: https://github.com/rusty-snake/fjp/compare/master...v0.3.0 59 | [0.3.0]: https://github.com/rusty-snake/fjp/releases/tag/v0.3.0 60 | [0.2.0]: https://github.com/rusty-snake/fjp/releases/tag/v0.2.0 61 | [0.1.0]: https://github.com/rusty-snake/fjp/releases/tag/v0.1.0 62 | -------------------------------------------------------------------------------- /src/enable.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | use crate::{ 21 | disable::DISABLED_DIR, 22 | profile::{Profile, ProfileFlags}, 23 | utils::input, 24 | USER_PROFILE_DIR, 25 | }; 26 | use log::{debug, error, info, warn}; 27 | use std::fs::rename; 28 | 29 | pub fn start(cli: &crate::cli::CliEnable) { 30 | debug!("subcommand: enable"); 31 | 32 | if cli.user { 33 | enable_user(); 34 | } else { 35 | let profile = Profile::new( 36 | cli.profile_name.as_deref().unwrap(), 37 | ProfileFlags::LOOKUP_USER | ProfileFlags::ASSUME_EXISTENCE | ProfileFlags::DENY_BY_PATH, 38 | ) 39 | .unwrap(); 40 | enable_profile(&profile); 41 | } 42 | } 43 | 44 | fn enable_user() { 45 | let mut disabled_user_profile_dir = USER_PROFILE_DIR.to_owned_inner(); 46 | disabled_user_profile_dir.set_extension("disabled"); 47 | debug!( 48 | "disabled user profile dir: {}", 49 | disabled_user_profile_dir.to_string_lossy() 50 | ); 51 | rename(&disabled_user_profile_dir, &*USER_PROFILE_DIR) 52 | .unwrap_or_else(|err| error!("Rename failed: {}", err)); 53 | } 54 | 55 | fn enable_profile(profile: &Profile<'_>) { 56 | let disabled_profile = DISABLED_DIR.get_profile_path(profile.full_name()); 57 | 58 | if !disabled_profile.exists() { 59 | error!("{} is not disabled.", profile.full_name()); 60 | return; 61 | } 62 | 63 | // NOTE: unwrap can't fail because profile is created with ASSUME_EXISTENCE. 64 | let enabled_profile = profile.path().unwrap(); 65 | 66 | if enabled_profile.exists() { 67 | warn!("Profile '{}' is alread enabled.", profile.full_name()); 68 | if input("Override? [Y/n] ").unwrap() != "y" { 69 | info!("Skipping"); 70 | return; 71 | } 72 | } 73 | 74 | debug!( 75 | "Move '{}' to '{}'", 76 | disabled_profile.display(), 77 | enabled_profile.display() 78 | ); 79 | rename(&disabled_profile, enabled_profile) 80 | .unwrap_or_else(|err| error!("Rename failed: {}", err)); 81 | } 82 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | #![warn(rust_2018_idioms)] 21 | #![deny(missing_debug_implementations)] 22 | 23 | //! A commandline program to deal with firejail profiles. 24 | 25 | use clap::Parser; 26 | use env_logger::{Builder, Env}; 27 | use lazy_static::lazy_static; 28 | use log::warn; 29 | use nix::unistd::getuid; 30 | 31 | mod cli; 32 | mod location; 33 | mod profile; 34 | mod profile_stream; 35 | mod utils; 36 | 37 | use location::Location; 38 | use utils::home_dir; 39 | 40 | mod cat; 41 | mod diff; 42 | mod disable; 43 | mod edit; 44 | mod enable; 45 | mod generate_standalone; 46 | mod has; 47 | mod list; 48 | mod rm; 49 | 50 | use cat::start as start_cat; 51 | use diff::start as start_diff; 52 | use disable::start as start_disable; 53 | use edit::start as start_edit; 54 | use enable::start as start_enable; 55 | use generate_standalone::start as start_generate_standalone; 56 | use has::start as start_has; 57 | use list::start as start_list; 58 | use rm::start as start_rm; 59 | 60 | lazy_static! { 61 | static ref SYSTEM_PROFILE_DIR: Location = Location::from("/etc/firejail/"); 62 | static ref USER_PROFILE_DIR: Location = { 63 | Location::from( 64 | home_dir() 65 | .expect("Can not get User's home dir.") 66 | .join(".config/firejail/"), 67 | ) 68 | }; 69 | } 70 | 71 | fn main() { 72 | #[cfg(feature = "full")] 73 | color_backtrace::install(); 74 | 75 | Builder::from_env(Env::new().default_filter_or("info")) 76 | .format_timestamp(None) 77 | .init(); 78 | 79 | if getuid().is_root() { 80 | warn!("fjp is designed to be used as regular user."); 81 | } 82 | 83 | match &cli::Cli::parse().subcommand { 84 | cli::Subcommands::Cat(cli) => start_cat(cli), 85 | cli::Subcommands::Diff(cli) => start_diff(cli), 86 | cli::Subcommands::Disable(cli) => start_disable(cli), 87 | cli::Subcommands::Edit(cli) => start_edit(cli), 88 | cli::Subcommands::Enable(cli) => start_enable(cli), 89 | cli::Subcommands::GenerateStandalone(cli) => start_generate_standalone(cli), 90 | cli::Subcommands::Has(cli) => start_has(cli), 91 | cli::Subcommands::List(cli) => start_list(cli), 92 | cli::Subcommands::Rm(cli) => start_rm(cli), 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /man/fjp.1.rst.in: -------------------------------------------------------------------------------- 1 | ### 2 | fjp 3 | ### 4 | 5 | a handy command line program to work fast and straightforward with firejail profiles 6 | #################################################################################### 7 | 8 | :Version: @VERSION@ 9 | :Manual section: 1 10 | 11 | SYNOPSIS 12 | ======== 13 | 14 | .. code-block:: sh 15 | 16 | fjp 17 | 18 | DESCRIPTION 19 | =========== 20 | 21 | fjp is a command-line program written in Rust, a modern and safe programming 22 | language. It allows you to show, edit, compare, disable or remove firejail 23 | profiles. And many more features like search, check, sed or merge will come. 24 | 25 | SUBCOMMANDS 26 | =========== 27 | 28 | cat 29 | --- 30 | 31 | Show a profile, its .local and its redirect profile. 32 | 33 | .. code-block:: sh 34 | 35 | fjp cat [FLAGS] 36 | 37 | ``--no-locals`` 38 | Do not show .local files. 39 | 40 | ``--no-pager`` 41 | Do not pipe output into a pager. 42 | 43 | ``--no-redirects`` 44 | Do not show redirect profiles. 45 | 46 | diff 47 | ---- 48 | 49 | Show the differences between two profiles. (experimental) 50 | 51 | .. code-block:: sh 52 | 53 | fjp diff [OPTIONS] 54 | 55 | ``-f, --format `` 56 | specify the diff format [default: simple] [possible values: color, simple] 57 | 58 | disable 59 | ------- 60 | 61 | Disable profiles 62 | 63 | .. code-block:: sh 64 | 65 | fjp disable [FLAGS] 66 | 67 | ``-l, --list`` 68 | List all disabled profiles 69 | 70 | ``-u, --user`` 71 | Disable ~/.config/firejail 72 | 73 | edit 74 | ---- 75 | 76 | .. code-block:: sh 77 | 78 | fjp edit [FLAGS] 79 | 80 | ``-t, --tmp`` 81 | Edit non-persistent 82 | 83 | enable 84 | ------ 85 | 86 | Enable profiles 87 | 88 | .. code-block:: sh 89 | 90 | fjp enable [FLAGS] 91 | 92 | ``-u, --user`` 93 | Enable ~/.config/firejail 94 | 95 | generate-standalone 96 | ------------------- 97 | 98 | Copy the profile and all its includes into one file. 99 | 100 | .. code-block:: sh 101 | 102 | fjp generate-standalone [FLAGS] [OPTIONS] 103 | 104 | ``--keep-incs`` 105 | Keep all includes of .inc's 106 | 107 | ``--keep-locals`` 108 | Keep all includes of .local's 109 | 110 | ``-o, --output `` 111 | The name of the file to write results 112 | 113 | has 114 | --- 115 | 116 | Look if a profile exists 117 | 118 | .. code-block:: sh 119 | 120 | fjp has 121 | 122 | list 123 | ---- 124 | 125 | List all user profile 126 | 127 | .. code-block:: sh 128 | 129 | fjp list [FLAGS] 130 | 131 | ``--incs`` 132 | List only .inc 133 | 134 | ``--locals`` 135 | List only .local 136 | 137 | ``--profiles`` 138 | List only .profile 139 | 140 | rm 141 | -- 142 | 143 | Remove profiles 144 | 145 | .. code-block:: sh 146 | 147 | fjp rm ... 148 | 149 | EXIT STATUS 150 | =========== 151 | 152 | | 0 if OK 153 | | 1 if Error 154 | | 100 if ``has`` could not find a profile 155 | 156 | ENVIRONMENT 157 | =========== 158 | 159 | EDITOR 160 | Respected by ``edit``. 161 | 162 | RUST_LOG 163 | Set log level, one of error, warn, info, debug or trace. 164 | 165 | RUST_LOG_STYLE 166 | Set log color: auto, always or never 167 | 168 | EXAMPLES 169 | ======== 170 | 171 | can be found at https://rusty-snake.github.io/fjp/#examples. 172 | 173 | REPORTING BUGS 174 | ============== 175 | 176 | Bugs can be reported at https://github.com/rusty-snake/fjp/issues 177 | and questions can be asked at https://github.com/rusty-snake/fjp/discussions. 178 | 179 | SEE ALSO 180 | ======== 181 | 182 | firejail-profiles(5) 183 | -------------------------------------------------------------------------------- /src/disable.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | use crate::{ 21 | fatal, 22 | location::Location, 23 | profile::{Profile, ProfileFlags}, 24 | utils::input, 25 | USER_PROFILE_DIR, 26 | }; 27 | use lazy_static::lazy_static; 28 | use log::{debug, error, info, warn}; 29 | use std::fs::{create_dir, rename}; 30 | use std::io::Result as IoResult; 31 | 32 | lazy_static! { 33 | pub static ref DISABLED_DIR: Location = { 34 | let mut path = USER_PROFILE_DIR.to_owned_inner(); 35 | path.push("disabled"); 36 | Location::from(path) 37 | }; 38 | } 39 | 40 | pub fn start(cli: &crate::cli::CliDisable) { 41 | debug!("subcommand: disable"); 42 | 43 | if cli.user { 44 | disable_user(); 45 | } else if cli.list { 46 | list().unwrap_or_else(|e| error!("An error occured while listing: {}", e)); 47 | } else { 48 | match create_dir(&*DISABLED_DIR) { 49 | Ok(()) => (), 50 | Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => (), 51 | Err(err) => fatal!("Failed to create the disabled dir: {}", err), 52 | } 53 | let profile = Profile::new( 54 | cli.profile_name.as_deref().unwrap(), 55 | ProfileFlags::LOOKUP_USER | ProfileFlags::DENY_BY_PATH, 56 | ) 57 | .unwrap(); 58 | disable_profile(&profile); 59 | } 60 | } 61 | 62 | fn disable_user() { 63 | let mut disabled_user_profile_dir = USER_PROFILE_DIR.to_owned_inner(); 64 | disabled_user_profile_dir.set_extension("disabled"); 65 | debug!( 66 | "disabled user profile dir: {}", 67 | disabled_user_profile_dir.to_string_lossy() 68 | ); 69 | rename(&*USER_PROFILE_DIR, &disabled_user_profile_dir) 70 | .unwrap_or_else(|e| error!("Rename failed: {}", e)); 71 | } 72 | 73 | fn list() -> IoResult<()> { 74 | for entry in DISABLED_DIR.get_ref().read_dir()? { 75 | println!("{}", entry?.file_name().to_string_lossy()); 76 | } 77 | 78 | Ok(()) 79 | } 80 | 81 | fn disable_profile(profile: &Profile<'_>) { 82 | let enabled_profile = if let Some(path) = profile.path() { 83 | path 84 | } else { 85 | error!( 86 | "Could not find '{}' in ~/.config/firejail", 87 | profile.full_name() 88 | ); 89 | return; 90 | }; 91 | 92 | let disabled_profile = DISABLED_DIR.get_profile_path(profile.full_name()); 93 | 94 | if disabled_profile.exists() { 95 | warn!("Profile '{}' is alread disabled.", profile.full_name()); 96 | if input("Override? [Y/n] ").unwrap() != "y" { 97 | info!("Skipping"); 98 | return; 99 | } 100 | } 101 | 102 | debug!( 103 | "Move '{}' to '{}'", 104 | enabled_profile.display(), 105 | disabled_profile.display() 106 | ); 107 | rename(enabled_profile, &disabled_profile).unwrap_or_else(|e| error!("Rename failed: {}", e)); 108 | } 109 | -------------------------------------------------------------------------------- /src/location.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | //! Module for dealing with the directories where profiles are stored 21 | 22 | #![allow(dead_code)] 23 | 24 | use std::convert::From; 25 | use std::fmt; 26 | use std::io::Result as IoResult; 27 | use std::path::{Path, PathBuf}; 28 | 29 | /// A directory where firejail-profiles are stored, such as `/etc/firejail/` 30 | /// 31 | /// # Examples 32 | /// 33 | /// ``` 34 | /// let system_l = Location::from("/etc/firejail/") 35 | /// let firefox_profile_path; 36 | /// if system.has_profile("firefox.profile") { 37 | /// firefox_profile_path = system_l.get_profile_path("firefox.profile"); 38 | /// } 39 | /// ``` 40 | #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] 41 | pub struct Location { 42 | inner: PathBuf, 43 | } 44 | 45 | impl Location { 46 | /// Get the path to profile named `name` in this location 47 | /// 48 | /// NOTE: This does not check if `name` exists. 49 | /// 50 | /// # Examples 51 | /// 52 | /// ``` 53 | /// assert_eq!( 54 | /// Location::from("/etc/firejail/").get_profile_path("firefox.profile"), 55 | /// PathBuf::from("/etc/firejail/firefox.profile"), 56 | /// ); 57 | /// ``` 58 | pub fn get_profile_path(&self, name: &str) -> PathBuf { 59 | let mut p = self.inner.to_path_buf(); 60 | p.push(name); 61 | p 62 | } 63 | 64 | /// Check if a file named `name` exists in this location 65 | pub fn has_profile(&self, name: &str) -> IoResult { 66 | for entry in self.inner.read_dir()? { 67 | if entry?.file_name() == name { 68 | return Ok(true); 69 | } 70 | } 71 | Ok(false) 72 | } 73 | 74 | pub fn get_ref(&self) -> &Path { 75 | &self.inner 76 | } 77 | 78 | /// Clone the inner PathBuf and return it 79 | pub fn to_owned_inner(&self) -> PathBuf { 80 | self.inner.to_path_buf() 81 | } 82 | } 83 | 84 | impl AsRef for Location { 85 | fn as_ref(&self) -> &Path { 86 | &self.inner 87 | } 88 | } 89 | 90 | impl> From for Location { 91 | fn from(p: T) -> Self { 92 | Self { inner: p.into() } 93 | } 94 | } 95 | 96 | impl fmt::Display for Location { 97 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { 98 | write!(f, "{}", self.inner.to_string_lossy()) 99 | } 100 | } 101 | 102 | #[cfg(test)] 103 | mod tests { 104 | use super::*; 105 | 106 | #[test] 107 | fn test_get_profile_path() { 108 | assert_eq!( 109 | Location::from("/").get_profile_path("MyProfile"), 110 | PathBuf::from("/MyProfile"), 111 | ); 112 | } 113 | 114 | #[test] 115 | fn test_get_ref() { 116 | assert_eq!(Location::from("/").get_ref(), Path::new("/")); 117 | } 118 | 119 | #[test] 120 | fn test_to_owned_inner() { 121 | assert_eq!(Location::from("/").to_owned_inner(), PathBuf::from("/")); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > **Warning**: This project is unmaintained, I will not work on it anymore. For [questions](https://github.com/rusty-snake/fjp/discussions) I will still be there. 2 | 3 | > **Warning**: There are known bugs that cause data loss ([#67](https://github.com/rusty-snake/fjp/issues/67)). Do not use. 4 | 5 | 6 | fjp – firejail-profile 7 | ====================== 8 | 9 | [![](https://github.com/rusty-snake/fjp/workflows/Rust%20CI/badge.svg)](https://github.com/rusty-snake/fjp/actions?query=workflow%3A%22Rust+CI%22+event%3Apush+branch%3Amaster) 10 | ![MSRV: 1.57](https://img.shields.io/badge/MSRV-1.57-blue.svg?logo=rust) 11 | [![license: GPL-3.0-or-later](https://img.shields.io/static/v1?label=license&message=GPL-3.0-or-later&color=darkred&logo=gnu)](COPYING) 12 | [![maintenance-status: obsolete (as of 2022-12-20)](https://img.shields.io/badge/maintenance--status-obsolete_%28as_of_2022--12--20%29-red)](https://gist.github.com/rusty-snake/574a91f1df9f97ec77ca308d6d731e29) 13 | 14 | A handy command line program to work fast and straightforward with firejail profiles. 15 | 16 | fjp is a command-line program written in rust, a modern and safe programming language. It allows you to show, edit, compare, disable or remove firejail profiles. And many more features like search, check, sed or merge will come. 17 | 18 | Get started 19 | ----------- 20 | 21 | ### Install prebuild binary 22 | 23 | ```bash 24 | wget -qO- "https://github.com/rusty-snake/fjp/releases/download/v0.3.0/fjp-v0.3.0-x86_64-unknown-linux-musl.tar.xz" | tar -xJf- -C $HOME/.local 25 | ``` 26 | 27 | Read https://rusty-snake.github.io/fjp/#download for more detailed information. 28 | 29 | ### Build from source 30 | 31 | 1. Install build dependencies 32 | ([rust](https://www.rust-lang.org/tools/install) and 33 | [meson](https://mesonbuild.com/Getting-meson.html)) 34 | 35 | | Distro | Command(s) | 36 | | ------ | ---------- | 37 | | Arch Linux | `sudo pacman -S rust meson` | 38 | | Debian | `sudo apt install cargo meson` (NOTE: debian stable has likely to old packages) | 39 | | Fedora | `sudo dnf install cargo meson` | 40 | | Other | `curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rustup-init.sh`
`bash rustup-init.sh --no-modify-path --profile minimal`
`pip3 install --user meson` | 41 | 42 | [docutils](https://pypi.org/project/docutils/) and [Pygments](https://pypi.org/project/Pygments/) are required too if you want to build the manpage. 43 | 44 | 2. Clone this repo 45 | 46 | ``` 47 | $ git clone "https://github.com/rusty-snake/fjp.git" 48 | $ cd fjp 49 | ``` 50 | 51 | 3. Build and Install 52 | 53 | ``` 54 | $ meson setup --buildtype=release _builddir 55 | $ meson configure _builddir -Dmanpage=true # Optional 56 | $ meson compile -C _builddir 57 | $ sudo meson install --no-rebuild -C _builddir 58 | ``` 59 | 60 | 4. Start using it 61 | 62 | ``` 63 | $ fjp --help 64 | ``` 65 | 66 | Examples 67 | -------- 68 | 69 | Open `~/.config/firejail/firefox.profile` in your editor. You will be asked to copy the profile from `/etc/firejail` if it does not exists yet: 70 | 71 | $ fjp edit firefox 72 | 73 | Open `~/.config/firejail/firefox.local` in your editor: 74 | 75 | $ fjp edit firefox.local 76 | 77 | Rename `~/.config/firejail` to `~/.config/firejail.disabled` in order to make firejail only using profiles from `/etc/firejail`. And revert it: 78 | 79 | $ fjp disable --user 80 | $ fjp enable --user 81 | 82 | Show firefox and all its includes. Actual firefox.local, globals.local, firefox.profile, firefox-common.local, firefox-common.profile 83 | 84 | $ fjp cat firefox 85 | 86 | See for more examples. 87 | 88 | FAQ 89 | --- 90 | 91 | #### 1. What does fjp stand for? 92 | 93 | firejail-profile, but fjp is faster to type. 94 | 95 | #### 2. How can I change the editor? 96 | 97 | fjp reads the `EDITOR` environment-varibale and use `/usr/bin/vim` as fallback. 98 | To use `nano` as editor, just call `EDITOR=nano fjp edit firefox`. In order to make this 99 | persistent, add `EDITOR=nano` to your `.bashrc`. 100 | 101 | #### 3. How can I change the log level? 102 | 103 | Set the environment-variable `RUST_LOG` to `trace`, `debug`, `info` (default), `warn` or `error`. 104 | Example: `$ RUST_LOG=debug fjp …` 105 | 106 | Changelog 107 | --------- 108 | 109 | [CHANGELOG.md](CHANGELOG.md) 110 | 111 | Contributing 112 | ------------ 113 | 114 | [CONTRIBUTING.md](CONTRIBUTING.md) 115 | 116 | License 117 | ------- 118 | 119 | [GPL-3.0-or-later](COPYING) 120 | -------------------------------------------------------------------------------- /src/diff.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | use crate::cli::CliDiffFormat; 21 | use crate::fatal; 22 | use crate::profile::{Profile, ProfileFlags}; 23 | use crate::profile_stream::ProfileStream; 24 | use crate::utils::ColoredText; 25 | use termcolor::Color; 26 | 27 | pub fn start(cli: &crate::cli::CliDiff) { 28 | let [(profile1, profile1_stream), (profile2, profile2_stream)] = read_and_parse(cli); 29 | 30 | match cli.format { 31 | CliDiffFormat::Color => { 32 | format_color(&profile1, &profile2, &profile1_stream, &profile2_stream); 33 | } 34 | CliDiffFormat::Simple => { 35 | format_simple(&profile1, &profile2, &profile1_stream, &profile2_stream); 36 | } 37 | } 38 | } 39 | 40 | fn read_and_parse(cli: &crate::cli::CliDiff) -> [(Profile<'_>, ProfileStream); 2] { 41 | let profile1_name = &cli.profile_name1; 42 | let profile2_name = &cli.profile_name2; 43 | 44 | let profile1 = Profile::new( 45 | profile1_name, 46 | ProfileFlags::default().with(ProfileFlags::READ), 47 | ) 48 | .unwrap_or_else(|err| fatal!("Failed to read {}: {}", profile1_name, err)); 49 | let profile2 = Profile::new( 50 | profile2_name, 51 | ProfileFlags::default().with(ProfileFlags::READ), 52 | ) 53 | .unwrap_or_else(|err| fatal!("Failed to read {}: {}", profile2_name, err)); 54 | 55 | let profile1_stream = profile1.raw_data().parse::().unwrap(); 56 | let profile2_stream = profile2.raw_data().parse::().unwrap(); 57 | 58 | [(profile1, profile1_stream), (profile2, profile2_stream)] 59 | } 60 | 61 | fn format_color( 62 | profile1: &Profile<'_>, 63 | profile2: &Profile<'_>, 64 | profile1_stream: &ProfileStream, 65 | profile2_stream: &ProfileStream, 66 | ) { 67 | println!( 68 | "{}\n{}\n{}\n{}", 69 | ColoredText::new( 70 | Color::Cyan, 71 | format!("{}:", profile1.path().unwrap().to_string_lossy()), 72 | ), 73 | profile1_stream 74 | .iter() 75 | .map(|l| if profile2_stream.contains(&l.content) { 76 | l.content.to_string() 77 | } else { 78 | ColoredText::new(Color::Green, l.content.to_string()).into_string() 79 | }) 80 | .collect::(), 81 | ColoredText::new( 82 | Color::Cyan, 83 | format!("{}:", profile2.path().unwrap().to_string_lossy()), 84 | ), 85 | profile2_stream 86 | .iter() 87 | .map(|l| if profile1_stream.contains(&l.content) { 88 | l.content.to_string() 89 | } else { 90 | ColoredText::new(Color::Green, l.content.to_string()).into_string() 91 | }) 92 | .collect::() 93 | ); 94 | } 95 | 96 | fn format_simple( 97 | profile1: &Profile<'_>, 98 | profile2: &Profile<'_>, 99 | profile1_stream: &ProfileStream, 100 | profile2_stream: &ProfileStream, 101 | ) { 102 | let profile1_unique = profile1_stream 103 | .iter() 104 | .filter(|l| !l.is_comment()) 105 | .filter(|l| !profile2_stream.contains(&l.content)) 106 | .cloned() 107 | .collect::(); 108 | let profile2_unique = profile2_stream 109 | .iter() 110 | .filter(|l| !l.is_comment()) 111 | .filter(|l| !profile1_stream.contains(&l.content)) 112 | .cloned() 113 | .collect::(); 114 | 115 | print!( 116 | "{}\n{}\n{}\n{}", 117 | ColoredText::new( 118 | Color::Cyan, 119 | format!( 120 | "The following commands are unique to {}:", 121 | profile1.full_name() 122 | ), 123 | ), 124 | profile1_unique, 125 | ColoredText::new( 126 | Color::Cyan, 127 | format!( 128 | "The following commands are unique to {}:", 129 | profile2.full_name() 130 | ), 131 | ), 132 | profile2_unique, 133 | ); 134 | } 135 | -------------------------------------------------------------------------------- /src/generate_standalone.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | use crate::{ 21 | fatal, 22 | profile::{Error as ProfileError, Profile, ProfileFlags}, 23 | }; 24 | use anyhow::{anyhow, ensure}; 25 | use bitflags::bitflags; 26 | use log::debug; 27 | use std::error::Error as StdError; 28 | use std::fs::File; 29 | use std::io::{stdout, BufWriter, Write as IoWrite}; 30 | 31 | bitflags! { 32 | struct Flags: u8 { 33 | const KEEP_INCS = 0b_0000_0001; 34 | const KEEP_LOCALS = 0b_0000_0010; 35 | } 36 | } 37 | 38 | #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] 39 | struct RecusionLevel(u8); 40 | impl RecusionLevel { 41 | pub const fn zero() -> Self { 42 | Self(0) 43 | } 44 | 45 | pub const fn max() -> Self { 46 | Self(16) 47 | } 48 | 49 | pub const fn incremented(current: Self) -> Self { 50 | Self(current.0 + 1) 51 | } 52 | } 53 | 54 | macro_rules! write_lined { 55 | ($src:expr, $dst:ident) => { 56 | $dst.write_all($src.as_bytes()).unwrap(); 57 | $dst.write_all(b"\n").unwrap(); 58 | }; 59 | } 60 | 61 | pub fn start(cli: &crate::cli::CliGenerateStandalone) { 62 | debug!("subcommand: generate-standalone"); 63 | 64 | let mut flags = Flags::empty(); 65 | if cli.keep_inc { 66 | flags.insert(Flags::KEEP_INCS); 67 | } 68 | if cli.keep_locals { 69 | flags.insert(Flags::KEEP_LOCALS); 70 | } 71 | 72 | let mut output: BufWriter> = 73 | BufWriter::new(cli.output_file.as_deref().map_or_else( 74 | || Box::new(stdout()) as Box, 75 | |file_name| { 76 | Box::new( 77 | File::create(file_name) 78 | .unwrap_or_else(|err| fatal!("Failed to create output file: {}", err)), 79 | ) 80 | }, 81 | )); 82 | 83 | let profile = Profile::new( 84 | &cli.profile_name, 85 | ProfileFlags::default().with(ProfileFlags::READ), 86 | ) 87 | .unwrap_or_else(|err| { 88 | if let ProfileError::ReadError { 89 | full_name, source, .. 90 | } = err 91 | { 92 | fatal!("Failed to read {}: {}", full_name, source) 93 | } 94 | unreachable!(); 95 | }); 96 | 97 | process(&profile, &mut output, RecusionLevel::zero(), flags) 98 | .unwrap_or_else(|err| fatal!("{}", err)); 99 | 100 | output.flush().unwrap(); 101 | } 102 | 103 | fn process( 104 | profile: &Profile<'_>, 105 | output: &mut dyn IoWrite, 106 | recusion_level: RecusionLevel, 107 | flags: Flags, 108 | ) -> anyhow::Result<()> { 109 | writeln!(output, "## Begin {} ##", profile.full_name()).unwrap(); 110 | for line in profile.raw_data().lines() { 111 | if let Some(other_profile) = line.strip_prefix("include ") { 112 | if (flags.contains(Flags::KEEP_INCS) && line.ends_with(".inc")) 113 | || (flags.contains(Flags::KEEP_LOCALS) && line.ends_with(".local")) 114 | { 115 | write_lined!(line, output); 116 | } else { 117 | ensure!( 118 | recusion_level <= RecusionLevel::max(), 119 | "To many include levels" 120 | ); 121 | 122 | match Profile::new( 123 | other_profile, 124 | ProfileFlags::default().with(ProfileFlags::READ), 125 | ) { 126 | Ok(profile) => process( 127 | &profile, 128 | output, 129 | RecusionLevel::incremented(recusion_level), 130 | flags, 131 | ), 132 | Err(err) if caused_by_no_path(&err) => Ok(()), 133 | Err(err) => Err(anyhow!("Failed to read '{}': {}", other_profile, err)), 134 | }?; 135 | } 136 | } else { 137 | write_lined!(line, output); 138 | } 139 | } 140 | writeln!(output, "## End {} ##", profile.full_name()).unwrap(); 141 | Ok(()) 142 | } 143 | 144 | fn caused_by_no_path(err: &(dyn StdError + 'static)) -> bool { 145 | if let Some(ProfileError::NoPath) = err.downcast_ref() { 146 | true 147 | } else if let Some(e) = err.source() { 148 | caused_by_no_path(e) 149 | } else { 150 | false 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/cli.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | use clap::{ArgEnum, Args, Parser, Subcommand}; 21 | 22 | #[derive(Debug, Parser)] 23 | #[clap(version, about)] 24 | pub struct Cli { 25 | #[clap(subcommand)] 26 | pub subcommand: Subcommands, 27 | } 28 | 29 | #[derive(Debug, Subcommand)] 30 | pub enum Subcommands { 31 | Cat(CliCat), 32 | Diff(CliDiff), 33 | Disable(CliDisable), 34 | Edit(CliEdit), 35 | Enable(CliEnable), 36 | GenerateStandalone(CliGenerateStandalone), 37 | Has(CliHas), 38 | List(CliList), 39 | Rm(CliRm), 40 | } 41 | 42 | #[derive(Debug, Args)] 43 | #[clap(about = "Show a profile, its .local and its redirect profile")] 44 | pub struct CliCat { 45 | #[clap(long, help = "Do not show .local files.")] 46 | pub no_locals: bool, 47 | #[clap(long, help = "Do not pipe output into a pager.")] 48 | pub no_pager: bool, 49 | #[clap(long, help = "Do not show redirect profiles.")] 50 | pub no_redirects: bool, 51 | #[clap(help = "The name of the profile to show.")] 52 | pub profile_name: String, 53 | } 54 | 55 | #[derive(Debug, Args)] 56 | #[clap(about = "Show the differences between two profiles")] 57 | pub struct CliDiff { 58 | #[clap( 59 | short, long, 60 | arg_enum, 61 | help = "specify the diff format", 62 | long_help = concat!( 63 | "specify the diff format\n", 64 | " color: highlight unique lines\n", 65 | " simple: show unique lines\n", 66 | ), 67 | )] 68 | pub format: CliDiffFormat, 69 | pub profile_name1: String, 70 | pub profile_name2: String, 71 | } 72 | 73 | #[derive(Debug, Clone, Copy, PartialEq, Eq, ArgEnum)] 74 | pub enum CliDiffFormat { 75 | Color, 76 | Simple, 77 | } 78 | 79 | #[derive(Debug, Args)] 80 | #[clap(about = "Disable profiles")] 81 | pub struct CliDisable { 82 | #[clap(short, long, exclusive = true, help = "List all disabled profiles")] 83 | pub list: bool, 84 | #[clap( 85 | short, 86 | long, 87 | exclusive = true, 88 | help = "Disable ~/.config/firejail", 89 | long_help = "Disable ~/.config/firejail by renaming it to firejail.disabled" 90 | )] 91 | pub user: bool, 92 | #[clap( 93 | required_unless_present_any = &["list", "user"], 94 | help = "The name of the profile to disable", 95 | )] 96 | pub profile_name: Option, 97 | } 98 | 99 | #[derive(Debug, Args)] 100 | #[clap(about = "Edit profiles")] 101 | pub struct CliEdit { 102 | #[clap( 103 | short, 104 | long, 105 | help = "Edit non-persistent", 106 | long_help = "Copy the profile if possible and discard all changes after editing." 107 | )] 108 | pub tmp: bool, 109 | #[clap( 110 | help = "The name of the profile to edit.", 111 | long_help = concat!( 112 | "The name of the profile to edit. If the profile does not exists,", 113 | "it is create except it is found in /etc/firejail, then it is copied from there.", 114 | ), 115 | )] 116 | pub profile_name: String, 117 | } 118 | 119 | #[derive(Debug, Args)] 120 | #[clap(about = "Enable profiles")] 121 | pub struct CliEnable { 122 | #[clap(short, long, exclusive = true, help = "Enable ~/.config/firejail")] 123 | pub user: bool, 124 | #[clap( 125 | required_unless_present = "user", 126 | help = "The name of the profile to enable" 127 | )] 128 | pub profile_name: Option, 129 | } 130 | 131 | #[derive(Debug, Args)] 132 | #[clap(about = "Copy the profile and all its includes into one file.")] 133 | pub struct CliGenerateStandalone { 134 | #[clap(long, help = "Keep all includes of .inc's")] 135 | pub keep_inc: bool, 136 | #[clap(long, help = "Keep all includes of .local's")] 137 | pub keep_locals: bool, 138 | #[clap(short, long, help = "The name of the file to write results")] 139 | pub output_file: Option, 140 | #[clap(help = "The name of the profile to generate a standalone version.")] 141 | pub profile_name: String, 142 | } 143 | 144 | #[derive(Debug, Args)] 145 | #[clap(about = "Look if a profile exists")] 146 | pub struct CliHas { 147 | #[clap(help = "The name of the program to look for a profile.")] 148 | pub profile_name: String, 149 | } 150 | 151 | #[derive(Debug, Args)] 152 | #[clap(about = "List all user profile")] 153 | pub struct CliList { 154 | #[clap( 155 | long, 156 | conflicts_with_all = &["locals", "profiles"], 157 | help = "List only .inc", 158 | )] 159 | pub incs: bool, 160 | #[clap( 161 | long, 162 | conflicts_with_all = &["incs", "profiles"], 163 | help = "List only .local", 164 | )] 165 | pub locals: bool, 166 | #[clap( 167 | long, 168 | conflicts_with_all = &["incs", "locals"], 169 | help = "List only .profile", 170 | )] 171 | pub profiles: bool, 172 | } 173 | 174 | #[derive(Debug, Args)] 175 | #[clap(about = "Remove profiles")] 176 | pub struct CliRm { 177 | #[clap(required = true, help = "The names of the profiles to delete.")] 178 | pub profile_names: Vec, 179 | } 180 | -------------------------------------------------------------------------------- /src/cat.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | use crate::profile::{Profile, ProfileFlags}; 21 | use crate::{fatal, utils::ColoredText}; 22 | use log::{debug, error, warn}; 23 | use nix::sys::signal::{kill, Signal::SIGTERM}; 24 | use nix::unistd::Pid; 25 | use std::convert::TryInto; 26 | use std::io; 27 | use std::process::{Child, Command, Stdio}; 28 | use termcolor::Color; 29 | 30 | #[derive(Debug, Default)] 31 | struct Options { 32 | show_locals: bool, 33 | show_redirects: bool, 34 | } 35 | 36 | pub fn start(cli: &crate::cli::CliCat) { 37 | debug!("subcommand: cat"); 38 | 39 | let cmd: &[&str] = if cli.no_pager { 40 | &["cat"] 41 | } else { 42 | &["less", "-R"] 43 | }; 44 | 45 | let mut child: Option = Command::new(cmd[0]) 46 | .args(&cmd[1..]) 47 | .stdin(Stdio::piped()) 48 | .stderr(Stdio::null()) 49 | .spawn() 50 | .map_or_else( 51 | |err| { 52 | warn!("Failed to start {}: {}", cmd[0], err); 53 | warn!("Continue without it."); 54 | None 55 | }, 56 | Some, 57 | ); 58 | 59 | let opts = Options { 60 | show_locals: !cli.no_locals, 61 | show_redirects: !cli.no_redirects, 62 | }; 63 | let name = &cli.profile_name; 64 | let profile_flags = ProfileFlags::default().with(ProfileFlags::READ); 65 | 66 | match Profile::new(name, profile_flags) { 67 | Ok(p) => { 68 | let mut output: Box = if let Some(ref mut child) = child { 69 | Box::new(child.stdin.as_mut().unwrap()) 70 | } else { 71 | Box::new(io::stdout()) 72 | }; 73 | process(&p, p.raw_data(), &opts, &mut output, 0); 74 | } 75 | Err(e) => { 76 | if let Some(ref child) = child { 77 | kill(Pid::from_raw(child.id().try_into().unwrap()), SIGTERM).unwrap(); 78 | } 79 | error!("Couldn't Read Profile. {}", e); 80 | } 81 | }; 82 | 83 | if let Some(ref mut child) = child { 84 | child.wait().unwrap(); 85 | } 86 | } 87 | 88 | fn process( 89 | profile: &Profile<'_>, 90 | content: &str, 91 | opts: &Options, 92 | output: &mut W, 93 | mut depth: u8, 94 | ) { 95 | if depth >= 16 { 96 | fatal!("To many include levels"); 97 | } 98 | depth += 1; 99 | 100 | let [locals, profiles] = parse(content); 101 | 102 | if opts.show_locals { 103 | if let Some(locals) = locals { 104 | show_locals(&locals, opts, output); 105 | } 106 | } 107 | 108 | show_file(profile, content, output); 109 | 110 | if opts.show_redirects { 111 | if let Some(profiles) = profiles { 112 | show_profiles(&profiles, opts, output, depth); 113 | } 114 | } 115 | } 116 | 117 | fn parse(content: &str) -> [Option>; 2] { 118 | let mut local = Vec::new(); 119 | let mut profile = Vec::new(); 120 | 121 | for line in content.lines() { 122 | if let Some(other_profile) = line.strip_prefix("include ") { 123 | if other_profile.ends_with(".local") { 124 | local.push(other_profile.to_string()); 125 | } else if other_profile.ends_with(".profile") { 126 | profile.push(other_profile.to_string()); 127 | } 128 | } 129 | } 130 | 131 | [ 132 | if local.is_empty() { None } else { Some(local) }, 133 | if profile.is_empty() { 134 | None 135 | } else { 136 | Some(profile) 137 | }, 138 | ] 139 | } 140 | 141 | fn show_file(profile: &Profile<'_>, content: &str, output: &mut W) { 142 | output 143 | .write_all( 144 | ColoredText::new( 145 | Color::Blue, 146 | &format!("# {}:\n", profile.path().unwrap().to_string_lossy()), 147 | ) 148 | .as_bytes(), 149 | ) 150 | .unwrap(); 151 | output.write_all(content.as_bytes()).unwrap(); 152 | } 153 | 154 | fn show_locals(locals: &[String], _opts: &Options, output: &mut W) { 155 | locals 156 | .iter() 157 | .filter(|&name| { 158 | name != "globals.local" && name != "pre-globals.local" && name != "post-globals.local" 159 | }) 160 | .filter_map(|name| { 161 | Profile::new(name, ProfileFlags::default().with(ProfileFlags::READ)).ok() 162 | }) 163 | .for_each(|profile| { 164 | show_file(&profile, profile.raw_data(), output); 165 | }); 166 | } 167 | 168 | fn show_profiles(profiles: &[String], opts: &Options, output: &mut W, depth: u8) { 169 | for name in profiles { 170 | let profile_flags = ProfileFlags::default().with(ProfileFlags::READ); 171 | match Profile::new(name, profile_flags) { 172 | Ok(p) => { 173 | process(&p, p.raw_data(), opts, output, depth); 174 | } 175 | Err(e) => { 176 | error!("Couldn't Read profile. {}", e); 177 | } 178 | }; 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/edit.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | #![allow(clippy::unreadable_literal)] // bitflags are easier to read without underscores!! 21 | 22 | use crate::fatal; 23 | use crate::profile::{Profile, ProfileFlags}; 24 | use crate::utils::input; 25 | use bitflags::bitflags; 26 | use log::{debug, warn}; 27 | use std::env::var_os; 28 | use std::ffi::OsString; 29 | use std::fs::{copy as copy_file, remove_file, rename}; 30 | use std::path::Path; 31 | use std::process::Command; 32 | 33 | bitflags! { 34 | struct Flags: u8 { 35 | const NULL = 0b00000000; 36 | const COPY = 0b00000001; 37 | const TMP = 0b00000100; 38 | } 39 | } 40 | 41 | pub fn start(cli: &crate::cli::CliEdit) { 42 | debug!("subcommand: edit"); 43 | 44 | let mut flags = Flags::empty(); 45 | if cli.tmp { 46 | flags.insert(Flags::TMP | Flags::COPY); 47 | } 48 | 49 | debug!("profile name: {}", cli.profile_name); 50 | 51 | let user_profile = Profile::new( 52 | &cli.profile_name, 53 | ProfileFlags::LOOKUP_USER | ProfileFlags::DENY_BY_PATH | ProfileFlags::ASSUME_EXISTENCE, 54 | ) 55 | .unwrap() 56 | .into_pathbuf(); 57 | 58 | let system_profile = Profile::new( 59 | &cli.profile_name, 60 | ProfileFlags::LOOKUP_SYSTEM | ProfileFlags::DENY_BY_PATH | ProfileFlags::ASSUME_EXISTENCE, 61 | ) 62 | .unwrap() 63 | .into_pathbuf(); 64 | 65 | if flags.contains(Flags::TMP) { 66 | prepare_tmp_edit(&user_profile, &system_profile, flags); 67 | } else { 68 | prepare_edit(&user_profile, &system_profile, flags); 69 | } 70 | } 71 | 72 | fn prepare_tmp_edit(user_profile: &Path, system_profile: &Path, flags: Flags) { 73 | if user_profile.exists() { 74 | let backup_profile = user_profile.with_extension("bak"); 75 | 76 | debug!( 77 | "Copy '{}' to '{}'.", 78 | user_profile.display(), 79 | backup_profile.display() 80 | ); 81 | copy_file(user_profile, &backup_profile).unwrap_or_else(|err| { 82 | fatal!( 83 | "Failed to create backup of {}: {}", 84 | user_profile.file_name().unwrap().to_string_lossy(), 85 | err 86 | ) 87 | }); 88 | 89 | prepare_edit(user_profile, system_profile, flags); 90 | 91 | debug!( 92 | "Move '{}' back to '{}'.", 93 | backup_profile.display(), 94 | user_profile.display() 95 | ); 96 | rename(&backup_profile, user_profile).unwrap_or_else(|err| { 97 | fatal!( 98 | "Failed to restore {}: {}", 99 | user_profile.file_name().unwrap().to_string_lossy(), 100 | err 101 | ) 102 | }); 103 | } else { 104 | prepare_edit(user_profile, system_profile, flags); 105 | 106 | debug!("Remove '{}'.", user_profile.display()); 107 | remove_file(user_profile) 108 | .unwrap_or_else(|err| fatal!("Failed to remove '{}': {}", user_profile.display(), err)); 109 | } 110 | } 111 | 112 | fn prepare_edit(user_profile: &Path, system_profile: &Path, flags: Flags) { 113 | let copy_system_profile_to_user_profile = || { 114 | debug!( 115 | "Copy '{}' to '{}'.", 116 | system_profile.display(), 117 | user_profile.display(), 118 | ); 119 | copy_file(system_profile, user_profile).unwrap_or_else(|err| { 120 | fatal!( 121 | "Failed to copy '{}' to '{}': {}", 122 | system_profile.display(), 123 | user_profile.display(), 124 | err 125 | ) 126 | }); 127 | }; 128 | 129 | if system_profile.exists() && (flags.contains(Flags::TMP) || !user_profile.exists()) { 130 | if flags.contains(Flags::COPY) { 131 | copy_system_profile_to_user_profile(); 132 | } else { 133 | match input("Should the profile be copied? [(y)es/(n)o/(a)bort] ") 134 | .unwrap() 135 | .to_lowercase() 136 | .as_str() 137 | { 138 | "y" => copy_system_profile_to_user_profile(), 139 | "n" => (), 140 | "a" => return, 141 | _ => println!("Invalid answer, continue without copying."), 142 | } 143 | } 144 | } 145 | 146 | open_user_profile(user_profile); 147 | } 148 | 149 | fn open_user_profile(profile: &Path) { 150 | let editor = var_os("EDITOR").unwrap_or_else(|| { 151 | warn!("$EDITOR not set or empty, using \"vim\" as fallback."); 152 | OsString::from("vim") 153 | }); 154 | 155 | debug!( 156 | "Open '{}' with {}.", 157 | profile.display(), 158 | editor.to_string_lossy() 159 | ); 160 | let exit_code = Command::new(&editor) 161 | .arg(profile) 162 | .status() 163 | .unwrap_or_else(|err| fatal!("Failed to start {}: {}", editor.to_string_lossy(), err)); 164 | if !exit_code.success() { 165 | warn!( 166 | "{} exited with exit code {}", 167 | editor.to_string_lossy(), 168 | exit_code 169 | .code() 170 | .map_or("unknow".to_string(), |c| c.to_string()) 171 | ); 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | //! Module for various helper functions, macros, types, traits, ... 21 | 22 | #![allow(dead_code)] // This module acts more like a library, so not yet used is ok. 23 | 24 | use log::debug; 25 | use nix::unistd; 26 | use std::fmt; 27 | use std::io; 28 | use std::io::prelude::*; 29 | use std::path; 30 | 31 | /// Call `error!` from the log crate and exit with exit-code 1 afterwards. 32 | #[macro_export] 33 | macro_rules! fatal { 34 | (target: $target:expr, $($arg:tt)+) => {{ 35 | ::log::error!(target: $target, $($arg)+); 36 | std::process::exit(1); 37 | }}; 38 | ($($arg:tt)+) => {{ 39 | ::log::error!($($arg)+); 40 | std::process::exit(1); 41 | }}; 42 | } 43 | 44 | /// Python like `input()`. 45 | pub fn input(prompt: &str) -> io::Result { 46 | let mut stdout = io::stdout(); 47 | stdout.write_all(prompt.as_bytes())?; 48 | stdout.flush()?; 49 | 50 | let mut buf = String::new(); 51 | io::stdin().read_line(&mut buf)?; 52 | 53 | Ok(buf.trim().to_string()) 54 | } 55 | 56 | #[allow(clippy::crate_in_macro_def)] 57 | #[macro_export] 58 | macro_rules! profile_path { 59 | (USER/$name:expr) => {{ 60 | let mut profile_p = crate::USER_PROFILE_DIR.to_owned_inner(); 61 | profile_p.push($name); 62 | profile_p 63 | }}; 64 | (SYSTEM/$name:expr) => {{ 65 | let mut profile_p = crate::SYSTEM_PROFILE_DIR.to_owned_inner(); 66 | profile_p.push($name); 67 | profile_p 68 | }}; 69 | } 70 | 71 | /// Return the path to profile `name` or None if it is not found. 72 | /// 73 | /// It will first look under `USER_PROFILE_DIR` and if it is not found there, 74 | /// then under `SYSTEM_PROFILE_DIR`. 75 | /// 76 | /// `find_profile`, `profile_path!` and `get_name1` are considered soft-deprecated. 77 | /// Use `profile::Profile::*` instead. 78 | pub fn find_profile(name: &str) -> Option { 79 | // Try user profile. 80 | let profile = profile_path!(USER / name); 81 | if profile.exists() { 82 | debug!( 83 | target: "fjp::utils::find_profile", 84 | "Profile '{}' found at {}.", 85 | name, 86 | profile.to_string_lossy(), 87 | ); 88 | return Some(profile); 89 | } 90 | 91 | // Try system profile. 92 | let profile = profile_path!(SYSTEM / name); 93 | if profile.exists() { 94 | debug!( 95 | target: "fjp::utils::find_profile", 96 | "Profile '{}' found at {}.", 97 | name, 98 | profile.to_string_lossy(), 99 | ); 100 | return Some(profile); 101 | } 102 | 103 | debug!(target: "fjp::utils::find_profile", "Could not find profile {}.", name); 104 | None 105 | } 106 | 107 | pub fn get_name1(raw: &str) -> String { 108 | if raw.contains("..") { 109 | panic!("'..' is not allowed inside a profile name."); 110 | } 111 | if raw.ends_with(".inc") || raw.ends_with(".local") || raw.ends_with(".profile") { 112 | raw.to_string() 113 | } else { 114 | raw.to_string() + ".profile" 115 | } 116 | } 117 | 118 | /// Gets the current User's Directory 119 | /// return `Option` 120 | /// Uses getpwuid_r to get User directory. 121 | pub fn home_dir() -> Option { 122 | use unistd::{Uid, User}; 123 | let user = User::from_uid(Uid::current()).unwrap().unwrap(); 124 | if user.dir.as_os_str().is_empty() { 125 | None 126 | } else { 127 | Some(user.dir) 128 | } 129 | } 130 | 131 | /// Flatten a iterable into a String, 132 | /// placing the string representaion of `sep` between. 133 | /// 134 | /// # Examples 135 | /// 136 | /// ``` 137 | /// assert_eq!( 138 | /// join(",", vec![1, 2, 3]), 139 | /// "1,2,3", 140 | /// ); 141 | /// assert_eq!( 142 | /// join('-', &["foo", "bar"]), 143 | /// "foo-bar", 144 | /// ); 145 | /// ``` 146 | pub fn join(sep: T, iterable: I) -> String 147 | where 148 | T: ToString, 149 | U: ToString, 150 | I: IntoIterator, 151 | { 152 | let sep = sep.to_string(); 153 | let mut iterable = iterable.into_iter(); 154 | 155 | if let Some(first_item) = iterable.next() { 156 | iterable.fold(first_item.to_string(), |acc, item| { 157 | acc + &sep + &item.to_string() 158 | }) 159 | } else { 160 | String::new() 161 | } 162 | } 163 | 164 | // 165 | // ColoredText 166 | // 167 | 168 | /// A colored string 169 | /// 170 | /// `termcolor` does not support simple coloring of string like `ansi_term` with 171 | /// `Red.paint("Hello")` or `colored` with `"Hello".green()` does. 172 | /// Instead you must manually write `set_color`, `write`, `reset`. 173 | /// This type tries to fixes this. 174 | #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] 175 | pub struct ColoredText { 176 | inner: String, 177 | } 178 | impl ColoredText { 179 | /// Create a new `ColoredText` instances 180 | pub fn new(color: termcolor::Color, text: impl AsRef) -> Self { 181 | use termcolor::{Buffer, ColorSpec, WriteColor}; 182 | 183 | let mut buffer = Buffer::ansi(); 184 | buffer 185 | .set_color(ColorSpec::new().set_fg(Some(color))) 186 | .unwrap(); 187 | buffer.write_all(text.as_ref().as_bytes()).unwrap(); 188 | buffer.reset().unwrap(); 189 | 190 | Self { 191 | inner: String::from_utf8_lossy(buffer.as_slice()).into_owned(), 192 | } 193 | } 194 | 195 | /// Get a references to the underlying String 196 | pub fn get_ref(&self) -> &String { 197 | &self.inner 198 | } 199 | 200 | /// Get a mutable references to the underlying String 201 | /// 202 | /// **Warning:** Be care full when editing this String, at the begin and end are 203 | /// ANSI-escape sequences. If you edit them, you might get ugly output. 204 | /// 205 | pub fn get_mut(&mut self) -> &mut String { 206 | &mut self.inner 207 | } 208 | 209 | pub fn as_bytes(&self) -> &[u8] { 210 | self.inner.as_bytes() 211 | } 212 | 213 | pub fn as_str(&self) -> &str { 214 | self.inner.as_str() 215 | } 216 | 217 | pub fn into_bytes(self) -> Vec { 218 | self.inner.into_bytes() 219 | } 220 | 221 | pub fn into_string(self) -> String { 222 | self.inner 223 | } 224 | } 225 | impl fmt::Display for ColoredText { 226 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 227 | fmt::Display::fmt(&self.inner, f) 228 | } 229 | } 230 | impl AsRef<[u8]> for ColoredText { 231 | fn as_ref(&self) -> &[u8] { 232 | self.inner.as_bytes() 233 | } 234 | } 235 | impl AsRef for ColoredText { 236 | fn as_ref(&self) -> &str { 237 | self.inner.as_str() 238 | } 239 | } 240 | 241 | #[cfg(test)] 242 | mod tests { 243 | use super::*; 244 | #[test] 245 | fn test_home_dir() { 246 | use unistd::{Uid, User}; 247 | assert_eq!( 248 | home_dir(), 249 | Some(User::from_uid(Uid::current()).unwrap().unwrap().dir) 250 | ); 251 | } 252 | #[test] 253 | fn test_home_dir_user_without_dir() { 254 | // Emulate a user without home dir e.g postgres 255 | // For next Pull request. 256 | assert_ne!(home_dir(), None); 257 | } 258 | #[test] 259 | fn test_get_name1() { 260 | assert_eq!(get_name1("firefox"), "firefox.profile"); 261 | assert_eq!(get_name1("firefox.profile"), "firefox.profile"); 262 | assert_eq!(get_name1("firefox.local"), "firefox.local"); 263 | assert_eq!(get_name1("firefox.inc"), "firefox.inc"); 264 | // Should not happen in real because PROFILE_NAME is required on the subcommands 265 | assert_eq!(get_name1(""), ".profile"); 266 | } 267 | 268 | #[test] 269 | #[should_panic(expected = "'..' is not allowed inside a profile name.")] 270 | fn test_get_name1_dotdot_in_name() { 271 | get_name1("./../forbidden"); 272 | } 273 | } 274 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "addr2line" 7 | version = "0.17.0" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" 10 | dependencies = [ 11 | "gimli", 12 | ] 13 | 14 | [[package]] 15 | name = "adler" 16 | version = "1.0.2" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" 19 | 20 | [[package]] 21 | name = "anyhow" 22 | version = "1.0.66" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "216261ddc8289130e551ddcd5ce8a064710c0d064a4d2895c67151c92b5443f6" 25 | 26 | [[package]] 27 | name = "atty" 28 | version = "0.2.14" 29 | source = "registry+https://github.com/rust-lang/crates.io-index" 30 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 31 | dependencies = [ 32 | "hermit-abi", 33 | "libc", 34 | "winapi", 35 | ] 36 | 37 | [[package]] 38 | name = "autocfg" 39 | version = "1.1.0" 40 | source = "registry+https://github.com/rust-lang/crates.io-index" 41 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 42 | 43 | [[package]] 44 | name = "backtrace" 45 | version = "0.3.66" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | checksum = "cab84319d616cfb654d03394f38ab7e6f0919e181b1b57e1fd15e7fb4077d9a7" 48 | dependencies = [ 49 | "addr2line", 50 | "cc", 51 | "cfg-if", 52 | "libc", 53 | "miniz_oxide", 54 | "object", 55 | "rustc-demangle", 56 | ] 57 | 58 | [[package]] 59 | name = "bitflags" 60 | version = "1.3.2" 61 | source = "registry+https://github.com/rust-lang/crates.io-index" 62 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 63 | 64 | [[package]] 65 | name = "cc" 66 | version = "1.0.77" 67 | source = "registry+https://github.com/rust-lang/crates.io-index" 68 | checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4" 69 | 70 | [[package]] 71 | name = "cfg-if" 72 | version = "1.0.0" 73 | source = "registry+https://github.com/rust-lang/crates.io-index" 74 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 75 | 76 | [[package]] 77 | name = "clap" 78 | version = "3.2.23" 79 | source = "registry+https://github.com/rust-lang/crates.io-index" 80 | checksum = "71655c45cb9845d3270c9d6df84ebe72b4dad3c2ba3f7023ad47c144e4e473a5" 81 | dependencies = [ 82 | "atty", 83 | "bitflags", 84 | "clap_derive", 85 | "clap_lex", 86 | "indexmap", 87 | "once_cell", 88 | "strsim", 89 | "termcolor", 90 | "terminal_size", 91 | "textwrap", 92 | ] 93 | 94 | [[package]] 95 | name = "clap_complete" 96 | version = "3.2.5" 97 | source = "registry+https://github.com/rust-lang/crates.io-index" 98 | checksum = "3f7a2e0a962c45ce25afce14220bc24f9dade0a1787f185cecf96bfba7847cd8" 99 | dependencies = [ 100 | "clap", 101 | ] 102 | 103 | [[package]] 104 | name = "clap_derive" 105 | version = "3.2.18" 106 | source = "registry+https://github.com/rust-lang/crates.io-index" 107 | checksum = "ea0c8bce528c4be4da13ea6fead8965e95b6073585a2f05204bd8f4119f82a65" 108 | dependencies = [ 109 | "heck", 110 | "proc-macro-error", 111 | "proc-macro2", 112 | "quote", 113 | "syn", 114 | ] 115 | 116 | [[package]] 117 | name = "clap_lex" 118 | version = "0.2.4" 119 | source = "registry+https://github.com/rust-lang/crates.io-index" 120 | checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5" 121 | dependencies = [ 122 | "os_str_bytes", 123 | ] 124 | 125 | [[package]] 126 | name = "color-backtrace" 127 | version = "0.5.1" 128 | source = "registry+https://github.com/rust-lang/crates.io-index" 129 | checksum = "cd6c04463c99389fff045d2b90ce84f5131332712c7ffbede020f5e9ad1ed685" 130 | dependencies = [ 131 | "atty", 132 | "backtrace", 133 | "termcolor", 134 | ] 135 | 136 | [[package]] 137 | name = "env_logger" 138 | version = "0.9.3" 139 | source = "registry+https://github.com/rust-lang/crates.io-index" 140 | checksum = "a12e6657c4c97ebab115a42dcee77225f7f482cdd841cf7088c657a42e9e00e7" 141 | dependencies = [ 142 | "atty", 143 | "log", 144 | "termcolor", 145 | ] 146 | 147 | [[package]] 148 | name = "errno" 149 | version = "0.2.8" 150 | source = "registry+https://github.com/rust-lang/crates.io-index" 151 | checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1" 152 | dependencies = [ 153 | "errno-dragonfly", 154 | "libc", 155 | "winapi", 156 | ] 157 | 158 | [[package]] 159 | name = "errno-dragonfly" 160 | version = "0.1.2" 161 | source = "registry+https://github.com/rust-lang/crates.io-index" 162 | checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" 163 | dependencies = [ 164 | "cc", 165 | "libc", 166 | ] 167 | 168 | [[package]] 169 | name = "fjp" 170 | version = "0.4.0-dev" 171 | dependencies = [ 172 | "anyhow", 173 | "bitflags", 174 | "clap", 175 | "clap_complete", 176 | "color-backtrace", 177 | "env_logger", 178 | "lazy_static", 179 | "libc", 180 | "log", 181 | "macros", 182 | "nix", 183 | "termcolor", 184 | "thiserror", 185 | ] 186 | 187 | [[package]] 188 | name = "gimli" 189 | version = "0.26.2" 190 | source = "registry+https://github.com/rust-lang/crates.io-index" 191 | checksum = "22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d" 192 | 193 | [[package]] 194 | name = "hashbrown" 195 | version = "0.12.3" 196 | source = "registry+https://github.com/rust-lang/crates.io-index" 197 | checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" 198 | 199 | [[package]] 200 | name = "heck" 201 | version = "0.4.0" 202 | source = "registry+https://github.com/rust-lang/crates.io-index" 203 | checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" 204 | 205 | [[package]] 206 | name = "hermit-abi" 207 | version = "0.1.19" 208 | source = "registry+https://github.com/rust-lang/crates.io-index" 209 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 210 | dependencies = [ 211 | "libc", 212 | ] 213 | 214 | [[package]] 215 | name = "indexmap" 216 | version = "1.9.2" 217 | source = "registry+https://github.com/rust-lang/crates.io-index" 218 | checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399" 219 | dependencies = [ 220 | "autocfg", 221 | "hashbrown", 222 | ] 223 | 224 | [[package]] 225 | name = "io-lifetimes" 226 | version = "0.7.5" 227 | source = "registry+https://github.com/rust-lang/crates.io-index" 228 | checksum = "59ce5ef949d49ee85593fc4d3f3f95ad61657076395cbbce23e2121fc5542074" 229 | 230 | [[package]] 231 | name = "lazy_static" 232 | version = "1.4.0" 233 | source = "registry+https://github.com/rust-lang/crates.io-index" 234 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 235 | 236 | [[package]] 237 | name = "libc" 238 | version = "0.2.137" 239 | source = "registry+https://github.com/rust-lang/crates.io-index" 240 | checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" 241 | 242 | [[package]] 243 | name = "linux-raw-sys" 244 | version = "0.0.46" 245 | source = "registry+https://github.com/rust-lang/crates.io-index" 246 | checksum = "d4d2456c373231a208ad294c33dc5bff30051eafd954cd4caae83a712b12854d" 247 | 248 | [[package]] 249 | name = "log" 250 | version = "0.4.17" 251 | source = "registry+https://github.com/rust-lang/crates.io-index" 252 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" 253 | dependencies = [ 254 | "cfg-if", 255 | ] 256 | 257 | [[package]] 258 | name = "macros" 259 | version = "0.4.0-dev" 260 | dependencies = [ 261 | "proc-macro2", 262 | "quote", 263 | "syn", 264 | ] 265 | 266 | [[package]] 267 | name = "memchr" 268 | version = "2.5.0" 269 | source = "registry+https://github.com/rust-lang/crates.io-index" 270 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" 271 | 272 | [[package]] 273 | name = "memoffset" 274 | version = "0.6.5" 275 | source = "registry+https://github.com/rust-lang/crates.io-index" 276 | checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" 277 | dependencies = [ 278 | "autocfg", 279 | ] 280 | 281 | [[package]] 282 | name = "miniz_oxide" 283 | version = "0.5.4" 284 | source = "registry+https://github.com/rust-lang/crates.io-index" 285 | checksum = "96590ba8f175222643a85693f33d26e9c8a015f599c216509b1a6894af675d34" 286 | dependencies = [ 287 | "adler", 288 | ] 289 | 290 | [[package]] 291 | name = "nix" 292 | version = "0.25.0" 293 | source = "registry+https://github.com/rust-lang/crates.io-index" 294 | checksum = "e322c04a9e3440c327fca7b6c8a63e6890a32fa2ad689db972425f07e0d22abb" 295 | dependencies = [ 296 | "autocfg", 297 | "bitflags", 298 | "cfg-if", 299 | "libc", 300 | "memoffset", 301 | "pin-utils", 302 | ] 303 | 304 | [[package]] 305 | name = "object" 306 | version = "0.29.0" 307 | source = "registry+https://github.com/rust-lang/crates.io-index" 308 | checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53" 309 | dependencies = [ 310 | "memchr", 311 | ] 312 | 313 | [[package]] 314 | name = "once_cell" 315 | version = "1.16.0" 316 | source = "registry+https://github.com/rust-lang/crates.io-index" 317 | checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" 318 | 319 | [[package]] 320 | name = "os_str_bytes" 321 | version = "6.4.1" 322 | source = "registry+https://github.com/rust-lang/crates.io-index" 323 | checksum = "9b7820b9daea5457c9f21c69448905d723fbd21136ccf521748f23fd49e723ee" 324 | 325 | [[package]] 326 | name = "pin-utils" 327 | version = "0.1.0" 328 | source = "registry+https://github.com/rust-lang/crates.io-index" 329 | checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" 330 | 331 | [[package]] 332 | name = "proc-macro-error" 333 | version = "1.0.4" 334 | source = "registry+https://github.com/rust-lang/crates.io-index" 335 | checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" 336 | dependencies = [ 337 | "proc-macro-error-attr", 338 | "proc-macro2", 339 | "quote", 340 | "syn", 341 | "version_check", 342 | ] 343 | 344 | [[package]] 345 | name = "proc-macro-error-attr" 346 | version = "1.0.4" 347 | source = "registry+https://github.com/rust-lang/crates.io-index" 348 | checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" 349 | dependencies = [ 350 | "proc-macro2", 351 | "quote", 352 | "version_check", 353 | ] 354 | 355 | [[package]] 356 | name = "proc-macro2" 357 | version = "1.0.47" 358 | source = "registry+https://github.com/rust-lang/crates.io-index" 359 | checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" 360 | dependencies = [ 361 | "unicode-ident", 362 | ] 363 | 364 | [[package]] 365 | name = "quote" 366 | version = "1.0.21" 367 | source = "registry+https://github.com/rust-lang/crates.io-index" 368 | checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" 369 | dependencies = [ 370 | "proc-macro2", 371 | ] 372 | 373 | [[package]] 374 | name = "rustc-demangle" 375 | version = "0.1.21" 376 | source = "registry+https://github.com/rust-lang/crates.io-index" 377 | checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" 378 | 379 | [[package]] 380 | name = "rustix" 381 | version = "0.35.13" 382 | source = "registry+https://github.com/rust-lang/crates.io-index" 383 | checksum = "727a1a6d65f786ec22df8a81ca3121107f235970dc1705ed681d3e6e8b9cd5f9" 384 | dependencies = [ 385 | "bitflags", 386 | "errno", 387 | "io-lifetimes", 388 | "libc", 389 | "linux-raw-sys", 390 | "windows-sys", 391 | ] 392 | 393 | [[package]] 394 | name = "strsim" 395 | version = "0.10.0" 396 | source = "registry+https://github.com/rust-lang/crates.io-index" 397 | checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" 398 | 399 | [[package]] 400 | name = "syn" 401 | version = "1.0.103" 402 | source = "registry+https://github.com/rust-lang/crates.io-index" 403 | checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" 404 | dependencies = [ 405 | "proc-macro2", 406 | "quote", 407 | "unicode-ident", 408 | ] 409 | 410 | [[package]] 411 | name = "termcolor" 412 | version = "1.1.3" 413 | source = "registry+https://github.com/rust-lang/crates.io-index" 414 | checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" 415 | dependencies = [ 416 | "winapi-util", 417 | ] 418 | 419 | [[package]] 420 | name = "terminal_size" 421 | version = "0.2.2" 422 | source = "registry+https://github.com/rust-lang/crates.io-index" 423 | checksum = "40ca90c434fd12083d1a6bdcbe9f92a14f96c8a1ba600ba451734ac334521f7a" 424 | dependencies = [ 425 | "rustix", 426 | "windows-sys", 427 | ] 428 | 429 | [[package]] 430 | name = "textwrap" 431 | version = "0.16.0" 432 | source = "registry+https://github.com/rust-lang/crates.io-index" 433 | checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d" 434 | dependencies = [ 435 | "terminal_size", 436 | ] 437 | 438 | [[package]] 439 | name = "thiserror" 440 | version = "1.0.37" 441 | source = "registry+https://github.com/rust-lang/crates.io-index" 442 | checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e" 443 | dependencies = [ 444 | "thiserror-impl", 445 | ] 446 | 447 | [[package]] 448 | name = "thiserror-impl" 449 | version = "1.0.37" 450 | source = "registry+https://github.com/rust-lang/crates.io-index" 451 | checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb" 452 | dependencies = [ 453 | "proc-macro2", 454 | "quote", 455 | "syn", 456 | ] 457 | 458 | [[package]] 459 | name = "unicode-ident" 460 | version = "1.0.5" 461 | source = "registry+https://github.com/rust-lang/crates.io-index" 462 | checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" 463 | 464 | [[package]] 465 | name = "version_check" 466 | version = "0.9.4" 467 | source = "registry+https://github.com/rust-lang/crates.io-index" 468 | checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" 469 | 470 | [[package]] 471 | name = "winapi" 472 | version = "0.3.9" 473 | source = "registry+https://github.com/rust-lang/crates.io-index" 474 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 475 | dependencies = [ 476 | "winapi-i686-pc-windows-gnu", 477 | "winapi-x86_64-pc-windows-gnu", 478 | ] 479 | 480 | [[package]] 481 | name = "winapi-i686-pc-windows-gnu" 482 | version = "0.4.0" 483 | source = "registry+https://github.com/rust-lang/crates.io-index" 484 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 485 | 486 | [[package]] 487 | name = "winapi-util" 488 | version = "0.1.5" 489 | source = "registry+https://github.com/rust-lang/crates.io-index" 490 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 491 | dependencies = [ 492 | "winapi", 493 | ] 494 | 495 | [[package]] 496 | name = "winapi-x86_64-pc-windows-gnu" 497 | version = "0.4.0" 498 | source = "registry+https://github.com/rust-lang/crates.io-index" 499 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 500 | 501 | [[package]] 502 | name = "windows-sys" 503 | version = "0.42.0" 504 | source = "registry+https://github.com/rust-lang/crates.io-index" 505 | checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" 506 | dependencies = [ 507 | "windows_aarch64_gnullvm", 508 | "windows_aarch64_msvc", 509 | "windows_i686_gnu", 510 | "windows_i686_msvc", 511 | "windows_x86_64_gnu", 512 | "windows_x86_64_gnullvm", 513 | "windows_x86_64_msvc", 514 | ] 515 | 516 | [[package]] 517 | name = "windows_aarch64_gnullvm" 518 | version = "0.42.0" 519 | source = "registry+https://github.com/rust-lang/crates.io-index" 520 | checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e" 521 | 522 | [[package]] 523 | name = "windows_aarch64_msvc" 524 | version = "0.42.0" 525 | source = "registry+https://github.com/rust-lang/crates.io-index" 526 | checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4" 527 | 528 | [[package]] 529 | name = "windows_i686_gnu" 530 | version = "0.42.0" 531 | source = "registry+https://github.com/rust-lang/crates.io-index" 532 | checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7" 533 | 534 | [[package]] 535 | name = "windows_i686_msvc" 536 | version = "0.42.0" 537 | source = "registry+https://github.com/rust-lang/crates.io-index" 538 | checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246" 539 | 540 | [[package]] 541 | name = "windows_x86_64_gnu" 542 | version = "0.42.0" 543 | source = "registry+https://github.com/rust-lang/crates.io-index" 544 | checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed" 545 | 546 | [[package]] 547 | name = "windows_x86_64_gnullvm" 548 | version = "0.42.0" 549 | source = "registry+https://github.com/rust-lang/crates.io-index" 550 | checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028" 551 | 552 | [[package]] 553 | name = "windows_x86_64_msvc" 554 | version = "0.42.0" 555 | source = "registry+https://github.com/rust-lang/crates.io-index" 556 | checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" 557 | -------------------------------------------------------------------------------- /src/profile.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | //! Module for dealing with profiles 21 | 22 | #![allow(dead_code)] // Some methods are for future use, others are USED! (=false positive) 23 | 24 | use crate::location::Location; 25 | use crate::{SYSTEM_PROFILE_DIR, USER_PROFILE_DIR}; 26 | use bitflags::bitflags; 27 | use lazy_static::lazy_static; 28 | use log::{debug, warn}; 29 | use std::borrow::Cow; 30 | use std::collections::HashMap; 31 | use std::error::Error as StdError; 32 | use std::fs::{read_dir, read_to_string}; 33 | use std::io; 34 | use std::path::{Path, PathBuf}; 35 | 36 | lazy_static! { 37 | /// `lazy_static`: HashMap with the shortnames used by [`complete_name`] 38 | static ref SHORTNAMES: HashMap<&'static str, &'static str> = [ 39 | ("abs", "allow-bin-sh.inc"), 40 | ("acd", "allow-common-devel.inc"), 41 | ("ag", "allow-gjs.inc"), 42 | ("aj", "allow-java.inc"), 43 | ("al", "allow-lua.inc"), 44 | ("an", "allow-nodejs.inc"), 45 | ("ap", "allow-perl.inc"), 46 | ("app", "allow-php.inc"), 47 | ("ap2", "allow-python2.inc"), 48 | ("ap3", "allow-python3.inc"), 49 | ("ar", "allow-ruby.inc"), 50 | ("as", "allow-ssh.inc"), 51 | ("dc", "disable-common.inc"), 52 | ("dd", "disable-devel.inc"), 53 | ("de", "disable-exec.inc"), 54 | ("di", "disable-interpreters.inc"), 55 | ("dp", "disable-programs.inc"), 56 | ("dpm", "disable-passwdmgr.inc"), 57 | ("ds", "disable-shell.inc"), 58 | ("dwm", "disable-write-mnt.inc"), 59 | ("dX", "disable-X11.inc"), 60 | ("dx", "disable-xdg.inc"), 61 | ("wc", "whitelist-common.inc"), 62 | ("wrc", "whitelist-run-common.inc"), 63 | ("wruc", "whitelist-runuser-common.inc"), 64 | ("wusc", "whitelist-usr-share-common.inc"), 65 | ("wvc", "whitelist-var-common.inc"), 66 | ] 67 | // TODO: Use .into_iter().collect() when we upgrade to rust 2021 edition 68 | .iter() 69 | .copied() 70 | .collect(); 71 | } 72 | 73 | bitflags! { 74 | /// Flags for creating a new instance of profile 75 | pub struct ProfileFlags: u8 { 76 | /// Search in the current working directory (default) 77 | const LOOKUP_CWD = 0b_0000_0001; 78 | /// Search under `~/.config/firejail` (default) 79 | const LOOKUP_USER = 0b_0000_0010; 80 | /// Search under `/etc/firejail` (default) 81 | const LOOKUP_SYSTEM = 0b_0000_0100; 82 | /// Read the data of the profile 83 | const READ = 0b_0000_1000; 84 | /// Reject profiles with a '/' 85 | const DENY_BY_PATH = 0b_0001_0000; 86 | /// Assume that the profile exists in the location with the highest priority 87 | const ASSUME_EXISTENCE = 0b_0010_0000; 88 | } 89 | } 90 | impl ProfileFlags { 91 | /// Add flag `other` to self and return the result 92 | /// 93 | /// # Examples 94 | /// 95 | /// ``` 96 | /// ProfileFlags::default().with(ProfileFlags::READ) 97 | /// ``` 98 | pub fn with(self, other: Self) -> Self { 99 | self | other 100 | } 101 | 102 | /// Remove flag `other` from self and return the result 103 | /// 104 | /// # Examples 105 | /// 106 | /// ``` 107 | /// ProfileFlags::default().without(ProfileFlags::LOOKUP_CWD) 108 | /// ``` 109 | pub fn without(self, other: Self) -> Self { 110 | self & !other 111 | } 112 | } 113 | /// Default is `LOOKUP_CWD`, `LOOKUP_USER` and `LOOKUP_SYSTEM` 114 | impl Default for ProfileFlags { 115 | fn default() -> Self { 116 | Self::LOOKUP_CWD | Self::LOOKUP_USER | Self::LOOKUP_SYSTEM 117 | } 118 | } 119 | 120 | /// The representation of a profile 121 | #[non_exhaustive] 122 | #[derive(Clone, Debug, Default, Eq, PartialEq)] 123 | pub struct Profile<'a> { 124 | /// The raw name of the profile, passed to [`new`] 125 | /// 126 | /// [`new`]: #method.new 127 | raw_name: Cow<'a, str>, 128 | /// The completed name of the profile, maybe equal to raw_name 129 | full_name: Cow<'a, str>, 130 | /// The path to the profile 131 | /// 132 | /// This is `None` if [`new`] is called without any `LOOKUP_*` flag 133 | /// or no profile exists for it in the searched locations. 134 | /// 135 | /// | | `.`, user, system | `.`, user | `.`, system | user, system | `.` | user | system | 136 | /// | | | | | | | | | 137 | /// | CWD USER SYSTEM (default) | `.` | `.` | `.` | user | `.` | user | system | 138 | /// | CWD USER SYSTEM ASSUME | `.` | `.` | `.` | `.` | `.` | `.` | `.` | 139 | /// | USER | user | user | none | user | none | user | none | 140 | /// | USER ASSUME | user | user | user | user | user | user | user | 141 | /// 142 | /// [`new`]: #method.new 143 | path: Option, 144 | /// The profile raw data 145 | /// 146 | /// This is `None` if [`new`] is called without READ flag (default), 147 | /// and [`read`] hasn't been called on it. 148 | /// 149 | /// [`new`]: #method.new 150 | /// [`read`]: #method.read 151 | raw_data: Option, 152 | } 153 | impl<'a> Profile<'a> { 154 | /// Create a new Profile 155 | /// 156 | /// If new is called without `READ` flag, it is save to call unwrap on it. 157 | /// However, be aware that this may change in the future. 158 | /// 159 | /// # Errors 160 | /// 161 | /// - [`Error::ReadError`] 162 | /// 163 | /// # Panics 164 | /// 165 | /// Panics if `name` is `.` or `..`. 166 | /// 167 | /// # Examples 168 | /// 169 | /// ``` 170 | /// // unwrap is save here, because ProfileFlags::default() does not contain READ 171 | /// let firefox_profile = Profile::new("firefox", ProfileFlags::default()).unwrap(); 172 | /// 173 | /// let totem_profile = Profile::new( 174 | /// "totem.profile", 175 | /// ProfileFlags::default_with(ProfileFlags::READ), 176 | /// )?; 177 | /// 178 | /// let keepassxc_user_path: Option = Profile::new( 179 | /// "keepassxc", 180 | /// ProfileFlags::LOOKUP_USER | ProfileFlags::ASSUME_EXISTENCE | ProfileFlags::DENY_BY_PATH 181 | /// )?.path(); 182 | /// ``` 183 | /// 184 | /// [`ErrorContext`]: struct.ErrorContext.html 185 | pub fn new(name: &'a str, flags: ProfileFlags) -> Result { 186 | let raw_name = Cow::Borrowed(name); 187 | let full_name = complete_name(name, flags); 188 | 189 | debug!("Expanded profile-name '{}' to '{}'.", raw_name, full_name); 190 | 191 | let path; 192 | if name.contains('/') { 193 | if flags.contains(ProfileFlags::DENY_BY_PATH) { 194 | path = None; 195 | } else if flags.contains(ProfileFlags::ASSUME_EXISTENCE) || Path::new(name).exists() { 196 | path = Some(PathBuf::from(name)); 197 | } else { 198 | path = None; 199 | } 200 | } else { 201 | path = lookup_profile(&full_name, flags); 202 | } 203 | 204 | if !flags.contains(ProfileFlags::ASSUME_EXISTENCE) { 205 | if let Some(ref path) = path { 206 | debug!("Found profile {} at '{}'", full_name, path.display()); 207 | } 208 | } 209 | 210 | let mut new_profile = Self { 211 | raw_name, 212 | full_name, 213 | path, 214 | raw_data: None, 215 | }; 216 | 217 | if flags.contains(ProfileFlags::READ) { 218 | let res = new_profile.read(); 219 | if let Err(err) = res { 220 | return Err(Error::ReadError { 221 | raw_name: new_profile.raw_name.to_string(), 222 | full_name: new_profile.full_name.to_string(), 223 | path: new_profile.path.unwrap_or_default(), 224 | source: Box::new(err), 225 | }); 226 | } 227 | } 228 | 229 | Ok(new_profile) 230 | } 231 | 232 | /// Get the raw_name of the profile (i.e. the one passed to new). 233 | pub fn raw_name(&self) -> &Cow<'_, str> { 234 | &self.raw_name 235 | } 236 | 237 | /// Get the full_name of the profile. 238 | pub fn full_name(&self) -> &Cow<'_, str> { 239 | &self.full_name 240 | } 241 | 242 | /// Get the path of the profile (if exists). 243 | pub fn path(&self) -> Option<&Path> { 244 | self.path.as_deref() 245 | } 246 | 247 | /// Get the raw_data of the profile. 248 | /// 249 | /// # Panics 250 | /// 251 | /// This function panics if `self.raw_data` is `None`. 252 | pub fn raw_data(&self) -> &str { 253 | self.raw_data 254 | .as_deref() 255 | .expect("Called raw_data() on a profile without raw_data.") 256 | } 257 | 258 | /// Get the raw_data of the profile (if exists). 259 | pub fn try_raw_data(&self) -> Option<&str> { 260 | self.raw_data.as_deref() 261 | } 262 | 263 | /// Converts a `Profile` into a `PathBuf` 264 | /// 265 | /// # Panics 266 | /// 267 | /// Panics if `self.path` is `None`. 268 | pub fn into_pathbuf(self) -> PathBuf { 269 | self.path 270 | .expect("Called into_pathbuf() on a profile without a path.") 271 | } 272 | 273 | /// Converts a `Profile` into a `PathBuf` if possible. 274 | pub fn try_into_pathbuf(self) -> Option { 275 | self.path 276 | } 277 | 278 | /// Read the data of the profile 279 | /// 280 | /// This will re-read it if it is already read. 281 | /// 282 | /// # Errors 283 | /// 284 | /// - [`Error::NoPath`] 285 | /// - [`Error::Io`] 286 | /// 287 | /// # Examples 288 | /// 289 | /// ``` 290 | /// let mut profile = Profile::new("firefox", ProfileFlags::default())?; 291 | /// assert_eq!(profile.data(), &None); 292 | /// 293 | /// profile.read()?; 294 | /// assert_eq!(profile.data(), &Some(String::from("{Data of firefox.profile here}"))); 295 | /// 296 | /// # Ok::<(), Box>(()) 297 | /// ``` 298 | pub fn read(&mut self) -> Result<(), Error> { 299 | if let Some(ref path) = self.path { 300 | self.raw_data = Some(read_to_string(path)?); 301 | Ok(()) 302 | } else { 303 | Err(Error::NoPath) 304 | } 305 | } 306 | 307 | /// Return true if the profile is read (i.e. the data filed is not None), otherwise false. 308 | /// 309 | /// # Examples 310 | /// 311 | /// ``` 312 | /// let profile = Profile::new("firefox", ProfileFlags::READ)?; 313 | /// assert_eq!(profile.is_read(), true); 314 | /// 315 | /// let mut profile = Profile::new("firefox", ProfileFlags::default())?; 316 | /// assert_eq!(profile.is_read(), false); 317 | /// profile.read()?; 318 | /// assert_eq!(profile.is_read(), true); 319 | /// # Ok::<(), Box>(()) 320 | /// ``` 321 | pub fn is_read(&self) -> bool { 322 | self.raw_data.is_some() 323 | } 324 | } 325 | 326 | /// Complete a profile name 327 | /// 328 | /// - extract the basename if `name` is a path 329 | /// - expand shortnames if possible 330 | /// - add `.profile` if necessary 331 | /// 332 | /// # Panics 333 | /// 334 | /// This functions panics if `name` contains a `/` and flags does not contain `DENY_BY_PATH`. 335 | pub fn complete_name(name: &str, flags: ProfileFlags) -> Cow<'_, str> { 336 | if name.contains('/') { 337 | if flags.contains(ProfileFlags::DENY_BY_PATH) { 338 | panic!("Profile-names must not contain '/'."); 339 | } else { 340 | Cow::Borrowed(name.rsplit('/').next().unwrap()) 341 | } 342 | } else if let Some(long_name) = SHORTNAMES.get(name) { 343 | Cow::Borrowed(long_name) 344 | } else if name.ends_with(".inc") || name.ends_with(".local") || name.ends_with(".profile") { 345 | Cow::Borrowed(name) 346 | } else { 347 | Cow::Owned(name.to_string() + ".profile") 348 | } 349 | } 350 | 351 | /// Lookup for a file named `name` in every location specified in `flags` 352 | /// 353 | /// The path to the first found profile is returned, 354 | /// if no profile is found, `None` is returned. 355 | /// `ASSUME_EXISTENCE` is respected. 356 | /// 357 | /// Search order: 358 | /// 1. `LOOKUP_CWD` (`.`) 359 | /// 2. `LOOKUP_USER` (USER_PROFILE_DIR (`~/.config/firejail`)) 360 | /// 3. `LOOKUP_SYSTEM` (SYSTEM_PROFILE_DIR (`/etc/firejail`)) 361 | fn lookup_profile(name: &str, flags: ProfileFlags) -> Option { 362 | macro_rules! black_magic { 363 | (if $cond:expr => $location:expr) => { 364 | if $cond { 365 | if flags.contains(ProfileFlags::ASSUME_EXISTENCE) { 366 | Some($location.get_profile_path(name)) 367 | } else { 368 | match read_dir($location.as_ref()) { 369 | Ok(files) => files 370 | .filter_map(|ent| match ent { 371 | Ok(ent) => Some(ent), 372 | Err(err) => { 373 | warn!("There was a error in the lookup of: {}", err); 374 | None 375 | } 376 | }) 377 | .find(|ent| ent.file_name() == name) 378 | .map(|ent| ent.path()), 379 | Err(err) => { 380 | warn!("Failed to open {}: {}", $location, err); 381 | None 382 | } 383 | } 384 | } 385 | } else { 386 | None 387 | } 388 | }; 389 | } 390 | 391 | black_magic!(if flags.contains(ProfileFlags::LOOKUP_CWD) => Location::from(".")) 392 | .or_else( 393 | || black_magic!(if flags.contains(ProfileFlags::LOOKUP_USER) => &*USER_PROFILE_DIR), 394 | ) 395 | .or_else( 396 | || black_magic!(if flags.contains(ProfileFlags::LOOKUP_SYSTEM) => &*SYSTEM_PROFILE_DIR), 397 | ) 398 | } 399 | 400 | /// Profile Error 401 | #[derive(Debug, thiserror::Error)] 402 | #[allow(clippy::enum_variant_names)] 403 | pub enum Error { 404 | /// Occurs when calling [`new`](Profile::new) with [`ProfileFlags::READ`] and 405 | /// the internal call to [`read`](Profile::read) fails. 406 | /// 407 | /// If you expect that this likely happens, you should call [`read`](Profile::read) 408 | /// yourself, because the creation of this variant calls `.to_string()` 409 | /// on `raw_name` and `full_name` 410 | #[error("Failed to read '{full_name}': {source}")] 411 | ReadError { 412 | /// [`Profile::raw_name`] 413 | raw_name: String, 414 | /// [`Profile::full_name`] 415 | full_name: String, 416 | /// [`Profile::path`] or [`PathBuf::defaul()`](std::path::PathBuf::default) 417 | path: PathBuf, 418 | /// The error returned by [`read`](Profile::read) 419 | source: Box, 420 | }, 421 | /// Occurs when calling [`read`](Profile::read) on a [`Profile`] without a path 422 | /// (i.e. [`path`](Profile::path) is `None`). 423 | #[error("Called read on a Profile without a path.")] 424 | NoPath, 425 | /// Wraps an [I/O Error](std::io::Error). 426 | #[error("{0}")] 427 | Io(#[from] io::Error), 428 | } 429 | 430 | #[cfg(test)] 431 | mod tests { 432 | use super::*; 433 | 434 | #[test] 435 | fn profile_flags_with() { 436 | assert_eq!( 437 | ProfileFlags::default().with(ProfileFlags::READ), 438 | ProfileFlags::default() | ProfileFlags::READ, 439 | ); 440 | } 441 | 442 | #[test] 443 | fn profile_flags_without() { 444 | assert_eq!( 445 | ProfileFlags::default().without(ProfileFlags::LOOKUP_CWD), 446 | ProfileFlags::default() & !ProfileFlags::LOOKUP_CWD, 447 | ); 448 | } 449 | 450 | #[test] 451 | fn complete_name_path() { 452 | assert_eq!( 453 | complete_name("/etc/firejail/gnome-clocks.profile", ProfileFlags::empty()), 454 | "gnome-clocks.profile" 455 | ); 456 | assert_eq!( 457 | complete_name("/etc/firejail/gnome-clocks", ProfileFlags::empty()), 458 | "gnome-clocks" 459 | ); 460 | assert_eq!( 461 | complete_name("etc/firejail/gnome-clocks", ProfileFlags::empty()), 462 | "gnome-clocks" 463 | ); 464 | assert_eq!( 465 | complete_name("~/etc/firejail/gnome-clocks.profile", ProfileFlags::empty()), 466 | "gnome-clocks.profile" 467 | ); 468 | assert_eq!( 469 | complete_name("./gnome-clocks.local", ProfileFlags::empty()), 470 | "gnome-clocks.local" 471 | ); 472 | } 473 | 474 | #[test] 475 | #[should_panic(expected = "Profile-names must not contain '/'.")] 476 | fn complete_name_path_deny_by_path_1() { 477 | complete_name( 478 | "/etc/firejail/gnome-clocks.profile", 479 | ProfileFlags::DENY_BY_PATH, 480 | ); 481 | } 482 | 483 | #[test] 484 | #[should_panic(expected = "Profile-names must not contain '/'.")] 485 | fn complete_name_path_deny_by_path_2() { 486 | complete_name("/etc/firejail/gnome-clocks", ProfileFlags::DENY_BY_PATH); 487 | } 488 | 489 | #[test] 490 | #[should_panic(expected = "Profile-names must not contain '/'.")] 491 | fn complete_name_path_deny_by_path_3() { 492 | complete_name("etc/firejail/gnome-clocks", ProfileFlags::DENY_BY_PATH); 493 | } 494 | 495 | #[test] 496 | #[should_panic(expected = "Profile-names must not contain '/'.")] 497 | fn complete_name_path_deny_by_path_4() { 498 | complete_name( 499 | "~/etc/firejail/gnome-clocks.profile", 500 | ProfileFlags::DENY_BY_PATH, 501 | ); 502 | } 503 | 504 | #[test] 505 | #[should_panic(expected = "Profile-names must not contain '/'.")] 506 | fn complete_name_path_deny_by_path_5() { 507 | complete_name("./gnome-clocks.local", ProfileFlags::DENY_BY_PATH); 508 | } 509 | 510 | #[test] 511 | fn complete_name_short_names() { 512 | for (sname, lname) in &*SHORTNAMES { 513 | assert_eq!(complete_name(sname, ProfileFlags::empty()), *lname,); 514 | } 515 | } 516 | 517 | #[test] 518 | fn complete_name_inc_local_profile() { 519 | assert_eq!( 520 | complete_name("libreoffice.inc", ProfileFlags::empty()), 521 | "libreoffice.inc" 522 | ); 523 | assert_eq!( 524 | complete_name("libreoffice.local", ProfileFlags::empty()), 525 | "libreoffice.local" 526 | ); 527 | assert_eq!( 528 | complete_name("libreoffice.profile", ProfileFlags::empty()), 529 | "libreoffice.profile" 530 | ); 531 | } 532 | 533 | #[test] 534 | fn complete_name_append_profile() { 535 | assert_eq!( 536 | complete_name("bijiben", ProfileFlags::empty()), 537 | "bijiben.profile" 538 | ); 539 | } 540 | } 541 | -------------------------------------------------------------------------------- /src/profile_stream.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2020-2022 The fjp Authors 3 | * 4 | * This file is part of fjp 5 | * 6 | * fjp is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * fjp is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | //! Abstract representations of a firejail profile 21 | 22 | #![allow(clippy::cognitive_complexity)] 23 | 24 | use crate::utils::join; 25 | use std::borrow::{Borrow, BorrowMut}; 26 | use std::fmt; 27 | use std::iter::FromIterator; 28 | use std::slice; 29 | use std::str::FromStr; 30 | use std::sync::Arc; 31 | use std::vec; 32 | 33 | /// An abstract stream of lines in a firejail profile 34 | #[derive(Clone, Debug)] 35 | pub struct ProfileStream { 36 | inner: Vec, 37 | } 38 | impl ProfileStream { 39 | /// Check whether `self` contains `content` or not 40 | pub fn contains(&self, content: &Content) -> bool { 41 | self.inner.iter().any(|l| &*l.content == content) 42 | } 43 | 44 | /// Check whether there are any invalid lines 45 | pub fn has_errors(&self) -> bool { 46 | self.inner.iter().any(|line| !line.is_valid()) 47 | } 48 | 49 | /// Retruns a ProfileStream containing all invalid lines from self 50 | pub fn errors(&self) -> Self { 51 | self.inner 52 | .iter() 53 | .filter(|line| !line.is_valid()) 54 | .cloned() 55 | .collect() 56 | } 57 | 58 | /// Set all `lineno` in the `ProfileStream` to `None` 59 | pub fn strip_lineno(&mut self) { 60 | for l in &mut self.inner { 61 | l.lineno = None; 62 | } 63 | } 64 | 65 | /// Rewrite all `lineno` based on the current position in the `ProfileStream` 66 | pub fn rewrite_lineno(&mut self) { 67 | for (i, l) in self.inner.iter_mut().enumerate() { 68 | l.lineno = Some(i); 69 | } 70 | } 71 | 72 | /// Returns `true` if the profile-stream contains no lines 73 | pub fn is_empty(&self) -> bool { 74 | self.inner.is_empty() 75 | } 76 | } 77 | impl ProfileStream { 78 | /// Extracts a slice containing the entire underlying vector 79 | #[inline] 80 | pub fn as_slice(&self) -> &[Line] { 81 | &self.inner[..] 82 | } 83 | 84 | /// Extracts a mutable slice containing the entire underlying vector 85 | #[inline] 86 | pub fn as_mut_slice(&mut self) -> &mut [Line] { 87 | &mut self.inner[..] 88 | } 89 | 90 | /// Consum the `ProfileStream` and retrun the underlying vector 91 | #[inline] 92 | pub fn into_inner(self) -> Vec { 93 | self.inner 94 | } 95 | 96 | #[inline] 97 | pub fn iter(&self) -> slice::Iter<'_, Line> { 98 | self.inner.iter() 99 | } 100 | 101 | #[inline] 102 | pub fn iter_mut(&mut self) -> slice::IterMut<'_, Line> { 103 | self.inner.iter_mut() 104 | } 105 | } 106 | macro_rules! impl_borrow_and_convert_traits { 107 | ( $( $trait_:ty = fn $fname:ident$params:tt -> $rt:ty : $body:expr; )* ) => { 108 | $( 109 | impl $trait_ for ProfileStream { 110 | #[inline] 111 | fn $fname$params -> $rt { 112 | $body 113 | } 114 | } 115 | )* 116 | }; 117 | } 118 | impl_borrow_and_convert_traits! { 119 | AsMut> = fn as_mut(&mut self) -> &mut Vec: &mut self.inner ; 120 | AsMut<[Line]> = fn as_mut(&mut self) -> &mut [Line] : &mut self.inner[..]; 121 | AsRef> = fn as_ref(&self) -> &Vec : &self.inner ; 122 | AsRef<[Line]> = fn as_ref(&self) -> &[Line] : &self.inner[..] ; 123 | BorrowMut> = fn borrow_mut(&mut self) -> &mut Vec: &mut self.inner ; 124 | BorrowMut<[Line]> = fn borrow_mut(&mut self) -> &mut [Line] : &mut self.inner[..]; 125 | Borrow> = fn borrow(&self) -> &Vec : &self.inner ; 126 | Borrow<[Line]> = fn borrow(&self) -> &[Line] : &self.inner[..] ; 127 | From> = fn from(v: Vec) -> Self : Self { inner: v } ; 128 | } 129 | impl From for Vec { 130 | fn from(ps: ProfileStream) -> Self { 131 | ps.inner 132 | } 133 | } 134 | impl Extend for ProfileStream { 135 | #[inline] 136 | fn extend(&mut self, iter: T) 137 | where 138 | T: IntoIterator, 139 | { 140 | self.inner.extend(iter); 141 | } 142 | } 143 | impl FromIterator for ProfileStream { 144 | #[inline] 145 | fn from_iter(iter: T) -> Self 146 | where 147 | T: IntoIterator, 148 | { 149 | Self { 150 | inner: Vec::from_iter(iter), 151 | } 152 | } 153 | } 154 | impl IntoIterator for ProfileStream { 155 | type Item = Line; 156 | type IntoIter = vec::IntoIter; 157 | 158 | #[inline] 159 | fn into_iter(self) -> Self::IntoIter { 160 | self.inner.into_iter() 161 | } 162 | } 163 | impl<'a> IntoIterator for &'a ProfileStream { 164 | type Item = &'a Line; 165 | type IntoIter = slice::Iter<'a, Line>; 166 | 167 | #[inline] 168 | fn into_iter(self) -> Self::IntoIter { 169 | self.inner.iter() 170 | } 171 | } 172 | impl fmt::Display for ProfileStream { 173 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 174 | for Line { content, .. } in self.inner.iter().map(Borrow::borrow) { 175 | write!(f, "{}", content)?; 176 | } 177 | Ok(()) 178 | } 179 | } 180 | impl FromStr for ProfileStream { 181 | type Err = Self; 182 | 183 | fn from_str(s: &str) -> Result { 184 | let mut valid = true; 185 | let profile_stream = Self { 186 | inner: s 187 | .lines() 188 | .map(|line| { 189 | line.parse::().unwrap_or_else(|invalid| { 190 | valid = false; 191 | invalid 192 | }) 193 | }) 194 | .map(Arc::new) 195 | .enumerate() 196 | .map(|(lineno, content)| (Some(lineno), content)) 197 | .map(|(lineno, content)| Line { lineno, content }) 198 | .collect(), 199 | }; 200 | 201 | if valid { 202 | Ok(profile_stream) 203 | } else { 204 | Err(profile_stream) 205 | } 206 | } 207 | } 208 | 209 | // 210 | // Line 211 | // 212 | 213 | /// A profile-line 214 | #[derive(Clone, Debug, PartialEq, Eq)] 215 | pub struct Line { 216 | /// The line number of this line if known 217 | pub lineno: Option, 218 | /// The content of this line 219 | pub content: Arc, 220 | } 221 | impl Line { 222 | /// Returns `true` if this line is valid or `false` otherwise. 223 | /// 224 | /// A line is valid if `content` is something else than [`Content::Invalid`]. 225 | pub fn is_valid(&self) -> bool { 226 | !matches!(*self.content, Content::Invalid(_, _)) 227 | } 228 | 229 | /// Returns `true` if this line is a comment or `false` otherwise. 230 | pub fn is_comment(&self) -> bool { 231 | matches!(*self.content, Content::Comment(_)) 232 | } 233 | } 234 | impl AsRef for Line { 235 | fn as_ref(&self) -> &Content { 236 | &self.content 237 | } 238 | } 239 | 240 | // 241 | // Content 242 | // 243 | 244 | /// The content of a profile-`Line` 245 | #[derive(Clone, Debug, PartialEq, Eq)] 246 | pub enum Content { 247 | Blank, 248 | Command(Command), 249 | Comment(String), 250 | Conditional(Conditional), 251 | Invalid(String, Error), 252 | } 253 | impl fmt::Display for Content { 254 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 255 | match self { 256 | Self::Blank => writeln!(f), 257 | Self::Command(command) => writeln!(f, "{}", command), 258 | Self::Comment(comment) => writeln!(f, "#{}", comment), 259 | Self::Conditional(conditional) => writeln!(f, "{}", conditional), 260 | Self::Invalid(invalid, _) => writeln!(f, "{}", invalid), 261 | } 262 | } 263 | } 264 | impl FromStr for Content { 265 | type Err = Self; 266 | 267 | fn from_str(line: &str) -> Result { 268 | if line.is_empty() { 269 | Ok(Self::Blank) 270 | } else if let Some(comment) = line.strip_prefix('#') { 271 | Ok(Self::Comment(comment.to_string())) 272 | } else if line.starts_with('?') { 273 | match line.parse() { 274 | Ok(cond) => Ok(Self::Conditional(cond)), 275 | Err(err) => Err(Self::Invalid(line.to_string(), err)), 276 | } 277 | } else { 278 | match line.parse() { 279 | Ok(comm) => Ok(Self::Command(comm)), 280 | Err(err) => Err(Self::Invalid(line.to_string(), err)), 281 | } 282 | } 283 | } 284 | } 285 | 286 | // 287 | // Command 288 | // 289 | 290 | /// A firejail command 291 | #[non_exhaustive] 292 | #[derive(Clone, Debug, Hash, PartialEq, Eq)] 293 | pub enum Command { 294 | AllowDebuggers, 295 | Allusers, 296 | Apparmor, 297 | Bind(String, String), 298 | Blacklist(String), 299 | BlacklistNolog(String), 300 | Caps, 301 | CapsDropAll, 302 | CapsDrop(Vec), 303 | CapsKeep(Vec), 304 | DBusUser(DBusPolicy), 305 | DBusUserOwn(String), 306 | DBusUserTalk(String), 307 | DBusSystem(DBusPolicy), 308 | DBusSystemOwn(String), 309 | DBusSystemTalk(String), 310 | DisableMnt, 311 | /// `Env(String::from("WEBKIT_FORCE_SANDBOX"), String::from("0"))`: `env WEBKIT_FORCE_SANDBOX=0` 312 | Env(String, String), 313 | Hostname(String), 314 | Ignore(String), 315 | /// TODO: Recusive `ProfileStream`s 316 | Include(String), 317 | IpcNamespace, 318 | JoinOrStart(String), 319 | MachineId, 320 | MemoryDenyWriteExecute, 321 | Mkdir(String), 322 | Mkfile(String), 323 | Name(String), 324 | Netfilter, 325 | NetNone, 326 | No3d, 327 | Noblacklist(String), 328 | Nodvd, 329 | Noexec(String), 330 | Nogroups, 331 | Noinput, 332 | Nonewprivs, 333 | Noroot, 334 | Nosound, 335 | Notv, 336 | Nou2f, 337 | Novideo, 338 | Nowhitelist(String), 339 | /// `Private(None)`: `private`
340 | /// `Private(Some(String::from("${HOME}/spam")))`: `private ${HOME}/spam` 341 | Private(Option), 342 | PrivateBin(Vec), 343 | PrivateCache, 344 | PrivateCwd(String), 345 | PrivateDev, 346 | PrivateEtc(Vec), 347 | PrivateLib(Option>), 348 | PrivateOpt(Vec), 349 | PrivateSrv(Vec), 350 | PrivateTmp, 351 | Protocol(Vec), 352 | Quiet, 353 | ReadOnly(String), 354 | ReadWrite(String), 355 | Rmenv(String), 356 | /// `Seccomp(None)`: `seccomp`
357 | /// `Seccomp(Some(vec!["!chroot".to_string()]))`: `seccomp !chroot` 358 | Seccomp(Option>), 359 | SeccompBlockSecondary, 360 | SeccompDrop(Vec), 361 | SeccompErrorAction(SeccompErrorAction), 362 | ShellNone, 363 | Tmpfs(String), 364 | Tracelog, 365 | Whitelist(String), 366 | WriteableEtc, 367 | WritableRunUser, 368 | WritableVar, 369 | WritableVarLog, 370 | X11None, 371 | } 372 | impl fmt::Display for Command { 373 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 374 | use Command::*; 375 | match self { 376 | AllowDebuggers => write!(f, "allow-debuggers"), 377 | Allusers => write!(f, "allusers"), 378 | Apparmor => write!(f, "apparmor"), 379 | Bind(src_path, dst_path) => write!(f, "bind {},{}", src_path, dst_path), 380 | Blacklist(path) => write!(f, "blacklist {}", path), 381 | BlacklistNolog(path) => write!(f, "blacklist-nolog {}", path), 382 | Caps => write!(f, "caps"), 383 | CapsDropAll => write!(f, "caps.drop all"), 384 | CapsDrop(caps) => write!(f, "caps.drop {}", join(',', caps)), 385 | CapsKeep(caps) => write!(f, "caps.keep {}", join(',', caps)), 386 | DBusUser(policy) => write!(f, "dbus-user {}", policy), 387 | DBusUserOwn(name) => write!(f, "dbus-user.own {}", name), 388 | DBusUserTalk(name) => write!(f, "dbus-user.talk {}", name), 389 | DBusSystem(policy) => write!(f, "dbus-system {}", policy), 390 | DBusSystemOwn(name) => write!(f, "dbus-system.own {}", name), 391 | DBusSystemTalk(name) => write!(f, "dbus-system.talk {}", name), 392 | DisableMnt => write!(f, "disable-mnt"), 393 | Env(name, value) => write!(f, "env {}={}", name, value), 394 | Hostname(hostname) => write!(f, "hostname {}", hostname), 395 | Ignore(profile_line) => write!(f, "ignore {}", profile_line), 396 | Include(profile) => write!(f, "include {}", profile), 397 | IpcNamespace => write!(f, "ipc-namespace"), 398 | JoinOrStart(name) => write!(f, "join-or-start {}", name), 399 | MachineId => write!(f, "machine-id"), 400 | MemoryDenyWriteExecute => write!(f, "memory-deny-write-execute"), 401 | Mkdir(path) => write!(f, "mkdir {}", path), 402 | Mkfile(path) => write!(f, "mkfile {}", path), 403 | Name(name) => write!(f, "name {}", name), 404 | Netfilter => write!(f, "netfilter"), 405 | NetNone => write!(f, "net none"), 406 | No3d => write!(f, "no3d"), 407 | Noblacklist(path) => write!(f, "noblacklist {}", path), 408 | Nodvd => write!(f, "nodvd"), 409 | Noexec(path) => write!(f, "noexec {}", path), 410 | Nogroups => write!(f, "nogroups"), 411 | Noinput => write!(f, "noinput"), 412 | Nonewprivs => write!(f, "nonewprivs"), 413 | Noroot => write!(f, "noroot"), 414 | Nosound => write!(f, "nosound"), 415 | Notv => write!(f, "notv"), 416 | Nou2f => write!(f, "nou2f"), 417 | Novideo => write!(f, "novideo"), 418 | Nowhitelist(path) => write!(f, "nowhitelist {}", path), 419 | Private(None) => write!(f, "private"), 420 | Private(Some(path)) => write!(f, "private {}", path), 421 | PrivateBin(bins) => write!(f, "private-bin {}", bins.join(",")), 422 | PrivateCache => write!(f, "private-cache"), 423 | PrivateCwd(path) => write!(f, "private-cwd {}", path), 424 | PrivateDev => write!(f, "private-dev"), 425 | PrivateEtc(files) => write!(f, "private-etc {}", files.join(",")), 426 | PrivateLib(None) => write!(f, "private-lib"), 427 | PrivateLib(Some(files)) => write!(f, "private-lib {}", files.join(",")), 428 | PrivateOpt(files) => write!(f, "private-opt {}", files.join(",")), 429 | PrivateSrv(files) => write!(f, "private-srv {}", files.join(",")), 430 | PrivateTmp => write!(f, "private-tmp"), 431 | Protocol(protocols) => write!(f, "protocol {}", join(",", protocols)), 432 | Quiet => write!(f, "quiet"), 433 | ReadOnly(path) => write!(f, "read-only {}", path), 434 | ReadWrite(path) => write!(f, "read-write {}", path), 435 | Rmenv(name) => write!(f, "rmenv {}", name), 436 | Seccomp(None) => write!(f, "seccomp"), 437 | Seccomp(Some(syscalls)) => write!(f, "seccomp {}", syscalls.join(",")), 438 | SeccompBlockSecondary => write!(f, "seccomp.block-secondary"), 439 | SeccompDrop(syscalls) => write!(f, "seccomp.drop {}", syscalls.join(",")), 440 | SeccompErrorAction(action) => write!(f, "seccomp-error-action {}", action), 441 | ShellNone => write!(f, "shell none"), 442 | Tmpfs(path) => write!(f, "tmpfs {}", path), 443 | Tracelog => write!(f, "tracelog"), 444 | Whitelist(path) => write!(f, "whitelist {}", path), 445 | WriteableEtc => write!(f, "writable-etc"), 446 | WritableRunUser => write!(f, "writable-run-user"), 447 | WritableVar => write!(f, "writable-var"), 448 | WritableVarLog => write!(f, "writable-var-log"), 449 | X11None => write!(f, "x11 none"), 450 | } 451 | } 452 | } 453 | impl FromStr for Command { 454 | type Err = Error; 455 | 456 | fn from_str(line: &str) -> Result { 457 | use Command::*; 458 | 459 | Ok(if line == "allow-debuggers" { 460 | AllowDebuggers 461 | } else if line == "allusers" { 462 | Allusers 463 | } else if line == "apparmor" { 464 | Apparmor 465 | } else if let Some(paths) = line.strip_prefix("bind ") { 466 | paths 467 | .split_once(',') 468 | .map(|(src, dst)| Bind(src.to_string(), dst.to_string())) 469 | .ok_or(Error::BadBind)? 470 | } else if let Some(path) = line.strip_prefix("blacklist ") { 471 | Blacklist(path.to_string()) 472 | } else if let Some(path) = line.strip_prefix("blacklist-nolog ") { 473 | BlacklistNolog(path.to_string()) 474 | } else if line == "caps" { 475 | Caps 476 | } else if line == "caps.drop all" { 477 | CapsDropAll 478 | } else if let Some(caps) = line.strip_prefix("caps.drop ") { 479 | CapsDrop(caps.split(',').map(str::parse).collect::>()?) 480 | } else if let Some(caps) = line.strip_prefix("caps.keep ") { 481 | CapsKeep(caps.split(',').map(str::parse).collect::>()?) 482 | } else if line == "dbus-user filter" { 483 | DBusUser(DBusPolicy::Filter) 484 | } else if line == "dbus-user none" { 485 | DBusUser(DBusPolicy::None) 486 | } else if let Some(name) = line.strip_prefix("dbus-user.own ") { 487 | DBusUserOwn(name.to_string()) 488 | } else if let Some(name) = line.strip_prefix("dbus-user.talk ") { 489 | DBusUserTalk(name.to_string()) 490 | } else if line == "dbus-system filter" { 491 | DBusSystem(DBusPolicy::Filter) 492 | } else if line == "dbus-system none" { 493 | DBusSystem(DBusPolicy::None) 494 | } else if let Some(name) = line.strip_prefix("dbus-system.own ") { 495 | DBusSystemOwn(name.to_string()) 496 | } else if let Some(name) = line.strip_prefix("dbus-system.talk ") { 497 | DBusSystemTalk(name.to_string()) 498 | } else if line == "disable-mnt" { 499 | DisableMnt 500 | } else if let Some(name_and_value) = line.strip_prefix("env ") { 501 | name_and_value 502 | .split_once('=') 503 | .map(|(name, value)| Env(name.to_string(), value.to_string())) 504 | .ok_or(Error::BadEnv)? 505 | } else if let Some(hostname) = line.strip_prefix("hostname ") { 506 | Hostname(hostname.to_string()) 507 | } else if let Some(line) = line.strip_prefix("ignore ") { 508 | Ignore(line.to_string()) 509 | } else if let Some(other_profile) = line.strip_prefix("include ") { 510 | Include(other_profile.to_string()) 511 | } else if line == "ipc-namespace" { 512 | IpcNamespace 513 | } else if let Some(name) = line.strip_prefix("join-or-start ") { 514 | JoinOrStart(name.to_string()) 515 | } else if line == "machine-id" { 516 | MachineId 517 | } else if line == "memory-deny-write-execute" { 518 | MemoryDenyWriteExecute 519 | } else if let Some(path) = line.strip_prefix("mkdir ") { 520 | Mkdir(path.to_string()) 521 | } else if let Some(path) = line.strip_prefix("mkfile ") { 522 | Mkfile(path.to_string()) 523 | } else if let Some(sandboxname) = line.strip_prefix("name ") { 524 | Name(sandboxname.to_string()) 525 | } else if line == "netfilter" { 526 | Netfilter 527 | } else if line == "net none" { 528 | NetNone 529 | } else if line == "no3d" { 530 | No3d 531 | } else if let Some(path) = line.strip_prefix("noblacklist ") { 532 | Noblacklist(path.to_string()) 533 | } else if line == "nodvd" { 534 | Nodvd 535 | } else if let Some(path) = line.strip_prefix("noexec ") { 536 | Noexec(path.to_string()) 537 | } else if line == "nogroups" { 538 | Nogroups 539 | } else if line == "noinput" { 540 | Noinput 541 | } else if line == "nonewprivs" { 542 | Nonewprivs 543 | } else if line == "noroot" { 544 | Noroot 545 | } else if line == "nosound" { 546 | Nosound 547 | } else if line == "notv" { 548 | Notv 549 | } else if line == "nou2f" { 550 | Nou2f 551 | } else if line == "novideo" { 552 | Novideo 553 | } else if let Some(path) = line.strip_prefix("nowhitelist ") { 554 | Nowhitelist(path.to_string()) 555 | } else if line == "private" { 556 | Private(None) 557 | } else if let Some(path) = line.strip_prefix("private ") { 558 | Private(Some(path.to_string())) 559 | } else if let Some(bins) = line.strip_prefix("private-bin ") { 560 | PrivateBin(bins.split(',').map(String::from).collect()) 561 | } else if line == "private-cache" { 562 | PrivateCache 563 | } else if let Some(path) = line.strip_prefix("private-cwd ") { 564 | PrivateCwd(path.to_string()) 565 | } else if line == "private-dev" { 566 | PrivateDev 567 | } else if let Some(files) = line.strip_prefix("private-etc ") { 568 | PrivateEtc(files.split(',').map(String::from).collect()) 569 | } else if line == "private-lib" { 570 | PrivateLib(None) 571 | } else if let Some(libs) = line.strip_prefix("private-lib ") { 572 | PrivateLib(Some(libs.split(',').map(String::from).collect())) 573 | } else if let Some(paths) = line.strip_prefix("private-opt ") { 574 | PrivateOpt(paths.split(',').map(String::from).collect()) 575 | } else if let Some(paths) = line.strip_prefix("private-srv ") { 576 | PrivateSrv(paths.split(',').map(String::from).collect()) 577 | } else if line == "private-tmp" { 578 | PrivateTmp 579 | } else if let Some(protocols) = line.strip_prefix("protocol ") { 580 | Protocol( 581 | protocols 582 | .split(',') 583 | .map(FromStr::from_str) 584 | .collect::>()?, 585 | ) 586 | } else if line == "quiet" { 587 | Quiet 588 | } else if let Some(path) = line.strip_prefix("read-only ") { 589 | ReadOnly(path.to_string()) 590 | } else if let Some(path) = line.strip_prefix("read-write ") { 591 | ReadWrite(path.to_string()) 592 | } else if let Some(name) = line.strip_prefix("rmenv ") { 593 | Rmenv(name.to_string()) 594 | } else if line == "seccomp" { 595 | Seccomp(None) 596 | } else if let Some(syscalls) = line.strip_prefix("seccomp ") { 597 | Seccomp(Some(syscalls.split(',').map(String::from).collect())) 598 | } else if line == "seccomp.block-secondary" { 599 | SeccompBlockSecondary 600 | } else if let Some(syscalls) = line.strip_prefix("seccomp.drop ") { 601 | SeccompDrop(syscalls.split(',').map(String::from).collect()) 602 | } else if let Some(action) = line.strip_prefix("seccomp-error-action ") { 603 | SeccompErrorAction(action.parse()?) 604 | } else if line == "shell none" { 605 | ShellNone 606 | } else if let Some(path) = line.strip_prefix("tmpfs ") { 607 | Tmpfs(path.to_string()) 608 | } else if line == "tracelog" { 609 | Tracelog 610 | } else if let Some(path) = line.strip_prefix("whitelist ") { 611 | Whitelist(path.to_string()) 612 | } else if line == "writable-etc" { 613 | WriteableEtc 614 | } else if line == "writable-run-user" { 615 | WritableRunUser 616 | } else if line == "writable-var" { 617 | WritableVar 618 | } else if line == "writable-var-log" { 619 | WritableVarLog 620 | } else if line == "x11 none" { 621 | X11None 622 | } else { 623 | return Err(Error::BadCommand); 624 | }) 625 | } 626 | } 627 | 628 | // 629 | // Conditional 630 | // 631 | 632 | /// A condition with an conditional command 633 | #[non_exhaustive] 634 | #[derive(Clone, Debug, Hash, PartialEq, Eq)] 635 | pub enum Conditional { 636 | BrowserAllowDrm(Command), 637 | BrowserDisableU2f(Command), 638 | HasAppimage(Command), 639 | HasNet(Command), 640 | HasNodbus(Command), 641 | HasNosound(Command), 642 | HasPrivate(Command), 643 | HasX11(Command), 644 | } 645 | impl FromStr for Conditional { 646 | type Err = Error; 647 | 648 | fn from_str(line: &str) -> Result { 649 | let mut splited_line = line.splitn(2, ' '); 650 | let con = splited_line.next().unwrap(); 651 | let cmd = splited_line.next().ok_or(Error::EmptyCondition)?; 652 | 653 | if con == "?BROWSER_ALLOW_DRM:" { 654 | Ok(Self::BrowserAllowDrm(cmd.parse()?)) 655 | } else if con == "?BROWSER_DISABLE_U2F:" { 656 | Ok(Self::BrowserDisableU2f(cmd.parse()?)) 657 | } else if con == "?HAS_APPIMAGE:" { 658 | Ok(Self::HasAppimage(cmd.parse()?)) 659 | } else if con == "?HAS_NET:" { 660 | Ok(Self::HasNet(cmd.parse()?)) 661 | } else if con == "?HAS_NODBUS:" { 662 | Ok(Self::HasNodbus(cmd.parse()?)) 663 | } else if con == "?HAS_NOSOUND:" { 664 | Ok(Self::HasNosound(cmd.parse()?)) 665 | } else if con == "?HAS_PRIVATE: " { 666 | Ok(Self::HasPrivate(cmd.parse()?)) 667 | } else if con == "?HAS_X11:" { 668 | Ok(Self::HasX11(cmd.parse()?)) 669 | } else { 670 | Err(Error::BadCondition) 671 | } 672 | } 673 | } 674 | impl fmt::Display for Conditional { 675 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 676 | match self { 677 | Self::BrowserAllowDrm(cmd) => write!(f, "?BROWSER_ALLOW_DRM: {}", cmd), 678 | Self::BrowserDisableU2f(cmd) => write!(f, "?BROWSER_DISABLE_U2F: {}", cmd), 679 | Self::HasAppimage(cmd) => write!(f, "?HAS_APPIMAGE: {}", cmd), 680 | Self::HasNet(cmd) => write!(f, "?HAS_NET: {}", cmd), 681 | Self::HasNodbus(cmd) => write!(f, "?HAS_NODBUS: {}", cmd), 682 | Self::HasNosound(cmd) => write!(f, "?HAS_NOSOUND: {}", cmd), 683 | Self::HasPrivate(cmd) => write!(f, "?HAS_PRIVATE: {}", cmd), 684 | Self::HasX11(cmd) => write!(f, "?HAS_X11: {}", cmd), 685 | } 686 | } 687 | } 688 | 689 | macro_rules! values { 690 | ( 691 | $( #[ $attr:meta ] )* 692 | pub enum $T:ident { 693 | $( $variant:ident = $value:literal, )* 694 | _ = $from_str_error:path, 695 | } 696 | ) => { 697 | $( #[ $attr ] )* 698 | pub enum $T { 699 | $( $variant ),* 700 | } 701 | impl fmt::Display for $T { 702 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 703 | match self { 704 | $( Self::$variant => write!(f, $value), )* 705 | } 706 | } 707 | } 708 | impl FromStr for $T { 709 | type Err = Error; 710 | 711 | fn from_str(s: &str) -> Result { 712 | match s { 713 | $( $value => Ok(Self::$variant), )* 714 | _ => Err($from_str_error), 715 | } 716 | } 717 | } 718 | }; 719 | } 720 | 721 | // 722 | // Capabilities 723 | // 724 | 725 | values! { 726 | /// Caps used by the various `caps` commands 727 | #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] 728 | pub enum Capabilities { 729 | AuditControl = "audit_control", 730 | AuditRead = "audit_read", 731 | AuditWrite = "audit_write", 732 | BlockSuspend = "block_suspend", 733 | Bpf = "bpf", 734 | CheckpointRestore = "checkpoint_restore", 735 | Chown = "chown", 736 | DacOverride = "dac_override", 737 | DacReadSearch = "dac_read_search", 738 | Fowner = "fowner", 739 | Fsetid = "fsetid", 740 | IpcLock = "ipc_lock", 741 | IpcOwner = "ipc_owner", 742 | Kill = "kill", 743 | Lease = "lease", 744 | LinuxImmutable = "linux_immutable", 745 | MacAdmin = "mac_admin", 746 | MacOverride = "mac_override", 747 | Mknod = "mknod", 748 | NetAdmin = "net_admin", 749 | NetBindService = "net_bind_service", 750 | NetBroadcast = "net_broadcast", 751 | NetRaw = "net_raw", 752 | Perfmon = "perfmon", 753 | Setfcap = "setfcap", 754 | Setgid = "setgid", 755 | Setpcap = "setpcap", 756 | Setuid = "setuid", 757 | SysAdmin = "sys_admin", 758 | SysBoot = "sys_boot", 759 | SysChroot = "sys_chroot", 760 | SysModule = "sys_module", 761 | SysNice = "sys_nice", 762 | SysPacct = "sys_pacct", 763 | SysPtrace = "sys_ptrace", 764 | SysRawio = "sys_rawio", 765 | SysResource = "sys_resource", 766 | SysTime = "sys_time", 767 | SysTtyConfig = "sys_tty_config", 768 | Syslog = "syslog", 769 | WakeAlarm = "wake_alarm", 770 | _ = Error::BadCap, 771 | } 772 | } 773 | 774 | // 775 | // DBusPolicy 776 | // 777 | 778 | values! { 779 | /// DBus Policy 780 | #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] 781 | pub enum DBusPolicy { 782 | Filter = "filter", 783 | None = "none", 784 | _ = Error::BadDBusPolicy, 785 | } 786 | } 787 | 788 | // 789 | // Protocol 790 | // 791 | 792 | values! { 793 | /// A `Protocol` from firejails `protocol` command 794 | /// 795 | /// TODO: Support prefixes: `-`, `+` and `=`. 796 | #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] 797 | pub enum Protocol { 798 | Unix = "unix", 799 | Inet = "inet", 800 | Inet6 = "inet6", 801 | Netlink = "netlink", 802 | Packet = "packet", 803 | Bluetooth = "bluetooth", 804 | _ = Error::BadProtocol, 805 | } 806 | } 807 | 808 | macro_rules! seccomp_error_action { 809 | ( $( $act:ident ),* $(,)? ) => { 810 | /// A action for firejails `seccomp-error-action` 811 | #[allow(clippy::upper_case_acronyms)] 812 | #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] 813 | pub enum SeccompErrorAction { 814 | Kill, 815 | Log, 816 | $( $act ),* 817 | } 818 | impl fmt::Display for SeccompErrorAction { 819 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 820 | match self { 821 | Self::Kill => write!(f, "kill"), 822 | Self::Log => write!(f, "log"), 823 | $( Self::$act => write!(f, stringify!($act)), )* 824 | } 825 | } 826 | } 827 | impl FromStr for SeccompErrorAction { 828 | type Err = Error; 829 | 830 | fn from_str(s: &str) -> Result { 831 | match s { 832 | "kill" => Ok(Self::Kill), 833 | "log" => Ok(Self::Log), 834 | $( stringify!($act) => Ok(Self::$act), )* 835 | _ => Err(Error::BadSeccompErrorAction), 836 | } 837 | } 838 | } 839 | }; 840 | } 841 | #[rustfmt::skip] 842 | // Creates `enum SeccompErrorAction` 843 | seccomp_error_action! { 844 | // gcc -dM -E /usr/include/errno.h | grep -E "^#define E" | cut -d" " -f2 | sort | tr '\n' ',' | sed "s/,/, /g" 845 | E2BIG, EACCES, EADDRINUSE, EADDRNOTAVAIL, EADV, EAFNOSUPPORT, EAGAIN, EALREADY, EBADE, EBADF, 846 | EBADFD, EBADMSG, EBADR, EBADRQC, EBADSLT, EBFONT, EBUSY, ECANCELED, ECHILD, ECHRNG, ECOMM, 847 | ECONNABORTED, ECONNREFUSED, ECONNRESET, EDEADLK, EDEADLOCK, EDESTADDRREQ, EDOM, EDOTDOT, EDQUOT, 848 | EEXIST, EFAULT, EFBIG, EHOSTDOWN, EHOSTUNREACH, EHWPOISON, EIDRM, EILSEQ, EINPROGRESS, EINTR, 849 | EINVAL, EIO, EISCONN, EISDIR, EISNAM, EKEYEXPIRED, EKEYREJECTED, EKEYREVOKED, EL2HLT, EL2NSYNC, 850 | EL3HLT, EL3RST, ELIBACC, ELIBBAD, ELIBEXEC, ELIBMAX, ELIBSCN, ELNRNG, ELOOP, EMEDIUMTYPE, 851 | EMFILE, EMLINK, EMSGSIZE, EMULTIHOP, ENAMETOOLONG, ENAVAIL, ENETDOWN, ENETRESET, ENETUNREACH, 852 | ENFILE, ENOANO, ENOBUFS, ENOCSI, ENODATA, ENODEV, ENOENT, ENOEXEC, ENOKEY, ENOLCK, ENOLINK, 853 | ENOMEDIUM, ENOMEM, ENOMSG, ENONET, ENOPKG, ENOPROTOOPT, ENOSPC, ENOSR, ENOSTR, ENOSYS, ENOTBLK, 854 | ENOTCONN, ENOTDIR, ENOTEMPTY, ENOTNAM, ENOTRECOVERABLE, ENOTSOCK, ENOTSUP, ENOTTY, ENOTUNIQ, 855 | ENXIO, EOPNOTSUPP, EOVERFLOW, EOWNERDEAD, EPERM, EPFNOSUPPORT, EPIPE, EPROTO, EPROTONOSUPPORT, 856 | EPROTOTYPE, ERANGE, EREMCHG, EREMOTE, EREMOTEIO, ERESTART, ERFKILL, EROFS, ESHUTDOWN, 857 | ESOCKTNOSUPPORT, ESPIPE, ESRCH, ESRMNT, ESTALE, ESTRPIPE, ETIME, ETIMEDOUT, ETOOMANYREFS, 858 | ETXTBSY, EUCLEAN, EUNATCH, EUSERS, EWOULDBLOCK, EXDEV, EXFULL, 859 | } 860 | 861 | // 862 | // Error 863 | // 864 | 865 | #[non_exhaustive] 866 | #[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)] 867 | pub enum Error { 868 | #[error("Invalid bind command")] 869 | BadBind, 870 | #[error("Invalid capability")] 871 | BadCap, 872 | #[error("Invalid command")] 873 | BadCommand, 874 | #[error("Invalid condition")] 875 | BadCondition, 876 | #[error("Invalid dbus policy")] 877 | BadDBusPolicy, 878 | #[error("Invalid env command")] 879 | BadEnv, 880 | #[error("Invalid protocol")] 881 | BadProtocol, 882 | #[error("Invalid seccomp-error-action")] 883 | BadSeccompErrorAction, 884 | #[error("No command after condition")] 885 | EmptyCondition, 886 | } 887 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------