Example #1
0
static void final_cleanup(void)
{
 #if SFX_LEVEL>=ARJSFXV
  file_close(aistream);
  aistream=NULL;
  file_close(atstream);
  atstream=NULL;
 #else
  if(atstream!=NULL)
   fclose(atstream);
 #endif
 #if SFX_LEVEL>=ARJSFXV
  if(tmp_tmp_filename!=NULL&&!keep_tmp_file&&tmp_tmp_filename[0]!='\0')
   file_unlink(tmp_tmp_filename);
 #else
  if(tmp_tmp_filename[0]!='\0')
   file_unlink(tmp_tmp_filename);
 #endif
 #if SFX_LEVEL>=ARJSFXV&&(TARGET!=UNIX||defined(HAVE_FCLOSEALL))
  fcloseall();
 #endif
 if(quiet_mode)
  freopen(dev_con, m_w, stdout);
 #if SFX_LEVEL>=ARJSFXV
  if(ferror(stdout))
   msg_fprintf(stderr, M_DISK_FULL);
  if(debug_enabled&&strchr(debug_opt, 't')!=NULL)
  {
   ticks=get_ticks()-ticks;
   msg_cprintf(0, M_FINAL_TIMING, ticks);
  }
 #endif
}
void stopdnsmasq() {
    // Stopping dnsmasq
	writelog(kill_processes_by_name((char *)"dnsmasq"),(char *)"Stopping dnsmasq");
	if (file_exists((char*)"/data/data/android.tether.usb/var/dnsmasq.pid") == 0) {
		file_unlink((char*)"/data/data/android.tether.usb/var/dnsmasq.pid");
	}
	if (file_exists((char*)"/data/data/android.tether.usb/var/dnsmasq.leases") == 0) {
		file_unlink((char*)"/data/data/android.tether.usb/var/dnsmasq.leases");
	}
}
Example #3
0
void FileStore::open( bool deleteFile )
{

  if ( m_msgFile ) fclose( m_msgFile );
  if ( m_headerFile ) fclose( m_headerFile );
  if ( m_seqNumsFile ) fclose( m_seqNumsFile );
  if ( m_sessionFile ) fclose( m_sessionFile );

  m_msgFile = 0;
  m_headerFile = 0;
  m_seqNumsFile = 0;
  m_sessionFile = 0;

  if ( deleteFile )
  {
    file_unlink( m_msgFileName.c_str() );
    file_unlink( m_headerFileName.c_str() );
    file_unlink( m_seqNumsFileName.c_str() );
    file_unlink( m_sessionFileName.c_str() );
  }

  populateCache();
  m_msgFile = file_fopen( m_msgFileName.c_str(), "r+" );
  if ( !m_msgFile ) m_msgFile = file_fopen( m_msgFileName.c_str(), "w+" );
  if ( !m_msgFile ) throw ConfigError( "Could not open body file: " + m_msgFileName );

  m_headerFile = file_fopen( m_headerFileName.c_str(), "r+" );
  if ( !m_headerFile ) m_headerFile = file_fopen( m_headerFileName.c_str(), "w+" );
  if ( !m_headerFile ) throw ConfigError( "Could not open header file: " + m_headerFileName );

  m_seqNumsFile = file_fopen( m_seqNumsFileName.c_str(), "r+" );
  if ( !m_seqNumsFile ) m_seqNumsFile = file_fopen( m_seqNumsFileName.c_str(), "w+" );
  if ( !m_seqNumsFile ) throw ConfigError( "Could not open seqnums file: " + m_seqNumsFileName );

  bool setCreationTime = false;
  m_sessionFile = file_fopen( m_sessionFileName.c_str(), "r" );
  if ( !m_sessionFile ) setCreationTime = true;
  else fclose( m_sessionFile );

  m_sessionFile = file_fopen( m_sessionFileName.c_str(), "r+" );
  if ( !m_sessionFile ) m_sessionFile = file_fopen( m_sessionFileName.c_str(), "w+" );
  if ( !m_sessionFile ) throw ConfigError( "Could not open session file" );
  if ( setCreationTime ) setSession();

  setNextSenderMsgSeqNum( getNextSenderMsgSeqNum() );
  setNextTargetMsgSeqNum( getNextTargetMsgSeqNum() );

  
}
Example #4
0
static void dir_remove(struct dir_info *dir)
{
	char *path;

	/* Remove directory contents */
	while (dir->first) {
		struct dir_entry_info *entry;

		entry = dir->first;
		if (entry->type == 'd')
			dir_remove(entry->entry.dir);
		else if (entry->type == 'f')
			file_unlink(entry);
		else if (entry->type == 's')
			symlink_remove(entry->entry.symlink);
		else
			CHECK(0); /* Invalid struct dir_entry_info */
	}
	/* Remove entry from parent directory */
	remove_dir_entry(dir->entry);
	/* Remove directory itself */
	path = dir_path(dir->parent, dir->name);
	CHECK(rmdir(path) != -1);
	free(dir);
}
int main(int argc, char *argv[]) {
	if (argc != 2) {
		fprintf(stderr, "Usage: tether <start|stop>\n");
		return -1;
	}

	// Reading config-files
	readlanconfig();

	// Remove old Logfile
	file_unlink((char*)"/data/data/android.tether.usb/var/tether.log");

	// Open Logfile
	log = fopen ("/data/data/android.tether.usb/var/tether.log","w");

	if (strcmp(argv[1],"start") == 0) {
	 	startint();
	  	startipt();
	  	startipfw();
	  	startdnsmasq();
	}
	else if (strcmp(argv[1],"stop") == 0) {
	    stopdnsmasq();
	    stopint();
	    stopipfw();
	    stopipt();
	}

	if (log != NULL) {
		fclose (log);
	}
	return 0;
}
Example #6
0
void blockstore_zap(struct config *config) {
  char *file;

  file = blockstore_get_filename(config);

  Warning(LGPFX " removing blockset '%s'.\n", file);
  file_unlink(file);
  free(file);
}
Example #7
0
int disc_cache_bdrom_file(BD_DISC *p, const char *rel_path, const char *cache_path)
{
    BD_FILE_H *fp_in;
    BD_FILE_H *fp_out;
    int64_t    got;
    size_t     size;

    if (!cache_path || !cache_path[0]) {
        return -1;
    }

    /* make sure cache directory exists */
    if (file_mkdirs(cache_path) < 0) {
        return -1;
    }

    /* plain directory ? */
    size = strlen(rel_path);
    if (rel_path[size - 1] == '/' || rel_path[size - 1] == '\\') {
        return 0;
    }

    /* input file from BD-ROM */
    fp_in = p->pf_file_open_bdrom(p->fs_handle, rel_path);
    if (!fp_in) {
        BD_DEBUG(DBG_FILE | DBG_CRIT, "error caching file %s (does not exist ?)\n", rel_path);
        return -1;
    }

    /* output file in local filesystem */
    fp_out = file_open(cache_path, "wb");
    if (!fp_out) {
        BD_DEBUG(DBG_FILE | DBG_CRIT, "error creating cache file %s\n", cache_path);
        file_close(fp_in);
        return -1;
    }

    do {
        uint8_t buf[16*2048];
        got = file_read(fp_in, buf, sizeof(buf));

        /* we'll call write(fp, buf, 0) after EOF. It is used to check for errors. */
        if (got < 0 || fp_out->write(fp_out, buf, got) != got) {
            BD_DEBUG(DBG_FILE | DBG_CRIT, "error caching file %s\n", rel_path);
            file_close(fp_out);
            file_close(fp_in);
            (void)file_unlink(cache_path);
            return -1;
        }
    } while (got > 0);

    BD_DEBUG(DBG_FILE, "cached %s to %s\n", rel_path, cache_path);

    file_close(fp_out);
    file_close(fp_in);
    return 0;
}
Example #8
0
static void file_unlink_file(struct file_info *file)
{
	struct dir_entry_info *entry;

	entry = pick_entry(file);
	if (!entry)
		return;
	file_unlink(entry);
}
Example #9
0
void
cache_delete (const char *filename)
{
	char *cache_name;

	cache_name = cache_get_nautilus_cache_name (filename);
	file_unlink (cache_name);
	g_free (cache_name);
}
Example #10
0
int netmatch_filter_ctor(struct netmatch_filter *netmatch, char const *libname)
{
    netmatch->libname = objalloc_strdup(libname);
    if (! netmatch->libname) {
        goto err0;
    }

    netmatch->handle = lt_dlopen(libname);
    if (! netmatch->handle) {
        SLOG(LOG_CRIT, "Cannot load netmatch shared object %s: %s", libname, lt_dlerror());
        goto err1;
    }
    (void)file_unlink(libname);

    netmatch->match_fun = lt_dlsym(netmatch->handle, "match");
    if (! netmatch->match_fun) {
        SLOG(LOG_CRIT, "Cannot find match function in netmatch shared object %s", libname);
        goto err2;
    }

    unsigned const *nb_regs_ptr = lt_dlsym(netmatch->handle, "nb_registers");
    if (! nb_regs_ptr) {
        SLOG(LOG_CRIT, "Cannot find nb_registers symbol in netmatch shared object %s", libname);
        goto err2;
    }

    netmatch->nb_registers = *nb_regs_ptr;
    if (netmatch->nb_registers > 0) {
        netmatch->regfile = objalloc_nice(netmatch->nb_registers * sizeof(*netmatch->regfile), "netmatches");
        if (! netmatch->regfile) goto err3;
        memset(netmatch->regfile, 0, netmatch->nb_registers * sizeof(*netmatch->regfile));
    } else {
        netmatch->regfile = NULL;
    }

    return 0;
err3:
    if (netmatch->regfile) {
        objfree(netmatch->regfile);
        netmatch->regfile = NULL;
    }
err2:
    if (netmatch->handle) {
        (void)lt_dlclose(netmatch->handle);
        netmatch->handle = NULL;
    }
err1:
    if (netmatch->libname) {
        objfree(netmatch->libname);
        netmatch->libname = NULL;
    }
err0:
    return -1;
}
Example #11
0
static void file_delete(struct file_info *file)
{
	struct dir_entry_info *entry = file->links;

	file_close_all(file);
	while (entry) {
		struct dir_entry_info *next = entry->next_link;

		file_unlink(entry);
		entry = next;
	}
}
Example #12
0
static gboolean
process_files_cb (gpointer data)
{
	NautilusCacheRemoveData *ncrd = data;
	GList *scan = ncrd->scan;
	int    i = 0;

	if (ncrd->process_timeout != 0) {
		g_source_remove (ncrd->process_timeout);
		ncrd->process_timeout = 0;
	}

	if ((ncrd->scan == NULL) || ncrd->interrupted) {
		process__final_step (ncrd);
		return FALSE;
	}

	g_free (ncrd->handle);
	ncrd->handle = NULL;

	for (; scan && i < PROCESS_MAX_FILES; scan = scan->next, i++) {
		FileData *fd = scan->data;
		char     *rc_file = fd->path;
		char     *real_file;

		real_file = get_real_name_from_nautilus_cache (rc_file);

		if (real_file == NULL)
			continue;

		if (ncrd->clear_all || ! path_is_file (real_file)) {
			if (! file_unlink (rc_file))
				g_warning ("Cannot delete %s\n", rc_file);
		}

		g_free (real_file);
	}

	ncrd->scan = scan;
	ncrd->process_timeout = g_timeout_add (PROCESS_DELAY,
					       process_files_cb,
					       ncrd);

	return FALSE;
}
Example #13
0
int delete_files(char *name)
{
 char tmp_name[CCHMAXPATHCOMP];
 struct flist_root root;
 FILE_COUNT curfile;

 flist_init(&root, FCLIM_DELETION, FL_STANDARD);
 if(flist_add_files(&root, NULL, name, 1, 0, FETCH_FILES, NULL))
  return(1);
 for(curfile=0; curfile<root.files; curfile++)
 {
  flist_retrieve(tmp_name, NULL, &root, curfile);
  msg_cprintf(0, M_DELETING, tmp_name);
  if(is_directory(tmp_name)?file_rmdir(tmp_name):file_unlink(tmp_name))
   msg_cprintf(H_ERR, M_CANT_DELETE, tmp_name);
 }
 flist_cleanup(&root);
 return(0);
}
Example #14
0
void
cache_copy (const char *src,
	    const char *dest)
{
	char   *cache_src;
	time_t  dest_mtime = get_file_mtime (dest);

	cache_src = cache_get_nautilus_cache_name (src);
	if (path_is_file (cache_src)) {
		char *cache_dest = cache_get_nautilus_cache_name (dest);

		if (path_is_file (cache_dest))
			file_unlink (cache_dest);
		if (file_copy (cache_src, cache_dest))
			set_file_mtime (cache_dest, dest_mtime);

		g_free (cache_dest);
	}
	g_free (cache_src);
}
/* fork and the child executes Settings.Convertor on fname
   create temporary file containing stdin when fname == NULL and convert it
   passing special option STDOUT to convertor (that is assumed to delete
   the temporary file itself)
   from_enc, to_enc are encoding names as should be passed to convertor
   returns 0 on success, nonzero on failure;
   on critical failure (like we cannot fork()) it simply aborts */
int
convert_external(File *file,
                 const EncaEncoding from_enc)
{
  /* special fourth parameter passed to external convertor to instruct it to
  send result to stdout */
  static const char *STDOUT_CONV = "-";

  pid_t pid;
  int status;
  File *tempfile = NULL;
  char *from_name, *target_name;

  if (*extern_convertor == '\0') {
    fprintf(stderr, "%s: No external convertor defined!\n", program_name);
    return ERR_CANNOT;
  }

  if (options.verbosity_level > 2)
    fprintf(stderr, "    launching `%s' to convert `%s'\n",
                    extern_convertor, ffname_r(file->name));

  /* Is conversion of stdin requested? */
  if (file->name == NULL) {
    /* Then we have to copy it to a temporary file. */
    tempfile = file_temporary(file->buffer, 0);
    if (tempfile == NULL)
      return ERR_IOFAIL;

    if (copy_and_convert(file, tempfile, NULL) != 0) {
      file_unlink(tempfile->name);
      file_free(tempfile);
      return ERR_IOFAIL;
    }
  }

  /* Construct the charset names before fork() */
  from_name = enca_strconcat(enca_charset_name(from_enc.charset,
                                               ENCA_NAME_STYLE_ENCA),
                             enca_get_surface_name(from_enc.surface,
                                                   ENCA_NAME_STYLE_ENCA),
                             NULL);
  if (enca_charset_is_known(options.target_enc.charset)
      && (options.target_enc.surface & ENCA_SURFACE_UNKNOWN) == 0) {
    target_name
      = enca_strconcat(enca_charset_name(options.target_enc.charset,
                                         ENCA_NAME_STYLE_ENCA),
                       enca_get_surface_name(options.target_enc.surface,
                                             ENCA_NAME_STYLE_ENCA),
                       NULL);
  }
  else
    target_name = enca_strdup(options.target_enc_str);

  /* Fork. */
  pid = vfork();
  if (pid == 0) {
    /* Child. */
    if (tempfile)
      execlp(extern_convertor, extern_convertor,
             from_name, target_name, tempfile->name,
             STDOUT_CONV, NULL);
    else
      execlp(extern_convertor, extern_convertor,
             from_name, target_name, file->name, NULL);

    exit(ERR_EXEC);
  }

  /* Parent. */
  if (pid == -1) {
    fprintf(stderr, "%s: Cannot fork() to execute convertor: %s\n",
                    program_name,
                    strerror(errno));
    exit(EXIT_TROUBLE);
  }
  /* Wait until the child returns. */
  if (waitpid(pid, &status, 0) == -1) {
    /* Error. */
    fprintf(stderr, "%s: wait_pid() error while waiting for convertor: %s\n",
                    program_name,
                    strerror(errno));
    exit(EXIT_TROUBLE);
  }
  if (!WIFEXITED(status)) {
    /* Child exited abnormally. */
    fprintf(stderr, "%s: Child convertor process has been murdered.\n",
                    program_name);
    exit(EXIT_TROUBLE);
  }

  enca_free(from_name);
  enca_free(target_name);

  if (tempfile) {
    unlink(tempfile->name);
    file_free(tempfile);
  }

  /* Child exited normally, test exit status. */
  if (WEXITSTATUS(status) != EXIT_SUCCESS) {
    /* This means child was unable to execute convertor or convertor failed. */
    fprintf(stderr, "%s: External convertor failed (error code %d)\n",
                    program_name,
                    WEXITSTATUS(status));
    if (WEXITSTATUS(status) == ERR_EXEC)
      return ERR_EXEC;
    else
      return ERR_CANNOT;
  }
  /* Success!  Wow! */
  return ERR_OK;
}
Example #16
0
inline bool file_unlink(const std::string& a_path) { return file_unlink(a_path.c_str()); }
Example #17
0
int main(int argc, char **argv)
{
    if(argc == 1)
    {
        usage();
        exit(1);
    }
    while((cret = getopt(argc,argv,"bwetvf:s:l:u: ")) != EOF) {
        switch(cret) {
        case 'f':	/* Force factor */
            x=atoi(optarg);
            if(x < 0)
                x=1;
            break;
        case 's':	/* Size of files */
            sz=atoi(optarg);
            if(optarg[strlen(optarg)-1]=='k' ||
                    optarg[strlen(optarg)-1]=='K') {
                sz = (1024 * atoi(optarg));
            }
            if(optarg[strlen(optarg)-1]=='m' ||
                    optarg[strlen(optarg)-1]=='M') {
                sz = (1024 * 1024 * atoi(optarg));
            }
            if(sz < 0)
                sz=1;
            break;
        case 'l':	/* lower force value */
            lower=atoi(optarg);
            range=1;
            if(lower < 0)
                lower=1;
            break;
        case 'v':	/* version */
            splash();
            exit(0);
            break;
        case 'u':	/* upper force value */
            upper=atoi(optarg);
            range=1;
            if(upper < 0)
                upper=1;
            break;
        case 't':	/* verbose */
            verbose=1;
            break;
        case 'e':	/* Excel */
            excel=1;
            break;
        case 'b':	/* Best */
            best=1;
            break;
        case 'w':	/* Worst */
            worst=1;
            break;
        }
    }
    mbuffer=(char *)malloc(sz);
    memset(mbuffer,'a',sz);
    if(!excel)
        printf("\nFileop:  File size is %d,  Output is in Ops/sec. (A=Avg, B=Best, W=Worst)\n",sz);
    if(!verbose)
    {
#ifdef Windows
        printf(" .     %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s %12s\n",
               "mkdir","rmdir","create","read","write","close","stat",
               "access","chmod","readdir","delete"," Total_files");
#else

        printf(" .     %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s %6s %12s\n",
               "mkdir","rmdir","create","read","write","close","stat",
               "access","chmod","readdir","link  ","unlink","delete",
               " Total_files");
#endif
    }
    if(x==0)
        x=1;
    if(range==0)
        lower=upper=x;
    for(i=lower; i<=upper; i++)
    {
        clear_stats();
        x=i;
        /*
         * Dir Create test
         */
        dir_create(x);

        if(verbose)
        {
            printf("mkdir:   Dirs = %9lld ",stats[_STAT_DIR_CREATE].counter);
            printf("Total Time = %12.9f seconds\n", stats[_STAT_DIR_CREATE].total_time);
            printf("         Avg mkdir(s)/sec     = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_DIR_CREATE].counter/stats[_STAT_DIR_CREATE].total_time,
                   stats[_STAT_DIR_CREATE].total_time/stats[_STAT_DIR_CREATE].counter);
            printf("         Best mkdir(s)/sec    = %12.2f (%12.9f seconds/op)\n",1/stats[_STAT_DIR_CREATE].best,stats[_STAT_DIR_CREATE].best);
            printf("         Worst mkdir(s)/sec   = %12.2f (%12.9f seconds/op)\n\n",1/stats[_STAT_DIR_CREATE].worst,stats[_STAT_DIR_CREATE].worst);
        }
        /*
         * Dir delete test
         */
        dir_delete(x);

        if(verbose)
        {
            printf("rmdir:   Dirs = %9lld ",stats[_STAT_DIR_DELETE].counter);
            printf("Total Time = %12.9f seconds\n",stats[_STAT_DIR_DELETE].total_time);
            printf("         Avg rmdir(s)/sec     = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_DIR_DELETE].counter/stats[_STAT_DIR_DELETE].total_time,
                   stats[_STAT_DIR_DELETE].total_time/stats[_STAT_DIR_DELETE].counter);
            printf("         Best rmdir(s)/sec    = %12.2f (%12.9f seconds/op)\n",1/stats[_STAT_DIR_DELETE].best,stats[_STAT_DIR_DELETE].best);
            printf("         Worst rmdir(s)/sec   = %12.2f (%12.9f seconds/op)\n\n",1/stats[_STAT_DIR_DELETE].worst,stats[_STAT_DIR_DELETE].worst);
        }

        /*
         * Create test
         */
        file_create(x);
        if(verbose)
        {
            printf("create:  Files = %9lld ",stats[_STAT_CREATE].counter);
            printf("Total Time = %12.9f seconds\n", stats[_STAT_CREATE].total_time);
            printf("         Avg create(s)/sec    = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_CREATE].counter/stats[_STAT_CREATE].total_time,
                   stats[_STAT_CREATE].total_time/stats[_STAT_CREATE].counter);
            printf("         Best create(s)/sec   = %12.2f (%12.9f seconds/op)\n",
                   1/stats[_STAT_CREATE].best,stats[_STAT_CREATE].best);
            printf("         Worst create(s)/sec  = %12.2f (%12.9f seconds/op)\n\n",
                   1/stats[_STAT_CREATE].worst,stats[_STAT_CREATE].worst);
            printf("write:   Files = %9lld ",stats[_STAT_WRITE].counter);
            printf("Total Time = %12.9f seconds\n", stats[_STAT_WRITE].total_time);
            printf("         Avg write(s)/sec     = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_WRITE].counter/stats[_STAT_WRITE].total_time,
                   stats[_STAT_WRITE].total_time/stats[_STAT_WRITE].counter);
            printf("         Best write(s)/sec    = %12.2f (%12.9f seconds/op)\n",
                   1/stats[_STAT_WRITE].best,stats[_STAT_WRITE].best);
            printf("         Worst write(s)/sec   = %12.2f (%12.9f seconds/op)\n\n",
                   1/stats[_STAT_WRITE].worst,stats[_STAT_WRITE].worst);
            printf("close:   Files = %9lld ",stats[_STAT_CLOSE].counter);
            printf("Total Time = %12.9f seconds\n", stats[_STAT_CLOSE].total_time);
            printf("         Avg close(s)/sec     = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_CLOSE].counter/stats[_STAT_CLOSE].total_time,
                   stats[_STAT_CLOSE].total_time/stats[_STAT_CLOSE].counter);
            printf("         Best close(s)/sec    = %12.2f (%12.9f seconds/op)\n",
                   1/stats[_STAT_CLOSE].best,stats[_STAT_CLOSE].best);
            printf("         Worst close(s)/sec   = %12.2f (%12.9f seconds/op)\n\n",
                   1/stats[_STAT_CLOSE].worst,stats[_STAT_CLOSE].worst);
        }

        /*
         * Stat test
         */
        file_stat(x);

        if(verbose)
        {
            printf("stat:    Files = %9lld ",stats[_STAT_STAT].counter);
            printf("Total Time = %12.9f seconds\n", stats[_STAT_STAT].total_time);
            printf("         Avg stat(s)/sec      = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_STAT].counter/stats[_STAT_STAT].total_time,
                   stats[_STAT_STAT].total_time/stats[_STAT_STAT].counter);
            printf("         Best stat(s)/sec     = %12.2f (%12.9f seconds/op)\n",
                   1/stats[_STAT_STAT].best,stats[_STAT_STAT].best);
            printf("         Worst stat(s)/sec    = %12.2f (%12.9f seconds/op)\n\n",
                   1/stats[_STAT_STAT].worst,stats[_STAT_STAT].worst);
        }
        /*
         * Read test
         */
        file_read(x);

        if(verbose)
        {
            printf("read:    Files = %9lld ",stats[_STAT_READ].counter);
            printf("Total Time = %12.9f seconds\n", stats[_STAT_READ].total_time);
            printf("         Avg read(s)/sec      = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_READ].counter/stats[_STAT_READ].total_time,
                   stats[_STAT_READ].total_time/stats[_STAT_READ].counter);
            printf("         Best read(s)/sec     = %12.2f (%12.9f seconds/op)\n",
                   1/stats[_STAT_READ].best,stats[_STAT_READ].best);
            printf("         Worst read(s)/sec    = %12.2f (%12.9f seconds/op)\n\n",
                   1/stats[_STAT_READ].worst,stats[_STAT_READ].worst);
        }

        /*
         * Access test
         */
        file_access(x);
        if(verbose)
        {
            printf("access:  Files = %9lld ",stats[_STAT_ACCESS].counter);
            printf("Total Time = %12.9f seconds\n", stats[_STAT_ACCESS].total_time);
            printf("         Avg access(s)/sec    = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_ACCESS].counter/stats[_STAT_ACCESS].total_time,
                   stats[_STAT_ACCESS].total_time/stats[_STAT_ACCESS].counter);
            printf("         Best access(s)/sec   = %12.2f (%12.9f seconds/op)\n",
                   1/stats[_STAT_ACCESS].best,stats[_STAT_ACCESS].best);
            printf("         Worst access(s)/sec  = %12.2f (%12.9f seconds/op)\n\n",
                   1/stats[_STAT_ACCESS].worst,stats[_STAT_ACCESS].worst);
        }
        /*
         * Chmod test
         */
        file_chmod(x);

        if(verbose)
        {
            printf("chmod:   Files = %9lld ",stats[_STAT_CHMOD].counter);
            printf("Total Time = %12.9f seconds\n", stats[_STAT_CHMOD].total_time);
            printf("         Avg chmod(s)/sec     = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_CHMOD].counter/stats[_STAT_CHMOD].total_time,
                   stats[_STAT_CHMOD].total_time/stats[_STAT_CHMOD].counter);
            printf("         Best chmod(s)/sec    = %12.2f (%12.9f seconds/op)\n",
                   1/stats[_STAT_CHMOD].best,stats[_STAT_CHMOD].best);
            printf("         Worst chmod(s)/sec   = %12.2f (%12.9f seconds/op)\n\n",
                   1/stats[_STAT_CHMOD].worst,stats[_STAT_CHMOD].worst);
        }
        /*
         * readdir test
         */
        file_readdir(x);

        if(verbose)
        {
            printf("readdir: Files = %9lld ",stats[_STAT_READDIR].counter);
            printf("Total Time = %12.9f seconds\n", stats[_STAT_READDIR].total_time);
            printf("         Avg readdir(s)/sec   = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_READDIR].counter/stats[_STAT_READDIR].total_time,
                   stats[_STAT_READDIR].total_time/stats[_STAT_READDIR].counter);
            printf("         Best readdir(s)/sec  = %12.2f (%12.9f seconds/op)\n",
                   1/stats[_STAT_READDIR].best,stats[_STAT_READDIR].best);
            printf("         Worst readdir(s)/sec = %12.2f (%12.9f seconds/op)\n\n",
                   1/stats[_STAT_READDIR].worst,stats[_STAT_READDIR].worst);
        }
#if !defined(Windows)
        /*
         * link test
         */
        file_link(x);
        if(verbose)
        {
            printf("link:    Files = %9lld ",stats[_STAT_LINK].counter);
            printf("Total Time = %12.9f seconds\n",stats[_STAT_LINK].total_time);
            printf("         Avg link(s)/sec      = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_LINK].counter/stats[_STAT_LINK].total_time,
                   stats[_STAT_LINK].total_time/stats[_STAT_LINK].counter);
            printf("         Best link(s)/sec     = %12.2f (%12.9f seconds/op)\n",
                   1/stats[_STAT_LINK].best,stats[_STAT_LINK].best);
            printf("         Worst link(s)/sec    = %12.2f (%12.9f seconds/op)\n\n",
                   1/stats[_STAT_LINK].worst,stats[_STAT_LINK].worst);
        }
        /*
         * unlink test
         */
        file_unlink(x);
        if(verbose)
        {
            printf("unlink:  Files = %9lld ",stats[_STAT_UNLINK].counter);
            printf("Total Time = %12.9f seconds\n", stats[_STAT_UNLINK].total_time);
            printf("         Avg unlink(s)/sec    = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_UNLINK].counter/stats[_STAT_UNLINK].total_time,
                   stats[_STAT_UNLINK].total_time/stats[_STAT_UNLINK].counter);
            printf("         Best unlink(s)/sec   = %12.2f (%12.9f seconds/op)\n",
                   1/stats[_STAT_UNLINK].best,stats[_STAT_UNLINK].best);
            printf("         Worst unlink(s)/sec  = %12.2f (%12.9f seconds/op)\n\n",
                   1/stats[_STAT_UNLINK].worst,stats[_STAT_UNLINK].worst);
        }
#endif
        /*
         * Delete test
         */
        file_delete(x);
        if(verbose)
        {
            printf("delete:  Files = %9lld ",stats[_STAT_DELETE].counter);
            printf("Total Time = %12.9f seconds\n", stats[_STAT_DELETE].total_time);
            printf("         Avg delete(s)/sec    = %12.2f (%12.9f seconds/op)\n",
                   stats[_STAT_DELETE].counter/stats[_STAT_DELETE].total_time,
                   stats[_STAT_DELETE].total_time/stats[_STAT_DELETE].counter);
            printf("         Best delete(s)/sec   = %12.2f (%12.9f seconds/op)\n",
                   1/stats[_STAT_DELETE].best,stats[_STAT_DELETE].best);
            printf("         Worst delete(s)/sec  = %12.2f (%12.9f seconds/op)\n\n",
                   1/stats[_STAT_DELETE].worst,stats[_STAT_DELETE].worst);
        }
        if(!verbose)
        {
            printf("%c %4d %6.0f ",'A',x,stats[_STAT_DIR_CREATE].counter/stats[_STAT_DIR_CREATE].total_time);
            printf("%6.0f ",stats[_STAT_DIR_DELETE].counter/stats[_STAT_DIR_DELETE].total_time);
            printf("%6.0f ",stats[_STAT_CREATE].counter/stats[_STAT_CREATE].total_time);
            printf("%6.0f ",stats[_STAT_READ].counter/stats[_STAT_READ].total_time);
            printf("%6.0f ",stats[_STAT_WRITE].counter/stats[_STAT_WRITE].total_time);
            printf("%6.0f ",stats[_STAT_CLOSE].counter/stats[_STAT_CLOSE].total_time);
            printf("%6.0f ",stats[_STAT_STAT].counter/stats[_STAT_STAT].total_time);
            printf("%6.0f ",stats[_STAT_ACCESS].counter/stats[_STAT_ACCESS].total_time);
            printf("%6.0f ",stats[_STAT_CHMOD].counter/stats[_STAT_CHMOD].total_time);
            printf("%6.0f ",stats[_STAT_READDIR].counter/stats[_STAT_READDIR].total_time);
#ifndef Windows
            printf("%6.0f ",stats[_STAT_LINK].counter/stats[_STAT_LINK].total_time);
            printf("%6.0f ",stats[_STAT_UNLINK].counter/stats[_STAT_UNLINK].total_time);
#endif
            printf("%6.0f ",stats[_STAT_DELETE].counter/stats[_STAT_DELETE].total_time);
            printf("%12d ",x*x*x);
            printf("\n");
            fflush(stdout);

            if(best)
            {
                printf("%c %4d %6.0f ",'B',x, 1/stats[_STAT_DIR_CREATE].best);
                printf("%6.0f ",1/stats[_STAT_DIR_DELETE].best);
                printf("%6.0f ",1/stats[_STAT_CREATE].best);
                printf("%6.0f ",1/stats[_STAT_READ].best);
                printf("%6.0f ",1/stats[_STAT_WRITE].best);
                printf("%6.0f ",1/stats[_STAT_CLOSE].best);
                printf("%6.0f ",1/stats[_STAT_STAT].best);
                printf("%6.0f ",1/stats[_STAT_ACCESS].best);
                printf("%6.0f ",1/stats[_STAT_CHMOD].best);
                printf("%6.0f ",1/stats[_STAT_READDIR].best);
#ifndef Windows
                printf("%6.0f ",1/stats[_STAT_LINK].best);
                printf("%6.0f ",1/stats[_STAT_UNLINK].best);
#endif
                printf("%6.0f ",1/stats[_STAT_DELETE].best);
                printf("%12d ",x*x*x);
                printf("\n");
                fflush(stdout);
            }
            if(worst)
            {
                printf("%c %4d %6.0f ",'W',x, 1/stats[_STAT_DIR_CREATE].worst);
                printf("%6.0f ",1/stats[_STAT_DIR_DELETE].worst);
                printf("%6.0f ",1/stats[_STAT_CREATE].worst);
                printf("%6.0f ",1/stats[_STAT_READ].worst);
                printf("%6.0f ",1/stats[_STAT_WRITE].worst);
                printf("%6.0f ",1/stats[_STAT_CLOSE].worst);
                printf("%6.0f ",1/stats[_STAT_STAT].worst);
                printf("%6.0f ",1/stats[_STAT_ACCESS].worst);
                printf("%6.0f ",1/stats[_STAT_CHMOD].worst);
                printf("%6.0f ",1/stats[_STAT_READDIR].worst);
#ifndef Windows
                printf("%6.0f ",1/stats[_STAT_LINK].worst);
                printf("%6.0f ",1/stats[_STAT_UNLINK].worst);
#endif
                printf("%6.0f ",1/stats[_STAT_DELETE].worst);
                printf("%12d ",x*x*x);
                printf("\n");
                fflush(stdout);
            }
        }
    }
    return(0);
}
asmlinkage long xcrypt(void *arg)
{
    if (arg == NULL) {
	printk("User level argument is NULL\n");
	return -EINVAL;
    } else {
	struct myargs *arguments;
	int result, paddedresult, padvalue, preambleWritten, temp, paddingWritten, paddingRead;
	struct file *filp=NULL, *filp1=NULL;
	struct dentry *dentry=NULL, *olddentry=NULL, *newdentry=NULL;
	long int inputFileLen=-1, outputFileLen=-1, keyLen=-1;
	char *srcbuffer, *destbuffer, *padding, *keyFromFile=NULL, *md5_hash=NULL, *tempOutFile;
	umode_t inputFileMode, outputFileMode;
	bool outFileCreated=false, renamed=false, success = false;
	int err=0;	
	arguments = (struct myargs *)kmalloc(sizeof(struct myargs), GFP_KERNEL);
	if (arguments==NULL) {
	    printk("Failed to allocate kernel memory\n");
	    err = -ENOMEM;
	    goto out1;
	}
	result = copy_from_user((void *)arguments, arg, sizeof(struct myargs));
	if(result!=0) {
	    printk("Copying from user failed\n");
	    err = -EFAULT;
	    goto out2;
	}
	if (((struct myargs*)arg)->inputFile == NULL) { /*Checking whether user passed NULL input File*/
	    printk("user level input file argument is NULL\n");
	    err = -EINVAL;
	    goto out2;
	}
	inputFileLen = strnlen_user(((struct myargs*)arg)->inputFile, 32767); //TODO get the maximum value from getname 
	if (inputFileLen == -1) {
	    printk("Finding User inputFile string length Failed\n");
	    err = -EFAULT;
	    goto out2;
	}
	arguments->inputFile = (char *)kmalloc(inputFileLen*sizeof(char), GFP_KERNEL);
	if ((arguments->inputFile)==NULL) {
            printk("Failed to allocate kernel memory for input file\n");
            err = -ENOMEM;
	    goto out2;
        }
	result = strncpy_from_user(arguments->inputFile, ((struct myargs*)arg)->inputFile, inputFileLen);
	if(result!=(inputFileLen-1)) {
            printk("Copying input file string from user failed\n");
            err = -EFAULT;
	    goto out3;
        }
	if((arguments->inputFile)==NULL) {
	    printk("Copying input file string from user failed\n");
	    err = -EFAULT;
	    goto out3;
	}
	if (((struct myargs*)arg)->outputFile == NULL) {
            printk("user level output file argument is NULL\n");
            err = -EINVAL;
	    goto out3;
        }
	outputFileLen = strnlen_user(((struct myargs*)arg)->outputFile, 32767); //TODO get the maximum value from getname
	if (outputFileLen == -1) {
            printk("Finding User outputFile string length Failed\n");
            err = -EFAULT;
	    goto out3;
        }
	arguments->outputFile = (char *)kmalloc(outputFileLen*sizeof(char), GFP_KERNEL);
	if ((arguments->outputFile)==NULL) {
            printk("Failed to allocate kernel memory for outputfile\n");
            err = -ENOMEM;
	    goto out3;
        }
	result = strncpy_from_user(arguments->outputFile, ((struct myargs*)arg)->outputFile, outputFileLen);
	if(result!=(outputFileLen-1)) {
            printk("Copying output file string from user failed\n");
            err = -EFAULT;
	    goto out4;
        }
	if((arguments->outputFile)==NULL) {
            printk("Copying output file string from user failed\n");
            err = -EFAULT;
	    goto out4;
        }
	if (((struct myargs*)arg)->keyBuf == NULL) {
            printk("user level key buffer argument is NULL\n");
            err = -EINVAL;
            goto out4;
        }
	keyLen = strnlen_user(((struct myargs*)arg)->keyBuf, 32767); //TODO get the maximum value from getname
        if (keyLen == -1) {
            printk("Finding User keyBuf string length Failed\n");
            err = -EFAULT;
	    goto out4;
        }
	arguments->keyBuf = (char *)kmalloc(keyLen*sizeof(char), GFP_KERNEL);
	if ((arguments->keyBuf)==NULL) {
            printk("Failed to allocate kernel memory\n");
            err = -ENOMEM;
	    goto out4;
        }
	result = strncpy_from_user(arguments->keyBuf, ((struct myargs*)arg)->keyBuf, keyLen);
	if(result!=(keyLen-1)) {
            printk("Copying key buf string from user failed\n");
            err = -EFAULT;
	    goto out5;
        }
	if((arguments->keyBuf)==NULL) {
            printk("Copying key buf string from user failed\n");
            err = -EFAULT;
	    goto out5;
        }

	if (strlen(arguments->keyBuf) != arguments->keyLen) {
	    printk("User key buffer length and kernel key buffer lengths differ\n");
	    err = -EINVAL;
	    goto out5;
	}

	if((arguments->flags)!=0 && (arguments->flags)!=1) {
	    printk("Invalid values for flag argument, it should be either 1 or 0\n");
	    err = -EINVAL;
	    goto out5;
	}

	srcbuffer = (char *)kmalloc((PAGE_SIZE+1)*sizeof(char), GFP_KERNEL);
	if (srcbuffer==NULL) {
	    printk("Failed to allocate kernel memory for srcbuffer\n");
            err = -ENOMEM;
	    goto out5;
	}
        
        destbuffer = (char *)kmalloc((PAGE_SIZE+1)*sizeof(char), GFP_KERNEL);
        if (destbuffer==NULL) {
            printk("Failed to allocate kernel memory for destbuffer\n");
            err = -ENOMEM;
	    goto out6;
        }

	padding = (char *)kmalloc(4*sizeof(char), GFP_KERNEL);
	if (padding==NULL) {
	    printk("Failed to allocate kernel memory for padding\n");
            err = -ENOMEM;
	    goto out7;
	}

        initialisePadding(padding); /*Initialising the padding array to all 0's */
        
	result=PAGE_SIZE;

	filp = filp_open(arguments->inputFile, O_RDONLY, 0);
	if (PTR_ERR(filp)==-ENOENT) {
	    printk("Input File doesnot exists\n");
	    err = -ENOENT; 
	    goto out8;
	} else {
	    printk("Input File exists\n");
	}
	
        if (!filp || IS_ERR(filp)) {
            printk("Read error for input file %d\n", (int) PTR_ERR(filp));
            err = PTR_ERR(filp);
	    goto out8;
        }

	inputFileMode = filp->f_inode->i_mode;

	if(!S_ISREG(inputFileMode)) {
	    printk("Input File is not a regular file\n");
	    err = -EISDIR;
	    goto out9;
	}

	if (!filp->f_op->read) {
	    printk("Error in reading input file\n");
            err = PTR_ERR(filp);
	    goto out9;
	}

	filp1 = filp_open(arguments->outputFile, O_WRONLY, 0);
	if (PTR_ERR(filp1)==-ENOENT) {
            printk("Output File doesnot exists, creating it\n");
	    filp1 = filp_open(arguments->outputFile, O_CREAT, inputFileMode); /*Creating output file if it doesnot exists with input file permissions*/
	    if(!filp1 || IS_ERR(filp1)) {
		printk("Error in creating output file\n");
		err = PTR_ERR(filp1);
		goto out8_1;
	    } else {
		printk("Output File created succesfully\n");
		outFileCreated = true;
	    }
        } else {
            printk("Output File exists\n");
        }

	if(!outFileCreated) {
	    if(!filp1 || IS_ERR(filp1)) {
		printk("Error in opening output file\n");
		err = PTR_ERR(filp1);
                goto out8_1;
	    }
	}

	if(!outFileCreated) {
	    outputFileMode = filp1->f_inode->i_mode;
	
	    if(!S_ISREG(outputFileMode)) {
                printk("Output File is not a regular file\n");
                err = -EISDIR;
		goto out9;
            }
	}

	if(!outFileCreated) {
	    if (filp->f_inode->i_ino == filp1->f_inode->i_ino) {
	        printk("Both input and output files are same, they should be different\n");
	        err = -EPERM;
		goto out9;
 	    }
	}
	
	if(!outFileCreated) {
	    olddentry = filp1->f_path.dentry;
            filp_close(filp1, NULL);
	    tempOutFile =  (char *)kmalloc((strlen(arguments->outputFile)+5)*sizeof(char), GFP_KERNEL);
	    strncpy(tempOutFile, arguments->outputFile, strlen(arguments->outputFile));
	    strcat(tempOutFile, ".tmp");
	    tempOutFile[(strlen(arguments->outputFile)+5)]='\0';
	    filp1 = filp_open(tempOutFile, O_WRONLY, 0);
            if (PTR_ERR(filp1)==-ENOENT || IS_ERR(filp1)) {
                printk("temp Output File doesnot exists, creating it\n");
            } else {
                printk("temp output File exists, truncating and creating new one\n");
		dentry = filp1->f_path.dentry;
		filp_close(filp1, NULL);
		err = file_unlink(dentry->d_parent->d_inode, dentry);
		if(err != 0) {
		    printk("unlink of already existing temporary file failed\n");
		    err = -EBUSY;
		    goto out9;
		}
		printk("unlink function returned : %d\n", err);
            }
            filp1 = filp_open(tempOutFile, O_CREAT, outputFileMode);
            if(!filp1 || IS_ERR(filp1)) {
                printk("Error in creating temp output file\n");
                err = PTR_ERR(filp1);
		goto out8_1;
            } else {
                printk("temp output File created succesfully\n");
            }
	}
	
	newdentry = filp1->f_path.dentry;

	if (!filp1 || IS_ERR(filp1)) {
            printk("Write error for output file %d\n", (int) PTR_ERR(filp1));
            err = PTR_ERR(filp1);
	    goto out10;
        }

        if (!filp1->f_op->write) {
	    printk("Error in writing to temp output file\n");
            err = PTR_ERR(filp1);
	    goto out10;
	}

	md5_hash = kmalloc(17*sizeof(char), GFP_KERNEL);
	if (md5_hash==NULL) {
            printk("Failed to allocate kernel memory for key from file\n");
            err = -ENOMEM;
	    goto out10;
        }
        err = generate_md5(arguments->keyBuf, md5_hash, strlen(arguments->keyBuf));
	if(err != 0) {
	    printk("kernel MD5 generation failed\n");
	    goto out11;
	}
	md5_hash[strlen(arguments->keyBuf)] = '\0';
        
	if (arguments->flags) { //ENCRYPTION
	    preambleWritten = wrapfs_write_file(filp1, (void *)(md5_hash), strlen(md5_hash)); /*Writing Key hash to the file*/	   
	    if(preambleWritten < 0) {
		printk("Writing preamble failed\n");
		err = -EFAULT;
		goto out11;
	    }
	    paddingWritten = wrapfs_write_file(filp1, (void *)(padding), 4); /*Writing Inital Padding to the file*/
	    if (paddingWritten < 0) {
		printk("Writing padding failed\n");
                err = -EFAULT;
		goto out11;
	    }
	    while(result==PAGE_SIZE) {
	        result = wrapfs_read_file(filp, (void *)srcbuffer, PAGE_SIZE);
		if(result < 0) {
		    printk("Reading from input file failed\n");
                    err = -EFAULT;
		    goto out11;
		}
	        err = encrypt_Cipher(arguments->keyBuf, srcbuffer, destbuffer, result, &paddedresult);
		if (err < 0) {
		    printk("Error occured while encrypting\n");
		    goto out11;
		}
	        if(paddedresult!=result) {
		    padvalue = paddedresult - result;
		    buildPadding(padding, padvalue);
		    result = paddedresult;
	        }
	        result = wrapfs_write_file(filp1, (void *)destbuffer, result);
		if (result < 0) {
		    printk("Writing to output file failed\n");
                    err = -EFAULT;
		    goto out11;
		}
	    }
	    paddingWritten = wrapfs_write_file_pos(filp1, (void *)padding, 4, preambleWritten);
	    if (paddingWritten < 0) {
                printk("Writing padding failed\n");
                err = -EFAULT;
		goto out11;
            }
	} else {  //DECRYPTION
	    keyFromFile = kmalloc(16*sizeof(char), GFP_KERNEL);
	    if (keyFromFile==NULL) {
                printk("Failed to allocate kernel memory for key from file\n");
                err = -ENOMEM;
		goto out11;
            }
	    temp = wrapfs_read_file(filp, (void *)keyFromFile, strlen(md5_hash));
	    if (temp != strlen(md5_hash)) {
		printk("reading key from file failed\n");
		err = -EFAULT;
		goto out12;
	    }
	    if (compareKeys(md5_hash, keyFromFile, temp)) {
		printk("Both Keys Match\n");
	    } else {
		printk("Both keys doesnot match\n");
		err = -EINVAL; //TODO : Return proper error Value.
		goto out12;
	    }
	    paddingRead = wrapfs_read_file(filp, (void *)padding, 4);
	    if(paddingRead < 0) {
		printk("Reading padding failed\n");
                err = -EFAULT;
		goto out12;
	    }
	    padvalue = reconstructPadding(padding);
	    if (padvalue < 0) {
		printk("Reconstructing padding value failed(negative value not acceptable)\n");
                err = -EFAULT;
		goto out12;
	    }
	    printk("Pad value returned : %d\n", padvalue);
	    while(result==PAGE_SIZE) {
                result = wrapfs_read_file(filp, (void *)srcbuffer, PAGE_SIZE);
		if (result < 0) {
		    printk("Reading from input file failed\n");
                    err = -EFAULT;
		    goto out12;
		}
                printk("result read from file : %u\n", result);
                err = decrypt_Cipher(arguments->keyBuf, srcbuffer, destbuffer, result);
		if (err < 0) {
                    printk("Error occured while encrypting\n");
                    goto out12;
                }	
		if (result<PAGE_SIZE) {
		    result = result - padvalue;
		}
                result = wrapfs_write_file(filp1, (void *)destbuffer, result);
		if(result < 0) {
		    printk("writing to output file failed\n");
                    err = -EFAULT; //TODO goto
		    goto out12;
		}
            }
	}
	if(!outFileCreated) {
	    err = file_rename(newdentry->d_parent->d_inode, newdentry, olddentry->d_parent->d_inode, olddentry);
	    if(err!=0) {
		printk("renaming of tempfile to output file failed\n");
                err = -EBUSY;
		goto out12;
	    } else
		renamed = true;
        } else
	    success = true;

out12:
	if(keyFromFile)
	    kfree(keyFromFile);
out11:
	kfree(md5_hash);
out10:
	if(filp1)
	    filp_close(filp1, NULL);
	if((!renamed && !outFileCreated)||(!success && outFileCreated))
	    file_unlink(newdentry->d_parent->d_inode, newdentry);
out9:
	if(filp1)
	    filp_close(filp1, NULL);
out8_1:
	if(filp)
	    filp_close(filp, NULL);
out8:
	kfree(padding);
out7:
	kfree(destbuffer);
out6:
	kfree(srcbuffer);
out5:
	kfree(arguments->keyBuf);
out4:
	kfree(arguments->outputFile);
out3:
	kfree(arguments->inputFile);
out2:
 	kfree(arguments);
out1:
	return err;
    }
}