Example #1
0
		void Connection::DoRead()
		{
			auto self(shared_from_this());
			m_Socket.async_read_some(boost::asio::buffer(m_Buffer),
				[this, self](boost::system::error_code ec, std::size_t bytes_transferred)
			{
				if (!ec)
				{
					request_parser::result_type result;
					std::tie(result, std::ignore) = m_RequestParser.parse(
						m_Request, m_Buffer.data(), m_Buffer.data() + bytes_transferred);

					if (result == request_parser::good)
					{
						m_RequestHandler.HandleRequest(m_Request, m_Reply);
						DoWrite();
					}
					else if (result == request_parser::bad)
					{
						m_Reply = Reply::StockReply(Reply::ST_BAD_REQUEST);
						DoWrite();
					}
					else
					{
						DoRead();
					}
				}
				else if (ec != boost::asio::error::operation_aborted)
				{
					m_ConnectionManager.Stop(shared_from_this());
				}
			});
		}
Example #2
0
bool CIOThread::WriteToFile(char* pBuffer, int64_t len)
{
#ifdef SIMULATE_IO
	return true;
#endif
	// In binary mode, no conversion has to be done.
	// Also, under Windows the native newline format is already identical
	// to the newline format of the FTP protocol
#ifndef FZ_WINDOWS
	if (m_binary) {
#endif
		return DoWrite(pBuffer, len);
#ifndef FZ_WINDOWS
	}
	else {

		// On all CRLF pairs, omit the CR. Don't harm stand-alone CRs

		// Handle trailing CR from last write
		if (m_wasCarriageReturn && len && *pBuffer != '\n' && *pBuffer != '\r') {
			m_wasCarriageReturn = false;
			const char CR = '\r';
			if (!DoWrite(&CR, 1))
				return false;
		}

		// Skip forward to end of buffer or first CR
		const char* r = pBuffer;
		const char* const end = pBuffer + len;
		while (r != end && *r != '\r') {
			++r;
		}

		if (r != end) {
			// Now we gotta move data and also handle additional CRs.
			m_wasCarriageReturn = true;

			char* w = const_cast<char*>(r++);
			for (; r != end; ++r) {
				if (*r == '\r') {
					m_wasCarriageReturn = true;
				}
				else if (*r == '\n') {
					m_wasCarriageReturn = false;
					*(w++) = *r;
				}
				else {
					if (m_wasCarriageReturn) {
						m_wasCarriageReturn = false;
						*(w++) = '\r';
					}
					*(w++) = *r;
				}
			}
			len = w - pBuffer;
		}
		return DoWrite(pBuffer, len);
	}
#endif
}
Example #3
0
/*********************************************************************
 * Function:        XEE_RESULT XEEWrite(BYTE val)
 *
 * PreCondition:    XEEInit() && XEEBeginWrite() are already called.
 *
 * Input:           val - Byte to be written
 *
 * Output:          XEE_SUCCESS
 *
 * Side Effects:    None
 *
 * Overview:        Writes a byte to the write cache, and if full, 
 *					commits the write.  Also, if a write boundary is 
 *					reached the write is committed.  When finished 
 *					writing, XEEEndWrite() must be called to commit 
 *					any unwritten bytes from the write cache.
 *
 * Note:            None
 ********************************************************************/
XEE_RESULT XEEWrite(BYTE val)
{
	EEPROMBuffer[vBytesInBuffer++] = val;
	if(vBytesInBuffer >= sizeof(EEPROMBuffer))
		DoWrite();
	else if((((BYTE)EEPROMAddress + vBytesInBuffer) & (EEPROM_PAGE_SIZE-1)) == 0u)
		DoWrite();

    return XEE_SUCCESS;
}
Example #4
0
void CodeWriter::Write( wxString code )
{
	if ( m_cols == 0 )
	{
		// Inserting indents
		for ( int i = 0; i < m_indent; i++ )
		{
			DoWrite( m_indent_with_spaces ? wxT("    ") :  wxT("\t") );
		}

		m_cols = m_indent;
	}

	DoWrite( code );
}
Example #5
0
/*********************************************************************
 * Function:        XEE_RESULT XEEEndWrite(void)
 *
 * PreCondition:    XEEInit() && XEEBeginWrite() are already called.
 *
 * Input:           None
 *
 * Output:          XEE_SUCCESS
 *
 * Side Effects:    None
 *
 * Overview:        Commits any last uncommitted bytes in cache to 
 *					physical storage.
 *
 * Note:            Call this function when you no longer need to 
 *					write any more bytes at the selected address.
 ********************************************************************/
XEE_RESULT XEEEndWrite(void)
{
	if(vBytesInBuffer)
		DoWrite();

    return XEE_SUCCESS;
}
Example #6
0
void TreeSocket::SendError(const std::string &errormessage)
{
	WriteLine("ERROR :"+errormessage);
	DoWrite();
	LinkState = DYING;
	SetError(errormessage);
}
//
// DTrkXtiChannel::DoControl
//
TInt DTrkXtiChannel::DoControl(TInt aFunction, TAny* a1, TAny* a2)
{
	LOG_MSG("DTrkXtiChannel::DoControl()");
	
	TInt err = KErrNone;
	
	switch(aFunction)
	{
		case RTrkXtiDriver::EControlWrite:
		{
			//lock the Semaphore so that write doesn't happen when a write is already in progress.
			Kern::SemaphoreWait(*iLock);
			err = DoWrite((TUint32)a1, a2);			
			Kern::SemaphoreSignal(*iLock);			
			break;
		}
		default:
		{
			return KErrGeneral;
		}

	}
	if (KErrNone != err)
	{
		LOG_MSG2("Error %d from control function", err);
	}
	return err;
}
Example #8
0
void StreamSocket::Close()
{
	if (this->fd > -1)
	{
		// final chance, dump as much of the sendq as we can
		DoWrite();
		if (GetIOHook())
		{
			try
			{
				GetIOHook()->OnStreamSocketClose(this);
			}
			catch (CoreException& modexcept)
			{
				ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "%s threw an exception: %s",
					modexcept.GetSource(), modexcept.GetReason());
			}
			DelIOHook();
		}
		ServerInstance->SE->Shutdown(this, 2);
		ServerInstance->SE->DelFd(this);
		ServerInstance->SE->Close(this);
		fd = -1;
	}
}
Example #9
0
bool CIOThread::WriteToFile(char* pBuffer, int len)
{
	// In binary mode, no conversion has to be done.
	// Also, under Windows the native newline format is already identical
	// to the newline format of the FTP protocol
#ifndef __WXMSW__
	if (m_binary)
	{
#endif
		return DoWrite(pBuffer, len);
#ifndef __WXMSW__
	}
	else
	{
		// On all CRLF pairs, omit the CR. Don't harm stand-alone CRs
		// I assume disk access is buffered, otherwise the 1 byte writes are
		// going to hurt performance.
		const char CR = '\r';
		const char* const end = pBuffer + len;
		for (char* r = pBuffer; r != end; r++)
		{
			char c = *r;
			if (c == '\r')
				m_wasCarriageReturn = true;
			else if (c == '\n')
			{
				m_wasCarriageReturn = false;
				if (!DoWrite(&c, 1))
					return false;
			}
			else
			{
				if (m_wasCarriageReturn)
				{
					m_wasCarriageReturn = false;
					if (!DoWrite(&CR, 1))
						return false;
				}

				if (!DoWrite(&c, 1))
					return false;
			}
		}
		return true;
	}
#endif
}
Example #10
0
/*----------------------------------------------------------------------
|       AP4_RtpConstructor::Write
+---------------------------------------------------------------------*/
AP4_Result
AP4_RtpConstructor::Write(AP4_ByteStream& stream)
{
    AP4_Result result = stream.WriteUI08(m_Type);
    if (AP4_FAILED(result)) return result;

    return DoWrite(stream);
}
Example #11
0
void StreamSocket::HandleEvent(EventType et, int errornum)
{
	if (!error.empty())
		return;
	BufferedSocketError errcode = I_ERR_OTHER;
	try {
		switch (et)
		{
			case EVENT_ERROR:
			{
				if (errornum == 0)
					SetError("Connection closed");
				else
					SetError(SocketEngine::GetError(errornum));
				switch (errornum)
				{
					case ETIMEDOUT:
						errcode = I_ERR_TIMEOUT;
						break;
					case ECONNREFUSED:
					case 0:
						errcode = I_ERR_CONNECT;
						break;
					case EADDRINUSE:
						errcode = I_ERR_BIND;
						break;
					case EPIPE:
					case EIO:
						errcode = I_ERR_WRITE;
						break;
				}
				break;
			}
			case EVENT_READ:
			{
				DoRead();
				break;
			}
			case EVENT_WRITE:
			{
				DoWrite();
				break;
			}
		}
	}
	catch (CoreException& ex)
	{
		ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Caught exception in socket processing on FD %d - '%s'",
			fd, ex.GetReason().c_str());
		SetError(ex.GetReason());
	}
	if (!error.empty())
	{
		ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Error on FD %d - '%s'", fd, error.c_str());
		OnError(errcode);
	}
}
Example #12
0
   void SIO_SequentialIO :: Write( char * pStringParm  ,
                                    bool   NewLineParm  )
   {

   #ifdef _DEBUG
      EXC_ASSERT( VerifySeqIO( )) ;
      EXC_ASSERT( ( OpeningMode & SIO_ModeWrite ) != 0 ) ;
      EXC_ASSERT( pStringParm != NULL ) ;
   #endif

      if ( NewLineParm )
      {
         DoWrite( EOLString ) ;
         LineCount ++ ;
      } /* if */

      DoWrite( pStringParm ) ;

   } // End of function: SIO  !Write character string constant
Example #13
0
void CActiveWriter::WriteL(const TDesC8& aPacket)
	{
	HBufC8* newbuf = HBufC8::NewL(KWriteBufSize);
	newbuf->Des() = aPacket;
	iWriteBuffers.Append(newbuf);
	if (IsActive())
		return; //try again later

	DoWrite();
	}
Example #14
0
trap_retval ReqFile_write_console( void )
{
    file_write_console_ret      *ret;

    ret = GetOutPtr( 0 );
    ret->len = DoWrite( 2, GetInPtr( sizeof( file_write_console_req ) ),
                        GetTotalSize() - sizeof( file_write_console_req ) );
    ret->err = errno;
    CONV_LE_32( ret->err );
    CONV_LE_16( ret->len );
    return( sizeof( *ret ) );
}
Example #15
0
void NetClientEx::Send(SendPacket& INsendPacket)
{
	m_ioService.GetIOService().post(
		[this, INsendPacket]()
	{
		bool write_in_progress = !m_sendPacketDeque.empty();
		m_sendPacketDeque.push_back(std::move(INsendPacket));
		if (!write_in_progress)
		{
			DoWrite();
		}
	});
}
Example #16
0
/** 
A function called by the local media subsystem to deal with a request;
this is implemented by the generic layer of the LFFS media driver.

The implementation delegates the handling of reading, writing and erasing
to the specific layer's DoRead(), DoWrite() and DoErase() functions 
respectively.
	
@param aRequest An object that encapsulates information about the request.
    
@return A value indicating the result:
        KErrNone, if the request has been sucessfully initiated;
        KErrNotSupported, if the request cannot be handled by the device;
        KMediaDriverDeferRequest, if the request cannot be handled
        immediately because of an outstanding request (this request will be
        deferred until the outstanding request has completed);
        otherwise one of the other system-wide error codes.
        
@see DMediaDriverFlash::DoRead()        
@see DMediaDriverFlash::DoWrite()
@see DMediaDriverFlash::DoErase()
*/
TInt DMediaDriverFlash::Request(TLocDrvRequest& m)
	{
	TInt r=KErrNotSupported;
	TInt id=m.Id();
	__KTRACE_OPT(KLOCDRV,Kern::Printf(">DMediaDriverFlash::Request %d",id));
	if (id==DLocalDrive::ECaps)
		{
  		TLocalDriveCapsV4& c=*(TLocalDriveCapsV4*)m.RemoteDes();
		r=Caps(c);
		c.iSize=m.Drive()->iPartitionLen;
		c.iPartitionType=m.Drive()->iPartitionType;
		SetTotalSizeInBytes(c);
		return r;
		}
	switch (id)
		{
		case DLocalDrive::ERead:
			if (iReadReq)
				return KMediaDriverDeferRequest;	// read already in progress so defer this one
			iReadReq=&m;
			r=DoRead();
			if (r!=KErrNone)
				iReadReq=NULL;
			break;
		case DLocalDrive::EWrite:
			if (iWriteReq)
				return KMediaDriverDeferRequest;	// write already in progress so defer this one
			iWriteReq=&m;
			r=DoWrite();
			if (r!=KErrNone)
				iWriteReq=NULL;
			break;
		case DLocalDrive::EFormat:
			if (iEraseReq)
				return KMediaDriverDeferRequest;	// erase already in progress so defer this one
			iEraseReq=&m;
			r=DoErase();
			if (r!=KErrNone)
				iEraseReq=NULL;
			break;
		case DLocalDrive::EEnlarge:
		case DLocalDrive::EReduce:
		default:
			r=KErrNotSupported;
			break;
		}
	__KTRACE_OPT(KLOCDRV,Kern::Printf("<DMediaDriverFlash::Request %d",r));
	if (r<0)
		DMediaDriver::Complete(m,r);
	return r;
	}
Example #17
0
	virtual int OnRawSocketWrite(int fd, const char* buffer, int count)
	{		
		issl_session* session = &sessions[fd];

		if(!session->sess)
		{
			ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: No session to write to");
			CloseSession(session);
			return 1;
		}
		
		ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: Adding %d bytes to the outgoing buffer", count);		
		session->outbuf.append(buffer, count);
		
		if(session->status == ISSL_HANDSHAKING)
		{
			// The handshake isn't finished, try to finish it.
			if(session->rstat == ISSL_WRITE || session->wstat == ISSL_WRITE)
			{
				if(Handshake(session))
				{
					// Handshake successfully resumed.
					ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: successfully resumed handshake");
				}
				else
				{
					// Couldn't resume handshake.	
					ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: failed to resume handshake"); 
				}
			}
			else
			{
				ServerInstance->Log(DEBUG, "m_ssl_openssl.so: OnRawSocketWrite: handshake wants to read data but we are currently writing");			
			}
		}
		
		if(session->status == ISSL_OPEN)
		{
			if(session->rstat == ISSL_WRITE)
			{
				DoRead(session);
			}
			
			if(session->wstat == ISSL_WRITE)
			{
				return DoWrite(session);
			}
		}
		
		return 1;
	}
Example #18
0
void CActiveWriter::RunL()
	{
	TPtr8 currentbuffer = (iWriteBuffers[0])->Des();

	iConsole.Printf(_L("Write of %d bytes (including header) returned result %d.\n"), currentbuffer.Length(), iStatus.Int());
	
	// the write has completed - clear up the buffer
	delete iWriteBuffers[0];
	iWriteBuffers.Remove(0);

	if (iWriteBuffers.Count())
		// more to send
		DoWrite();
	}
Example #19
0
trap_retval ReqFile_write( void )
{
    file_write_req      *acc;
    file_write_ret      *ret;

    acc = GetInPtr( 0 );
    CONV_LE_32( acc->handle );
    ret = GetOutPtr( 0 );
    ret->len = DoWrite( acc->handle, GetInPtr( sizeof( *acc ) ),
                        GetTotalSize() - sizeof( *acc ) );
    ret->err = errno;
    CONV_LE_32( ret->err );
    CONV_LE_16( ret->len );
    return( sizeof( *ret ) );
}
int16_t
NamedPipeInfo::GetPollFlags(int16_t aInFlags, int16_t* aOutFlags)
{
  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);

  *aOutFlags = 0;

  if (aInFlags & PR_POLL_READ) {
    int32_t bytesToRead = 0;
    if (mReadBegin < mReadEnd) { // data in buffer and is ready to be read
      bytesToRead = Available();
    } else if (mHasPendingRead) { // nonblocking I/O and has pending task
      bytesToRead = DoReadContinue();
    } else { // read bufer is empty.
      bytesToRead = DoRead();
    }

    if (bytesToRead > 0) {
      *aOutFlags |= PR_POLL_READ;
    } else if (bytesToRead < 0) {
      *aOutFlags |= PR_POLL_ERR;
    }
  }

  if (aInFlags & PR_POLL_WRITE) {
    int32_t bytesWritten = 0;
    if (mHasPendingWrite) { // nonblocking I/O and has pending task.
      bytesWritten = DoWriteContinue();
    } else if (mWriteBegin < mWriteEnd) { // data in buffer, ready to write
      bytesWritten = DoWrite();
    } else { // write buffer is empty.
      *aOutFlags |= PR_POLL_WRITE;
    }

    if (bytesWritten < 0) {
      *aOutFlags |= PR_POLL_ERR;
    } else if (bytesWritten &&
               !mHasPendingWrite &&
               mWriteBegin == mWriteEnd) {
      *aOutFlags |= PR_POLL_WRITE;
    }
  }

  return *aOutFlags;
}
Example #21
0
void dng_stream::Flush ()
	{
	
	if (fBufferDirty)
		{
		
		dng_abort_sniffer::SniffForAbort (fSniffer);

		DoWrite (fBuffer,
				 (uint32) (fBufferEnd - fBufferStart),
				 fBufferStart);
				 
		fBufferStart = 0;
		fBufferEnd   = 0;
		fBufferLimit = fBufferSize;
		
		fBufferDirty = false;
		
		}

	}
Example #22
0
STDMETHODIMP 
HXOpwaveTCPSocket::Write(THIS_
			 IHXBuffer*	pBuffer)
{

    DPRINTF(D_TCPSOCKET, ("HXOpwaveTCPSocket::Write()\n"));

    HX_RESULT res = HXR_OK;
    if (!pBuffer)
    {
    	res = HXR_INVALID_PARAMETER;
    }
    //OpDPRINTF("Write: this=%p, lwsize=%d, bread=%d, newwritesize=%d, bwrite=%d\n", this, m_ulBytesLeftToWrite, m_bReadable, pBuffer->GetSize(), m_bWritable);
    UCHAR* pBufData = pBuffer->GetBuffer(); 
    if (SUCCEEDED(res) && (m_state == tcpConnected))
    {
        /// First add to our list
        pBuffer->AddRef();
        m_writeList.AddTail(pBuffer);

        /// decide if we need to do a write 
        /// because last time when it is ready to write, there is no data 
        /// to be written.
        if (m_bWritable)
        {
            if (!m_pWriteBuffer)
            {
                m_pWriteBuffer = (IHXBuffer*)m_writeList.RemoveHead();
                m_ulBytesLeftToWrite = m_pWriteBuffer->GetSize();  
            }
            res =DoWrite();
            if (SUCCEEDED(res))
            {
                m_bWritable = FALSE;
            }
        }
    }
    return res;
}
Example #23
0
void NetClientEx::DoWrite()
{
	EnPacket& packet = m_sendPacketDeque.front().GetEnPacket();
#ifdef NET_DEBUG_INFO
	cout << "Post Send Packet Size : " << packet.GetLength() << endl;
#endif
	boost::asio::async_write(m_socket,
		boost::asio::buffer(packet.GetString(),
		packet.GetLength()),
		[this](boost::system::error_code ec, std::size_t length)
	{
		if (!ec)
		{
#ifdef NET_DEBUG_INFO
			cout << "Send Packet Complete, Size : " << length << endl;
#endif
			m_sendPacketDeque.pop_front();
			if (!m_sendPacketDeque.empty())
			{
				DoWrite();
			}
		}
		else
		{
			m_receivedPacket.Clear();
			m_receivedPacket.SetPacketType(EPacketTypeSpecial_Disconnect);
			AddReceivedPacket(m_receivedPacket);
			m_receivedPacket.Clear();

			cout << "Error : " << ec << " Stop Client " << endl;

			boost::system::error_code ignored_ec;
			m_socket.close(ignored_ec);

			Clear();
		}
	});
}
void Block() {
  Scan();
  NewLine();
  while(Token != 'e' && Token != 'l') {
    switch(Token) {
      case 'i':
        DoIf();
        break;
      case 'w':
        DoWhile();
        break;
      case 'W':
        DoWrite();
        break;
      case 'R':
        DoRead();
        break;
      default:
        Assignment();
    }
    NewLine();
    Scan();
  }
}
Example #25
0
unsigned RemoteWriteConsole( void *buff, unsigned len )
{
    if( SuppFileId == 0 ) return( 0 );
    return( DoWrite( REQ_FILE_WRITE_CONSOLE, NIL_SYS_HANDLE, buff, len ) );
}
Example #26
0
void dng_stream::Put (const void *data,
					  uint32 count)
	{
	
	// See if we can replace or append to the existing buffer.
	
	uint64 endPosition = fPosition + count;
	
	if (fBufferDirty                &&
		fPosition   >= fBufferStart &&
		fPosition   <= fBufferEnd   &&
		endPosition <= fBufferLimit)
		{
		
		DoCopyBytes (data,
					 fBuffer + (uint32) (fPosition - fBufferStart),
				     count);
				
		if (fBufferEnd < endPosition)
			fBufferEnd = endPosition;
		
		}
		
	// Else we need to write to the file.
		
	else
		{
		
		// Write existing buffer.
		
		Flush ();
		
		// Write large blocks unbuffered.
		
		if (count >= fBufferSize)
			{
			
			dng_abort_sniffer::SniffForAbort (fSniffer);
			
			DoWrite (data, count, fPosition);
			
			}
			
		// Start a new buffer with small blocks.
			
		else
			{
			
			fBufferDirty = true;
			
			fBufferStart = fPosition;
			fBufferEnd   = endPosition;
			fBufferLimit = fBufferStart + fBufferSize;
			
			DoCopyBytes (data,
						 fBuffer,
					     count);
				
			}
		
		}
		
	fPosition = endPosition;
	
	fLength = Max_uint64 (Length (), fPosition);
	
	}
Example #27
0
//write the file track by track, with moov box before or after the mdat
GF_Err WriteFlat(MovieWriter *mw, u8 moovFirst, GF_BitStream *bs)
{
	GF_Err e;
	u32 i;
	u64 offset, finalOffset, totSize, begin, firstSize, finalSize;
	GF_Box *a;
	GF_List *writers = gf_list_new();
	GF_ISOFile *movie = mw->movie;

	begin = totSize = 0;

	//first setup the writers
	e = SetupWriters(mw, writers, 0);
	if (e) goto exit;

	if (!moovFirst) {
		if (movie->openMode == GF_ISOM_OPEN_WRITE) {
			begin = 0;
			totSize = gf_isom_datamap_get_offset(movie->editFileMap);
			/*start boxes have not been written yet, do it*/
			if (!totSize) {
				if (movie->is_jp2) {
					gf_bs_write_u32(movie->editFileMap->bs, 12);
					gf_bs_write_u32(movie->editFileMap->bs, GF_4CC('j','P',' ',' '));
					gf_bs_write_u32(movie->editFileMap->bs, 0x0D0A870A);
					totSize += 12;
					begin += 12;
				}
				if (movie->brand) {
					e = gf_isom_box_size((GF_Box *)movie->brand); if (e) goto exit;
					e = gf_isom_box_write((GF_Box *)movie->brand, movie->editFileMap->bs); if (e) goto exit;
					totSize += movie->brand->size;
					begin += movie->brand->size;
				}
				if (movie->pdin) {
					e = gf_isom_box_size((GF_Box *)movie->pdin); if (e) goto exit;
					e = gf_isom_box_write((GF_Box *)movie->pdin, movie->editFileMap->bs); if (e) goto exit;
					totSize += movie->pdin->size;
					begin += movie->pdin->size;
				}
			} else {
				if (movie->is_jp2) begin += 12;
				if (movie->brand) begin += movie->brand->size;
				if (movie->pdin) begin += movie->pdin->size;
			}
			totSize -= begin;
		} else {
			if (movie->is_jp2) {
				gf_bs_write_u32(bs, 12);
				gf_bs_write_u32(bs, GF_4CC('j','P',' ',' '));
				gf_bs_write_u32(bs, 0x0D0A870A);
			}
			if (movie->brand) {
				e = gf_isom_box_size((GF_Box *)movie->brand);
				if (e) goto exit;
				e = gf_isom_box_write((GF_Box *)movie->brand, bs);
				if (e) goto exit;
			}
			/*then progressive download*/
			if (movie->pdin) {
				e = gf_isom_box_size((GF_Box *)movie->pdin);
				if (e) goto exit;
				e = gf_isom_box_write((GF_Box *)movie->pdin, bs);
				if (e) goto exit;
			}
		}

		//if the moov is at the end, write directly
		i=0;
		while ((a = (GF_Box*)gf_list_enum(movie->TopBoxes, &i))) {
			switch (a->type) {
			/*written by hand*/
			case GF_ISOM_BOX_TYPE_MOOV:
			case GF_ISOM_BOX_TYPE_META:
			case GF_ISOM_BOX_TYPE_FTYP:
			case GF_ISOM_BOX_TYPE_PDIN:
				break;
			case GF_ISOM_BOX_TYPE_MDAT:
				//in case we're capturing
				if (movie->openMode == GF_ISOM_OPEN_WRITE) {
					//emulate a write to recreate our tables (media data already written)
					e = DoWrite(mw, writers, bs, 1, begin);
					if (e) goto exit;
					continue;
				}
				//to avoid computing the size each time write always 4 + 4 + 8 bytes before
				begin = gf_bs_get_position(bs);
				gf_bs_write_u64(bs, 0);
				gf_bs_write_u64(bs, 0);
				e = DoWrite(mw, writers, bs, 0, gf_bs_get_position(bs));
				if (e) goto exit;
				totSize = gf_bs_get_position(bs) - begin;
				break;
			default:
				e = gf_isom_box_size(a);
				if (e) goto exit;
				e = gf_isom_box_write(a, bs);
				if (e) goto exit;
				break;
			}
		}

		//OK, write the movie box.
		e = WriteMoovAndMeta(movie, writers, bs);
		if (e) goto exit;

		/*if data has been written, update mdat size*/
		if (totSize) {
			offset = gf_bs_get_position(bs);
			e = gf_bs_seek(bs, begin);
			if (e) goto exit;
			if (totSize > 0xFFFFFFFF) {
				gf_bs_write_u32(bs, 1);
			} else {
				gf_bs_write_u32(bs, (u32) totSize);
			}
			gf_bs_write_u32(bs, GF_ISOM_BOX_TYPE_MDAT);
			if (totSize > 0xFFFFFFFF) gf_bs_write_u64(bs, totSize);
			e = gf_bs_seek(bs, offset);
		}
		movie->mdat->size = totSize;
		goto exit;
	}

	//nope, we have to write the moov first. The pb is that 
	//1 - we don't know its size till the mdat is written
	//2 - we don't know the ofset at which the mdat will start...
	//3 - once the mdat is written, the chunkOffset table can have changed...
	
	if (movie->is_jp2) {
		gf_bs_write_u32(bs, 12);
		gf_bs_write_u32(bs, GF_4CC('j','P',' ',' '));
		gf_bs_write_u32(bs, 0x0D0A870A);
	}
	if (movie->brand) {
		e = gf_isom_box_size((GF_Box *)movie->brand);
		if (e) goto exit;
		e = gf_isom_box_write((GF_Box *)movie->brand, bs);
		if (e) goto exit;
	}
	/*then progressive dnload*/
	if (movie->pdin) {
		e = gf_isom_box_size((GF_Box *)movie->pdin);
		if (e) goto exit;
		e = gf_isom_box_write((GF_Box *)movie->pdin, bs);
		if (e) goto exit;
	}
	//What we will do is first emulate the write from the begining...
	//note: this will set the size of the mdat
	e = DoWrite(mw, writers, bs, 1, gf_bs_get_position(bs));
	if (e) goto exit;
	
	firstSize = GetMoovAndMetaSize(movie, writers);
	//offset = (firstSize > 0xFFFFFFFF ? firstSize + 8 : firstSize) + 8 + (movie->mdat->dataSize > 0xFFFFFFFF ? 8 : 0);
	offset = firstSize + 8 + (movie->mdat->dataSize > 0xFFFFFFFF ? 8 : 0);
	e = ShiftOffset(movie, writers, offset);
	if (e) goto exit;
	//get the size and see if it has changed (eg, we moved to 64 bit offsets)
	finalSize = GetMoovAndMetaSize(movie, writers);
	if (firstSize != finalSize) {
		//we need to remove our offsets
		ResetWriters(writers);
		//finalOffset = (finalSize > 0xFFFFFFFF ? finalSize + 8 : finalSize) + 8 + (movie->mdat->dataSize > 0xFFFFFFFF ? 8 : 0);
		finalOffset = finalSize + 8 + (movie->mdat->dataSize > 0xFFFFFFFF ? 8 : 0);
		//OK, now we're sure about the final size.
		//we don't need to re-emulate, as the only thing that changed is the offset
		//so just shift the offset
		e = ShiftOffset(movie, writers, finalOffset - offset);
		if (e) goto exit;
	}
	//now write our stuff
	e = WriteMoovAndMeta(movie, writers, bs);
	if (e) goto exit;
	e = gf_isom_box_size((GF_Box *)movie->mdat);
	if (e) goto exit;
	e = gf_isom_box_write((GF_Box *)movie->mdat, bs);
	if (e) goto exit;

	//we don't need the offset as the moov is already written...
	ResetWriters(writers);
	e = DoWrite(mw, writers, bs, 0, 0);
	if (e) goto exit;
	//then the rest
	i=0;
	while ((a = (GF_Box*)gf_list_enum(movie->TopBoxes, &i))) {
		switch (a->type) {
		case GF_ISOM_BOX_TYPE_MOOV:
		case GF_ISOM_BOX_TYPE_META:
		case GF_ISOM_BOX_TYPE_FTYP:
		case GF_ISOM_BOX_TYPE_PDIN:
		case GF_ISOM_BOX_TYPE_MDAT:
			break;
		default:
			e = gf_isom_box_size(a);
			if (e) goto exit;
			e = gf_isom_box_write(a, bs);
			if (e) goto exit;
		}
	}

exit:
	CleanWriters(writers);
	gf_list_del(writers);
	return e;
}
Example #28
0
//! \overload Write( const wxJSONValue&, wxString& )
void
wxJSONWriter::Write( const wxJSONValue& value, wxOutputStream& os )
{
    m_level = 0;
    DoWrite( os, value, 0, false );
}
Example #29
0
void MainProc() {
	for (;;) {
		int MaxFd;
		fd_set ReadQ;
		fd_set WriteQ;

		if (Reconnect) {
			close(connection->Fd);
			FreeConnection(connection);
			// To prevent floods. I know, this should be rather handled by ewrecv, but that would be nontrivial.
			sleep(2);
			AttachConnection();
			Reconnect = 0;
		}

		MaxFd = 0;

		FD_ZERO(&ReadQ);
		FD_ZERO(&WriteQ);

		// stdin
		if (read_from_stdin
		&& !want_quit
		&& strlen(Commands) < COMMANDS_MAXLEN) {
			FD_SET(0, &ReadQ);
		}

		if (connection) {
			FD_SET(connection->Fd, &ReadQ);
			if (connection->Fd > MaxFd) MaxFd = connection->Fd;
			if (connection->WriteBuffer) FD_SET(connection->Fd, &WriteQ);
		}

		struct timeval to;
		to.tv_sec = timeout_denominator;
		to.tv_usec = 0;
		struct timeval *top = &to;
		if (timeout_denominator == 0) top = NULL;

		int s = select(MaxFd + 1, &ReadQ, &WriteQ, 0, top);

		if (s < 0) {
			if (errno == EINTR) continue;
			Done(1);
		} else if (s == 0) {
			// timeout
		} else {
			// stdin
			if (read_from_stdin
			&& strlen(Commands) < COMMANDS_MAXLEN
			&& FD_ISSET(0, &ReadQ)) {
				char buf[256+1] = "";

				int to_read = COMMANDS_MAXLEN - strlen(Commands);
				if (to_read > 256) to_read = 256;

				int r = read(0, buf, to_read);
				buf[r] = 0;

				if (r == 0) {
					want_quit = 1;

					TryQuit();
				} else {
					strncat(Commands, buf, r);

					SendNextCommand();
				}
			}

			// Exchange input
			if (connection && FD_ISSET(connection->Fd, &ReadQ)) {
				errno = 0;
				if (DoRead(connection) <= 0) {
					if (detaching) {
						Done(0);
					} else {
						Done(1);
					}
				} else {
					int Chr;

					while (Read(connection, &Chr, 1)) {
						TestIProtoChar(connection, Chr);
					}
				}
			}

			// Exchange output
			if (connection && FD_ISSET(connection->Fd, &WriteQ)) {
				if (DoWrite(connection) < 0) Done(1);
			}
		}

		if (login_timeout && login_start && !logged_in) {
			if (time(NULL) - login_start > login_timeout) Done(103);
		}

		if (command_timeout && command_start && jobs) {
			if (time(NULL) - command_start > command_timeout) Done(104);
		}
	}
}
Example #30
0
/*!
 This is a recursive function that gets the type of the \c value object and
 calls several protected functions depending on the type:

 \li \c WriteNullvalue for type NULL
 \li \c WriteStringValue() for STRING and CSTRING types
 \li \c WriteIntValue for INT types
 \li \c WriteUIntValue for UINT types
 \li \c WriteBoolValue for BOOL types
 \li \c WriteDoubleValue for DOUBLE types
 \li \c WriteMemoryBuff for MEMORYBUFF types

 If the value is an array or key/value map (types ARRAY and OBJECT), the function
 iterates through all JSON value object in the array/map and calls itself for every
 item in the container.
*/
int
wxJSONWriter::DoWrite( wxOutputStream& os, const wxJSONValue& value, const wxString* key, bool comma )
{
    // note that this function is recursive

    // some variables that cannot be allocated in the switch statement
    const wxJSONInternalMap* map = 0;
    int size;
    m_colNo = 1; m_lineNo = 1;
    // determine the comment position; it is one of:
    //
    //  wxJSONVALUE_COMMENT_BEFORE
    //  wxJSONVALUE_COMMENT_AFTER
    //  wxJSONVALUE_COMMENT_INLINE
    //
    // or -1 if comments have not to be written
    int commentPos = -1;
    if ( value.GetCommentCount() > 0 && (m_style & wxJSONWRITER_WRITE_COMMENTS))  {
        commentPos = value.GetCommentPos();
        if ( ( m_style & wxJSONWRITER_COMMENTS_BEFORE) != 0 ) {
            commentPos = wxJSONVALUE_COMMENT_BEFORE;
        }
        else if ( (m_style & wxJSONWRITER_COMMENTS_AFTER) != 0 ) {
            commentPos = wxJSONVALUE_COMMENT_AFTER;
        }
    }

    int lastChar = 0;  // check if WriteComment() writes the last LF char

    // first write the comment if it is BEFORE
    if ( commentPos == wxJSONVALUE_COMMENT_BEFORE )   {
        lastChar = WriteComment( os, value, true );
        if ( lastChar < 0 )   {
            return lastChar;
        }
        else if ( lastChar != '\n' )  {
            WriteSeparator( os );
        }
    }

    lastChar = WriteIndent( os );
    if ( lastChar < 0 )   {
        return lastChar;
    }

    // now write the key if it is not NULL
    if ( key )   {
        lastChar = WriteKey( os, *key );
    }
    if ( lastChar < 0 )   {
        return lastChar;
    }

    // now write the value
    wxJSONInternalMap::const_iterator it;    // declare the map object
    long int count = 0;

    wxJSONType t = value.GetType();
    switch ( t )  {
    case wxJSONTYPE_INVALID :
        WriteInvalid( os );
        wxFAIL_MSG( _T("wxJSONWriter::WriteEmpty() cannot be called (not a valid JSON text"));
        break;

    case wxJSONTYPE_INT :
    case wxJSONTYPE_SHORT :
    case wxJSONTYPE_LONG :
    case wxJSONTYPE_INT64 :
        lastChar = WriteIntValue( os, value );
        break;

    case wxJSONTYPE_UINT :
    case wxJSONTYPE_USHORT :
    case wxJSONTYPE_ULONG :
    case wxJSONTYPE_UINT64 :
        lastChar = WriteUIntValue( os, value );
        break;

    case wxJSONTYPE_NULL :
        lastChar = WriteNullValue( os );
        break;
    case wxJSONTYPE_BOOL :
        lastChar = WriteBoolValue( os, value );
        break;

    case wxJSONTYPE_DOUBLE :
        lastChar = WriteDoubleValue( os, value );
        break;

    case wxJSONTYPE_STRING :
    case wxJSONTYPE_CSTRING :
        lastChar = WriteStringValue( os, value.AsString());
        break;

    case wxJSONTYPE_MEMORYBUFF :
        lastChar = WriteMemoryBuff( os, value.AsMemoryBuff());
        break;

    case wxJSONTYPE_ARRAY :
        ++m_level;
        os.PutC( '[' );
        // the inline comment for objects and arrays are printed in the open char
        if ( commentPos == wxJSONVALUE_COMMENT_INLINE )   {
            commentPos = -1;  // we have already written the comment
            lastChar = WriteComment( os, value, false );
            if ( lastChar < 0 )   {
                return lastChar;
            }
            if ( lastChar != '\n' )   {
                lastChar = WriteSeparator( os );
            }
        }
        else   {    // comment is not to be printed inline, so write a LF
            lastChar = WriteSeparator( os );
            if ( lastChar < 0 )   {
                return lastChar;
            }
        }

        // now iterate through all sub-items and call DoWrite() recursively
        size = value.Size();
        for ( int i = 0; i < size; i++ )  {
            bool comma = false;
            if ( i < size - 1 )  {
                comma = true;
            }
            wxJSONValue v = value.ItemAt( i );
            lastChar = DoWrite( os, v, 0, comma );
            if ( lastChar < 0 )  {
                return lastChar;
            }

        }
        --m_level;
        lastChar = WriteIndent( os );
        if ( lastChar < 0 )   {
            return lastChar;
        }
        os.PutC( ']' );
        break;

    case wxJSONTYPE_OBJECT :
        ++m_level;

        os.PutC( '{' );
        // the inline comment for objects and arrays are printed in the open char
        if ( commentPos == wxJSONVALUE_COMMENT_INLINE )   {
            commentPos = -1;  // we have already written the comment
            lastChar = WriteComment( os, value, false );
            if ( lastChar < 0 )   {
                return lastChar;
            }
            if ( lastChar != '\n' )   {
                WriteSeparator( os );
            }
        }
        else   {
            lastChar = WriteSeparator( os );
        }

        map = value.AsMap();
        size = value.Size();
        count = 0;
        for ( it = map->begin(); it != map->end(); ++it )  {
            // get the key and the value
            wxString key = it->first;
            const wxJSONValue& v = it->second;
            bool comma = false;
            if ( count < size - 1 )  {
                comma = true;
            }
            lastChar = DoWrite( os, v, &key, comma );
            if ( lastChar < 0 )  {
                return lastChar;
            }
            count++;
        }
        --m_level;
        lastChar = WriteIndent( os );
        if ( lastChar < 0 )   {
            return lastChar;
        }
        os.PutC( '}' );
        break;

    default :
        // a not yet defined wxJSONType: we FAIL
        wxFAIL_MSG( _T("wxJSONWriter::DoWrite() undefined wxJSONType type"));
        break;
    }

    // writes the comma character before the inline comment
    if ( comma )  {
        os.PutC( ',' );
    }

    if ( commentPos == wxJSONVALUE_COMMENT_INLINE )   {
        lastChar = WriteComment( os, value, false );
        if ( lastChar < 0 )   {
            return lastChar;
        }
    }
    else if ( commentPos == wxJSONVALUE_COMMENT_AFTER )   {
        WriteSeparator( os );
        lastChar = WriteComment( os, value, true );
        if ( lastChar < 0 )   {
            return lastChar;
        }
    }
    if ( lastChar != '\n' )  {
        lastChar = WriteSeparator( os );
    }
    return lastChar;
}