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
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  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
 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
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 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
 306
 307
 308
 309
 310
 311
 312
 313
 314
 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
 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
 368
 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
 440
 441
 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
 470
 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
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
use errno::{errno, Errno};
use glfs::*;
use libc::{c_uchar, c_void, dev_t, dirent, ENOENT, flock, LOCK_SH, LOCK_EX, LOCK_UN, ino_t, mode_t,
           stat, timespec};
use libffi::high::Closure3;

use std::error::Error as err;
use std::mem::zeroed;
use std::ffi::{CStr, CString, IntoStringError, NulError};
use std::fmt;
use std::io::Error;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::ptr;
use std::string::FromUtf8Error;

/// Custom error handling for the library
#[derive(Debug)]
pub enum GlusterError {
    FromUtf8Error(FromUtf8Error),
    NulError(NulError),
    Error(String),
    IoError(Error),
    IntoStringError(IntoStringError),
}

impl fmt::Display for GlusterError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.description())
    }
}

impl err for GlusterError {
    fn description(&self) -> &str {
        match *self {
            GlusterError::FromUtf8Error(ref e) => e.description(),
            GlusterError::NulError(ref e) => e.description(),
            GlusterError::Error(ref e) => &e,
            GlusterError::IoError(ref e) => e.description(),
            GlusterError::IntoStringError(ref e) => e.description(),
        }
    }
    fn cause(&self) -> Option<&err> {
        match *self {
            GlusterError::FromUtf8Error(ref e) => e.cause(),
            GlusterError::NulError(ref e) => e.cause(),
            GlusterError::Error(_) => None,
            GlusterError::IoError(ref e) => e.cause(),
            GlusterError::IntoStringError(ref e) => e.cause(),
        }
    }
}
impl GlusterError {
    /// Create a new GlusterError with a String message
    fn new(err: String) -> GlusterError {
        GlusterError::Error(err)
    }

    /// Convert a GlusterError into a String representation.
    pub fn to_string(&self) -> String {
        match *self {
            GlusterError::FromUtf8Error(ref err) => err.utf8_error().to_string(),
            GlusterError::NulError(ref err) => err.description().to_string(),
            GlusterError::Error(ref err) => err.to_string(),
            GlusterError::IoError(ref err) => err.description().to_string(),
            GlusterError::IntoStringError(ref err) => err.description().to_string(),
        }
    }
}

impl From<NulError> for GlusterError {
    fn from(err: NulError) -> GlusterError {
        GlusterError::NulError(err)
    }
}

impl From<FromUtf8Error> for GlusterError {
    fn from(err: FromUtf8Error) -> GlusterError {
        GlusterError::FromUtf8Error(err)
    }
}
impl From<IntoStringError> for GlusterError {
    fn from(err: IntoStringError) -> GlusterError {
        GlusterError::IntoStringError(err)
    }
}
impl From<Error> for GlusterError {
    fn from(err: Error) -> GlusterError {
        GlusterError::IoError(err)
    }
}

fn get_error() -> String {
    let error = errno();
    format!("{}", error)
}

/// Apply or remove an advisory lock on the open file.
pub enum PosixLockCmd {
    /// Place  an  exclusive  lock.  Only one process may hold an
    /// exclusive lock for a given file at a given time.
    Exclusive,
    /// Place a shared lock. More than one  process may  hold  a shared
    /// lock for a given file at a given time.
    Shared,
    /// Remove an existing lock held by this process.
    Unlock,
}

impl Into<i32> for PosixLockCmd {
    fn into(self) -> i32 {
        match self {
            PosixLockCmd::Shared => LOCK_SH,
            PosixLockCmd::Exclusive => LOCK_EX,
            PosixLockCmd::Unlock => LOCK_UN,
        }
    }
}

// pub type glfs_io_cbk = ::std::option::Option<extern "C" fn(fd: *mut glfs_fd_t,
// ret: ssize_t,
// data: *mut c_void)
// -> ()>;pub type glfs_io_cbk = ::std::option::Option<extern "C" fn(fd: *mut glfs_fd_t,
// ret: ssize_t,
// data: *mut c_void)
// -> ()>;
//
#[derive(Debug)]
pub struct Gluster {
    cluster_handle: *mut Struct_glfs,
}

impl Drop for Gluster {
    fn drop(&mut self) {
        if self.cluster_handle.is_null() {
            // No cleanup needed
            return;
        }
        unsafe {
            glfs_fini(self.cluster_handle);
        }
    }
}

/// This uses readdirplus which is very efficient in Gluster.  In addition
/// to returning directory entries this also stats each file.
#[derive(Debug)]
pub struct GlusterDirectoryPlus {
    pub dir_handle: *mut Struct_glfs_fd,
}

pub struct DirEntryPlus {
    pub path: PathBuf,
    pub inode: ino_t,
    pub file_type: c_uchar,
    pub stat: stat,
}

impl Iterator for GlusterDirectoryPlus {
    type Item = DirEntryPlus;
    fn next(&mut self) -> Option<DirEntryPlus> {
        let mut dirent: dirent = unsafe { zeroed() };
        let mut next_entry: *mut dirent = ptr::null_mut();
        unsafe {
            let mut stat_buf: stat = zeroed();
            let ret_code =
                glfs_readdirplus_r(self.dir_handle, &mut stat_buf, &mut dirent, &mut next_entry);
            if ret_code < 0 {
                glfs_closedir(self.dir_handle);
                return None;
            }
            if dirent.d_ino == 0 {
                // End of stream reached
                return None;
            }
            let telldir_retcode = glfs_telldir(self.dir_handle);
            if telldir_retcode < 0 {
                return None;
            }
            let file_name = CStr::from_ptr(dirent.d_name.as_ptr());
            return Some(DirEntryPlus {
                path: PathBuf::from(file_name.to_string_lossy().into_owned()),
                inode: dirent.d_ino,
                file_type: dirent.d_type,
                stat: stat_buf,
            });
        }

    }
}

#[derive(Debug)]
pub struct GlusterDirectory {
    pub dir_handle: *mut Struct_glfs_fd,
}

#[derive(Debug)]
pub struct DirEntry {
    pub path: PathBuf,
    pub inode: ino_t,
    pub file_type: c_uchar,
}

impl Iterator for GlusterDirectory {
    type Item = DirEntry;
    fn next(&mut self) -> Option<DirEntry> {
        let mut dirent: dirent = unsafe { zeroed() };
        let mut next_entry: *mut dirent = ptr::null_mut();
        unsafe {
            let ret_code = glfs_readdir_r(self.dir_handle, &mut dirent, &mut next_entry);
            if ret_code < 0 {
                glfs_closedir(self.dir_handle);
                return None;
            }
            if dirent.d_ino == 0 {
                // End of stream reached
                return None;
            }
            let telldir_retcode = glfs_telldir(self.dir_handle);
            if telldir_retcode < 0 {
                return None;
            }
            let file_name = CStr::from_ptr(dirent.d_name.as_ptr());
            return Some(DirEntry {
                path: PathBuf::from(file_name.to_string_lossy().into_owned()),
                inode: dirent.d_ino,
                file_type: dirent.d_type,
            });
        }

    }
}

impl Gluster {
    /// Connect to a Ceph cluster and return a connection handle glfs_t
    /// port is usually 24007 but may differ depending on how the service was configured
    pub fn connect(volume_name: &str, server: &str, port: u16) -> Result<Gluster, GlusterError> {
        let vol_name = try!(CString::new(volume_name));
        let vol_transport = try!(CString::new("tcp"));
        let vol_host = try!(CString::new(server));
        unsafe {
            let cluster_handle = glfs_new(vol_name.as_ptr());
            if cluster_handle.is_null() {
                return Err(GlusterError::new("glfs_new failed".to_string()));
            }
            let ret_code = glfs_set_volfile_server(cluster_handle,
                                                   vol_transport.as_ptr(),
                                                   vol_host.as_ptr(),
                                                   port as ::libc::c_int);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }

            let ret_code = glfs_init(cluster_handle);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
            Ok(Gluster { cluster_handle: cluster_handle })
        }
    }

    /// Disconnect from a Gluster cluster and destroy the connection handle
    /// For clean up, this is only necessary after connect() has succeeded.
    /// Normally there is no need to call this function.  When Rust cleans
    /// up the Gluster struct it will automatically call disconnect
    pub fn disconnect(self) {
        if self.cluster_handle.is_null() {
            // No cleanup needed
            return;
        }
        unsafe {
            glfs_fini(self.cluster_handle);
        }
    }
    pub fn open(&self, path: &Path, flags: i32) -> Result<*mut Struct_glfs_fd, GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let file_handle = glfs_open(self.cluster_handle, path.as_ptr(), flags);
            Ok(file_handle)
        }
    }
    pub fn create(&self,
                  path: &Path,
                  flags: i32,
                  mode: mode_t)
                  -> Result<*mut Struct_glfs_fd, GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let file_handle = glfs_creat(self.cluster_handle, path.as_ptr(), flags, mode);
            if file_handle.is_null() {
                return Err(GlusterError::new(get_error()));
            }
            Ok(file_handle)
        }
    }
    pub fn close(&self, file_handle: *mut Struct_glfs_fd) -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_close(file_handle);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn read(&self,
                file_handle: *mut Struct_glfs_fd,
                fill_buffer: &mut Vec<u8>,
                count: usize,
                flags: i32)
                -> Result<isize, GlusterError> {
        self.pread(file_handle, fill_buffer, count, 0, flags)
    }
    pub fn write(&self,
                 file_handle: *mut Struct_glfs_fd,
                 buffer: &[u8],
                 flags: i32)
                 -> Result<isize, GlusterError> {
        self.pwrite(file_handle, buffer, buffer.len(), 0, flags)
    }

    pub fn write_async<F>(&self,
                          file_handle: *mut Struct_glfs_fd,
                          buffer: &[u8],
                          flags: i32,
                          callback: F,
                          data: &mut ::libc::c_void)
                          -> Result<(), GlusterError>
        where F: Fn(*mut Struct_glfs_fd, isize, *mut ::libc::c_void)
    {
        let closure = Closure3::new(&callback);
        let callback_ptr = closure.code_ptr();
        unsafe {
            let ret_code = glfs_write_async(file_handle,
                                            buffer.as_ptr() as *const c_void,
                                            buffer.len(),
                                            flags,
                                            Some(*callback_ptr),
                                            data);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn readv(&self,
                 file_handle: *mut Struct_glfs_fd,
                 iov: &mut [&mut [u8]],
                 flags: i32)
                 -> Result<isize, GlusterError> {
        unsafe {
            let read_size = glfs_readv(file_handle,
                                       iov.as_ptr() as *const iovec,
                                       iov.len() as i32,
                                       flags);
            if read_size < 0 {
                return Err(GlusterError::new(get_error()));
            }
            Ok(read_size)

        }
    }
    pub fn writev(&self,
                  file_handle: *mut Struct_glfs_fd,
                  iov: &[&[u8]],
                  flags: i32)
                  -> Result<isize, GlusterError> {
        unsafe {
            let write_size = glfs_writev(file_handle,
                                         iov.as_ptr() as *const iovec,
                                         iov.len() as i32,
                                         flags);
            if write_size < 0 {
                return Err(GlusterError::new(get_error()));
            }
            Ok(write_size)

        }
    }

    /// Read into fill_buffer at offset and return the number of bytes read
    pub fn pread(&self,
                 file_handle: *mut Struct_glfs_fd,
                 fill_buffer: &mut Vec<u8>,
                 count: usize,
                 offset: i64,
                 flags: i32)
                 -> Result<isize, GlusterError> {
        unsafe {
            let read_size = glfs_pread(file_handle,
                                       fill_buffer.as_mut_ptr() as *mut c_void,
                                       count,
                                       offset,
                                       flags);
            if read_size < 0 {
                return Err(GlusterError::new(get_error()));
            }
            fill_buffer.set_len(read_size as usize);
            Ok(read_size)
        }
    }
    pub fn pwrite(&self,
                  file_handle: *mut Struct_glfs_fd,
                  buffer: &[u8],
                  count: usize,
                  offset: i64,
                  flags: i32)
                  -> Result<isize, GlusterError> {
        unsafe {
            let write_size = glfs_pwrite(file_handle,
                                         buffer.as_ptr() as *mut c_void,
                                         count,
                                         offset,
                                         flags);
            if write_size < 0 {
                return Err(GlusterError::new(get_error()));
            }
            Ok(write_size)

        }
    }

    pub fn preadv(&self,
                  file_handle: *mut Struct_glfs_fd,
                  iov: &mut [&mut [u8]],
                  offset: i64,
                  flags: i32)
                  -> Result<isize, GlusterError> {
        unsafe {
            let read_size = glfs_preadv(file_handle,
                                        iov.as_ptr() as *const iovec,
                                        iov.len() as i32,
                                        offset,
                                        flags);
            if read_size < 0 {
                return Err(GlusterError::new(get_error()));
            }
            Ok(read_size)
        }
    }
    // TODO: Use C IoVec
    pub fn pwritev(&self,
                   file_handle: *mut Struct_glfs_fd,
                   iov: &[&[u8]],
                   offset: i64,
                   flags: i32)
                   -> Result<isize, GlusterError> {
        unsafe {
            let write_size = glfs_pwritev(file_handle,
                                          iov.as_ptr() as *const iovec,
                                          iov.len() as i32,
                                          offset,
                                          flags);
            if write_size < 0 {
                return Err(GlusterError::new(get_error()));
            }
            Ok(write_size)
        }
    }
    pub fn lseek(&self,
                 file_handle: *mut Struct_glfs_fd,
                 offset: i64,
                 whence: i32)
                 -> Result<i64, GlusterError> {
        unsafe {
            let file_offset = glfs_lseek(file_handle, offset, whence);
            if file_offset < 0 {
                return Err(GlusterError::new(get_error()));
            }
            Ok(file_offset)

        }

    }
    pub fn truncate(&self, path: &Path, length: i64) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));

        unsafe {
            let ret_code = glfs_truncate(self.cluster_handle, path.as_ptr(), length);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn ftruncate(&self,
                     file_handle: *mut Struct_glfs_fd,
                     length: i64)
                     -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_ftruncate(file_handle, length);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn lsstat(&self, path: &Path) -> Result<stat, GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let mut stat_buf: stat = zeroed();
            let ret_code = glfs_lstat(self.cluster_handle, path.as_ptr(), &mut stat_buf);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
            Ok(stat_buf)
        }
    }
    /// Tests for the existance of a file.  Returns true/false respectively.
    pub fn exists(&self, path: &Path) -> Result<bool, GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let mut stat_buf: stat = zeroed();
            let ret_code = glfs_stat(self.cluster_handle, path.as_ptr(), &mut stat_buf);
            if ret_code < 0 {
                let error = errno();
                if error == Errno(ENOENT) {
                    return Ok(false);
                }
                return Err(GlusterError::new(get_error()));
            }
            Ok(false)
        }
    }

    pub fn stat(&self, path: &Path) -> Result<stat, GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let mut stat_buf: stat = zeroed();
            let ret_code = glfs_stat(self.cluster_handle, path.as_ptr(), &mut stat_buf);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
            Ok(stat_buf)
        }

    }
    pub fn fstat(&self, file_handle: *mut Struct_glfs_fd) -> Result<stat, GlusterError> {
        unsafe {
            let mut stat_buf: stat = zeroed();
            let ret_code = glfs_fstat(file_handle, &mut stat_buf);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
            Ok(stat_buf)
        }
    }
    pub fn fsync(&self, file_handle: *mut Struct_glfs_fd) -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_fsync(file_handle);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    pub fn fdatasync(&self, file_handle: *mut Struct_glfs_fd) -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_fdatasync(file_handle);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }

        }
        Ok(())
    }
    pub fn access(&self, path: &Path, mode: i32) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_access(self.cluster_handle, path.as_ptr(), mode);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }

        }
        Ok(())
    }

    pub fn symlink(&self, oldpath: &Path, newpath: &Path) -> Result<(), GlusterError> {
        let old_path = try!(CString::new(oldpath.as_os_str().as_bytes()));
        let new_path = try!(CString::new(newpath.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_symlink(self.cluster_handle, old_path.as_ptr(), new_path.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }

        }
        Ok(())
    }

    pub fn readlink(&self, path: &Path, buf: &mut [u8]) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_readlink(self.cluster_handle,
                                         path.as_ptr(),
                                         buf.as_mut_ptr() as *mut i8,
                                         buf.len());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    pub fn mknod(&self, path: &Path, mode: mode_t, dev: dev_t) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_mknod(self.cluster_handle, path.as_ptr(), mode, dev);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }

        }
        Ok(())
    }

    pub fn mkdir(&self, path: &Path, mode: mode_t) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_mkdir(self.cluster_handle, path.as_ptr(), mode);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }

        }
        Ok(())
    }

    pub fn unlink(&self, path: &Path) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_unlink(self.cluster_handle, path.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }

        }
        Ok(())
    }
    pub fn rmdir(&self, path: &Path) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_rmdir(self.cluster_handle, path.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn rename(&self, oldpath: &Path, newpath: &Path) -> Result<(), GlusterError> {
        let old_path = try!(CString::new(oldpath.as_os_str().as_bytes()));
        let new_path = try!(CString::new(newpath.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_rename(self.cluster_handle, old_path.as_ptr(), new_path.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    pub fn link(&self, oldpath: &Path, newpath: &Path) -> Result<(), GlusterError> {
        let old_path = try!(CString::new(oldpath.as_os_str().as_bytes()));
        let new_path = try!(CString::new(newpath.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_link(self.cluster_handle, old_path.as_ptr(), new_path.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    pub fn opendir(&self, path: &Path) -> Result<*mut Struct_glfs_fd, GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let file_handle = glfs_opendir(self.cluster_handle, path.as_ptr());
            Ok(file_handle)
        }
    }
    pub fn getxattr(&self, path: &Path, name: &str) -> Result<String, GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        let name = try!(CString::new(name));
        let mut xattr_val_buff: Vec<u8> = Vec::with_capacity(1024);
        unsafe {
            let ret_code = glfs_getxattr(self.cluster_handle,
                                         path.as_ptr(),
                                         name.as_ptr(),
                                         xattr_val_buff.as_mut_ptr() as *mut c_void,
                                         xattr_val_buff.len());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
            // Set the buffer to the size of bytes read into it
            xattr_val_buff.set_len(ret_code as usize);
            Ok(String::from_utf8_lossy(&xattr_val_buff).into_owned())
        }
    }

    pub fn lgetxattr(&self, path: &Path, name: &str) -> Result<String, GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        let name = try!(CString::new(name));
        let mut xattr_val_buff: Vec<u8> = Vec::with_capacity(1024);
        unsafe {
            let ret_code = glfs_lgetxattr(self.cluster_handle,
                                          path.as_ptr(),
                                          name.as_ptr(),
                                          xattr_val_buff.as_mut_ptr() as *mut c_void,
                                          xattr_val_buff.len());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
            // Set the buffer to the size of bytes read into it
            xattr_val_buff.set_len(ret_code as usize);
            Ok(String::from_utf8_lossy(&xattr_val_buff).into_owned())
        }
    }
    pub fn fgetxattr(&self,
                     file_handle: *mut Struct_glfs_fd,
                     name: &str)
                     -> Result<String, GlusterError> {
        let name = try!(CString::new(name));
        let mut xattr_val_buff: Vec<u8> = Vec::with_capacity(1024);
        unsafe {
            let ret_code = glfs_fgetxattr(file_handle,
                                          name.as_ptr(),
                                          xattr_val_buff.as_mut_ptr() as *mut c_void,
                                          xattr_val_buff.len());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
            // Set the buffer to the size of bytes read into it
            xattr_val_buff.set_len(ret_code as usize);
            Ok(String::from_utf8_lossy(&xattr_val_buff).into_owned())
        }
    }
    pub fn listxattr(&self, path: &Path) -> Result<String, GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        let mut xattr_val_buff: Vec<u8> = Vec::with_capacity(1024);
        unsafe {
            let ret_code = glfs_listxattr(self.cluster_handle,
                                          path.as_ptr(),
                                          xattr_val_buff.as_mut_ptr() as *mut c_void,
                                          xattr_val_buff.len());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
            // Set the buffer to the size of bytes read into it
            xattr_val_buff.set_len(ret_code as usize);
            Ok(String::from_utf8_lossy(&xattr_val_buff).into_owned())
        }
    }
    pub fn llistxattr(&self, path: &Path) -> Result<String, GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        let mut xattr_val_buff: Vec<u8> = Vec::with_capacity(1024);
        unsafe {
            let ret_code = glfs_llistxattr(self.cluster_handle,
                                           path.as_ptr(),
                                           xattr_val_buff.as_mut_ptr() as *mut c_void,
                                           xattr_val_buff.len());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
            // Set the buffer to the size of bytes read into it
            xattr_val_buff.set_len(ret_code as usize);
            Ok(String::from_utf8_lossy(&xattr_val_buff).into_owned())
        }
    }
    pub fn flistxattr(&self, file_handle: *mut Struct_glfs_fd) -> Result<String, GlusterError> {
        let mut xattr_val_buff: Vec<u8> = Vec::with_capacity(1024);
        unsafe {
            let ret_code = glfs_flistxattr(file_handle,
                                           xattr_val_buff.as_mut_ptr() as *mut c_void,
                                           xattr_val_buff.len());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
            // Set the buffer to the size of bytes read into it
            xattr_val_buff.set_len(ret_code as usize);
            Ok(String::from_utf8_lossy(&xattr_val_buff).into_owned())
        }
    }
    pub fn setxattr(&self,
                    path: &Path,
                    name: &str,
                    value: &[u8],
                    flags: i32)
                    -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        let name = try!(CString::new(name));
        unsafe {
            let ret_code = glfs_setxattr(self.cluster_handle,
                                         path.as_ptr(),
                                         name.as_ptr(),
                                         value.as_ptr() as *const c_void,
                                         value.len(),
                                         flags);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn lsetxattr(&self,
                     name: &str,
                     value: &[u8],
                     path: &Path,
                     flags: i32)
                     -> Result<(), GlusterError> {
        let name = try!(CString::new(name));
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_lsetxattr(self.cluster_handle,
                                          path.as_ptr(),
                                          name.as_ptr(),
                                          value.as_ptr() as *const c_void,
                                          value.len(),
                                          flags);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn fsetxattr(&self,
                     file_handle: *mut Struct_glfs_fd,
                     name: &str,
                     value: &[u8],
                     flags: i32)
                     -> Result<(), GlusterError> {
        let name = try!(CString::new(name));
        unsafe {
            let ret_code = glfs_fsetxattr(file_handle,
                                          name.as_ptr(),
                                          value.as_ptr() as *const c_void,
                                          value.len(),
                                          flags);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn removexattr(&self, path: &Path, name: &str) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        let name = try!(CString::new(name));
        unsafe {
            let ret_code = glfs_removexattr(self.cluster_handle, path.as_ptr(), name.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn lremovexattr(&self, path: &Path, name: &str) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        let name = try!(CString::new(name));
        unsafe {
            let ret_code = glfs_lremovexattr(self.cluster_handle, path.as_ptr(), name.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn fremovexattr(&self,
                        file_handle: *mut Struct_glfs_fd,
                        name: &str)
                        -> Result<(), GlusterError> {
        let name = try!(CString::new(name));

        unsafe {
            let ret_code = glfs_fremovexattr(file_handle, name.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn fallocate(&self,
                     file_handle: *mut Struct_glfs_fd,
                     offset: i64,
                     keep_size: i32,
                     len: usize)
                     -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_fallocate(file_handle, keep_size, offset, len);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn discard(&self,
                   file_handle: *mut Struct_glfs_fd,
                   offset: i64,
                   len: usize)
                   -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_discard(file_handle, offset, len);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn zerofill(&self,
                    file_handle: *mut Struct_glfs_fd,
                    offset: i64,
                    len: i64)
                    -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_zerofill(file_handle, offset, len);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn getcwd(&self) -> Result<String, GlusterError> {
        let mut cwd_val_buff: Vec<u8> = Vec::with_capacity(1024);
        unsafe {
            let cwd = glfs_getcwd(self.cluster_handle,
                                  cwd_val_buff.as_mut_ptr() as *mut i8,
                                  cwd_val_buff.len());
            Ok(CStr::from_ptr(cwd).to_string_lossy().into_owned())
        }
    }
    pub fn chdir(&self, path: &Path) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_chdir(self.cluster_handle, path.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }
    pub fn fchdir(&self, file_handle: *mut Struct_glfs_fd) -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_fchdir(file_handle);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    /// times[0] specifies the new "last access time" (atime);
    /// times[1] specifies the new "last modification time" (mtime).
    pub fn utimens(&self, path: &Path, times: &[timespec; 2]) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_utimens(self.cluster_handle, path.as_ptr(), times.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    /// times[0] specifies the new "last access time" (atime);
    /// times[1] specifies the new "last modification time" (mtime).
    pub fn lutimens(&self, path: &Path, times: &[timespec; 2]) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_lutimens(self.cluster_handle, path.as_ptr(), times.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    /// times[0] specifies the new "last access time" (atime);
    /// times[1] specifies the new "last modification time" (mtime).
    pub fn futimens(&self,
                    file_handle: *mut Struct_glfs_fd,
                    times: &[timespec; 2])
                    -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_futimens(file_handle, times.as_ptr());
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    pub fn posixlock(&self,
                     file_handle: *mut Struct_glfs_fd,
                     command: PosixLockCmd,
                     flock: &mut flock)
                     -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_posix_lock(file_handle, command.into(), flock);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    pub fn chmod(&self, path: &Path, mode: mode_t) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_chmod(self.cluster_handle, path.as_ptr(), mode);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    pub fn fchmod(&self,
                  file_handle: *mut Struct_glfs_fd,
                  mode: mode_t)
                  -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_fchmod(file_handle, mode);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    pub fn chown(&self, path: &Path, uid: u32, gid: u32) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_chown(self.cluster_handle, path.as_ptr(), uid, gid);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    pub fn lchown(&self, path: &Path, uid: u32, gid: u32) -> Result<(), GlusterError> {
        let path = try!(CString::new(path.as_os_str().as_bytes()));
        unsafe {
            let ret_code = glfs_lchown(self.cluster_handle, path.as_ptr(), uid, gid);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    pub fn fchown(&self,
                  file_handle: *mut Struct_glfs_fd,
                  uid: u32,
                  gid: u32)
                  -> Result<(), GlusterError> {
        unsafe {
            let ret_code = glfs_fchown(file_handle, uid, gid);
            if ret_code < 0 {
                return Err(GlusterError::new(get_error()));
            }
        }
        Ok(())
    }

    // pub fn realpath(&self, path: &str) -> Result<String, GlusterError> {
    // let path = try!(CString::new(path));
    // let resolved_path_buf: Vec<u8> = Vec::with_capacity(512);
    // unsafe {
    // let real_path = glfs_realpath(self.cluster_handle,
    // path.as_ptr(),
    // resolved_path: *mut c_char);
    // Ok(CStr::from_ptr(real_path).to_string_lossy().into_owned())
    // }
    // }
    //
    pub fn dup(&self,
               file_handle: *mut Struct_glfs_fd)
               -> Result<*mut Struct_glfs_fd, GlusterError> {
        unsafe {
            let file_handle = glfs_dup(file_handle);
            Ok(file_handle)
        }
    }
}