Пример #1
0
int32 MCF::verifyAll(const char* tempPath)
{
	if (!tempPath)
	{
		printf("Temp path is null.\n");
		return 3;
	}

	if (!m_sHeader->isValid())
	{
		printf("Mcf header is invalid.\n");
		return 1;
	}

	uint32 count = 0;
	for (size_t x=0; x<m_pFileList.size(); x++)
	{
		if (!m_pFileList[x]->isSaved())
			continue;

		count++;
	}

	if (count == 0)
	{
		printf("No files in the mcf are saved.\n");
		return 2;
	}

	UTIL::FS::FileHandle fh(getFile(), UTIL::FS::FILE_READ);

	uint32 badCount = 0;
	bool placeholder = false;

	for (size_t x=0; x<m_pFileList.size(); x++)
	{
		if (!m_pFileList[x]->isSaved())
			continue;

		try
		{
			m_pFileList[x]->verifyMcf(fh, placeholder);
		}
		catch (gcException &e)
		{
			printf("%s", gcString("{0}: Failed to verify Mcf with file: {1}\n", m_pFileList[x]->getName(), e).c_str());
			badCount++;
			continue;
		}

		if (!m_pFileList[x]->isComplete())
		{
			printf("%s", gcString("{0}: Failed mcf verify\n", m_pFileList[x]->getName()).c_str());
			badCount++;
			continue;
		}

		gcString t("{0}{1}{2}", tempPath?tempPath:".", DIRS_STR, m_pFileList[x]->getFullPath());
		UTIL::FS::Path path(t, "", true);
		UTIL::FS::recMakeFolder(path);

		UTIL::MISC::Buffer buff(10*1024);

		try
		{
			UTIL::FS::FileHandle file(path, UTIL::FS::FILE_WRITE);
			fh.seek(m_pFileList[x]->getOffSet());
#ifdef WIN32
			size_t size = 0;
#endif
			if (m_pFileList[x]->isCompressed())
			{
				uint64 done = m_pFileList[x]->getCSize();
				UTIL::MISC::BZ2Worker bz(UTIL::MISC::BZ2_DECOMPRESS);

				fh.read(done, [&bz, &file](const unsigned char* buff, uint32 size) -> bool
				{
					UTIL::FS::FileHandle* pFile = &file;

					bz.write((const char*)buff, size, [pFile](const unsigned char* tbuff, uint32 tsize) -> bool
					{
						pFile->write((const char*)tbuff, tsize);
						return false;
					});

					return false;
				});

				bz.end([&file](const unsigned char* tbuff, uint32 tsize) -> bool
				{
					file.write((const char*)tbuff, tsize);
					return false;
				});
			}
			else
			{
				uint64 done = m_pFileList[x]->getSize();

				fh.read(done, [&file](const unsigned char* buff, uint32 size) -> bool
				{
					file.write((const char*)buff, size);
					return false;
				});
			}
		}
		catch (gcException &e)
		{
			printf("%s", gcString("{0}: Failed to save file: {1}\n", m_pFileList[x]->getName(), e).c_str());
			badCount++;

			UTIL::FS::delFile(path);
			continue;
		}

		m_pFileList[x]->setDir(tempPath);
		m_pFileList[x]->verifyFile();
		m_pFileList[x]->setDir("");

		if (!m_pFileList[x]->isComplete())
		{
			printf("%s", gcString("{0}: Failed file verify\n", m_pFileList[x]->getName()).c_str());
			badCount++;
		}

		UTIL::FS::delFile(path);
	}

	UTIL::FS::delEmptyFolders(tempPath);

	return (int32)badCount*-1;
}
Пример #2
0
void Input::TryLoad()
{
    QString headerText, codefileText;

    if(fileDialog == NULL)
    {
        fileDialog = new FileDialog(parentWindow,
                                    QFileDialog::AcceptOpen,
                                    QFileDialog::ExistingFile);
    }

    QString headerPath = fileDialog->ShowGetHeader();
    if(headerPath.isNull() || headerPath.isEmpty())
    {
        emit results(InResultUserCancelled);
        return;
    }

    QString codefilePath = fileDialog->ShowGetCodefile();
    if(codefilePath.isNull() || codefilePath.isEmpty())
    {
        emit results(InResultUserCancelled);
        return;
    }

    if(!getFile(headerPath, headerText))
    {
        return; //results() already emitted by getFile
    }
    if(!getFile(codefilePath, codefileText))
    {
        return;
    }

    QStringList notFound;
    QStringList notParsed;
    AllSettings::ParseHeaderToSettings(headerText, notFound, notParsed);
    AllSettings::ParseCodefileToSettings(codefileText, notFound, notParsed);

    if(notFound.count() > 0 || notParsed.count() > 0)
    {
        QString report;

        if(notFound.count() > 0)
        {
            report += "The following settings were not found in the selected configuration files: \n\n";
            for(int i = 0; i < notFound.count(); i++)
            {
                report += QString(" - ") + notFound[i] + QString("\n");
            }
            if(notParsed.count() > 0)
            {
                report += "\n";
            }
        }
        if(notParsed.count() > 0)
        {
            report += "The following settings were located in the selected configuration files but could not be parsed: \n\n";
            for(int i = 0; i < notParsed.count(); i++)
            {
                report += QString(" - ") + notParsed[i] + QString("\n");
            }
        }

        messageBox->setText("Some settings could not be loaded.");
        messageBox->setInformativeText("Press \"Show Details\" to view which values were not loaded properly.");
        messageBox->setDetailedText(report);
        messageBox->setIcon(QMessageBox::Warning);
        messageBox->setStandardButtons(QMessageBox::Ok);

        messageBox->exec();
    }

    emit results(InResultSuccess);
}
Пример #3
0
int main (void)
{
	FILE * pFile;
	int l, x, y, l1;
	unsigned char * p, *buf, *buf1, header[512]; 
	char name[F_NAMEL] = {0};
	system("del /q "F_TMP_N);
	system("del /q "F_PAK_N);
	system("dir /b > "F_TMP_N);

	l = getFile(&p, F_TMP_N);
	if (l)
	{
		for (buf = p, memset(name,0,F_NAMEL), x = getName(&buf, name, &l), y = 0; 
			 x;
			 memset(name,0,F_NAMEL),x = getName(&buf, name, &l)) {
			if (y == 0) {
				l1 = getFile(&buf1, name);
				if (l1) {
					pFile = fopen (F_PAK_N,"wb+");
					if (pFile!=NULL) {
						*(unsigned int *)header = F_MAGIC;
						memcpy((unsigned char *)(header+F_MAGL+F_NUML),name,F_NAMEL);
						*(unsigned int *)(header+F_MAGL+F_NUML+F_NAMEL) = BYTES4ALIGN(l1);
						fwrite (header, 1, F_MAGL+F_NUML+F_NAMEL+F_LENL, pFile);
						fwrite (buf1, 1, l1, pFile);
						l1 = (BYTES4ALIGN(l1) - l1);
						if (l1) {
							memset(header,0xFF,l1);
							fwrite (header, 1, l1, pFile);
						}
						fclose(pFile);
						y++;
					}
					free(buf1);
				}
			} else {
				l1 = getFile(&buf1, name);
				if (l1) {
					pFile = fopen (F_PAK_N,"ab+");
					if (pFile!=NULL) {
						memcpy(header,name,F_NAMEL);
						*(unsigned int *)(header+F_NAMEL) = BYTES4ALIGN(l1);
						fwrite (header, 1, F_NAMEL+F_LENL, pFile);
						fwrite (buf1, 1, l1, pFile);
						l1 = (BYTES4ALIGN(l1) - l1);
						if (l1) {
							memset(header,0xFF,l1);
							fwrite (header, 1, l1, pFile);
						}
						fclose(pFile);
						y++;
					}
					free(buf1);
				}
			}
		}
		pFile = fopen (F_PAK_N,"rb+");
		if (pFile!=NULL) {
			fseek (pFile, F_MAGL, SEEK_SET);
			fwrite ((unsigned char *)&y, 1, F_NUML, pFile);
			fclose(pFile);
		}
		free(p);
	}
	system("del /q "F_TMP_N);

	/* pack the package.bin into image */
	pFile = fopen (F_IMG_N,"ab+");
	if (pFile!=NULL) {
		fseek (pFile , 0 , SEEK_END);
		l = ftell (pFile);
		l1 = getFile(&p, F_PAK_N);
		if (l1)
		{
			l = (BYTES512ALIGN(l) - l);
			if (l) {
				memset(header,0xFF,l);
				fwrite (header, 1, l, pFile);
			}
			fwrite (p, 1, l1, pFile);
			free(p);
			system("del /q "F_PAK_N);
		}
		fclose(pFile);
	}
	return 0;
}
Пример #4
0
Image Project::Item::loadAsImageFile() const
{
    return isValid() ? ImageCache::getFromFile (getFile())
                     : Image::null;
}
Пример #5
0
void Project::Item::setFile (const File& file)
{
    setFile (RelativePath (project.getRelativePathForFile (file), RelativePath::projectFolder));
    jassert (getFile() == file);
}
Пример #6
0
int l_File_isDirectory(lua_State* L)
{
	File& file = getFile(L, 1);
	lua_pushboolean(L, file.is<Directory>() && file.isValid());
	return 1;
}
Пример #7
0
int
rcDataObjGet (rcComm_t *conn, dataObjInp_t *dataObjInp, char *locFilePath)
{
    int status;
    portalOprOut_t *portalOprOut = NULL;
    bytesBuf_t dataObjOutBBuf;
#ifndef windows_platform
    struct stat statbuf;
#else
    struct irodsntstat statbuf;
#endif

    if (strcmp (locFilePath, STDOUT_FILE_NAME) == 0) {
        /* no parallel I/O if pipe to stdout */
        dataObjInp->numThreads = NO_THREADING;
    }
#ifndef windows_platform
    else if (stat (locFilePath, &statbuf) >= 0)
#else
    else if(iRODSNt_stat(locFilePath, &statbuf) >= 0)
#endif
    {
        /* local file exists */
        if (getValByKey (&dataObjInp->condInput, FORCE_FLAG_KW) == NULL) {
            return (OVERWRITE_WITHOUT_FORCE_FLAG);
        }
    }

    status = _rcDataObjGet (conn, dataObjInp, &portalOprOut, &dataObjOutBBuf);

    if (status < 0) {
        if (portalOprOut != NULL) free (portalOprOut);
        return (status);
    }

    if (status == 0 || dataObjOutBBuf.len > 0) {
        /* data included */
        /**** Removed by Raja as this can cause problems when the data sizes are different - say when post processing is done....Dec 2 2010
        if (dataObjInp->dataSize > 0 &&
          dataObjInp->dataSize != dataObjOutBBuf.len) {
                    rodsLog (LOG_NOTICE,
                     "putFile: totalWritten %lld dataSize %lld mismatch",
                     dataObjOutBBuf.len, dataObjInp->dataSize);
                   return (SYS_COPY_LEN_ERR);
        }
             ****/
        status = getIncludeFile (conn, &dataObjOutBBuf, locFilePath);
        free (dataObjOutBBuf.buf);
#ifdef RBUDP_TRANSFER
    } else if (getUdpPortFromPortList (&portalOprOut->portList) != 0) {
        int veryVerbose;
        /* rbudp transfer */
        /* some sanity check */
        if (portalOprOut->numThreads != 1) {
            rcOprComplete (conn, SYS_INVALID_PORTAL_OPR);
            free (portalOprOut);
            return (SYS_INVALID_PORTAL_OPR);
        }
        conn->transStat.numThreads = portalOprOut->numThreads;
        if (getValByKey (&dataObjInp->condInput, VERY_VERBOSE_KW) != NULL) {
            printf ("From server: NumThreads=%d, addr:%s, port:%d, cookie=%d\n",
                    portalOprOut->numThreads, portalOprOut->portList.hostAddr,
                    portalOprOut->portList.portNum, portalOprOut->portList.cookie);
            veryVerbose = 2;
        } else {
            veryVerbose = 0;
        }
        status = getFileToPortalRbudp (portalOprOut, locFilePath, 0,
                                       dataObjInp->dataSize, veryVerbose, 0);
        /* just send a complete msg */
        if (status < 0) {
            rcOprComplete (conn, status);
        } else {
            status = rcOprComplete (conn, portalOprOut->l1descInx);
        }
#endif  /* RBUDP_TRANSFER */
    } else {

        if (portalOprOut->numThreads <= 0) {
            status = getFile (conn, portalOprOut->l1descInx,
                              locFilePath, dataObjInp->objPath, dataObjInp->dataSize);
        } else {
            if (getValByKey (&dataObjInp->condInput, VERY_VERBOSE_KW) != NULL) {
                printf ("From server: NumThreads=%d, addr:%s, port:%d, cookie=%d\n",
                        portalOprOut->numThreads, portalOprOut->portList.hostAddr,
                        portalOprOut->portList.portNum, portalOprOut->portList.cookie);
            }
            /* some sanity check */
            if (portalOprOut->numThreads >= 20 * DEF_NUM_TRAN_THR) {
                rcOprComplete (conn, SYS_INVALID_PORTAL_OPR);
                free (portalOprOut);
                return (SYS_INVALID_PORTAL_OPR);
            }

            conn->transStat.numThreads = portalOprOut->numThreads;
            status = getFileFromPortal (conn, portalOprOut, locFilePath,
                                        dataObjInp->objPath, dataObjInp->dataSize);
        }
        /* just send a complete msg */
        if (status < 0) {
            rcOprComplete (conn, status);
        } else {
            status = rcOprComplete (conn, portalOprOut->l1descInx);
        }
    }

    if (status >= 0 && conn->fileRestart.info.numSeg > 0) {   /* file restart */
        clearLfRestartFile (&conn->fileRestart);
    }

    if (getValByKey (&dataObjInp->condInput, VERIFY_CHKSUM_KW) != NULL) {
        if (portalOprOut == NULL || strlen (portalOprOut->chksum) == 0) {
            rodsLog (LOG_ERROR,
                     "rcDataObjGet: VERIFY_CHKSUM_KW set but no chksum from server");
        } else {
            char chksumStr[NAME_LEN];

            status = chksumLocFile (locFilePath, chksumStr);

            if (status < 0) {
                rodsLogError (LOG_ERROR, status,
                              "rcDataObjGet: chksumLocFile error for %s, status = %d",
                              locFilePath, status);
                if (portalOprOut != NULL)
                    free (portalOprOut);
                return (status);
            }

            if (strcmp (portalOprOut->chksum, chksumStr) != 0) {
                status = USER_CHKSUM_MISMATCH;
                rodsLogError (LOG_ERROR, status,
                              "rcDataObjGet: chksum mismatch error for %s, status = %d",
                              locFilePath, status);
                if (portalOprOut != NULL)
                    free (portalOprOut);
                return (status);
            }
        }
    }
    if (portalOprOut != NULL) {
        free (portalOprOut);
    }

    return (status);
}
Пример #8
0
UString FilePath::getStem(const UString &p) {
    UString file = getFile(p);

    return UString(file.begin(), file.findLast('.'));
}
Пример #9
0
_Tt_string _Tt_db_object::move (const _Tt_string &new_file)
{
  _Tt_string new_objid;

  if (!new_file.len()) {
    dbResults = TT_DB_ERR_ILLEGAL_FILE;
    return new_objid;
  }

  if (isObjectInDatabase()) {
    dbObjectFile = getFile();

    _Tt_string new_local_file;
    _Tt_string new_hostname;
    _Tt_string new_partition;
    _Tt_string new_file_network_path;
    dbResults = _tt_db_network_path(new_file,
	                            new_local_file,
	                            new_hostname,
		                    new_partition,
	                            new_file_network_path);

    // If we're not moving to the exact same file
    if (dbObjectFile != new_file_network_path) {
      new_objid = makeEquivalentObjectID(new_hostname, new_partition);

      if ((dbResults == TT_DB_OK) && new_objid.len()) {
	// If the objids are still the same, we only need to change the
	// object's file in the database...
	if (dbObjectID == new_objid) {
	  dbResults = dbObjectDatabase->setObjectFile(dbObjectID,
						      new_file_network_path);

	  if (dbResults == TT_DB_OK) {
	    dbResults = TT_DB_WRN_SAME_OBJECT_ID;
	  }
	}
	// Different objids and therefore different partitions or hosts
	else {
	  _Tt_db_object_ptr new_object = new _Tt_db_object;
	  dbResults = new_object->setObjectID(new_objid);

	  // The new object should not exist, yet...
	  if (dbResults == TT_DB_ERR_NO_SUCH_OBJECT) {
	    new_object->dbObjectHostname = new_hostname;
	    new_object->dbObjectFile = new_file_network_path;

	    // Refresh the current object's info
	    dbResults = internalRefresh();
	    if (dbResults == TT_DB_OK) {
	      (void)new_object->setAccess(dbObjectAccess);
	      (void)new_object->setProperties(dbObjectProperties);
	      (void)new_object->setType(dbObjectType);
	      dbResults = new_object->write();
	    }
	  }
	  // If the new object already exists, then there is something
	  // weird going on...
	  else if (dbResults == TT_DB_OK) {
	    dbResults = TT_DB_ERR_CORRUPT_DB;
	  }

	  if (dbResults == TT_DB_OK) {
	    // Remove current object from the DB and specify the new objid
	    // as the forward pointer.
	    dbResults = remove(new_objid);

	    if (dbResults == TT_DB_OK) {
	      setTtDBObjectDefaults();
	      dbResults = setObjectID(new_objid);
	    }
	  }
	}
      }
      else {
	if (dbResults == TT_DB_OK) {
	  dbResults = TT_DB_ERR_ILLEGAL_OBJECT;
	}
      }
    }
    else {
      dbResults = TT_DB_ERR_SAME_OBJECT;
    }
  }
  else {
    dbResults = TT_DB_ERR_NO_SUCH_OBJECT;
  }

  dbResults = processDBResults();
  return new_objid;
}
Пример #10
0
int main(int argc, char *argv[])
{
	if(argc<2)
	{
		std::cout << "Not enough parameters" << std::endl;
		return 1;
	}

	std::string cmd=argv[1];

	std::string backupfolder=getBackupfolderPath();

	if(backupfolder.empty())
	{
		std::cout << "Backupfolder not set" << std::endl;
		return 1;
	}
	
#ifndef _WIN32
	if(seteuid(0)!=0)
	{
		std::cout << "Cannot become root user" << std::endl;
		return 1;
	}
#endif

	if(cmd=="create")
	{
		if(argc<4)
		{
			std::cout << "Not enough parameters for create" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string name=handleFilename(argv[3]);

		std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;
		
		return create_subvolume(subvolume_folder)?0:1;
	}
	else if(cmd=="snapshot")
	{
		if(argc<5)
		{
			std::cout << "Not enough parameters for snapshot" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string src_name=handleFilename(argv[3]);
		std::string dst_name=handleFilename(argv[4]);

		std::string subvolume_src_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+src_name;
		std::string subvolume_dst_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+dst_name;

		return create_snapshot(subvolume_src_folder, subvolume_dst_folder)?0:1;
	}
	else if(cmd=="remove")
	{
		if(argc<4)
		{
			std::cout << "Not enough parameters for remove" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string name=handleFilename(argv[3]);

		std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;
		
		return remove_subvolume(subvolume_folder)?0:1;
	}
	else if(cmd=="test")
	{
		std::string clientdir=backupfolder+os_file_sepn()+"testA54hj5luZtlorr494";
		if(os_create_dir(clientdir))
		{
			
			if(!create_subvolume(clientdir+os_file_sepn()+"A") )
			{
				std::cout << "Creating test subvolume failed" << std::endl;
				os_remove_dir(clientdir);
				return 1;
			}
			
			bool suc=true;

			if(!create_snapshot(clientdir+os_file_sepn()+"A", clientdir+os_file_sepn()+"B") )
			{
				std::cout << "Creating test snapshot failed" << std::endl;
				suc=false;
			}
			
			if(suc)
			{			
				writestring("test", clientdir+os_file_sepn()+"A"+os_file_sepn()+"test");
				
				if(!os_create_hardlink(clientdir+os_file_sepn()+"B"+os_file_sepn()+"test", clientdir+os_file_sepn()+"A"+os_file_sepn()+"test", true, NULL))
				{
					std::cout << "Cross subvolume reflink failed" << std::endl;
					suc=false;
				}
			
				if(getFile(clientdir+os_file_sepn()+"B"+os_file_sepn()+"test")!="test")
				{
					std::cout << "Cannot read reflinked file" << std::endl;
					suc=false;
				}
			}

			if(!remove_subvolume(clientdir+os_file_sepn()+"A") )
			{
				std::cout << "Removing subvolume A failed" << std::endl;
				suc=false;
			}

			if(!remove_subvolume(clientdir+os_file_sepn()+"B") )
			{
				std::cout << "Removing subvolume B failed" << std::endl;
				suc=false;
			}

			if(!os_remove_dir(clientdir))
			{
				std::cout << "Removing test clientdir failed" << std::endl;
				return 1;
			}
			
			if(!suc)
			{
				return 1;
			}
		}
		else
		{
			std::cout << "Creating test clientdir \"" << clientdir << "\" failed" << std::endl;
			return 1;
		}
		return 0;
	}
	else if(cmd=="issubvolume")
	{
		if(argc<4)
		{
			std::cout << "Not enough parameters for issubvolume" << std::endl;
			return 1;
		}

		std::string clientname=handleFilename(argv[2]);
		std::string name=handleFilename(argv[3]);

		std::string subvolume_folder=backupfolder+os_file_sepn()+clientname+os_file_sepn()+name;
		
		return is_subvolume(subvolume_folder)?0:1;
	}
	else
	{
		std::cout << "Command not found" << std::endl;
		return 1;
	}
Пример #11
0
//Starts the server and listens for connections
void Server::start(){

	//check if directory exists
	//If it doesn't , try to create the directory

	char temp[1024];

	//Get address info purposes
	struct sockaddr_storage otherAddr, otherAddr2;		//Connectors address information
	socklen_t otherAddrLen, otherAddrLen2;
	int rv;
	int i;

	//Socket purposes
	int newfd;
	int newfd2;

	//port numbers
	unsigned short dataPort;

	//Handling child processes
	struct sigaction sa;

	//Char buffers
	char buffer[DATA_SIZE];

	//String vector
	vector<string> tokens;

	//extra string(s)
	string errMsg = INVCOM;


	//Copy the string into character array
	//since chdir() takes char * as argument
	strncpy( temp, rootDir.c_str() , sizeof(temp) );
	temp[ sizeof(temp) - 1 ] = 0;

	//Check if directory is valid
	//If no directory create one
	if( !validDir(temp) ){

		if( mkdir(temp, 0777) != 0 ){
			perror("mkdir");
			exit(1);
		}

	}

	//change directory
	//call chdir()
	if(chdir(temp) != 0){
		//If chdir fails
		perror("chdir");
		exit(1);
	}

	if ( !getPWD() ){
		cout << "Unable to get cwd" << endl;
		exit(1);
	}

	//We have now changed the program's pwd to root directory 
	//Now create a socket and bind to the control port and start listening
	//for connections

	cs = controlSock = createSocket( controlPort);
	if(verbose)
		cout << "Control socket created" << endl;

	ds = dataSock = createSocket("0");
	if(verbose)
		cout << "Data socket created" << endl;

	dataPort = getPort(dataSock);

	//Now we have successfully created the socket 
	//and bound it to the control port
	//Start listening for connections
	//Entering the listening loop

	if ( listen (controlSock , BACKLOG) != 0 ) {
		perror("listen");
		close(controlSock);
		exit(1);
	}

	if( listen(dataSock , BACKLOG) != 0 ){
		perror("listen");
		close(dataSock);
		exit(1);
	}

	//handle dead processes
	sa.sa_handler = sigchldHandler;		//read all dead processes
	sigemptyset( &sa.sa_mask );
	sa.sa_flags = SA_RESTART;
	if( sigaction( SIGCHLD, &sa , NULL ) == -1 ){
		perror("sigaction");
		exit(1);
	}

	//Handle user interrupts
	signal(SIGINT, userIntHandler);

	cout << "Waiting for connections ... " << endl;

	while(1){

		otherAddrLen = sizeof ( otherAddr) ;
		newfd = accept ( controlSock , (struct sockaddr *) &otherAddr , &otherAddrLen );
		cout << "Connection from " << getIPFromAddr(&otherAddr) << ":" << getPortFromAddr(&otherAddr) << endl;
		commsock = newfd;

		send(newfd, (unsigned short *)&dataPort, 2, 0);

		otherAddrLen2 = sizeof otherAddr2;
		newfd2 = accept(dataSock, (struct sockaddr *) &otherAddr2, &otherAddrLen2 );
		datacommsock = newfd2;
		cout << "Connection to data socket from client port " << getPortFromAddr(&otherAddr2) << endl;

		if( fork() == 0 ){
			//The code in this block is executed by the child process
			close(controlSock);  //Child doesn't require the control socket
			close(dataSock);

			if(verbose){
				cout << "Closing listener sockets" << endl;
				cout << "Child process created for communication with client" << endl;
			}

			if (dup2( newfd , 0 ) != 0 ){
				perror("dup2");
				exit(1);
			}

			do{
				
				if(fgets( buffer, DATA_SIZE, stdin ) == NULL){
					close(newfd);
					exit(1);
				}

				//Remove carriage return and new line characters
				for(rv = 0; rv < DATA_SIZE ; rv++){

					if(buffer[rv] == '\r'){
						buffer[rv] = 0;
						break;
					}

					if(buffer[rv] == '\n'){
						buffer[rv] = 0;
						break;
					}
				}
				
				//Read buffer and find what command it is
				//Call the corresponding method

				string s(buffer);		//convert the character array into string
				if(verbose){
					cout << "Received command " + s << endl;
				}

				istringstream iss(s);

				//copy the tokens into the string vector
				copy( istream_iterator<string>(iss),
				 istream_iterator<string>() ,
				 back_inserter<vector<string> >(tokens) );


				//Copied the tokens into tokens
				rv = tokens.size();
				if(rv > 0){
					//If there is atleast one word
					if(tokens[0].compare("ls") == 0){
						//The client requested a file listing
						ls(s, newfd2);
					}
					else if(tokens[0].compare("quit") == 0){
						//The client closed the connection
						break;
					}
					else if(tokens[0].compare("cd") == 0){
						//The client requested a directory change
						if(rv == 2){
							cd(tokens[1], newfd2);
						}
						else{
							sendMessage( errMsg.c_str() , errMsg.length() , ERROR, NF, dataSock );
						}
					}
					else if( tokens[0].compare("pwd") == 0 ){
						//Client requested a pwd
						PWD(newfd2);
					}
					else if(tokens[0].compare("get") == 0){
						string temp="";
						for(i=1; i < rv;i++){
							temp = temp + tokens[i] + " ";
						}
						temp = temp.substr(0, temp.length()-1 );
						getFile(temp, newfd2);
					}
					else if(tokens[0].compare("put") == 0){
						string temp="";
						for(i=1; i < rv;i++){
							temp = temp + tokens[i] + " ";
						}
						temp = temp.substr(0, temp.length()-1 );
						putFile(temp, newfd2);
					}
					else{
						sendMessage( errMsg.c_str() , errMsg.length() , ERROR, NF, newfd2 );
					}
				}

				tokens.clear();		//clear the tokens

			}while (1);

			//The client closed the connection
			//So, close the socket and quit the child process
			close(newfd);		
			close(newfd2);	
			cout << "Connection closed" << endl;
			exit(1);
		}
		close(newfd);

	}

	close(controlSock);
	

}
Пример #12
0
int main(int argc, char **argv) {
	int go = 1;
	char *param;
	char *command;
	int port = PORT;
	int sSock, lSock;
	pthread_t sThread;
	char input[USERIO];
	char rBuffer[BUFSIZE];
	unsigned short int lport;
	char *hostname = "localhost";
	struct sockaddr_in server_addr;
	struct addrinfo hints, *result;
	
    assert(pthread_mutex_init(&m, NULL) == 0);
	assert(pthread_cond_init(&in_process_condition, NULL) == 0);
	assert(pthread_cond_init(&all_complete_condition, NULL) == 0);

	if (argc == 4) {
		port = strToInt(argv[3]);
		if (port == -1) {
			printf("Server Error: Invalid port number. Switching back to default (%d).\n", PORT);
			port = PORT;
		}
	}

	if (argc >= 3) hostname = argv[2];

	if (argc >= 2) {
		path = argv[1];

		sSock = socket(PF_INET, SOCK_STREAM, 0);

		memset(&hints, 0, sizeof(hints));
		hints.ai_socktype = SOCK_STREAM;
		hints.ai_family = AF_INET;
		getaddrinfo(hostname, NULL, &hints, &result);

		server_addr.sin_family = AF_INET;
		server_addr.sin_port = htons(port);
		server_addr.sin_addr = ((struct sockaddr_in *) (result->ai_addr))->sin_addr;

		assert(connect(sSock, (struct sockaddr*) &server_addr, sizeof(server_addr)) != -1);
		recv(sSock, rBuffer, BUFSIZE, 0);
		printf("%s\n", rBuffer);
		bzero(rBuffer, BUFSIZE);
		
		listDirectory(sSock, path);

		lport = getListeningPort(sSock);
		assert(pthread_create(&sThread, NULL, serverThread, &lport) == 0);

		while (go) {
			if (fgets(input, USERIO, stdin) != NULL) {
				if (isEmpty(input)) {
					printf("Error: Command must have at least one character.\n");
				} else if (input[strlen(input) - 1] != '\n') {
					printf("Error: Line too long.\n");
				} else {
					input[strlen(input) - 1] = '\0';

					command = trim(strtok(input, " \t\v\f\r"));

					if (strcmp(command, "DIR") == 0) {
						if (strtok(NULL, " \t\v\f\r") != '\0') {
							printf("Error: Invalid command. Usage: DIR\n");
						} else {
							getFileList(sSock);
						}

					} else if (strcmp(command, "GET") == 0) {
						param = trim(strtok(NULL, " \t\v\f\r"));
						if (param == '\0' || strtok(NULL, " \t\v\f\r") != '\0') {
							printf("Error: Invalid command. Usage: GET <filename>\n");
						} else {
							getFile(sSock, path, param);
						}

					/* Command: QUIT - Close connection */
					} else if (strcmp(command, "QUIT") == 0) {
						if (strtok(NULL, " \t\v\f\r") != '\0') {
							printf("Error: Invalid command. Usage: QUIT\n");
						} else {
							send(sSock, "QUT", CMD, 0);
							recv(sSock, rBuffer, CMD, 0);
							if (strcmp(rBuffer, "TRM") == 0) go = 0;
						}

					} else {
						printf(
							"Error: Invalid command. Supported: DIR, GET and QUIT.\n");
					}
				}
			}
		}

		freeaddrinfo(result);
		done = 1;

		assert(pthread_mutex_lock(&m) == 0);
		assert(pthread_cond_wait(&all_complete_condition, &m) == 0);
		assert(pthread_mutex_unlock(&m) == 0);

		pthread_mutex_destroy(&m);
		pthread_cond_destroy(&in_process_condition);
		pthread_cond_destroy(&all_complete_condition);

	} else {
		printf(	"Error: Wrong number of arguments. Usage: file_client <dir> [hostname] [port].\n");
	}

	return 0;
}
String SourceFileTreeViewItem::getDisplayName() const
{
    return getFile().getFileName();
}
Пример #14
0
/*
 Insert a new tuple into the table described by pTable
 @param Table 	*pTable: describe the table
 @param Record 	*rec: record to insert 
 */
bool BufferManager::insertRec(const Table *pTable, Record* rec){
	FileInf *file;
	file = getFile(pTable);
	// TODO: Update FileInf
	UUID insert_uuid = pTable->recordNum + 1;				// Pre-condition: catalog has already update the record number

	//insert(file, insert_uuid, rec);

	/* Insert a record */
	if ( file->Block_Num == 0 ){
		file->Block_Num = 1;
		file->firstBlock = file->lastBlock = getBlock(file, 1);
		Bufferlist[file->firstBlock].next = -1;
		Bufferlist[file->firstBlock].lock();
	} 
	else { 															
		int BlockOffset = static_cast<int>(ceil((float)insert_uuid / file->recordPerBlock));
		if ( BlockOffset > file->Block_Num ){						// In case of block overflow
			file->Block_Num++;
			int block = getBlock(file, BlockOffset);
			Bufferlist[file->lastBlock].next = block;				// add a block to the table
			Bufferlist[file->lastBlock].unlock();
			Bufferlist[block].next = -1;
			Bufferlist[block].lock();
			file->lastBlock = block;
		}
	}
	

	long recordOffset = insert_uuid - file->recordPerBlock * (file->Block_Num - 1);		// Insert in the last block
	long byteOffset = file->recordLen * (recordOffset - 1);
	for (unsigned int i = 0; i < pTable->attributes.size(); i++){
		switch ( pTable->attributes.at(i).dataType ){
			case Int: {
				memcpy(&Bufferlist[file->lastBlock].token[byteOffset], rec->data.at(i), sizeof(int));
				byteOffset += sizeof(int);
				delete static_cast<int *>(rec->data.at(i));
				break;
			}
			case Float: {
				memcpy(&Bufferlist[file->lastBlock].token[byteOffset], rec->data.at(i),  sizeof(float));
				byteOffset += sizeof(float);
				delete static_cast<float *>(rec->data.at(i));
				break;
			}
			case String: {
				memcpy(&Bufferlist[file->lastBlock].token[byteOffset], static_cast<string *>(rec->data.at(i))->c_str(), strlen((char *)rec->data.at(i)) + 1);
				byteOffset += strlen(static_cast<string *>(rec->data.at(i))->c_str());
				delete static_cast<string *>(rec->data.at(i));
				break;
			}
			case Uuid: {
				memcpy(&Bufferlist[file->lastBlock].token[byteOffset], rec->data.at(i), sizeof(UUID));	
				byteOffset += sizeof(UUID);
				delete static_cast<UUID *>(rec->data.at(i));
				break;
			}
			
		} 
		
	}
	rec->data.clear();
	file->recordNum++;
	Bufferlist[file->lastBlock].is_Dirty = true;
	delete rec;
	return true;
}
Пример #15
0
int l_File_getFullExtension(lua_State* L)
{
	File& file = getFile(L, 1);
	lua_pushstring(L, file.getFullExtension().c_str());
	return 1;
}
Пример #16
0
dibSHP::dibSHP(QWidget *parent) :  QDialog(parent)
{
    QVBoxLayout *mainLayout = new QVBoxLayout;

    QPushButton *filebut = new QPushButton(tr("File..."));
    fileedit = new QLineEdit();
    QHBoxLayout *lofile = new QHBoxLayout;
    lofile->addWidget(filebut);
    lofile->addWidget(fileedit);
    lofile->setSizeConstraint(QLayout::SetFixedSize);//ni caso
    mainLayout->addLayout(lofile);

    QLabel *formatlabel = new QLabel(tr("File type:"));
    formattype = new QLabel(tr("Unknoun"));
    QHBoxLayout *loformat = new QHBoxLayout;
    loformat->addWidget(formatlabel);
    loformat->addWidget(formattype);
    loformat->addStretch();
    mainLayout->addLayout(loformat);

    QGroupBox *laybox = new QGroupBox(tr("Layer"));
    radiolay1 = new QRadioButton(tr("Current"));
    QRadioButton *radiolay2 = new QRadioButton(tr("From data:"));
    layerdata = new QComboBox();
    radiolay1->setChecked(true);
    QHBoxLayout *laylayout = new QHBoxLayout;
    laylayout->addWidget(radiolay1);
    laylayout->addWidget(radiolay2);
    laylayout->addWidget(layerdata);
    laylayout->addStretch(0);
    laybox->setLayout(laylayout);
    mainLayout->addWidget(laybox);

    QGroupBox *colbox = new QGroupBox(tr("Color"));
    radiocol1 = new QRadioButton(tr("Current"));
    QRadioButton *radiocol2 = new QRadioButton(tr("From data:"));
    colordata = new QComboBox();
    radiocol1->setChecked(true);
    QHBoxLayout *collayout = new QHBoxLayout;
    collayout->addWidget(radiocol1);
    collayout->addWidget(radiocol2);
    collayout->addWidget(colordata);
    collayout->addStretch(1);
    colbox->setLayout(collayout);
    mainLayout->addWidget(colbox);

    QGroupBox *ltypebox = new QGroupBox(tr("Line type"));
    radioltype1 = new QRadioButton(tr("Current"));
    QRadioButton *radioltype2 = new QRadioButton(tr("From data:"));
    ltypedata = new QComboBox();
    radioltype1->setChecked(true);
    QHBoxLayout *ltypelayout = new QHBoxLayout;
    ltypelayout->addWidget(radioltype1);
    ltypelayout->addWidget(radioltype2);
    ltypelayout->addWidget(ltypedata);
    ltypelayout->addStretch(1);
    ltypebox->setLayout(ltypelayout);
    mainLayout->addWidget(ltypebox);

    QGroupBox *lwidthbox = new QGroupBox(tr("Width"));
    radiolwidth1 = new QRadioButton(tr("Current"));
    QRadioButton *radiolwidth2 = new QRadioButton(tr("From data:"));
    lwidthdata = new QComboBox();
    radiolwidth1->setChecked(true);
    QHBoxLayout *lwidthlayout = new QHBoxLayout;
    lwidthlayout->addWidget(radiolwidth1);
    lwidthlayout->addWidget(radiolwidth2);
    lwidthlayout->addWidget(lwidthdata);
    lwidthlayout->addStretch(1);
    lwidthbox->setLayout(lwidthlayout);
    mainLayout->addWidget(lwidthbox);

    pointbox = new QGroupBox(tr("Point"));
    radiopoint1 = new QRadioButton(tr("as Point"));
    QRadioButton *radiopoint2 = new QRadioButton(tr("as Label:"));
    pointdata = new QComboBox();
    radiopoint1->setChecked(true);
    QHBoxLayout *pointlayout = new QHBoxLayout;
    pointlayout->addWidget(radiopoint1);
    pointlayout->addWidget(radiopoint2);
    pointlayout->addWidget(pointdata);
    pointlayout->addStretch(1);
    pointbox->setLayout(pointlayout);
    mainLayout->addWidget(pointbox);

    QHBoxLayout *loaccept = new QHBoxLayout;
    QPushButton *acceptbut = new QPushButton(tr("Accept"));
    QPushButton *cancelbut = new QPushButton(tr("Cancel"));
    loaccept->addStretch();
    loaccept->addWidget(acceptbut);
    loaccept->addWidget(cancelbut);
    loaccept->addStretch();
    mainLayout->addLayout(loaccept);

    setLayout(mainLayout);
    readSettings();
    updateFile();

    connect(cancelbut, SIGNAL(clicked()), this, SLOT(reject()));
    connect(acceptbut, SIGNAL(clicked()), this, SLOT(checkAccept()));
    connect(filebut, SIGNAL(clicked()), this, SLOT(getFile()));
    connect(fileedit, SIGNAL(editingFinished()), this, SLOT(updateFile()));
}
Пример #17
0
int l_File_isRegularFile(lua_State* L)
{
	File& file = getFile(L, 1);
	lua_pushboolean(L, file.is<RegularFile>() && file.isValid());
	return 1;
}
Пример #18
0
const String Timer::getFile(const String &name)
{
  return getFile(theInstance().currentTest, name);
}
Пример #19
0
uint32_t PackReader::getFileLength(const std::string & path){
    const File & file = getFile(path);
    return file.length;
}
void RecentlyOpenedFilesList::removeNonExistentFiles()
{
    for (int i = getNumFiles(); --i >= 0;)
        if (! getFile(i).exists())
            files.remove (i);
}
Пример #21
0
char *FilelistGetFileName(gp_file_t *pFile, int index)
{
	return getFile(pFile, index);
}
Пример #22
0
int main(int argc, char **argv)
{	

	const char *name;
	int sock = -1;
	char fin[512], fout[512];
	char cmd[512], reply[512];
	int params = -1;
	
	say ("\n%s (%s): started\n", TITLE, VERSION);
	
	if( argc == 1){
		say ("No service name passed, using default: %s\n", NAME);
		sock = initializeClient(NAME);
	} else{
		name = argv[1];
		say ("Connecting to: %s\n", name);
		sock = initializeClient(name);
	}
	usage();
	int i = 0;
	while(i<2){
		say(">>");
		cmd[0] = '\n';
		fin[0] = '\n';
		fout[0] = '\n';
		params = -1;
		
		
  		fgets(cmd, 511, stdin);

//		This is for quick testing with a couple of commands
// 		if(i==0)
// 			strcpy(cmd, "get asd asdsf\n");
// 		else if(i==1)
// 			strcpy(cmd, "put a.txt ss.txt\n");
// 		i++;
		
		
		
		if (strncmp(cmd, "get", 3) == 0){
			params = sscanf(cmd,"get %s %s", fin, fout);
			
			if(params !=2 ){
				sprintf(reply, "FAIL: invalid command (%s)\n", cmd);
				warn(reply);
				usage();
				continue;
			}
			
			if( strcmp(fin, fout) == 0){
				warn("Since both applications write to the same folder (local case) the names should be different.\n");
				continue;
			}
			
		  	getFile(sock, s_ad, s_hid, fin, fout);
			
		}
		else if (strncmp(cmd, "put", 3) == 0){
 			params = sscanf(cmd,"put %s %s", fin, fout);


			if(params !=2 ){
				sprintf(reply, "FAIL: invalid command (%s)\n", cmd);
				warn(reply);
				usage();
				continue;
			}

			
			if(strcmp(fin, fout) == 0){
				warn("Since both applications write to the same folder (local case) the names should be different.\n");
				continue;
			}
			if(!file_exists(fin)){
				warn("Source file: %s doesn't exist\n", fin);
				continue;
			}
				
			
			putFile(sock, my_ad, my_hid, fin, fout);
			
		}
		else{
			sprintf(reply, "FAIL: invalid command (%s)\n", cmd);
			warn(reply);
			usage();
		}
		
	}	
	return 1;
}
Пример #23
0
bool Project::Item::isImageFile() const     { return isFile() && ImageFileFormat::findImageFormatForFileExtension (getFile()) != nullptr; }
Пример #24
0
bool Project::Item::isImageFile() const     { return isFile() && getFile().hasFileExtension ("png;jpg;jpeg;gif;drawable"); }
Пример #25
0
ReturnStatus
FileMetaDAO::getDir2(const std::string &path,
                     std::list<EDEntry> *pEntryList)
{
    assert(pEntryList);

    Channel* pDataChannel = ChannelManager::getInstance()->Mapping(m_BucketId);
	NameSpace *DataNS = pDataChannel->m_DataNS;

    int rt = 0;
    int error = 0;
    std::string entryName;
    std::string npath;
	Args st;

    rt = DataNS->OpenDir(path.c_str(), &st);
    if (false == st.valid) {
        error = errno;

        ERROR_LOG("path %s, opendir() error, %s.",
                  path.c_str(), strerror(errno));

        if (ENOTDIR == error) {
            return ReturnStatus(MU_FAILED, NOT_DIRECTORY);

        } else if (ENOENT == error) {
            return checkPrefix(path);
        }
    }

    FileMeta meta;
    ReturnStatus rs;
    Dirent dirent;

    while(DataNS->ReadDirNext(&st, &dirent)){
        entryName = dirent.filetype;
        npath = path + PATH_SEPARATOR_STRING + entryName;

        // omit "." and ".."
        // omit user info file in user root dir
        if (entryName == DENTRY_CURRENT_DIR
            || entryName == DENTRY_PARENT_DIR
            || entryName == USER_INFO_FILE_NAME) {
            continue;
        }

        EDEntry ent;
        ent.m_Name = entryName;

        if (MU_DIRECTORY == dirent.filetype) {
            ent.m_Type = MU_DIRECTORY;

            rs = statDir(npath, &meta);

            if (!rs.success()) {
                ERROR_LOG("path %s, statDir() error", npath.c_str());
                return rs;
            }

            ent.m_Mode = meta.m_Attr.m_Mode;
            ent.m_CTime = meta.m_Attr.m_CTime;
            ent.m_MTime = meta.m_Attr.m_MTime;
            ent.m_Size = meta.m_Attr.m_Size;

        } else {
            // clear data of last entry
            meta.m_BlockList.clear();

            rs = getFile(npath, &meta);

            if (!rs.success()) {
                ERROR_LOG("path %s, getFile() error", npath.c_str());
                return rs;
            }

            ent.m_Mode = meta.m_Attr.m_Mode;
            ent.m_CTime = meta.m_Attr.m_CTime;
            ent.m_MTime = meta.m_Attr.m_MTime;
            ent.m_Size = meta.m_Attr.m_Size;
            ent.m_Version = meta.m_Attr.m_Version;
            ent.m_Type = meta.m_Attr.m_Type;

            ent.m_BlockList = meta.m_BlockList;
        }

        pEntryList->push_back(ent);
    }


    return ReturnStatus(MU_SUCCESS);
}
Пример #26
0
int l_File_getParentPath(lua_State* L)
{
	File& file = getFile(L, 1);
	lua_pushstring(L, file.getParentPath().c_str());
	return 1;
}
Пример #27
0
    Component* createEditor() override
    {
        ScopedPointer<JucerDocument> jucerDoc (JucerDocument::createForCppFile (getProject(), getFile()));

        if (jucerDoc != nullptr)
            return new JucerDocumentEditor (jucerDoc.release());

        return SourceCodeDocument::createEditor();
    }
Пример #28
0
int l_File_getShortStem(lua_State* L)
{
	File& file = getFile(L, 1);
	lua_pushstring(L, file.getShortStem().c_str());
	return 1;
}
Пример #29
0
 std::string TestAssertionFailureException::toString() const {
     std::ostringstream os;
     os << getMessage() << " @" << getFile() << ":" << getLine();
     return os.str();
 }
Пример #30
0
QString StackFrameItem::getFileName()
{
  return getFullName().isEmpty() ? getFile() : getFullName();
}