/* Test 7 -> Checks whether the read function in the
 * handles multiple block read requests
**/

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


void im_here(char * str) { fprintf(stderr, "I'm here: %s\n", str); 
	fflush(stderr);} 

void  print_hex(unsigned char *data, int length, char *lbl){
	int i=0;
	fprintf(stderr, "DATA ----- %08d -------- %s\n", length, lbl);
	for(i=0; i<length; i++) fprintf(stderr, "%02x", data[i]);
	fprintf(stderr, "\nEND DATA - %08x --------\n", length);
}

int main()
{
   int fd1 = -1, fd2 = -1;
   int err;
   void * handle = NULL;
   char buf[5*4096];
   char new_buf[5*4096];
   int i=0;
   int data_read = 0;
   int nr_blocks = 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");


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

/* Corrupt a block outside the library */
   fd2 = (*o_open)("file5", O_RDONLY);  
   if(fd2 == -1) {
         close(fd1);
         return -1;
   }

/* Read the file through the library and libc simultaneously */
     /* Request for 3 blocks */
          data_read = read(fd1, buf, 3*4096);
	  im_here("A1");
          if(data_read != 3*4096)
               goto fail;
	  im_here("A2");
          data_read = (*o_read)(fd2, new_buf, 3*4096);
	  im_here("A3");
          if(data_read != 3*4096)
               goto fail;
	  im_here("A4");
          if(memcmp(buf, new_buf, 3*4096) != 0)
               goto fail;
	  im_here("A5");

    /* Request for 5 blocks */
          data_read = read(fd1, buf, 5*4096);
	  im_here("A6");
          if(data_read != 5*4096)
               goto fail;
	  im_here("A7");
          data_read = (*o_read)(fd2, new_buf, 5*4096);
	  im_here("A8");
          if(data_read != 5*4096)
               goto fail;
	  im_here("A9");
          if(memcmp(buf, new_buf, 5*4096) != 0)
               goto fail;
	  im_here("A10");


pass:
   err = close(fd1);
   (*o_close)(fd2);
   if(err == -1)
        return -1;
   return 0;

fail:
   close(fd1);
   (*o_close)(fd2);
   return -1;

}
