main.rs 19.3 KB
Newer Older
Anders Blomdell's avatar
Anders Blomdell committed
1
2
3
4
5
6
7
8
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};
Anders Blomdell's avatar
Anders Blomdell committed
9
use std::sync::mpsc::{channel, Receiver, Sender};
Anders Blomdell's avatar
Anders Blomdell committed
10
11
12
13
14
15
use std::thread;
use std::fmt;
use std::process::exit;
use threadpool::ThreadPool;
use std::collections::HashMap;
use std::cell::RefCell;
Anders Blomdell's avatar
Anders Blomdell committed
16
use libc::{c_int, time_t};
Anders Blomdell's avatar
Anders Blomdell committed
17
18
19
20
21
use std::result::Result;
use std::io::Error as IOError;
use std::io::{self, Write};

mod libhash;
Anders Blomdell's avatar
Anders Blomdell committed
22
23
24
use libhash::{FLAGS_CLEAR_XATTR, FLAGS_READ_XATTR, FLAGS_WRITE_XATTR,
              FLAGS_MAX_AGE, FLAGS_NO_CALC_HASH,
              FLAGS_VERBOSE0, FLAGS_VERBOSE1, FLAGS_VERBOSE2, FLAGS_VERBOSE3};
Anders Blomdell's avatar
Anders Blomdell committed
25
26
27
28
29
30
31
32
33
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(()));
}

Anders Blomdell's avatar
Anders Blomdell committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Extract clap optin as an Option<t>
macro_rules! option_t_or_exit {
    ($m:ident, $v:expr, $t:ty) => (
        if let Some(v) = $m.value_of($v) {
            match v.trim().parse::<$t>() {
                Ok(val) => Option::Some(val),
                Err(_)  => {
                    println!("Argument '--{} {}' cant be parsed as '{}'",
                             $v, v, stringify!($t));
                    exit(1);
                }
            }
        } else {
            Option::None
        }
    )
}

#[derive(Clone)]
Anders Blomdell's avatar
Anders Blomdell committed
53
54
struct Inode {
    path: PathBuf,
55
    metadata: Option<Metadata>
Anders Blomdell's avatar
Anders Blomdell committed
56
57
58
59
60
61
62
63
}

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

enum WalkerMessage {
Anders Blomdell's avatar
Anders Blomdell committed
64
65
    Start(PathBuf),
    Inode(Inode), //path: PathBuf, metadata: Metadata},
Anders Blomdell's avatar
Anders Blomdell committed
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
    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 {
Anders Blomdell's avatar
Anders Blomdell committed
92
93
94
95
    inode: Inode,
    kind: char,
    md5: RefCell<HashOption<String, std::io::Error>>,
    sha512: RefCell<HashOption<String, std::io::Error>>
Anders Blomdell's avatar
Anders Blomdell committed
96
97
98
99
}

#[derive(Debug)]
struct WorkList {
Anders Blomdell's avatar
Anders Blomdell committed
100
101
102
    first: usize,
    last: usize,
    list: HashMap<usize, HashEntry>
Anders Blomdell's avatar
Anders Blomdell committed
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
}

#[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)
        }
    }
}

Anders Blomdell's avatar
Anders Blomdell committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
struct WorkerPool<T> {
    pool: ThreadPool,
    pending: usize,
    rx: Receiver<T>,
    tx: Sender<T>
}

/*trait ExecuteIf {
    fn execute_if<F, G, H>(&self, guard: bool, func: F)
        where F: FnOnce() -> G + Send + 'static,
              G: FnOnce() -> H + Send + 'static,
              H: std::fmt::Debug;
}

impl ExecuteIf for WorkerPool {
 */
impl<T> WorkerPool<T> {
    fn new(jobs: usize) -> WorkerPool<T> {
        let (tx, rx) = channel::<T>();
        WorkerPool {
            pool: ThreadPool::new(jobs),
            pending: 0,
            rx: rx,
            tx: tx
        }
    }
    fn free(&self) -> bool {
        self.pool.max_count() > self.pending
    }
    fn execute_if<F>(&mut self, guard: bool, func: F)
        where F: FnOnce() -> T + Send + 'static,
              T: Send + std::fmt::Debug + 'static {
        if guard {
            self.pending += 1;
            let tx = self.tx.clone();
            self.pool.execute(move || {
                tx.send(func()).unwrap();
            })
        }
    }
    fn recv(&mut self) -> T {
        self.pending -= 1;
        self.rx.recv().unwrap()
    }
}

fn options_to_flags(options: &clap::ArgMatches) -> (c_int, time_t) {
Anders Blomdell's avatar
Anders Blomdell committed
190
191
192
193
    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");
Anders Blomdell's avatar
Anders Blomdell committed
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
    let maxage = option_t_or_exit!(options, "max_age", libc::time_t);
    let mut flags = 0;
    let mut age = 0;
    match (xattr, read_xattr, write_xattr, clear_xattr, maxage) {
        (false, false, false, false, None) => {
        },
        (true, false, false, false, None) |
        (false, true, true, false, None) => {
            flags = FLAGS_READ_XATTR | FLAGS_WRITE_XATTR;
        },
        (true, false, false, false, Some(maxage)) |
        (false, true, true, false, Some(maxage)) => {
            flags = FLAGS_READ_XATTR | FLAGS_WRITE_XATTR | FLAGS_MAX_AGE;
            age = maxage;
        },
        (false, true, false, false, None) => {
            flags = FLAGS_READ_XATTR;
Anders Blomdell's avatar
Anders Blomdell committed
211
        },
Anders Blomdell's avatar
Anders Blomdell committed
212
213
214
        (false, true, false, false, Some(maxage)) => {
            flags = FLAGS_READ_XATTR | FLAGS_MAX_AGE;
            age = maxage;
Anders Blomdell's avatar
Anders Blomdell committed
215
        },
Anders Blomdell's avatar
Anders Blomdell committed
216
217
        (false, false, false, true, None) => {
            flags = FLAGS_CLEAR_XATTR | FLAGS_NO_CALC_HASH;
Anders Blomdell's avatar
Anders Blomdell committed
218
        },
Anders Blomdell's avatar
Anders Blomdell committed
219
220
221
222
        (_, _, _, _, Some(age)) => {
            panic!("--maxage={} specified without sane xattr flags", age);
        },
        (_, _, _, _, _) => {
Anders Blomdell's avatar
Anders Blomdell committed
223
224
225
            panic!("Invalid flags");
        }
    }
Anders Blomdell's avatar
Anders Blomdell committed
226
227
228
229
230
231
232
233
    match (options.is_present("quiet"), options.occurrences_of("verbose")) {
        (true, 0) => flags |= FLAGS_VERBOSE0,
        (false, 0) => flags |= FLAGS_VERBOSE1,
        (false, 1) => flags |= FLAGS_VERBOSE2,
        (false, 2) => flags |= FLAGS_VERBOSE3,
        (_, _) => panic!("Invalid verbosity")
    }
    (flags, age)
Anders Blomdell's avatar
Anders Blomdell committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
}

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>) {
Anders Blomdell's avatar
Anders Blomdell committed
249
250
251
    let jobs = option_t_or_exit!(options, "jobs", usize).unwrap_or(1);
    let lookahead = option_t_or_exit!(options, "lookahead", usize)
        .unwrap_or(jobs * 10);
Anders Blomdell's avatar
Anders Blomdell committed
252
253
    let calc_md5 = options.is_present("md5");
    let calc_sha512 = options.is_present("sha512");
Anders Blomdell's avatar
Anders Blomdell committed
254
255
    let (flags, maxage) = options_to_flags(&options);
    let mut pool = WorkerPool::<WorkerMessage>::new(jobs);
Anders Blomdell's avatar
Anders Blomdell committed
256
257
    let mut worklist = WorkList::new();
    let mut done = false;
258
259
260
261
    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
262
263
264
265
    loop {
        // reportln!("XXX {} {} {}", done, pending, worklist.used());
        if done && worklist.used() == 0 {
            break;
Anders Blomdell's avatar
Anders Blomdell committed
266
267
        } if !done && pool.free() && worklist.used() < lookahead {
            // Get paths from walker and enqueue work
Anders Blomdell's avatar
Anders Blomdell committed
268
269
270
271
272
            let message = match from_walker.recv() {
                Ok(message) => message,
                Err(_) => break
            };
            match message {
Anders Blomdell's avatar
Anders Blomdell committed
273
                WalkerMessage::Start(path) => {
274
275
276
277
278
279
280
281
282
283
                    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
284
                WalkerMessage::Inode(inode) => {
Anders Blomdell's avatar
Anders Blomdell committed
285
                    // Push to worklist
Anders Blomdell's avatar
Anders Blomdell committed
286
287
                    let path = inode.path;
                    let metadata = inode.metadata.unwrap();
Anders Blomdell's avatar
Anders Blomdell committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
                    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(),
305
                            metadata: Some(metadata.clone())
Anders Blomdell's avatar
Anders Blomdell committed
306
307
308
309
310
311
312
313
314
                        },
                        kind: kind,
                        md5: RefCell::new(md5),
                        sha512: RefCell::new(sha512),
                    });

                    match kind {
                        'F' => {
                            use WorkerMessageHash::{MD5, SHA512};
Anders Blomdell's avatar
Anders Blomdell committed
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
                            pool.execute_if(calc_md5, {
                                let path = path.clone();
                                let metadata = metadata.clone();
                                move || {
                                    let h = md5_file(path.as_path(),
                                                     metadata,
                                                     flags, maxage);
                                    WorkerMessage {
                                        index: index,
                                        hash: MD5(h)
                                    }
                                }
                            });
                            pool.execute_if(calc_sha512, {
                                let path = path.clone();
                                move || {
                                    let h = sha512_file(path.as_path(),
                                                        metadata,
                                                        flags, maxage);
                                    WorkerMessage {
                                        index: index,
                                        hash: SHA512(h)
                                    }
                                }
                            });
Anders Blomdell's avatar
Anders Blomdell committed
340
341
342
                        },
                        'L' => {
                            use WorkerMessageHash::{MD5, SHA512};
Anders Blomdell's avatar
Anders Blomdell committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
                            pool.execute_if(calc_md5, {
                                let path = path.clone();
                                move || {
                                    let h = md5_symlink(path.as_path());
                                    WorkerMessage {
                                        index: index,
                                        hash: MD5(h)
                                    }
                                }
                            });
                            pool.execute_if(calc_sha512, {
                                let path = path.clone();
                                move || {
                                    let h = sha512_symlink(path.as_path());
                                    WorkerMessage {
                                        index: index,
                                        hash: SHA512(h)
                                    }
                                }
                            });

Anders Blomdell's avatar
Anders Blomdell committed
364
365
366
367
368
369
370
                        },
                        _ => ()
                    };
                },
                WalkerMessage::Done =>
                    done = true,
            }
Anders Blomdell's avatar
Anders Blomdell committed
371
372
373
        } else if pool.pending > 0 {
            // Handle finished results
            let message = pool.recv();
Anders Blomdell's avatar
Anders Blomdell committed
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
            let index = message.index;
            let item = worklist.get(index).unwrap();
            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;
405
            } else {
Anders Blomdell's avatar
Anders Blomdell committed
406
407
408
409
410
411
412
413
                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),
Anders Blomdell's avatar
Anders Blomdell committed
414
                        (_, _)                => Option::None
Anders Blomdell's avatar
Anders Blomdell committed
415
                    };
Anders Blomdell's avatar
Anders Blomdell committed
416
417
418
                    if flags & FLAGS_CLEAR_XATTR != 0 {
                        continue;
                    }
Anders Blomdell's avatar
Anders Blomdell committed
419
420
421
422
                    match error {
                        Option::Some(e) => {
                            // Failed to checksum file, report and drop
                            reportln!("Error: {:?} {}", front.inode.path, e);
423
                            continue
Anders Blomdell's avatar
Anders Blomdell committed
424
425
426
427
428
                        }
                        _ => ()
                    }
                };
                match front.kind {
429
430
431
432
433
                    ' ' => {
                        // Start of new path
                        println!("#path: {}", front.inode.path.display());
                        continue
                    },
Anders Blomdell's avatar
Anders Blomdell committed
434
                    'F' | 'L' => {
435
                        let m = &front.inode.metadata.unwrap();
Anders Blomdell's avatar
Anders Blomdell committed
436
437
438
439
440
                        print!("{}:{}:{}:{}:{:o}:",
                               m.size(), m.mtime(), m.uid(), m.gid(),
                               m.mode() & 0o7777);
                    },
                    _ => {
441
                        let m = &front.inode.metadata.unwrap();
Anders Blomdell's avatar
Anders Blomdell committed
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
                        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());
            }
        }
    }
470
    println!("#endTOC")
Anders Blomdell's avatar
Anders Blomdell committed
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
}

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")
Anders Blomdell's avatar
Anders Blomdell committed
517
             .conflicts_with("quiet")
Anders Blomdell's avatar
Anders Blomdell committed
518
519
             .multiple(true)
             .help("Sets the level of verbosity"))
Anders Blomdell's avatar
Anders Blomdell committed
520
521
522
523
        .arg(Arg::with_name("quiet")
             .short("q")
             .conflicts_with("verbose")
             .help("Sets the level of verbosity"))
Anders Blomdell's avatar
Anders Blomdell committed
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
        .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 | {
Anders Blomdell's avatar
Anders Blomdell committed
544
545
        tx.send( WalkerMessage::Inode(
            Inode{path:p.to_owned(), metadata:Some(m.clone())})).unwrap();
Anders Blomdell's avatar
Anders Blomdell committed
546
    };
547
548
549
    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
550
    for p in paths {
551
        let path = std::path::Path::new(p);
Anders Blomdell's avatar
Anders Blomdell committed
552
        let _ = tx.send(WalkerMessage::Start(path.to_owned()));
Anders Blomdell's avatar
Anders Blomdell committed
553
554
555
556
557
        walk::visit(std::path::Path::new(p), &callback).unwrap();
    }
    tx.send(WalkerMessage::Done).unwrap();
    worker.join().unwrap();
}