Exemple #1
0
// get filename
bool SettingLoader::getFilename(const tstringi &i_name, tstringi *o_path,
								int i_debugLevel) const
{
	// the default filename is ".mayu"
	const tstringi &name = i_name.empty() ? tstringi(_T(".mayu")) : i_name;

	bool isFirstTime = true;

	while (true) {
		// find file from registry
		if (i_name.empty()) {			// called not from 'include'
			Setting::Symbols symbols;
			if (getFilenameFromRegistry(NULL, o_path, &symbols)) {
				if (o_path->empty())
					// find file from home directory
				{
					HomeDirectories pathes;
					getHomeDirectories(&pathes);
					for (HomeDirectories::iterator
							i = pathes.begin(); i != pathes.end(); ++ i) {
						*o_path = *i + _T("\\") + name;
						if (isReadable(*o_path, i_debugLevel))
							goto add_symbols;
					}
					return false;
				} else {
					if (!isReadable(*o_path, i_debugLevel))
						return false;
				}
add_symbols:
				for (Setting::Symbols::iterator
						i = symbols.begin(); i != symbols.end(); ++ i)
					m_setting->m_symbols.insert(*i);
				return true;
			}
		}

		if (!isFirstTime)
			return false;

		// find file from home directory
		HomeDirectories pathes;
		getHomeDirectories(&pathes);
		for (HomeDirectories::iterator i = pathes.begin(); i != pathes.end(); ++ i) {
			*o_path = *i + _T("\\") + name;
			if (isReadable(*o_path, i_debugLevel))
				return true;
		}

		if (!i_name.empty())
			return false;				// called by 'include'

		if (!DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_setting),
					   NULL, dlgSetting_dlgProc))
			return false;
	}
}
Exemple #2
0
Checksum Item::checksumPart(long long len) const {
  if(!isReadable()) {
    printf("Isn't readable: %s", local_path.c_str());
    CHECK(0);
  }

  for(int i = 0; i < css.size(); i++) {
    if(css[i].first == len)
      return css[i].second;
  }
  
  if(type != MTI_LOCAL) {
    printf("Invalid type %d, size %lld\n", type, size());
    for(int i = 0; i < css.size(); i++)
      printf("Css %lld\n", css[i].first);
    CHECK(0);
  }
  //printf("Doing full checksum of %s\n", local_path.c_str());
  
  long long bytu = 0;
  
  SHA_CTX c;
  SHA1_Init(&c);
  ItemShunt *phil = open();
  if(!phil) {
    printf("Couldn't open %s during checksum\n", local_path.c_str());
    CHECK(isReadable());
    CHECK(0);
  }
  while(1) {
    char buf[1024*512];
    int rv = phil->read(buf, sizeof(buf));
    
    if(bytu + rv >= len) {
      SHA1_Update(&c, buf, len - bytu);
      Checksum tcs = signaturePart(len);
      SHA1_Final(tcs.bytes, &c);
      delete phil;
      cssi += len;
      css.push_back(make_pair(len, tcs));
      return tcs;
    } else {
      SHA1_Update(&c, buf, rv);
    }
    
    if(rv != sizeof(buf)) {
      printf("Trying to read %lld from %s, only picked up %lld, last value %d!\n", len, local_path.c_str(), bytu + rv, rv);
      CHECK(0);
    }
    
    bytu += rv;
  }
  
  CHECK(0);
}
Exemple #3
0
bool FileMgr::existsFile(NormalizedPath const & path, char const * ifileName) {
    std::string buf(std::move(path));
    if (ifileName)
        buf.append("/").append(ifileName);

    return isReadable(buf);
}
Exemple #4
0
			bool isWritable() const {
#ifdef R_UM_OPT_ENFORCE_LOWLEV_VALIDITY
				assert(isReadable());
#endif
		
				return refcnt_ == 1;
			}
Exemple #5
0
// get filename from registry
bool SettingLoader::getFilenameFromRegistry(tstringi *o_path) const
{
	// get from registry
	Registry reg(MAYU_REGISTRY_ROOT);
	int index;
	reg.read(_T(".mayuIndex"), &index, 0);
	char buf[100];
	snprintf(buf, NUMBER_OF(buf), _T(".mayu%d"), index);
	if (!reg.read(buf, o_path))
		return false;

	// parse registry entry
	Regexp getFilename(_T("^[^;]*;([^;]*);(.*)$"));
	if (!getFilename.doesMatch(*o_path))
		return false;

	tstringi path = getFilename[1];
	tstringi options = getFilename[2];

	if (!(0 < path.size() && isReadable(path)))
		return false;
	*o_path = path;

	// set symbols
	Regexp symbol(_T("-D([^;]*)"));
	while (symbol.doesMatch(options)) {
		m_setting->symbols.insert(symbol[1]);
		options = options.substr(symbol.subBegin(1));
	}

	return true;
}
Exemple #6
0
Q_LONG QBuffer::readLine( char *p, Q_ULONG maxlen )
{
#if defined(QT_CHECK_NULL)
    if ( p == 0 ) {
        qWarning( "QBuffer::readLine: Null pointer error" );
        return -1;
    }
#endif
#if defined(QT_CHECK_STATE)
    if ( !isOpen() ) {                          // buffer not open
        qWarning( "QBuffer::readLine: Buffer not open" );
        return -1;
    }
    if ( !isReadable() ) {                      // reading not permitted
        qWarning( "QBuffer::readLine: Read operation not permitted" );
        return -1;
    }
#endif
    if ( maxlen == 0 )
        return 0;
    Q_ULONG start = ioIndex;
    char *d = a.data() + ioIndex;
    maxlen--;                                   // make room for 0-terminator
    if ( a.size() - ioIndex < maxlen )
        maxlen = a.size() - ioIndex;
    while ( maxlen-- ) {
        if ( (*p++ = *d++) == '\n' )
            break;
    }
    *p = '\0';
    ioIndex = d - a.data();
    return ioIndex - start;
}
QString FtpFileSystem::listDir(){
    QString fullPath = appendPath(mBaseDir, mCurDir);
    QDir dir(fullPath);
    if (!(dir.exists()))
        return NULL;

    dir.setSorting(QDir::Size | QDir::Reversed);
    QString buffer;
    QFileInfoList list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i) {
        QFileInfo fileInfo = list.at(i);
        if (fileInfo.fileName()=="." || fileInfo.fileName() == "..")
            continue;
         QString dirLabel = fileInfo.isDir()?"d":"-";
         bool writable = isWritable(fileInfo.fileName());
         bool readable =  isReadable(fileInfo.fileName());
         QString sfileSize = fileInfo.isDir()?"512":QString::number(fileInfo.size());
         QDateTime dt = fileInfo.lastModified();
         QString lastModified = formatDate(dt);
//         qDebug() << fileInfo.fileName();
         buffer = buffer % QString("%1%5%6-r--r-- 1 root root %2 %3 %4\r\n").arg(dirLabel).arg(sfileSize).arg(lastModified).arg(fileInfo.fileName())
                .arg(readable?"r":"-").arg(writable?"w":"-");
    }
    return buffer;
}
ISocketMultiplexerJob*
SecureSocket::serviceAccept(ISocketMultiplexerJob* job,
				bool, bool write, bool error)
{
	Lock lock(&getMutex());

	int status = 0;
#ifdef SYSAPI_WIN32
	status = secureAccept(static_cast<int>(getSocket()->m_socket));
#elif SYSAPI_UNIX
	status = secureAccept(getSocket()->m_fd);
#endif
		// If status < 0, error happened
	if (status < 0) {
		return NULL;
	}

	// If status > 0, success
	if (status > 0) {
		sendEvent(m_events->forClientListener().accepted());
		return newJob();
	}

	// Retry case
	return new TSocketMultiplexerMethodJob<SecureSocket>(
			this, &SecureSocket::serviceAccept,
			getSocket(), isReadable(), isWritable());
}
Exemple #9
0
  // @mfunc Attempt to read the number of bytes given by <p byteCount>
  //        from offset <p position> in this <c OMCachedRawStorage>
  //        into the buffer at address <p bytes>.
  //        The actual number of bytes read is returned in <p bytesRead>.
  //        Reading from positions greater than
  //        <mf OMCachedRawStorage::size> causes <p bytesRead> to be less
  //        than <p byteCount>. Reading bytes that have never been written
  //        returns undefined data in <p bytes>.
  //   @parm The position from which the bytes are to be read.
  //   @parm The buffer into which the bytes are to be read.
  //   @parm The number of bytes to read.
  //   @parm The number of bytes actually read.
  //   @this const
void OMCachedRawStorage::readAt(OMUInt64 position,
                                OMByte* bytes,
                                OMUInt32 byteCount,
                                OMUInt32& bytesRead) const
{
  TRACE("OMCachedRawStorage::readAt");
  PRECONDITION("Valid buffer", bytes != 0);
  PRECONDITION("Valid byte count", byteCount > 0);
  PRECONDITION("Readable", isReadable());
  PRECONDITION("Positionable", isPositionable());

  if (position < _size) {
    OMUInt32 readCount;
    OMUInt64 remaining = _size - position;
    if (byteCount > remaining) {
      readCount = static_cast<OMUInt32>(remaining);
    } else {
      readCount = byteCount;
    }
    const_cast<OMCachedRawStorage*>(this)->
    readCachedAt(position, bytes, readCount, bytesRead);
    ASSERT("All bytes read", bytesRead == readCount);
    const_cast<OMCachedRawStorage*>(this)->
    _position = position + bytesRead;
  } else {
    bytesRead = 0;
  }
}
Exemple #10
0
int main(int argc, char **argv)
{


    int result  = isReadable(argv[1]);
    printf("%d\n", (int)result );
}
Exemple #11
0
int QBuffer::readLine( char *p, uint maxlen )
{
#if defined(CHECK_STATE)
    CHECK_PTR( p );
    if ( !isOpen() ) {				// buffer not open
	qWarning( "QBuffer::readLine: Buffer not open" );
	return -1;
    }
    if ( !isReadable() ) {			// reading not permitted
	qWarning( "QBuffer::readLine: Read operation not permitted" );
	return -1;
    }
#endif
    if ( maxlen == 0 )
	return 0;
    uint start = (uint)ioIndex;
    char *d = a.data() + ioIndex;
    maxlen--;					// make room for 0-terminator
    if ( a.size() - (uint)ioIndex < maxlen )
	maxlen = a.size() - (uint)ioIndex;
    while ( maxlen-- ) {
	if ( (*p++ = *d++) == '\n' )
	    break;
    }
    *p = '\0';
    ioIndex = (int)(d - a.data());
    return (uint)ioIndex - start;
}
Exemple #12
0
int QBuffer::readBlock( char *p, uint len )
{
#if defined(CHECK_STATE)
    CHECK_PTR( p );
    if ( !isOpen() ) {				// buffer not open
	qWarning( "QBuffer::readBlock: Buffer not open" );
	return -1;
    }
    if ( !isReadable() ) {			// reading not permitted
	qWarning( "QBuffer::readBlock: Read operation not permitted" );
	return -1;
    }
#endif
    if ( (uint)ioIndex + len > a.size() ) {	// overflow
	if ( (uint)ioIndex >= a.size() ) {
	    setStatus( IO_ReadError );
	    return -1;
	} else {
	    len = a.size() - (uint)ioIndex;
	}
    }
    memcpy( p, a.data()+ioIndex, len );
    ioIndex += len;
    return len;
}
Exemple #13
0
bool QFile::open( int m, int f )
{
    if ( isOpen() ) {
#if defined(CHECK_RANGE)
	qWarning( "QFile::open: File already open" );
#endif
	return FALSE;
    }
    init();
    setMode( m |IO_Raw );
    setState( IO_Open );
    fd = f;
    ext_f = TRUE;
    STATBUF st;
    FSTAT( fd, &st );
    ioIndex  = (int)LSEEK(fd, 0, SEEK_CUR);
    if ( (st.st_mode & STAT_MASK) != STAT_REG ) {
	// non-seekable
	setType( IO_Sequential );
	length = INT_MAX;
    } else {
	length = (int)st.st_size;
	if ( length == 0 && isReadable() ) {
	    // try if you can read from it (if you can, it's a sequential
	    // device; e.g. a file in the /proc filesystem)
	    int c = getch();
	    if ( c != -1 ) {
		ungetch(c);
		setType( IO_Sequential );
		length = INT_MAX;
	    }
	}
    }
    return TRUE;
}
Exemple #14
0
int KFileItem::overlays() const
{
  int _state = 0;
  if ( m_bLink )
      _state |= KIcon::LinkOverlay;

  if ( !S_ISDIR( m_fileMode ) // Locked dirs have a special icon, use the overlay for files only
       && !isReadable())
     _state |= KIcon::LockOverlay;

  if ( isHidden() )
     _state |= KIcon::HiddenOverlay;

  if( S_ISDIR( m_fileMode ) && m_bIsLocalURL)
  {
    if (KSambaShare::instance()->isDirectoryShared( m_url.path() ) ||
        KNFSShare::instance()->isDirectoryShared( m_url.path() ))
    {
      //kdDebug()<<"KFileShare::isDirectoryShared : "<<m_url.path()<<endl;
      _state |= KIcon::ShareOverlay;
    }
  }

  if ( m_pMimeType->name() == "application/x-gzip" && m_url.fileName().right(3) == ".gz" )
     _state |= KIcon::ZipOverlay;
  return _state;
}
Exemple #15
0
bool QFile::open( int m, FILE *f )
{
    if ( isOpen() ) {
#if defined(CHECK_RANGE)
	qWarning( "QFile::open: File already open" );
#endif
	return FALSE;
    }
    init();
    setMode( m &~IO_Raw );
    setState( IO_Open );
    fh = f;
    ext_f = TRUE;
    STATBUF st;
    FSTAT( FILENO(fh), &st );
    ioIndex = (int)ftell( fh );
    if ( (st.st_mode & STAT_MASK) != STAT_REG || f == stdin ) { //stdin is non seekable
	// non-seekable
	setType( IO_Sequential );
	length = INT_MAX;
    } else {
	length = (int)st.st_size;
	if ( !(flags()&IO_Truncate) && length == 0 && isReadable() ) {
	    // try if you can read from it (if you can, it's a sequential
	    // device; e.g. a file in the /proc filesystem)
	    int c = getch();
	    if ( c != -1 ) {
		ungetch(c);
		setType( IO_Sequential );
		length = INT_MAX;
	    }
	}
    }
    return TRUE;
}
int UDPServer::recv(char *buffer, int maxlen, Address *address, int timeout) {

    checkInitialized();

    if (!isReadable(sock, timeout)) { return 0; }
    struct sockaddr_in sender;

#ifdef WIN32
    int len = sizeof(sender);
#else
    socklen_t len = sizeof(sender);
#endif

    int received = ::recvfrom(sock, buffer, maxlen, 0,
                              (struct sockaddr *)&sender, &len);
    //assert(received >= 0, "recv failed\n");
    if (received < 0) {
        return received;
    }

    // return the address of the sender
    if (address) { *address = Address(sender); }

    return received;
}
Exemple #17
0
Q_LONG QBuffer::readBlock( char *p, Q_ULONG len )
{
#if defined(QT_CHECK_STATE)
    if ( !p ) {
	qWarning( "QBuffer::readBlock: Null pointer error" );
	return -1;
    }
    if ( !isOpen() ) {                          // buffer not open
        qWarning( "QBuffer::readBlock: Buffer not open" );
        return -1;
    }
    if ( !isReadable() ) {                      // reading not permitted
        qWarning( "QBuffer::readBlock: Read operation not permitted" );
        return -1;
    }
#endif
    if ( ioIndex + len > a.size() ) {   // overflow
        if ( ioIndex >= a.size() ) {
            return 0;
        } else {
            len = a.size() - ioIndex;
        }
    }
    memcpy(p, a.data() + ioIndex, len);
    ioIndex += len;
    return len;
}
Exemple #18
0
PluginMetadata PluginMetadataReader::readPluginMetadata(const QString &pluginName, const QString &filePath) noexcept(false)
{
	auto fileInfo = QFileInfo{filePath};
	if (!fileInfo.exists() || !fileInfo.isReadable())
		throw PluginMetadataReaderException{};

	auto const lang = m_configuration->deprecatedApi()->readEntry("General", "Language");
	QSettings file{filePath, QSettings::IniFormat};
	file.setIniCodec("UTF-8");

	auto builder = PluginMetadataBuilder{};
	return builder
			.setName(pluginName)
			.setDisplayName(file.value("Module/DisplayName[" + lang + ']', file.value("Module/DisplayName")).toString())
			.setCategory(file.value("Module/Category").toString())
			.setType(file.value("Module/Type").toString())
			.setDescription(file.value("Module/Description[" + lang + ']', file.value("Module/Description")).toString())
			.setAuthor(file.value("Module/Author").toString())
			.setVersion(file.value("Module/Version").toString() == "core"
					? m_versionService->version()
					: file.value("Module/Version").toString())
			.setProvides(file.value("Module/Provides").toString())
			.setDependencies(file.value("Module/Dependencies").toString().split(' ', QString::SkipEmptyParts))
			.setReplaces(file.value("Module/Replaces").toString().split(' ', QString::SkipEmptyParts))
			.setLoadByDefault(file.value("Module/LoadByDefault").toBool())
			.create();
}
// Return True if the specified file is cashed in the specified context
bool GLC_CacheManager::isCashed(const QString& context, const QString& fileName) const
{
	if (! isReadable()) return false;

	QFileInfo fileInfo(m_Dir.absolutePath() + QDir::separator() + context + QDir::separator() + fileName + '.' + GLC_BSRep::suffix());
	return fileInfo.exists();
}
Exemple #20
0
bool Sock::rcv(NetEvent& serial)
{
    memset(msg,0x0,MAX_MSG);
    remoteLen = sizeof(remoteAddr);

    if (!isReadable(sd,&error)) return false;

    /* receive echoed message */
    n = recvfrom(sd, msg, MAX_MSG, FLAGS,
      (struct sockaddr *) &remoteAddr, &remoteLen);

    if(n<0) {
        std::cerr << "cannot receive data\n";
        return false;
    }
    
    remoteDefined = true;

    /* print received message */
    std::cout << "echo from " << inet_ntoa(remoteAddr.sin_addr)
              << " UDP:" << ntohs(remoteAddr.sin_port)
              << ": " << msg << std::endl;
    
    std::istringstream is(std::string(msg, strlen(msg)));
    boost::archive::text_iarchive ia(is);
    ia >> serial;
    return true;
}
Exemple #21
0
int QFile::ungetch( int ch )
{
#if defined(CHECK_STATE)
    if ( !isOpen() ) {				// file not open
	warning( "QFile::ungetch: File not open" );
	return EOF;
    }
    if ( !isReadable() ) {			// reading not permitted
	warning( "QFile::ungetch: Read operation not permitted" );
	return EOF;
    }
#endif
    if ( ch == EOF )				// cannot unget EOF
	return ch;
    if ( isRaw() ) {				// raw file (very inefficient)
	char buf[1];
	at( index-1 );
	buf[0] = ch;
	if ( writeBlock(buf, 1) == 1 )
	    at ( index-1 );
	else
	    ch = EOF;
    } else {					// buffered file
	if ( (ch = ungetc(ch, fh)) != EOF )
	    index--;
	else
	    setStatus( IO_ReadError );
    }
    return ch;
}
Exemple #22
0
void
SecureSocket::secureAccept()
{
	setJob(new TSocketMultiplexerMethodJob<SecureSocket>(
			this, &SecureSocket::serviceAccept,
			getSocket(), isReadable(), isWritable()));
}
Exemple #23
0
int QFile::readBlock( char *p, uint len )
{
#if defined(CHECK_NULL)
    if ( !p )
	warning( "QFile::readBlock: Null pointer error" );
#endif
#if defined(CHECK_STATE)
    if ( !isOpen() ) {				// file not open
	warning( "QFile::readBlock: File not open" );
	return -1;
    }
    if ( !isReadable() ) {			// reading not permitted
	warning( "QFile::readBlock: Read operation not permitted" );
	return -1;
    }
#endif
    int nread;					// number of bytes read
    if ( isRaw() ) {				// raw file
	nread = READ( fd, p, len );
	if ( len && nread <= 0 ) {
	    nread = 0;
	    setStatus(IO_ReadError);
	}
    } else {					// buffered file
	nread = fread( p, 1, len, fh );
	if ( (uint)nread != len ) {
	    if ( ferror( fh ) || nread==0 )
		setStatus(IO_ReadError);
	}
    }
    index += nread;
    return nread;
}
Exemple #24
0
int QFile::readLine( char *p, uint maxlen )
{
    if ( maxlen == 0 )				// application bug?
	return 0;
#if defined(CHECK_STATE)
    CHECK_PTR( p );
    if ( !isOpen() ) {				// file not open
	warning( "QFile::readLine: File not open" );
	return -1;
    }
    if ( !isReadable() ) {			// reading not permitted
	warning( "QFile::readLine: Read operation not permitted" );
	return -1;
    }
#endif
    int nread;					// number of bytes read
    if ( isRaw() ) {				// raw file
	nread = QIODevice::readLine( p, maxlen );
    } else {					// buffered file
	p = fgets( p, maxlen, fh );
	if ( p ) {
	    nread = strlen( p );
	    index += nread;
	} else {
	    nread = -1;
	    setStatus(IO_ReadError);
	}
    }
    return nread;
}
Exemple #25
0
static void print (const char * what, const char * buffer) {
	if (isReadable(buffer)){
		printf ("%s %s\n", what, buffer);
	} else {
		printf ("%s [unreadable]\n", what);
	}
}
void ReadableJSStream::error(JSC::ExecState& state, ExceptionCode& ec)
{
    if (!isReadable()) {
        ec = TypeError;
        return;
    }
    storeError(state, state.argument(0));
}
Exemple #27
0
			const Word &operator[](Word offset) const {
#ifdef R_UM_OPT_ENFORCE_LOWLEV_VALIDITY
				assert(isWithinBounds(offset));
				assert(isReadable());
#endif
		
				return block_[offset];
			}
Exemple #28
0
void Action::onSubProcessOutput()
{
    if ( m_processes.empty() )
        return;

    auto p = m_processes.back();
    if ( p->isReadable() )
        appendOutput( p->readAll() );
}
std::string DiskArbitrationEventPublisher::extractUdifChecksum(
    const std::string& path_str) {
  fs::path path = path_str;
  if (!pathExists(path).ok() || !isReadable(path).ok()) {
    return "";
  }

  boost::system::error_code ec;
  if (!fs::is_regular_file(path, ec) || ec.value() != errc::success) {
    return "";
  }

  // The koly trailer (footer) is 512 bytes
  // http://newosxbook.com/DMG.html
  if (fs::file_size(path) < 512) {
    return "";
  }

  std::ifstream dmg_file(path_str, std::ios::binary);
  if (dmg_file.is_open()) {
    dmg_file.seekg(-512L, std::ios::end);

    char* buffer = new char[4];
    dmg_file.read(buffer, 4);
    std::string koly_signature;
    koly_signature.assign(buffer, 4);
    delete[] buffer;

    // check for valid signature
    if (koly_signature != "koly") {
      dmg_file.close();
      return "";
    }

    uint32_t checksum_size;
    dmg_file.seekg(-156L, std::ios::end);
    dmg_file.read((char*)&checksum_size, sizeof(checksum_size));
    // checksum_size is in big endian and we need to byte swap
    checksum_size = CFSwapInt32(checksum_size);

    dmg_file.seekg(-152L, std::ios::end); // checksum offset
    unsigned char* u_buffer = new unsigned char[checksum_size];
    dmg_file.read((char*)u_buffer, checksum_size);
    // we don't want to byte swap checksum as disk utility/hdiutil doesn't
    std::stringstream checksum;
    for (size_t i = 0; i < checksum_size; i++) {
      if (u_buffer[i] != 0) {
        checksum << std::setw(2) << std::hex << std::uppercase
                 << (unsigned int)u_buffer[i];
      }
    }
    delete[] u_buffer;
    dmg_file.close();
    return checksum.str();
  }
  return "";
}
Exemple #30
0
void receiveDataFromServer(int sd, int flags, int timeOut, char *fileName){
	struct sockaddr_in echoServAddr;
	int echoLen, errorL, receivedCount, headerLength, seqNum, pktMaxNum, n;
	char buffer[PKT_SIZE];
	FILE *fileId;
	//open file to store reveived data
	fileId = fopen(fileName,"w"); // write mode
	if(fileId == NULL){error("Cannot open file on client.\n");}

	//wait for data from server
	while (!isReadable(sd,&errorL,timeOut)) printf(".");
	printf("\n");
	//reveive data from server; store them into buffer
	receivedCount = recvfrom(sd, buffer, PKT_SIZE, flags, (struct sockaddr *) &echoServAddr , &echoLen);
	if(receivedCount<0){error("Client cannot receive data.\n");}
	if(receivedCount>PKT_SIZE){error("Packet size from server is over the limit on client.\n");}
	//parse header
	headerLength = findHeaderLength(buffer, PKT_SIZE);if(headerLength<0){error("Invalid header.\n");}
	errorL = parseHeader(buffer, headerLength, &seqNum, &pktMaxNum);if(errorL < 0){error("Error parsing header.\n");}
	printf("Received packet %d.\n", seqNum);
	while(seqNum<pktMaxNum){
		//write data into file
		n = fwrite(buffer+headerLength, sizeof(char), receivedCount-headerLength, fileId);
		if(n<0){error("Error writing data into file.\n");}
		//wait for data from server
		while (!isReadable(sd,&errorL,timeOut)) printf(".");
		printf("\n");
		//reveive data from server; store them into buffer
		receivedCount = recvfrom(sd, buffer, PKT_SIZE, flags, (struct sockaddr *) &echoServAddr , &echoLen);
		if(receivedCount<0){error("Client cannot receive data.\n");}
		if(receivedCount>PKT_SIZE){error("Packet size from server is over the limit on client.\n");}
		//parse header
		headerLength = findHeaderLength(buffer, PKT_SIZE);if(headerLength<0){error("Invalid header.\n");}
		errorL = parseHeader(buffer, headerLength, &seqNum, &pktMaxNum);if(errorL < 0){error("Error parsing header.\n");}
		printf("Received packet %d.\n", seqNum);		
	}
	//write data into file
	n = fwrite(buffer+headerLength, sizeof(char), receivedCount-headerLength, fileId);
	if(n<0){error("Error writing data into file.\n");}
	//close file
	fclose(fileId);
	printf("Data successfully received.\n");
}