Ejemplo n.º 1
0
bool AL_CALLTYPE alFileStd_SetSize(void* _this, uint64 nSize)
{
	alFileStdi* _data = (alFileStdi*)_this;
	return (0 == _chsize(_fileno(_data->handle), (long)nSize));
}
Ejemplo n.º 2
0
int padding_decoder(char *file_name, unsigned long long content_length) {

  int fp_in;
  unsigned long long f_size;

#ifdef _MSC_VER
  struct __stat64 file_stats;
#else  
  struct stat64 file_stats;
#endif

  char file_name_in[256] = "";
  char file_name_out[256] = "";
  char *ptr;
  int retval;

  strcpy(file_name_in, file_name);  
  ptr = strstr(file_name_in, PAD_SUFFIX);

  memcpy(file_name_out, file_name_in, (ptr - file_name_in));

#ifdef _MSC_VER
  fp_in = open((const char*)file_name_in, _O_RDWR | _O_CREAT | _O_BINARY, _S_IREAD | _S_IWRITE);
#else
  fp_in = open64(file_name_in, O_RDWR | O_CREAT, S_IRWXU);
#endif

  if(fp_in == -1) {
    printf("open error: %s\n", file_name_in);
    return -1;
  }

#ifdef _MSC_VER
  _fstat64(fp_in, &file_stats);
#else
  fstat64(fp_in, &file_stats);
#endif

  f_size = file_stats.st_size;

  if(f_size > content_length) {
#ifdef _MSC_VER
    retval = _chsize(fp_in, (long)content_length); /* TODO: 64 bits, how ??? */
#else
	  retval = ftruncate64(fp_in, content_length);
#endif

	  if(retval != 0) {
		  printf("Problem in padding decoding.\n" );
		  close(fp_in);
		  return -1;
	  }
  }

  close(fp_in);
	 
	if(rename(file_name_in, file_name_out) < 0) {

		if(errno == EEXIST) {
			retval = remove(file_name_out);
		
			if(retval == -1) {    
				printf("errno: %i\n", errno);
				fflush(stdout);
				close(fp_in);
				return -1;
			}
		
			if(rename(file_name_in, file_name_out) < 0) {
				printf("rename() error1: %s\n", file_name_in);
				fflush(stdout);
				close(fp_in);
				return -1;
			}
		}
		else {
			printf("rename() error2: %s\n", file_name_in);
			fflush(stdout);
			close(fp_in);
			return -1;
		}
	}

  return 0;
}
Ejemplo n.º 3
0
//-----------------------------------------------------------------------------
// Purpose: 
// Input  : pszFilename - 
//			bIndexOnly - 
// Output : int
//-----------------------------------------------------------------------------
int CPrefabLibraryRMF::Save(LPCTSTR pszFilename, BOOL bIndexOnly)
{
	// temp storage
	static char szFile[MAX_PATH];

	// if only saving index, special code -
	if(bIndexOnly && m_file.is_open())
	{
		// close file, reopen in binary write
		m_file.close();
		if(Prefabs.GetCount())
		{
			// change size of file first
			int iHandle = _open(m_strOpenFileName, _O_BINARY | _O_WRONLY);
			_chsize(iHandle, m_dwDirOffset);
			_close(iHandle);
		}

		fstream file(m_strOpenFileName, ios::binary | ios::out);

		// write string header
		file << pLibHeader;
		// write binary header (in case notes have changed)
		PrefabLibraryHeader plh;
		plh.dwNumEntries = Prefabs.GetCount();
		plh.fVersion = fLibVersion;
		plh.dwDirOffset = m_dwDirOffset;
		strcpy(plh.szNotes, szNotes);
		file.write((char*)&plh, sizeof plh);

		// recreate a directory and write it
		PrefabHeader *ph = new PrefabHeader[Prefabs.GetCount()];
		int iCur = 0;

		POSITION p = Prefabs.GetHeadPosition();
		while(p)
		{
			CPrefab *pPrefab = Prefabs.GetNext(p);

			// setup this dir entry
			ph[iCur].dwOffset = pPrefab->dwFileOffset;
			ph[iCur].dwSize = pPrefab->dwFileSize;
			strcpy(ph[iCur].szName, pPrefab->GetName());
			strcpy(ph[iCur].szNotes, pPrefab->GetNotes());
			ph[iCur].iType = pPrefab->GetType();

			++iCur;	// increase current directory entry
		}

		// write directory
		file.seekp(m_dwDirOffset);
		file.write((char*)ph, sizeof(*ph) * Prefabs.GetCount());
		file.close();

		// re-open
		m_file.open(m_strOpenFileName, ios::in | ios::binary | ios::nocreate);
		return 1;
	}

	if(pszFilename == NULL)
	{
		pszFilename = szFile;

		if(m_strOpenFileName.IsEmpty())
		{
			char szNewFilename[MAX_PATH];
			CWorldcraft *pApp = (CWorldcraft*) AfxGetApp();
			pApp->GetDirectory(DIR_PREFABS, szNewFilename);

			sprintf(szNewFilename + strlen(szNewFilename), "\\%s.ol", m_szName);

			// make a name
			m_strOpenFileName = szNewFilename;
		}

		strcpy(szFile, m_strOpenFileName);
	}
	else
	{
		strcpy(szFile, pszFilename);
		SetNameFromFilename(pszFilename);
	}

	// open temp file to save to.. then delete & rename old one.
	CString strTempFileName = "Temporary Prefab Library.$$$";
	fstream file;
	file.open(strTempFileName, ios::binary | ios::out);

	// write string header
	file << pLibHeader;

	// write binary header
	// save current position so we can seek back and rewrite it
	DWORD dwBinaryHeaderOffset = file.tellp();
	PrefabLibraryHeader plh;
	plh.dwNumEntries = Prefabs.GetCount();
	plh.fVersion = fLibVersion;
	strcpy(plh.szNotes, szNotes);
	file.write((char*)&plh, sizeof plh);

	// allocate memory for directory
	PrefabHeader *ph = new PrefabHeader[plh.dwNumEntries];
	int iCur = 0;

	char *pCopyBuf = new char[64000];

	// write each prefab
	POSITION p = Prefabs.GetHeadPosition();
	while (p)
	{
		CPrefabRMF *pPrefab = (CPrefabRMF *)Prefabs.GetNext(p);

		// setup this dir entry
		ph[iCur].dwOffset = file.tellp();
		strcpy(ph[iCur].szName, pPrefab->GetName());
		strcpy(ph[iCur].szNotes, pPrefab->GetNotes());
		ph[iCur].iType = pPrefab->GetType();

		if(pPrefab->IsLoaded())
		{
			// it's loaded - save in native method
			pPrefab->Save(file, CPrefab::lsUpdateFilePos);
		}
		else
		{
			// it's not loaded - save with quick method by copying
			// bytes directly from the existing file
			ASSERT(m_file.is_open());
			m_file.seekg(pPrefab->dwFileOffset);
			DWORD dwToRead = 64000, dwCopied = 0;
			while(dwToRead == 64000)
			{
				if(dwCopied + dwToRead > pPrefab->dwFileSize)
					dwToRead = pPrefab->dwFileSize - dwCopied;
				m_file.read(pCopyBuf, dwToRead);
				file.write(pCopyBuf, dwToRead);
				dwCopied += dwToRead;
			}
		}

		// set offset info HERE because we might use it above
		pPrefab->dwFileOffset = ph[iCur].dwOffset;

		// set size info
		ph[iCur].dwSize = pPrefab->dwFileSize = 
			file.tellp() - ph[iCur].dwOffset;

		++iCur;	// increase current directory entry
	}

	// delete copy buf
	delete[] pCopyBuf;

	// rewrite binary header
	plh.dwDirOffset = m_dwDirOffset = file.tellp();
	file.seekp(dwBinaryHeaderOffset);
	file.write((char*)&plh, sizeof(plh));
	file.seekp(0, ios::end);

	// write directory
	file.write((char*)ph, sizeof(*ph) * plh.dwNumEntries);
	file.close();	// close temp file
	
	// delete original and rename
	m_file.close();	// might already be open.. might not.
	remove(m_strOpenFileName);

	m_strOpenFileName = szFile;
	int iRvl = rename(strTempFileName, m_strOpenFileName);
	
	// reopen original
	m_file.open(m_strOpenFileName, ios::in | ios::binary | ios::nocreate);

	return 1;
}
Ejemplo n.º 4
0
CFile::ERRCODE CWinFile::SetSize(FILESIZE iSize)
{
  ASSERT(IsValid());
  int iRes = _chsize(m_hFile, (long) iSize);
  return (iRes < 0) ? (ERRCODE) errno : 0;
}
Ejemplo n.º 5
0
int ftruncate(int file_Fd,off_t file_Size)
{
	return _chsize(file_Fd,file_Size);
}
Ejemplo n.º 6
0
    void acquirePathLock(bool doingRepair) {
        string name = ( boost::filesystem::path( dbpath ) / "mongod.lock" ).native_file_string();

        bool oldFile = false;

        if ( boost::filesystem::exists( name ) && boost::filesystem::file_size( name ) > 0 ) {
            oldFile = true;
        }

#ifdef _WIN32
        lockFileHandle = CreateFileA( name.c_str(), GENERIC_READ | GENERIC_WRITE,
            0 /* do not allow anyone else access */, NULL, 
            OPEN_ALWAYS /* success if fh can open */, 0, NULL );

        if (lockFileHandle == INVALID_HANDLE_VALUE) {
            DWORD code = GetLastError();
            char *msg;
            FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                NULL, code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                (LPSTR)&msg, 0, NULL);
            string m = msg;
            str::stripTrailing(m, "\r\n");
            uasserted( 13627 , str::stream() << "Unable to create/open lock file: " << name << ' ' << m << ". Is a mongod instance already running?" );
        }
        lockFile = _open_osfhandle((intptr_t)lockFileHandle, 0);
#else
        lockFile = open( name.c_str(), O_RDWR | O_CREAT , S_IRWXU | S_IRWXG | S_IRWXO );
        if( lockFile <= 0 ) {
            uasserted( 10309 , str::stream() << "Unable to create/open lock file: " << name << ' ' << errnoWithDescription() << " Is a mongod instance already running?" );
        }
        if (flock( lockFile, LOCK_EX | LOCK_NB ) != 0) {
            close ( lockFile );
            lockFile = 0;
            uassert( 10310 ,  "Unable to lock file: " + name + ". Is a mongod instance already running?",  0 );
        }
#endif

        if ( oldFile ) {
            // we check this here because we want to see if we can get the lock
            // if we can't, then its probably just another mongod running
            
            string errmsg;
            if (cmdLine.dur) {
                if (!dur::haveJournalFiles()) {
                    
                    vector<string> dbnames;
                    getDatabaseNames( dbnames );
                    
                    if ( dbnames.size() == 0 ) {
                        // this means that mongod crashed
                        // between initial startup and when journaling was initialized
                        // it is safe to continue
                    }
                    else {
                        errmsg = str::stream()
                            << "************** \n"
                            << "old lock file: " << name << ".  probably means unclean shutdown,\n"
                            << "but there are no journal files to recover.\n"
                            << "this is likely human error or filesystem corruption.\n"
                            << "found " << dbnames.size() << " dbs.\n"
                            << "see: http://dochub.mongodb.org/core/repair for more information\n"
                            << "*************";
                    }


                }
            }
            else {
                if (!dur::haveJournalFiles() && !doingRepair) {
                    errmsg = str::stream()
                             << "************** \n"
                             << "Unclean shutdown detected.\n"
                             << "Please visit http://dochub.mongodb.org/core/repair for recovery instructions.\n"
                             << "*************";
                }
            }

            if (!errmsg.empty()) {
                cout << errmsg << endl;
#ifdef _WIN32
                CloseHandle( lockFileHandle );
#else
                close ( lockFile );
#endif
                lockFile = 0;
                uassert( 12596 , "old lock file" , 0 );
            }
        }

        // Not related to lock file, but this is where we handle unclean shutdown
        if( !cmdLine.dur && dur::haveJournalFiles() ) {
            cout << "**************" << endl;
            cout << "Error: journal files are present in journal directory, yet starting without journaling enabled." << endl;
            cout << "It is recommended that you start with journaling enabled so that recovery may occur." << endl;
            cout << "**************" << endl;
            uasserted(13597, "can't start without --journal enabled when journal/ files are present");
        }

#ifdef _WIN32
        uassert( 13625, "Unable to truncate lock file", _chsize(lockFile, 0) == 0);
        writePid( lockFile );
        _commit( lockFile );
#else
        uassert( 13342, "Unable to truncate lock file", ftruncate(lockFile, 0) == 0);
        writePid( lockFile );
        fsync( lockFile );
        flushMyDirectory(name);
#endif
    }
Ejemplo n.º 7
0
void fs__ftruncate(uv_fs_t* req, uv_file file, off_t offset) {
  int result = _chsize(file, offset);
  SET_REQ_RESULT(req, result);
}
Ejemplo n.º 8
0
void dialogEditor_dataitem::OnSave()
{
	int fhOutput = -1;
	CString sError;
	int iLoop = 0;
	int iSub = 0;
	unsigned char cTemp;
	LPSTRUCT_LIVEBITITEM lpDataItem = NULL;
	unsigned long* lpOffset = NULL;
	POSITION pos = NULL;

	SaveChanges();
	BrowseForFile(&sError,"Select a filename for the Data Item Data File",OFN_OVERWRITEPROMPT);
	if((fhOutput = _open(sError,_O_BINARY | _O_CREAT | _O_WRONLY,_S_IWRITE)) == -1)
		return;
	if((_chsize(fhOutput,0)) == -1)
		return;

	// Live Data File Format
	// 1 bytes [Version Length]
	// x bytes [Version]
	// 1 bytes [Version Checksum]
	// [..]
	//		1 bytes [Byte]
	//		1 bytes [Bit]
	//		1 bytes [Name Length]
	//		x bytes [Name]
	//		4 bytes [Address High]
	//		4 bytes [Address Low]
	//		1 bytes [Type]
	//		2 bytes [Operand Addition]
	//		2 bytes [Operand Subtract]
	//		2 bytes [Operand Multiplier]
	//		2 bytes [Operand Divisor]
	//		2 bytes [Decimals]
	//		1 bytes [Unit Length]
	//		x bytes [Unit]
	//		2 bytes [Description Length]
	//		x bytes [Description]
	//		1 bytes [Checksum]
	// [..]

	cTemp = (char)sVersion.GetLength();
	_write(fhOutput,&cTemp,1);
	_write(fhOutput,(LPCTSTR)sVersion,cTemp);
	cTemp += GenerateChecksum(sVersion,sVersion.GetLength());
	_write(fhOutput,&cTemp,1);

	pos = listDataItem.GetHeadPosition();
	while(pos != NULL)
	{
		lpDataItem = (LPSTRUCT_LIVEBITITEM)listDataItem.GetNext(pos);
		_write(fhOutput,&lpDataItem->cByte,1);
		_write(fhOutput,&lpDataItem->cBit,1);
		_write(fhOutput,&lpDataItem->cLength_name,1);
		_write(fhOutput,lpDataItem->szName,lpDataItem->cLength_name);
		_write(fhOutput,&lpDataItem->ulAddress_high,4);
		_write(fhOutput,&lpDataItem->ulAddress_low,4);
		_write(fhOutput,&lpDataItem->cType,1);
		_write(fhOutput,&lpDataItem->usOperand_addition,2);
		_write(fhOutput,&lpDataItem->usOperand_subtract,2);
		_write(fhOutput,&lpDataItem->usOperand_multiplier,2);
		_write(fhOutput,&lpDataItem->usOperand_divisor,2);
		_write(fhOutput,&lpDataItem->usDecimals,2);
		_write(fhOutput,&lpDataItem->cLength_unit,1);
		_write(fhOutput,lpDataItem->szUnit,lpDataItem->cLength_unit);
		_write(fhOutput,&lpDataItem->usLength_description,2);
		_write(fhOutput,lpDataItem->szDescription,lpDataItem->usLength_description);

		cTemp = GenerateChecksum(lpDataItem);
		_write(fhOutput,&cTemp,1);
	}
}
Ejemplo n.º 9
0
bool AutoLockFile::truncateFile(size_t Length) {
  return _chsize(FileDescriptor, Length) == 0;
}
Ejemplo n.º 10
0
int
ftruncate(int fd, off_t length)
{
	return _chsize(fd, length);
}
Ejemplo n.º 11
0
/* Format an entire track.  The new track to be formatted must be after any existing tracks on
 * the disk.
 *
 * This routine should be enhanced to re-format an existing track to the same format (this
 * does not involve changing the disk image size.)
 *
 * Any existing data on the disk image will be destroyed when Track 0, Head 0 is formatted.
 * At that time, the IMD file is truncated.  So for the trackWrite to be used to sucessfully
 * format a disk image, then format program must format tracks starting with Cyl 0, Head 0,
 * and proceed sequentially through all tracks/heads on the disk.
 *
 * Format programs that are known to work include:
 * Cromemco CDOS "INIT.COM"
 * ADC Super-Six (CP/M-80) "FMT8.COM"
 * 86-DOS "INIT.COM"
 *
 */
t_stat trackWrite(DISK_INFO *myDisk,
               uint32 Cyl,
               uint32 Head,
               uint32 numSectors,
               uint32 sectorLen,
               uint8 *sectorMap,
               uint8 mode,
               uint8 fillbyte,
               uint32 *flags)
{
    FILE *fileref;
    IMD_HEADER track_header;
    uint8 *sectorData;
    unsigned long i;
    unsigned long dataLen;

    *flags = 0;

    /* Check parameters */
    if(myDisk == NULL) {
        *flags |= IMD_DISK_IO_ERROR_GENERAL;
        return(SCPE_IOERR);
    }

    if(myDisk->flags & FD_FLAG_WRITELOCK) {
        printf("Disk write-protected, cannot format tracks." NLP);
        *flags |= IMD_DISK_IO_ERROR_WPROT;
        return(SCPE_IOERR);
    }

    fileref = myDisk->file;

    DBG_PRINT(("Formatting C:%d/H:%d/N:%d, len=%d, Fill=0x%02x" NLP, Cyl, Head, numSectors, sectorLen, fillbyte));

    /* Truncate the IMD file when formatting Cyl 0, Head 0 */
    if((Cyl == 0) && (Head == 0))
    {
        /* Skip over IMD comment field. */
        commentParse(myDisk, NULL, 0);

        /* Truncate the IMD file after the comment field. */
#ifdef _WIN32 /* This might work under UNIX and/or VMS since this POSIX, but I haven't tried it. */
        _chsize(_fileno(fileref), ftell (fileref));
#else
        if (ftruncate(fileno(fileref), ftell (fileref)) == -1) {
            printf("Disk truncation failed." NLP);
            *flags |= IMD_DISK_IO_ERROR_GENERAL;
            return(SCPE_IOERR);
        }
#endif
        /* Flush and re-parse the IMD file. */
        fflush(fileref);
        diskParse(myDisk, 0);
    }

    /* Check to make sure the Cyl / Head is not already formatted. */
    if(sectSeek(myDisk, Cyl, Head) == 0) {
        printf("SIM_IMD: ERROR: Not Formatting C:%d/H:%d, track already exists." NLP, Cyl, Head);
        *flags |= IMD_DISK_IO_ERROR_GENERAL;
        return(SCPE_IOERR);
    }

    track_header.mode = mode;
    track_header.cyl = Cyl;
    track_header.head = Head;
    track_header.nsects = numSectors;
    track_header.sectsize = sectorLen;

    /* Forward to end of the file, write track header and sector map. */
    sim_fseek(myDisk->file, 0, SEEK_END);
    sim_fwrite(&track_header, 1, sizeof(IMD_HEADER), fileref);
    sim_fwrite(sectorMap, 1, numSectors, fileref);

    /* Compute data length, and fill a sector buffer with the
     * sector record type as the first byte, and fill the sector
     * data with the fillbyte.
     */
    dataLen = (128 << sectorLen)+1;
    sectorData = malloc(dataLen);
    memset(sectorData, fillbyte, dataLen);
    sectorData[0] = SECT_RECORD_NORM;

    /* For each sector on the track, write the record type and sector data. */
    for(i=0;i<numSectors;i++) {
        sim_fwrite(sectorData, 1, dataLen, fileref);
    }

    /* Flush the file, and free the sector buffer. */
    fflush(fileref);
    free(sectorData);

    /* Now that the disk track/sector layout has been modified, re-parse the disk image. */
    diskParse(myDisk, 0);

    return(SCPE_OK);
}
Ejemplo n.º 12
0
/*
 * Create an ImageDisk (IMD) file.  This function just creates the comment header, and allows
 * the user to enter a comment.  After the IMD is created, it must be formatted with a format
 * program on the simulated operating system, ie CP/M, CDOS, 86-DOS.
 *
 * If the IMD file already exists, the user will be given the option of overwriting it.
 */
t_stat diskCreate(FILE *fileref, char *ctlr_comment)
{
    DISK_INFO *myDisk = NULL;
    char *comment;
    char *curptr;
    char *result;
    uint8 answer;
    int32 len, remaining;

    if(fileref == NULL) {
        return (SCPE_OPENERR);
    }

    if(sim_fsize(fileref) != 0) {
        printf("SIM_IMD: Disk image already has data, do you want to overwrite it? ");
        answer = getchar();

        if((answer != 'y') && (answer != 'Y')) {
            return (SCPE_OPENERR);
        }
    }

    if((curptr = comment = calloc(1, MAX_COMMENT_LEN)) == 0) {
        printf("Memory allocation failure.\n");
        return (SCPE_MEM);
    }

    printf("SIM_IMD: Enter a comment for this disk.\n"
           "SIM_IMD: Terminate with a '.' on an otherwise blank line.\n");
    remaining = MAX_COMMENT_LEN;
    do {
        printf("IMD> ");
        result = fgets(curptr, remaining - 3, stdin);
        if ((result == NULL) || (strcmp(curptr, ".\n") == 0)) {
            remaining = 0;
        } else {
            len = strlen(curptr) - 1;
            if (curptr[len] != '\n')
                len++;
            remaining -= len;
            curptr += len;
            *curptr++ = 0x0d;
            *curptr++ = 0x0a;
        }
    } while (remaining > 4);
    *curptr = 0x00;

    /* rewind to the beginning of the file. */
    rewind(fileref);

    /* Erase the contents of the IMD file in case we are overwriting an existing image. */
#ifdef _WIN32 /* This might work under UNIX and/or VMS since this POSIX, but I haven't tried it. */
    _chsize(_fileno(fileref), ftell (fileref));
#else
    if (ftruncate(fileno(fileref), ftell (fileref)) == -1) {
        printf("SIM_IMD: Error overwriting disk image.\n");
        return(SCPE_OPENERR);
    }
#endif

    fprintf(fileref, "IMD SIMH %s %s\n", __DATE__, __TIME__);
    fputs(comment, fileref);
    free(comment);
    fprintf(fileref, "\n\n$Id: sim_imd.c 1999 2008-07-22 04:25:28Z hharte $\n");
    fprintf(fileref, "%s\n", ctlr_comment);
    fputc(0x1A, fileref); /* EOF marker for IMD comment. */
    fflush(fileref);

    if((myDisk = diskOpen(fileref, 0)) == NULL) {
        printf("SIM_IMD: Error opening disk for format.\n");
        return(SCPE_OPENERR);
    }

    if(diskFormat(myDisk) != SCPE_OK) {
        printf("SIM_IMD: error formatting disk.\n");
    }

    return diskClose(&myDisk);
}
Ejemplo n.º 13
0
void wbfs_file_truncate(void *handle,long long size)
{
	_chsize(fileno((FILE*)handle),size);
}
Ejemplo n.º 14
0
int ftruncate (int fd, long newSize) {
  int result = _chsize(fd, newSize);
  return result;
}
Ejemplo n.º 15
0
void INI_InsertSpace(int space)
{
  printf("Inserting space, space to insert is %d\n", space);
    // Since there is no good way to normally insert to or delete from a certain location in
    //  a file, this function was added.  It will insert (or delete) space bytes at the
    //  current location.

    // note: negative count means delete
    char chunk[2048];
    int len, file, start_pos, cur_pos;

#ifdef _WIN32
    file = _fileno(ini);
#else // _WIN32
   file = fileno(ini);
#endif // _WIN32

    start_pos = ftell(ini);
    fseek(ini,0,SEEK_END);

    // if adding, extend the file
    if (space > 0)
#ifdef _WIN32
        _chsize (file, _filelength(file)+space);
#else // _WIN32
     {
    int t1 = ftell(ini);
    fseek(ini, 0L, SEEK_END);
    int t2 = ftell(ini);
    fseek(ini, t1, SEEK_SET);
    if (ftruncate(file, t2+space) != 0)
        ERRLOG("Failed to truncate .ini file to %i bytes", t2+space);
    }
#endif // _WIN32

    while (1) {
        cur_pos = ftell(ini);
        len = cur_pos - start_pos;
        if (len == 0) break;
        if (len > 2048) len = 2048;

        fseek (ini,-len,SEEK_CUR);
        if (fread(chunk,1,len,ini) != (size_t) len)
            ERRLOG("Failed to read %i bytes from .ini file", len);
        fseek (ini,-len+space,SEEK_CUR);
        if (fwrite(chunk,1,len,ini) != (size_t) len)
            ERRLOG("Failed to write %i bytes to .ini file", len);
        fseek (ini,-len-space,SEEK_CUR);
    }

    // if deleted, make the file shorter
    if (space < 0)
#ifdef _WIN32
        _chsize (file, _filelength(file)+space);
#else // _WIN32
     {
    int t1 = ftell(ini);
    fseek(ini, 0L, SEEK_END);
    int t2 = ftell(ini);
    fseek(ini, t1, SEEK_SET);
    if (ftruncate(file, t2+space) != 0)
        ERRLOG("Failed to truncate .ini file to %i bytes", t2+space);
     }
#endif // _WIN32
}
Ejemplo n.º 16
0
    // if doingRepair is true don't consider unclean shutdown an error
    void acquirePathLock(MMAPV1Engine* storageEngine, bool doingRepair) {
        string name = (boost::filesystem::path(storageGlobalParams.dbpath) / "mongod.lock").string();

        bool oldFile = false;

        if ( boost::filesystem::exists( name ) && boost::filesystem::file_size( name ) > 0 ) {
            oldFile = true;
        }

#ifdef _WIN32
        lockFileHandle = CreateFileA( name.c_str(), GENERIC_READ | GENERIC_WRITE,
            0 /* do not allow anyone else access */, NULL, 
            OPEN_ALWAYS /* success if fh can open */, 0, NULL );

        if (lockFileHandle == INVALID_HANDLE_VALUE) {
            DWORD code = GetLastError();
            char *msg;
            FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                NULL, code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                (LPSTR)&msg, 0, NULL);
            string m = msg;
            str::stripTrailing(m, "\r\n");
            uasserted(ErrorCodes::DBPathInUse,
                      str::stream() << "Unable to create/open lock file: "
                                    << name << ' ' << m
                                    << ". Is a mongod instance already running?");
        }
        lockFile = _open_osfhandle((intptr_t)lockFileHandle, 0);
#else
        lockFile = open( name.c_str(), O_RDWR | O_CREAT , S_IRWXU | S_IRWXG | S_IRWXO );
        if( lockFile <= 0 ) {
            uasserted( ErrorCodes::DBPathInUse,
                       str::stream() << "Unable to create/open lock file: "
                                     << name << ' ' << errnoWithDescription()
                                     << " Is a mongod instance already running?" );
        }
        if (flock( lockFile, LOCK_EX | LOCK_NB ) != 0) {
            close ( lockFile );
            lockFile = 0;
            uasserted(ErrorCodes::DBPathInUse,
                      "Unable to lock file: " + name + ". Is a mongod instance already running?");
        }
#endif

        if ( oldFile ) {
            // we check this here because we want to see if we can get the lock
            // if we can't, then its probably just another mongod running
            
            string errmsg;
            if (doingRepair && dur::haveJournalFiles()) {
                errmsg = "************** \n"
                         "You specified --repair but there are dirty journal files. Please\n"
                         "restart without --repair to allow the journal files to be replayed.\n"
                         "If you wish to repair all databases, please shutdown cleanly and\n"
                         "run with --repair again.\n"
                         "**************";
            }
            else if (storageGlobalParams.dur) {
                if (!dur::haveJournalFiles(/*anyFiles=*/true)) {
                    // Passing anyFiles=true as we are trying to protect against starting in an
                    // unclean state with the journal directory unmounted. If there are any files,
                    // even prealloc files, then it means that it is mounted so we can continue.
                    // Previously there was an issue (SERVER-5056) where we would fail to start up
                    // if killed during prealloc.

                    vector<string> dbnames;
                    storageEngine->listDatabases( &dbnames );

                    if ( dbnames.size() == 0 ) {
                        // this means that mongod crashed
                        // between initial startup and when journaling was initialized
                        // it is safe to continue
                    }
                    else {
                        errmsg = str::stream()
                            << "************** \n"
                            << "old lock file: " << name << ".  probably means unclean shutdown,\n"
                            << "but there are no journal files to recover.\n"
                            << "this is likely human error or filesystem corruption.\n"
                            << "please make sure that your journal directory is mounted.\n"
                            << "found " << dbnames.size() << " dbs.\n"
                            << "see: http://dochub.mongodb.org/core/repair for more information\n"
                            << "*************";
                    }

                }
            }
            else {
                if (!dur::haveJournalFiles() && !doingRepair) {
                    errmsg = str::stream()
                             << "************** \n"
                             << "Unclean shutdown detected.\n"
                             << "Please visit http://dochub.mongodb.org/core/repair for recovery instructions.\n"
                             << "*************";
                }
            }

            if (!errmsg.empty()) {
                log() << errmsg << endl;
#ifdef _WIN32
                CloseHandle( lockFileHandle );
#else
                close ( lockFile );
#endif
                lockFile = 0;
                uassert( 12596 , "old lock file" , 0 );
            }
        }

        // Not related to lock file, but this is where we handle unclean shutdown
        if (!storageGlobalParams.dur && dur::haveJournalFiles()) {
            log() << "**************" << endl;
            log() << "Error: journal files are present in journal directory, yet starting without journaling enabled." << endl;
            log() << "It is recommended that you start with journaling enabled so that recovery may occur." << endl;
            log() << "**************" << endl;
            uasserted(13597, "can't start without --journal enabled when journal/ files are present");
        }

#ifdef _WIN32
        uassert( 13625, "Unable to truncate lock file", _chsize(lockFile, 0) == 0);
        writePid( lockFile );
        _commit( lockFile );
#else
        uassert( 13342, "Unable to truncate lock file", ftruncate(lockFile, 0) == 0);
        writePid( lockFile );
        fsync( lockFile );
        flushMyDirectory(name);
#endif
    }
Ejemplo n.º 17
0
/* Checks finished transfer. */
static as_bool download_finished (ASDownload *dl)
{
	ASHash *hash;
#ifdef WIN32
	int fd;
#endif

	/* Stop all chunk downloads if there are still any */
	stop_all_connections (dl);

	/* Make sure any source search is gone */
	if (dl->search)
		as_searchman_remove (AS->searchman, dl->search);
	dl->search = NULL;

	AS_DBG_1 ("Verifying download \"%s\"", dl->filename);

	/* Do some sanity checks */
	assert (dl->chunks->next == NULL);
	assert (((ASDownChunk *)dl->chunks->data)->udata == NULL);
	assert (((ASDownChunk *)dl->chunks->data)->size == dl->size);
	assert (dl->fp != NULL);

	/* Close file pointer */
	fclose (dl->fp);
	dl->fp = NULL;

	/* raise callback */
	if (!download_set_state (dl, DOWNLOAD_VERIFYING, TRUE))
		return FALSE;

	/* Truncate incomplete file to correct size removing the state data at
	 * the end.
	 */
	assert (dl->size > 0);

#ifndef WIN32
	if (truncate (dl->path, dl->size) < 0)
#else
	if ((fd = _open (dl->path, _O_BINARY | _O_WRONLY)) < 0 ||
	    _chsize (fd, dl->size) != 0 ||
	    _close (fd) != 0)
#endif
	{
		AS_ERR_1 ("Failed to truncate complete download \"%s\"",
		          dl->path);
		/* File is probably still useful so continue. */
	}

	/* Hash file and compare hashes.
	 * TODO: Make non-blocking.
	 */
	if (!(hash = as_hash_file (dl->path)))
	{
		AS_ERR_1 ("Couldn't hash \"%s\" for verification", dl->path);
		return download_failed (dl);
	}

	if (!as_hash_equal (dl->hash, hash))
	{
		AS_ERR_1 ("Downloaded file \"%s\" corrupted!", dl->path);
		as_hash_free (hash);
		return download_failed (dl);
	}

	as_hash_free (hash);

	/* Download is OK */
	return download_complete (dl);
}
Ejemplo n.º 18
0
gint
g_win32_ftruncate (gint  fd,
		   guint size)
{
  return _chsize (fd, size);
}
Ejemplo n.º 19
0
/* Open input and output files, and check is there is a checkpoint file */
static void init_files(void)
{
	const char *outfile_openmode = "w";
	char *file_name;

	/* Open the input file */
	file_name = DC_resolveFileName(DC_FILE_IN, INPUT_LABEL);
	if (!file_name)
	{
		fprintf(stderr, "APP: Could not resolve the input file name\n");
		DC_finishClient(1);
	}

	infile = fopen(file_name, "rb");
	if (!infile)
	{
		perror("APP: Could not open the input file");
		DC_finishClient(1);
	}
	free(file_name);

	/* Determine the size of the input file */
	fseek(infile, 0, SEEK_END);
	frac_total_size = ftell(infile);
	fseek(infile, 0, SEEK_SET);

	/* Check the checkpoint file */
	file_name = DC_resolveFileName(DC_FILE_IN, DC_CHECKPOINT_FILE);
	if (file_name)
	{
		FILE *ckptfile;
		int ret;

		ckptfile = fopen(file_name, "r");
		if (!ckptfile)
		{
			perror("APP: Could not open the initial checkpoint file");
			DC_finishClient(1);
		}
		free(file_name);

		/* ckpt file exists: read and set everything according to it */
		ret = fscanf(ckptfile, "%d", &frac_current_pos);
		if (ret != 1 || frac_current_pos < 0 ||
				frac_current_pos > frac_total_size)
		{
			fprintf(stderr, "APP: Failed to parse the contents of "
				"the checkpoint file, starting from the "
				"beginning\n");
			frac_current_pos = 0;
		}
		else
		{
			fprintf(stderr, "APP: Found checkpoint file, starting "
				"from position %d.\n", frac_current_pos);
			outfile_openmode = "r+";
		}
		fclose(ckptfile);

		fseek(infile, frac_current_pos, SEEK_SET);
	}

	/* Open the output file */
	file_name = DC_resolveFileName(DC_FILE_OUT, OUTPUT_LABEL);
	if (!file_name)
	{
		fprintf(stderr, "APP: Could not resolve the output file name\n");
		DC_finishClient(1);
	}

	outfile = fopen(file_name, outfile_openmode);
	if (!outfile)
	{
		perror("APP: Could not open/create the output file");
		DC_finishClient(1);
	}
	free(file_name);

	/* If we are starting from a checkpoint file, restore the state of
	 * the output file as well */
#ifdef _WIN32
	_chsize(fileno(outfile), frac_current_pos);
#else
	ftruncate(fileno(outfile), frac_current_pos);
#endif

	fseek(outfile, 0, SEEK_END);
}
Ejemplo n.º 20
0
/*! \brief Delete the given data from the file.
	\details The function erases the given data from the file at the given write
   position. This
	operation may take a while to complete, but is faster than insertData.

	The write position is not changed and the read position	is checked for
   validity upon function exit.
	\param start The offset of the first byte to delete
	\param length The total number of bytes to delete
	\returns XRV_OK if the data was deleted successfully
*/
XsResultValue IoInterfaceFile::deleteData(XsFilePos start, XsSize length)
{
	if (!m_handle) return m_lastResult = XRV_NOFILEOPEN;
	if (m_readOnly) return m_lastResult = XRV_READONLY;

	gotoWrite();

	XsFilePos wPos = start;
	XsFilePos rPos = wPos + length;

	size_t read1;
	XsFilePos endPos = (start + (XsFilePos)length);
	if (endPos < m_fileSize)
	{
		XsFilePos remaining = m_fileSize - endPos;
		char buffer[512];

		// copy data
		FSEEK(rPos);

		while (remaining > 0)
		{
			if (remaining >= 512)
				read1 = fread(buffer, 1, 512, m_handle);
			else
				read1 = fread(buffer, 1, (size_t)remaining, m_handle);

			remaining -= read1;
			rPos += read1;

			// write block to the correct position
			FSEEK(wPos);
			wPos += fwrite(buffer, 1, read1, m_handle);
			FSEEK(rPos);
		}
		m_fileSize -= length;
	}
	else
	{
		m_fileSize = start;
	}

#ifdef _WIN32
	int32_t rv = _chsize(_fileno(m_handle), (int32_t)m_fileSize);
#else
	int32_t rv = ftruncate(fileno(m_handle), (int32_t)m_fileSize);
#endif
	int32_t eno = 0;
	if (rv != 0) eno = errno;
	m_writePos = start;
	FSEEK(wPos);
	if (rv != 0)
	{
		switch (eno)
		{
			case EACCES:
				return m_lastResult = XRV_BUSY;
			case EBADF:
				return m_lastResult = XRV_INVALIDINSTANCE;
			case ENOSPC:
				return m_lastResult = XRV_OUTOFMEMORY;
			case EINVAL:
				return m_lastResult = XRV_INVALIDPARAM;
			default:
				return m_lastResult = XRV_ERROR;
		}
	}

	return m_lastResult = XRV_OK;
}
Ejemplo n.º 21
0
bool write_netlog(int sn, long sent, long recd, char *tmused)
{
	char s[101], s1[81], s2[81];
	//printf(" write_netlog: %d %ld %ld %s", sn, sent, recd, tmused );
	
	time_t some = time(NULL);
	struct tm *time_now = localtime(&some);
	strftime(s1, 35, "%m/%d/%y %H:%M:%S", time_now);
	
	if (sent || recd) 
	{
		if (recd && !sent)
		{
			sprintf(s2, "       , R:%4ldk,", recd);
		}
		else 
		{
			if (recd && sent)
			{
				sprintf(s2, "S:%4ldk, R:%4ldk,", sent, recd);
			}
			else
			{
				sprintf(s2, "S:%4ldk,         ", sent);
			}
		}
	} 
	else
	{
		strcpy(s2, "                 ");
	}

	if ( strlen( tmused ) > 10 )
	{
		printf(" Bad time pased to tmused\r\n" );
		tmused = "0.0";
	}
	sprintf(s, "%s To %5d, %s         %5s min  %s\r\n", s1, sn, s2, tmused, net_name);
	
	char* ss = (char *) malloc(MAX_LEN + 1024L);
	if (ss == NULL)
	{
		return false;
	}
	strcpy(ss, s);
	
	char szFileName[_MAX_PATH];
	sprintf(szFileName, "%snet.log", syscfg.gfilesdir);
	int hFile = open_netlog(szFileName);
	_lseek(hFile, 0L, SEEK_SET);
	int nLength = _read(hFile, (void *) (&(ss[strlen(s)])), (int) MAX_LEN) + strlen(s);
	while (nLength > 0 && ss[nLength] != '\n')
	{
		--nLength;
	}
	_lseek(hFile, 0L, SEEK_SET);
	_write(hFile, ss, nLength + 1);
	_chsize(hFile, nLength + 1);
	if (ss) 
	{
		free(ss);
		ss = NULL;
	}
	_close(hFile);
	return true;
}
Ejemplo n.º 22
0
    /** also called by ntservice.cpp */
    void shutdownServer() {

        log() << "shutdown: going to close listening sockets..." << endl;
        ListeningSockets::get()->closeAll();

        log() << "shutdown: going to flush diaglog..." << endl;
        _diaglog.flush();

        /* must do this before unmapping mem or you may get a seg fault */
        log() << "shutdown: going to close sockets..." << endl;
        boost::thread close_socket_thread( boost::bind(MessagingPort::closeAllSockets, 0) );

        // wait until file preallocation finishes
        // we would only hang here if the file_allocator code generates a
        // synchronous signal, which we don't expect
        log() << "shutdown: waiting for fs preallocator..." << endl;
        FileAllocator::get()->waitUntilFinished();

        if( cmdLine.dur ) {
            log() << "shutdown: lock for final commit..." << endl;
            {
                int n = 10;
                while( 1 ) {
                    // we may already be in a read lock from earlier in the call stack, so do read lock here 
                    // to be consistent with that.
                    readlocktry w(20000);
                    if( w.got() ) { 
                        log() << "shutdown: final commit..." << endl;
                        getDur().commitNow();
                        break;
                    }
                    if( --n <= 0 ) {
                        log() << "shutdown: couldn't acquire write lock, aborting" << endl;
                        mongoAbort("couldn't acquire write lock");
                    }
                    log() << "shutdown: waiting for write lock..." << endl;
                }
            }
            MemoryMappedFile::flushAll(true);
        }

        log() << "shutdown: closing all files..." << endl;
        stringstream ss3;
        MemoryMappedFile::closeAllFiles( ss3 );
        log() << ss3.str() << endl;

        if( cmdLine.dur ) {
            dur::journalCleanup(true);
        }

#if !defined(__sunos__)
        if ( lockFile ) {
            log() << "shutdown: removing fs lock..." << endl;
            /* This ought to be an unlink(), but Eliot says the last
               time that was attempted, there was a race condition
               with acquirePathLock().  */
#ifdef _WIN32
            if( _chsize( lockFile , 0 ) )
                log() << "couldn't remove fs lock " << WSAGetLastError() << endl;
            CloseHandle(lockFileHandle);
#else
            if( ftruncate( lockFile , 0 ) )
                log() << "couldn't remove fs lock " << errnoWithDescription() << endl;
            flock( lockFile, LOCK_UN );
#endif
        }
#endif
    }
Ejemplo n.º 23
0
/**** log_score
      Inputs: 'progname' - the program to log a score for
              'level' - the freeform level identifier
	      'username' - the username that this score is logged under
	      'score' - the game score
	      'ordering' - whether lower scores are better.
      Outputs: 'retval' - Whether the score got onto the highscore list

      Description: Loads all the existing scores into the 'scores'
                   list.  Goes through and finds out whether there's a
                   place for the new score on the high-score list, and
                   if so, inserts it. Writes out the new high-score list.
 */
static gint
log_score (const gchar * progname, const gchar * level, gchar * username,
	   gfloat score, gboolean ordering)
{
   FILE *infile;
   FILE *outfile;
   gchar buf[512], *buf2;
   GList *scores = NULL, *anode;
   gchar *game_score_file;
   gfloat ascore;
   struct ascore_t *anitem, *curscore;
   int i;
   gint retval = 1;
   gint pos;

   game_score_file = gnome_get_score_file_name (progname, level);

   infile = g_fopen (game_score_file, "r");
   if (infile)
     {
       /* make sure we read values from files in a consistent manner */
       gnome_i18n_push_c_numeric_locale ();
       while(fgets(buf, sizeof(buf), infile))
	 {
	     long ltime;
	     i = strlen (buf) - 1;	/* Chomp */
	     while (g_ascii_isspace (buf[i]))
	       buf[i--] = '\0';

  	     {
	        char *tokp;

	        if((buf2 = strtok_r (buf, " ", &tokp)) == NULL)
		  break;
	        ascore = atof (buf2);
	        if((buf2 = strtok_r (NULL, " ", &tokp)) == NULL)
		  break;
	        ltime = atoi (buf2);
	        if((buf2 = strtok_r (NULL, "\n", &tokp)) == NULL)
		  break;
	     }

	     anitem = g_new(struct ascore_t, 1);
	     anitem->score = ascore;
	     anitem->username = g_strdup (buf2);
	     anitem->scoretime = (time_t)ltime;
	     scores = g_list_append (scores, (gpointer) anitem);
	  }
        gnome_i18n_pop_c_numeric_locale ();

	fclose (infile);
     }

   anitem = g_new(struct ascore_t, 1);
   anitem->score = score;
   anitem->username = g_strdup (username);
   anitem->scoretime = time (NULL);

   for (pos = 0, anode = scores;
	pos < NSCORES && anode;
	pos++, anode = anode->next)
     {
	curscore = anode->data;
	if (ordering)
	  {
	     if (curscore->score < anitem->score)
	       break;
	  }
	else
	  {
	     if (curscore->score > anitem->score)
	       break;
	  }
     }

   if (pos < NSCORES)
     {
	scores = g_list_insert (scores, anitem, pos);
	if ((anode = g_list_nth (scores, NSCORES)))
	  {
	     free_ascore (anode->data);
	     scores =
	       g_list_remove_link (scores, g_list_nth (scores, NSCORES));
	  }
	retval = pos + 1;
     }
   else
     retval = 0;

   /* we dont create the file; it must already exist */
   outfile = g_fopen (game_score_file, "r+");
#ifndef G_OS_WIN32
   ftruncate (fileno (outfile), 0);
#else
   _chsize (fileno (outfile), 0);
#endif

   if (outfile)
     {
	gnome_i18n_push_c_numeric_locale ();
	g_list_foreach (scores, (GFunc) print_ascore, outfile);
	gnome_i18n_pop_c_numeric_locale ();
	fclose (outfile);
     }
   else
     perror (game_score_file);

   g_free (game_score_file);

   g_list_foreach (scores, (GFunc) free_ascore, NULL);
   g_list_free (scores);

   return retval;
}
Ejemplo n.º 24
0
int EbrIOFile::Truncate(off_t size) {
    return _chsize(filefd, size);
}
Ejemplo n.º 25
0
/**
 * The  truncate function is used to truncate the size of an open file in storage.
 */
int pcsl_file_truncate(void *handle, long size)
{
	return _chsize((int)handle, size);
}