├── .gitignore ├── ip.sh ├── src ├── net │ ├── mod.rs │ ├── ether.rs │ ├── arp.rs │ ├── mac.rs │ └── ip.rs ├── lib.rs ├── advert.rs ├── error.rs ├── config.rs ├── node.rs ├── ip_carp.rs └── carp.rs ├── ucarp.sh ├── ucarp.c.patch ├── Vagrantfile ├── provision.sh ├── run.sh ├── .travis.yml ├── Cargo.toml ├── examples └── basic.rs ├── COPYING.OLD ├── tests └── lib.rs ├── README.md ├── Cargo.lock ├── COPYING.LESSER └── COPYING /.gitignore: -------------------------------------------------------------------------------- 1 | .vagrant 2 | target 3 | -------------------------------------------------------------------------------- /ip.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}' 4 | -------------------------------------------------------------------------------- /src/net/mod.rs: -------------------------------------------------------------------------------- 1 | //! Networking primitives 2 | //! 3 | 4 | pub mod arp; 5 | pub mod ether; 6 | pub mod ip; 7 | pub mod mac; 8 | -------------------------------------------------------------------------------- /ucarp.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DIR=/home/vagrant/UCarp 4 | 5 | sudo $DIR/src/ucarp --interface=eth1 --srcip=10.0.2.30 --vhid=1 \ 6 | --pass=secret --addr=10.0.2.100 --advbase=3 \ 7 | --upscript=$DIR/examples/linux/vip-up.sh \ 8 | --downscript=$DIR/examples/linux/vip-down.sh 9 | -------------------------------------------------------------------------------- /ucarp.c.patch: -------------------------------------------------------------------------------- 1 | --- ucarp.c 2016-04-16 14:12:37.189347963 +0000 2 | +++ ucarp.c.fix 2016-04-16 14:13:38.752116683 +0000 3 | @@ -90,6 +90,8 @@ 4 | int option_index = 0; 5 | int fodder; 6 | 7 | + debug = 1; 8 | + 9 | #ifdef HAVE_SETLOCALE 10 | setlocale(LC_ALL, ""); 11 | #endif 12 | -------------------------------------------------------------------------------- /Vagrantfile: -------------------------------------------------------------------------------- 1 | # -*- mode: ruby -*- 2 | # vi: set ft=ruby : 3 | 4 | VAGRANTFILE_API_VERSION = "2" 5 | 6 | Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| 7 | 8 | config.vm.box = "ubuntu/trusty64" 9 | config.vm.network :private_network, ip: "10.0.2.30" 10 | config.vm.network :private_network, ip: "10.0.2.40" 11 | config.vm.network :private_network, ip: "10.0.2.100" 12 | 13 | # requires working internet connection 14 | config.vm.box_check_update = false 15 | end 16 | -------------------------------------------------------------------------------- /provision.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | sudo apt-get update 6 | sudo apt-get install -y libtool autoconf gettext libpcap0.8 libpcap0.8-dev libpcap-dev sqlite3 libsqlite3-dev gdb git 7 | curl -sSf https://static.rust-lang.org/rustup.sh | sh -s -- --channel=nightly 8 | 9 | cd /home/vagrant/ 10 | git clone https://github.com/jedisct1/UCarp 11 | cd UCarp 12 | patch src/ucarp.c /vagrant/ucarp.c.patch 13 | libtoolize 14 | gettextize -f 15 | cp po/Makevars.template po/Makevars 16 | autoreconf -i 17 | ./configure && make 18 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | SESSION=carp 3 | 4 | tmux -2 new-session -d -s $SESSION 5 | tmux bind-key -n C-c kill-session 6 | tmux bind-key -n C-d kill-session 7 | tmux bind-key -n Escape kill-session 8 | 9 | tmux new-window -t $SESSION:1 -n 'CARP' 10 | tmux split-window -v 11 | tmux select-pane -t 0 12 | tmux send-keys "sh /vagrant/ucarp.sh" C-m 13 | tmux select-pane -t 1 14 | tmux send-keys "sleep 10 && sudo RUST_LOG=trace /vagrant/target/debug/examples/basic -i eth2 -s 10.0.2.40" C-m 15 | 16 | # Attach to session 17 | tmux -2 attach-session -t $SESSION 18 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | dist: trusty 3 | 4 | language: rust 5 | 6 | rust: 7 | - nightly 8 | - beta 9 | - stable 10 | 11 | cache: cargo 12 | 13 | before_script: 14 | - sudo apt-get -qq update 15 | - sudo apt-get -y install libpcap-dev sqlite3 libsqlite3-dev 16 | # See https://github.com/travis-ci/travis-ci/issues/1350 17 | - sudo sed -i -e 's/^Defaults\tsecure_path.*$//' /etc/sudoers 18 | 19 | script: 20 | - cargo build --verbose 21 | - sudo TEST_INF=eth0 TEST_SRCIP=$(sh ./ip.sh) RUST_LOG=carp RUST_BACKTRACE=1 RUST_TEST_THREADS=1 cargo test --verbose -- --nocapture 22 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "carp" 3 | version = "0.1.0" 4 | license = "MIT/Apache-2.0" 5 | authors = ["Herman J. Radtke III "] 6 | description = "A pure rust library for the Common Address Redundancy Protocol (CARP)." 7 | documentation = "https://github.com/hjr3/carp-rs" 8 | homepage = "https://github.com/hjr3/carp-rs" 9 | repository = "https://github.com/hjr3/carp-rs" 10 | 11 | [dependencies] 12 | libc = "0.2.7" 13 | log = "0.3.5" 14 | env_logger = "0.3.2" 15 | nix = "0.5.0" 16 | rust-crypto = "0.2.34" 17 | pcap = "0.5.3" 18 | byteorder = "0.4.2" 19 | getopts = "0.2.4" 20 | rand = "0.3" 21 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 Herman J. Radtke III 2 | // 3 | // This file is part of carp-rs. 4 | // 5 | // carp-rs is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Lesser General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // carp-rs is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Lesser General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Lesser General Public License 16 | // along with carp-rs. If not, see . 17 | 18 | extern crate libc; 19 | 20 | #[macro_use] 21 | extern crate log; 22 | 23 | #[cfg(unix)] 24 | extern crate nix; 25 | 26 | extern crate rand; 27 | extern crate pcap; 28 | extern crate crypto; 29 | extern crate byteorder; 30 | 31 | use std::result; 32 | 33 | pub mod net; 34 | 35 | mod error; 36 | mod node; 37 | pub mod advert; 38 | pub mod ip_carp; 39 | pub mod config; 40 | pub mod carp; 41 | 42 | pub type Result = result::Result; 43 | -------------------------------------------------------------------------------- /examples/basic.rs: -------------------------------------------------------------------------------- 1 | extern crate carp; 2 | extern crate getopts; 3 | 4 | use std::str::FromStr; 5 | use getopts::Options; 6 | use std::env; 7 | 8 | #[macro_use] extern crate log; 9 | extern crate env_logger; 10 | 11 | fn main() { 12 | env_logger::init().ok().expect("Failed to init logger"); 13 | trace!("Starting basic example"); 14 | 15 | let args: Vec = env::args().collect(); 16 | let mut opts = Options::new(); 17 | opts.optopt("s", "", "The src ip", "SRCIP"); 18 | opts.optopt("i", "", "The interface. Example: eth0", "INTERFACE"); 19 | 20 | let matches = opts.parse(&args[1..]).unwrap(); 21 | let srcip = matches.opt_str("s").unwrap(); 22 | let if_name = matches.opt_str("i").unwrap(); 23 | 24 | let mut config = carp::config::Config::new( 25 | FromStr::from_str("10.0.2.100").unwrap(), 26 | FromStr::from_str(&srcip).unwrap(), 27 | "secret" 28 | ); 29 | 30 | //config.set_password("thisisatest"); 31 | config.set_interface(if_name.as_ref()); 32 | config.set_advbase(1); 33 | config.set_advskew(1); 34 | config.set_preempt(true); 35 | 36 | let capture = carp::carp::Carp::default_pcap(&if_name).unwrap(); 37 | let mut carp = carp::carp::Carp::new(config, capture); 38 | carp.on_up(my_up_callback); 39 | carp.on_down(|| { 40 | println!("In my_down_callback()"); 41 | }); 42 | carp.run().unwrap(); 43 | } 44 | 45 | fn my_up_callback() 46 | { 47 | println!("In my_up_callback()"); 48 | } 49 | -------------------------------------------------------------------------------- /COPYING.OLD: -------------------------------------------------------------------------------- 1 | 2 | UCARP is covered by the following license : 3 | 4 | /* 5 | * Copyright (c) 2004-2015 Frank Denis with the help of all 6 | * contributors. 7 | * 8 | * Permission to use, copy, modify, and/or distribute this software for any 9 | * purpose with or without fee is hereby granted, provided that the above 10 | * copyright notice and this permission notice appear in all copies. 11 | * 12 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 13 | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 14 | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 15 | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 16 | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 17 | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 18 | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 19 | */ 20 | 21 | 22 | ------------------------------------------ 23 | 24 | 25 | Some code has been imported from the Pure-FTPd project. 26 | 27 | 28 | ------------------------------------------ 29 | 30 | 31 | 32 | The bsd-getopt_long.c and bsd-getopt_long.h source code is based upon the 33 | OpenBSD and NetBSD projects and it is covered by the BSD license. 34 | The carp.c and ip_carp.h files are derived from OpenBSD source code. 35 | The original license is enclosed at the beginning of the related files. 36 | -------------------------------------------------------------------------------- /src/advert.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 Herman J. Radtke III 2 | // 3 | // This file is part of carp-rs. 4 | // 5 | // carp-rs is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Lesser General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // carp-rs is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Lesser General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Lesser General Public License 16 | // along with carp-rs. If not, see . 17 | 18 | use byteorder; 19 | use net::ip::Ipv4Header; 20 | use net::ether::EtherHeader; 21 | use ip_carp::CarpHeader; 22 | 23 | /// A Carp packet 24 | /// 25 | /// Follows Ethernet Type II Frame structure 26 | #[derive(Debug)] 27 | #[repr(C, packed)] 28 | pub struct CarpPacket { 29 | ether_header: EtherHeader, 30 | pub ip: Ipv4Header, 31 | pub carp: CarpHeader, 32 | } 33 | 34 | impl CarpPacket { 35 | pub fn new(eh: EtherHeader, ip: Ipv4Header, ch: CarpHeader) -> CarpPacket { 36 | CarpPacket { 37 | ether_header: eh, 38 | ip: ip, 39 | carp: ch, 40 | } 41 | } 42 | 43 | pub fn into_bytes(&self) -> byteorder::Result> { 44 | let mut wtr: Vec = vec![]; 45 | 46 | let mut t = try!(self.ether_header.into_bytes()); 47 | wtr.append(&mut t); 48 | 49 | let mut t = try!(self.ip.into_bytes()); 50 | wtr.append(&mut t); 51 | 52 | let mut t = try!(self.carp.into_bytes()); 53 | wtr.append(&mut t); 54 | 55 | Ok(wtr) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 Herman J. Radtke III 2 | // 3 | // This file is part of carp-rs. 4 | // 5 | // carp-rs is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Lesser General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // carp-rs is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Lesser General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Lesser General Public License 16 | // along with carp-rs. If not, see . 17 | 18 | use std::io; 19 | use std::fmt; 20 | 21 | use byteorder; 22 | use nix; 23 | use pcap; 24 | 25 | #[derive(Debug)] 26 | pub enum Error { 27 | InvalidVirtualIp, 28 | InvalidMulticastIp, 29 | InvalidSourceIp, 30 | InvalidVirtualHardwareId, 31 | InvalidNetworkInterface, 32 | InvalidPassword, 33 | InvalidDeadRatio, 34 | InvalidUnknown, 35 | CarpFailure, 36 | Pcap(pcap::Error), 37 | Io(io::Error), 38 | ByteOrder(byteorder::Error), 39 | Nix(nix::Error), 40 | } 41 | 42 | impl fmt::Display for Error { 43 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 44 | use self::Error::*; 45 | 46 | match *self { 47 | InvalidVirtualIp => write!(fmt, "InvalidVirtualIp"), 48 | InvalidMulticastIp => write!(fmt, "InvalidMulticastIp"), 49 | InvalidSourceIp => write!(fmt, "InvalidSourceIp"), 50 | InvalidVirtualHardwareId => write!(fmt, "InvalidVirtualHardwareId"), 51 | InvalidNetworkInterface => write!(fmt, "InvalidNetworkInterface"), 52 | InvalidPassword => write!(fmt, "InvalidPassword"), 53 | InvalidDeadRatio => write!(fmt, "InvalidDeadRatio"), 54 | InvalidUnknown => write!(fmt, "InvalidUnknown"), 55 | CarpFailure => write!(fmt, "CarpFailure"), 56 | Pcap(ref err) => write!(fmt, "{}", err), 57 | Io(ref err) => write!(fmt, "{}", err), 58 | ByteOrder(ref err) => write!(fmt, "{}", err), 59 | Nix(ref err) => write!(fmt, "{}", err), 60 | } 61 | } 62 | } 63 | 64 | impl From for Error { 65 | fn from(err: pcap::Error) -> Self { 66 | Error::Pcap(err) 67 | } 68 | } 69 | 70 | impl From for Error { 71 | fn from(err: io::Error) -> Self { 72 | Error::Io(err) 73 | } 74 | } 75 | 76 | impl From for Error { 77 | fn from(err: byteorder::Error) -> Self { 78 | Error::ByteOrder(err) 79 | } 80 | } 81 | 82 | impl From for Error { 83 | fn from(err: nix::Error) -> Self { 84 | Error::Nix(err) 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /tests/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate carp; 2 | 3 | #[macro_use] extern crate log; 4 | extern crate env_logger; 5 | 6 | use std::env; 7 | use std::str::FromStr; 8 | 9 | use carp::net::ip::{Ipv4Header, Ipv4HeaderBuilder, Flags, Tos, Protocol}; 10 | use carp::net::mac::HwAddr; 11 | use carp::net::ether::{EtherHeader, EtherType}; 12 | use carp::ip_carp::CarpHeader; 13 | use carp::advert::CarpPacket; 14 | use carp::carp::Carp; 15 | 16 | /// Tests for the primary selection process 17 | /// 18 | /// Note: integration tests have to be run with a privileged user capable of running pcap 19 | /// functions. 20 | 21 | fn setup(advbase: u8) -> Carp { 22 | 23 | let ip = env::var("TEST_SRCIP").unwrap_or("10.0.2.40".to_string()); 24 | debug!("srcip = {}", ip); 25 | 26 | let interface = env::var("TEST_INF").unwrap_or("eth3".to_string()); 27 | debug!("interface = {}", interface); 28 | 29 | let mut config = carp::config::Config::new( 30 | FromStr::from_str("10.0.2.100").unwrap(), 31 | FromStr::from_str(&ip).unwrap(), 32 | "secret" 33 | ); 34 | config.set_interface(interface.as_ref()); 35 | config.set_advbase(advbase); 36 | config.set_advskew(0); 37 | config.set_preempt(true); 38 | let capture = carp::carp::Carp::default_pcap(&interface).unwrap(); 39 | let mut carp = carp::carp::Carp::new(config, capture); 40 | carp.setup().unwrap(); 41 | 42 | carp 43 | } 44 | 45 | fn setup_ether_header() -> EtherHeader { 46 | let shost = HwAddr::new(0x08, 0x00, 0x27, 0xc0, 0xee, 0xbe); 47 | let dhost = HwAddr::new(0x08, 0x00, 0x27, 0xf4, 0x18, 0xd5); 48 | EtherHeader::new(&dhost, &shost, EtherType::Ip) 49 | } 50 | 51 | fn setup_ipv4_header(source: &str) -> Ipv4Header { 52 | Ipv4HeaderBuilder::new() 53 | .tos(Tos::low_delay()) 54 | .data_length(20) 55 | .random_id() 56 | .flags(Flags::dont_fragment()) 57 | .ttl(255) 58 | .protocol(Protocol::Carp) 59 | .source_address(FromStr::from_str(source).unwrap()) 60 | .destination_address(FromStr::from_str("127.0.0.1").unwrap()) 61 | .build() 62 | } 63 | 64 | fn setup_carp_header(advbase: u8) -> CarpHeader { 65 | let mut ch = CarpHeader::default(); 66 | ch.carp_advbase = advbase; 67 | ch 68 | } 69 | 70 | fn force_primary(carp: &mut Carp) { 71 | loop { 72 | carp.run_once().unwrap(); 73 | 74 | if carp.is_primary() { 75 | break; 76 | } 77 | } 78 | } 79 | 80 | #[test] 81 | fn test_role_is_backup_on_init() { 82 | let carp = setup(1); 83 | 84 | assert!(carp.is_backup()); 85 | } 86 | 87 | #[test] 88 | fn test_role_change_primary_on_timeout() { 89 | let mut carp = setup(1); 90 | 91 | force_primary(&mut carp); 92 | 93 | assert!(carp.is_primary()); 94 | } 95 | 96 | #[test] 97 | fn test_role_change_backup_if_larger_advert_base() { 98 | let cp = CarpPacket::new( 99 | setup_ether_header(), 100 | setup_ipv4_header("10.0.0.2"), 101 | setup_carp_header(1) 102 | ); 103 | 104 | let mut carp = setup(2); 105 | 106 | force_primary(&mut carp); 107 | 108 | carp.check_role_change(&cp); 109 | 110 | assert!(carp.is_backup()); 111 | } 112 | 113 | #[test] 114 | fn test_role_change_primary_if_shorter_advert_base() { 115 | let cp = CarpPacket::new( 116 | setup_ether_header(), 117 | setup_ipv4_header("10.0.0.2"), 118 | setup_carp_header(2) 119 | ); 120 | 121 | let mut carp = setup(1); 122 | 123 | carp.check_role_change(&cp); 124 | 125 | assert!(carp.is_primary()); 126 | } 127 | 128 | #[test] 129 | fn test_role_change_backup_if_equal_advbase_higher_ip() { 130 | let cp = CarpPacket::new( 131 | setup_ether_header(), 132 | setup_ipv4_header("10.0.0.2"), 133 | setup_carp_header(1) 134 | ); 135 | 136 | let mut carp = setup(1); 137 | 138 | force_primary(&mut carp); 139 | 140 | assert!(carp.is_primary()); 141 | 142 | carp.check_role_change(&cp); 143 | 144 | assert!(carp.is_backup()); 145 | } 146 | 147 | #[test] 148 | fn test_role_stay_primary_if_equal_advbase_lower_ip() { 149 | //env_logger::init().ok().expect("Failed to init logger"); 150 | let cp = CarpPacket::new( 151 | setup_ether_header(), 152 | setup_ipv4_header("10.244.244.244"), 153 | setup_carp_header(1) 154 | ); 155 | 156 | let mut carp = setup(1); 157 | 158 | force_primary(&mut carp); 159 | 160 | assert!(carp.is_primary()); 161 | 162 | carp.check_role_change(&cp); 163 | 164 | assert!(carp.is_primary()); 165 | } 166 | -------------------------------------------------------------------------------- /src/net/ether.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 Herman J. Radtke III 2 | // 3 | // This file is part of carp-rs. 4 | // 5 | // carp-rs is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Lesser General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // carp-rs is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Lesser General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Lesser General Public License 16 | // along with carp-rs. If not, see . 17 | 18 | use libc::{uint8_t, uint16_t}; 19 | 20 | use std::io::Cursor; 21 | use byteorder::{self, BigEndian, ReadBytesExt, WriteBytesExt}; 22 | 23 | use net::mac::HwAddr; 24 | 25 | pub const ETH_ALEN: usize = 6; 26 | 27 | /// Ethernet frame types 28 | pub enum EtherType { 29 | Ip = 0x0800, 30 | Arp = 0x0806, 31 | } 32 | 33 | /// Ethernet header 34 | /// 35 | /// Follows Ethernet Type II Frame structure 36 | #[derive(Debug, Eq, PartialEq)] 37 | #[repr(C, packed)] 38 | pub struct EtherHeader { 39 | /// Destination hardware (MAC) address 40 | ether_dhost: [uint8_t; ETH_ALEN], 41 | 42 | /// Source hardware (MAC) address 43 | ether_shost: [uint8_t; ETH_ALEN], 44 | 45 | /// packet type ID field 46 | ether_type: uint16_t, 47 | } 48 | 49 | impl EtherHeader { 50 | pub fn new(dhost: &HwAddr, shost: &HwAddr, type_: EtherType) -> EtherHeader { 51 | EtherHeader { 52 | ether_dhost: dhost.octets(), 53 | ether_shost: shost.octets(), 54 | ether_type: type_ as uint16_t, 55 | } 56 | } 57 | 58 | pub fn from_bytes(data: &[u8]) -> byteorder::Result { 59 | let mut rdr = Cursor::new(data); 60 | 61 | let ether_dhost = [try!(rdr.read_u8()), 62 | try!(rdr.read_u8()), 63 | try!(rdr.read_u8()), 64 | try!(rdr.read_u8()), 65 | try!(rdr.read_u8()), 66 | try!(rdr.read_u8())]; 67 | 68 | let ether_shost = [try!(rdr.read_u8()), 69 | try!(rdr.read_u8()), 70 | try!(rdr.read_u8()), 71 | try!(rdr.read_u8()), 72 | try!(rdr.read_u8()), 73 | try!(rdr.read_u8())]; 74 | 75 | let ether_type = try!(rdr.read_u16::()); 76 | 77 | Ok(EtherHeader { 78 | ether_dhost: ether_dhost, 79 | ether_shost: ether_shost, 80 | ether_type: ether_type, 81 | }) 82 | } 83 | 84 | pub fn into_bytes(&self) -> byteorder::Result> { 85 | let mut wtr = vec![]; 86 | 87 | for i in self.ether_dhost.iter() { 88 | try!(wtr.write_u8(*i)); 89 | } 90 | 91 | for i in self.ether_shost.iter() { 92 | try!(wtr.write_u8(*i)); 93 | } 94 | 95 | try!(wtr.write_u16::(self.ether_type)); 96 | 97 | Ok(wtr) 98 | } 99 | } 100 | 101 | #[cfg(test)] 102 | mod test { 103 | 104 | use libc::{uint8_t, uint16_t}; 105 | use super::*; 106 | 107 | #[test] 108 | fn test_from_bytes() { 109 | let bytes: [uint8_t; 14] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x5e, 0x00, 110 | 0x00, 0x01, 0x08, 0x00]; 111 | 112 | let eh = EtherHeader::from_bytes(&bytes).unwrap(); 113 | 114 | let shost: [uint8_t; ETH_ALEN] = [0x00, 0x00, 0x5e, 0x00, 0x00, 0x01]; 115 | 116 | let dhost: [uint8_t; ETH_ALEN] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; 117 | 118 | let expected = EtherHeader { 119 | ether_dhost: dhost, 120 | ether_shost: shost, 121 | ether_type: EtherType::Ip as uint16_t, 122 | }; 123 | 124 | assert_eq!(expected, eh); 125 | } 126 | 127 | #[test] 128 | fn test_into_bytes() { 129 | let shost: [uint8_t; ETH_ALEN] = [0x00, 0x00, 0x5e, 0x00, 0x00, 0x01]; 130 | 131 | let dhost: [uint8_t; ETH_ALEN] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; 132 | 133 | let eh = EtherHeader { 134 | ether_dhost: dhost, 135 | ether_shost: shost, 136 | ether_type: EtherType::Ip as uint16_t, 137 | }; 138 | 139 | let bytes = eh.into_bytes().unwrap(); 140 | 141 | let expected: [uint8_t; 14] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x5e, 0x00, 142 | 0x00, 0x01, 0x08, 0x00]; 143 | 144 | assert_eq!(expected, bytes[..]); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 Herman J. Radtke III 2 | // 3 | // This file is part of carp-rs. 4 | // 5 | // carp-rs is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Lesser General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // carp-rs is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Lesser General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Lesser General Public License 16 | // along with carp-rs. If not, see . 17 | 18 | use std::net::IpAddr; 19 | use std::str::FromStr; 20 | 21 | /// Configuration options for CARP 22 | #[derive(Debug)] 23 | pub struct Config { 24 | /// Virtual shared IP address 25 | /// 26 | /// This is the value that will be dynamically answered by one alive host. 27 | pub vaddr: IpAddr, 28 | 29 | /// Real IP address of the host 30 | pub srcip: IpAddr, 31 | 32 | /// Virtual IP identifier. Must be between 1-255 33 | /// 34 | /// The virtual IP identifier field only is only eight bits, providing up 35 | /// to 255 different virtual IPs on the same multicast group IP. For larger 36 | /// deployments, and more flexibility in allocation, ucarp can optionally 37 | /// use a different multicast IP. 38 | pub vhid: u8, 39 | 40 | /// Password used to encrypt CARP messages 41 | /// 42 | /// This password will never be sent in plaintext over the network. 43 | pub password: String, 44 | 45 | /// Advertisement base (in seconds) 46 | pub advbase: u8, 47 | 48 | /// Advertisement skew. Must be between 1-255 49 | pub advskew: u8, 50 | 51 | /// Ratio to consider host as dead. Default is 3. 52 | /// 53 | /// This ratio changes how long a backup server will wait for an 54 | /// unresponsive primary before considering it as dead, and becoming the 55 | /// new primary. In the original protocol, the ratio is 3. 56 | pub dead_ratio: u32, 57 | 58 | /// Bind interface. 59 | /// 60 | /// Defaults to using `pcap_lookupdev` to find the default device on which 61 | /// to capture. 62 | pub interface: Option, 63 | 64 | /// Multicast group IP address (default 224.0.0.18). 65 | /// 66 | /// This is how servers will send and receive CARP messages. By default, 67 | /// carp will send/listen on 224.0.0.18, which is the assigned IP for VRRP. 68 | /// Consult the [IPv4 Multicast Address Space Registry](http://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml) 69 | /// before deciding to use a different one. 70 | /// 71 | /// Other useful links: 72 | /// http://tools.ietf.org/html/rfc5771 73 | /// http://tools.ietf.org/html/rfc2365 74 | /// 75 | /// Addresses within 239.192.0.0/14 should be most appropriate. 76 | /// 77 | /// If carp isn't working on a different IP, check that your networking gear is 78 | /// set up to handle it. tcpdump on each host can be handy for diagnosis: 79 | /// 80 | /// tcpdump -n 'net 224.0.0.0/4' 81 | pub mcast: IpAddr, 82 | 83 | /// Become master as soon as possible 84 | pub preempt: bool, 85 | 86 | /// Do not run `onShutdown` callback at start if in backup state 87 | pub neutral: bool, 88 | 89 | /// Call `onShutdown` callback on exit if not in backup state 90 | pub shutdown_at_exit: bool, 91 | 92 | /// Ignore interface state (down, no carrier). 93 | /// 94 | /// This option tells CARP to ignore unplugged network cable. It is useful 95 | /// when you connect ucarp nodes with a crossover patch cord (not via a hub 96 | /// or a switch). Without this option the node in MASTER state will switch 97 | /// to BACKUP state when the other node is powered down, because network 98 | /// interface shows that cable is unplugged (NO-CARRIER). Some network interface 99 | /// drivers don't support NO-CARRIER feature, and this option is not needed for 100 | /// these network cards. The card that definitely supports this feature is 101 | /// Realtek 8139. 102 | pub ignoreifstate: bool, 103 | 104 | /// Use broadcast (instead of multicast) advertisements 105 | pub no_mcast: bool, 106 | } 107 | 108 | // facility: CString, // type? 109 | 110 | impl Config { 111 | pub fn new(vaddr: IpAddr, srcip: IpAddr, password: S) -> Config 112 | where S: Into 113 | { 114 | Config { 115 | vaddr: vaddr, 116 | srcip: srcip, 117 | vhid: 1, 118 | password: password.into(), 119 | advbase: 1, 120 | advskew: 0, 121 | dead_ratio: 3, 122 | interface: None, 123 | mcast: FromStr::from_str("224.0.0.18").unwrap(), 124 | preempt: false, 125 | neutral: false, 126 | shutdown_at_exit: false, 127 | ignoreifstate: false, 128 | no_mcast: false, 129 | } 130 | } 131 | 132 | pub fn set_password(&mut self, password: S) 133 | where S: Into 134 | { 135 | self.password = password.into(); 136 | } 137 | 138 | pub fn set_interface(&mut self, interface: S) 139 | where S: Into 140 | { 141 | self.interface = Some(interface.into()); 142 | } 143 | 144 | pub fn set_advbase(&mut self, advbase: u8) { 145 | self.advbase = advbase; 146 | } 147 | 148 | pub fn set_advskew(&mut self, advskew: u8) { 149 | self.advskew = advskew; 150 | } 151 | 152 | pub fn set_preempt(&mut self, preempt: bool) { 153 | self.preempt = preempt; 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Common Address Redundancy Protocol 2 | 3 | carp-rs allows a couple of hosts to share common virtual IP addresses in order 4 | to provide automatic failover. It is a portable userland implementation of the 5 | secure and patent-free Common Address Redundancy Protocol (CARP, OpenBSD's 6 | alternative to the patents-bloated VRRP). 7 | 8 | Strong points of the CARP protocol are: very low overhead, cryptographically 9 | signed messages, interoperability between different operating systems and no 10 | need for any dedicated extra network link between redundant hosts. 11 | 12 | This project has been forked from https://github.com/jedisct1/UCarp and 13 | relicensed under the LGPL. The original BSD license has been moved to 14 | the COPYING.OLD file. 15 | 16 | [![Build Status](https://travis-ci.org/hjr3/carp-rs.svg?branch=master)](https://travis-ci.org/hjr3/carp-rs) 17 | 18 | ## Compilation 19 | 20 | * libpcap (http://www.tcpdump.org/) must be installed on your system, with 21 | development files (headers). 22 | * On Ubuntu: `apt-get install libtool autoconf gettext libpcap0.8 libpcap0.8-dev libpcap-dev sqlite3 libsqlite3-dev` 23 | 24 | The Rust library has only been tested with Ubuntu precise 64. 25 | 26 | ## Examples 27 | 28 | There is a basic example at `examples/basic.rs`. To run this example: 29 | 30 | ``` 31 | sudo RUST_LOG=carp=debug cargo run --example basic -- -i eth3 -s 10.0.2.40 32 | ``` 33 | 34 | Note: carp uses the pcap library which requires root for certain operations. 35 | 36 | You should see some output similar to: 37 | 38 | ``` 39 | INFO:carp::carp: Using [eth3] as a network interface 40 | INFO:carp::carp: Local advertised ethernet address is [08:00:27:f4:18:d5] 41 | DEBUG:carp::carp: srcip = 10.0.2.40 42 | DEBUG:carp::carp: mcast = 224.0.0.18 43 | DEBUG:carp::carp: Next primary timeout in SystemTime { tv_sec: 1461942434, tv_nsec: 156471873 } 44 | DEBUG:carp::carp: Interface switched to running 45 | DEBUG:carp::carp: Next primary timeout in SystemTime { tv_sec: 1461942434, tv_nsec: 157813524 } 46 | INFO:carp::carp: Remote primary down. Switching to Primary state 47 | In my_up_callback() 48 | DEBUG:carp::carp: Next primary timeout in SystemTime { tv_sec: 1461942435, tv_nsec: 177767553 } 49 | ``` 50 | 51 | 52 | ## Primary Selection Process 53 | 54 | When carp first runs, it starts as a backup and listens to the network 55 | to determine if it should become the primary. If at any time more than 56 | three times the node's advertising interval (defined as the advertising 57 | base (seconds) plus a fudge factor, the advertising skew) passes without 58 | hearing a peer's CARP advertisement, the node will transition itself to 59 | being a primary. 60 | 61 | Transitioning from backup to primary means: 62 | 63 | 1. Calling the specified callback to assign the vip to the local system. 64 | 2. Sending a gratuitous arp to the network to claim the vip. 65 | 3. Continuously sending CARP advertisements to the network every interval. 66 | 67 | Transitioning from primary to backup means: 68 | 69 | 1. Calling the specified callback to remove the vip from the local system 70 | 71 | To understand how carp works, it's important to note that the 72 | advertisement interval is not only used as the time in between which 73 | each CARP advertisement is sent by the primary, but also as a priority 74 | mechanism where shorter (i.e. more frequent) is better. The interval 75 | base and skew values are stored in the CARP advertisement and are used 76 | by other nodes to make certain decisions. 77 | 78 | By default, once a node becomes the primary, it will continue on 79 | indefinitely as the primary. If you like/want/need this behavior, or don't 80 | have a preferred primary, then choose the same interval on all hosts. 81 | If for whatever reason you were to choose different intervals on the 82 | hosts, then over time the one with the shortest interval would tend to 83 | become the primary as machines are rebooted, after failures, etc. 84 | 85 | Also of note is a conflict resolution algorithm that in case a primary 86 | hears another, equal (in terms of its advertised interval) primary, the 87 | one with the lower IP address will remain primary and the other will 88 | immediately demote itself. This is simply to eliminate flapping and 89 | quickly determine who should remain primary. This situation should not 90 | happen very often but it can. 91 | 92 | If you want a "preferred" primary to always be the primary (even if another 93 | host is already the primary), add the preempt switch and 94 | assign a shorter interval via the advertisement base and 95 | skew. This will cause the preferred node to ignore a 96 | primary who is advertising a longer interval and promote itself to primary. 97 | The old primary will quickly hear the preferred node advertising a shorter 98 | interval and immediately demote itself. 99 | 100 | In summary, a backup will become primary if: 101 | 102 | * no one else advertises for 3 times its own advertisement interval 103 | * you specified --preempt and it hears a primary with a longer interval 104 | 105 | and a primary will become backup if: 106 | 107 | * another primary advertises a shorter interval 108 | * another primary advertises the same interval, and has a lower IP address 109 | 110 | ## Original Authors 111 | 112 | The carp-rs project is based upon the hard work of many people on the original UCarp project. 113 | 114 | * Frank DENIS 115 | * Eric Evans - maintainer of Debian packages. 116 | * David H - maintainer of Fink packages. 117 | * Richard Bellamy - helped a lot with Solaris portability. 118 | * Russell Mosemann - neutral mode and bug fixes. 119 | * Dean Gaudet - EINTR handling, log exec errors, --passfile. 120 | * Steve Kehlet and Marcus Goller - fixed the bogus code that issued poisonous 121 | gratuitous ARP, and improved the behavior when multiple nodes are started 122 | with the same interval and skew. Steve helped a lot on many things. 123 | * Tim Niemeyer - Ensure remastering works when the 124 | preferred master has its network connection flap. 125 | * Serve Sireskin - --ignoreifstate option. 126 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | [root] 2 | name = "carp" 3 | version = "0.1.0" 4 | dependencies = [ 5 | "byteorder 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", 6 | "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", 7 | "getopts 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", 8 | "libc 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", 9 | "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", 10 | "nix 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", 11 | "pcap 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", 12 | "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", 13 | "rust-crypto 0.2.35 (registry+https://github.com/rust-lang/crates.io-index)", 14 | ] 15 | 16 | [[package]] 17 | name = "aho-corasick" 18 | version = "0.5.1" 19 | source = "registry+https://github.com/rust-lang/crates.io-index" 20 | dependencies = [ 21 | "memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", 22 | ] 23 | 24 | [[package]] 25 | name = "bitflags" 26 | version = "0.4.0" 27 | source = "registry+https://github.com/rust-lang/crates.io-index" 28 | 29 | [[package]] 30 | name = "byteorder" 31 | version = "0.4.2" 32 | source = "registry+https://github.com/rust-lang/crates.io-index" 33 | 34 | [[package]] 35 | name = "env_logger" 36 | version = "0.3.3" 37 | source = "registry+https://github.com/rust-lang/crates.io-index" 38 | dependencies = [ 39 | "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", 40 | "regex 0.1.66 (registry+https://github.com/rust-lang/crates.io-index)", 41 | ] 42 | 43 | [[package]] 44 | name = "gcc" 45 | version = "0.3.27" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | 48 | [[package]] 49 | name = "getopts" 50 | version = "0.2.14" 51 | source = "registry+https://github.com/rust-lang/crates.io-index" 52 | 53 | [[package]] 54 | name = "kernel32-sys" 55 | version = "0.2.2" 56 | source = "registry+https://github.com/rust-lang/crates.io-index" 57 | dependencies = [ 58 | "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", 59 | "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 60 | ] 61 | 62 | [[package]] 63 | name = "libc" 64 | version = "0.1.12" 65 | source = "registry+https://github.com/rust-lang/crates.io-index" 66 | 67 | [[package]] 68 | name = "libc" 69 | version = "0.2.10" 70 | source = "registry+https://github.com/rust-lang/crates.io-index" 71 | 72 | [[package]] 73 | name = "log" 74 | version = "0.3.6" 75 | source = "registry+https://github.com/rust-lang/crates.io-index" 76 | 77 | [[package]] 78 | name = "memchr" 79 | version = "0.1.11" 80 | source = "registry+https://github.com/rust-lang/crates.io-index" 81 | dependencies = [ 82 | "libc 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", 83 | ] 84 | 85 | [[package]] 86 | name = "nix" 87 | version = "0.5.0" 88 | source = "registry+https://github.com/rust-lang/crates.io-index" 89 | dependencies = [ 90 | "bitflags 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 91 | "libc 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", 92 | ] 93 | 94 | [[package]] 95 | name = "pcap" 96 | version = "0.5.5" 97 | source = "registry+https://github.com/rust-lang/crates.io-index" 98 | dependencies = [ 99 | "libc 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", 100 | ] 101 | 102 | [[package]] 103 | name = "rand" 104 | version = "0.3.14" 105 | source = "registry+https://github.com/rust-lang/crates.io-index" 106 | dependencies = [ 107 | "libc 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", 108 | ] 109 | 110 | [[package]] 111 | name = "regex" 112 | version = "0.1.66" 113 | source = "registry+https://github.com/rust-lang/crates.io-index" 114 | dependencies = [ 115 | "aho-corasick 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", 116 | "memchr 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)", 117 | "regex-syntax 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", 118 | "thread_local 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", 119 | "utf8-ranges 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", 120 | ] 121 | 122 | [[package]] 123 | name = "regex-syntax" 124 | version = "0.3.1" 125 | source = "registry+https://github.com/rust-lang/crates.io-index" 126 | 127 | [[package]] 128 | name = "rust-crypto" 129 | version = "0.2.35" 130 | source = "registry+https://github.com/rust-lang/crates.io-index" 131 | dependencies = [ 132 | "gcc 0.3.27 (registry+https://github.com/rust-lang/crates.io-index)", 133 | "libc 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", 134 | "rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", 135 | "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", 136 | "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", 137 | ] 138 | 139 | [[package]] 140 | name = "rustc-serialize" 141 | version = "0.3.19" 142 | source = "registry+https://github.com/rust-lang/crates.io-index" 143 | 144 | [[package]] 145 | name = "thread-id" 146 | version = "2.0.0" 147 | source = "registry+https://github.com/rust-lang/crates.io-index" 148 | dependencies = [ 149 | "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", 150 | "libc 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", 151 | ] 152 | 153 | [[package]] 154 | name = "thread_local" 155 | version = "0.2.3" 156 | source = "registry+https://github.com/rust-lang/crates.io-index" 157 | dependencies = [ 158 | "thread-id 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", 159 | "unreachable 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 160 | ] 161 | 162 | [[package]] 163 | name = "time" 164 | version = "0.1.35" 165 | source = "registry+https://github.com/rust-lang/crates.io-index" 166 | dependencies = [ 167 | "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", 168 | "libc 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", 169 | "winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", 170 | ] 171 | 172 | [[package]] 173 | name = "unreachable" 174 | version = "0.1.1" 175 | source = "registry+https://github.com/rust-lang/crates.io-index" 176 | dependencies = [ 177 | "void 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", 178 | ] 179 | 180 | [[package]] 181 | name = "utf8-ranges" 182 | version = "0.1.3" 183 | source = "registry+https://github.com/rust-lang/crates.io-index" 184 | 185 | [[package]] 186 | name = "void" 187 | version = "1.0.1" 188 | source = "registry+https://github.com/rust-lang/crates.io-index" 189 | 190 | [[package]] 191 | name = "winapi" 192 | version = "0.2.6" 193 | source = "registry+https://github.com/rust-lang/crates.io-index" 194 | 195 | [[package]] 196 | name = "winapi-build" 197 | version = "0.1.1" 198 | source = "registry+https://github.com/rust-lang/crates.io-index" 199 | 200 | -------------------------------------------------------------------------------- /src/net/arp.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 Herman J. Radtke III 2 | // 3 | // This file is part of carp-rs. 4 | // 5 | // carp-rs is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Lesser General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // carp-rs is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Lesser General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Lesser General Public License 16 | // along with carp-rs. If not, see . 17 | 18 | use std::io::{self, Error, ErrorKind}; 19 | use std::mem::size_of; 20 | use std::net::Ipv4Addr; 21 | use libc::{sockaddr, sockaddr_ll, AF_PACKET, uint8_t, uint16_t, c_void, c_int}; 22 | use nix::sys::socket::{socket, SockType, SockFlag, AddressFamily}; 23 | use net::mac::{HwIf, HwAddr}; 24 | 25 | const ETH_ALEN: usize = 6; 26 | const ETH_P_ARP: c_int = 0x0806; 27 | 28 | /// Ethernet frame types 29 | enum EtherType { 30 | Arp = 0x0806, 31 | } 32 | 33 | pub enum ArpOp { 34 | Request = 1, 35 | Reply = 2, 36 | } 37 | 38 | /// An Arp packet 39 | /// 40 | /// Follows Ethernet Type II Frame structure 41 | #[derive(Debug)] 42 | #[repr(C, packed)] 43 | struct ArpPacket { 44 | /// Destination hardware (MAC) address 45 | ether_dhost: [uint8_t; ETH_ALEN], 46 | 47 | /// Source hardware (MAC) address 48 | ether_shost: [uint8_t; ETH_ALEN], 49 | 50 | /// packet type ID field 51 | ether_type: uint16_t, 52 | 53 | /// Hardware type 54 | /// 55 | /// This field specifies the network protocol type. Example: Ethernet is 1. 56 | htype: uint16_t, 57 | 58 | /// Protocol type 59 | /// 60 | /// This field specifies the internetwork protocol for which the ARP request is intended. 61 | ptype: uint16_t, 62 | 63 | /// Hardware length 64 | /// 65 | /// Length (in octets) of a hardware address. 66 | hlen: uint8_t, 67 | 68 | /// Protocol length 69 | /// 70 | /// Length (in octets) of addresses used in upper layer protocol (ptype). 71 | plen: uint8_t, 72 | 73 | /// Operation 74 | /// 75 | /// Specifies the operation that the sender is performing: 1 for request, 2 for reply. 76 | operation: uint16_t, 77 | 78 | /// Sender hardware address 79 | /// 80 | /// Media address of the sender. In an ARP request this field is used to indicate the address 81 | /// of the host sending the request. In an ARP reply this field is used to indicate the address 82 | /// of the host that the request was looking for. (Not necessarily address of the host replying 83 | /// as in the case of virtual media.) Note that switches do not pay attention to this field, 84 | /// particularly in learning MAC addresses. The ARP PDU is encapsulated in Ethernet frame, and 85 | /// that is what Layer 2 devices examine. 86 | sender_hw_addr: [uint8_t; 6], 87 | 88 | /// Sender protocol address 89 | /// 90 | /// Internetwork address of the sender. 91 | sender_proto_addr: [uint8_t; 4], 92 | 93 | /// Target hardware address 94 | /// 95 | /// Media address of the intended receiver. In an ARP request this field is ignored. In an ARP 96 | /// reply this field is used to indicate the address of the host that originated the ARP 97 | /// request. 98 | target_hw_addr: [uint8_t; 6], 99 | 100 | /// Target protocol address 101 | /// 102 | /// Internetwork address of the intended receiver. 103 | target_proto_addr: [uint8_t; 4], 104 | 105 | _padding: [uint8_t; 18], 106 | } 107 | 108 | impl ArpPacket { 109 | fn new(sender_hw_addr: &HwAddr, 110 | sender_proto_addr: &Ipv4Addr, 111 | target_hw_addr: &HwAddr, 112 | target_proto_addr: &Ipv4Addr, 113 | operation: ArpOp, 114 | ether_type: EtherType) 115 | -> ArpPacket { 116 | 117 | ArpPacket { 118 | ether_dhost: target_hw_addr.octets(), 119 | ether_shost: sender_hw_addr.octets(), 120 | ether_type: (ether_type as u16).to_be(), 121 | htype: (1 as u16).to_be(), // ethernet 122 | ptype: (0x0800 as u16).to_be(), // IPv4 123 | hlen: 6, // ethernet 124 | plen: 4, 125 | operation: (operation as u16).to_be(), 126 | sender_hw_addr: sender_hw_addr.octets(), 127 | sender_proto_addr: sender_proto_addr.octets(), 128 | target_hw_addr: target_hw_addr.octets(), 129 | target_proto_addr: target_proto_addr.octets(), 130 | _padding: [0; 18], 131 | } 132 | } 133 | } 134 | 135 | /// Update ARP tables on other machines 136 | /// 137 | /// See: https://wiki.wireshark.org/Gratuitous_ARP 138 | pub fn gratuitous_arp(if_name: &str, ip: Ipv4Addr) -> io::Result<()> { 139 | 140 | let hw_if = HwIf::new(if_name); 141 | 142 | let mac = try!(hw_if.hwaddr()); 143 | let idx = try!(hw_if.index()); 144 | 145 | let fd = try!(socket(AddressFamily::Packet, 146 | SockType::Raw, 147 | SockFlag::empty(), 148 | ETH_P_ARP.to_be())); 149 | 150 | if fd == -1 { 151 | return Err(Error::last_os_error()); 152 | } 153 | 154 | let sa = Box::new(sockaddr_ll { 155 | sll_family: AF_PACKET as u16, 156 | sll_protocol: (ETH_P_ARP as u16).to_be(), 157 | sll_ifindex: idx, 158 | sll_hatype: 0, 159 | sll_pkttype: 0, 160 | sll_halen: 0, 161 | sll_addr: [0; 8], 162 | }); 163 | 164 | let broadcast_mac = HwAddr::new(0xff, 0xff, 0xff, 0xff, 0xff, 0xff); 165 | 166 | let frame = Box::new(ArpPacket::new(&mac, 167 | &ip, 168 | &broadcast_mac, 169 | &ip, 170 | ArpOp::Request, 171 | EtherType::Arp)); 172 | 173 | let f = &*frame as *const _ as *const c_void; 174 | let flen = size_of::(); 175 | let s = &*sa as *const _ as *const sockaddr; 176 | let slen = size_of::() as u32; 177 | 178 | loop { 179 | let rc = ffi::sendto(fd, f, flen, 0, s, slen); 180 | 181 | if rc >= 0 { 182 | break; 183 | } 184 | 185 | if rc < 0 { 186 | let err = Error::last_os_error(); 187 | match err.kind() { 188 | ErrorKind::Interrupted => {} 189 | _ => { 190 | return Err(err); 191 | } 192 | } 193 | } 194 | } 195 | 196 | Ok(()) 197 | } 198 | 199 | mod ffi { 200 | use std::os::unix::io::RawFd; 201 | use libc::{self, sockaddr, c_void, c_int, size_t, ssize_t, socklen_t}; 202 | 203 | // not using the nix sendto as it will take some work to make it compatible. 204 | pub fn sendto(fd: RawFd, 205 | buf: *const c_void, 206 | blen: size_t, 207 | flags: c_int, 208 | socket: *const sockaddr, 209 | slen: socklen_t) 210 | -> ssize_t { 211 | unsafe { libc::sendto(fd, buf, blen, flags, socket, slen) } 212 | } 213 | } 214 | 215 | #[cfg(test)] 216 | mod test { 217 | 218 | use super::*; 219 | 220 | #[test] 221 | fn test_gratuitous_arp() { 222 | 223 | let device = "eth0"; 224 | let ip = "10.0.2.15".parse().unwrap(); 225 | 226 | assert!(gratuitous_arp(device, ip).is_ok()); 227 | } 228 | } 229 | -------------------------------------------------------------------------------- /src/node.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 Herman J. Radtke III 2 | // 3 | // This file is part of carp-rs. 4 | // 5 | // carp-rs is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Lesser General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // carp-rs is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Lesser General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Lesser General Public License 16 | // along with carp-rs. If not, see . 17 | 18 | use std::cmp::Ordering; 19 | use std::net::IpAddr; 20 | use std::time::Duration; 21 | 22 | #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] 23 | pub enum Role { 24 | Primary, 25 | Backup, 26 | } 27 | 28 | /// Whether to become a primary node as soon as possible 29 | #[derive(Debug, Eq, PartialEq)] 30 | pub enum Alignment { 31 | Passive, 32 | Aggressive, 33 | } 34 | 35 | /// A CARP node 36 | /// 37 | /// The node can be local or remote 38 | #[derive(Debug, Eq, PartialEq)] 39 | pub struct Node { 40 | /// Role of the node 41 | pub role: Role, 42 | 43 | /// Advertisement frequency 44 | /// 45 | /// Lower is more frequent 46 | pub adv_freq: Duration, 47 | 48 | /// IP address of the node 49 | /// 50 | /// This is used to break ties when determine roles 51 | pub ip: IpAddr, 52 | } 53 | 54 | impl Node { 55 | pub fn new(role: Role, adv_freq: Duration, ip: IpAddr) -> Node { 56 | Node { 57 | role: role, 58 | adv_freq: adv_freq, 59 | ip: ip, 60 | } 61 | } 62 | 63 | /// Compare another node to determine if a role change is required 64 | /// 65 | /// A passive node will only become primary when another primary node times out 66 | pub fn role_change(&self, other: &Self, alignment: Alignment) -> Role { 67 | match self.role { 68 | Role::Primary => { 69 | if self > other { 70 | Role::Backup 71 | } else { 72 | Role::Primary 73 | } 74 | } 75 | Role::Backup => { 76 | if alignment == Alignment::Aggressive && self < other { 77 | Role::Primary 78 | } else { 79 | Role::Backup 80 | } 81 | } 82 | } 83 | } 84 | } 85 | 86 | impl PartialOrd for Node { 87 | fn partial_cmp(&self, other: &Self) -> Option { 88 | if self.adv_freq == other.adv_freq { 89 | Some(match self.ip.cmp(&other.ip) { 90 | Ordering::Less => Ordering::Less, 91 | Ordering::Greater => Ordering::Greater, 92 | Ordering::Equal => Ordering::Less, 93 | }) 94 | 95 | } else { 96 | Some(self.adv_freq.cmp(&other.adv_freq)) 97 | } 98 | } 99 | } 100 | 101 | impl Ord for Node { 102 | fn cmp(&self, other: &Self) -> Ordering { 103 | self.partial_cmp(other).unwrap() 104 | } 105 | } 106 | 107 | #[cfg(test)] 108 | mod tests { 109 | use std::cmp::Ordering; 110 | use std::time::Duration; 111 | 112 | use super::*; 113 | 114 | #[test] 115 | fn test_primary_role_change() { 116 | let node = Node::new(Role::Primary, 117 | Duration::from_secs(2), 118 | "10.0.0.2".parse().unwrap()); 119 | let other = Node::new(Role::Primary, 120 | Duration::from_secs(1), 121 | "10.0.0.1".parse().unwrap()); 122 | 123 | assert_eq!(Role::Backup, node.role_change(&other, Alignment::Passive)); 124 | 125 | let node = Node::new(Role::Primary, 126 | Duration::from_secs(1), 127 | "10.0.0.1".parse().unwrap()); 128 | let other = Node::new(Role::Primary, 129 | Duration::from_secs(1), 130 | "10.0.0.2".parse().unwrap()); 131 | 132 | assert_eq!(Role::Primary, node.role_change(&other, Alignment::Passive)); 133 | 134 | let node = Node::new(Role::Primary, 135 | Duration::from_secs(1), 136 | "10.0.0.2".parse().unwrap()); 137 | let other = Node::new(Role::Primary, 138 | Duration::from_secs(1), 139 | "10.0.0.1".parse().unwrap()); 140 | 141 | assert_eq!(Role::Backup, node.role_change(&other, Alignment::Passive)); 142 | } 143 | 144 | #[test] 145 | fn test_backup_role_change() { 146 | let node = Node::new(Role::Backup, 147 | Duration::from_secs(1), 148 | "10.0.0.1".parse().unwrap()); 149 | let other = Node::new(Role::Backup, 150 | Duration::from_secs(2), 151 | "10.0.0.2".parse().unwrap()); 152 | 153 | assert_eq!(Role::Primary, 154 | node.role_change(&other, Alignment::Aggressive)); 155 | 156 | let node = Node::new(Role::Backup, 157 | Duration::from_secs(1), 158 | "10.0.0.1".parse().unwrap()); 159 | let other = Node::new(Role::Backup, 160 | Duration::from_secs(1), 161 | "10.0.0.2".parse().unwrap()); 162 | 163 | assert_eq!(Role::Primary, 164 | node.role_change(&other, Alignment::Aggressive)); 165 | 166 | let node = Node::new(Role::Backup, 167 | Duration::from_secs(1), 168 | "10.0.0.1".parse().unwrap()); 169 | let other = Node::new(Role::Backup, 170 | Duration::from_secs(2), 171 | "10.0.0.2".parse().unwrap()); 172 | 173 | assert_eq!(Role::Backup, node.role_change(&other, Alignment::Passive)); 174 | } 175 | 176 | #[test] 177 | fn test_cmp_less() { 178 | let node = Node::new(Role::Backup, 179 | Duration::from_secs(1), 180 | "10.0.0.2".parse().unwrap()); 181 | let other = Node::new(Role::Backup, 182 | Duration::from_secs(2), 183 | "10.0.0.1".parse().unwrap()); 184 | let given = node.cmp(&other); 185 | assert_eq!(Ordering::Less, given); 186 | 187 | let node = Node::new(Role::Backup, 188 | Duration::from_secs(1), 189 | "10.0.0.2".parse().unwrap()); 190 | let other = Node::new(Role::Backup, 191 | Duration::from_secs(1), 192 | "10.0.0.1".parse().unwrap()); 193 | let given = node.cmp(&other); 194 | assert_eq!(Ordering::Greater, given); 195 | } 196 | 197 | #[test] 198 | fn test_cmp_greater() { 199 | let node = Node::new(Role::Backup, 200 | Duration::from_secs(2), 201 | "10.0.0.1".parse().unwrap()); 202 | let other = Node::new(Role::Backup, 203 | Duration::from_secs(1), 204 | "10.0.0.2".parse().unwrap()); 205 | let given = node.cmp(&other); 206 | assert_eq!(Ordering::Greater, given); 207 | 208 | let node = Node::new(Role::Backup, 209 | Duration::from_secs(1), 210 | "10.0.0.1".parse().unwrap()); 211 | let other = Node::new(Role::Backup, 212 | Duration::from_secs(1), 213 | "10.0.0.2".parse().unwrap()); 214 | let given = node.cmp(&other); 215 | assert_eq!(Ordering::Less, given); 216 | } 217 | } 218 | -------------------------------------------------------------------------------- /COPYING.LESSER: -------------------------------------------------------------------------------- 1 | GNU LESSER 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 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /src/ip_carp.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 Herman J. Radtke III 2 | // 3 | // This file is part of carp-rs. 4 | // 5 | // carp-rs is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Lesser General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // carp-rs is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Lesser General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Lesser General Public License 16 | // along with carp-rs. If not, see . 17 | 18 | // The CARP header layout is as follows: 19 | // 20 | // 0 1 2 3 21 | // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 22 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 23 | // |Version| Type | VirtualHostID | AdvSkew | Auth Len | 24 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 25 | // | Reserved | AdvBase | Checksum | 26 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 27 | // | Counter (1) | 28 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 29 | // | Counter (2) | 30 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 31 | // | SHA-1 HMAC (1) | 32 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 33 | // | SHA-1 HMAC (2) | 34 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 35 | // | SHA-1 HMAC (3) | 36 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 37 | // | SHA-1 HMAC (4) | 38 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 39 | // | SHA-1 HMAC (5) | 40 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 41 | // 42 | // 43 | 44 | use libc::{c_uchar, uint8_t, uint16_t, uint64_t}; 45 | 46 | use std::io::{Read, Cursor}; 47 | use byteorder::{self, BigEndian, ReadBytesExt, WriteBytesExt}; 48 | 49 | /// CarpHeader 50 | /// 51 | /// The struct aims to keep the byte representation compatible with C. This allows for the use of 52 | /// `from_bytes` as a safe method and transmute for speed. Transmute is not supported at this time. 53 | /// I need to find a way to get ByteOrders API but not switch the endianness. 54 | #[derive(Debug, Default)] 55 | #[repr(C, packed)] 56 | pub struct CarpHeader { 57 | carp_version_type: uint8_t, 58 | 59 | /// Virtual host id 60 | pub carp_vhid: uint8_t, 61 | 62 | /// Advertisement skew 63 | pub carp_advskew: uint8_t, 64 | 65 | /// Size of counter+md, 32bit chunks 66 | pub carp_authlen: uint8_t, 67 | 68 | /// Reserved 69 | pub carp_pad1: uint8_t, 70 | 71 | /// Advertisement interval 72 | pub carp_advbase: uint8_t, 73 | 74 | carp_cksum: uint16_t, 75 | carp_counter: uint64_t, 76 | 77 | /// SHA1 HMAC 78 | pub carp_md: [c_uchar; 20], 79 | } 80 | 81 | impl CarpHeader { 82 | #[inline] 83 | pub fn version() -> uint8_t { 84 | 2 85 | } 86 | 87 | /// Type of CARP header to send 88 | #[inline] 89 | pub fn advertisement() -> uint8_t { 90 | 1 91 | } 92 | 93 | #[inline] 94 | pub fn authlen() -> uint8_t { 95 | 7 96 | } 97 | 98 | #[inline] 99 | pub fn ttl() -> uint8_t { 100 | 255 101 | } 102 | 103 | pub fn from_bytes(data: &[u8]) -> byteorder::Result { 104 | let mut rdr = Cursor::new(data); 105 | 106 | let carp_version_type = try!(rdr.read_u8()); 107 | let carp_vhid = try!(rdr.read_u8()); 108 | let carp_advskew = try!(rdr.read_u8()); 109 | let carp_authlen = try!(rdr.read_u8()); 110 | let carp_pad1 = try!(rdr.read_u8()); 111 | let carp_advbase = try!(rdr.read_u8()); 112 | let carp_cksum = try!(rdr.read_u16::()); 113 | let carp_counter = try!(rdr.read_u64::()); 114 | 115 | let mut carp_md: [c_uchar; 20] = [0; 20]; 116 | try!(rdr.read_exact(&mut carp_md)); 117 | 118 | Ok(CarpHeader { 119 | carp_version_type: carp_version_type, 120 | carp_vhid: carp_vhid, 121 | carp_advskew: carp_advskew, 122 | carp_authlen: carp_authlen, 123 | carp_pad1: carp_pad1, 124 | carp_advbase: carp_advbase, 125 | carp_cksum: carp_cksum, 126 | carp_counter: carp_counter, 127 | carp_md: carp_md, 128 | }) 129 | } 130 | 131 | pub fn into_bytes(&self) -> byteorder::Result> { 132 | let mut wtr = vec![]; 133 | 134 | try!(wtr.write_u8(self.carp_version_type)); 135 | try!(wtr.write_u8(self.carp_vhid)); 136 | try!(wtr.write_u8(self.carp_advskew)); 137 | try!(wtr.write_u8(self.carp_authlen)); 138 | try!(wtr.write_u8(self.carp_pad1)); 139 | try!(wtr.write_u8(self.carp_advbase)); 140 | try!(wtr.write_u16::(self.carp_cksum)); 141 | try!(wtr.write_u64::(self.carp_counter)); 142 | 143 | for i in self.carp_md.iter() { 144 | try!(wtr.write_u8(*i)); 145 | } 146 | 147 | Ok(wtr) 148 | } 149 | 150 | #[cfg(target_endian = "little")] 151 | #[inline] 152 | pub fn carp_type(&self) -> uint8_t { 153 | self.carp_version_type & 0xF 154 | } 155 | 156 | #[cfg(target_endian = "little")] 157 | #[inline] 158 | pub fn carp_version(&self) -> uint8_t { 159 | self.carp_version_type >> 4 160 | } 161 | 162 | #[cfg(target_endian = "little")] 163 | #[inline] 164 | pub fn carp_set_version_type(&mut self, version: uint8_t, type_: uint8_t) { 165 | self.carp_version_type = (version << 4) + type_; 166 | } 167 | 168 | #[cfg(target_endian = "big")] 169 | #[inline] 170 | pub fn carp_type(&self) -> uint8_t { 171 | self.carp_version_type >> 4 172 | } 173 | 174 | #[cfg(target_endian = "big")] 175 | #[inline] 176 | pub fn carp_version(&self) -> uint8_t { 177 | self.carp_version_type & 0xF 178 | } 179 | 180 | #[cfg(target_endian = "big")] 181 | #[inline] 182 | pub fn carp_set_version_type(&mut self, version: uint8_t, type_: uint8_t) { 183 | self.carp_version_type = (type_ << 4) + version; 184 | } 185 | 186 | #[inline] 187 | pub fn carp_cksum(&self) -> uint16_t { 188 | self.carp_cksum 189 | } 190 | 191 | pub fn carp_set_cksum(&mut self, cksum: uint16_t) { 192 | self.carp_cksum = cksum; 193 | } 194 | 195 | #[inline] 196 | pub fn carp_counter(&self) -> u64 { 197 | self.carp_counter 198 | // let mut t: u64 = self.carp_counter[0] as u64; 199 | // t = t << 32; 200 | // t = t + self.carp_counter[1] as u64; 201 | // t 202 | } 203 | 204 | pub fn carp_set_counter(&mut self, counter: u64) { 205 | self.carp_counter = counter; 206 | } 207 | 208 | #[inline] 209 | pub fn carp_bulk_update_min_delay(&self) -> usize { 210 | 240 211 | } 212 | } 213 | 214 | // impl Default for CarpHeader { 215 | // fn default() -> CarpHeader { 216 | // let ch = CarpHeader { 217 | // carp_version_type: CarpHeader::version(), 218 | // carp_vhid: self.config.vhid, 219 | // carp_advskew: self.config.advskew, 220 | // carp_authlen: CarpHeader::authlen(), 221 | // carp_pad1: 0, 222 | // carp_advbase: self.config.advbase, 223 | // carp_cksum: 0, 224 | // carp_counter: [0; 2], 225 | // carp_md: md, 226 | // }; 227 | // } 228 | // } 229 | 230 | #[cfg(test)] 231 | mod test { 232 | use super::*; 233 | 234 | #[test] 235 | fn test_from_bytes() { 236 | let bytes: [u8; 36] = [33, 1, 1, 7, 0, 1, 67, 60, 54, 208, 19, 50, 106, 121, 153, 232, 11, 237 | 225, 167, 175, 127, 243, 33, 245, 83, 103, 152, 57, 240, 194, 21, 238 | 219, 160, 185, 99, 228]; 239 | 240 | let ch = CarpHeader::from_bytes(&bytes).unwrap(); 241 | 242 | assert_eq!(ch.carp_version(), 2); 243 | assert_eq!(ch.carp_type(), 1); 244 | assert_eq!(ch.carp_vhid, 1); 245 | assert_eq!(ch.carp_advskew, 1); 246 | assert_eq!(ch.carp_authlen, 7); 247 | assert_eq!(ch.carp_pad1, 0); 248 | assert_eq!(ch.carp_advbase, 1); 249 | assert_eq!(ch.carp_cksum, 17212); 250 | assert_eq!(ch.carp_counter, 3949677980459571688); 251 | // assert_eq!(ch.carp_counter[0], 919606066); 252 | // assert_eq!(ch.carp_counter[1], 1786354152); 253 | 254 | // TODO test sha1 HMAC 255 | } 256 | 257 | #[test] 258 | fn test_into_bytes() { 259 | let bytes: [u8; 36] = [33, 1, 1, 7, 0, 1, 67, 60, 54, 208, 19, 50, 106, 121, 153, 232, 11, 260 | 225, 167, 175, 127, 243, 33, 245, 83, 103, 152, 57, 240, 194, 21, 261 | 219, 160, 185, 99, 228]; 262 | 263 | let ch = CarpHeader::from_bytes(&bytes).unwrap(); 264 | 265 | let given = ch.into_bytes().unwrap(); 266 | 267 | // PartialEq is not implemented for [T; 36], so turn it into a &[T] 268 | assert_eq!(&bytes[..], given.as_slice()); 269 | } 270 | } 271 | -------------------------------------------------------------------------------- /src/net/mac.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 Herman J. Radtke III 2 | // 3 | // This file is part of carp-rs. 4 | // 5 | // carp-rs is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Lesser General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // carp-rs is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Lesser General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Lesser General Public License 16 | // along with carp-rs. If not, see . 17 | 18 | use std::fmt; 19 | use std::io::{self, Error, ErrorKind}; 20 | use std::net::IpAddr; 21 | use std::os::unix::io::RawFd; 22 | use libc::{sockaddr, c_int, c_short, c_char, c_ulong}; 23 | use nix::sys::socket::{socket, SockType, SockFlag, AddressFamily}; 24 | 25 | const SIOCGIFHWADDR: c_ulong = 0x00008927; 26 | 27 | // TODO check if this changes across OSes 28 | const SIOCGIFFLAGS: c_ulong = 0x00008913; 29 | const SIOCGIFINDEX: c_ulong = 0x00008933; 30 | 31 | /// Interface RFC2863 OPER_UP 32 | const IFF_RUNNING: c_short = 0x40; 33 | 34 | const IFREQUNIONSIZE: usize = 24; 35 | 36 | #[repr(C)] 37 | struct IfReqUnion { 38 | data: [u8; IFREQUNIONSIZE], 39 | } 40 | 41 | impl IfReqUnion { 42 | fn as_sockaddr(&self) -> sockaddr { 43 | // let len = mem::size_of::(); 44 | // mem::transmute(& *self.data[0..len]) 45 | 46 | let mut s = sockaddr { 47 | sa_family: u16::from_be((self.data[0] as u16) << 8 | (self.data[1] as u16)), 48 | sa_data: [0; 14], 49 | }; 50 | 51 | // basically a memcpy 52 | for (i, b) in self.data[2..16].iter().enumerate() { 53 | s.sa_data[i] = *b as i8; 54 | } 55 | 56 | s 57 | } 58 | 59 | fn as_int(&self) -> c_int { 60 | c_int::from_be((self.data[0] as c_int) << 24 | (self.data[1] as c_int) << 16 | 61 | (self.data[2] as c_int) << 8 | 62 | (self.data[3] as c_int)) 63 | } 64 | 65 | fn as_short(&self) -> c_short { 66 | c_short::from_be((self.data[0] as c_short) << 8 | (self.data[1] as c_short)) 67 | } 68 | } 69 | 70 | impl Default for IfReqUnion { 71 | fn default() -> IfReqUnion { 72 | IfReqUnion { data: [0; IFREQUNIONSIZE] } 73 | } 74 | } 75 | 76 | const IFNAMESIZE: usize = 16; 77 | 78 | #[repr(C)] 79 | pub struct IfReq { 80 | ifr_name: [c_char; IFNAMESIZE], 81 | union: IfReqUnion, 82 | } 83 | 84 | impl IfReq { 85 | /// 86 | /// Create an interface request struct with the interface name set 87 | /// 88 | pub fn with_if_name(if_name: &str) -> io::Result { 89 | let mut if_req = IfReq::default(); 90 | 91 | if if_name.len() >= if_req.ifr_name.len() { 92 | return Err(Error::new(ErrorKind::Other, "Interface name too long")); 93 | } 94 | 95 | // basically a memcpy 96 | for (a, c) in if_req.ifr_name.iter_mut().zip(if_name.bytes()) { 97 | *a = c as i8; 98 | } 99 | 100 | Ok(if_req) 101 | } 102 | 103 | pub fn ifr_hwaddr(&self) -> sockaddr { 104 | self.union.as_sockaddr() 105 | } 106 | 107 | pub fn ifr_ifindex(&self) -> c_int { 108 | self.union.as_int() 109 | } 110 | 111 | pub fn ifr_flags(&self) -> c_short { 112 | self.union.as_short() 113 | } 114 | } 115 | 116 | impl Default for IfReq { 117 | fn default() -> IfReq { 118 | IfReq { 119 | ifr_name: [0; IFNAMESIZE], 120 | union: IfReqUnion::default(), 121 | } 122 | } 123 | } 124 | 125 | extern "C" { 126 | fn ioctl(fd: c_int, request: c_ulong, ifreq: *mut IfReq) -> c_int; 127 | } 128 | 129 | #[derive(Debug, Eq, PartialEq)] 130 | pub struct HwAddr { 131 | a: u8, 132 | b: u8, 133 | c: u8, 134 | d: u8, 135 | e: u8, 136 | f: u8, 137 | } 138 | 139 | /// Representation of a MAC address 140 | impl HwAddr { 141 | pub fn new(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> HwAddr { 142 | HwAddr { 143 | a: a, 144 | b: b, 145 | c: c, 146 | d: d, 147 | e: e, 148 | f: f, 149 | } 150 | } 151 | 152 | /// Returns the six eight-bit integers that make up this address. 153 | pub fn octets(&self) -> [u8; 6] { 154 | [self.a, self.b, self.c, self.d, self.e, self.f] 155 | } 156 | 157 | /// Map a multicast ip address to a MAC address 158 | /// 159 | /// TODO: should i check for is_multicast? 160 | pub fn from_multicast_ip(ip: IpAddr) -> HwAddr { 161 | match ip { 162 | IpAddr::V4(ip) => { 163 | let octets = ip.octets(); 164 | HwAddr { 165 | a: 0x01, 166 | b: 0x00, 167 | c: 0x5e, 168 | d: octets[1] & 0x7f, 169 | e: octets[2], 170 | f: octets[3], 171 | } 172 | } 173 | _ => { 174 | panic!("IPv6 is not supported at this time"); 175 | } 176 | } 177 | } 178 | } 179 | 180 | impl fmt::Display for HwAddr { 181 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 182 | let mac = format!( 183 | "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", 184 | self.a, 185 | self.b, 186 | self.c, 187 | self.d, 188 | self.e, 189 | self.f, 190 | ); 191 | 192 | write!(f, "{}", mac) 193 | } 194 | } 195 | 196 | /// Friendly interface for SIOCGIFFLAGS response 197 | pub struct HwFlags { 198 | flags: c_short, 199 | } 200 | 201 | impl HwFlags { 202 | /// Determine if interface is running 203 | pub fn is_running(&self) -> bool { 204 | self.flags & IFF_RUNNING != 0 205 | } 206 | } 207 | 208 | /// ioctl operations on a hardware interface 209 | pub struct HwIf { 210 | if_name: String, 211 | fd: Option, 212 | } 213 | 214 | impl HwIf { 215 | /// Create new hardware interface instance 216 | /// 217 | /// The interface name is something like `eth0`. 218 | pub fn new(if_name: S) -> HwIf 219 | where S: Into 220 | { 221 | HwIf { 222 | if_name: if_name.into(), 223 | fd: None, 224 | } 225 | } 226 | 227 | /// Use user-specified fd when calling ioctl 228 | /// 229 | /// This allows the caller to create a socket and specifiy and custom socket options they want 230 | /// prior to making the call to ioctl. Example: Setting up a socket with multicast. 231 | pub fn use_raw_fd(&mut self, fd: RawFd) { 232 | self.fd = Some(fd); 233 | } 234 | 235 | /// Get Hardware (MAC) address for the network interface 236 | pub fn hwaddr(&self) -> io::Result { 237 | let if_req = try!(self.ioctl(&self.if_name, SIOCGIFHWADDR)); 238 | 239 | let ifr_hwaddr = if_req.ifr_hwaddr(); 240 | 241 | Ok(HwAddr { 242 | a: ifr_hwaddr.sa_data[0] as u8, 243 | b: ifr_hwaddr.sa_data[1] as u8, 244 | c: ifr_hwaddr.sa_data[2] as u8, 245 | d: ifr_hwaddr.sa_data[3] as u8, 246 | e: ifr_hwaddr.sa_data[4] as u8, 247 | f: ifr_hwaddr.sa_data[5] as u8, 248 | }) 249 | } 250 | 251 | /// Get the index for the network interface 252 | pub fn index(&self) -> io::Result { 253 | let if_req = try!(self.ioctl(&self.if_name, SIOCGIFINDEX)); 254 | 255 | Ok(if_req.ifr_ifindex()) 256 | } 257 | 258 | /// Get the active flag word of the device. 259 | pub fn flags(&self) -> io::Result { 260 | let if_req = try!(self.ioctl(&self.if_name, SIOCGIFFLAGS)); 261 | 262 | let hw_flags = HwFlags { flags: if_req.ifr_flags() }; 263 | Ok(hw_flags) 264 | } 265 | 266 | fn ioctl(&self, if_name: &str, ident: c_ulong) -> io::Result { 267 | 268 | let fd = if self.fd.is_some() { 269 | self.fd.unwrap() 270 | } else { 271 | try!(socket(AddressFamily::Inet, 272 | SockType::Datagram, 273 | SockFlag::empty(), 274 | 0)) 275 | }; 276 | 277 | let if_req = try!(IfReq::with_if_name(if_name)); 278 | let mut req: Box = Box::new(if_req); 279 | 280 | if unsafe { ioctl(fd, ident, &mut *req) } == -1 { 281 | return Err(Error::last_os_error()); 282 | } 283 | 284 | Ok(*req) 285 | } 286 | } 287 | 288 | #[cfg(test)] 289 | mod tests { 290 | use std::net::IpAddr; 291 | use std::net::Ipv4Addr; 292 | use nix::sys::socket::{socket, SockType, SockFlag, AddressFamily}; 293 | use super::*; 294 | 295 | #[test] 296 | fn test_hw_addr() { 297 | // TODO dynamically get interface 298 | let hw_if = HwIf::new("eth0"); 299 | assert!(hw_if.hwaddr().is_ok()); 300 | 301 | for if_name in &["nope", "waytoolonginterface", "1234567890123456"] { 302 | let hw_if = HwIf::new(*if_name); 303 | assert!(hw_if.hwaddr().is_err()); 304 | } 305 | } 306 | 307 | #[test] 308 | fn test_hw_addr_format() { 309 | // TODO dynamically get interface 310 | let hw_if = HwIf::new("eth0"); 311 | let mac = format!("{}", hw_if.hwaddr().unwrap()); 312 | assert_eq!(17, mac.len()); 313 | } 314 | 315 | #[test] 316 | fn test_hw_addr_from_multicast_ip() { 317 | let addr = Ipv4Addr::new(224, 192, 16, 1); 318 | let expected = HwAddr::new(0x01, 0x00, 0x5e, 0x40, 0x10, 0x01); 319 | 320 | let given = HwAddr::from_multicast_ip(IpAddr::V4(addr)); 321 | 322 | assert_eq!(expected, given); 323 | } 324 | 325 | #[test] 326 | fn test_if_index() { 327 | // TODO dynamically get interface 328 | let hw_if = HwIf::new("eth0"); 329 | assert!(hw_if.index().is_ok()); 330 | } 331 | 332 | #[test] 333 | fn test_if_flags() { 334 | // TODO dynamically get interface 335 | let hw_if = HwIf::new("eth0"); 336 | assert!(hw_if.flags().is_ok()); 337 | } 338 | 339 | #[test] 340 | fn test_if_flags_using_raw_fd() { 341 | let fd = socket(AddressFamily::Inet, 342 | SockType::Datagram, 343 | SockFlag::empty(), 344 | 0) 345 | .unwrap(); 346 | 347 | // TODO dynamically get interface 348 | let mut hw_if = HwIf::new("eth0"); 349 | hw_if.use_raw_fd(fd); 350 | assert!(hw_if.flags().is_ok()); 351 | } 352 | } 353 | -------------------------------------------------------------------------------- /src/net/ip.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 Herman J. Radtke III 2 | // 3 | // This file is part of carp-rs. 4 | // 5 | // carp-rs is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Lesser General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // carp-rs is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Lesser General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Lesser General Public License 16 | // along with carp-rs. If not, see . 17 | 18 | use std::io::Cursor; 19 | use std::net::Ipv4Addr; 20 | 21 | use libc::{uint8_t, uint16_t, uint32_t}; 22 | use rand::{self, Rng}; 23 | use byteorder::{self, ByteOrder, BigEndian, ReadBytesExt, WriteBytesExt}; 24 | 25 | pub enum Protocol { 26 | Carp = 112, // VRRP 27 | } 28 | 29 | // this is triggering doc tests and i do not know why. plus, i don't even think is a good approach 30 | // Various Control Flags 31 | // 32 | // The flags are part of a larger 16 bit value. These three values represent the first 3 bits of 33 | // the 16 total bits. 34 | // 35 | // Bit 0: reserved, must be zero 36 | // Bit 1: (DF) 0 = May Fragment, 1 = Don't Fragment. 37 | // Bit 2: (MF) 0 = Last Fragment, 1 = More Fragments. 38 | // 39 | // 0 1 2 40 | // +---+---+---+ 41 | // | | D | M | 42 | // | 0 | F | F | 43 | // +---+---+---+ 44 | pub struct Flags(uint16_t); 45 | 46 | impl Flags { 47 | #[inline] 48 | pub fn reserved() -> Flags { 49 | Flags(0x0) 50 | } 51 | 52 | #[inline] 53 | pub fn may_fragment() -> Flags { 54 | Flags(0x0) 55 | } 56 | 57 | #[inline] 58 | pub fn dont_fragment() -> Flags { 59 | Flags(0x4000) 60 | } 61 | 62 | #[inline] 63 | pub fn last_fragment() -> Flags { 64 | Flags(0x0) 65 | } 66 | 67 | #[inline] 68 | pub fn more_fragment() -> Flags { 69 | Flags(0x2000) 70 | } 71 | } 72 | 73 | /// Type of Service 74 | /// 75 | /// Bits 0-2: Precedence. 76 | /// Bit 3: 0 = Normal Delay, 1 = Low Delay. 77 | /// Bits 4: 0 = Normal Throughput, 1 = High Throughput. 78 | /// Bits 5: 0 = Normal Relibility, 1 = High Relibility. 79 | /// Bit 6-7: Reserved for Future Use. 80 | /// 81 | /// 0 1 2 3 4 5 6 7 82 | /// +-----+-----+-----+-----+-----+-----+-----+-----+ 83 | /// | | | | | | | 84 | /// | PRECEDENCE | D | T | R | 0 | 0 | 85 | /// | | | | | | | 86 | /// +-----+-----+-----+-----+-----+-----+-----+-----+ 87 | pub struct Tos(uint8_t); 88 | 89 | impl Tos { 90 | pub fn normal_delay() -> Tos { 91 | Tos(0x0) 92 | } 93 | 94 | pub fn low_delay() -> Tos { 95 | Tos(0x10) 96 | } 97 | 98 | pub fn normal_throughput() -> Tos { 99 | Tos(0x0) 100 | } 101 | 102 | pub fn high_throughput() -> Tos { 103 | Tos(0x8) 104 | } 105 | 106 | pub fn normal_reliability() -> Tos { 107 | Tos(0x0) 108 | } 109 | 110 | pub fn high_reliability() -> Tos { 111 | Tos(0x4) 112 | } 113 | } 114 | 115 | /// Structure of an v4 internet header, naked of options. 116 | /// 117 | /// The struct aims to keep the byte representation compatible with C. This allows for the use of 118 | /// `from_bytes` as a safe method and transmute for speed. Transmute is not supported at this time. 119 | /// I need to find a way to get ByteOrders API but not switch the endianness. 120 | /// 121 | /// See: https://tools.ietf.org/html/rfc791 122 | #[derive(Debug, Default)] 123 | #[repr(C)] 124 | pub struct Ipv4Header { 125 | /// Header length and version 126 | /// 127 | /// This is endian specific. Use helper methods. 128 | v_hl: uint8_t, 129 | 130 | /// Type of service 131 | /// 132 | /// This can also be the DSCP and ECN bits 133 | /// 134 | /// See: https://tools.ietf.org/html/rfc2474 135 | /// See: https://tools.ietf.org/html/rfc3168 136 | pub tos: uint8_t, 137 | 138 | /// Total length 139 | /// 140 | /// Total Length is the length of the datagram, measured in octets, 141 | /// including internet header and data. 142 | total_length: uint16_t, 143 | 144 | /// Identification 145 | id: uint16_t, 146 | 147 | /// Fragment offset field 148 | frag_off: uint16_t, 149 | 150 | /// Time to live 151 | pub ttl: uint8_t, 152 | 153 | /// Protocol 154 | pub protocol: uint8_t, 155 | 156 | /// Checksum 157 | cksum: uint16_t, 158 | 159 | /// Source address 160 | saddr: uint32_t, 161 | 162 | /// Destination address 163 | daddr: uint32_t, 164 | } 165 | 166 | impl Ipv4Header { 167 | pub fn from_bytes(buf: &[u8]) -> byteorder::Result { 168 | let mut rdr = Cursor::new(buf); 169 | 170 | let v_hl = try!(rdr.read_u8()); 171 | let tos = try!(rdr.read_u8()); 172 | let total_length = try!(rdr.read_u16::()); 173 | let id = try!(rdr.read_u16::()); 174 | let frag_off = try!(rdr.read_u16::()); 175 | let ttl = try!(rdr.read_u8()); 176 | let protocol = try!(rdr.read_u8()); 177 | let cksum = try!(rdr.read_u16::()); 178 | 179 | let saddr = try!(rdr.read_u32::()); 180 | let daddr = try!(rdr.read_u32::()); 181 | 182 | Ok(Ipv4Header { 183 | v_hl: v_hl, 184 | tos: tos, 185 | total_length: total_length, 186 | id: id, 187 | frag_off: frag_off, 188 | ttl: ttl, 189 | protocol: protocol, 190 | cksum: cksum, 191 | saddr: saddr, 192 | daddr: daddr, 193 | }) 194 | } 195 | 196 | pub fn into_bytes(&self) -> byteorder::Result> { 197 | let mut wtr = vec![]; 198 | 199 | try!(wtr.write_u8(self.v_hl)); 200 | try!(wtr.write_u8(self.tos)); 201 | try!(wtr.write_u16::(self.total_length)); 202 | try!(wtr.write_u16::(self.id)); 203 | try!(wtr.write_u16::(self.frag_off)); 204 | try!(wtr.write_u8(self.ttl)); 205 | try!(wtr.write_u8(self.protocol)); 206 | try!(wtr.write_u16::(self.cksum)); 207 | try!(wtr.write_u32::(self.saddr)); 208 | try!(wtr.write_u32::(self.daddr)); 209 | 210 | Ok(wtr) 211 | } 212 | 213 | /// Apply checksum value to bytes version of Ipv4Header 214 | pub fn apply_cksum(buf: &mut [u8]) { 215 | let cksum = Self::checksum(buf); 216 | 217 | BigEndian::write_u16(&mut buf[10..12], cksum as u16); 218 | } 219 | 220 | /// IPv4 checksum 221 | /// 222 | /// Form the ones' complement of the ones' complement sum of the buffers's 223 | /// 16-bit words. 224 | pub fn checksum(buf: &[u8]) -> uint16_t { 225 | if buf.len() <= 0 { 226 | return 0; 227 | } 228 | 229 | let mut sum: usize = 0; 230 | for chunk in buf.chunks(2) { 231 | let i = if chunk.len() == 2 { 232 | BigEndian::read_u16(chunk) 233 | } else { 234 | let t = [chunk[0], 0]; 235 | BigEndian::read_u16(&t) 236 | }; 237 | 238 | sum += i as usize; 239 | if sum > 0xFFFF { 240 | sum &= 0xFFFF; 241 | sum += 1; 242 | } 243 | } 244 | 245 | let r = !(sum as u16); 246 | 247 | r 248 | } 249 | 250 | #[cfg(target_endian = "big")] 251 | #[inline] 252 | pub fn version(&self) -> uint8_t { 253 | self.v_hl & 0xF 254 | } 255 | 256 | /// Internet Header Length 257 | #[cfg(target_endian = "big")] 258 | #[inline] 259 | pub fn ihl(&self) -> uint8_t { 260 | self.v_hl >> 4 261 | } 262 | 263 | #[cfg(target_endian = "big")] 264 | pub fn set_version(&mut self, version: uint8_t) { 265 | let len = ::std::mem::size_of::() / 4; 266 | self.v_hl = ((len << 4) as u8) + version; 267 | } 268 | 269 | #[cfg(target_endian = "little")] 270 | #[inline] 271 | pub fn version(&self) -> uint8_t { 272 | self.v_hl >> 4 273 | } 274 | 275 | /// Internet Header Length 276 | #[cfg(target_endian = "little")] 277 | #[inline] 278 | pub fn ihl(&self) -> uint8_t { 279 | self.v_hl & 0xF 280 | } 281 | 282 | #[cfg(target_endian = "little")] 283 | pub fn set_version(&mut self, version: uint8_t) { 284 | let len = ::std::mem::size_of::() / 4; 285 | self.v_hl = len as u8 + (version << 4); 286 | } 287 | 288 | /// Total length 289 | #[inline] 290 | pub fn total_length(&self) -> uint16_t { 291 | self.total_length 292 | } 293 | 294 | pub fn set_total_length(&mut self, length: uint16_t) { 295 | self.total_length = length; 296 | } 297 | 298 | /// Identification 299 | #[inline] 300 | pub fn id(&self) -> uint16_t { 301 | self.id 302 | } 303 | 304 | pub fn generate_id(&mut self) { 305 | let mut rng = rand::thread_rng(); 306 | self.id = rng.gen(); 307 | } 308 | 309 | /// Fragment offset field 310 | #[inline] 311 | pub fn frag_off(&self) -> uint16_t { 312 | self.frag_off 313 | } 314 | 315 | pub fn set_frag_off(&mut self, frag_off: Flags) { 316 | let Flags(f) = frag_off; 317 | self.frag_off = f; 318 | } 319 | 320 | /// Checksum 321 | #[inline] 322 | pub fn cksum(&self) -> uint16_t { 323 | self.cksum 324 | } 325 | 326 | pub fn set_cksum(&mut self, cksum: uint16_t) { 327 | self.cksum = cksum; 328 | } 329 | 330 | /// Source address 331 | #[inline] 332 | pub fn saddr(&self) -> uint32_t { 333 | self.saddr 334 | } 335 | 336 | pub fn set_saddr(&mut self, saddr: uint32_t) { 337 | self.saddr = saddr; 338 | } 339 | 340 | /// Destination address 341 | #[inline] 342 | pub fn daddr(&self) -> uint32_t { 343 | self.daddr 344 | } 345 | 346 | pub fn set_daddr(&mut self, daddr: uint32_t) { 347 | self.daddr = daddr; 348 | } 349 | } 350 | 351 | /// Building a Ipv4Header struct 352 | /// 353 | /// Ipv4Header has the same byte representation as `struct ip` in C. The 354 | /// builder pattern provides a better interface for dealing with byte order 355 | /// specific unions. It also means we can use types like `Ipv4Addr` instead 356 | /// of `c::in_addr`. 357 | #[derive(Default)] 358 | pub struct Ipv4HeaderBuilder { 359 | version: uint8_t, 360 | tos: uint8_t, 361 | total_length: uint16_t, 362 | id: uint16_t, 363 | frag_off: uint16_t, 364 | ttl: uint8_t, 365 | protocol: uint8_t, 366 | cksum: uint16_t, 367 | saddr: uint32_t, 368 | daddr: uint32_t, 369 | } 370 | 371 | impl Ipv4HeaderBuilder { 372 | pub fn new() -> Ipv4HeaderBuilder { 373 | let mut ipb = Self::default(); 374 | ipb.version = 4; 375 | ipb 376 | } 377 | 378 | pub fn tos(&mut self, tos: Tos) -> &mut Ipv4HeaderBuilder { 379 | let Tos(t) = tos; 380 | self.tos = t; 381 | self 382 | } 383 | 384 | pub fn data_length(&mut self, data_length: uint16_t) -> &mut Ipv4HeaderBuilder { 385 | let header_length = ::std::mem::size_of::(); 386 | self.total_length = header_length as uint16_t + data_length; 387 | self 388 | } 389 | 390 | pub fn random_id(&mut self) -> &mut Ipv4HeaderBuilder { 391 | let mut rng = rand::thread_rng(); 392 | self.id = rng.gen(); 393 | self 394 | } 395 | 396 | pub fn flags(&mut self, frag_off: Flags) -> &mut Ipv4HeaderBuilder { 397 | let Flags(f) = frag_off; 398 | self.frag_off = f; 399 | self 400 | } 401 | 402 | pub fn ttl(&mut self, ttl: uint8_t) -> &mut Ipv4HeaderBuilder { 403 | self.ttl = ttl; 404 | self 405 | } 406 | 407 | pub fn protocol(&mut self, protocol: Protocol) -> &mut Ipv4HeaderBuilder { 408 | self.protocol = protocol as uint8_t; 409 | self 410 | } 411 | 412 | pub fn source_address(&mut self, addr: Ipv4Addr) -> &mut Ipv4HeaderBuilder { 413 | self.saddr = BigEndian::read_u32(&addr.octets()); 414 | self 415 | } 416 | 417 | pub fn destination_address(&mut self, addr: Ipv4Addr) -> &mut Ipv4HeaderBuilder { 418 | self.daddr = BigEndian::read_u32(&addr.octets()); 419 | self 420 | } 421 | 422 | pub fn build(&mut self) -> Ipv4Header { 423 | let mut ip = Ipv4Header { 424 | v_hl: 0, 425 | tos: self.tos, 426 | total_length: self.total_length, 427 | id: self.id, 428 | frag_off: self.frag_off, 429 | ttl: self.ttl, 430 | protocol: self.protocol, 431 | cksum: self.cksum, 432 | saddr: self.saddr, 433 | daddr: self.daddr, 434 | }; 435 | 436 | ip.set_version(self.version); 437 | ip 438 | } 439 | } 440 | 441 | #[cfg(test)] 442 | mod test { 443 | use super::*; 444 | use std::net::Ipv4Addr; 445 | use std::str::FromStr; 446 | 447 | #[test] 448 | fn test_from_builder() { 449 | let ip = Ipv4HeaderBuilder::new() 450 | .tos(Tos::low_delay()) 451 | .data_length(20) 452 | .flags(Flags::dont_fragment()) 453 | .ttl(255) 454 | .protocol(Protocol::Carp) 455 | .source_address(FromStr::from_str("10.0.0.2").unwrap()) 456 | .destination_address(FromStr::from_str("10.0.0.3").unwrap()) 457 | .build(); 458 | 459 | assert_eq!(4, ip.version()); 460 | assert_eq!(5, ip.ihl()); 461 | assert_eq!(40, ip.total_length()); 462 | assert_eq!(0x4000, ip.frag_off()); 463 | assert_eq!(255, ip.ttl); 464 | assert_eq!(112, ip.protocol); 465 | assert_eq!(167772162, ip.saddr()); 466 | assert_eq!(167772163, ip.daddr()); 467 | assert_eq!(0, ip.cksum()); 468 | } 469 | 470 | #[test] 471 | fn test_from_bytes() { 472 | let bytes: [u8; 20] = [69, 16, 0, 56, 36, 97, 64, 0, 255, 112, 0, 0, 10, 0, 2, 30, 224, 0, 473 | 0, 18]; 474 | let iph = Ipv4Header::from_bytes(&bytes).unwrap(); 475 | 476 | assert_eq!(iph.version(), 4); 477 | assert_eq!(iph.ihl(), 5); 478 | assert_eq!(iph.tos, 16); 479 | assert_eq!(iph.total_length(), 56); 480 | assert_eq!(iph.id(), 9313); 481 | assert_eq!(iph.frag_off(), 16384); 482 | assert_eq!(iph.ttl, 255); 483 | assert_eq!(iph.protocol, 112); 484 | assert_eq!(iph.cksum(), 0); 485 | assert_eq!(Ipv4Addr::from(iph.saddr()), "10.0.2.30".parse().unwrap()); 486 | assert_eq!(Ipv4Addr::from(iph.daddr()), "224.0.0.18".parse().unwrap()); 487 | } 488 | 489 | #[test] 490 | fn test_into_bytes() { 491 | let bytes: [u8; 20] = [69, 16, 0, 56, 36, 97, 64, 0, 255, 112, 0, 0, 10, 0, 2, 30, 224, 0, 492 | 0, 18]; 493 | let iph = Ipv4Header::from_bytes(&bytes).unwrap(); 494 | let given = iph.into_bytes().unwrap(); 495 | 496 | assert_eq!(bytes, given.as_slice()); 497 | } 498 | 499 | // #[test] 500 | // fn test_transmute() { 501 | // let bytes: [u8; 20] = [69, 16, 0, 56, 36, 97, 64, 0, 255, 112, 0, 0, 10, 0, 2, 30, 224, 0, 0, 18]; 502 | // let iph: Ipv4Header = unsafe { ::std::mem::transmute(bytes) }; 503 | 504 | // assert_eq!(iph.version(), 4); 505 | // assert_eq!(iph.ihl(), 5); 506 | // assert_eq!(iph.tos, 16); 507 | // assert_eq!(iph.total_length, 56); 508 | // assert_eq!(iph.id, 9313); 509 | // assert_eq!(iph.frag_off, 16384); 510 | // assert_eq!(iph.ttl, 255); 511 | // assert_eq!(iph.protocol, 112); 512 | // assert_eq!(iph.cksum, 0); 513 | // assert_eq!(Ipv4Addr::from(iph.saddr), "10.0.2.30".parse().unwrap()); 514 | // assert_eq!(Ipv4Addr::from(iph.daddr), "224.0.0.18".parse().unwrap()); 515 | // } 516 | 517 | #[test] 518 | fn test_cksum_zero_len() { 519 | let buf = []; 520 | 521 | assert_eq!(0, Ipv4Header::checksum(&buf)); 522 | } 523 | 524 | #[test] 525 | fn test_calculate_cksum_even_len() { 526 | let mut buf = [69, 0, 0, 115, 0, 0, 64, 0, 64, 17, 0, 0, 192, 168, 0, 1, 192, 168, 0, 199]; 527 | let expected = [69, 0, 0, 115, 0, 0, 64, 0, 64, 17, 184, 97, 192, 168, 0, 1, 192, 168, 0, 528 | 199]; 529 | 530 | Ipv4Header::apply_cksum(&mut buf); 531 | assert_eq!(expected, buf); 532 | } 533 | 534 | #[test] 535 | fn test_calculate_cksum_odd_len() { 536 | let mut buf = [69, 0, 0, 115, 0, 0, 64, 0, 64, 17, 0, 0, 192, 168, 0, 1, 192, 168, 0, 199, 537 | 0]; 538 | let expected = [69, 0, 0, 115, 0, 0, 64, 0, 64, 17, 184, 97, 192, 168, 0, 1, 192, 168, 0, 539 | 199, 0]; 540 | 541 | Ipv4Header::apply_cksum(&mut buf); 542 | assert_eq!(expected, buf); 543 | } 544 | 545 | #[test] 546 | fn test_verify_cksum_even_len() { 547 | let buf = [69, 0, 0, 115, 0, 0, 64, 0, 64, 17, 184, 97, 192, 168, 0, 1, 192, 168, 0, 199]; 548 | 549 | assert_eq!(0, Ipv4Header::checksum(&buf)); 550 | } 551 | 552 | #[test] 553 | fn test_verify_cksum_odd_len() { 554 | let buf = [69, 0, 0, 115, 0, 0, 64, 0, 64, 17, 184, 97, 192, 168, 0, 1, 192, 168, 0, 199, 555 | 0]; 556 | 557 | assert_eq!(0, Ipv4Header::checksum(&buf)); 558 | } 559 | } 560 | -------------------------------------------------------------------------------- /src/carp.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 Herman J. Radtke III 2 | // 3 | // This file is part of carp-rs. 4 | // 5 | // carp-rs is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU Lesser General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // carp-rs is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU Lesser General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU Lesser General Public License 16 | // along with carp-rs. If not, see . 17 | 18 | use std::cmp; 19 | use std::fmt; 20 | use std::mem; 21 | use std::io; 22 | use std::os::unix::io::{RawFd, AsRawFd}; 23 | use std::net::IpAddr; 24 | use std::net::Ipv4Addr; 25 | use std::thread; 26 | use std::result; 27 | use std::time::{SystemTime, Duration}; 28 | use std::process; 29 | 30 | use libc::{uint8_t, uint16_t}; 31 | 32 | use nix; 33 | use nix::poll::{self, PollFd, EventFlags, POLLIN, POLLERR, POLLHUP}; 34 | use nix::sys::signal; 35 | use nix::sys::socket::{self, ip_mreq, socket, setsockopt, SockType, SockFlag, AddressFamily}; 36 | use nix::sys::socket::sockopt::IpAddMembership; 37 | use nix::unistd::write; 38 | 39 | use pcap::{self, Capture, Active, Packet}; 40 | 41 | use crypto::mac::{Mac, MacResult}; 42 | use crypto::hmac::Hmac; 43 | use crypto::sha1::Sha1; 44 | 45 | use byteorder::{ByteOrder, BigEndian}; 46 | 47 | use config::Config; 48 | use Result; 49 | use net::mac::{HwIf, HwAddr}; 50 | use net::ether::{EtherHeader, EtherType}; 51 | use net::ip::{self, Ipv4Header, Ipv4HeaderBuilder}; 52 | use ip_carp::CarpHeader; 53 | use advert::CarpPacket; 54 | use node; 55 | use net::arp::gratuitous_arp; 56 | 57 | const ETHERNET_MTU: i32 = 1500; 58 | const IPPROTO_CARP: uint8_t = 112; 59 | 60 | static mut received_signal: usize = 0; 61 | 62 | #[derive(Debug, Eq, PartialEq)] 63 | enum State { 64 | Primary, 65 | Backup, 66 | } 67 | 68 | impl fmt::Display for State { 69 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 70 | 71 | match *self { 72 | State::Primary => write!(f, "Primary"), 73 | State::Backup => write!(f, "Backup"), 74 | } 75 | } 76 | } 77 | 78 | pub struct Carp { 79 | config: Config, 80 | state: State, 81 | interface: String, 82 | iface_running: bool, 83 | capture: Capture, 84 | fd: Option, 85 | 86 | /// Advertisement timeout 87 | ad_tmo: Option, 88 | 89 | /// Primary down timeout 90 | pd_tmo: Option, 91 | counter: Option, 92 | 93 | delayed_arp: isize, 94 | 95 | up_cb: Option>, 96 | down_cb: Option>, 97 | } 98 | 99 | impl Carp { 100 | pub fn default_pcap(interface: &str) -> result::Result, pcap::Error> { 101 | let cap = try!(try!(Capture::from_device(interface)) 102 | .snaplen(ETHERNET_MTU) 103 | .timeout(1000) 104 | .open()); 105 | 106 | Ok(cap) 107 | } 108 | 109 | pub fn new(config: Config, capture: Capture) -> Carp { 110 | let interface = config.interface.clone().expect("Interface is not set"); 111 | Carp { 112 | config: config, 113 | state: State::Backup, 114 | interface: interface, 115 | iface_running: false, 116 | capture: capture, 117 | fd: None, 118 | ad_tmo: None, 119 | pd_tmo: None, 120 | counter: None, 121 | delayed_arp: -1, 122 | up_cb: None, 123 | down_cb: None, 124 | } 125 | } 126 | 127 | /// Register callback when role changes from backup to primary 128 | pub fn on_up(&mut self, cb: F) 129 | where F: Fn() + 'static 130 | { 131 | self.up_cb = Some(Box::new(cb)); 132 | } 133 | 134 | /// Register callback when role changes from primary to backup 135 | pub fn on_down(&mut self, cb: F) 136 | where F: Fn() + 'static 137 | { 138 | self.down_cb = Some(Box::new(cb)); 139 | } 140 | 141 | fn up_callback(&self) { 142 | match self.up_cb { 143 | Some(ref func) => { 144 | func(); 145 | } 146 | None => { 147 | warn!("No up callback registered"); 148 | } 149 | } 150 | } 151 | 152 | fn down_callback(&self) { 153 | match self.down_cb { 154 | Some(ref func) => { 155 | func(); 156 | } 157 | None => { 158 | warn!("No down callback registered"); 159 | } 160 | } 161 | } 162 | 163 | pub fn is_backup(&self) -> bool { 164 | self.state == State::Backup 165 | } 166 | 167 | pub fn is_primary(&self) -> bool { 168 | self.state == State::Primary 169 | } 170 | 171 | pub fn run_once(&mut self) -> io::Result { 172 | if self.check_interface() == false { 173 | trace!("Check interface failed"); 174 | return Ok(false); 175 | } 176 | 177 | if self.check_signals() == false { 178 | trace!("Check signals failed"); 179 | return Ok(false); 180 | } 181 | 182 | match self.poll() { 183 | Err(e) => { 184 | if e.kind() != io::ErrorKind::Interrupted { 185 | return Ok(true); 186 | } else { 187 | return Err(e); 188 | } 189 | } 190 | Ok(_) => { 191 | self.check_primary_tmo(); 192 | } 193 | } 194 | 195 | Ok(true) 196 | } 197 | 198 | // Roles: Primary, Backup 199 | // States: check interface, check signals, poll, check timeout, send advert 200 | // Transitions: 201 | // * Primary -> Backup: we need to advertise, then change role 202 | // * Backup -> Primary: we change role, then advertise 203 | // * Other case: Primary reasserting dominance 204 | pub fn run(&mut self) -> Result<()> { 205 | try!(self.setup()); 206 | 207 | trace!("starting to loop"); 208 | loop { 209 | let should_keep_running = try!(self.run_once()); 210 | if should_keep_running == false { 211 | break; 212 | } 213 | } 214 | 215 | self.tear_down(); 216 | 217 | Ok(()) 218 | } 219 | 220 | pub fn setup(&mut self) -> Result<()> { 221 | try!(self.setup_hwaddr()); 222 | try!(self.setup_pcap()); 223 | 224 | try!(self.setup_signal_handlers()); 225 | 226 | self.fd = Some(try!(self.setup_socket())); 227 | 228 | self.reset_timers(); 229 | 230 | Ok(()) 231 | } 232 | 233 | // TODO can probably get rid of this since gratuitious_arp function handles it 234 | fn setup_hwaddr(&self) -> io::Result<()> { 235 | info!("Using [{}] as a network interface", self.interface); 236 | 237 | let hw_if = HwIf::new(self.interface.as_ref()); 238 | let mac = try!(hw_if.hwaddr()); 239 | 240 | info!("Local advertised ethernet address is [{}]", mac); 241 | 242 | Ok(()) 243 | } 244 | 245 | fn setup_pcap(&mut self) -> result::Result<(), pcap::Error> { 246 | trace!("setup_pcap"); 247 | 248 | match self.config.srcip { 249 | IpAddr::V4(ip) => { 250 | let bpf_rule = self.bpf_rule(ip); 251 | try!(self.capture.filter(bpf_rule.as_ref())); 252 | } 253 | _ => { 254 | panic!("IPv6 is not supported at this time"); 255 | } 256 | } 257 | 258 | Ok(()) 259 | } 260 | 261 | fn bpf_rule(&self, srcip: Ipv4Addr) -> String { 262 | format!("proto {} and src host not {}", IPPROTO_CARP, srcip) 263 | } 264 | 265 | fn setup_signal_handlers(&self) -> io::Result<()> { 266 | trace!("setup_signal_handlers"); 267 | 268 | if self.config.shutdown_at_exit == true { 269 | let sig_action = signal::SigAction::new(signal::SigHandler::Handler(sighandler_exit), 270 | signal::SA_NODEFER, 271 | signal::SigSet::empty()); 272 | 273 | unsafe { 274 | try!(signal::sigaction(signal::SIGINT, &sig_action)); 275 | try!(signal::sigaction(signal::SIGQUIT, &sig_action)); 276 | try!(signal::sigaction(signal::SIGTERM, &sig_action)); 277 | try!(signal::sigaction(signal::SIGHUP, &sig_action)); 278 | } 279 | } 280 | 281 | let sig_action = signal::SigAction::new(signal::SigHandler::Handler(sighandler_usr), 282 | signal::SA_NODEFER, 283 | signal::SigSet::empty()); 284 | 285 | unsafe { 286 | try!(signal::sigaction(signal::SIGUSR1, &sig_action)); 287 | try!(signal::sigaction(signal::SIGUSR2, &sig_action)); 288 | } 289 | 290 | Ok(()) 291 | } 292 | 293 | fn setup_socket(&self) -> io::Result { 294 | trace!("setup_socket"); 295 | 296 | let fd = try!(socket(AddressFamily::Inet, 297 | SockType::Datagram, 298 | SockFlag::empty(), 299 | 0)); 300 | 301 | if self.config.no_mcast == false { 302 | let srcip = match self.net_ipaddr_to_nix_ipaddr(self.config.srcip) { 303 | socket::IpAddr::V4(ip) => ip, 304 | _ => { 305 | panic!("IPv6 is not supported at this time"); 306 | } 307 | }; 308 | 309 | let mcast = match self.net_ipaddr_to_nix_ipaddr(self.config.mcast) { 310 | socket::IpAddr::V4(ip) => ip, 311 | _ => { 312 | panic!("IPv6 is not supported at this time"); 313 | } 314 | }; 315 | 316 | debug!("srcip = {}", srcip); 317 | debug!("mcast = {}", mcast); 318 | let req_add = ip_mreq::new(mcast, Some(srcip)); 319 | try!(setsockopt(fd, IpAddMembership, &req_add)); 320 | } 321 | 322 | Ok(fd) 323 | } 324 | 325 | fn net_ipaddr_to_nix_ipaddr(&self, ip: IpAddr) -> socket::IpAddr { 326 | match ip { 327 | IpAddr::V4(ref ip) => socket::IpAddr::V4(socket::Ipv4Addr::from_std(ip)), 328 | _ => { 329 | panic!("IPv6 is not supported at this time"); 330 | } 331 | } 332 | } 333 | 334 | fn check_interface(&mut self) -> bool { 335 | trace!("check_interface"); 336 | 337 | let mut hw_if = HwIf::new(self.interface.as_ref()); 338 | hw_if.use_raw_fd(self.fd.expect("Network interface fd is not set")); 339 | let hw_flags = hw_if.flags().unwrap(); 340 | 341 | if hw_flags.is_running() == false { 342 | if self.config.ignoreifstate == false { 343 | self.state = State::Backup; 344 | self.down_callback(); 345 | self.reset_timers(); 346 | 347 | self.iface_running = false; 348 | 349 | thread::sleep(Duration::from_millis(10000)); 350 | return false; 351 | } 352 | } else { 353 | if self.iface_running == false { 354 | debug!("Interface switched to running"); 355 | self.iface_running = true; 356 | self.reset_timers(); 357 | } 358 | } 359 | 360 | true 361 | } 362 | 363 | fn check_signals(&mut self) -> bool { 364 | trace!("check_signals"); 365 | 366 | let flag = unsafe { received_signal }; 367 | if flag != 0 { 368 | 369 | unsafe { 370 | received_signal = 0; 371 | } 372 | 373 | match flag { 374 | 1 => { 375 | info!("{} on {} id {}", 376 | self.state, 377 | self.interface, 378 | self.config.vhid); 379 | } 380 | 2 => { 381 | debug!("Caught signal (USR2) considering going down"); 382 | 383 | if self.state != State::Backup { 384 | self.state = State::Backup; 385 | self.down_callback(); 386 | thread::sleep(Duration::from_millis(3000)); 387 | self.reset_timers(); 388 | return false; 389 | } 390 | } 391 | 15 => { 392 | debug!("sighandler_exit(): Triggering callback and exiting"); 393 | // if state is PRIMARY, then trigger callback 394 | // callback is async, so this might be tricky 395 | process::exit(0); 396 | } 397 | _ => { 398 | // skip 399 | } 400 | } 401 | } 402 | 403 | true 404 | } 405 | 406 | fn calc_next_timeout(&self, ratio: u8) -> SystemTime { 407 | let now = SystemTime::now(); 408 | 409 | now + calc_adv_freq(self.config.advbase, self.config.advskew, ratio) 410 | } 411 | 412 | fn reset_timers(&mut self) { 413 | match self.state { 414 | State::Primary => { 415 | let tmo = self.calc_next_timeout(1); 416 | debug!("Next primary timeout in {:?}", tmo); 417 | self.pd_tmo = Some(tmo); 418 | } 419 | State::Backup => { 420 | self.ad_tmo = None; 421 | let tmo = self.calc_next_timeout(self.config.dead_ratio as u8); 422 | debug!("Next primary timeout in {:?}", tmo); 423 | self.pd_tmo = Some(tmo); 424 | } 425 | } 426 | } 427 | 428 | fn poll(&mut self) -> io::Result<()> { 429 | trace!("poll"); 430 | 431 | // TODO fix this to reuse capture 432 | let mut capture = Self::default_pcap(self.interface.as_ref()).unwrap(); 433 | let dev_fd = capture.as_raw_fd(); 434 | 435 | let poll_sleep_time = self.calculate_poll_sleep_time(); 436 | 437 | let fd = PollFd { 438 | fd: dev_fd, 439 | events: POLLIN | POLLERR | POLLHUP, 440 | revents: EventFlags::empty(), 441 | }; 442 | 443 | let mut pfds = [fd]; 444 | 445 | let max = cmp::max(1, poll_sleep_time); 446 | 447 | trace!("Polling for {} milliseconds", max); 448 | 449 | // need to set the capture back here if we are in a soft error state 450 | let nfds = try!(poll::poll(&mut pfds, max as i32)); 451 | 452 | // TODO push this up the stack 453 | // if nfds.is_err() { 454 | // let error = io::Error::from(nfds.unwrap_err()); 455 | // if error.kind() == ErrorKind::Interrupted { 456 | // return Ok(false); 457 | // } 458 | // } 459 | 460 | if self.poll_revent_error(&pfds).is_err() { 461 | return Err(io::Error::new(io::ErrorKind::Other, "Poll revent error")); 462 | } 463 | 464 | let mut cp = Err(()); 465 | if nfds == 1 { 466 | let packet = capture.next(); 467 | if packet.is_ok() { 468 | cp = self.handle_packet(&packet.unwrap()); 469 | }; 470 | } 471 | 472 | if cp.is_ok() { 473 | self.check_role_change(&cp.unwrap()); 474 | } 475 | 476 | Ok(()) 477 | } 478 | 479 | fn calculate_poll_sleep_time(&self) -> u64 { 480 | 481 | match self.ad_tmo { 482 | None => { 483 | let tmpskew = (self.config.advskew as u64) * 1000 / 256; 484 | (self.config.advbase as u64) * 1000 + tmpskew 485 | } 486 | Some(ad_tmo) => { 487 | let now = SystemTime::now(); 488 | 489 | let t = match ad_tmo.duration_since(now) { 490 | Ok(t) => t, 491 | Err(e) => { 492 | error!("Error calculating timeout: {}. Defaulting to 10000 ms", e); 493 | Duration::from_secs(10) 494 | } 495 | }; 496 | (t.as_secs() * 1000) + (t.subsec_nanos() as u64 / 1000000) 497 | } 498 | } 499 | } 500 | 501 | fn poll_revent_error(&self, pfds: &[PollFd]) -> result::Result<(), ()> { 502 | if (pfds[0].revents & (POLLERR | POLLHUP)) != EventFlags::empty() { 503 | error!("exiting: pfds[0].revents = POLLERR | POLLHUP"); 504 | 505 | 506 | // TODO move this up in the stack 507 | // if ((sc.sc_state != BACKUP) && (shutdown_at_exit != 0)) { 508 | // trigger_down_callback(); 509 | // } 510 | 511 | Err(()) 512 | } else { 513 | Ok(()) 514 | } 515 | } 516 | 517 | /// Parse incoming packet into a CarpPacket 518 | /// 519 | /// If parsing fails, return an err. This is a soft failure case. 520 | fn handle_packet(&mut self, packet: &Packet) -> result::Result { 521 | let header = match EtherHeader::from_bytes(&packet.data) { 522 | Ok(header) => header, 523 | Err(e) => { 524 | warn!("Unable create EtherHeader: {:?}", e); 525 | return Err(()); 526 | } 527 | }; 528 | 529 | let eh_len = mem::size_of::(); 530 | let ip = match Ipv4Header::from_bytes(&packet.data[eh_len..]) { 531 | Ok(ip) => ip, 532 | Err(e) => { 533 | warn!("Unable create Ip: {:?}", e); 534 | return Err(()); 535 | } 536 | }; 537 | 538 | let ip_len = mem::size_of::(); 539 | 540 | let ch = match CarpHeader::from_bytes(&packet.data[eh_len + ip_len..]) { 541 | Ok(ip) => ip, 542 | Err(e) => { 543 | warn!("Unable create CarpHeader: {:?}", e); 544 | return Err(()); 545 | } 546 | }; 547 | 548 | if ip.protocol != IPPROTO_CARP { 549 | trace!("Protocol {} does not match {}", ip.protocol, IPPROTO_CARP); 550 | return Err(()); 551 | } 552 | 553 | // TODO just make this impl Debug 554 | // debug!("{}", ch); 555 | debug!("CARP type: {}", ch.carp_type()); 556 | debug!("CARP version: {}", ch.carp_version()); 557 | debug!("CARP vhid: {}", ch.carp_vhid); 558 | debug!("CARP advskew: {}", ch.carp_advskew); 559 | debug!("CARP advbase: {}", ch.carp_advbase); 560 | debug!("CARP cksum: {}", ch.carp_cksum()); 561 | debug!("CARP counter: {:?}", ch.carp_counter()); 562 | 563 | if ip.ttl != CarpHeader::ttl() { 564 | warn!("Bad TTL: {}", ip.ttl); 565 | return Err(()); 566 | } 567 | 568 | if ch.carp_version() != CarpHeader::version() { 569 | warn!("Bad version: {}", ch.carp_version()); 570 | return Err(()); 571 | } 572 | 573 | if ch.carp_vhid != self.config.vhid { 574 | debug!("Ignoring vhid: {}", ch.carp_vhid); 575 | return Err(()); 576 | } 577 | 578 | match self.config.mcast { 579 | IpAddr::V4(mcast) => { 580 | let ip_dst = Ipv4Addr::from(ip.daddr()); 581 | 582 | if ip_dst != mcast { 583 | debug!("Ignoring different multicast ip: {}", ip_dst); 584 | return Err(()); 585 | } 586 | } 587 | IpAddr::V6(_) => { 588 | panic!("IpV6 not supported at this time"); 589 | } 590 | } 591 | 592 | if Ipv4Header::checksum(&packet.data[eh_len + ip_len..]) != 0 { 593 | warn!("Bad IP checksum"); 594 | return Err(()); 595 | } 596 | 597 | if self.check_digest(&ch) != true { 598 | warn!("Bad digest! Check vhid, password and virtual IP address"); 599 | return Err(()); 600 | } 601 | 602 | let cp = CarpPacket::new(header, ip, ch); 603 | 604 | Ok(cp) 605 | } 606 | 607 | pub fn check_role_change(&mut self, cp: &CarpPacket) { 608 | 609 | let ip = &cp.ip; 610 | let ch = &cp.carp; 611 | 612 | self.counter = Some(ch.carp_counter()); 613 | 614 | // TODO this should be checking if we _suppress_ preempt 615 | let skew = if false && 616 | (self.config.advskew as usize) < ch.carp_bulk_update_min_delay() { 617 | ch.carp_bulk_update_min_delay() as u8 618 | } else { 619 | self.config.advskew 620 | }; 621 | 622 | let adv_freq = calc_adv_freq(self.config.advbase, skew, 1); 623 | let ch_adv_freq = calc_adv_freq(ch.carp_advbase, ch.carp_advskew, 1); 624 | let saddr_ip = IpAddr::V4(Ipv4Addr::from(ip.saddr())); 625 | debug!("adv_freq = {:?}, ch_adv_freq = {:?}", adv_freq, ch_adv_freq); 626 | 627 | let state = if self.state == State::Primary { 628 | node::Role::Primary 629 | } else { 630 | node::Role::Backup 631 | }; 632 | 633 | let node = node::Node::new(state, adv_freq, self.config.srcip); 634 | let other = node::Node::new(node::Role::Primary, ch_adv_freq, saddr_ip); 635 | 636 | let alignment = if self.config.preempt == true { 637 | node::Alignment::Aggressive 638 | } else { 639 | node::Alignment::Passive 640 | }; 641 | 642 | let role = node.role_change(&other, alignment); 643 | 644 | match state { 645 | node::Role::Primary => { 646 | match role { 647 | node::Role::Primary => { 648 | warn!("Non-preferred primary advertised: {}. Reasserting primary role.", 649 | saddr_ip); 650 | match self.config.srcip { 651 | IpAddr::V4(srcip) => { 652 | gratuitous_arp(self.interface.as_ref(), srcip).unwrap(); 653 | } 654 | _ => { 655 | panic!("IPv6 is not supported at this time"); 656 | } 657 | } 658 | } 659 | node::Role::Backup => { 660 | warn!("Preferred primary advertised: {}. Going back to backup role.", 661 | saddr_ip); 662 | self.send_advert().unwrap_or_else(|e| { 663 | error!("Failed to send advertisement: {}", e); 664 | }); 665 | 666 | self.state = State::Backup; 667 | self.down_callback(); 668 | self.reset_timers(); 669 | } 670 | } 671 | } 672 | node::Role::Backup => { 673 | match role { 674 | node::Role::Primary => { 675 | warn!("Putting remote primary {} down.", saddr_ip); 676 | self.state = State::Primary; 677 | 678 | self.send_advert().unwrap_or_else(|e| { 679 | error!("Failed to send advertisement: {}", e); 680 | }); 681 | 682 | self.delayed_arp += 1; 683 | 684 | self.reset_timers(); 685 | } 686 | node::Role::Backup => { 687 | self.reset_timers(); 688 | } 689 | } 690 | } 691 | } 692 | } 693 | 694 | fn generate_digest(&self, counter: u64) -> MacResult { 695 | let mut hmac = Hmac::new(Sha1::new(), self.config.password.as_bytes()); 696 | hmac.input(&[CarpHeader::version(), 697 | CarpHeader::advertisement(), 698 | self.config.vhid /* why is the C code doing `& 0xFF` here? */]); 699 | 700 | match self.config.vaddr { 701 | IpAddr::V4(ref vaddr) => { 702 | hmac.input(&vaddr.octets()); 703 | } 704 | _ => { 705 | panic!("IPv6 is not supported at this time"); 706 | } 707 | } 708 | 709 | let mut buf: [u8; 8] = [0; 8]; 710 | BigEndian::write_u64(&mut buf, counter); 711 | hmac.input(&buf); 712 | 713 | hmac.result() 714 | } 715 | 716 | fn check_digest(&self, ch: &CarpHeader) -> bool { 717 | let result = self.generate_digest(ch.carp_counter()); 718 | let expected = MacResult::new(&ch.carp_md); 719 | 720 | result == expected 721 | } 722 | 723 | fn handle_remote_primary_down(&mut self) { 724 | trace!("Handling remote primary being down"); 725 | 726 | if self.state == State::Backup { 727 | 728 | info!("Remote primary down. Switching to Primary state"); 729 | self.state = State::Primary; 730 | self.up_callback(); 731 | 732 | self.send_advert().unwrap_or_else(|e| { 733 | error!("Failed to send advertisement: {}", e); 734 | }); 735 | 736 | self.delayed_arp += 1; 737 | 738 | self.reset_timers(); 739 | } 740 | } 741 | 742 | fn check_primary_tmo(&mut self) { 743 | trace!("Checking timeouts"); 744 | let now = SystemTime::now(); 745 | 746 | // debug!("now = {:?}", now); 747 | // debug!("self.pd_tmo = {:?}", self.pd_tmo); 748 | 749 | if self.pd_tmo.is_some() && now > self.pd_tmo.unwrap() { 750 | self.handle_remote_primary_down(); 751 | } 752 | 753 | 754 | // TODO simplify advertisement timeout logic 755 | // we can simplify this by subtracting now from the timeout 756 | // if within 1 millisecond, then we can advertise 757 | if self.ad_tmo.is_some() { 758 | if now > self.ad_tmo.unwrap() { 759 | self.send_advert().unwrap_or_else(|e| { 760 | error!("Failed to send advertisement: {}", e); 761 | }); 762 | } else { 763 | // TODO handle failure here 764 | let duration = self.ad_tmo.unwrap().duration_since(now).unwrap(); 765 | 766 | let diff_ms = (duration.as_secs() * 1000) + 767 | ((duration.subsec_nanos() / 1000) as u64); 768 | 769 | if diff_ms <= 1 { 770 | self.send_advert().unwrap_or_else(|e| { 771 | error!("Failed to send advertisement: {}", e); 772 | }); 773 | } 774 | } 775 | } 776 | } 777 | 778 | // here are all the places we send advertisements from: 779 | // * primary timeout - aka we have not heard from primary server in a long time 780 | // * advert timeout - aka we have not been able to send an advert due to some system issue 781 | // * the remote primary is down - this is triggered from a few areas 782 | fn send_advert(&mut self) -> Result<()> { 783 | trace!("Sending advertisement"); 784 | 785 | if self.counter.is_none() { 786 | // TODO fix this to use some rng 787 | let now = SystemTime::now(); 788 | self.counter = Some(now.elapsed().unwrap().as_secs()); 789 | } 790 | 791 | let hmac = self.generate_digest(self.counter.unwrap()); 792 | 793 | let mut md: [u8; 20] = [0; 20]; 794 | md.clone_from_slice(hmac.code()); 795 | 796 | let mut ch = CarpHeader::default(); 797 | ch.carp_set_version_type(CarpHeader::version(), CarpHeader::advertisement()); 798 | ch.carp_vhid = self.config.vhid; 799 | ch.carp_advskew = self.config.advskew; 800 | ch.carp_authlen = CarpHeader::authlen(); 801 | ch.carp_pad1 = 0; 802 | ch.carp_advbase = self.config.advbase; 803 | ch.carp_set_counter(self.counter.unwrap()); 804 | ch.carp_md = md; 805 | 806 | let ch_bytes = try!(ch.into_bytes()); 807 | ch.carp_set_cksum(Ipv4Header::checksum(ch_bytes.as_slice())); 808 | 809 | let srcip_v4 = match self.config.srcip { 810 | IpAddr::V4(srcip) => srcip, 811 | IpAddr::V6(_) => panic!("V6 not currently supported"), 812 | }; 813 | 814 | let mcast_v4 = match self.config.mcast { 815 | IpAddr::V4(mcast) => mcast, 816 | IpAddr::V6(_) => panic!("V6 not currently supported"), 817 | }; 818 | 819 | let mut ip = Ipv4HeaderBuilder::new() 820 | .tos(ip::Tos::low_delay()) 821 | .data_length(mem::size_of::() as uint16_t) 822 | .random_id() 823 | .flags(ip::Flags::dont_fragment()) 824 | .ttl(CarpHeader::ttl()) 825 | .protocol(ip::Protocol::Carp) 826 | .source_address(srcip_v4) 827 | .destination_address(mcast_v4) 828 | .build(); 829 | 830 | let mut ch_bytes = try!(ch.into_bytes()); 831 | let mut ip_bytes = try!(ip.into_bytes()); 832 | ip_bytes.append(&mut ch_bytes); 833 | 834 | ip.set_cksum(Ipv4Header::checksum(ip_bytes.as_slice())); 835 | 836 | let dhost = if self.config.no_mcast { 837 | HwAddr::new(0xff, 0xff, 0xff, 0xff, 0xff, 0xff) 838 | } else { 839 | HwAddr::from_multicast_ip(self.config.mcast) 840 | }; 841 | 842 | let shost = HwAddr::new(0x00, 0x00, 0x5e, 0x00, 0x00, self.config.vhid); 843 | 844 | let eh = EtherHeader::new(&dhost, &shost, EtherType::Ip); 845 | let cp = CarpPacket::new(eh, ip, ch); 846 | let buf = try!(cp.into_bytes()); 847 | 848 | loop { 849 | let rc = write(self.capture.as_raw_fd(), &buf); 850 | 851 | if rc.is_ok() { 852 | break; 853 | } else { 854 | let err = rc.unwrap_err(); 855 | match err.errno() { 856 | nix::Errno::EINTR => {} 857 | _ => { 858 | error!("Failed to write advertisement: {}", err); 859 | } 860 | } 861 | } 862 | } 863 | 864 | // TODO handle advert send errors 865 | 866 | if self.delayed_arp > 0 { 867 | self.delayed_arp -= 1; 868 | } 869 | 870 | if self.delayed_arp == 0 { 871 | if self.state == State::Primary { 872 | match self.config.srcip { 873 | IpAddr::V4(srcip) => { 874 | try!(gratuitous_arp(self.interface.as_ref(), srcip)); 875 | } 876 | _ => { 877 | panic!("IPv6 is not supported at this time"); 878 | } 879 | } 880 | } 881 | self.delayed_arp = -1; 882 | } 883 | 884 | if self.config.advbase != 255 || self.config.advskew != 255 { 885 | self.ad_tmo = Some(self.calc_next_timeout(1)); 886 | } 887 | 888 | Ok(()) 889 | } 890 | 891 | fn tear_down(&self) { 892 | // TODO pcap_close 893 | // TODO pcap_freecode 894 | } 895 | } 896 | 897 | /// Calculate the advertisement frequency 898 | pub fn calc_adv_freq(advbase: u8, advskew: u8, ratio: u8) -> Duration { 899 | let secs = advbase as u64 * ratio as u64; 900 | let nanos = advskew as u64 * 1000000000 / 256000 as u64; 901 | 902 | Duration::new(secs, nanos as u32) 903 | } 904 | 905 | extern "C" fn sighandler_exit(_: signal::SigNum) { 906 | unsafe { 907 | received_signal = 15; 908 | } 909 | } 910 | 911 | extern "C" fn sighandler_usr(sig: signal::SigNum) { 912 | unsafe { 913 | match sig { 914 | signal::SIGUSR1 => { 915 | received_signal = 1; 916 | } 917 | signal::SIGUSR2 => { 918 | received_signal = 2; 919 | } 920 | _ => { 921 | panic!("Unknown signal received"); 922 | } 923 | } 924 | } 925 | } 926 | 927 | #[cfg(test)] 928 | mod tests { 929 | use super::*; 930 | use std::time::Duration; 931 | 932 | // #[test] 933 | // fn test_bpf_rule() { 934 | // let expect = "proto 112 and src host not 127.0.0.1"; 935 | // let ip = "127.0.0.1".parse().unwrap(); 936 | 937 | // assert_eq!(expect.to_owned(), bpf_rule(ip)); 938 | // } 939 | 940 | #[test] 941 | fn test_calc_adv_freq() { 942 | let advbase = 1; 943 | let advskew = 1; 944 | let ratio = 3; 945 | 946 | let given = calc_adv_freq(advbase, advskew, ratio); 947 | 948 | let expected = Duration::new(3, 3906); 949 | 950 | assert_eq!(expected, given); 951 | } 952 | } 953 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------