示例#1
0
// Remove the headers from the input buffer, handing each to OnHeaderLine
BOOL CConnection::ReadHeaders()
{
	// Move the first line from the m_pInput buffer to strLine and do the contents of the while loop
	CString strLine;
	while ( Read( strLine ) )	// ReadLine will return false when there are no more lines
	{
		// If the line is more than 256 KB, change it to the long line error code
		if ( strLine.GetLength() > HTTP_HEADER_MAX_LINE )
			strLine = _T("#LINE_TOO_LONG#");

		// Find the first colon in the line
		int nPos = strLine.Find( _T(":") );

		// The line is empty, it's just a \n character
		if ( strLine.IsEmpty() )
		{
			// Empty the last header member variable (do)
			m_sLastHeader.Empty();

			// Call the OnHeadersComplete method for the most advanced class that inherits from CConnection
			return OnHeadersComplete();
		}
		else if ( _istspace( strLine.GetAt( 0 ) ) )		// Get the first character in the string, and see if its a space
		{
			// The line starts with a space

			// The last header has length
			if ( ! m_sLastHeader.IsEmpty() )
			{
				// Trim whitespace from both ends of the line, and ensure it still has length
				strLine.Trim();
				if ( strLine.IsEmpty() ) continue;

				// Give OnHeaderLine the last header and this line
				if ( ! OnHeaderLine( m_sLastHeader, strLine ) )
					return FALSE;
			}
		}
		else if ( nPos > 1 && nPos < 64 )	// ":a" is 0 and "a:a" is 1, but "aa:a" is greater than 1
		{
			// The colon is at a distance greater than 1 and less than 64

			// The line is like "header:value", copy out both parts
			CString strHeader	= strLine.Left( nPos );
			CString strValue	= strLine.Mid( nPos + 1 );
			m_sLastHeader = strHeader;

			strValue.Trim();
			if ( strValue.IsEmpty() ) continue;

			// Give OnHeaderLine this last header, and its value
			if ( ! OnHeaderLine( strHeader, strValue ) )
				return FALSE;
		}
	}

	// Send the contents of the output buffer to the remote computer
	OnWrite();
	return TRUE;
}
示例#2
0
CCircBuf::t_size CCircBuf::Write( oexCPVOID x_pvBuf, t_size x_uSize, oexUINT x_uEncode )
{
	// Sanity check
	if ( !oexCHECK_PTR( x_pvBuf ) || !x_uSize )
		return 0;

	// Lock the buffer
	oexAutoLock ll( &m_lock );
	if ( !ll.IsLocked() )
		return 0;

	// Do we want to auto expand the buffer?
	if ( eWmGrow == m_nWriteMode )
	{
		if ( !m_pBi )
			Allocate( x_uSize );
		else
			EnsureWriteSpace( x_uSize, m_pBi->uReadPtr, m_pBi->uWritePtr, m_uSize );

	} // end if

	// Do we have a buffer?
	if ( !m_pBi )
		return 0;

	// Attempt to actually write the data
	if ( !Write( x_pvBuf, x_uSize, &m_pBi->uWritePtr, x_uEncode ) )
		return 0;

	OnWrite();

	return x_uSize;
}
示例#3
0
文件: imconn.cpp 项目: narychen/eggie
void imconn_callback_sp(void* callback_data, uint8_t msg, uint32_t handle, void* pParam)
{
	NOTUSED_ARG(handle);
	NOTUSED_ARG(pParam);
	auto imconn_map_sp = (ConnMap_sp_t*)callback_data;
	
	auto pConn = FindImConnSp(imconn_map_sp, handle);
	if (!pConn)
		return;

	// log("msg=%d, handle=%d ", msg, handle);

	switch (msg)
	{
	case NETLIB_MSG_CONFIRM:
		pConn->OnConfirm();
		break;
	case NETLIB_MSG_READ:
		pConn->OnRead();
		break;
	case NETLIB_MSG_WRITE:
		pConn->OnWrite();
		break;
	case NETLIB_MSG_CLOSE:
		pConn->OnClose();
		break;
	default:
		loge("!!!imconn_callback error msg: %d ", msg);
		break;
	}
}
示例#4
0
bool PeerClient::ServeDataRequest(size_t index)
{
    assert(_mediaSlicer != NULL);

	std::map<size_t,size_t>::iterator it = m_sendList.find( index );
	if( it != m_sendList.end() ) 
    {
        return true;
    }

    MediaSlice* slice = _mediaSlicer->GetSlice( index );

    if( slice == NULL ) 
    { 
        return false;
    }

    PPPacket* pPacket = PPPacket::New( PS_PACKET_ANS_DATA );

    slice->ToBuffer( pPacket );

    pPacket->ToBuffer( m_pOutput );

    slice->Delete();

    pPacket->Release();

    OnWrite();    

	m_sendList[index] = index;
	
	theLogger.Message(MSG_SYSTEM,"Service index = %d\r\n",index);

    return true;
}
示例#5
0
// Call OnWrite if DoRun has just succeeded (do)
void CConnection::QueueRun()
{
	// If the queued run state is 1 or 2, make it 2, if it's 0, call OnWrite now (do)
	if ( m_nQueuedRun )
		m_nQueuedRun = 2;	// The queued run state is not 0, make it 2 and do nothing else
	else
		OnWrite();			// The queued run state is 0, do a write (do)
}
示例#6
0
BOOL CTransfer::SendPacket(const void* pData, DWORD nLength)
{
	if ( ! m_bConnected ) return FALSE;
	CSingleLock pLock( &m_pSection, TRUE );
	
	m_pOutput->Add( pData, nLength );
	if ( m_bConnected ) OnWrite();
	
	return TRUE;
}
示例#7
0
status_t
SerialDevice::_WriteToDevice()
{
	char *buffer = fOutputBuffer;
	size_t bytesLeft = fOutputBufferSize;
	status_t status = gTTYModule->tty_read(fDeviceTTYCookie, buffer,
		&bytesLeft);
	if (status != B_OK) {
		TRACE_ALWAYS("write to device: failed to read from TTY: %s\n",
			strerror(status));
		return status;
	}

	while (!fDeviceRemoved && bytesLeft > 0) {
		size_t length = MIN(bytesLeft, fWriteBufferSize);
		size_t packetLength = length;
		OnWrite(buffer, &length, &packetLength);

		status = gUSBModule->queue_bulk(fWritePipe, fWriteBuffer, packetLength,
			_WriteCallbackFunction, this);
		if (status != B_OK) {
			TRACE_ALWAYS("write to device: queueing failed with status "
				"0x%08x\n", status);
			return status;
		}

		status = acquire_sem_etc(fDoneWrite, 1, B_CAN_INTERRUPT, 0);
		if (status != B_OK) {
			TRACE_ALWAYS("write to device: failed to get write done sem "
				"0x%08x\n", status);
			return status;
		}

		if (fStatusWrite != B_OK) {
			TRACE("write to device: device status error 0x%08x\n",
				fStatusWrite);
			if (fStatusWrite == B_DEV_STALLED) {
				status = gUSBModule->clear_feature(fWritePipe,
					USB_FEATURE_ENDPOINT_HALT);
				if (status != B_OK) {
					TRACE_ALWAYS("write to device: failed to clear device "
						"halt\n");
					return B_ERROR;
				}
			}

			continue;
		}

		buffer += length;
		bytesLeft -= length;
	}

	return B_OK;
}
示例#8
0
status_t
SerialDevice::Write(const char *buffer, size_t *numBytes)
{
	size_t bytesLeft = *numBytes;
	*numBytes = 0;

	status_t status = mutex_lock(&fWriteLock);
	if (status != B_OK) {
		TRACE_ALWAYS("write: failed to get write lock\n");
		return status;
	}

	if (fDeviceRemoved) {
		mutex_unlock(&fWriteLock);
		return B_DEV_NOT_READY;
	}

	while (bytesLeft > 0) {
		size_t length = MIN(bytesLeft, fWriteBufferSize);
		size_t packetLength = length;
		OnWrite(buffer, &length, &packetLength);

		status = gUSBModule->queue_bulk(fWritePipe, fWriteBuffer,
			packetLength, WriteCallbackFunction, this);
		if (status < B_OK) {
			TRACE_ALWAYS("write: queueing failed with status 0x%08x\n", status);
			break;
		}

		status = acquire_sem_etc(fDoneWrite, 1, B_CAN_INTERRUPT, 0);
		if (status < B_OK) {
			TRACE_ALWAYS("write: failed to get write done sem 0x%08x\n", status);
			break;
		}

		if (fStatusWrite != B_OK) {
			TRACE("write: device status error 0x%08x\n", fStatusWrite);
			status = gUSBModule->clear_feature(fWritePipe,
				USB_FEATURE_ENDPOINT_HALT);
			if (status < B_OK) {
				TRACE_ALWAYS("write: failed to clear device halt\n");
				status = B_ERROR;
				break;
			}
			continue;
		}

		buffer += length;
		*numBytes += length;
		bytesLeft -= length;
	}

	mutex_unlock(&fWriteLock);
	return status;
}
示例#9
0
BOOL CTransfer::SendPacket(CPacket* pPacket, BOOL bPeek)
{
	if ( ! m_bConnected ) return FALSE;
	CSingleLock pLock( &m_pSection, TRUE );
	
	pPacket->EncodeBody( m_pOutput );
	if ( m_bConnected ) OnWrite();
	
	if ( ! bPeek ) pPacket->Release();

	return TRUE;
}
示例#10
0
bool PeerClient::OnRun()
{   
	if ( m_nState == kClosed )	
    {
        return false;
    }
    
	if(m_DataRequestList.empty()) 
    {  
        UInt32L tNow = OSMilliSeconds();

        if(tNow - m_tLastIsNotEmtpy > MAX_TIME_NO_REQUEST)
        {
            theLogger.Message(MSG_SYSTEM,"Client %s left or need nothing\r\n", m_RemoteEndpoint.GetHostString() );
            return false;
        }
    
        return true;
    }
    m_tLastIsNotEmtpy  = OSMilliSeconds();


	while(!m_DataRequestList.empty() && m_pOutput->readable() <= m_nSendRate)
    {
        DataRequestTag* tempDataRequest = (DataRequestTag*)m_DataRequestList.front();
		
        int nMin, nMax, n;
        n = nMin = tempDataRequest->m_nMin;
        nMax = tempDataRequest->m_nMax;

        if(nMin < nMax)  
        {
            tempDataRequest->m_nMin++;
        }
        else 
        {
            m_DataRequestList.pop_front();
        }

        if(!ServeDataRequest(n)) 
        {
            PPPacket* pErrorPacket = PPPacket::New(PS_PACKET_ANS_FAIL); 
            pErrorPacket->write16u(n);
            pErrorPacket->writeString(m_sMediaName);
            pErrorPacket->ToBuffer(m_pOutput);
            OnWrite();  
			pErrorPacket->Release();
            return false;
        }     
    }

    return true;
}
NS_IMETHODIMP nsCacheEntryDescriptor::
nsOutputStreamWrapper::Write(const char * buf,
                             PRUint32     count,
                             PRUint32 *   result)
{
    nsresult rv = EnsureInit();
    if (NS_FAILED(rv)) return rv;

    rv = OnWrite(count);
    if (NS_FAILED(rv)) return rv;

    return mOutput->Write(buf, count, result);
}
nsresult nsCacheEntryDescriptor::
nsOutputStreamWrapper::Write_Locked(const char * buf,
                                    uint32_t count,
                                    uint32_t * result)
{
    nsresult rv = EnsureInit();
    if (NS_FAILED(rv)) return rv;

    rv = OnWrite(count);
    if (NS_FAILED(rv)) return rv;

    return mOutput->Write(buf, count, result);
}
示例#13
0
bool_t PacketHandler::HandleEvents(serial_t uidx, Session *sess, EVENT_T e)
{
	if(!sess) { ECILA_TRACE(); return FALSE; }

	switch(e)
	{
	case NS_ECILA::EVENT_OPEN	: return OnOpen(uidx, sess);
	case NS_ECILA::EVENT_CLOSE	: return OnClose(uidx, sess);
	case NS_ECILA::EVENT_READ	: return OnRead(uidx, sess);
	case NS_ECILA::EVENT_WRITE	: return OnWrite(uidx, sess);
	default						: { ECILA_TRACE(); return FALSE; }
	}
}
示例#14
0
bool PeerClient::OnMetaRequest(PPPacket* pPacket)
{   
    if(m_bMetaSended == true)
    {
        return true;
    }
    
    assert(_mediaSlicer != NULL);
    size_t sliceCount = _mediaSlicer->GetSliceCount();
	SliceTable* pTable  = _mediaSlicer->GetSliceTable();
    assert(pTable != NULL);
	if ( pTable == NULL ) 
    {
        return false;
    }

    PPPacket* pOutPacket = PPPacket::New( PS_PACKET_ANS_META );
    pOutPacket->write32u( (uint32_t)sliceCount);
	for( size_t i=0; i < sliceCount; i++)
    {
		pOutPacket->write32u( (uint32_t)pTable[i].nLen );
        pOutPacket->write8u( pTable[i].bKeyFrame );
    }

    std::string sdp = _mediaSlicer->GetSDP();
	pOutPacket->writeString( sdp );

	MediaSlice* pFirstSlice = _mediaSlicer->GetSlice(0);
	if(pFirstSlice)
	{
		pOutPacket->write8u(1);

		pFirstSlice->ToBuffer(pOutPacket);

		pFirstSlice->Delete();
	}
	else
		pOutPacket->write8u(0);
    
    pOutPacket->ToBuffer( m_pOutput );	

    OnWrite();

    pOutPacket->Release();
     
    theLogger.Message(MSG_SYSTEM,"Get a Meta Request %s!", m_sMediaName.c_str() );

    m_bMetaSended = true;

    return true;
}
示例#15
0
void PeerClient::Send(PPPacket* pPacket)
{
    assert(m_hSocket != INVALID_SOCKET);

    if(pPacket != NULL)
    {
        pPacket->ToBuffer(m_pOutput);
    }	

    OnWrite();

    m_nOutPackets++;

    pPacket->Release();
}
示例#16
0
void CHostBrowser::SendRequest()
{
	if ( m_nProtocol != PROTOCOL_ED2K && m_nProtocol != PROTOCOL_DC )
	{
		if ( ! IsValid() ) return;

		if ( m_bNewBrowse )
			Write( _P("GET /gnutella/browse/v1 HTTP/1.1\r\n") );
		else if ( Settings.Downloads.RequestHTTP11 )
			Write( _P("GET / HTTP/1.1\r\n") );
		else
			Write( _P("GET / HTTP/1.0\r\n") );

		CString strHeader = Settings.SmartAgent();

		if ( ! strHeader.IsEmpty() )
		{
			Write( _P("User-Agent: ") );
			Write( strHeader );
			Write( _P("\r\n") );
		}

		Write( _P("Accept: text/html, application/x-gnutella-packets, application/x-gnutella2\r\n") );
		Write( _P("Accept-Encoding: deflate\r\n") );
	//	if ( ! m_sKey.IsEmpty() )	// ToDo: Proposed PrivateKey extension
	//		Write( L"Authorization: :" + m_sKey + L"\r\n" );

		Write( _P("Connection: close\r\n") );

		strHeader.Format( L"Host: %s:%lu\r\n\r\n", (LPCTSTR)m_sAddress, htons( m_pHost.sin_port ) );
		Write( strHeader );

		LogOutgoing();

		OnWrite();

		m_nProtocol = PROTOCOL_ANY;
	}

	m_nState	= hbsRequesting;
	m_bDeflate	= FALSE;
	m_nLength	= SIZE_UNKNOWN;
	m_bConnect	= TRUE;

	m_mInput.pLimit = m_mOutput.pLimit = &Settings.Bandwidth.Downloads;

	theApp.Message( MSG_INFO, IDS_BROWSE_SENT_REQUEST, (LPCTSTR)m_sAddress );
}
示例#17
0
void SyncClientChannel::TryFireMessage() {
  while (true) {
    ProtocolMessage* fire_message = sequence_keeper_.Fire();
    if (!fire_message) {
      return;
    }

    if (Protocol::kEncodeSuccess != GetProtocol()->Encode(&write_buffer_, fire_message)) {
      MI_LOG_WARN(logger, "SyncClientChannel::TryFireMessage encode fail");
      DoSendBack(fire_message, ProtocolMessage::kStatusEncodeFail);
      sequence_keeper_.Fetch();
      continue;
    }

    OnWrite();
    break;
  }
}
示例#18
0
static int HandleEvents(SOCKET sockfd, int index, const WSANETWORKEVENTS* events_struct)
{
    const int* errorlist = events_struct->iErrorCode;
    int events = events_struct->lNetworkEvents;
    if (events & FD_READ)
    {
        OnRecv(sockfd, index, errorlist[FD_READ_BIT]);
    }
    if (events & FD_WRITE)
    {
        OnWrite(sockfd, index, errorlist[FD_WRITE_BIT]);
    }
    if (events & FD_CLOSE)
    {
        OnClose(sockfd, index, errorlist[FD_CLOSE_BIT]);
    }
    return 0;
}
示例#19
0
    Buffer* ResponseMessage::toBuffer()
    {
        unsigned int nCode = msg->code();
        std::string sReason = msg->message();
        size_t nHdrLen = msg->headerLen();
        size_t nBufLen = msg->bufferLen();
        
        // "RTSP/1.0" SP <code> SP <reason> CRLF
        // <headers> CRLF
        // <buf> (or terminating NULL from sprintf() if no buffer)
        size_t size = 8 + 1 + 3 + 1 + sReason.length() + 2 + nHdrLen + 2;
        size += nBufLen != 0 ? nBufLen : 1;
        
        char* buf = new char[size];
        assert(buf != NULL);
        if(buf == NULL)
        {
            std::cout << "RTSPServer send response out of memory.\n";
            return false;
        }
        
        char* p = buf;
        p += sprintf(p, "RTSP/1.0 %u %s\r\n", nCode, sReason.c_str());
        
        for(UINT n = 0; n < msg->headerCount(); n++ )
        {
            RTSPHeader* pHeader = msg->header(n);
            p += sprintf(p, "%s: %s\r\n", pHeader->key().c_str(), pHeader->value().c_str());
        }
        p += sprintf(p, "\r\n");
        
        if( nBufLen )
        {
            memcpy(p, msg->buffer(), nBufLen );
            p += nBufLen;
        }
        
        m_pOutput->Add(buf, p - buf);
        OnWrite();
        delete[] buf;

        return NULL;
    }
示例#20
0
void IEventChannel::FiredEvents()
{
	ChannelEventFlags val=mFiredEvents;
	mFiredEvents = ChannelEventFlags::None;

	if (MEDUSA_FLAG_HAS(val,ChannelEventFlags::Read))
	{
		OnActive();
		OnRead();
	}
	if (!mIsAlive)
	{
		return;
	}

	if (MEDUSA_FLAG_HAS(val, ChannelEventFlags::Write))
	{
		OnActive();
		OnWrite();
	}

	if (MEDUSA_FLAG_HAS(val, ChannelEventFlags::Timeout))
	{
		OnTimeout();
	}

	if (MEDUSA_FLAG_HAS(val, ChannelEventFlags::Retry))
	{
		OnRetry();
	}

	if (MEDUSA_FLAG_HAS(val, ChannelEventFlags::Fault))
	{
		OnError();
	}
	
	if (MEDUSA_FLAG_HAS(val, ChannelEventFlags::Idle))
	{
		OnIdle();
	}

}
示例#21
0
BOOL CConnection::OnRun()
{
	if ( INVALID_SOCKET == m_hSocket ) return FALSE;
	
	WSANETWORKEVENTS pEvents;
	WSAEnumNetworkEvents( m_hSocket, NULL, &pEvents );
	
	if ( pEvents.lNetworkEvents & FD_CONNECT )
	{
		if ( pEvents.iErrorCode[ FD_CONNECT_BIT ] != 0 )
		{
			OnDropped( TRUE );
			return FALSE;
		}

		if ( ! OnConnected() ) return FALSE;
	}
	
	BOOL bClosed = ( pEvents.lNetworkEvents & FD_CLOSE ) ? TRUE : FALSE;
	
	// if ( pEvents.lNetworkEvents & FD_WRITE )
	{
		if ( ! OnWrite() ) return FALSE;
	}

	// if ( pEvents.lNetworkEvents & FD_READ )
	{
		if ( ! OnRead() ) return FALSE;
	}
	
	if ( bClosed )
	{
		OnDropped( pEvents.iErrorCode[ FD_CLOSE_BIT ] != 0 );
		return FALSE;
	}

	return TRUE;
}
示例#22
0
void APISocket::CSocket::AsyncNotifications()
{
	if (!m_sock) return;

	fd_set read_fds, write_fds;
	FD_ZERO(&read_fds);
	FD_ZERO(&write_fds);
	FD_SET(m_sock, &read_fds);
	FD_SET(m_sock, &write_fds);

	int res = select(m_sock + 1, &read_fds, &write_fds, NULL, NULL);
	if (res > 0)
	{
		if (FD_ISSET(m_sock, &read_fds))
		{
			if (ReadableByteCount())
			{
				inAsyncNotificationLoop = true;
				OnRead();
			}
			else
			{
				inAsyncNotificationLoop = true;
				OnError(GetLastError());
				shouldAsyncQuit = true;
				return;
			}
		}

		if (FD_ISSET(m_sock, &write_fds))
		{
			inAsyncNotificationLoop = true;
			OnWrite();
		}
	}
	inAsyncNotificationLoop = true;
}
示例#23
0
文件: textbuf.cpp 项目: EdgarTx/wx
bool wxTextBuffer::Write(wxTextFileType typeNew, const wxMBConv& conv)
{
    return OnWrite(typeNew, conv);
}
示例#24
0
 client() : _super_t() {
   _super_t::onRead.connect([this](){ OnRead(); });
   _super_t::onWrite.connect([this](){ OnWrite(); });
   _super_t::onError.connect([this](){ OnError(); });
 }
示例#25
0
int CSocketClient::Run()
{
	try
	{		
		HANDLE handlesToWaitFor[2];
		
		handlesToWaitFor[0] = m_shutdownEvent.GetEvent();
		handlesToWaitFor[1] = m_successConnectionsEvent.GetEvent();
		
		while ( !m_shutdownEvent.Wait( 0 ) )
		{
			DWORD waitResult = ::WaitForMultipleObjects( 2, handlesToWaitFor, false, INFINITE );
			
			if ( waitResult == WAIT_OBJECT_0 )
			{
				/*
				 * Time to shutdown
				 */
				break;
			}
			else if ( waitResult == WAIT_OBJECT_0 + 1 )
			{
				/*
				 * Allocate a buffer for required read
				 */
				CIOBuffer *pReadContext = Allocate();

				while ( !m_shutdownEvent.Wait( 0 ) && m_successConnectionsEvent.Wait( 0 ) )
				{
					if ( m_eventSelect.WaitForEnumEvent( m_connectSocket, 1000 ) )
					{
						/*
						 * Find some events and process it
						 */
						
						/*
						 * A event to connect
						 */
						if ( m_eventSelect.IsConnect() )
						{
							OnConnect();						
						}

						/*
						 * A event to close
						 */
						if ( m_eventSelect.IsClose() )
						{
							OnClose();						
						}

						/*
						 * A event to read
						 */
						if ( m_eventSelect.IsRead() )
						{
							OnRead( pReadContext );
						}

						/*
						 * A event to write
						 */
						if ( m_eventSelect.IsWrite() )
						{
							OnWrite();
						}
					}
				} // while (...

				pReadContext->Release();
			}
			else
			{
				/*
				 * Call to unqualified virtual function
				 */
				OnError( _T("CSocketClient::Run() - WaitForMultipleObjects: ") + GetLastErrorMessage( ::GetLastError() ) );
			}
			
		} // while ( ... 		
	}
	catch( const CException &e )
	{
		/*
		 * Call to unqualified virtual function
		 */
		OnError( _T("CSocketClient::Run() - Exception: ") + e.GetWhere() + _T(" - ") + e.GetMessage() );
	}
	catch(...)
	{
		/*
		 * Call to unqualified virtual function
		 */
		OnError( _T("CSocketClient::Run() - Unexpected exception") );
	}
	
	/*
	 * Call to unqualified virtual function
	 */
	OnShutdownComplete();
	
	return 0;
}
示例#26
0
 void CTcpHandler::TcpWrite()
 {
     int iLength = evbuffer_get_length(bufferevent_get_output(m_pBufevt));
     OnWrite(iLength); 
 }
示例#27
0
bool PeerClient::OnClientJoin(PPPacket* pPacket)
{
    if(pPacket == NULL)
    {
        return false;
    }
    assert(pPacket != NULL);
        
    std::string mediaName;
    if(!pPacket->readString(mediaName, '\0') || mediaName.empty())
    {
        assert(false);
        return false;
    }
    
#if _OS_WINDOWS
	std::string::size_type idx = mediaName.find( '/' );
	while ( idx != std::string::npos )
	{
		mediaName.replace( idx, 1, "\\" );
		idx = mediaName.find( '/' );
	}
#endif
    
    if (m_sMediaName.empty()) 
    {
        m_sMediaName = mediaName ;
    }
    else
    {
		if ( m_sMediaName.size() != mediaName.size() || 
			! equal( m_sMediaName.begin(), m_sMediaName.end(), mediaName.begin(), nocase_compare) )
        {
            PPPacket* pErrorPacket = PPPacket::New( PS_PACKET_HND_RJCT ); 
            pErrorPacket->writeString("Media name error!");
            pErrorPacket->ToBuffer( m_pOutput );
            OnWrite();
			pErrorPacket->Release();
            return false;
        }
    }
    
    if ( _mediaSlicer == NULL ) 
    {
        MediaSlicer* slicer = new MediaSlicer();
        assert(slicer != NULL);
        
        // MediaSlicer use full path name
        std::string path_name;
        std::vector<std::string> dirs = theSettings.System.LocalDirs;
        
        std::vector<std::string>::iterator it = dirs.begin();
        for ( ; it != dirs.end(); ++it )
        {
            path_name = *it;
            path_name.append( m_sMediaName );
            
            if(slicer->Initialize(path_name))
            {
                break;
            }
        }
        
        if(it == dirs.end())
        {
            // No file found
            delete slicer;
            
            PPPacket* pErrorPacket = PPPacket::New( PS_PACKET_HND_RJCT ); 
            pErrorPacket->writeString("Can not find media file error!");
            pErrorPacket->ToBuffer( m_pOutput );
            OnWrite();
			pErrorPacket->Release();
            return false;
        }

        _mediaSlicer = slicer;
    }
    
	m_nSendRate = _mediaSlicer->GetBitrate();
    PPPacket* pResPacket = PPPacket::New( PS_PACKET_HND_ALLW ); 
    pResPacket->write32u((uint32_t)m_nSendRate);
    pResPacket->ToBuffer( m_pOutput );
    OnWrite();
	pResPacket->Release();
    
    theLogger.Message(MSG_SYSTEM,"Client Join %s, Request Movie %s", m_RemoteEndpoint.GetHostString(),m_sMediaName.c_str() );
    
    return true;
}
示例#28
0
// Talk to the other computer, write the output buffer to the socket and read from the socket to the input buffer
// Return true if this worked, false if we've lost the connection
BOOL CConnection::DoRun()
{
	// If this socket is invalid, call OnRun and return the result (do)
	if ( ! IsValid() )
		return OnRun();

	// Setup pEvents to store the socket's internal information about network events
	WSANETWORKEVENTS pEvents = {};
	if ( WSAEnumNetworkEvents( m_hSocket, NULL, &pEvents ) != 0 )
		return FALSE;

	// If the FD_CONNECT network event has occurred
	if ( pEvents.lNetworkEvents & FD_CONNECT )
	{
		// If there is a nonzero error code for the connect operation, this connection was dropped
		if ( pEvents.iErrorCode[ FD_CONNECT_BIT ] != 0 )
		{
			Statistics.Current.Connections.Errors++;

			OnDropped();
			return FALSE;
		}

		// The socket is now connected
		m_bConnected = TRUE;
		m_tConnected = m_mInput.tLast = m_mOutput.tLast = GetTickCount();	// Store the time 3 places

		// Call CShakeNeighbour::OnConnected to start reading the handshake
		if ( ! OnConnected() )
			return FALSE;

		Network.AcquireLocalAddress( m_hSocket );
	}

	// If the FD_CLOSE network event has occurred, set bClosed to true, otherwise set it to false
	BOOL bClosed = ( pEvents.lNetworkEvents & FD_CLOSE ) ? TRUE : FALSE;

	// If the close event happened, null a pointer within the TCP bandwidth meter for input (do)
	if ( bClosed )
		m_mInput.pLimit = NULL;

	// Change the queued run state to 1 (do)
	m_nQueuedRun = 1;

	// Write the contents of the output buffer to the remote computer, and read in data it sent us
	if ( ! OnWrite() )
		return FALSE;
	if ( ! OnRead() )
		return FALSE;

	// If the close event happened
	if ( bClosed )
	{
		// theApp.Message( MSG_DEBUG, _T("socket close() error %i"), pEvents.iErrorCode[ FD_CLOSE_BIT ] );
		// Call OnDropped, telling it true if there is a close error
		OnDropped();	// True if there is an nonzero error code for the close bit
		return FALSE;
	}

	// Make sure the handshake doesn't take too long
	if ( ! OnRun() )
		return FALSE;

	// If the queued run state is 2 and OnWrite returns false, leave here with false also
	if ( m_nQueuedRun == 2 && ! OnWrite() )
		return FALSE;

	// Change the queued run state back to 0 and report success (do)
	m_nQueuedRun = 0;
	return TRUE;
}
示例#29
0
文件: Remote.cpp 项目: GetEnvy/Envy
BOOL CRemote::OnHeadersComplete()
{
	if ( m_sHandshake.Find( L"GET /" ) != 0 )
	{
		Close();
		delete this;
		return FALSE;
	}

	m_sHandshake = m_sHandshake.Mid( 4 ).SpanExcluding( L" \t" );

	CString strPath = m_sHandshake.SpanExcluding( L"?&" );
	ToLower( strPath );

	m_sRedirect.Empty();
	m_sHeader.Empty();
	m_sResponse.Empty();
	m_pResponse.Clear();

	PageSwitch( strPath );

	if ( ! m_sRedirect.IsEmpty() )
	{
		Write( _P("HTTP/1.1 302 Found\r\n") );
		Write( _P("Content-Length: 0\r\n") );
		if ( ! m_sHeader.IsEmpty() )
			Write( m_sHeader );
		Write( _P("Location: ") );
		Write( m_sRedirect );
		Write( _P("\r\n") );
	}
	else if ( ! m_sResponse.IsEmpty() )
	{
		CString strLength;
		Prepare();
		Output( L"tail" );
		int nBytes = WideCharToMultiByte( CP_UTF8, 0, m_sResponse, m_sResponse.GetLength(), NULL, 0, NULL, NULL );
		strLength.Format( L"Content-Length: %i\r\n", nBytes );
		Write( _P("HTTP/1.1 200 OK\r\n") );
		Write( _P("Content-Type: text/html; charset=UTF-8\r\n") );
		Write( strLength );
		if ( ! m_sHeader.IsEmpty() )
			Write( m_sHeader );
	}
	else if ( m_pResponse.m_nLength > 0 )
	{
		Write( _P("HTTP/1.1 200 OK\r\n") );
		CString strLength;
		strLength.Format( L"Content-Length: %u\r\n", m_pResponse.m_nLength );
		Write( strLength );
		if ( ! m_sHeader.IsEmpty() ) Write( m_sHeader );
	}
	else
	{
		Write( _P("HTTP/1.1 404 Not Found\r\n") );
		Write( _P("Content-Length: 0\r\n") );
		Write( _P("Content-Type: text/html\r\n") );
	}

	LogOutgoing();

	Write( _P("\r\n") );
	if ( ! m_sResponse.IsEmpty() )
	{
		Write( m_sResponse, CP_UTF8 );
		m_sResponse.Empty();
	}
	else if ( m_pResponse.m_nLength > 0 )
	{
		Write( &m_pResponse );
	}

	m_sHandshake.Empty();
	ClearHeaders();
	OnWrite();

	return TRUE;
}
示例#30
0
HRESULT WpdObjectResources::DispatchWpdMessage(
    const PROPERTYKEY&     Command,
    IPortableDeviceValues* pParams,
    IPortableDeviceValues* pResults)
{

    HRESULT hr = S_OK;

    if (hr == S_OK)
    {
        if (Command.fmtid != WPD_CATEGORY_OBJECT_RESOURCES)
        {
            hr = E_INVALIDARG;
            CHECK_HR(hr, "This object does not support this command category %ws",CComBSTR(Command.fmtid));
        }
    }

    if (hr == S_OK)
    {
        if (IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_GET_SUPPORTED))
        {
            hr = OnGetSupportedResources(pParams, pResults);
            CHECK_HR(hr, "Failed to get supported resources");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_GET_ATTRIBUTES))
        {
            hr = OnGetAttributes(pParams, pResults);
            if(FAILED(hr))
            {
                CHECK_HR(hr, "Failed to get resource attributes");
            }
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_OPEN))
        {
            hr = OnOpen(pParams, pResults);
            CHECK_HR(hr, "Failed to open resource");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_READ))
        {
            hr = OnRead(pParams, pResults);
            CHECK_HR(hr, "Failed to read resource data");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_WRITE))
        {
            hr = OnWrite(pParams, pResults);
            CHECK_HR(hr, "Failed to write resource data");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_CLOSE))
        {
            hr = OnClose(pParams, pResults);
            CHECK_HR(hr, "Failed to close resource");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_DELETE))
        {
            hr = OnDelete(pParams, pResults);
            CHECK_HR(hr, "Failed to delete resources");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_CREATE_RESOURCE))
        {
            hr = OnCreate(pParams, pResults);
            CHECK_HR(hr, "Failed to create resource");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_REVERT))
        {
            hr = OnRevert(pParams, pResults);
            CHECK_HR(hr, "Failed to revert resource operation");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_SEEK))
        {
            hr = OnSeek(pParams, pResults);
            CHECK_HR(hr, "Failed resource seek operation");
        }
        else
        {
            hr = E_NOTIMPL;
            CHECK_HR(hr, "This object does not support this command id %d", Command.pid);
        }
    }
    return hr;
}