Example #1
0
bool BaseHTTPProtocol::HandleFixedLengthContent(IOBuffer &buffer) {
	//1. Compute the chunk size that we areg going to read
	//which is how many bytes we have available, but no more than _contentLength
	uint32_t chunkSize = GETAVAILABLEBYTESCOUNT(buffer);
	assert(_sessionDecodedBytesCount <= _contentLength);
	uint32_t remaining = _contentLength - _sessionDecodedBytesCount;
	chunkSize = chunkSize > remaining ? remaining : chunkSize;

	//2. Update the session decoded bytes count and decoded bytes count
	_sessionDecodedBytesCount += chunkSize;
	_decodedBytesCount += chunkSize;

	//3. Make the copy and ignore the chunk size
	_inputBuffer.ReadFromBuffer(GETIBPOINTER(buffer), chunkSize);
	buffer.Ignore(chunkSize);

	//3. Call the near protocol
	if (!_pNearProtocol->SignalInputData(_inputBuffer)) {
		FATAL("Unable to call the next protocol in stack");
		return false;
	}

	//4. reset the state if necessary
	if (TransferCompleted()) {
		_headers.Reset();
		_contentLength = 0;
		_chunkedContent = false;
		_lastChunk = false;
		_state = HTTP_STATE_HEADERS;
		_sessionDecodedBytesCount = 0;
	}

	//5. we are done
	return true;
}
bool NATTraversalProtocol::SignalInputData(IOBuffer &buffer, sockaddr_in *pPeerAddress) {
	//FINEST("_inputBuffer:\n%s", STR(buffer));
	buffer.IgnoreAll();
	if (_pOutboundAddress == NULL)
		return true;
	if (_pOutboundAddress->sin_addr.s_addr != pPeerAddress->sin_addr.s_addr) {
		WARN("Attempt to divert traffic. DoS attack!?");
		return true;
	}
	string ipAddress = inet_ntoa(_pOutboundAddress->sin_addr);
	if (_pOutboundAddress->sin_port == pPeerAddress->sin_port) {
		INFO("The client has public endpoint: %s:%"PRIu16,
				STR(ipAddress),
				ENTOHS(_pOutboundAddress->sin_port));
	} else {
		INFO("The client is behind firewall: %s:%"PRIu16" -> %s:%"PRIu16,
				STR(ipAddress),
				ENTOHS(_pOutboundAddress->sin_port),
				STR(ipAddress),
				ENTOHS(pPeerAddress->sin_port));
		_pOutboundAddress->sin_port = pPeerAddress->sin_port;
	}
	_pOutboundAddress = NULL;
	return true;
}
Example #3
0
bool InboundXMLCLIProtocol::SignalInputData(IOBuffer &buffer) {
  //1. Get the buffer and the length
  uint8_t *pBuffer = GETIBPOINTER(buffer);
  uint32_t length = GETAVAILABLEBYTESCOUNT(buffer);
  if (length == 0)
    return true;

  //2. Walk through the buffer and execute the commands
  string command = "";
  for (uint32_t i = 0; i < length; i++) {
    if ((pBuffer[i] == 0x0d) || (pBuffer[i] == 0x0a)) {
      if (command != "") {
        if (!ParseCommand(command)) {
          FATAL("Unable to parse command\n`%s`", STR(command));
          return false;
        }
      }
      command = "";
      buffer.Ignore(i);
      pBuffer = GETIBPOINTER(buffer);
      length = GETAVAILABLEBYTESCOUNT(buffer);
      i = 0;
      continue;
    }
    command += (char) pBuffer[i];
    if (command.length() >= MAX_COMMAND_LENGTH) {
      FATAL("Command too long");
      return false;
    }
  }

  //3. Done
  return true;
}
Example #4
0
void AtomURL::SerializeToBuffer(IOBuffer& data, uint32_t maxFrames) {
  uint32_t start=GETAVAILABLEBYTESCOUNT(data);
  VersionedAtom::SerializeToBuffer(data, maxFrames);
  data.ReadFromString(_location);
  _size=GETAVAILABLEBYTESCOUNT(data)-start;
  *(uint32_t*)(GETIBPOINTER(data)+start) = endianSwap32(_size);
}
Example #5
0
bool TCPCarrier::OnEvent(struct kevent &event) {
    int32_t readAmount = 0;
    int32_t writeAmount = 0;

    //3. Do the I/O
    switch (event.filter) {
    case EVFILT_READ:
    {
        IOBuffer *pInputBuffer = _pProtocol->GetInputBuffer();
        assert(pInputBuffer != NULL);
        if (!pInputBuffer->ReadFromTCPFd(event.ident, event.data, readAmount)) {
            FATAL("Unable to read data. %s:%hu -> %s:%hu",
                  STR(_farIp), _farPort,
                  STR(_nearIp), _nearPort);
            return false;
        }
        _rx += readAmount;
        return _pProtocol->SignalInputData(readAmount);
    }
    case EVFILT_WRITE:
    {
        IOBuffer *pOutputBuffer = NULL;

        if ((pOutputBuffer = _pProtocol->GetOutputBuffer()) != NULL) {
            if (!pOutputBuffer->WriteToTCPFd(event.ident, event.data, writeAmount)) {
                FATAL("Unable to send data. %s:%hu -> %s:%hu",
                      STR(_farIp), _farPort,
                      STR(_nearIp), _nearPort);
                IOHandlerManager::EnqueueForDelete(this);
                return false;
            }
            _tx += writeAmount;
            if (GETAVAILABLEBYTESCOUNT(*pOutputBuffer) == 0) {
                DISABLE_WRITE_DATA;
            }
        } else {
            DISABLE_WRITE_DATA;
        }
        return true;
    }
    default:
    {
        ASSERT("Invalid state: %hd", event.filter);
        return false;
    }
    }
}
bool InboundMJPGHTTPStreamProtocol::SignalInputData(IOBuffer &buffer) {
	//1. Is the stream name acquired?
	if (_streamNameAcquired) {
		buffer.IgnoreAll();
		return true;
	}

	if (!AcquireStreamName(buffer)) {
		FATAL("Unable to get the stream name");
		return false;
	}

	if (!_streamNameAcquired) {
		return true;
	}

	//7. Search for the stream called streamName and pick the first one
	map<uint32_t, BaseStream *> inStreams =
			GetApplication()->GetStreamsManager()->FindByTypeByName(
			ST_IN_CAM_MJPG, _streamName, false, true);
	if (inStreams.size() == 0) {
		if (lowerCase(_streamName) == "crossdomain.xml") {
			return SendCrossDomain();
		} else {
			FATAL("Stream %s not found", STR(_streamName));
			return Send404NotFound();
		}
	}
	BaseInStream *pInStream = (BaseInStream *) MAP_VAL(inStreams.begin());

	//8. Create our raw outbound stream
	_pOutStream = new OutNetMJPGHTTPStream(this,
			GetApplication()->GetStreamsManager(), _streamName);

	//9. Link it to the in stream
	if (!pInStream->Link(_pOutStream)) {
		FATAL("Unable to link to the in stream");
		return false;
	}

	//10. All done. Ignore all the traffic
	buffer.IgnoreAll();

	//11. Done
	return true;
}
Example #7
0
 ReturnCode receive(IOBuffer &buffer)
 {
     MSS_BEGIN(ReturnCode);
     MSS(state == Connected, InvalidState);
     MSS(!buffer.full());
     auto nrReceived = ::recv(fid, buffer.freeData(), buffer.freeSize(), 0);
     MSS(nrReceived != -1, CouldNotReceive);
     if (nrReceived == 0)
     {
         //Peer closed connection
         changeState(Closed);
         MSS_Q(ReturnCode::ConnectionWasClosed);
     }
     else
         MSS(buffer.scrollEnd(nrReceived));
     MSS_END();
 }
Example #8
0
bool InboundHTTP4RTMP::ProcessIdle(vector<string> &parts) {

	BaseProtocol *pProtocol = Bind(parts[2]);
	if (pProtocol == NULL) {
		FATAL("Unable to bind protocol");
		return false;
	}

	_outputBuffer.ReadFromByte(1);
	IOBuffer *pBuffer = pProtocol->GetOutputBuffer();
	if (pBuffer != NULL) {
		_outputBuffer.ReadFromBuffer(GETIBPOINTER(*pBuffer), GETAVAILABLEBYTESCOUNT(*pBuffer));
		pBuffer->IgnoreAll();
	}

	return BaseProtocol::EnqueueForOutbound();
}
Example #9
0
bool StdioCarrier::OnEvent(select_event &event) {
	int32_t recvAmount = 0;

	//3. Do the I/O
	switch (event.type) {
		case SET_READ:
		{
			IOBuffer *pInputBuffer = _pProtocol->GetInputBuffer();
			assert(pInputBuffer != NULL);
			if (!pInputBuffer->ReadFromStdio(_inboundFd,
					FD_READ_CHUNK, recvAmount)) {
				FATAL("Unable to read data");
				return false;
			}

			return _pProtocol->SignalInputData(recvAmount);
		}
		case SET_WRITE:
		{
			IOBuffer *pOutputBuffer = NULL;

			while ((pOutputBuffer = _pProtocol->GetOutputBuffer()) != NULL) {
				if (!pOutputBuffer->WriteToStdio(_outboundFd,
						FD_WRITE_CHUNK)) {
					FATAL("Unable to send data");
					IOHandlerManager::EnqueueForDelete(this);
					return false;
				}
				if (GETAVAILABLEBYTESCOUNT(*pOutputBuffer) > 0) {
					ENABLE_WRITE_DATA;
					break;
				}
			}
			if (pOutputBuffer == NULL) {
				DISABLE_WRITE_DATA;
			}
			return true;
		}
		default:
		{
			ASSERT("Invalid state: %hhu", event.type);
			return false;
		}
	}
}
Example #10
0
static status_t
synchronous_io(io_request* request, DoIO& io)
{
	TRACE_RIO("[%" B_PRId32 "] synchronous_io(request: %p (offset: %" B_PRIdOFF
		", length: %" B_PRIuGENADDR "))\n", find_thread(NULL), request,
		request->Offset(), request->Length());

	IOBuffer* buffer = request->Buffer();

	iovec vector;
	void* virtualVecCookie = NULL;
	off_t offset = request->Offset();
	generic_size_t length = request->Length();

	for (; length > 0
			&& buffer->GetNextVirtualVec(virtualVecCookie, vector) == B_OK;) {
		void* vecBase = (void*)(addr_t)vector.iov_base;
		size_t vecLength = min_c(vector.iov_len, length);

		TRACE_RIO("[%ld]   I/O: offset: %lld, vecBase: %p, length: %lu\n",
			find_thread(NULL), offset, vecBase, vecLength);

		size_t transferred = vecLength;
		status_t error = io.IO(offset, vecBase, &transferred);
		if (error != B_OK) {
			TRACE_RIO("[%ld]   I/O failed: %#lx\n", find_thread(NULL), error);
			buffer->FreeVirtualVecCookie(virtualVecCookie);
			request->SetStatusAndNotify(error);
			return error;
		}

		offset += transferred;
		length -= transferred;

		if (transferred != vecLength)
			break;
	}

	TRACE_RIO("[%ld] synchronous_io() succeeded\n", find_thread(NULL));

	buffer->FreeVirtualVecCookie(virtualVecCookie);
	request->SetTransferredBytes(length > 0, request->Length() - length);
	request->SetStatusAndNotify(B_OK);
	return B_OK;
}
Example #11
0
Error VGA::read(IOBuffer & buffer, Size size, Size offset)
{
    if (offset + size > width * height * sizeof(u16))
    {
        return EFAULT;
    }
    buffer.write(vga + (offset / sizeof(u16)), size);
    return size;
}
Example #12
0
Error VGA::write(IOBuffer & buffer, Size size, Size offset)
{
    if (offset + size > width * height * sizeof(u16))
    {
        return EFAULT;
    }
    memcpy(vga + (offset / sizeof(u16)), buffer.getBuffer(), size);    
    return size;
}
bool OutboundRTMPProtocol::PerformHandshake(IOBuffer &buffer) {
	switch (_rtmpState) {
		case RTMP_STATE_NOT_INITIALIZED:
		{
			_encrypted = (VariantType) _customParameters[CONF_PROTOCOL] == V_STRING &&
					_customParameters[CONF_PROTOCOL] == CONF_PROTOCOL_OUTBOUND_RTMPE;
			_usedScheme = _encrypted ? 1 : 0;

			if ((VariantType) _customParameters[CONF_PROTOCOL] == V_STRING &&
					_customParameters[CONF_PROTOCOL] == CONF_PROTOCOL_OUTBOUND_RTMPE) {
				return PerformHandshakeStage1(true);
			} else {
				return PerformHandshakeStage1(false);
			}
		}
		case RTMP_STATE_CLIENT_REQUEST_SENT:
		{
			if (GETAVAILABLEBYTESCOUNT(buffer) < 3073)
				return true;

			if (!PerformHandshakeStage2(buffer, _encrypted)) {
				FATAL("Unable to handshake");
				return false;
			}

			if (_pFarProtocol != NULL) {
				if (!_pFarProtocol->EnqueueForOutbound()) {
					FATAL("Unable to signal output data");
					return false;
				}
			}

			if (_pKeyIn != NULL && _pKeyOut != NULL) {
				//insert the RTMPE protocol in the current protocol stack
				BaseProtocol *pFarProtocol = GetFarProtocol();
				RTMPEProtocol *pRTMPE = new RTMPEProtocol(_pKeyIn, _pKeyOut,
						GETAVAILABLEBYTESCOUNT(_outputBuffer));
				ResetFarProtocol();
				pFarProtocol->SetNearProtocol(pRTMPE);
				pRTMPE->SetNearProtocol(this);
				//FINEST("New protocol chain: %s", STR(*pFarProtocol));
			}

			if (!buffer.Ignore(3073)) {
				FATAL("Unable to ignore 3073 bytes");
				return false;
			}
			_handshakeCompleted = true;
			return true;
		}
		default:
		{
			FATAL("Invalid RTMP state: %d", _rtmpState);
			return false;
		}
	}
}
// prepends the headers to the buffer for a http resonse.
IOBuffer ofxAMFHTTPResponse::createHTTPResponse(IOBuffer& buffer) {
	IOBuffer http_buffer;
	http_buffer.setup(buffer.getNumBytesStored());
	http_buffer.storeString("HTTP/1.1 200 OK\r\n");

	stringstream ss;
	ss << "Content-Length: " << buffer.getNumBytesStored() << "\r\n";
	http_buffer.storeString(ss.str());
	
	http_buffer.storeString("Connection: close\r\n");
	http_buffer.storeString("Content-type: application/x-amf\r\n");
	http_buffer.storeString("\r\n");
	
	http_buffer.storeBuffer(buffer);
	return http_buffer;

	
}
Example #15
0
bool InFileRTMPStream::MP3Builder::BuildFrame(MediaFile *pFile,
		MediaFrame &mediaFrame, IOBuffer &buffer) {
	buffer.ReadFromRepeat(0x2f, 1);

	//2. Seek into the data file at the correct position
	if (!pFile->SeekTo(mediaFrame.start)) {
		FATAL("Unable to seek to position %"PRIu64, mediaFrame.start);
		return false;
	}

	//3. Read the data
	if (!buffer.ReadFromFs(*pFile, (uint32_t) mediaFrame.length)) {
		FATAL("Unable to read %"PRIu64" bytes from offset %"PRIu64, mediaFrame.length, mediaFrame.start);
		return false;
	}

	return true;
}
Example #16
0
bool AMF0Serializer::ReadObject(IOBuffer &buffer, Variant &variant,
		bool readType) {
	if (readType) {
		AMF_CHECK_BOUNDARIES(buffer, 1);
		if (GETIBPOINTER(buffer)[0] != AMF0_OBJECT) {
			FATAL("AMF type not valid: want: %"PRIu8"; got: %"PRIu8,
					AMF0_OBJECT, GETIBPOINTER(buffer)[0]);
			return false;
		}

		if (!buffer.Ignore(1)) {
			FATAL("Unable to ignore 1 bytes");
			return false;
		}
	}

	AMF_CHECK_BOUNDARIES(buffer, 3);
	while (!((GETIBPOINTER(buffer)[0] == 0) && (GETIBPOINTER(buffer)[1] == 0) && (GETIBPOINTER(buffer)[2] == 9))) {
		Variant key;
		Variant value;
		if (!ReadShortString(buffer, key, false)) {
			FATAL("Unable to read key");
			return false;
		}
		if (!Read(buffer, value)) {
			FATAL("Unable to read value");
			return false;
		}
		variant[key] = value;
	}

	AMF_CHECK_BOUNDARIES(buffer, 3);
	if (!buffer.Ignore(3)) {
		FATAL("Unable to ignore 3 bytes");
		return false;
	}

	variant.IsArray(false);

	return true;
}
int IOBuffer::storeBuffer(IOBuffer& other, rx_uint32 numBytes) {
	// check if we can read this many bytes from other buffer.
	numBytes = other.getMostNumberOfBytesWeCanConsume(numBytes);
	if(numBytes == 0) {
		return 0;
	}
	ensureSize(numBytes);
	memcpy(buffer+published, other.buffer+other.consumed, numBytes);
	published += numBytes;
	other.published += numBytes;
	return numBytes;
}
Example #18
0
void AtomMVHD::SerializeToBuffer(IOBuffer& data, uint32_t maxFrames) {
  uint32_t start=GETAVAILABLEBYTESCOUNT(data);
  VersionedAtom::SerializeToBuffer(data, maxFrames);
  data.ReadFromDataType<uint32_t>(endianSwap32(_creationTime));
  data.ReadFromDataType<uint32_t>(endianSwap32(_modificationTime));
  data.ReadFromDataType<uint32_t>(endianSwap32(_timeScale));
  _offset=GETAVAILABLEBYTESCOUNT(data);
  data.ReadFromDataType<uint32_t>(endianSwap32(_duration));
  data.ReadFromDataType<uint32_t>(endianSwap32(_preferredRate));
  data.ReadFromDataType<uint16_t>(endianSwap16(_preferredVolume));
  data.ReadFromBuffer(_reserved, sizeof(_reserved));
  for (uint32_t i=0; i<9; i++) 
    data.ReadFromDataType<uint32_t>(endianSwap32(_matrixStructure[i]));
  for (uint32_t i=0; i<6; i++) {
    data.ReadFromRepeat(0x00, 4);
  }
  data.ReadFromDataType<uint32_t>(endianSwap32(_nextTrakId));
  _size=GETAVAILABLEBYTESCOUNT(data)-start;

  *(uint32_t*)(GETIBPOINTER(data)+start) = endianSwap32(_size);
}
Example #19
0
  void test_io_read_into_buffer() {
    int fds[2];
    TS_ASSERT(!pipe(fds));

    TestChannelObject chan(state);
    event::Read* read = new event::Read(state, &chan, fds[0]);
    
    IOBuffer *buf = IOBuffer::create(state, 12);
    read->into_buffer(buf, 1);
    TS_ASSERT_EQUALS(buf->used(), Fixnum::from(0));
    TS_ASSERT_EQUALS(buf->start(), Fixnum::from(0));

    state->events->start(read);
    TS_ASSERT(!chan.called);
    state->events->poll();
    TS_ASSERT(!chan.called);
    
    /* Write some garbage into the buffer to be sure it's overridden */
    char* str = buf->byte_address();
    str[0] = str[1] = 47;

    TS_ASSERT_EQUALS(write(fds[1], "!", 1),1);
    state->events->poll();
    TS_ASSERT(chan.called);
    TS_ASSERT_EQUALS(chan.value, Fixnum::from(1));
    TS_ASSERT_EQUALS(buf->used(), Fixnum::from(1));
    TS_ASSERT_EQUALS(buf->start(), Fixnum::from(0));

    TS_ASSERT_EQUALS(str[0], '!');
    TS_ASSERT_EQUALS(str[1], 0);
    
    close(fds[0]);
    close(fds[1]);
  }
bool UXDomainSocketAppProtocolHandler::EventSocket(UnixDomainSocketProtocol *pFrom, IOBuffer &buffer) {
  uint32_t buflen = GETAVAILABLEBYTESCOUNT(buffer);

  while (buflen>=16) {
    uint8_t* pBuf=GETIBPOINTER(buffer);

    CHK_ALIGN4(pBuf);
    uint32_t msglen=*((uint32_t*)(pBuf+12));
    uint32_t total = PADDED_TOTAL(msglen+16);
    string data;

    if (buflen < total) {
      break;
    }
    uint16_t type=*((uint16_t*)(pBuf));
    uint32_t subType=*((uint16_t*)(pBuf+2));
    uint64_t eventInfo=0;

    DEBUG ("type:%d, subtype:%d", type, subType);
    //message has data
    if (msglen) {
      string temp((char*)(pBuf+16), msglen);
      data=temp;
    }
    QICStreamerApplication *pApp=
        static_cast<QICStreamerApplication*>(GetApplication());

    switch (type) {
      case (CLOUD_MSG_ERROR):
        pApp->SendError(subType, data);
        HardwareManager::SetStatus(subType, false);
        break;
      case (CLOUD_MSG_EVENT):
        eventInfo=*((uint64_t*)(pBuf+4));
        pApp->SendEvent(subType, eventInfo, data);
        break;
      case (DEVICE_EVENT):
        {
          RestCLIMessage restMessage;
          uint32_t start=0;
          ActionRouter *pActionRouter=pApp->GetActionRouter();
          Variant::DeserializeFromJSON(data, restMessage.request, start);
          pActionRouter->RouteRequestAction(restMessage);
        }
        break;
    }
    buffer.Ignore(total);
    buflen = GETAVAILABLEBYTESCOUNT(buffer);
  }

  return true;
}
Example #21
0
  void test_create_buffer() {
    IOBuffer* buf = IOBuffer::create(state, 10);
    Fixnum* zero = Fixnum::from(0);

    TS_ASSERT_EQUALS(zero, buf->start());
    TS_ASSERT_EQUALS(zero, buf->used());
    TS_ASSERT_EQUALS(Fixnum::from(10), buf->total());
    TS_ASSERT_EQUALS(10U, buf->left());
    TS_ASSERT(kind_of<Channel>(buf->channel()));
    TS_ASSERT_EQUALS(Qfalse, buf->eof());
  }
Example #22
0
bool BaseSSLProtocol::EnqueueForOutbound() {
	//1. Is the SSL handshake completed?
	if (!_sslHandshakeCompleted) {
		return DoHandshake();
	}

	//2. Do we have some outstanding data?
	IOBuffer *pBuffer = _pNearProtocol->GetOutputBuffer();
	if (pBuffer == NULL)
		return true;

	//3. Encrypt the outstanding data
	if (SSL_write(_pSSL, GETIBPOINTER(*pBuffer), GETAVAILABLEBYTESCOUNT(*pBuffer))
			!= (int32_t) GETAVAILABLEBYTESCOUNT(*pBuffer)) {
		FATAL("Unable to write %u bytes", GETAVAILABLEBYTESCOUNT(*pBuffer));
		return false;
	}
	pBuffer->IgnoreAll();

	//4. Do the actual I/O
	return PerformIO();
}
Example #23
0
bool InFileRTMPStream::AACBuilder::BuildFrame(MediaFile* pFile, MediaFrame& mediaFrame, IOBuffer& buffer) {
	//1. add the binary header
	if (mediaFrame.isBinaryHeader) {
		buffer.ReadFromBuffer(_audioCodecHeaderInit, sizeof (_audioCodecHeaderInit));
	} else {
		buffer.ReadFromBuffer(_audioCodecHeader, sizeof (_audioCodecHeader));
	}

	//2. Seek into the data file at the correct position
	if (!pFile->SeekTo(mediaFrame.start)) {
		FATAL("Unable to seek to position %"PRIu64, mediaFrame.start);
		return false;
	}

	//3. Read the data
	if (!buffer.ReadFromFs(*pFile, (uint32_t) mediaFrame.length)) {
		FATAL("Unable to read %"PRIu64" bytes from offset %"PRIu64, mediaFrame.length, mediaFrame.start);
		return false;
	}

	return true;
}
Example #24
0
Error LinnDirectory::read(IOBuffer & buffer, Size size, Size offset)
{
    LinnSuperBlock *sb = fs->getSuperBlock();
    LinnDirectoryEntry dent;
    LinnInode *dInode;
    Size bytes = ZERO, blk;
    Error e;
    Dirent tmp;

    /* Read directory entries. */
    for (u32 ent = 0; ent < inode->size / sizeof(LinnDirectoryEntry); ent++)
    {
	/* Point to correct (direct) block. */
	if ((blk = (ent * sizeof(LinnDirectoryEntry)) / sb->blockSize)
	     >= LINN_INODE_DIR_BLOCKS)
	{
	    break;
	}
	/* Calculate offset to read. */
	u64 off = (inode->block[blk] * sb->blockSize) +
	    	  (ent * sizeof(LinnDirectoryEntry));

	/* Get the next entry. */
	if (fs->getStorage()->read(off, &dent,
			           sizeof(LinnDirectoryEntry)) < 0)
	{
	    return EACCES;
	}
	/* Can we read another entry? */
        if (bytes + sizeof(Dirent) > size)
        {
	    return EFAULT;
	}
	/* Fill in the Dirent. */
	if (!(dInode = fs->getInode(dent.inode)))
	{
	    return EINVAL;
	}
	strlcpy(tmp.name, dent.name, LINN_DIRENT_NAME_LEN);
	tmp.type = (FileType) dInode->type;

	/* Copy to the buffer. */
	if (( e = buffer.write(&tmp, sizeof(Dirent), bytes)) < 0)
	{
	    return e;
	}
	bytes += sizeof(Dirent);
    }
    /* All done. */
    return bytes;
}
Example #25
0
bool TSDocument::ParseDocument() {
	if (!DetermineChunkSize()) {
		FATAL("Unable to determine chunk size");
		return false;
	}

	if (!_mediaFile.SeekTo(_chunkSizeDetectionCount)) {
		FATAL("Unable to seek at %"PRIu32, _chunkSizeDetectionCount);
		return false;
	}

	_pParser->SetChunkSize(_chunkSize);

	IOBuffer buffer;
	uint32_t defaultBlockSize = ((1024 * 1024 * 4) / _chunkSize) * _chunkSize;

	while (!_chunkSizeErrors) {
		uint32_t available = (uint32_t) (_mediaFile.Size() - _mediaFile.Cursor());
		if (available < _chunkSize) {
			break;
		}
		if (GETAVAILABLEBYTESCOUNT(buffer) != 0) {
			WARN("Leftovers detected");
			break;
		}
		uint32_t blockSize = defaultBlockSize < available ? defaultBlockSize : available;
		buffer.MoveData();
		if (!buffer.ReadFromFs(_mediaFile, blockSize)) {
			WARN("Unable to read %"PRIu32" bytes from file", blockSize);
			break;
		}
		if (!_pParser->ProcessBuffer(buffer, false)) {
			WARN("Unable to process block of data");
			break;
		}
	}
	return true;
}
Example #26
0
Error i8250::read(IOBuffer & buffer, Size size, Size offset)
{
    Size bytes = 0;
    u8 byte;
    
    /* Read as much bytes as possible. */
    while (ReadByte(base + LINESTATUS) & RXREADY && bytes < size)
    {
        byte = ReadByte(base);
        buffer.bufferedWrite(&byte, 1);
        bytes++;
    }
    return bytes ? (Error) bytes : EAGAIN;
}
Example #27
0
bool BaseSSLProtocol::SignalInputData(IOBuffer &buffer) {

	//1. get the SSL input buffer
	BIO *pInBio = SSL_get_rbio(_pSSL);

	//2. dump all the data from the network inside the ssl input
	BIO_write(pInBio, GETIBPOINTER(buffer),
			GETAVAILABLEBYTESCOUNT(buffer));
	buffer.IgnoreAll();

	//3. Do we have to do some handshake?
	if (!_sslHandshakeCompleted) {
		if (!DoHandshake()) {
			FATAL("Unable to do the SSL handshake");
			return false;
		}
		if (!_sslHandshakeCompleted) {
			return true;
		}
	}

	//4. Read the actual data an put it in the descrypted input buffer
	int32_t read = 0;
	while ((read = SSL_read(_pSSL, _pReadBuffer, MAX_SSL_READ_BUFFER)) > 0) {
		_inputBuffer.ReadFromBuffer(_pReadBuffer, (uint32_t) read);
	}
	if (read < 0) {
		int32_t error = SSL_get_error(_pSSL, read);
		if (error != SSL_ERROR_WANT_READ &&
				error != SSL_ERROR_WANT_WRITE) {
			FATAL("Unable to read data: %d", error);
			return false;
		}
	}

	//6. If we have pending data inside the decrypted buffer, bubble it up on the protocol stack
	if (GETAVAILABLEBYTESCOUNT(_inputBuffer) > 0) {
		if (_pNearProtocol != NULL) {
			if (!_pNearProtocol->SignalInputData(_inputBuffer)) {
				FATAL("Unable to signal near protocol for new data");
				return false;
			}
		}
	}

	//7. After the data was sent on the upper layers, we might have outstanding
	//data that needs to be sent.
	return PerformIO();
}
Example #28
0
bool StreamCapabilities::Deserialize(IOBuffer &src, StreamCapabilities &capabilities) {
	uint8_t *pBuffer = GETIBPOINTER(src);
	uint32_t length = GETAVAILABLEBYTESCOUNT(src);
	if (length < 28) {
		FATAL("Not enough data");
		return false;
	}
	uint64_t ver = ENTOHLLP(pBuffer);
	if (ver != __STREAM_CAPABILITIES_VERSION) {
		FATAL("Invalid stream capabilities version. Wanted: %"PRIu64"; Got: %"PRIu64,
				__STREAM_CAPABILITIES_VERSION, ver);
		return false;
	}
	capabilities.Clear();
	capabilities.videoCodecId = ENTOHLLP(pBuffer + 8);
	capabilities.audioCodecId = ENTOHLLP(pBuffer + 16);
	capabilities.bandwidthHint = ENTOHLP(pBuffer + 24);
	src.Ignore(28);
	switch (capabilities.videoCodecId) {
		case CODEC_VIDEO_AVC:
		{
			if (!_VIDEO_AVC::Deserialize(src, capabilities.avc)) {
				FATAL("Unable to deserialize avc");
				return false;
			}
			break;
		}
		default:
		{
			break;
		}
	}
	switch (capabilities.audioCodecId) {
		case CODEC_AUDIO_AAC:
		{
			if (!_AUDIO_AAC::Deserialize(src, capabilities.aac)) {
				FATAL("Unable to deserialize aac");
				return false;
			}
			break;
		}
		default:
		{
			break;
		}
	}
	return true;
}
bool InFileRTMPFLVStream::BuildFrame(FileClass *pFile, MediaFrame &mediaFrame,
		IOBuffer &buffer) {
	//1. Seek into the data file at the correct position
	if (!pFile->SeekTo(mediaFrame.start)) {
		FATAL("Unable to seek to position %"PRIu64, mediaFrame.start);
		return false;
	}

	//2. Read the data
	if (!buffer.ReadFromFs(*pFile, (uint32_t) mediaFrame.length)) {
		FATAL("Unable to read %"PRIu64" bytes from offset %"PRIu64, mediaFrame.length, mediaFrame.start);
		return false;
	}

	//3. Done
	return true;
}
bool UXDomainSocketAppProtocolHandler::IpcEventSocket(UnixDomainSocketProtocol *pFrom, IOBuffer &buffer) {
    uint32_t length = GETAVAILABLEBYTESCOUNT(buffer);
    uint8_t *pBuf = GETIBPOINTER(buffer);
    BaseAVCVideoCapture *_pAVCCaptureInstance;

    _pAVCCaptureInstance = reinterpret_cast<BaseAVCVideoCapture *>(HardwareManager::GetHardwareInstance(HT_VIDEO_AVC));

    printf ("buf length (%d): %s\n", length, pBuf);
    buffer.Ignore(length);

    _pAVCCaptureInstance->VerifyResolution(640,360);
    _pAVCCaptureInstance->SetResolution(640,360);

    UnixDomainSocketManager::SendResponseToIpcEvent ("2");

    return true;
}