<commit_before>//! Implementation of a simple uTP client and server.
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate getopts;
extern crate daemonize;
extern crate udt;
extern crate crypto;
extern crate byteorder;

use daemonize::{Daemonize};
use std::process;
use std::process::Command;
use std::thread;
use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr};
use std::net;
use std::str;
use std::env;
use std::fs::File;
use std::str::FromStr;
use std::path::Path;
use std::io;
use std::io::{Cursor, Error, Seek, SeekFrom, ErrorKind, stdin, stdout, stderr, Read, Write};
use getopts::Options;
use crypto::{blake2b};
use udt::*;
use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian};

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} [options] REMOTE-LOCATION", program);
    print!("{}", opts.usage(&brief));
}

fn send_file(stream: UdtSocket, filename: &str) -> Result<(), Error> {
    let mut f = File::open(filename).unwrap();

    let mut filesize = 0u64;
    let mut buf = vec![0; 1024 * 1024];
    loop {
        match try!(f.read(&mut buf)) {
            0    => { break },
            read => { filesize += read as u64 },
        }
    }

    let mut wtr = vec![];
    wtr.write_u64::<LittleEndian>(filesize).unwrap();
    match stream.sendmsg(&wtr[..]) {
        Ok(0) => {
            return Err(Error::new(ErrorKind::WriteZero, "failed to write filesize header before timeout"))
        },
        Err(e) => {
            return Err(Error::new(ErrorKind::Other, format!("{:?}", e)))
        }
        _ => {
            println!("wrote filesize of {}.", filesize);
        }
    }
    let mut total = 0;
    let mut payload = vec![0; 1300];
    f.seek(SeekFrom::Start(0));
    loop {
        match f.read(&mut payload) {
            Ok(0) => {
                println!("\nEOF.");
                stream.sendmsg(&vec![0;0]);
                break;
            }
            Ok(read) => {
                match stream.sendmsg(&payload[0..read]) {
                    Ok(written) => {
                        total += written;
                        print!("\rwritten {} / {}", total, filesize);
                    },
                    Err(e) => {
                        stream.close().expect("Error closing stream");
                        panic!("{:?}", e);
                    }
                }
            },
            Err(e) => {
                stream.close().expect("Error closing stream");
                panic!("{}", e);
            }
        }
    }

    stream.close().expect("Error closing stream.");
    println!("all done!");
    Ok(())
}

fn recv_file(sock: UdtSocket, filesize: u64, filename: &str) -> Result<(), Error> {
    let mut f = File::create(filename).unwrap();
    let mut total = 0u64;
    loop {
        let buf = try!(sock.recvmsg(1024*1024).map_err(|e| Error::new(ErrorKind::Other, format!("{:?}", e))));
        total += buf.len() as u64;
        f.write_all(&buf[..]);
        print!("read {}\r", total);
        if total >= filesize {
            println!("\nEOF");
            break;
        }
    }
    sock.close();
    Ok(())
}

fn main() {

    // This example may run in either server or client mode.
    // Using an enum tends to make the code cleaner and easier to read.
    enum Mode {Server, Client}

    // Start logging
    env_logger::init().expect("Error starting logger");

    // Fetch arguments
    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();
    let mut opts = Options::new();
    opts.optopt("o", "output", "set output file name", "NAME");
    opts.optflag("s", "server", "server mode");
    opts.optflag("p", "port-range", "server listening port range");
    opts.optflag("h", "help", "print this help menu");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => { panic!(f.to_string()) }
    };

    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }

    let input = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        print_usage(&program, opts);
        return;
    };

    // Parse the mode argument
    let mode: Mode = match matches.opt_present("s") {
        true => Mode::Server,
        false => Mode::Client
    };

    match mode {
        Mode::Server => {
            udt::init();
            let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Datagram).unwrap();
            sock.setsockopt(UdtOpts::UDP_RCVBUF, 5590000i32);
            sock.setsockopt(UdtOpts::UDP_SNDBUF, 5590000i32);
            // sock.setsockopt(UdtOpts::UDT_SNDSYN, true);
            sock.bind(SocketAddr::V4(SocketAddrV4::from_str("0.0.0.0:55000").unwrap())).unwrap();
            let my_addr = sock.getsockname().unwrap();
            println!("Server bound to {:?}", my_addr);

            sock.listen(1).unwrap();

            let (mut stream, peer) = sock.accept().unwrap();
            println!("Received new connection from peer {:?}", peer);

            let daemonize = Daemonize::new();

            let mut clientversion = vec![0; 1];
            if let Ok(version) = stream.recvmsg(1) {
                println!("frand using protocol version {}.", version[0]);
                if version[0] == 0x00 {
                    send_file(stream, &input);
                } else {
                    panic!("Unrecognized version.");
                }
            } else {
                panic!("Failed to receive version byte from client.");
            }

            // match daemonize.start() {
            //     Ok(_) => { let _ = writeln!(&mut stderr(), "daemonized"); }
            //     Err(e) => { let _ = writeln!(&mut stderr(), "RWRWARWARARRR"); }
            // }

        }
        Mode::Client => {
            let sections: Vec<&str> = input.split(":").collect();
            let addr: String = sections[0].to_owned();
            let path: String = sections[1].to_owned();
            let cmd = format!("~/bin/shoop -s {}", path);
            println!("addr: {}, path: {}, cmd: {}", addr, path, cmd);

            // let output = Command::new("ssh")
            //                      .arg(addr.to_owned())
            //                      .arg(cmd)
            //                      .output()
            //                      .unwrap_or_else(|e| {
            //                          panic!("failed to execute process: {}", e);
            //                      });
            // let udp_addr = String::from_utf8_lossy(&output.stdout).trim().to_owned();
            //
            // // Create a stream and try to connect to the remote address
            // println!("shoop server told us to connect to {}", udp_addr);
            udt::init();
            let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Datagram).unwrap();
            sock.setsockopt(UdtOpts::UDP_RCVBUF, 5590000i32);
            sock.setsockopt(UdtOpts::UDP_SNDBUF, 5590000i32);
            let addr: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from_str(&addr).unwrap(), 55000));
            sock.bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from_str("0.0.0.0").unwrap(), 0)));
            match sock.connect(addr) {
                Ok(()) => {
                    println!("connected!");
                },
                Err(e) => {
                    panic!("errrrrrrr {:?}", e);
                }
            }

            sock.sendmsg(&[0u8; 1]);
            println!("checking if server is frand");

            match sock.recvmsg(8) {
                Ok(msg) => {
                    if msg.len() == 0 {
                        panic!("failed to get filesize from server, probable timeout.");
                    }
                    let mut rdr = Cursor::new(msg);
                    let filesize = rdr.read_u64::<LittleEndian>().unwrap();
                    println!("got reported filesize of {}", filesize);
                    recv_file(sock, filesize, "outfile");
                }
                Err(e) => {
                    panic!("{:?}", e);
                }
            }
        }
    }
}

<commit_msg>try stream?<commit_after>//! Implementation of a simple uTP client and server.
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate getopts;
extern crate daemonize;
extern crate udt;
extern crate crypto;
extern crate byteorder;

use daemonize::{Daemonize};
use std::process;
use std::process::Command;
use std::thread;
use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr};
use std::net;
use std::str;
use std::env;
use std::fs::File;
use std::str::FromStr;
use std::path::Path;
use std::io;
use std::io::{Cursor, Error, Seek, SeekFrom, ErrorKind, stdin, stdout, stderr, Read, Write};
use getopts::Options;
use crypto::{blake2b};
use udt::*;
use byteorder::{ReadBytesExt, WriteBytesExt, LittleEndian};

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} [options] REMOTE-LOCATION", program);
    print!("{}", opts.usage(&brief));
}

fn send_file(stream: UdtSocket, filename: &str) -> Result<(), Error> {
    let mut f = File::open(filename).unwrap();

    let mut filesize = 0u64;
    let mut buf = vec![0; 1024 * 1024];
    loop {
        match try!(f.read(&mut buf)) {
            0    => { break },
            read => { filesize += read as u64 },
        }
    }

    let mut wtr = vec![];
    wtr.write_u64::<LittleEndian>(filesize).unwrap();
    match stream.sendmsg(&wtr[..]) {
        Ok(0) => {
            return Err(Error::new(ErrorKind::WriteZero, "failed to write filesize header before timeout"))
        },
        Err(e) => {
            return Err(Error::new(ErrorKind::Other, format!("{:?}", e)))
        }
        _ => {
            println!("wrote filesize of {}.", filesize);
        }
    }
    let mut total = 0;
    let mut payload = vec![0; 1300];
    f.seek(SeekFrom::Start(0));
    loop {
        match f.read(&mut payload) {
            Ok(0) => {
                println!("\nEOF.");
                stream.sendmsg(&vec![0;0]);
                break;
            }
            Ok(read) => {
                match stream.sendmsg(&payload[0..read]) {
                    Ok(written) => {
                        total += written;
                        print!("\rwritten {} / {}", total, filesize);
                    },
                    Err(e) => {
                        stream.close().expect("Error closing stream");
                        panic!("{:?}", e);
                    }
                }
            },
            Err(e) => {
                stream.close().expect("Error closing stream");
                panic!("{}", e);
            }
        }
    }

    stream.close().expect("Error closing stream.");
    println!("all done!");
    Ok(())
}

fn recv_file(sock: UdtSocket, filesize: u64, filename: &str) -> Result<(), Error> {
    let mut f = File::create(filename).unwrap();
    let mut total = 0u64;
    loop {
        let buf = try!(sock.recvmsg(1024*1024).map_err(|e| Error::new(ErrorKind::Other, format!("{:?}", e))));
        total += buf.len() as u64;
        f.write_all(&buf[..]);
        print!("read {}\r", total);
        if total >= filesize {
            println!("\nEOF");
            break;
        }
    }
    sock.close();
    Ok(())
}

fn main() {

    // This example may run in either server or client mode.
    // Using an enum tends to make the code cleaner and easier to read.
    enum Mode {Server, Client}

    // Start logging
    env_logger::init().expect("Error starting logger");

    // Fetch arguments
    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();
    let mut opts = Options::new();
    opts.optopt("o", "output", "set output file name", "NAME");
    opts.optflag("s", "server", "server mode");
    opts.optflag("p", "port-range", "server listening port range");
    opts.optflag("h", "help", "print this help menu");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => { panic!(f.to_string()) }
    };

    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }

    let input = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        print_usage(&program, opts);
        return;
    };

    // Parse the mode argument
    let mode: Mode = match matches.opt_present("s") {
        true => Mode::Server,
        false => Mode::Client
    };

    match mode {
        Mode::Server => {
            udt::init();
            let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Stream).unwrap();
            sock.setsockopt(UdtOpts::UDP_RCVBUF, 5590000i32);
            sock.setsockopt(UdtOpts::UDP_SNDBUF, 5590000i32);
            // sock.setsockopt(UdtOpts::UDT_SNDSYN, true);
            sock.bind(SocketAddr::V4(SocketAddrV4::from_str("0.0.0.0:55000").unwrap())).unwrap();
            let my_addr = sock.getsockname().unwrap();
            println!("Server bound to {:?}", my_addr);

            sock.listen(1).unwrap();

            let (mut stream, peer) = sock.accept().unwrap();
            println!("Received new connection from peer {:?}", peer);

            let daemonize = Daemonize::new();

            let mut clientversion = vec![0; 1];
            if let Ok(version) = stream.recvmsg(1) {
                println!("frand using protocol version {}.", version[0]);
                if version[0] == 0x00 {
                    send_file(stream, &input);
                } else {
                    panic!("Unrecognized version.");
                }
            } else {
                panic!("Failed to receive version byte from client.");
            }

            // match daemonize.start() {
            //     Ok(_) => { let _ = writeln!(&mut stderr(), "daemonized"); }
            //     Err(e) => { let _ = writeln!(&mut stderr(), "RWRWARWARARRR"); }
            // }

        }
        Mode::Client => {
            let sections: Vec<&str> = input.split(":").collect();
            let addr: String = sections[0].to_owned();
            let path: String = sections[1].to_owned();
            let cmd = format!("~/bin/shoop -s {}", path);
            println!("addr: {}, path: {}, cmd: {}", addr, path, cmd);

            // let output = Command::new("ssh")
            //                      .arg(addr.to_owned())
            //                      .arg(cmd)
            //                      .output()
            //                      .unwrap_or_else(|e| {
            //                          panic!("failed to execute process: {}", e);
            //                      });
            // let udp_addr = String::from_utf8_lossy(&output.stdout).trim().to_owned();
            //
            // // Create a stream and try to connect to the remote address
            // println!("shoop server told us to connect to {}", udp_addr);
            udt::init();
            let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Stream).unwrap();
            sock.setsockopt(UdtOpts::UDP_RCVBUF, 5590000i32);
            sock.setsockopt(UdtOpts::UDP_SNDBUF, 5590000i32);
            let addr: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from_str(&addr).unwrap(), 55000));
            sock.bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from_str("0.0.0.0").unwrap(), 0)));
            match sock.connect(addr) {
                Ok(()) => {
                    println!("connected!");
                },
                Err(e) => {
                    panic!("errrrrrrr {:?}", e);
                }
            }

            sock.sendmsg(&[0u8; 1]);
            println!("checking if server is frand");

            match sock.recvmsg(8) {
                Ok(msg) => {
                    if msg.len() == 0 {
                        panic!("failed to get filesize from server, probable timeout.");
                    }
                    let mut rdr = Cursor::new(msg);
                    let filesize = rdr.read_u64::<LittleEndian>().unwrap();
                    println!("got reported filesize of {}", filesize);
                    recv_file(sock, filesize, "outfile");
                }
                Err(e) => {
                    panic!("{:?}", e);
                }
            }
        }
    }
}

<|endoftext|>


<commit_before>extern crate core;
extern crate iron;
extern crate mount;
extern crate rustc_serialize;
extern crate staticfile;
extern crate toml;
extern crate url;

use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;

use iron::prelude::*;
use mount::Mount;
use staticfile::Static;

mod api;
mod collection;
mod error;
mod vfs;

use api::*;
use collection::*;

fn main() {

    let mut collection = Collection::new();
    collection.load_config(Path::new("Polaris.toml")).unwrap();

    let collection = Arc::new(Mutex::new(collection));

    let mut mount = Mount::new();
    let api_handler = get_api_handler(collection);
    mount.mount("/api/", api_handler);
    mount.mount("/", Static::new(Path::new("../polaris-web")));

    Iron::new(mount).http("localhost:3000").unwrap();
}
<commit_msg>Revert "Only list music files in browse/flatten"<commit_after>extern crate core;
extern crate iron;
extern crate mount;
extern crate rustc_serialize;
extern crate staticfile;
extern crate toml;
extern crate url;

use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;

use iron::prelude::*;
use mount::Mount;
use staticfile::Static;

mod api;
mod collection;
mod error;
mod vfs;

use api::*;
use collection::*;

fn main() {

    let mut collection = Collection::new();
    collection.load_config(Path::new("Polaris.toml")).unwrap();

    let collection = Arc::new(Mutex::new(collection));

    let mut mount = Mount::new();
    let api_handler = get_api_handler(collection);
    mount.mount("/api/", api_handler);
    mount.mount("/", Static::new(Path::new("web")));

    Iron::new(mount).http("localhost:3000").unwrap();
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate glium;

use glium::DisplayBuild;
use glium::Surface;

extern crate rand;
use rand::distributions::{IndependentSample, Range};

#[derive(Default, Copy, Clone)]
struct Vertex {
    position: [f64; 2],
}

struct Ball {
    vertex: Vertex,
    radius: f64,
    velocity: [f64; 3],
    tris: u8,
}

impl Ball {
    fn new(position: [f64; 2], radius: f64, velocity: [f64; 3]) -> Ball {
        Ball {
            vertex: Vertex { position: position },
            radius: radius,
            velocity: velocity,
            tris: 50,
        }
    }

    fn update(&mut self) {
        self.vertex.position[0] += self.velocity[0];
        self.vertex.position[1] += self.velocity[1];
    }

    fn render(&self) -> Vec<Vertex> {
        let mut vertices = vec![];

        vertices.push(self.vertex.clone());
        for n in 0..self.tris + 1 {
            vertices.push(Vertex {
                position: [&self.vertex.position[0] + (&self.radius * (n as f64 * PI2 / self.tris as f64).cos()),
                           &self.vertex.position[1] + (&self.radius * (n as f64 * PI2 / self.tris as f64).sin())],
            });
        }

        vertices
    }
}

const PI2: f64 = std::f64::consts::PI * 2.;

fn main() {
    let display = glium::glutin::WindowBuilder::new()
        .with_dimensions(640, 480)
        .with_title(format!("Elma Menu bounce balls deluxe"))
        .build_glium()
        .unwrap();

    implement_vertex!(Vertex, position);

    let rand_range = Range::new(0.028648_f64, 89.848719_f64);
    let mut rng_gen = rand::thread_rng();
    let rand_degree = rand_range.ind_sample(&mut rng_gen) * std::f64::consts::PI / 180.0; // deg to rad
    let mut circles = vec![Ball::new([-0.375, 0.5], 0.075, [rand_degree.cos() / 5000.0, rand_degree.sin() / 5000.0, 0.0]),
                        Ball::new([0.0, 0.5], 0.09375, [0.0, 0.0, 0.0]), Ball::new([0.375, 0.5], 0.15625, [0.0, 0.0, 0.0]),
                       Ball::new([-0.375, 0.0], 0.075, [0.0, 0.0, 0.0]), Ball::new([0.0, 0.0], 0.09375, [0.0, 0.0, 0.0]),
                       Ball::new([0.375, 0.0], 0.15625, [0.0, 0.0, 0.0]),
                       Ball::new([-0.375, -0.5], 0.075, [0.0, 0.0, 0.0]), Ball::new([0.0, -0.5], 0.09375, [0.0, 0.0, 0.0]),
                       Ball::new([0.375, -0.5], 0.15625, [0.0, 0.0, 0.0])];

    let vertex_shader_src = include_str!("shaders/ball.vert");
    let fragment_shader_src = include_str!("shaders/ball.frag");

    let program =
        glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src, None)
            .unwrap();

    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan);

    loop {
        let mut target = display.draw();
        target.clear_color(0.0, 0.0, 0.0, 1.0);

        let mut vbuffers = vec![];
        for circle in &mut circles {
            circle.update();
            vbuffers.push(glium::VertexBuffer::new(&display, &circle.render()).unwrap());
        }

        for buffer in &vbuffers {
            target.draw(buffer,
                      &indices,
                      &program,
                      &glium::uniforms::EmptyUniforms,
                      &Default::default())
                .unwrap();
        }
        target.finish().unwrap();

        for event in display.poll_events() {
            match event {
                glium::glutin::Event::Closed => return,
                _ => (),
            }
        }
    }
}
<commit_msg>fix: remove vbuffer stuff for now<commit_after>#[macro_use]
extern crate glium;

use glium::DisplayBuild;
use glium::Surface;

extern crate rand;
use rand::distributions::{IndependentSample, Range};

#[derive(Default, Copy, Clone)]
struct Vertex {
    position: [f64; 2],
}

struct Ball {
    vertex: Vertex,
    radius: f64,
    velocity: [f64; 3],
    tris: u8,
}

impl Ball {
    fn new(position: [f64; 2], radius: f64, velocity: [f64; 3]) -> Ball {
        Ball {
            vertex: Vertex { position: position },
            radius: radius,
            velocity: velocity,
            tris: 50,
        }
    }

    fn update(&mut self) {
        self.vertex.position[0] += self.velocity[0];
        self.vertex.position[1] += self.velocity[1];
    }

    fn render(&self) -> Vec<Vertex> {
        let mut vertices = vec![];

        vertices.push(self.vertex.clone());
        for n in 0..self.tris + 1 {
            vertices.push(Vertex {
                position: [&self.vertex.position[0] + (&self.radius * (n as f64 * PI2 / self.tris as f64).cos()),
                           &self.vertex.position[1] + (&self.radius * (n as f64 * PI2 / self.tris as f64).sin())],
            });
        }

        vertices
    }
}

const PI2: f64 = std::f64::consts::PI * 2.;

fn main() {
    let display = glium::glutin::WindowBuilder::new()
        .with_dimensions(640, 480)
        .with_title(format!("Elma Menu bounce balls deluxe"))
        .build_glium()
        .unwrap();

    implement_vertex!(Vertex, position);

    let rand_range = Range::new(0.028648_f64, 89.848719_f64);
    let mut rng_gen = rand::thread_rng();
    let rand_degree = rand_range.ind_sample(&mut rng_gen) * std::f64::consts::PI / 180.0; // deg to rad
    let mut circles = vec![Ball::new([-0.375, 0.5], 0.075, [rand_degree.cos() / 5000.0, rand_degree.sin() / 5000.0, 0.0]),
                        Ball::new([0.0, 0.5], 0.09375, [0.0, 0.0, 0.0]), Ball::new([0.375, 0.5], 0.15625, [0.0, 0.0, 0.0]),
                       Ball::new([-0.375, 0.0], 0.075, [0.0, 0.0, 0.0]), Ball::new([0.0, 0.0], 0.09375, [0.0, 0.0, 0.0]),
                       Ball::new([0.375, 0.0], 0.15625, [0.0, 0.0, 0.0]),
                       Ball::new([-0.375, -0.5], 0.075, [0.0, 0.0, 0.0]), Ball::new([0.0, -0.5], 0.09375, [0.0, 0.0, 0.0]),
                       Ball::new([0.375, -0.5], 0.15625, [0.0, 0.0, 0.0])];

    let vertex_shader_src = include_str!("shaders/ball.vert");
    let fragment_shader_src = include_str!("shaders/ball.frag");

    let program =
        glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src, None)
            .unwrap();

    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan);

    loop {
        let mut target = display.draw();
        target.clear_color(0.0, 0.0, 0.0, 1.0);

        for circle in &mut circles {
            circle.update();
            target.draw(&glium::VertexBuffer::new(&display, &circle.render()).unwrap(),
                &indices,
                &program,
                &glium::uniforms::EmptyUniforms,
                &Default::default())
                .unwrap();
        }

        target.finish().unwrap();

        for event in display.poll_events() {
            match event {
                glium::glutin::Event::Closed => return,
                _ => (),
            }
        }
    }
}
<|endoftext|>


<commit_before>extern crate wol;
extern crate getopts;

use getopts::Options;
use std::env;

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} [-h] [-4|-6]  MAC", program);
    print!("{}", opts.usage(&brief));
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();
    let mut opts = Options::new();
    opts.optopt("",
                "mac",
                "the MAC address of the remote system",
                "00:00:00:00:00:00");
    opts.optflag("4", "ipv4", "use IPv4");
    opts.optflag("6", "ipv6", "use IPv6 (default)");
    opts.optflag("h", "help", "print this help menu");
    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => {
            println!("Illegal argument: {}", f.to_string());
            return;
        }
    };
    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }
    let macstr = matches.opt_str("mac").expect("no MAC address given");
    let mac: Vec<u8> = wol::parse_mac(macstr).expect("parse error");
    wol::send_magic_packet_v6(mac).expect("Transmission error");
}
<commit_msg>ipv4/ipv6 option added<commit_after>extern crate wol;
extern crate getopts;

use getopts::Options;
use std::env;

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} [-h] [-4|-6]  MAC", program);
    print!("{}", opts.usage(&brief));
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();
    let mut opts = Options::new();
    opts.optopt("",
                "mac",
                "the MAC address of the remote system",
                "00:00:00:00:00:00");
    opts.optflag("4", "ipv4", "use IPv4");
    opts.optflag("6", "ipv6", "use IPv6 (default)");
    opts.optflag("h", "help", "print this help menu");
    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => {
            println!("Illegal argument: {}", f.to_string());
            return;
        }
    };
    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }
    let macstr = matches.opt_str("mac").expect("no MAC address given");
    let mac: Vec<u8> = wol::parse_mac(macstr).expect("parse error");
    if matches.opt_present("4") {
        wol::send_magic_packet_v4(mac).expect("Transmission error");
    } else {
        wol::send_magic_packet_v6(mac).expect("Transmission error");
    }
}
<|endoftext|>


<commit_before>extern crate clap;
extern crate elf;
extern crate rbpf;

use std::process;
use clap::{Arg, App};

fn main() {
    let matches = App::new("ebpf-disasm")
        .version("1.0")
        .author("Jan-Erik Rediger")
        .about("Output disassembled eBPF read from an ELF file")
        .arg(Arg::with_name("section")
             .short("s")
             .long("section")
             .value_name("SECTION")
             .help("Specify a section name")
             .takes_value(true))
        .arg(Arg::with_name("INPUT")
             .help("Sets the input ELF file to use")
             .required(true)
             .index(1))
        .arg(Arg::with_name("bytecode")
            .short("b")
            .long("bytecode")
            .help("Only show raw bytecode"))
        .get_matches();

    let section = matches.value_of("section").unwrap_or(".classifier");
    let input_file = matches.value_of("INPUT").unwrap();
    let show_bytecode = matches.is_present("bytecode");

    let file = match elf::File::open_path(&input_file) {
        Ok(f) => f,
        Err(e) => {
            println!("Could not read elf file.");
            println!("Error: {:?}", e);
            process::exit(1);
        }
    };

    let text_scn = match file.get_section(&section) {
        Some(s) => s,
        None => {
            println!("Failed to lookup '{}' section.", section);
            process::exit(1);
        }
    };

    let prog = &text_scn.data;

    if show_bytecode {
        for insn in prog.chunks(8) {
            for i in insn {
                print!("0x{:>02x}, ", i);
            }
            println!("");
        }
    } else {
        for insn in rbpf::disassembler::to_insn_vec(prog) {
            println!("{}", insn.desc.replace(" ", "\t"));
        }
    }
}
<commit_msg>Option to output as a C-compatible bpf_insn array<commit_after>extern crate clap;
extern crate elf;
extern crate rbpf;

use std::process;
use clap::{Arg, App};

fn main() {
    let matches = App::new("ebpf-disasm")
        .version("1.0")
        .author("Jan-Erik Rediger")
        .about("Output disassembled eBPF read from an ELF file")
        .arg(Arg::with_name("section")
             .short("s")
             .long("section")
             .value_name("SECTION")
             .help("Specify a section name")
             .takes_value(true))
        .arg(Arg::with_name("INPUT")
             .help("Sets the input ELF file to use")
             .required(true)
             .index(1))
        .arg(Arg::with_name("bytecode")
            .short("b")
            .long("bytecode")
            .help("Only show raw bytecode"))
        .arg(Arg::with_name("ccode")
            .short("c")
            .long("ccode")
            .help("Only show a C compatible bpf_insn array"))
        .get_matches();

    let section = matches.value_of("section").unwrap_or(".classifier");
    let input_file = matches.value_of("INPUT").unwrap();
    let show_bytecode = matches.is_present("bytecode");
    let show_ccode = matches.is_present("ccode");

    if show_bytecode && show_ccode {
        println!("Can't show both bytecode and C code.");
        process::exit(1);
    }

    let file = match elf::File::open_path(&input_file) {
        Ok(f) => f,
        Err(e) => {
            println!("Could not read elf file.");
            println!("Error: {:?}", e);
            process::exit(1);
        }
    };

    let text_scn = match file.get_section(&section) {
        Some(s) => s,
        None => {
            println!("Failed to lookup '{}' section.", section);
            process::exit(1);
        }
    };

    let prog = &text_scn.data;

    if show_bytecode {
        for insn in prog.chunks(8) {
            for i in insn {
                print!("0x{:>02x}, ", i);
            }
            println!("");
        }
    } else if show_ccode {
        println!("struct bpf_insn prog[] = {{");
        for insn in prog.chunks(8) {
            print!("\t{{ ");
            print!(".code = 0x{:>02x}, ", insn[0]);
            print!(".dst_reg = 0x{:>x}, ", insn[1]&0x0f);
            print!(".src_reg = 0x{:>x}, ", insn[1]>>4);
            let off = (insn[2] as u16)<<8 | (insn[3] as u16);
            print!(".off = 0x{:>04x}, ", off);
            let imm = (insn[7] as u32)<<24 |
                (insn[6] as u32)<<16 |
                (insn[5] as u32)<<8 |
                (insn[4] as u32)<<0;
            print!(".imm = 0x{:>08x}", imm);
            println!(" }},");
        }
        println!("}};");
    } else {
        for insn in rbpf::disassembler::to_insn_vec(prog) {
            println!("{}", insn.desc.replace(" ", "\t"));
        }
    }
}
<|endoftext|>


<commit_before>#![feature(slice_patterns)]
extern crate num;
#[macro_use]
extern crate glium;
extern crate nalgebra;
use nalgebra::*;
use glium::{DisplayBuild, Surface};
use num::traits::Zero;
use glium::glutin::Event::*;
use glium::glutin::ElementState::*;
use glium::glutin::MouseScrollDelta::PixelDelta;
use glium::glutin::MouseButton::*;

fn main() {
  let display = glium::glutin::WindowBuilder::new()
                  .with_vsync()
                  .build_glium().unwrap();

  #[derive(Copy, Clone)]
  struct Vertex {position: [f32; 2]}
  implement_vertex!(Vertex, position);

  let vertex_shader_src = r#"
      #version 140
      uniform mat2 projection;
      uniform vec2 translation;
      in vec2 position;
      void main() {
          gl_Position = vec4(projection * (position + translation), 0.0, 1.0);
      }
  "#;

  let fragment_shader_src = r#"
      #version 140

      out vec4 color;

      void main() {
          color = vec4(0.0, 0.0, 0.0, 1.0);
      }
  "#;

  let indices = glium::index::NoIndices(glium::index::PrimitiveType::LineStrip);

  let params = glium::DrawParameters {
    line_width: Some(2.0),
    .. Default::default()
  };

  let program = glium::Program::from_source(
    &display,
    vertex_shader_src,
    fragment_shader_src,
    None).unwrap();

  let mut current_line : Vec<Vertex> = Vec::new();
  let mut commited_lines : Vec<glium::VertexBuffer<Vertex>> = Vec::new();

  #[derive(Copy, Clone)]
  enum State {
    None,
    Drawing,
    Dragging(Vec2<f32>)
  }

  let mut state = State::None;

  let mut scale = 1.0;
  let mut translation = Vec2::zero();
  let mut mouse_last = Vec2::zero();

  loop {

    let (frame_dx, frame_dy) = display.get_framebuffer_dimensions();
    let (frame_dx, frame_dy) = (frame_dx as f32, frame_dy as f32);

    let projection
      = Mat2::new(2.0/frame_dx, 0.0,
                  0.          , 2.0/frame_dy);

    for event in display.poll_events() {
      match (event, state) {

        (MouseWheel(PixelDelta(_, dy)), _)  => {
          if dy > 0.0 {
            scale *= 1.1;
          } else {
            scale *= 0.9;
          }
          translation = -mouse_last + mouse_last/scale;
        },

        (MouseInput(Pressed,Left), State::None) => {
          state = State::Drawing;
        },

        (MouseInput(Pressed,Middle), State::None) => {
            state = State::Dragging(mouse_last);
        },

        (MouseInput(Released,Left), State::Drawing) => {
            commited_lines.push(
              glium::VertexBuffer::immutable(&display, &current_line).unwrap());
            current_line.clear();
            state = State::None;
        },

        (MouseInput(Released,Middle), State::Dragging(_)) => {
            state = State::None;
        },

        (MouseMoved((mouse_x, mouse_y)), state) => {
          let screen
            = Vec2::new(
                2.0*(mouse_x as f32)/frame_dx - 1.0,
               -2.0*(mouse_y as f32)/frame_dy + 1.0);

          let world  = projection.inv().unwrap()
                        * (1.0/scale)
                        * screen
                        - translation;

          match state {
            State::Drawing => {
              current_line.push(Vertex{position: [world.x, world.y]});
            },
            State::Dragging(drag_start) => {
              translation.x +=  world.x - drag_start.x;
              translation.y +=  world.y - drag_start.y;
            },
            _ => {}
          }

          mouse_last = world;
        },

        (Closed, _) => return,
        _ => ()
      }
    }

    let uniforms = uniform!(
      projection : projection * scale,
      translation: translation,
    );

    let mut target = display.draw();
    target.clear_color(1.0, 1.0, 1.0, 1.0);

    for line in &commited_lines[..] {
      target.draw(
        line,
        &indices,
        &program,
        &uniforms,
        &params).unwrap();
    }

    if let State::Drawing = state {
        target.draw(
          &glium::VertexBuffer::new(&display, &current_line).unwrap(),
          &indices,
          &program,
          &uniforms,
          &Default::default()).unwrap();
    }

    target.finish().unwrap();
  }
}
<commit_msg>tweaked zoom factors<commit_after>#![feature(slice_patterns)]
extern crate num;
#[macro_use]
extern crate glium;
extern crate nalgebra;
use nalgebra::*;
use glium::{DisplayBuild, Surface};
use num::traits::Zero;
use glium::glutin::Event::*;
use glium::glutin::ElementState::*;
use glium::glutin::MouseScrollDelta::PixelDelta;
use glium::glutin::MouseButton::*;

fn main() {
  let display = glium::glutin::WindowBuilder::new()
                  .with_vsync()
                  .build_glium().unwrap();

  #[derive(Copy, Clone)]
  struct Vertex {position: [f32; 2]}
  implement_vertex!(Vertex, position);

  let vertex_shader_src = r#"
      #version 140
      uniform mat2 projection;
      uniform vec2 translation;
      in vec2 position;
      void main() {
          gl_Position = vec4(projection * (position + translation), 0.0, 1.0);
      }
  "#;

  let fragment_shader_src = r#"
      #version 140

      out vec4 color;

      void main() {
          color = vec4(0.0, 0.0, 0.0, 1.0);
      }
  "#;

  let indices = glium::index::NoIndices(glium::index::PrimitiveType::LineStrip);

  let params = glium::DrawParameters {
    line_width: Some(2.0),
    .. Default::default()
  };

  let program = glium::Program::from_source(
    &display,
    vertex_shader_src,
    fragment_shader_src,
    None).unwrap();

  let mut current_line : Vec<Vertex> = Vec::new();
  let mut commited_lines : Vec<glium::VertexBuffer<Vertex>> = Vec::new();

  #[derive(Copy, Clone)]
  enum State {
    None,
    Drawing,
    Dragging(Vec2<f32>)
  }

  let mut state = State::None;

  let mut scale = 1.0;
  let mut translation = Vec2::zero();
  let mut mouse_last = Vec2::zero();

  loop {

    let (frame_dx, frame_dy) = display.get_framebuffer_dimensions();
    let (frame_dx, frame_dy) = (frame_dx as f32, frame_dy as f32);

    let projection
      = Mat2::new(2.0/frame_dx, 0.0,
                  0.          , 2.0/frame_dy);

    for event in display.poll_events() {
      match (event, state) {

        (MouseWheel(PixelDelta(_, dy)), _)  => {
          if dy > 0.0 {
            scale /= 0.99;
          } else {
            scale *= 0.99;
          }
          translation = -mouse_last + mouse_last/scale;
        },

        (MouseInput(Pressed,Left), State::None) => {
          state = State::Drawing;
        },

        (MouseInput(Pressed,Middle), State::None) => {
            state = State::Dragging(mouse_last);
        },

        (MouseInput(Released,Left), State::Drawing) => {
            commited_lines.push(
              glium::VertexBuffer::immutable(&display, &current_line).unwrap());
            current_line.clear();
            state = State::None;
        },

        (MouseInput(Released,Middle), State::Dragging(_)) => {
            state = State::None;
        },

        (MouseMoved((mouse_x, mouse_y)), state) => {
          let screen
            = Vec2::new(
                2.0*(mouse_x as f32)/frame_dx - 1.0,
               -2.0*(mouse_y as f32)/frame_dy + 1.0);

          let world  = projection.inv().unwrap()
                        * (1.0/scale)
                        * screen
                        - translation;

          match state {
            State::Drawing => {
              current_line.push(Vertex{position: [world.x, world.y]});
            },
            State::Dragging(drag_start) => {
              translation.x +=  world.x - drag_start.x;
              translation.y +=  world.y - drag_start.y;
            },
            _ => {}
          }

          mouse_last = world;
        },

        (Closed, _) => return,
        _ => ()
      }
    }

    let uniforms = uniform!(
      projection : projection * scale,
      translation: translation,
    );

    let mut target = display.draw();
    target.clear_color(1.0, 1.0, 1.0, 1.0);

    for line in &commited_lines[..] {
      target.draw(
        line,
        &indices,
        &program,
        &uniforms,
        &params).unwrap();
    }

    if let State::Drawing = state {
        target.draw(
          &glium::VertexBuffer::new(&display, &current_line).unwrap(),
          &indices,
          &program,
          &uniforms,
          &Default::default()).unwrap();
    }

    target.finish().unwrap();
  }
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate log;
extern crate getopts;
#[macro_use]
extern crate shoop;

use std::str;
use std::env;
use std::path::Path;
use getopts::Options;
use shoop::{ShoopLogger, Server, download};
use shoop::connection::PortRange;

const DEFAULT_PORT_RANGE: &'static str = "55000-55050";

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Shoop is a ultrafast, (hopefully) secure file transfer tool, that is
(hopefully) ideal for transferring large files.

Usage: {0} [options] SOURCE DEST
...where HOST is an SSH host
...where PATH is the path on the *remote* machine of the file you want
...where DEST is either an existing folder or a location for the new
                 file (\".\" by default)

Example: {0} seedbox.facebook.com:/home/zuck/internalized_sadness.zip .",
                        program);
    print!("{}", opts.usage(&brief));
}

enum Target {
    Local(String),
    Remote(String, String),
}

impl Target {
    fn from(s: String) -> Target {
        match s.find(':') {
            None => Target::Local(s),
            Some(i) => {
                let owned = s.to_owned();
                let (first, second) = owned.split_at(i);
                if first.contains('/') {
                    Target::Local(s)
                } else {
                    Target::Remote(String::from(first), String::from(second))
                }
            }
        }
    }
}

fn main() {
    enum Mode {
        Server,
        Client,
    }
    ShoopLogger::init().expect("Error starting shoop logger.");

    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();
    let mut opts = Options::new();
    // TODO
    // opts.optopt("o", "output", "set output file name", "NAME");
    // opts.optopt("a", "ssh-args", "arguments to pass to ssh directly (at your own risk)", ARGS);
    opts.optopt("p",
                "port-range",
                "server listening port range",
                DEFAULT_PORT_RANGE);
    opts.optflag("s", "server", "server mode (advanced usage only)");
    opts.optflag("h", "help", "print this help menu");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string()),
    };

    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }

    let source = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        print_usage(&program, opts);
        return;
    };

    let mode: Mode = if matches.opt_present("s") {
        Mode::Server
    } else {
        Mode::Client
    };

    let port_range = {
        let range_opt = &matches.opt_str("p").unwrap_or_else(|| String::from(DEFAULT_PORT_RANGE));
        PortRange::from(range_opt).unwrap()
    };

    match mode {
        Mode::Server => {
            Server::new(port_range, &source).start();
        }
        Mode::Client => {
            let dest = if matches.free.len() > 1 {
                matches.free[1].clone()
            } else {
                String::from(".")
            };

            match Target::from(source) {
                Target::Local(_) => panic!("Sorry, you can only copy *from* a remote host currently."),
                Target::Remote(source_addr, source_path_str) => {
                    match Target::from(dest) {
                        Target::Remote(_,_) => panic!("Sorry, you can only copy to a local path currently."),
                        Target::Local(dest_path_str) => {
                            let source_path = Path::new(&source_path_str);
                            let source_file_name = match source_path.file_name() {
                                Some(s) => s,
                                None => {
                                    die!("The remote path specified doesn't look like a path to a file.");
                                }
                            };
                            let dest_path = Path::new(&dest_path_str);
                            let final_dest_path = if dest_path.is_dir() {
                                dest_path.join(source_file_name)
                            } else {
                                dest_path.to_path_buf()
                            };

                            download(&source_addr, port_range, &dest_path_str, final_dest_path);
                        }
                    }
                }
            }

        }
    }
}
<commit_msg>panic is the wrong thing to use here<commit_after>#[macro_use]
extern crate log;
extern crate getopts;
#[macro_use]
extern crate shoop;

use std::str;
use std::env;
use std::path::Path;
use getopts::Options;
use shoop::{ShoopLogger, Server, download};
use shoop::connection::PortRange;

const DEFAULT_PORT_RANGE: &'static str = "55000-55050";

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Shoop is a ultrafast, (hopefully) secure file transfer tool, that is
(hopefully) ideal for transferring large files.

Usage: {0} [options] SOURCE DEST
...where HOST is an SSH host
...where PATH is the path on the *remote* machine of the file you want
...where DEST is either an existing folder or a location for the new
                 file (\".\" by default)

Example: {0} seedbox.facebook.com:/home/zuck/internalized_sadness.zip .",
                        program);
    print!("{}", opts.usage(&brief));
}

enum Target {
    Local(String),
    Remote(String, String),
}

impl Target {
    fn from(s: String) -> Target {
        match s.find(':') {
            None => Target::Local(s),
            Some(i) => {
                let owned = s.to_owned();
                let (first, second) = owned.split_at(i);
                if first.contains('/') {
                    Target::Local(s)
                } else {
                    Target::Remote(String::from(first), String::from(second))
                }
            }
        }
    }
}

fn main() {
    enum Mode {
        Server,
        Client,
    }
    ShoopLogger::init().expect("Error starting shoop logger.");

    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();
    let mut opts = Options::new();
    // TODO
    // opts.optopt("o", "output", "set output file name", "NAME");
    // opts.optopt("a", "ssh-args", "arguments to pass to ssh directly (at your own risk)", ARGS);
    opts.optopt("p",
                "port-range",
                "server listening port range",
                DEFAULT_PORT_RANGE);
    opts.optflag("s", "server", "server mode (advanced usage only)");
    opts.optflag("h", "help", "print this help menu");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string()),
    };

    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }

    let source = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        print_usage(&program, opts);
        return;
    };

    let mode: Mode = if matches.opt_present("s") {
        Mode::Server
    } else {
        Mode::Client
    };

    let port_range = {
        let range_opt = &matches.opt_str("p").unwrap_or_else(|| String::from(DEFAULT_PORT_RANGE));
        PortRange::from(range_opt).unwrap()
    };

    match mode {
        Mode::Server => {
            Server::new(port_range, &source).start();
        }
        Mode::Client => {
            let dest = if matches.free.len() > 1 {
                matches.free[1].clone()
            } else {
                String::from(".")
            };

            match Target::from(source) {
                Target::Local(_) => error!("Sorry, you can only copy *from* a remote host currently."),
                Target::Remote(source_addr, source_path_str) => {
                    match Target::from(dest) {
                        Target::Remote(_,_) => error!("Sorry, you can only copy to a local path currently."),
                        Target::Local(dest_path_str) => {
                            let source_path = Path::new(&source_path_str);
                            let source_file_name = match source_path.file_name() {
                                Some(s) => s,
                                None => {
                                    error!("The remote path specified doesn't look like a path to a file.");
                                    std::process::exit(1);
                                }
                            };
                            let dest_path = Path::new(&dest_path_str);
                            let final_dest_path = if dest_path.is_dir() {
                                dest_path.join(source_file_name)
                            } else {
                                dest_path.to_path_buf()
                            };

                            download(&source_addr, port_range, &dest_path_str, final_dest_path);
                        }
                    }
                }
            }

        }
    }
}
<|endoftext|>


<commit_before>// Algobot 3, Rust Version
// Casey Primozic, 2016-2016

extern crate redis;
extern crate futures;
// extern crate futures_cpupool;

use std::thread;

use futures::*;
use futures::stream::{Stream, Sender, Receiver, channel};

mod datafield;
mod calc;
mod tick;
mod transport;
mod conf;

use transport::Tickstream;

// create a thread that
fn get_ticks(tx: Sender<String, ()>) {
    let mut ts = Tickstream::new();
    let listener = thread::spawn(move || {
        // perform blocking read operation inside the thread
        let res = ts.get_tick();
        // send the result from redis through the channel,
        // which returns a new tx.
        let new_tx = tx.send(Ok(res)).and_then(|new_tx| {
            println!("{:?}", "got it");
            // call this function and restart the process of listening for ticks.
            get_ticks(new_tx);
            Ok(())
        }).forget();
    });
}

fn main() {
    let (tx, rx) = channel::<String, ()>();

    // start listening for new ticks on a separate thread
    get_ticks(tx);

    // do something each time something is received on the Receiver
    rx.for_each(|res| {
        // do whatever you want to do with the received tick.
        // This will be handled asynchronously.
        println!("{:?}", res);
        Ok(())
    }).forget(); // register this callback and continue program's execution

    loop {
        // do whatever you want here and the tick listener
        // and callback will continue to run in the background
    }
}
<commit_msg>Added in a delay in the loop to prevent it from consuming 100% CPU Fixed comment<commit_after>// Algobot 3, Rust Version
// Casey Primozic, 2016-2016

extern crate redis;
extern crate futures;
// extern crate futures_cpupool;

use std::thread;
use std::time::Duration;

use futures::*;
use futures::stream::{Stream, Sender, Receiver, channel};

mod datafield;
mod calc;
mod tick;
mod transport;
mod conf;

use transport::Tickstream;

// create a thread that listens for new messages on redis
// and resets itself after the results are consumed
fn get_ticks(tx: Sender<String, ()>) {
    let mut ts = Tickstream::new();
    let listener = thread::spawn(move || {
        // perform blocking read operation inside the thread
        let res = ts.get_tick();
        // send the result from redis through the channel,
        // which returns a new tx.
        let new_tx = tx.send(Ok(res)).and_then(|new_tx| {
            println!("{:?}", "got it");
            // call this function and restart the process of listening for ticks.
            get_ticks(new_tx);
            Ok(())
        }).forget();
    });
}

fn main() {
    let (tx, rx) = channel::<String, ()>();

    // start listening for new ticks on a separate thread
    get_ticks(tx);

    // do something each time something is received on the Receiver
    rx.for_each(|res| {
        // do whatever you want to do with the received tick.
        // This will be handled asynchronously.
        println!("{:?}", res);
        Ok(())
    }).forget(); // register this callback and continue program's execution

    loop {
        // do whatever you want here and the tick listener
        // and callback will continue to run in the background
        thread::sleep(Duration::new(5, 0));
    }
}
<|endoftext|>


<commit_before>extern crate gfx_texture;
extern crate image;
extern crate piston;
extern crate piston_window;
extern crate texture;

use gfx_texture::Texture;
use image::ImageBuffer;
use piston::input::*;
use piston_window::*;
use texture::TextureSettings;

const WIDTH: u32 = 60;  // Width of window, in cells.
const HEIGHT: u32 = 60;  // Height of window, in cells.
const CELL_SIZE: u32 = 10;  // Effectively a zoom factor.  CELL_SIZE * WIDTH => width of the window in pixels.

fn main() {
	let mut window : PistonWindow = WindowSettings::new("conway", [WIDTH * CELL_SIZE, HEIGHT * CELL_SIZE])
		.exit_on_esc(true)
		.build()
		.expect("error making window");

	// Since we're modeling one cell per pixel, the texture gets magnified.  Setting the
	// mag filter to Nearest gives us sharp edges on the cells.
	let tset = TextureSettings::new()
		.mag(texture::Filter::Nearest);

	let buf = vec![0u8; (WIDTH * HEIGHT * 4) as usize];
	let mut cells = ImageBuffer::from_raw(WIDTH, HEIGHT, buf).unwrap();
	let mut tex = Texture::from_image(&mut window.factory, &cells, &tset).unwrap();

	while let Some(e) = window.next() {
		if let Some(Button::Keyboard(key)) = e.press_args() {
			if key == Key::Space {
				for p in cells.enumerate_pixels_mut() {
					if p.0 % 2 == p.1 % 2 {
						p.2.data = [0xFF, 0xFF, 0xFF, 0xFF];
					}
				}
				tex = Texture::from_image(&mut window.factory, &cells, &tset).unwrap();
			}
		}
		window.draw_2d(&e, |c, g| {
			clear([0.0, 0.0, 0.0, 1.0], g);
			image(&tex, c.transform.scale(CELL_SIZE as f64, CELL_SIZE as f64), g);
		});
	}
}
<commit_msg>Added a basic tick to control the recalculation timing<commit_after>extern crate gfx_texture;
extern crate image;
extern crate piston;
extern crate piston_window;
extern crate texture;

use gfx_texture::Texture;
use image::ImageBuffer;
use piston::input::*;
use piston_window::*;
use std::time;
use texture::TextureSettings;

const WIDTH: u32 = 60;  // Width of window, in cells.
const HEIGHT: u32 = 60;  // Height of window, in cells.
const CELL_SIZE: u32 = 10;  // Effectively a zoom factor.  CELL_SIZE * WIDTH => width of the window in pixels.
const TICK_PERIOD: u32 = 1500;  // The number of milliseconds between each recalculation of the cell grid.

fn main() {
	let mut window : PistonWindow = WindowSettings::new("conway", [WIDTH * CELL_SIZE, HEIGHT * CELL_SIZE])
		.exit_on_esc(true)
		.build()
		.expect("error making window");

	// Since we're modeling one cell per pixel, the texture gets magnified.  Setting the
	// mag filter to Nearest gives us sharp edges on the cells.
	let tset = TextureSettings::new()
		.mag(texture::Filter::Nearest);

	// This is our cell buffer.  When using the iterators provided by ImageBuffer, p.0 and p.1
	// are the x, y coordinates, and p.2 is the four-byte array that represents RGBA.
	let buf = vec![0u8; (WIDTH * HEIGHT * 4) as usize];
	let mut cells = ImageBuffer::from_raw(WIDTH, HEIGHT, buf).unwrap();
	let mut tex = Texture::from_image(&mut window.factory, &cells, &tset).unwrap();

	// Time keeping to know when to recalculate the cell grid.
	let tick_period = time::Duration::from_millis(TICK_PERIOD as u64);
	let mut last_tick = time::Instant::now();

	// Don't start the game until the user presses a key.  This gives the "player" an opportunity
	// to observe the starting state.
	while let Some(e) = window.next() {
		// Render the starting position.  (For now, just a blank slate)
		window.draw_2d(&e, |_, g| {
			clear([1.0, 1.0, 1.0, 1.0], g);
		});

		if e.press_args().is_some() {
			break;
		}
	}

	// Main game loop: continue recalculating and rendering once per tick forever.
	while let Some(e) = window.next() {
		// Recalculate the cell field once per tick.
		if last_tick.elapsed() > tick_period {
			for p in cells.enumerate_pixels_mut() {
				p.2.data = [0, 0, 0, 255];
			}
			tex = Texture::from_image(&mut window.factory, &cells, &tset).unwrap();
			last_tick = time::Instant::now();
		}

		// This is the draw step.  In our case it's very simple - clear the window then render
		// the image buffer as a scaled-up texture.
		window.draw_2d(&e, |c, g| {
			clear([0.0, 0.0, 0.0, 1.0], g);
			image(&tex, c.transform.scale(CELL_SIZE as f64, CELL_SIZE as f64), g);
		});

	}
}
<|endoftext|>


<commit_before>#![feature(globs)]

extern crate graphics;
extern crate piston;
extern crate sdl2_game_window;
extern create opengl_graphics;

upse opengl_graphics::{
    Gl,
    Texture,
};

use sdl2_game_window::WindowSDL2;

use piston::{
    AssetStore,
    EventIterator,
    EventSettings,
    WindowSettings,
    Render,
};

fn main() {
    let opengl = piston::shader_version::opengl::OpenGL_3_2;
    let mut window = WindowSDL2::new(
        opengl,
        WindowSettings {
            title: "Image".to_string(),
            size: [480,800],
            fullscreen: false,
            exit_on_esc: true,
            samples: 0,
        }
    );

    let asset_store = AssetStore::from_folder("../bin/assets");

    let image = asset_store.path("rust-logo.png").unwrap();
    let image = Texture::from_path(&image).unwrap();
    let event_settings = EventSettings {
        update_per_second: 120,
        max_frames_per_second: 60,
    };

    let ref mut gl = Gl::new(opengl);
    for e in EventIterator::new(&mut window, &event_settings) {
        match e {
            Render(args) => {
                gl.viewport(0, 0, args.width as i32, args.height as i32);

                let c = Context::abs(args.width as f64, args.height as f64);

                c.rgb(1.0, 1.0, 1.0).draw(gl);
                c.image(&image).draw(gl);

            },
            _ => {},
        }
    }
}
<commit_msg>Now recreates piston-example image<commit_after>
#![feature(globs)]

extern crate graphics;
extern crate piston;
extern crate sdl2_game_window;
extern crate opengl_graphics;

use opengl_graphics::{
    Gl,
    Texture,
};
use sdl2_game_window::WindowSDL2;
use piston::{
    AssetStore,
    EventIterator,
    EventSettings,
    WindowSettings,
    Render,
};
use piston::graphics::*;

fn main() {
    let opengl = piston::shader_version::opengl::OpenGL_3_2;
    let mut window = WindowSDL2::new(
        opengl,
        WindowSettings {
            title: "Image".to_string(),
            size: [800,480],
            fullscreen: false,
            exit_on_esc: true,
            samples: 0,
        }
    );

    let asset_store = AssetStore::from_folder("../bin/assets");

    let image = asset_store.path("rust-logo.png").unwrap();
    let image = Texture::from_path(&image).unwrap();
    let event_settings = EventSettings {
            updates_per_second: 120,
            max_frames_per_second: 60,
        };
    let ref mut gl = Gl::new(opengl);
    for e in EventIterator::new(&mut window, &event_settings) {
        match e {
            Render(args) => {
                gl.viewport(0, 0, args.width as i32, args.height as i32);

                let c = Context::abs(args.width as f64, args.height as f64);
                c.rgb(1.0, 1.0, 1.0).draw(gl);
                    c.image(&image).draw(gl);
            },
            _ => {},
        }
    }
}

<|endoftext|>


<commit_before>extern crate byteorder;
extern crate crc;

use std::fs::File;
use std::io::{Read, Result, Error, Seek, SeekFrom};
use std::io::ErrorKind::Other;

use byteorder::{LittleEndian, ByteOrder};

use crc::{crc32, Hasher32};

const LABEL_SCAN_SECTORS: usize = 4;
const MYPATH: &'static str = "/dev/mapper/luks-291e9250-200e-4c36-8e5e-66aa257669ed";
const ID_LEN: usize = 32;
const MDA_MAGIC: &'static str = "\x20\x4c\x56\x4d\x32\x20\x78\x5b\x35\x41\x25\x72\x30\x4e\x2a\x3e";
const INITIAL_CRC: u32 = 0xf597a6cf;
const SECTOR_SIZE: usize = 512;

#[derive(Debug)]
struct Label {
    id: String,
    sector: u64,
    crc: u32,
    offset: u32,
    label: String,
}

#[derive(Debug)]
struct PvArea {
    offset: u64,
    size: u64,
}

#[derive(Debug)]
struct PvHeader {
    uuid: String,
    size: u64, // in bytes
    ext_version: u32,
    ext_flags: u32,
    data_areas: Vec<PvArea>,
    metadata_areas: Vec<PvArea>,
    bootloader_areas: Vec<PvArea>,
}

fn get_label(buf: &[u8]) -> Result<Label> {
    for x in 0..LABEL_SCAN_SECTORS {
        let sec_buf = &buf[x*SECTOR_SIZE..x*SECTOR_SIZE+SECTOR_SIZE];
        if &sec_buf[..8] == b"LABELONE" {
            let crc = LittleEndian::read_u32(&sec_buf[16..20]);
            crc32_ok(crc, &sec_buf[20..SECTOR_SIZE]);

            let sector = LittleEndian::read_u64(&sec_buf[8..16]);
            if sector != x as u64 {
                println!("sector field is {} in sector {}", sector, x);
            }

            return Ok(Label{
                id: String::from_utf8_lossy(&sec_buf[..8]).into_owned(),
                sector: sector,
                crc: crc,
                offset: LittleEndian::read_u32(&sec_buf[20..24]) + (x*SECTOR_SIZE as usize) as u32,
                label: String::from_utf8_lossy(&sec_buf[24..32]).into_owned(),
            })
        }
    }

    Err(Error::new(Other, "bad"))
}

fn get_pv_header(buf: &[u8]) -> Result<PvHeader> {

    let mut da_buf = &buf[ID_LEN+8..];
    let mut da_vec = Vec::new();

    loop {
        let da_off = LittleEndian::read_u64(&da_buf[..8]);
        if da_off == 0 { break; }

        da_vec.push(PvArea {
            offset: da_off,
            size: LittleEndian::read_u64(&da_buf[8..16]),
        });

        da_buf = &da_buf[16..];
    }

    let mut md_vec = Vec::new();

    // metadata list is after a null entry for the data areas
    da_buf = &da_buf[16..];

    loop {
        let da_off = LittleEndian::read_u64(&da_buf[..8]);
        if da_off == 0 { break; }

        md_vec.push(PvArea {
            offset: da_off,
            size: LittleEndian::read_u64(&da_buf[8..16]),
        });

        da_buf = &da_buf[16..];
    }

    // pv extension is after a null entry for the metadata areas
    da_buf = &da_buf[16..];

    let ext_version = LittleEndian::read_u32(&da_buf[..4]);
    let mut ext_flags = 0;
    let mut ba_vec = Vec::new();

    if ext_version != 0 {
        ext_flags = LittleEndian::read_u32(&da_buf[4..8]);

        da_buf = &da_buf[8..];

        loop {
            let da_off = LittleEndian::read_u64(&da_buf[..8]);
            if da_off == 0 { break; }

            ba_vec.push(PvArea {
                offset: da_off,
                size: LittleEndian::read_u64(&da_buf[8..16]),
            });

            da_buf = &da_buf[16..];
        }
    }

    Ok(PvHeader{
        uuid: String::from_utf8_lossy(&buf[..ID_LEN]).into_owned(),
        size: LittleEndian::read_u64(&buf[ID_LEN..ID_LEN+8]),
        ext_version: ext_version,
        ext_flags: ext_flags,
        data_areas: da_vec,
        metadata_areas: md_vec,
        bootloader_areas: ba_vec,
    })
}

fn crc32_ok(val: u32, buf: &[u8]) -> bool {
    let mut digest = crc32::Digest::new(INITIAL_CRC);
    digest.write(&buf);
    let crc32 = digest.sum32();
    if val != crc32 {
        println!("CRC32: input {:x} != calculated {:x}", val, crc32);
    }
    val == crc32
}

fn parse_mda_header(buf: &[u8]) -> () {

    let crc1 = LittleEndian::read_u32(&buf[..4]);

    // TODO: why is this failing?
    crc32_ok(crc1, &buf[4..512]);
}

fn find_stuff(path: &str) -> Result<Label> {

    let mut f = try!(File::open(path));

    let mut buf = vec![0; LABEL_SCAN_SECTORS * 512];

    try!(f.read(&mut buf));

    let label = try!(get_label(&buf));

    let pvheader = try!(get_pv_header(&buf[label.offset as usize..]));

    for md in &pvheader.metadata_areas {
        try!(f.seek(SeekFrom::Start(md.offset)));

        println!("AA {} {}", md.offset, md.size);

        let mut buf = vec![0; md.size as usize];

        try!(f.read(&mut buf));

        parse_mda_header(&buf);
    }

    println!("pvheader {:?}", pvheader);

    return Ok(label);
}

fn main() {

    let label = find_stuff(MYPATH).unwrap();

    println!("{:?}", label);
}
<commit_msg>Use an iterator for PV areas<commit_after>extern crate byteorder;
extern crate crc;

use std::fs::File;
use std::io::{Read, Result, Error, Seek, SeekFrom};
use std::io::ErrorKind::Other;

use byteorder::{LittleEndian, ByteOrder};

use crc::{crc32, Hasher32};

const LABEL_SCAN_SECTORS: usize = 4;
const MYPATH: &'static str = "/dev/mapper/luks-291e9250-200e-4c36-8e5e-66aa257669ed";
const ID_LEN: usize = 32;
const MDA_MAGIC: &'static str = "\x20\x4c\x56\x4d\x32\x20\x78\x5b\x35\x41\x25\x72\x30\x4e\x2a\x3e";
const INITIAL_CRC: u32 = 0xf597a6cf;
const SECTOR_SIZE: usize = 512;

#[derive(Debug)]
struct Label {
    id: String,
    sector: u64,
    crc: u32,
    offset: u32,
    label: String,
}

#[derive(Debug)]
struct PvArea {
    offset: u64,
    size: u64,
}

#[derive(Debug)]
struct PvHeader {
    uuid: String,
    size: u64, // in bytes
    ext_version: u32,
    ext_flags: u32,
    data_areas: Vec<PvArea>,
    metadata_areas: Vec<PvArea>,
    bootloader_areas: Vec<PvArea>,
}

fn get_label(buf: &[u8]) -> Result<Label> {
    for x in 0..LABEL_SCAN_SECTORS {
        let sec_buf = &buf[x*SECTOR_SIZE..x*SECTOR_SIZE+SECTOR_SIZE];
        if &sec_buf[..8] == b"LABELONE" {
            let crc = LittleEndian::read_u32(&sec_buf[16..20]);
            crc32_ok(crc, &sec_buf[20..SECTOR_SIZE]);

            let sector = LittleEndian::read_u64(&sec_buf[8..16]);
            if sector != x as u64 {
                println!("sector field is {} in sector {}", sector, x);
            }

            return Ok(Label{
                id: String::from_utf8_lossy(&sec_buf[..8]).into_owned(),
                sector: sector,
                crc: crc,
                offset: LittleEndian::read_u32(&sec_buf[20..24]) + (x*SECTOR_SIZE as usize) as u32,
                label: String::from_utf8_lossy(&sec_buf[24..32]).into_owned(),
            })
        }
    }

    Err(Error::new(Other, "bad"))
}

struct PvAreaIter<'a> {
    area: &'a[u8],
}

fn iter_pv_area<'a>(buf: &'a[u8]) -> PvAreaIter<'a> {
    PvAreaIter { area: buf }
}

impl<'a> Iterator for PvAreaIter<'a> {
    type Item = PvArea;

    fn next (&mut self) -> Option<PvArea> {
        let off = LittleEndian::read_u64(&self.area[..8]);
        let size = LittleEndian::read_u64(&self.area[8..16]);

        if off == 0 {
            None
        }
        else {
            self.area = &self.area[16..];
            Some(PvArea {
                offset: off,
                size: size,
            })
        }
    }
}

//
// PV HEADER LAYOUT:
// - static header (uuid and size)
// - 0+ data areas
// - blank entry
// - 0+ metadata areas
// - blank entry
// - 8 bytes of pvextension header
// - if version > 0
//   - list of bootloader areas
//
fn get_pv_header(buf: &[u8]) -> Result<PvHeader> {

    let mut da_buf = &buf[ID_LEN+8..];

    let da_vec: Vec<_> = iter_pv_area(da_buf).collect();

    // move slice past any actual entries plus blank
    // terminating entry
    da_buf = &da_buf[(da_vec.len()+1)*16..];

    let md_vec: Vec<_> = iter_pv_area(da_buf).collect();

    da_buf = &da_buf[(md_vec.len()+1)*16..];

    let ext_version = LittleEndian::read_u32(&da_buf[..4]);
    let mut ext_flags = 0;
    let mut ba_vec = Vec::new();

    if ext_version != 0 {
        ext_flags = LittleEndian::read_u32(&da_buf[4..8]);

        da_buf = &da_buf[8..];

        ba_vec = iter_pv_area(da_buf).collect();
    }

    Ok(PvHeader{
        uuid: String::from_utf8_lossy(&buf[..ID_LEN]).into_owned(),
        size: LittleEndian::read_u64(&buf[ID_LEN..ID_LEN+8]),
        ext_version: ext_version,
        ext_flags: ext_flags,
        data_areas: da_vec,
        metadata_areas: md_vec,
        bootloader_areas: ba_vec,
    })
}

fn crc32_ok(val: u32, buf: &[u8]) -> bool {
    let mut digest = crc32::Digest::new(INITIAL_CRC);
    digest.write(&buf);
    let crc32 = digest.sum32();
    if val != crc32 {
        println!("CRC32: input {:x} != calculated {:x}", val, crc32);
    }
    val == crc32
}

fn parse_mda_header(buf: &[u8]) -> () {

    let crc1 = LittleEndian::read_u32(&buf[..4]);

    // TODO: why is this failing?
    crc32_ok(crc1, &buf[4..512]);
}

fn find_stuff(path: &str) -> Result<Label> {

    let mut f = try!(File::open(path));

    let mut buf = vec![0; LABEL_SCAN_SECTORS * 512];

    try!(f.read(&mut buf));

    let label = try!(get_label(&buf));

    let pvheader = try!(get_pv_header(&buf[label.offset as usize..]));

    println!("pvheader {:?}", pvheader);

    for md in &pvheader.metadata_areas {
        try!(f.seek(SeekFrom::Start(md.offset)));

        println!("AA {} {}", md.offset, md.size);

        let mut buf = vec![0; md.size as usize];

        try!(f.read(&mut buf));

        parse_mda_header(&buf);
    }

    return Ok(label);
}

fn main() {

    let label = find_stuff(MYPATH).unwrap();

    println!("{:?}", label);
}
<|endoftext|>


<commit_before>extern crate log;
extern crate lancelot;

use std::env;
use std::process;
use log::{debug, error, trace};
use goblin::Object;

use lancelot::{Workspace, Error};
use lancelot::analysis;

pub struct Config {
    pub filename: String,
}

impl Config {
    pub fn from_args(args: env::Args) -> Result<Config, &'static str> {
        let args: Vec<String> = args.collect();

        if args.len() < 2 {
            return Err("not enough arguments");
        }

        let filename = args[1].clone();
        trace!("config: parsed filename: {:?}", filename);

        Ok(Config { filename })
    }
}

pub fn setup_logging(_args: &Config) {
    simplelog::TermLogger::init(simplelog::LevelFilter::Info, simplelog::Config::default())
        .expect("failed to setup logging");
}

pub fn run(args: &Config) -> Result<(), Error> {
    debug!("filename: {:?}", args.filename);
    let ws = Workspace::from_file(&args.filename)?;

    if let Object::PE(pe) = ws.get_obj()? {
        let oep = if let Some(opt) = pe.header.optional_header {
            opt.standard_fields.address_of_entry_point
        } else {
            0x0
        };
        println!("entrypoint: {:}", ws.get_insn(oep)?);
    }

    //println!("roots: {:}", analysis::find_roots(&ws).expect("foo").len());
    /*
    println!(
        "call targets: {:}",
        analysis::find_call_targets(&ws).expect("foo").len()
    );
    println!(
        "branch targets: {:}",
        analysis::find_branch_targets(&ws).expect("foo").len()
    );
    */
    println!(
        "entry points: {:}",
        analysis::find_entrypoints(&ws).expect("foo").len()
    );
    println!(
        "runtime functions: {:}",
        analysis::find_runtime_functions(&ws).expect("foo").len()
    );

    let fvas = analysis::find_functions(&ws).expect("foo");

    println!("find functions: {:}", fvas.len());

    analysis::compute_coverage(&ws, &fvas)?;

    Ok(())
}

fn main() {
    let args = Config::from_args(env::args()).unwrap_or_else(|err| {
        eprintln!("error parsing arguments: {}", err);
        process::exit(1);
    });

    setup_logging(&args);

    if let Err(e) = run(&args) {
        error!("{:?}", e)
    }
}
<commit_msg>main: bump logging levels<commit_after>extern crate log;
extern crate lancelot;

use std::env;
use std::process;
use log::{error, info, trace};
use goblin::Object;

use lancelot::{Workspace, Error};
use lancelot::analysis;

pub struct Config {
    pub filename: String,
}

impl Config {
    pub fn from_args(args: env::Args) -> Result<Config, &'static str> {
        let args: Vec<String> = args.collect();

        if args.len() < 2 {
            return Err("not enough arguments");
        }

        let filename = args[1].clone();
        trace!("config: parsed filename: {:?}", filename);

        Ok(Config { filename })
    }
}

pub fn setup_logging(_args: &Config) {
    simplelog::TermLogger::init(simplelog::LevelFilter::Info, simplelog::Config::default())
        .expect("failed to setup logging");
}

pub fn run(args: &Config) -> Result<(), Error> {
    info!("filename: {:?}", args.filename);
    let ws = Workspace::from_file(&args.filename)?;

    if let Object::PE(pe) = ws.get_obj()? {
        let oep = if let Some(opt) = pe.header.optional_header {
            opt.standard_fields.address_of_entry_point
        } else {
            0x0
        };
        println!("entrypoint: {:}", ws.get_insn(oep)?);
    }

    //println!("roots: {:}", analysis::find_roots(&ws).expect("foo").len());
    /*
    println!(
        "call targets: {:}",
        analysis::find_call_targets(&ws).expect("foo").len()
    );
    println!(
        "branch targets: {:}",
        analysis::find_branch_targets(&ws).expect("foo").len()
    );
    */
    println!(
        "entry points: {:}",
        analysis::find_entrypoints(&ws).expect("foo").len()
    );
    println!(
        "runtime functions: {:}",
        analysis::find_runtime_functions(&ws).expect("foo").len()
    );

    let fvas = analysis::find_functions(&ws).expect("foo");

    println!("find functions: {:}", fvas.len());

    analysis::compute_coverage(&ws, &fvas)?;

    Ok(())
}

fn main() {
    let args = Config::from_args(env::args()).unwrap_or_else(|err| {
        eprintln!("error parsing arguments: {}", err);
        process::exit(1);
    });

    setup_logging(&args);

    if let Err(e) = run(&args) {
        error!("{:?}", e)
    }
}
<|endoftext|>


<commit_before>fn main() {
    println!("Hello, world!");
}
<commit_msg>added main function to generate random password and added length argument<commit_after>extern crate argparse;
extern crate rand;

use rand::{random, Rng};
use argparse::{ArgumentParser, Store};

fn random_password(length:u32) -> String {
    (0..length).map(|_| (0x20u8 + (random::<f32>() * 96.0) as u8) as char).collect()
}

fn main() {
    let mut length:u32 = rand::thread_rng().gen_range(10, 21);
    {  // this block limits scope of borrows by ap.refer() method
        let mut ap = ArgumentParser::new();
        ap.set_description("This tool generates a random password");
        ap.refer(&mut length)
        .add_option(&["-l", "--length"], Store,
        "Length of password, defaults to a random length between 10 and 20");
        ap.parse_args_or_exit();
    }
    println!("Generated password of length {} => {}", length, random_password(length));
}
<|endoftext|>