main.rs 15.5 KB
Newer Older
Anders Blomdell's avatar
Anders Blomdell committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
extern crate clap;
extern crate libc;
extern crate threadpool;

use clap::{Arg, App};
use std::os::unix::fs::{FileTypeExt, MetadataExt};
use std::fs::{Metadata};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{channel, Receiver};
use std::thread;
use std::fmt;
use std::process::exit;
use threadpool::ThreadPool;
use std::collections::HashMap;
use std::cell::RefCell;
use libc::c_int;
use std::result::Result;
use std::io::Error as IOError;
use std::io::{self, Write};

mod libhash;
mod hash;
use hash::{md5_file, md5_symlink, sha512_file, sha512_symlink};
mod walk;

macro_rules! reportln {
    () => (writeln!(io::stderr()).unwrap_or(()));
    ($($arg:tt)*) => (writeln!(io::stderr(), $($arg)*).unwrap_or(()));
}

struct Inode {
    path: PathBuf,
33
    metadata: Option<Metadata>
Anders Blomdell's avatar
Anders Blomdell committed
34
35
36
37
38
39
40
41
}

impl std::fmt::Debug for Inode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Inode {{ path: {:?} }}", self.path)
    }}

enum WalkerMessage {
42
    Start{path: PathBuf},
Anders Blomdell's avatar
Anders Blomdell committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    Inode{path: PathBuf, metadata: Metadata},
    Done
}

#[derive(Debug)]
enum WorkerMessageHash {
    MD5(Result<String, IOError>),
    SHA512(Result<String, IOError>)
}

#[derive(Debug)]
struct WorkerMessage {
    index:usize,
    hash: WorkerMessageHash
}

#[derive(Debug)]
enum HashOption<T, E> {
    None,
    Unused,
    Pending,
    Err(E),
    Some(T)
}

#[derive(Debug)]
struct HashEntry {
    inode : Inode,
    kind : char,
    md5 : RefCell<HashOption<String, std::io::Error>>,
    sha512 : RefCell<HashOption<String, std::io::Error>>
}

#[derive(Debug)]
struct WorkList {
    first : usize,
    last : usize,
    list : HashMap<usize, HashEntry>
}

#[allow(dead_code)]
impl WorkList {
    fn new() -> WorkList {
        WorkList{first: 0,
                 last: 0,
                 list: HashMap::<usize, HashEntry>::new()
        }
    }
    fn used(&self) -> usize {
        self.last - self.first
    }
    fn get_front(&self) -> Option<&HashEntry> {
        if self.first == self.last {
            None
        } else {
            self.list.get(&self.first)
        }
    }
    fn get(&self, index: usize) -> Option<&HashEntry> {
        self.list.get(&index)
    }
    fn push_back(&mut self, entry: HashEntry) -> usize {
        let last = self.last;
        self.last += 1;
        self.list.insert(last, entry);
        last
    }
    fn pop_front(&mut self) -> Option<HashEntry> {
       if self.first == self.last {
            None
       } else {
           let first = self.first;
           self.first += 1;
           self.list.remove(&first)
        }
    }
}

fn options_to_flags(options: &clap::ArgMatches) -> c_int {
    let xattr = options.is_present("xattr");
    let read_xattr = options.is_present("read_xattr");
    let write_xattr = options.is_present("write_xattr");
    let clear_xattr = options.is_present("clear_xattr");
    let mut flags : c_int = 0;
    match (xattr, read_xattr, write_xattr, clear_xattr) {
        (false, false, false, false) => {
            flags = 0;
        },
        (true, false, false, false) |
        (false, true, true, false) => {
            flags |= libhash::FLAGS_READ_XATTR | libhash::FLAGS_WRITE_XATTR;
        },
        (false, false, false, true) => {
            flags |= libhash::FLAGS_CLEAR_XATTR;
        },
        (_, _, _, _) => {
            panic!("Invalid flags");
        }
    }
    flags
}

fn file_type_to_flag(file_type: &std::fs::FileType) -> char {
    if file_type.is_file()              { 'F' }
    else if file_type.is_symlink()      { 'L' }
    else if file_type.is_dir()          { 'D' }
    else if file_type.is_char_device()  { 'C' }
    else if file_type.is_block_device() { 'B' }
    else if file_type.is_socket()       { 'S' }
    else if file_type.is_fifo()         { 'P' }
    else                                { unreachable!() }
}

fn dispatcher(options: clap::ArgMatches,
              from_walker: Receiver<WalkerMessage>) {
    macro_rules! parse_opt {
159
        ($n:expr, $t:ty) => (
Anders Blomdell's avatar
Anders Blomdell committed
160
161
            if let Some(v) = options.value_of($n) {
                match v.parse::<$t>() {
162
                    Ok(val) => Option::Some(val),
Anders Blomdell's avatar
Anders Blomdell committed
163
164
165
166
167
168
169
                    Err(_)  => {
                        println!("Argument '--{} {}' cant be parsed as '{}'",
                                 $n, v, stringify!($t));
                        exit(1);
                    }
                }
            } else {
170
                Option::None
Anders Blomdell's avatar
Anders Blomdell committed
171
172
173
            }
        )
    };
174
175
    let jobs = parse_opt!("jobs", usize).unwrap_or(1);
    let lookahead = parse_opt!("lookahead", usize).unwrap_or(jobs * 10);
Anders Blomdell's avatar
Anders Blomdell committed
176
177
178
179
180
181
182
183
    let calc_md5 = options.is_present("md5");
    let calc_sha512 = options.is_present("sha512");
    let flags = options_to_flags(&options);
    let mut pending = 0 as usize;
    let pool = ThreadPool::new(jobs);
    let mut worklist = WorkList::new();
    let (worker_to_dispatcher, from_pool) = channel::<WorkerMessage>();
    let mut done = false;
184
185
186
187
    print!("#fields: size:mtime:uid:gid:mode:");
    if calc_md5 { print!("md5:"); }
    if calc_sha512 { print!("sha512:"); }
    println!("kind:name");
Anders Blomdell's avatar
Anders Blomdell committed
188
189
190
191
192
193
194
195
196
197
198
    loop {
        // reportln!("XXX {} {} {}", done, pending, worklist.used());
        if done && worklist.used() == 0 {
            break;
        } if !done && pending < jobs && worklist.used() < lookahead {
            // Get paths to checksum
            let message = match from_walker.recv() {
                Ok(message) => message,
                Err(_) => break
            };
            match message {
199
200
201
202
203
204
205
206
207
208
209
                WalkerMessage::Start{path} => {
                    worklist.push_back(HashEntry {
                        inode: Inode {
                            path:path.clone(),
                            metadata: None
                        },
                        kind: ' ',
                        md5: RefCell::new(HashOption::Unused),
                        sha512: RefCell::new(HashOption::Unused),
                    });
                },
Anders Blomdell's avatar
Anders Blomdell committed
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
                WalkerMessage::Inode{path, metadata} => {
                    // Push to worklist
                    use HashOption::{Pending, Unused, None};
                    let (kind, md5, sha512) = match
                        file_type_to_flag(&metadata.file_type()) {
                            kind @ 'F' | kind @ 'L' =>
                                (kind,
                                 if calc_md5 { Pending } else { Unused },
                                 if calc_sha512 { Pending } else { Unused }
                                ),
                            kind @ _ =>
                                (kind,
                                 if calc_md5 { None } else { Unused },
                                 if calc_sha512 { None } else { Unused }
                                )
                        };
                    let index = worklist.push_back(HashEntry {
                        inode: Inode {
                            path:path.clone(),
229
                            metadata: Some(metadata.clone())
Anders Blomdell's avatar
Anders Blomdell committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
                        },
                        kind: kind,
                        md5: RefCell::new(md5),
                        sha512: RefCell::new(sha512),
                    });

                    // Spawn off needed work
                    macro_rules! execute {
                        ($guard:expr, $func:expr, $message:ident) => (
                            if $guard {
                                let path = path.clone();
                                let tx = worker_to_dispatcher.clone();
                                let flags = flags;
                                pending += 1;
                                pool.execute(move || {
                                    let h = $func(path.as_path(), flags);
                                    tx.send( WorkerMessage {
                                        index: index,
                                        hash:$message(h)
                                    }).unwrap();
                                });
                            }
                        )
                    };
                    match kind {
                        'F' => {
                            use WorkerMessageHash::{MD5, SHA512};
                            execute!(calc_md5, md5_file, MD5);
                            execute!(calc_sha512, sha512_file, SHA512);
                        },
                        'L' => {
                            use WorkerMessageHash::{MD5, SHA512};
                            execute!(calc_md5, md5_symlink, MD5);
                            execute!(calc_sha512, sha512_symlink, SHA512);
                        },
                        _ => ()
                    };
                },
                WalkerMessage::Done =>
                    done = true,
            }
        } else if pending > 0 {
            // Handle paths being processed
            let message = from_pool.recv().unwrap();
            let index = message.index;
            let item = worklist.get(index).unwrap();
            pending -= 1;
            use WorkerMessageHash::{MD5,SHA512};
            match message.hash {
                MD5(hash)  => {
                    *item.md5.borrow_mut() = match hash {
                        Ok(h @ _) => HashOption::Some(h),
                        Err(e @ _) => HashOption::Err(e)
                    }
                },
                SHA512(hash)  => {
                    *item.sha512.borrow_mut() = match hash {
                        Ok(h @ _) => HashOption::Some(h),
                        Err(e @ _) => HashOption::Err(e)
                    }
                }
            }
        }
        
        // Consume finished entries
        while worklist.used() > 0 {
            if { use HashOption::Pending;
                 let front = worklist.get_front().unwrap();
                 let ref md5 = *front.md5.borrow();
                 let ref sha512 = *front.sha512.borrow();
                 match (md5, sha512) {
                     (&Pending, _) | (_, &Pending) => true,
                     (_, _) => false
                 } } {
                // First entry still has pending work
                break;
306
            } else {
Anders Blomdell's avatar
Anders Blomdell committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
                let front = worklist.pop_front().unwrap();
                {
                    let ref md5 = *front.md5.borrow();
                    let ref sha512 = *front.sha512.borrow();
                    use HashOption::{Err};
                    let error = match ( md5, sha512 ) {
                        (&Err(ref e @ _), _) => Option::Some(e),
                        (_, &Err(ref e @ _)) => Option::Some(e),
                        (_,_)                => Option::None
                    };
                    match error {
                        Option::Some(e) => {
                            // Failed to checksum file, report and drop
                            reportln!("Error: {:?} {}", front.inode.path, e);
321
                            continue
Anders Blomdell's avatar
Anders Blomdell committed
322
323
324
325
326
                        }
                        _ => ()
                    }
                };
                match front.kind {
327
328
329
330
331
                    ' ' => {
                        // Start of new path
                        println!("#path: {}", front.inode.path.display());
                        continue
                    },
Anders Blomdell's avatar
Anders Blomdell committed
332
                    'F' | 'L' => {
333
                        let m = &front.inode.metadata.unwrap();
Anders Blomdell's avatar
Anders Blomdell committed
334
335
336
337
338
                        print!("{}:{}:{}:{}:{:o}:",
                               m.size(), m.mtime(), m.uid(), m.gid(),
                               m.mode() & 0o7777);
                    },
                    _ => {
339
                        let m = &front.inode.metadata.unwrap();
Anders Blomdell's avatar
Anders Blomdell committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
                        print!("::{}:{}:{:o}:",
                               m.uid(), m.gid(), m.mode() & 0o7777);
                    }
                }
                use HashOption::{None,Some,Unused};
                match *front.md5.borrow() {
                    None => print!(":"),
                    Some(ref hash) => print!("{}:", hash),
                    Unused => (),
                    _ => unreachable!()
                }
                match *front.sha512.borrow() {
                    None => print!(":"),
                    Some(ref hash) => print!("{}:", hash),
                    Unused => (),
                    _ => unreachable!()
                }                
                let mut path = front.inode.path.as_path();
                loop {
                    match path.strip_prefix("./") {
                        Ok(p) => path = p,
                        _ => break
                    }
                }
                println!("{}:{}", front.kind, path.display());
            }
        }
    }
368
    println!("#endTOC")
Anders Blomdell's avatar
Anders Blomdell committed
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
}

fn main() {
    let matches = App::new("hashtoc")
        .version("1.0")
        .author("Anders Blomdell <anders.blomdell@control.lth.se>")
        .about("Generate a Table Of Contents with HASHes for all files")
        .arg(Arg::with_name("jobs")
             .short("j")
             .long("jobs")
             .takes_value(true)
             .help("number of jobs [threads] to use for HASH calculations"))
        .arg(Arg::with_name("lookahead")
             .short("l")
             .long("lookahead")
             .takes_value(true)
             .help("size of lookahead buffer for HASH calculations [jobs*10]"))
        .arg(Arg::with_name("xattr")
             .short("x")
             .long("xattr")
             .conflicts_with_all(&["read_xattr", "write_xattr", "clear_xattr"])
             .help("read/write HASH extended attribute(s)"))
        .arg(Arg::with_name("read_xattr")
             .short("r")
             .long("read-xattr")
             .conflicts_with_all(&["xattr", "clear_xattr"])
             .help(concat!("read HASH extended attribute(s)\n",
                           "(remove if mtime mismatch detected)")))
        .arg(Arg::with_name("write_xattr")
             .short("w")
             .long("write-xattr")
             .conflicts_with_all(&["xattr", "clear_xattr"])
             .help("write HASH extended attribute(s)"))
        .arg(Arg::with_name("clear_xattr")
             .short("c")
             .long("clear-xattr")
             .conflicts_with_all(&["xattr", "read_xattr", "write_xattr"])
             .help("clear hash extended attribute(s)"))
        .arg(Arg::with_name("md5")
             .long("md5")
             .help("Calculate MD5 hash"))
        .arg(Arg::with_name("sha512")
             .long("sha512")
             .help("Calculate SHA512 hash"))
        .arg(Arg::with_name("verbose")
             .short("v")
             .multiple(true)
             .help("Sets the level of verbosity"))
        .arg(Arg::with_name("max_age")
             .short("m")
             .long("max-age")
             .takes_value(true)
             .help("max age of HASH extended attribute(s)"))
        .arg(Arg::with_name("PATH")
             .help("path(s) to traverse")
             .required(true)
             .multiple(true)
             .index(1))
        .get_matches();


    let (worker, tx) = {
        let (tx, rx) = channel();
        let args = matches.clone();
        let worker = thread::spawn(move|| { dispatcher(args, rx); });
        (worker, tx)
    };
    let callback = | p:&Path, m:&Metadata | {
        tx.send( WalkerMessage::Inode{
            path:p.to_owned(), metadata:m.clone()}).unwrap();
    };
440
441
442
    let paths : Vec<_> = matches.values_of_os("PATH").unwrap().collect();
//    let mut paths : Vec<_> = matches.values_of_os("PATH").unwrap().collect();
//    paths.sort();
Anders Blomdell's avatar
Anders Blomdell committed
443
    for p in paths {
444
445
        let path = std::path::Path::new(p);
        let _ = tx.send(WalkerMessage::Start{path: path.to_owned()});
Anders Blomdell's avatar
Anders Blomdell committed
446
447
448
449
450
        walk::visit(std::path::Path::new(p), &callback).unwrap();
    }
    tx.send(WalkerMessage::Done).unwrap();
    worker.join().unwrap();
}