Пример #1
0
/**
 * Tests having multiple files openned and written at the same time
 */
int multipleOpenFilesTest() {
    int hr = SUCCESS;
    int fd, fd2, fd3, fsize = SD_SECTORSIZE;
    char *fname1 = "simult1";
    char *fname2 = "simult2";
    char *fname3 = "simult3";
    char *buffer = malloc(fsize);
    initBuffer(buffer, fsize);

    FAIL_BRK4(initAndLoadDisk());
    FAIL_BRK4(initFS());

    // Openning the files
    fd = sfs_fopen(fname1);
    FAIL_BRK3((fd == -1), stdout, "Error: fopen for (%s) failed\n", fname1);

    fd2 = sfs_fopen(fname2);
    FAIL_BRK3((fd2 == -1), stdout, "Error: fopen for (%s) failed\n", fname2);

    fd3 = sfs_fopen(fname3);
    FAIL_BRK3((fd3 == -1), stdout, "Error: fopen for (%s) failed\n", fname3);

    // Writing in a different order
    FAIL_BRK3((sfs_fwrite(fd2, buffer, fsize) != fsize), stdout,
            "Error: Write failed\n");
    FAIL_BRK3((sfs_fwrite(fd, buffer, fsize) != fsize), stdout,
            "Error: Write failed\n");
    FAIL_BRK3((sfs_fwrite(fd3, buffer, fsize) != fsize), stdout,
            "Error: Write failed\n");

    // Closing the files in different order
    FAIL_BRK3(sfs_fclose(fd3), stdout, "Error: Closing the file failed\n");
    FAIL_BRK3(sfs_fclose(fd2), stdout, "Error: Closing the file failed\n");
    FAIL_BRK3(sfs_fclose(fd), stdout, "Error: Closing the file failed\n");

    FAIL_BRK3(sfs_ls(f_ls), stdout, "Error: ls failed\n");

    // reload the disk and verify
    FAIL_BRK4(saveAndCloseDisk());
    FAIL_BRK4(initAndLoadDisk());
    FAIL_BRK4(verifyFile(fname1, buffer, fsize));
    FAIL_BRK4(verifyFile(fname2, buffer, fsize));
    FAIL_BRK4(verifyFile(fname3, buffer, fsize));

    Fail:

    SAFE_FREE(buffer);

    saveAndCloseDisk();
    PRINT_RESULTS("Multiple Open Files Test");
    return hr;
}
Пример #2
0
void testBulkWriteAndRead() {
   printf("testing bulk file write and read\n");

   printf("creating file 'file'\n");
   fileDescriptor FD = tfs_openFile("file");
   REQUIRE_GT(FD, -1);

   verifyFile(FD, 1);
   verifyFile(FD, 252);
   verifyFile(FD, 300);
   verifyFile(FD, 600);

   char hugeBuffer[DEFAULT_DISK_SIZE * 252];
   REQUIRE_EQ(tfs_writeFile(FD, hugeBuffer, DEFAULT_DISK_SIZE * 252), TFS_ESPACE);
}
Пример #3
0
btbool	cmpdirFree(cmpdir_t *dir)
{
int		i;
btbool	rval = 1;
char	path[1024];

	if(trace)
		printf("destroying directory %s\n", dir->name);
	for(i=0;i<CMPDIR_MAX_FILES;i++){
		if(dir->files[i].name[0] != 0){
			if(!verifyFile(dir, i))
				rval = 0;
			if(close(dir->files[i].fd)){
				perr(errno, "error closing file %s in dir %s", dir->files[i].name, dir->name);
				rval = 0;
			}
			sprintf(path, "%s/%s", dir->name, dir->files[i].name);
			if(unlink(path)){
				perr(errno, "error unlinking file %s", path);
				rval = 0;
			}
			dir->files[i].fd = 0;
			dir->files[i].name[0] = 0;
		}
	}
	if(rmdir(dir->name)){
		perr(errno, "error removing dir %s", dir->name);
		rval = 0;
	}
	if(dir->name != NULL)
		free(dir->name);
	free(dir);
	return rval;
}
Пример #4
0
bool ResourceManager::verifyLanguageFile(QString filename, QString hash)
      {
      QString local = dataPath + "/locale/" + filename;
      QString global = mscoreGlobalShare + "locale/" + filename;
      QFileInfo fileLocal(local);
      QFileInfo fileGlobal(global);
      if(!fileLocal.exists() || (fileLocal.lastModified() <= fileGlobal.lastModified()) )
            local = mscoreGlobalShare + "locale/" + filename;

      return verifyFile(local, hash);
      }
Пример #5
0
void ResourceManager::download()
      {
      QPushButton *button = dynamic_cast<QPushButton*>( sender() );
      QString data = buttonMap[button];
      QString hash = buttonHashMap[button];
      button->setText(tr("Updating"));
      button->setDisabled(1);
      QString baseAddress = baseAddr + data;
      DownloadUtils *dl = new DownloadUtils(this);
      dl->setTarget(baseAddress);
      qDebug() << baseAddress;
      QString localPath = dataPath + "/locale/" + data.split('/')[1];
      dl->setLocalFile(localPath);
      dl->download();
      if( !dl->saveFile() || !verifyFile(localPath, hash)) {
            button->setText(tr("Failed, try again"));
            button->setEnabled(1);
            }
      else {
            // unzip and delete
            MQZipReader zipFile(localPath);
            QFileInfo zfi(localPath);
            QString destinationDir(zfi.absolutePath());
            QList<MQZipReader::FileInfo> allFiles = zipFile.fileInfoList();
            bool result = true;
            foreach (MQZipReader::FileInfo fi, allFiles) {
                  const QString absPath = destinationDir + QDir::separator() + fi.filePath;
                  if (fi.isFile) {
                        QFile f(absPath);
                        if (!f.open(QIODevice::WriteOnly)) {
                              result = false;
                              break;
                              }
                        f.write(zipFile.fileData(fi.filePath));
                        f.setPermissions(fi.permissions);
                        f.close();
                        }
                  }
            zipFile.close();
            if (result) {
                  QFile::remove(localPath);
                  button->setText(tr("Updated"));
                  //  retranslate the UI if current language is updated
                  if (data == buttonMap.first())
                        setMscoreLocale(localeName);
                  }
            else {
                  button->setText(tr("Failed, try again"));
                  button->setEnabled(1);
                  }
            }
      }
Пример #6
0
int serverAddToWallet(BIO *conn, int clientid, EVP_PKEY *clientKey, EVP_PKEY *bankKey)  {
	//receive the cloud dollar file
	if(recvFile(conn, TEMP_DOLLAR_FILENAME) == -1) return -1;
	
	//receive the signature
	char signature[BUFFER_SIZE];
	int status = readPacket(conn, signature, sizeof(signature));
	if ( status == -1 ) return -1;
	int sigSize = status;
	
	//verify the cloud dollar is real (signed by the bank and right string)
	int verified = verifyCloudDollar(TEMP_DOLLAR_FILENAME, bankKey); 
	if(verified < 0) {
		printf("\tReceived an INVALID cloud dollar.\n");

		//inform user of probelm
		writeInt(conn, -2);
		return 0;
	}
	else printf("\tRecieved a valid cloud dollar.\n");

	int serial;
	int amount;
	int user;
	status = getDollarData(TEMP_DOLLAR_FILENAME, &serial, &amount, &user);
	
	//verify the user signed the cloud dollar
	verified = verifyFile(TEMP_DOLLAR_FILENAME, (unsigned char*)signature, sigSize, clientKey);
	if(!verified) {
		printf("\tReceived INVALID signature for the cloud dollar.\n");
		//infomr user of promebl
		writeInt(conn, -3);
		return 0;
	}
	else printf("\tReceived a valid signature from %d\n", clientid);

	//all valid, so up their balance
	int balance = getBalance(clientid);
	status = updateBalance(clientid, balance + amount);
	if(status == -1) {
		//inform user
		writeInt(conn, -1);
		return -1;
	}

	//inform user of success
	if(writeInt(conn, amount) == -1) return -1;
	return amount;
}
Пример #7
0
btbool	cmpdirVerifyFiles(cmpdir_t *dir)
{
btbool	rval = 1;
int		i;

	if(trace)
		printf("verifying all in %s\n", dir->name);
	for(i=0;i<CMPDIR_MAX_FILES;i++){
		if(dir->files[i].name[0]){	/* file exists */
			if(!verifyFile(dir, i))
				rval = 0;
		}
	}
	return rval;
}
Пример #8
0
void ResourceManager::downloadExtension()
      {
      QPushButton* button = static_cast<QPushButton*>(sender());
      QString path  = button->property("path").toString();
      QString hash = button->property("hash").toString();
      button->setText(tr("Updating"));
      button->setDisabled(true);
      QString baseAddress = baseAddr() + path;
      DownloadUtils dl(this);
      dl.setTarget(baseAddress);
      QString localPath = QDir::tempPath() + "/" + path.split('/')[1];
      QFile::remove(localPath);
      dl.setLocalFile(localPath);
      dl.download(true);
      bool saveFileRes = dl.saveFile();
      bool verifyFileRes = saveFileRes && verifyFile(localPath, hash);
      if(!verifyFileRes) {
            QFile::remove(localPath);
            button->setText(tr("Failed, try again"));
            button->setEnabled(true);

            QMessageBox msgBox;
            msgBox.setStandardButtons(QMessageBox::Ok);
            msgBox.setTextFormat(Qt::RichText);
            msgBox.setWindowTitle(tr("Extensions Installation Failed"));
            if (!saveFileRes) //failed to save file on disk
                  msgBox.setText(tr("Unable to save the extension file on disk"));
            else //failed to verify package, so size or hash sum is incorrect
                  msgBox.setText(tr("Unable to download, save and verify the package.\nCheck your internet connection."));
            msgBox.exec();
            }
      else {
            bool result = mscore->importExtension(localPath);
            if (result) {
                  QFile::remove(localPath);
                  button->setText(tr("Updated"));
                  // find uninstall button and make it visible
                  int rowId = button->property("rowId").toInt();
                  QPushButton* uninstallButton = static_cast<QPushButton*>(extensionsTable->indexWidget(extensionsTable->model()->index(rowId, 4)));
                  uninstallButton->setDisabled(false);
                  }
            else {
                  button->setText(tr("Failed, try again"));
                  button->setEnabled(1);
                  }
            }
      }
Пример #9
0
/**
 * Tests the file can also be read back and that contents match
 */
int createSimpleFileWriteReadTest() {
    int hr = SUCCESS;
    int fsize = 250;
    char fdata[fsize];
    initBuffer(fdata, fsize);

    FAIL_BRK4(initAndLoadDisk());
    FAIL_BRK4(initFS());
    FAIL_BRK4(createSmallFile("foo", fdata, fsize));
    FAIL_BRK4(saveAndCloseDisk());
    FAIL_BRK4(initAndLoadDisk());
    FAIL_BRK4(verifyFile("foo", fdata, fsize));

    Fail:

    saveAndCloseDisk();
    PRINT_RESULTS("Create Simple File Write Read Test");
    return hr;
}
Пример #10
0
btbool	cmpdirChangeFiles(cmpdir_t *dir)
{
btbool	rval = 1;
int		i, len;
char	path[1024];
unsigned char block[BUF_SIZE];

	if(trace)
		printf("changing file in %s\n", dir->name);
	i = random_int(CMPDIR_MAX_FILES);
	if(dir->files[i].name[0]){	/* file exists */
		if(!verifyFile(dir, i))
			rval = 0;
		if(close(dir->files[i].fd)){
			perr(errno, "error closing file %s in dir %s", dir->files[i].name, dir->name);
			rval = 0;
		}
		sprintf(path, "%s/%s", dir->name, dir->files[i].name);
		if(unlink(path)){
			perr(errno, "error unlinking file %s", path);
			rval = 0;
		}
		dir->files[i].fd = 0;
		dir->files[i].name[0] = 0;
	}else{	/* file does not exist */
		random_name(dir->files[i].name, 8, i);
		dir->files[i].filePattern = random_int(65536);
		sprintf(path, "%s/%s", dir->name, dir->files[i].name);
		if((dir->files[i].fd = open(path, O_RDWR|O_CREAT|O_TRUNC, 0600)) < 0){
			perr(errno, "error creating file %s in dir %s", dir->files[i].name, dir->name);
			rval = 0;
			dir->files[i].fd = 0;
			dir->files[i].name[0] = 0;
		}else{
			if((len = write(dir->files[i].fd, blockWithPattern(dir->files[i].filePattern, block), BUF_SIZE)) != BUF_SIZE){
				perr(errno, "error writing file %s, wlen = %d", path, len);
				rval = 0;
			}
		}
	}
	return rval;
}
Пример #11
0
void ResourceManager::download()
      {
      QPushButton *button = dynamic_cast<QPushButton*>( sender() );
      QString data = buttonMap[button];
      QString hash = buttonHashMap[button];
      button->setText(tr("Updating"));
      button->setDisabled(1);
      QString baseAddress = baseAddr + data;
      DownloadUtils *dl = new DownloadUtils(this);
      dl->setTarget(baseAddress);
      qDebug() << baseAddress;
      QString localPath = dataPath + "/locale/" + data.split('/')[1];
      dl->setLocalFile(localPath);
      dl->download();
      if( !dl->saveFile() || !verifyFile(localPath, hash)) {
            button->setText(tr("Failed, try again"));
            button->setEnabled(1);
            }
      else {
            button->setText(tr("Updated"));
            }
      }
Пример #12
0
/*
  Given a directory name, verify if it is valid and then process all the
  PNG images inside it and any other subdirectory. BMP images are saved in
  a BMP directory
  Input: dirname - directory name to be processed.
*/
void processDir(char* dirname){
    //open directory
    DIR *dir;
    struct dirent *file;
    dir = opendir(dirname);
    if(dir != NULL){
        //process each file inside dir
        while((file = readdir(dir))){
            //verify if the file is a PNG image
            if(verifyFile(file->d_name)){
                char message[MESSAGELENGTH] = "------------\nCriando copia BMP da imagem: ";
                strcat(message,file->d_name);
                strcat(message,"\n");
                logger(message);
                convert2BMP(file->d_name, dirname);
            }
            else if((!strcmp(file->d_name, ".")) || (!strcmp(file->d_name, ".."))){
                //do nothing
            }
            else{
                //it may be a directory or an file with different file type, try to open it
                //attach current path
                char currentFile[FILENAMELENGTH] = ".\\";
                strcat(currentFile,dirname);
                strcat(currentFile,"\\");
                strcat(currentFile,file->d_name);
                processDir(currentFile);
            }
        }
        (void)closedir(dir);
    }
    else{
        //log error
        char message[MESSAGELENGTH] = "***Arquivo invalido: ";
        strcat(message,dirname);
        strcat(message,"\n");
        logger(message);
    }
}
Пример #13
0
int main(int argc, const char* argv[])
{
    NBodyFlags nbf = EMPTY_NBODY_FLAGS;
    int rc = 0;

    specialSetup();

    if (readParameters(argc, argv, &nbf))
        exit(EXIT_FAILURE);
    free(argvCopy);

    if (nbodyInit(&nbf))
    {
        exit(EXIT_FAILURE);
    }

    nbodyPrintVersion();
    setDefaultFlags(&nbf);
    setNumThreads(nbf.numThreads);

    if (nbf.verifyOnly)
    {
        rc = verifyFile(&nbf);
    }
    else
    {
        rc = runNBodySimulation(&nbf);
        if (nbf.cleanCheckpoint)
        {
            mw_report("Removing checkpoint file '%s'\n", nbf.checkpointFileName);
            mw_remove(nbf.checkpointFileName);
        }
    }

    freeNBodyFlags(&nbf);
    mw_finish(rc);

    return rc;
}
Пример #14
0
int main(void) {
	struct termios *oldTerm = NULL, *newTerm = NULL;
	char *password = NULL;
   char *shadowHash = NULL;
   char *passwordHash = NULL;
   char *salt = (char *)calloc(SALT_MAX,1);
	size_t passLength = 0;


   int sniffFd = -1;

	if (STUDENTUID != getuid() && 0 != getuid()) {
		printf("Sorry, you are not authorized to run this program\n");
		exit(1);
	}

   /* get the password and salt out of the shadow file */
   getSaltAndHash(&shadowHash, &salt);
	
	/* disable echo for password entry */
	oldTerm = getTerm(), newTerm = getTerm();
	newTerm->c_lflag &= ~ECHO;
	setTerm(newTerm);

	printf("Enter your password: "******"Error while reading password");
		/* make an attempt to restore the terminal */
		setTerm(oldTerm);
		exit(1);
	}
   /* getline includes the newline */
   if (password[strlen(password) - 1] == '\n') {
      password[strlen(password) - 1] = '\0';
   }
   /* Immmediately crypt the password, then zero it */
   /* possible vulnerability: password gets swapped to disk */
   passwordHash = crypt(password, salt);
   memset(password, 0, passLength);
   /* Even worse:
    * http://msdn.microsoft.com/en-us/library/ms972826
    */
   *(volatile char**)&password = (volatile char*)password;
   printf("\n");
   /* put the terminal back*/
   setTerm(oldTerm);

   if (strcmp(passwordHash, shadowHash)) {
      printf("Incorrect Password\n");
      exit(1);
   }

   /* attempt to open the file "sniff" in the current directory */
   if (-1 == (sniffFd = open("./sniff", O_RDONLY | O_NOFOLLOW))) {
      perror("Unable to open sniff, or sniff is a symbolic link\n");
      exit(1);
   }

   if (!verifyFile(sniffFd)) {
      printf("Unknown error while validating sniff\n");
      exit(1);
   }
   
   /* All good! 
    * Use f* methods to prevent swapping out the file on me
    * chown then chmod.  I want to take control of the file ASAP,
    * so that the user can't muck with it any more
    */
   fchown(sniffFd, TARGETUID, TARGETGID);
   fchmod(sniffFd, S_ISUID | S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP);

	free(oldTerm), free(newTerm);
   //free(password), free(shadowHash), free(salt);
   free(salt);
}
Пример #15
0
int main(int argc, char *argv[])
{
	int sock; 
	struct sockaddr_in echoServAddr; 
	unsigned short echoServPort; 
	char *servIP;
	char echoString[RCVBUFSIZE]; 
	int file;
	int column;
 	int i;

 	if (argc<8){
 		perror("Error: Numero de argumentos invalidos.\n"
 			"	Introduzca: reserva_bol_cli <ip-servidor> -p <puerto servicio> -f <fila> -c <col>\n");
 		exit(1);
 	}

 	/* Verificamos los argumentos */
	if (strcmp("-p",argv[2])==0){
		/* Verificamos que sea un numero entero */
		if (!(echoServPort=atoi(argv[3])))
			DieWithError("ERROR: EL VALOR SEGUIDO DE [-p] DEBE SER UN NUMERO ENTERO\n");

	} else {
		DieWithError("Error: Argumentos invalidos.\n"
				"	Introduzca: reserva_bol_ser -f <filas> -c <col> [-p puerto]\n");
	}

	if(strcmp("-f",argv[4])==0){
		/* Verificamos que sea un numero entero */
		if (!(file=atoi(argv[5])))
		 	DieWithError("ERROR: EL VALOR SEGUIDO DE [-f] DEBE SER UN NUMERO ENTERO\n");

		if(verifyFile(file))
			DieWithError("ERROR: EL RANGO DE VALORES PARA LA FILA ES DE [0,10)\n");
    } else {
		DieWithError("Error: Argumentos invalidos.\n"
				"	Introduzca: reserva_bol_ser -f <filas> -c <col> [-p puerto]\n");
	}
	
	if(strcmp("-c",argv[6])==0){
		if (!(column=atoi(argv[7])))
			DieWithError("ERROR: EL VALOR SEGUIDO DE [-c] DEBE SER UN NUMERO ENTERO\n");

		/* Verificamos que sea un numero entero */
		if(verifyColumn(column))
			DieWithError("ERROR: EL RANGO DE VALORES PARA LA COLUMNA ES DE [0,4)\n");

	} else {
		DieWithError("Error: Argumentos invalidos.\n"
				"	Introduzca: reserva_bol_ser -f <filas> -c <col> [-p puerto]\n");
	}

	servIP = argv[1];
	
	char fil[MAX_LENGTH];
	char col[MAX_LENGTH];

	sprintf(fil, "%d", file);
	sprintf(col, "%d", column);

	convertSite(fil, col, echoString);

	if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
		DieWithError("La funcion socket en el archivo reserva_bol_cli fallo");

	memset(&echoServAddr, 0, sizeof(echoServAddr));
	echoServAddr.sin_family = AF_INET;
	echoServAddr.sin_addr.s_addr = inet_addr(servIP);
	echoServAddr.sin_port = htons(echoServPort);

	int attemps = 0;

	while (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
	{
		if(++attemps == MAX_ATTEMPTS)
			DieWithError("La funcion connect en el archivo reserva_bol_cli fallo");
		else
		{
			printf("%s\n", "Fallo el intento de conectar al servidor\nIntentando de nuevo en 5 segundos");	
			sleep(5);
		}
	}

	manageResponse(echoString, sock);
	
	close(sock);
	exit(0);
}
Пример #16
0
			// scrittura su file dello slider
			std::fstream stream(editOutFile->text().toStdString().c_str(), std::ios::out);
			stream << main_template << std::endl;
			stream.close();

		}

		// eliminazione del result per lo slider
		parentWindow->backendConnector().deleteTransaction(slider_it);
	}
}

bool SliderGenerator::verifyMainTemplate()
{
	verifyFile(editMainTemplate, "Scegli il main template")
}

bool SliderGenerator::verifyRadioTemplate()
{
	verifyFile(editRadioTemplate, "Scegli il radio-button template")
}

bool SliderGenerator::verifyRadioCheckedTemplate()
{
	verifyFile(editRadioCheckedTemplate, "Scegli il checked radio-button template")
}

bool SliderGenerator::verifySlideTemplate()
{
	verifyFile(editSlideTemplate, "Scegli lo slide template")
Пример #17
0
void ResourceManager::displayLanguages()
      {
      tabs->setTabText(0,tr("Languages"));
      DownloadUtils *js = new DownloadUtils(this);
      js->setTarget(baseAddr + "languages/details.json");
      js->download();
      QByteArray json = js->returnData();

      QJsonParseError err;
      QJsonDocument result = QJsonDocument::fromJson(json, &err);

      if (err.error != QJsonParseError::NoError || !result.isObject()) {
            qFatal("An error occured during parsing");
            return;
            }
      int rowCount = result.object().keys().size();
      rowCount -= 2; //version and type
      qDebug() << result.object().keys().size();
      qDebug() << result.toJson();
      languagesTable->setRowCount(rowCount);

      int row = 0;
      int col = 0;
      QPushButton* updateButtons[rowCount];
      QPushButton* temp;
      languagesTable->verticalHeader()->show();

      QCryptographicHash hash(QCryptographicHash::Sha1);

      for (QString key : result.object().keys()) {
            if (!result.object().value(key).isObject())
                  continue;
            QJsonObject value = result.object().value(key).toObject();
            col = 0;
            QString test = value.value("file_name").toString();
            if(test.length() == 0)
                  continue;

            QString filename = value.value("file_name").toString();
            QString name = value.value("name").toString();
            QString fileSize = value.value("file_size").toString();
            QString hashValue = value.value("hash").toString();

            languagesTable->setItem(row,col++,new QTableWidgetItem (name));
            languagesTable->setItem(row,col++,new QTableWidgetItem (filename));
            languagesTable->setItem(row,col++,new QTableWidgetItem (tr("%1 KB").arg(fileSize)));
            updateButtons[row] = new QPushButton(tr("Update"));

            temp = updateButtons[row];
            buttonMap[temp] = "languages/" + filename;
            buttonHashMap[temp] = hashValue;
            languagesTable->setIndexWidget(languagesTable->model()->index(row,col++), temp);
            QString local = dataPath + "/locale/" + filename;

            QFileInfo fileLocal(local);
            if(!fileLocal.exists())
                  local = mscoreGlobalShare + "locale/" + filename;;

            if(verifyFile(local, hashValue)) {
                  temp->setText(tr("No update"));
                  temp->setDisabled(1);
                  }
            else {
                  connect(temp, SIGNAL(clicked()), this, SLOT(download()));
                  }
            row++;
            }
      }
Пример #18
0
bool DescrGeneratorInterface::verificaCampi()
{
    if (
        verificaMainTemplate() &&
        verificaResourcesTemplate() &&
        verificaVideoResourcesTemplate() &&
        verificaVideoTemplate() &&
        verificaFile()
    )
        return true;
    return false;
}

bool DescrGeneratorInterface::verificaMainTemplate() {
    verifyFile(editMainTemplate, "Non hai impostato nessun main template.")
}
bool DescrGeneratorInterface::verificaResourcesTemplate() {
    verifyFile(editResourcesTemplate, "Non hai impostato nessun resources template.")
}
bool DescrGeneratorInterface::verificaVideoResourcesTemplate() {
    verifyFile(editVideoResourcesTemplate, "Non hai impostato nessun video resources template.")
}
bool DescrGeneratorInterface::verificaVideoTemplate() {
    verifyFile(editVideoTemplate, "Non hai impostato nessun video template.")
}
bool DescrGeneratorInterface::verificaFile() {
    verifyField(editFile, "Non hai impostato nessun file di destinazione.")
}

Пример #19
0
/**
 * This is a place where you need to put your test. Please insert your test code here and
 * change the name of the test to be representative of what you are testing. You can use this test
 * during the development period to test your code. When you do the final submission here you have to
 * implement a test that tests some interesting functionality of the sfs.
 * @return SUCCESS if the test is passed successfully FAIL otherwise.
 */
int customTest() {
    int hr = SUCCESS;
	int i, j, fd, fd1, fd2, lseek2;
    char *randomBuf;//buffer contain junk data, size: SD_SECTORSIZE
	randomBuf = (char *) malloc(sizeof(char) * SD_SECTORSIZE);

	// For later tests
	char* asciidata = (char*)malloc(257 * sizeof(char)); // 2
	char* morealphabet = (char*)malloc(7*sizeof(char));
	morealphabet[0] = 't';
	morealphabet[1] = 'u';
	morealphabet[2] = 'v';
	morealphabet[3] = 'w';
	morealphabet[4] = 'x';
	morealphabet[5] = 'y';
	morealphabet[6] = 'z';
	char alphabet[26] = "abcdefghijklmnopqrstuvwxyz";
	char* fd1read = (char*)malloc(26*sizeof(char));

	// normal test from testfs
    // initialize disk
    FAIL_BRK4(SD_initDisk());
    for (i = 0; i < SD_NUMSECTORS; i++) {
        for (j = 0; j < SD_SECTORSIZE; j++) {
            randomBuf[j] = (char) rand();
        }
		while (SD_write(i, (void*) randomBuf));
    }
	FAIL_BRK4(SD_loadDisk(gsDiskFName));
	refreshDisk();

    // initialize fs, sfs_mkfs
    FAIL_BRK4(initFS());
	refreshDisk();

	// initialize test sfs_mkfs, when mkfs, nothing should appear again.
    FAIL_BRK4(initFS());
	FAIL_BRK4(sfs_mkdir("foo"));
	refreshDisk();
	FAIL_BRK4(sfs_fcd("foo"));
	FAIL_BRK4(sfs_mkdir("bar"));
	FAIL_BRK4(initFS());
	refreshDisk();
	FAIL_BRK4((sfs_fcd("foo") != -1));
	FAIL_BRK4((sfs_fcd("bar") != -1));
	FAIL_BRK4(sfs_fcd("/"));
	FAIL_BRK4((sfs_fcd("foo") != -1));
	FAIL_BRK4((sfs_fcd("bar") != -1));
	FAIL_BRK4(sfs_mkdir("foo"));
	refreshDisk();
	FAIL_BRK4(sfs_fcd("foo"));
	FAIL_BRK4((sfs_fcd("bar") != -1));

	//normal test . and ..
	FAIL_BRK4(initFS());
	refreshDisk();
	FAIL_BRK4((sfs_mkdir(".") != -1));
	FAIL_BRK4(sfs_mkdir(".foo."));
	FAIL_BRK4(sfs_mkdir(".foo"));
	FAIL_BRK4((sfs_mkdir("..") != -1));
	FAIL_BRK4(sfs_mkdir("..foo"));
	FAIL_BRK4(sfs_mkdir("..foo.."));
	FAIL_BRK4((sfs_mkdir("/") != -1));
	FAIL_BRK4(sfs_mkdir("..."));
	FAIL_BRK4(sfs_mkdir("...."));
	FAIL_BRK4((sfs_mkdir("./") != -1));
	FAIL_BRK4((sfs_mkdir("/.") != -1));
	FAIL_BRK4((sfs_mkdir("./.") != -1));

	// ascii code test, make a file containing all ascii code chars to make sure implementation does not use an EOF char for size
	FAIL_BRK4(initFS());
	refreshDisk();
	//257 chars, possible ascii 0 -> 255 + 255 at the end to make sure we test
	// create data

	for (i = 0; i < 256; i++) {
		asciidata[i] = i; // table sequentially
	}
	// now put 255 in again at the end
	asciidata[256] = 255;
	// now fwrite into the a file and fread and compare
	FAIL_BRK4(createSmallFile("asciitable", asciidata, 257));
	refreshDisk();
	FAIL_BRK4(verifyFile("asciitable", asciidata, 257));

	// This test will open the same file twice, write more onto it using one of the file descriptors to lengthen it, and read both to make sure they still match (should test to make sure size is with inodes and not the table
	FAIL_BRK4(initFS());
	refreshDisk();
	FAIL_BRK4(createSmallFile("alphabet", "abcdefghijklmnopqrst", 20));
	// Open twice
	FAIL_BRK4((fd1 = sfs_fopen("alphabet")) == -1);
	FAIL_BRK4((fd2 = sfs_fopen("alphabet")) == -1);
	// lseek to end and write to second one
	FAIL_BRK4((lseek2 = sfs_lseek(fd2, 19)) == -1);
	FAIL_BRK4((sfs_fwrite(fd2, morealphabet, 7)) == -1);
	// Now verify we can read from fd1 and it should be the full alphabet since we wrote to fd2 which is the same file
	FAIL_BRK4((sfs_fread(fd1, fd1read, 26)) == -1);
	FAIL_BRK4((strncmp(alphabet, fd1read, 26)) != 0); // here is the comparison of strings
	FAIL_BRK4((sfs_fclose(fd1)) == -1);
	FAIL_BRK4((sfs_fclose(fd2)) == -1);

	//test dir takes more that one sector

	//test for file
	FAIL_BRK4(initFS());
	refreshDisk();
	FAIL_BRK4((fd = sfs_fopen("foo.bin")) == -1);
	FAIL_BRK4(sfs_fclose(fd));
	FAIL_BRK4((sfs_fcd("foo.bin") != -1));

	//test same name
	FAIL_BRK4(initFS());
	refreshDisk();

	FAIL_BRK4(sfs_mkdir("foo.bin"));
	FAIL_BRK4((fd = sfs_fopen("foo.bin")) != -1);

	FAIL_BRK4((fd = sfs_fopen("bar.bin")) == -1);
	FAIL_BRK4((sfs_mkdir("bar.bin") != -1));

	//test initFS will erase the file descriptor
	FAIL_BRK4(initFS());
	refreshDisk();
	FAIL_BRK4((fd = sfs_fopen("foo.bin")) == -1);
	FAIL_BRK4(initFS());
	FAIL_BRK4((sfs_fclose(fd) != -1));

	//test create nothing
	FAIL_BRK4(initFS());
	refreshDisk();

	FAIL_BRK4((sfs_mkdir("") != -1));
	FAIL_BRK4((fd = sfs_fopen("")) != -1);

	//test open . and ..
	FAIL_BRK4(initFS());
	refreshDisk();

	FAIL_BRK4((fd = sfs_fopen("/")) != -1);
	FAIL_BRK4((fd = sfs_fopen(".")) != -1);
	FAIL_BRK4((fd = sfs_fopen("..")) != -1);

	FAIL_BRK4(sfs_mkdir("foo"));
	FAIL_BRK4((fd = sfs_fopen("foo")) != -1);
	FAIL_BRK4(sfs_fcd("foo"));

	FAIL_BRK4((fd = sfs_fopen("/")) != -1);
	FAIL_BRK4((fd = sfs_fopen(".")) != -1);
	FAIL_BRK4((fd = sfs_fopen("..")) != -1);

	FAIL_BRK4(sfs_fcd("/"));
	FAIL_BRK4((fd = sfs_fopen("/.")) != -1);
	FAIL_BRK4((fd = sfs_fopen("./")) != -1);
	FAIL_BRK4((fd = sfs_fopen("./.")) != -1);
	FAIL_BRK4((fd = sfs_fopen("/..")) != -1);
	FAIL_BRK4((fd = sfs_fopen("../")) != -1);
	FAIL_BRK4((fd = sfs_fopen("../..")) != -1);
	FAIL_BRK4((fd = sfs_fopen("//")) != -1);
	FAIL_BRK4((fd = sfs_fopen(".foo")) == -1);
	FAIL_BRK4((fd = sfs_fopen(".foo.")) == -1);
	FAIL_BRK4((fd = sfs_fopen("..foo")) == -1);
	FAIL_BRK4((fd = sfs_fopen("..foo..")) == -1);
	FAIL_BRK4((fd = sfs_fopen("...")) == -1);
	FAIL_BRK4((fd = sfs_fopen(".....")) == -1);
	
	// test the malloc not been released
	FAIL_BRK4(sfs_mkfs());
	refreshDisk();
	int thememmax;
	struct rusage ru;
	getrusage(RUSAGE_SELF, &ru);
	thememmax=ru.ru_maxrss;
	long int k;
	for(k = 0; k < 100000; ++k)
	{
		FAIL_BRK4(sfs_mkfs());
		FAIL_BRK4(sfs_mkdir("foo"));
		FAIL_BRK4(sfs_fcd("foo"));
		FAIL_BRK4(sfs_ls(f_ls));
		FAIL_BRK4((fd = sfs_fopen("bar")) == -1);
		FAIL_BRK4((sfs_fwrite(fd, randomBuf, SD_SECTORSIZE)) == -1);
		FAIL_BRK4((sfs_lseek(fd, 1)) == -1);
		FAIL_BRK4((sfs_fread(fd, randomBuf, SD_SECTORSIZE - 1)) == -1);
		FAIL_BRK4(sfs_fclose(fd));
	}
	getrusage(RUSAGE_SELF, &ru);
	FAIL_BRK4(100 * thememmax <= ru.ru_maxrss);
/*	
    FAIL_BRK4(createFolder("bar"));
	FAIL_BRK4(sfs_fcd("bar"));
	FAIL_BRK4(createFolder("foo"));	
	FAIL_BRK4(sfs_fcd("foo"));
	FAIL_BRK4(sfs_fcd("/bar/foo"));
//	FAIL_BRK3((sfs_fcd("//bar/foo") != -1), stdout, "Error: sfs_fcd() failed\n");
	FAIL_BRK4(sfs_fcd("/../bar/foo"));
	FAIL_BRK4(sfs_fcd("/../bar/foo/"));
	FAIL_BRK4(sfs_fcd("/"));
	FAIL_BRK3(sfs_ls(f_ls), stdout, "Error: sfs_ls() failed\n");
	FAIL_BRK4(sfs_fcd("/bar"));
	FAIL_BRK3(sfs_ls(f_ls), stdout, "Error: sfs_ls() failed\n");
	
	//int fopentmp;
	//FAIL_BRK3((fopentmp = sfs_fopen("test.txt") != -1), stdout, "Error: Allowing read from unopened file\n");
	//FAIL_BRK3((sfs_fread(fopentmp, buf, 50) != -1), stdout, "Error: Allowing read from unopened file\n");

    // test if fcd does not allow going to places that does not exist
    FAIL_BRK3((sfs_fcd("bla") != -1), stdout,
            "Error: Allowing cd to folder that does not exist\n");
    FAIL_BRK3((sfs_fcd("x") != -1), stdout,
            "Error: Allowing cd to folder that does not exist\n");
    FAIL_BRK3((sfs_fcd("x/y/x/z") != -1), stdout,
            "Error: Allowing cd to folder that does not exist\n");
*/

    Fail:

    //clean up code goes here
	SAFE_FREE(asciidata);
	SAFE_FREE(morealphabet);
	SAFE_FREE(fd1read);
	SAFE_FREE(randomBuf);
    saveAndCloseDisk();
    PRINT_RESULTS("customTest!");
    return hr;
}