Пример #1
0
Object * Object::Parse(Context * ctx){
    Object * ret = NULL;
    Header hdr;
    hdr.Read(ctx);
    if(hdr.GetFlag() == FLAG_ARRAY){
        NativeType type = hdr.GetType();
        if(type!=0){
            int64_t count = hdr.GetLength() / Native::SizeForNative(type);
            Array * array = Array::WithType(type,(uint32_t)count);
            dynamic_cast<Object*>(array)->Read(hdr, ctx);
            ret = array;
        }else{
            Array * array = Array::WithCapacity();
            dynamic_cast<Object*>(array)->Read(hdr, ctx);
            ret = array;
        }
    }else if(hdr.GetFlag() == FLAG_MAP){
        Map * obj = new Map();
        dynamic_cast<Object*>(obj)->Read(hdr, ctx);
        ret = obj;
    }else if(hdr.GetFlag() == FLAG_OBJECT){
        Native * obj = new Native();
        dynamic_cast<Object*>(obj)->Read(hdr, ctx);
        ret = obj;
    }
    return ret;
}
Пример #2
0
void Map::Read(const Header & hdr,Context * ctx){
    header = hdr;
    uint64_t ref = ctx->Tell();
    while( (ctx->Tell() - ref) < header.GetLength()){
        
        Header kh;
        kh.Read(ctx);
        
        if(kh.GetType() == TYPE_STRING){
            Native * native = new Native();
            dynamic_cast<Object*>(native)->Read(kh,ctx);
            
            if(native->GetString().size()>0){
                Object * obj = Object::Parse(ctx);
                map.insert(std::pair<std::string,Object*>(native->GetString(),obj));
                delete native;
            }
        }else{
            throw EXCEPTION_WRONG_TYPE;
        }
    }
}
Пример #3
0
void
TarExtractor::Extract (/*[in]*/ Stream *		pStreamIn_,
		       /*[in]*/ const PathName &	destDir,
		       /*[in]*/ bool			makeDirectories,
		       /*[in]*/ IExtractCallback *	pCallback,
		       /*[in]*/ const char *		lpszPrefix)
{
  try
    {
      pStreamIn = pStreamIn_;
      totalBytesRead = 0;

      traceStream->WriteFormattedLine ("libextractor",
				       T_("extracting to %s (%s)"),
				       Q_(destDir),
				       (makeDirectories
					? T_("make directories")
					: T_("don't make directories")));

      size_t len;
      Header header;
      size_t prefixLen = (lpszPrefix == 0 ? 0 : StrLen(lpszPrefix));
      unsigned fileCount = 0;
  
      bool checkHeader = true;
  
      CharBuffer<char> buffer;
      buffer.Reserve (1024 * 1024);

      while ((len = Read(&header, sizeof(header))) > 0)
	{
	  // read next header
	  if (len != sizeof(header))
	    {
	      FATAL_EXTRACTOR_ERROR
		("TarExtractor::Extract",
		 T_("Invalid package archive file."),
		 0);
	    }
      
	  if (header.IsEndOfArchive())
	    {
	      break;
	    }
      
	  if (checkHeader)
	    {
	      if (! header.Check())
		{
		  FATAL_EXTRACTOR_ERROR
		    ("TarExtractor::Extract",
		     T_("Invalid package archive file."),
		     0);
		}
#if ! defined(MIKTEX_DEBUG)
	      checkHeader = false;
#endif
	    }
      
	  PathName dest = header.GetFileName();
	  size_t size = header.GetFileSize();
      
	  if (! header.IsNormalFile())
	    {
	      if (header.GetType() == Header::LongName)
		{
		  if (size >= BLOCKSIZE)
		    {
		      UNEXPECTED_CONDITION ("TarExtractor::Extract");
		    }
		  char longNameData[BLOCKSIZE];
		  ReadBlock (longNameData);
		  longNameData[size] = 0;
		  longName = longNameData;
		  haveLongName = true;
		}
	      else
		{
		  Skip (((size + sizeof(Header) - 1) / sizeof(Header))
			* sizeof(Header));
		}
	      continue;
	    }

	  if (haveLongName)
	    {
	      dest = longName;
	      haveLongName = false;
	    }
      
	  // skip directory prefix
	  if (lpszPrefix != 0
	      && PathName::Compare(lpszPrefix, dest, prefixLen) == 0)
	    {
	      PathName tmp (dest);
	      dest = tmp.Get() + prefixLen;
	    }
      
	  // make the destination path name
	  PathName path (destDir);
	  if (! makeDirectories)
	    {
	      dest.RemoveDirectorySpec ();
	    }
	  path += dest;
      
	  // notify the client
	  if (pCallback != 0)
	    {
	      pCallback->OnBeginFileExtraction (path.Get(), size);
	    }
      
	  // create the destination directory
	  Directory::Create (PathName(path).RemoveFileSpec());
      
	  // remove the existing file
	  if (File::Exists(path))
	    {
	      File::Delete (path, true);
	    }
      
	  // extract the file
	  FileStream streamOut (File::Open(path,
					   FileMode::Create,
					   FileAccess::Write,
					   false));
	  size_t bytesRead = 0;
	  while (bytesRead < size)
	  {
	    size_t remaining = size - bytesRead;
	    size_t n = (remaining > buffer.GetCapacity() ? buffer.GetCapacity() : remaining);
	    if (Read(buffer.GetBuffer(), n) != n)
	    {
	      FATAL_EXTRACTOR_ERROR ("TarExtractor::Extract",
		T_("Invalid package archive file."),
		0);
	    }
	    streamOut.Write (buffer.Get(), n);
	    bytesRead += n;
	  }
	  streamOut.Close ();

	  // skip extra bytes
	  if (bytesRead % sizeof(Header) > 0)
	    {
	      Skip (sizeof(Header) - bytesRead % sizeof(Header));
	    }
      
	  fileCount += 1;
      
	  // set time when the file was created
	  time_t time = header.GetLastModificationTime();
	  File::SetTimes (path, time, time, time);
      
#if 0
	  // set file attributes
	  File::SetAttributes (path, todo);
#endif
      
	  // notify the client
	  if (pCallback != 0)
	    {
	      pCallback->OnEndFileExtraction (0, size);
	    }
	}
  
      traceStream->WriteFormattedLine ("libextractor",
				       T_("extracted %u file(s)"),
				       fileCount);
    }
  catch (const exception &)
    {
      traceStream->WriteFormattedLine
	("libextractor",
	 T_("%u bytes were read from the tar stream"),
	 static_cast<unsigned>(totalBytesRead));
      throw;
    }
}
Пример #4
0
void Client::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
    Header responseHeader;
    Header requestHeader;
    RequestMetadata requestMetadata;
    Message *message = NULL;
    ThreadError error;

    SuccessOrExit(error = responseHeader.FromMessage(aMessage));
    aMessage.MoveOffset(responseHeader.GetLength());

    message = FindRelatedRequest(responseHeader, aMessageInfo, requestHeader, requestMetadata);

    if (message == NULL)
    {
        ExitNow();
    }

    switch (responseHeader.GetType())
    {
    case kCoapTypeReset:
        if (responseHeader.IsEmpty())
        {
            FinalizeCoapTransaction(*message, requestMetadata, NULL, NULL, kThreadError_Abort);
        }

        // Silently ignore non-empty reset messages (RFC 7252, p. 4.2).
        break;

    case kCoapTypeAcknowledgment:
        if (responseHeader.IsEmpty())
        {
            // Empty acknowledgment.
            if (requestMetadata.mConfirmable)
            {
                requestMetadata.mAcknowledged = true;
                requestMetadata.UpdateIn(*message);
            }

            // Remove the message if response is not expected, otherwise await response.
            if (requestMetadata.mResponseHandler == NULL)
            {
                DequeueMessage(*message);
            }
        }
        else if (responseHeader.IsResponse() && responseHeader.IsTokenEqual(requestHeader))
        {
            // Piggybacked response.
            FinalizeCoapTransaction(*message, requestMetadata, &responseHeader, &aMessage, kThreadError_None);
        }

        // Silently ignore acknowledgments carrying requests (RFC 7252, p. 4.2)
        // or with no token match (RFC 7252, p. 5.3.2)
        break;

    case kCoapTypeConfirmable:
    case kCoapTypeNonConfirmable:
        if (responseHeader.IsConfirmable())
        {
            // Send empty ACK if it is a CON message.
            SendEmptyAck(aMessageInfo.GetPeerAddr(), aMessageInfo.mPeerPort, responseHeader.GetMessageId());
        }

        FinalizeCoapTransaction(*message, requestMetadata, &responseHeader, &aMessage, kThreadError_None);

        break;
    }

exit:

    if (error == kThreadError_None && message == NULL)
    {
        if (responseHeader.IsConfirmable() || responseHeader.IsNonConfirmable())
        {
            // Successfully parsed a header but no matching request was found - reject the message by sending reset.
            SendReset(aMessageInfo.GetPeerAddr(), aMessageInfo.mPeerPort, responseHeader.GetMessageId());
        }
    }
}