/* Test 9 -> Checks whether the read call in library
* detects multiple block corruption and returns an error
* on read to a corrupted block
**/

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <dlfcn.h>

int main()
{
   int fd1 = -1;
   int err;
   void * handle = NULL;
   char buf[4096];
   char new_buf[4096];
   off_t cur=0;
   int i=0;
   int data_read = 0;

    handle = dlopen("/lib/libc.so.6",  RTLD_LAZY);
    if (handle == NULL) {
	fprintf(stderr, "%s", dlerror());
	return -1;
    }
    int (*o_open)(const char *, int) = (int (*)(const char *, int)) dlsym(handle, "open");
    ssize_t (*o_read)(int, void *, size_t) = (ssize_t (*)(int, void *, size_t)) dlsym(handle, "read");
    ssize_t (*o_write)(int, void *, size_t) = (ssize_t (*)(int, void *, size_t)) dlsym(handle, "write");
    off_t (*o_lseek)(int, off_t, int) = (off_t (*)(int, off_t, int)) dlsym(handle, "lseek");
    int (*o_close)(int) = (int (*)(int)) dlsym(handle, "close");


   printf("Starting Test---------------------------------------------------------------------\n");

/* Bootstrap the file with libfsprotect.c */
   fd1 = open("file5", O_RDONLY);
   if(fd1 == -1) {
         return -1;
   }
   err = close(fd1);
   if(err == -1)
        return -1;

/* Corrupt the 1st and the 3rd block outside the library */
   fd1 = (*o_open)("file5", O_RDWR);  
   if(fd1 == -1) {
         return -1;
   }
   err = (*o_read)(fd1, buf, 4096);
   if(err == -1)
        return -1;
   memcpy(new_buf, buf, 4096);
   for(i=130; i<160; i++) {
        new_buf[i]++;
   }
   (*o_lseek)(fd1, 0, SEEK_SET);
   err = (*o_write)(fd1, new_buf, 4096);
   if(err == -1)
        return -1;

   err = (*o_read)(fd1, buf, 4096);
   if(err == -1)
        return -1;
   err = (*o_read)(fd1, buf, 4096);
   if(err == -1)
        return -1;
   memcpy(new_buf, buf, 4096);
   for(i=130; i<160; i++) {
        new_buf[i]++;
   }
   (*o_lseek)(fd1, 8192, SEEK_SET);
   err = (*o_write)(fd1, new_buf, 4096);
   if(err == -1)
        return -1;
   (*o_close)(fd1);

/* Re-open the file with the library. This should correct the file */
   printf("---------------------------------------about to open----------------------------------\n");
   fd1 = open("file5",O_RDONLY);
   if(fd1 == -1) {
         return -1;
   }
   printf("Done opening\n");
/* Try to access the corrupted first block */
   data_read = read(fd1, new_buf, 4096);
   if(data_read == -1)
        goto pass;  
   else 
        goto fail;

pass:
   err = close(fd1);
   if(err == -1)
        return -1;

   return 0;

fail:
   close(fd1);
   return -1;


}
