示例#1
0
CTransferSocket::~CTransferSocket()
{
	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("~CTransferSocket()"));
	nb_free(m_pBuffer);
#ifndef MPEXT_NO_ZLIB
	nb_free(m_pBuffer2);
#endif
	PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), 0);
	Close();
	RemoveAllLayers();
	delete m_pProxyLayer;
#ifndef MPEXT_NO_SSL
	delete m_pSslLayer;
#endif
#ifndef MPEXT_NO_GSS
	delete m_pGssLayer;
#endif
	m_pOwner->RemoveActiveTransfer();

	delete m_pListResult;

#ifndef MPEXT_NO_ZLIB
	if (m_useZlib)
	{
		if (m_nMode & CSMODE_UPLOAD)
			deflateEnd(&m_zlibStream);
		else
			inflateEnd(&m_zlibStream);
	}
#endif
}
CTransferSocket::~CTransferSocket()
{
  nb_free(m_pBuffer);
#ifndef MPEXT_NO_ZLIB
  nb_free(m_pBuffer2);
#endif
  GetIntern()->FZPostMessage(FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), 0);
  Close();
  RemoveAllLayers();
  delete m_pProxyLayer;
  delete m_pSslLayer;
#ifndef MPEXT_NO_GSS
  delete m_pGssLayer;
#endif
  m_pOwner->RemoveActiveTransfer();

  delete m_pListResult;

#ifndef MPEXT_NO_ZLIB
  if (m_useZlib)
  {
    if (m_nMode & CSMODE_UPLOAD)
      deflateEnd(&m_zlibStream);
    else
      inflateEnd(&m_zlibStream);
  }
#endif
}
示例#3
0
void DynamicQueue<TX>::ReAllocate(int num) {
   // Increase size of memory buffer. 
   // This function is used only internally. 
   // Note: ReAllocate leaves OldBuffer to be deleted by the calling function
   if (OldBuffer) nb_free(OldBuffer);            // Should not occur in single-threaded applications

   TX * Buffer2 = 0;                             // New buffer
   Buffer2 = static_cast<TX *>(nb_malloc(sizeof(TX) * num));                        // Allocate new buffer
   if (Buffer2 == 0) {Error(3,num); return;}     // Error can't allocate
   if (Buffer) {
      // A smaller buffer is previously allocated
      // Copy queue from old to new buffer
      if (tail < head) {
         // trail is unbroken, copy as one block
         memcpy(Buffer2, Buffer + tail, NumEntries*sizeof(TX));
      }
      else if (NumEntries) {
         // trail is wrapping around or full, copy two blocks
         memcpy(Buffer2, Buffer + tail, (MaxNum - tail)*sizeof(TX));
         if (head) {
            memcpy(Buffer2 + (MaxNum - tail), Buffer, head*sizeof(TX));
         }
      }
      // Reset head and tail
      tail = 0;  head = NumEntries;
   }
   OldBuffer = Buffer;                           // Save old buffer. Deleted by calling function
   Buffer = Buffer2;                             // Save pointer to buffer
   MaxNum = num;                                 // Save new size
}
示例#4
0
void * TMemoryStream::Realloc(__int64 & NewCapacity)
{
  if ((NewCapacity > 0) && (NewCapacity != FSize))
  {
    NewCapacity = (NewCapacity + (MemoryDelta - 1)) & ~(MemoryDelta - 1);
  }
  void * Result = FMemory;
  if (NewCapacity != FCapacity)
  {
    if (NewCapacity == 0)
    {
      nb_free(FMemory);
      FMemory = nullptr;
      Result = nullptr;
    }
    else
    {
      if (FCapacity == 0)
      {
        Result = nb_malloc(static_cast<size_t>(NewCapacity));
      }
      else
      {
        Result = nb_realloc(FMemory, static_cast<size_t>(NewCapacity));
      }
      if (Result == nullptr)
      {
        throw EStreamError(FMTLOAD(SMemoryStreamError));
      }
    }
  }
  return Result;
}
示例#5
0
BOOL CAsyncSocketExLayer::CreateNext(UINT nSocketPort, int nSocketType, long lEvent, LPCTSTR lpszSocketAddress, int nFamily /*=AF_INET*/)
{
  DebugAssert(GetLayerState()==notsock);
  BOOL res = FALSE;

  m_nFamily = nFamily;

  if (m_pNextLayer)
    res = m_pNextLayer->Create(nSocketPort, nSocketType, lEvent, lpszSocketAddress, nFamily);
  else if (m_nFamily == AF_UNSPEC)
  {
    m_lEvent = lEvent;
    nb_free(m_lpszSocketAddress);
    if (lpszSocketAddress && *lpszSocketAddress)
    {
      m_lpszSocketAddress = static_cast<TCHAR *>(nb_calloc(_tcslen(lpszSocketAddress) + 1, sizeof(TCHAR)));
      _tcscpy(m_lpszSocketAddress, lpszSocketAddress);
    }
    else
      m_lpszSocketAddress = 0;
    m_nSocketPort = nSocketPort;
    res = TRUE;
  }
  else
  {
    SOCKET hSocket=socket(nFamily, nSocketType, 0);
    if (hSocket == INVALID_SOCKET)
    {
      m_pOwnerSocket->Close();
      return FALSE;
    }
    m_pOwnerSocket->m_SocketData.hSocket=hSocket;
    m_pOwnerSocket->AttachHandle(hSocket);
    if (!m_pOwnerSocket->AsyncSelect(lEvent))
    {
      m_pOwnerSocket->Close();
      return FALSE;
    }
    if (m_pOwnerSocket->m_pFirstLayer)
    {
      if (WSAAsyncSelect(m_pOwnerSocket->m_SocketData.hSocket, m_pOwnerSocket->GetHelperWindowHandle(), m_pOwnerSocket->m_SocketData.nSocketIndex+WM_SOCKETEX_NOTIFY, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE) )
      {
        m_pOwnerSocket->Close();
        return FALSE;
      }
    }
    if (!m_pOwnerSocket->Bind(nSocketPort, lpszSocketAddress))
    {
      m_pOwnerSocket->Close();
      return FALSE;
    }
    res = TRUE;
  }
  if (res)
    SetLayerState(unconnected);
  return res;
}
示例#6
0
BOOL CAsyncSocketExLayer::GetPeerNameNext( CString& rPeerAddress, UINT& rPeerPort )
{
  if (m_pNextLayer)
  {
    return m_pNextLayer->GetPeerName(rPeerAddress, rPeerPort);
  }
  else
  {
    SOCKADDR* sockAddr = NULL;
    int nSockAddrLen = 0;

    if (m_nFamily == AF_INET6)
    {
      sockAddr = (SOCKADDR*)new SOCKADDR_IN6;
      nSockAddrLen = sizeof(SOCKADDR_IN6);
    }
    else if (m_nFamily == AF_INET)
    {
      sockAddr = (SOCKADDR*)new SOCKADDR_IN;
      nSockAddrLen = sizeof(SOCKADDR_IN);
    }

    memset(sockAddr, 0, nSockAddrLen);

    BOOL bResult = GetPeerName(sockAddr, &nSockAddrLen);

    if (bResult)
    {
      if (m_nFamily == AF_INET6)
      {
        rPeerPort = ntohs(((SOCKADDR_IN6*)sockAddr)->sin6_port);
        LPTSTR buf = Inet6AddrToString(((SOCKADDR_IN6*)sockAddr)->sin6_addr);
        rPeerAddress = buf;
        nb_free(buf);
      }
      else if (m_nFamily == AF_INET)
      {
        rPeerPort = ntohs(((SOCKADDR_IN*)sockAddr)->sin_port);
        rPeerAddress = inet_ntoa(((SOCKADDR_IN*)sockAddr)->sin_addr);
      }
      else
      {
        delete sockAddr;
        return FALSE;
      }
    }
    delete sockAddr;

    return bResult;
  }
}
示例#7
0
  //Adds a socket to the list of attached sockets
  BOOL AddSocket(CAsyncSocketEx *pSocket, int &nSocketIndex)
  {
    DebugAssert(pSocket);
    if (!m_nWindowDataSize)
    {
      DebugAssert(!m_nSocketCount);
      m_nWindowDataSize=512;
      m_pAsyncSocketExWindowData=static_cast<t_AsyncSocketExWindowData *>(nb_calloc(512, sizeof(t_AsyncSocketExWindowData))); //Reserve space for 512 active sockets
      memset(m_pAsyncSocketExWindowData, 0, 512*sizeof(t_AsyncSocketExWindowData));
    }

    if (nSocketIndex!=-1)
    {
      DebugAssert(m_pAsyncSocketExWindowData);
      DebugAssert(m_nWindowDataSize>nSocketIndex);
      DebugAssert(m_pAsyncSocketExWindowData[nSocketIndex].m_pSocket==pSocket);
      DebugAssert(m_nSocketCount);
      return TRUE;
    }

    //Increase socket storage if too small
    if (m_nSocketCount>=(m_nWindowDataSize-10))
    {
      int nOldWindowDataSize=m_nWindowDataSize;
      DebugAssert(m_nWindowDataSize<MAX_SOCKETS);
      m_nWindowDataSize+=512;
      if (m_nWindowDataSize>MAX_SOCKETS)
        m_nWindowDataSize=MAX_SOCKETS;
      t_AsyncSocketExWindowData *tmp=m_pAsyncSocketExWindowData;
      m_pAsyncSocketExWindowData = static_cast<t_AsyncSocketExWindowData *>(nb_calloc(m_nWindowDataSize, sizeof(t_AsyncSocketExWindowData)));
      memcpy(m_pAsyncSocketExWindowData, tmp, nOldWindowDataSize * sizeof(t_AsyncSocketExWindowData));
      memset(m_pAsyncSocketExWindowData+nOldWindowDataSize, 0, (m_nWindowDataSize-nOldWindowDataSize)*sizeof(t_AsyncSocketExWindowData));
      nb_free(tmp);
    }

    //Search for free slot
    for (int i=m_nWindowDataPos;i<(m_nWindowDataSize+m_nWindowDataPos);i++)
    {
      if (!m_pAsyncSocketExWindowData[i%m_nWindowDataSize].m_pSocket)
      {
        m_pAsyncSocketExWindowData[i%m_nWindowDataSize].m_pSocket=pSocket;
        nSocketIndex=i%m_nWindowDataSize;
        m_nWindowDataPos=(i+1)%m_nWindowDataSize;
        m_nSocketCount++;
        return TRUE;
      }
    }

    //No slot found, maybe there are too much sockets!
    return FALSE;
  }
示例#8
0
void DynamicQueue<TX>::Reserve(int num) {
   // Allocate buffer of the specified size
   // Setting num > current MaxNum will allocate a larger buffer and 
   // move all data to the new buffer.
   // Setting num <= current MaxNum will do nothing. The buffer will 
   // only grow, not shrink.
   // Setting num = 0 will discard all data and de-allocate the buffer.
   if (num <= MaxNum) {
      if (num <= 0) {
         if (num < 0) Error(1, num);
         // num = 0. Discard data and de-allocate buffer
         if (Buffer) nb_free(Buffer);            // De-allocate buffer
         Buffer = 0;                             // Reset everything
         MaxNum = NumEntries = head = tail = 0;
         return;
      }
      // Request to reduce size. Ignore
      return;
   }
   // num > MaxNum. Increase Buffer
   ReAllocate(num);
   // OldBuffer must be deleted after calling ReAllocate
   if (OldBuffer) {nb_free(OldBuffer);  OldBuffer = 0;}
}
示例#9
0
  virtual ~CAsyncSocketExHelperWindow()
  {
    //Clean up socket storage
    nb_free(m_pAsyncSocketExWindowData);
    m_pAsyncSocketExWindowData=0;
    m_nWindowDataSize=0;
    m_nSocketCount=0;

    //Destroy window
    if (m_hWnd)
    {
      DestroyWindow(m_hWnd);
      m_hWnd=0;
    }
  }
示例#10
0
void DynamicQueue<TX>::Put(const TX & obj) {
   // Add object to buffer, return index

   if (NumEntries >= MaxNum) {
      // buffer too small or no buffer. Allocate more memory
      // Determine new size = 2 * current size + the number of objects that correspond to AllocateSpace
      int NewSize = MaxNum * 2 + (AllocateSpace+sizeof(TX)-1)/sizeof(TX);

      ReAllocate(NewSize);
   }
   // Insert new object at head
   Buffer[head] = obj;
   // Delete old buffer after copying object, in case obj was in old buffer
   if (OldBuffer) {nb_free(OldBuffer);  OldBuffer = 0;}
   // Make head point to next vacant slot
   if (++head >= MaxNum) head = 0;
   // Count entries
   NumEntries++;
}
示例#11
0
int CControlSocket::OnLayerCallback(rde::list<t_callbackMsg>& callbacks)
{
	USES_CONVERSION;

	for (rde::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
	{
		if (iter->nType == LAYERCALLBACK_STATECHANGE)
		{
		    if (CAsyncSocketEx::LogStateChange(iter->nParam1, iter->nParam2))
		    {
			    const TCHAR * state2Desc = CAsyncSocketEx::GetStateDesc(iter->nParam2);
			    const TCHAR * state1Desc = CAsyncSocketEx::GetStateDesc(iter->nParam1);
				if (iter->pLayer == m_pProxyLayer)
					LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Proxy layer changed state from %s to %s"), state2Desc, state1Desc);
#ifndef MPEXT_NO_GSS
				else if (iter->pLayer == m_pGssLayer)
					LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pGssLayer changed state from %s to %s"), state2Desc, state1Desc);
#endif
				else
					LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Layer @ %d changed state from %s to %s"), iter->pLayer, state2Desc, state1Desc);
			}
		}
		else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
		{
			if (iter->pLayer == m_pProxyLayer)
			{
				switch (iter->nParam1)
				{
				case PROXYERROR_NOERROR:
					ShowStatus(IDS_PROXY_CONNECTED, FZ_LOG_STATUS);
					break;
				case PROXYERROR_NOCONN:
					ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, FZ_LOG_ERROR);
					break;
				case PROXYERROR_REQUESTFAILED:
					ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, FZ_LOG_ERROR);
					if (iter->str)
						ShowStatus(A2T(iter->str), FZ_LOG_ERROR);
					break;
				case PROXYERROR_AUTHTYPEUNKNOWN:
					ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, FZ_LOG_ERROR);
					break;
				case PROXYERROR_AUTHFAILED:
					ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, FZ_LOG_ERROR);
					break;
				case PROXYERROR_AUTHNOLOGON:
					ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, FZ_LOG_ERROR);
					break;
				case PROXYERROR_CANTRESOLVEHOST:
					ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, FZ_LOG_ERROR);
					break;
				default:
					LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Unknown proxy error") );
				}
			}
#ifndef MPEXT_NO_GSS
			else if (iter->pLayer == m_pGssLayer)
			{
				switch (iter->nParam1)
				{
				case GSS_INFO:
					LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
					break;
				case GSS_ERROR:
					LogMessageRaw(FZ_LOG_APIERROR, A2CT(iter->str));
					break;
				case GSS_COMMAND:
					ShowStatus(A2CT(iter->str), FZ_LOG_COMMAND);
					break;
				case GSS_REPLY:
					ShowStatus(A2CT(iter->str), FZ_LOG_REPLY);
					break;
				}
			}
#endif
		}

		nb_free(iter->str);
	}

	return 1;
}
/////////////////////////////////////////////////////////////////////////////
// Member-Funktion CTransferSocket
void CTransferSocket::OnReceive(int nErrorCode)
{
  if (GetState() != connected && GetState() != attached && GetState() != closed)
    return;
  if (m_nTransferState == STATE_WAITING)
  {
    m_nNotifyWaiting |= FD_READ;
    return;
  }

  if (m_bSentClose)
    return;
  if (m_bListening)
    return;

  if (m_nMode&CSMODE_LIST)
  {
    if (m_nTransferState == STATE_STARTING)
      OnConnect(0);

    char *buffer = nb::chcalloc(BUFSIZE);
    int numread = CAsyncSocketEx::Receive(buffer, BUFSIZE);
    if (numread != SOCKET_ERROR && numread)
    {
      m_LastActiveTime = CTime::GetCurrentTime();

#ifndef MPEXT_NO_ZLIB
      if (m_useZlib)
      {
        m_zlibStream.next_in = (Bytef *)buffer;
        m_zlibStream.avail_in = numread;
        char *out = nb::calloc(BUFSIZE);
        m_zlibStream.next_out = (Bytef *)out;
        m_zlibStream.avail_out = BUFSIZE;
        int res = inflate(&m_zlibStream, 0);
        while (res == Z_OK)
        {
          m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
          out = nb::calloc(BUFSIZE);
          m_zlibStream.next_out = (Bytef *)out;
          m_zlibStream.avail_out = BUFSIZE;
          res = inflate(&m_zlibStream, 0);
        }
        nb_free(buffer);
        if (res == Z_STREAM_END)
          m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
        else if (res != Z_OK && res != Z_BUF_ERROR)
        {
          nb_free(out);
          CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
          return;
        }
        else
          nb_free(out);
      }
      else
#endif
        m_pListResult->AddData(buffer, numread);
      m_transferdata.transfersize += numread;
      t_ffam_transferstatus *status = new t_ffam_transferstatus();
      status->bFileTransfer = FALSE;
      status->transfersize = -1;
      status->bytes = m_transferdata.transfersize;
      GetIntern()->FZPostMessage(FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
    }
    else
      nb_free(buffer);
    if (!numread)
    {
      CloseAndEnsureSendClose(0);
    }
    if (numread == SOCKET_ERROR)
    {
      int nError = GetLastError();
      if (nError == WSAENOTCONN)
      {
        //Not yet connected
        return;
      }
      else if (m_pSslLayer && nError == WSAESHUTDOWN)
      {
        // Do nothing, wait for shutdown complete notification.
        return;
      }
      else if (nError != WSAEWOULDBLOCK)
      {
        LogError(nError);
        CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
      }
    }
  }
  else if (m_nMode & CSMODE_DOWNLOAD)
  {
    if (m_nTransferState == STATE_STARTING)
      OnConnect(0);

    bool beenWaiting = false;
    _int64 ableToRead;
    if (GetState() != closed)
      ableToRead = m_pOwner->GetAbleToTransferSize(CFtpControlSocket::download, beenWaiting);
    else
      ableToRead = BUFSIZE;

    if (!beenWaiting)
      DebugAssert(ableToRead);
    else if (!ableToRead)
    {
      TriggerEvent(FD_READ);
      return;
    }

    if (!m_pBuffer)
      m_pBuffer = nb::chcalloc(BUFSIZE);

    int numread = CAsyncSocketEx::Receive(m_pBuffer, static_cast<int>(ableToRead));
    if (numread!=SOCKET_ERROR)
    {
      m_pOwner->SpeedLimitAddTransferredBytes(CFtpControlSocket::download, numread);
    }

    if (!numread)
    {
      CloseAndEnsureSendClose(0);
      return;
    }

    if (numread == SOCKET_ERROR)
    {
      int nError = GetLastError();
      if (nError == WSAENOTCONN)
      {
        //Not yet connected
        return;
      }
      else if (m_pSslLayer && nError == WSAESHUTDOWN)
      {
        // Do nothing, wait for shutdown complete notification.
        return;
      }
      else if (nError != WSAEWOULDBLOCK)
      {
        LogError(nError);
        CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
      }

      UpdateStatusBar(false);
      return;
    }

    int written = 0;
    m_LastActiveTime = CTime::GetCurrentTime();
    TRY
    {
#ifndef MPEXT_NO_ZLIB
      if (m_useZlib)
      {
        if (!m_pBuffer2)
          m_pBuffer2 = nb::calloc(BUFSIZE);

        m_zlibStream.next_in = (Bytef *)m_pBuffer;
        m_zlibStream.avail_in = numread;
        m_zlibStream.next_out = (Bytef *)m_pBuffer2;
        m_zlibStream.avail_out = BUFSIZE;
        int res = inflate(&m_zlibStream, 0);
        while (res == Z_OK)
        {
          m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
          written += BUFSIZE - m_zlibStream.avail_out;
          m_zlibStream.next_out = (Bytef *)m_pBuffer2;
          m_zlibStream.avail_out = BUFSIZE;
          res = inflate(&m_zlibStream, 0);
        }
        if (res == Z_STREAM_END)
        {
          m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
          written += BUFSIZE - m_zlibStream.avail_out;
        }
        else if (res != Z_OK && res != Z_BUF_ERROR)
        {
          m_pOwner->ShowStatus(L"Compression error", FZ_LOG_ERROR);
          CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
          return;
        }
      }
      else
#endif
      {
        m_pFile->Write(m_pBuffer, numread);
        written = numread;
      }
    }
    CATCH(CFileException,e)
    {
      LPTSTR msg = nb::wchcalloc(BUFSIZE);
      if (e->GetErrorMessage(msg, BUFSIZE))
        m_pOwner->ShowStatus(msg, FZ_LOG_ERROR);
      nb_free(msg);
      CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
      return;
    }
    END_CATCH;
    m_transferdata.transferleft -= written;

    UpdateStatusBar(false);
  }
示例#13
0
/////////////////////////////////////////////////////////////////////////////
// Member-Funktion CTransferSocket
void CTransferSocket::OnReceive(int nErrorCode)
{
	if (GetState() != connected && GetState() != attached && GetState() != closed)
		return;
	if (m_nTransferState == STATE_WAITING)
	{
		m_nNotifyWaiting |= FD_READ;
		return;
	}

	if (m_bSentClose)
		return;
	if (m_bListening)
		return;

	if (m_nMode&CSMODE_LIST)
	{
		if (m_nTransferState == STATE_STARTING)
			OnConnect(0);

		char *buffer = static_cast<char *>(nb_calloc(1, BUFSIZE));
		int numread = CAsyncSocketEx::Receive(buffer, BUFSIZE);
		if (numread != SOCKET_ERROR && numread)
		{
			m_LastActiveTime = CTime::GetCurrentTime();
			UpdateRecvLed();

#ifndef MPEXT_NO_ZLIB
			if (m_useZlib)
			{
				m_zlibStream.next_in = (Bytef *)buffer;
				m_zlibStream.avail_in = numread;
				char *out = static_cast<char *>(nb_calloc(1, BUFSIZE));
				m_zlibStream.next_out = (Bytef *)out;
				m_zlibStream.avail_out = BUFSIZE;
				int res = inflate(&m_zlibStream, 0);
				while (res == Z_OK)
				{
					m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
					out = static_cast<char *>(nb_calloc(1, BUFSIZE));
					m_zlibStream.next_out = (Bytef *)out;
					m_zlibStream.avail_out = BUFSIZE;
					res = inflate(&m_zlibStream, 0);
				}
				nb_free(buffer);
				if (res == Z_STREAM_END)
					m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
				else if (res != Z_OK && res != Z_BUF_ERROR)
				{
					nb_free(out);
					CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
					return;
				}
				else
					nb_free(out);
			}
			else
#endif
				m_pListResult->AddData(buffer, numread);
			m_transferdata.transfersize += numread;
			CTimeSpan timespan = CTime::GetCurrentTime() - m_StartTime;
			int elapsed = (int)timespan.GetTotalSeconds();
			//TODO
			//There are servers which report the total number of
			//bytes in the list response message, but yet it is not supported by FZ.
			/*double leftmodifier=(transfersize-transferstart-transferleft);
			leftmodifier*=100;
			leftmodifier/=(transfersize-transferstart);
			if (leftmodifier==0)
				leftmodifier=1;
			double leftmodifier2=100-leftmodifier;
			int left=(int)((elapsed/leftmodifier)*leftmodifier2);
			int percent=MulDiv(100,transfersize-transferleft,transfersize);*/
			int transferrate=static_cast<int>( (elapsed && m_transferdata.transfersize)?m_transferdata.transfersize/elapsed:0 );
			t_ffam_transferstatus *status = new t_ffam_transferstatus;
			status->bFileTransfer = FALSE;
#ifdef MPEXT
			status->transfersize = -1;
#endif
			status->bytes = m_transferdata.transfersize;
			status->percent = -1;
			status->timeelapsed = elapsed;
			status->timeleft = -1;
			status->transferrate = transferrate;
			PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
		}
		else
			nb_free(buffer);
		if (!numread)
		{
			CloseAndEnsureSendClose(0);
		}
		if (numread == SOCKET_ERROR)
		{
			int nError = GetLastError();
			if (nError == WSAENOTCONN)
			{
				//Not yet connected
				return;
			}
#ifndef MPEXT_NO_SSL
			else if (m_pSslLayer && nError == WSAESHUTDOWN)
			{
				// Do nothing, wait for shutdown complete notification.
				return;
			}
#endif
			else if (nError != WSAEWOULDBLOCK)
			{
				LogError(nError);
				CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
			}
		}
	}
	else if (m_nMode & CSMODE_DOWNLOAD)
	{
		if (m_nTransferState == STATE_STARTING)
			OnConnect(0);

		bool beenWaiting = false;
		_int64 ableToRead;
		if (GetState() != closed)
			ableToRead = m_pOwner->GetAbleToTransferSize(CControlSocket::download, beenWaiting);
		else
			ableToRead = BUFSIZE;

		if (!beenWaiting)
			ASSERT(ableToRead);
		else if (!ableToRead)
		{
			TriggerEvent(FD_READ);
			return;
		}

		if (!m_pBuffer)
			m_pBuffer = static_cast<char *>(nb_calloc(1, BUFSIZE));

		int numread = CAsyncSocketEx::Receive(m_pBuffer, static_cast<int>(ableToRead));
		if (numread!=SOCKET_ERROR)
		{
			Transfered( numread, CTime::GetCurrentTime());
			m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::download, numread);
		}

		if (!numread)
		{
			CloseAndEnsureSendClose(0);
			return;
		}

		if (numread == SOCKET_ERROR)
		{
			int nError = GetLastError();
			if (nError == WSAENOTCONN)
			{
				//Not yet connected
				return;
			}
#ifndef MPEXT_NO_SSL
			else if (m_pSslLayer && nError == WSAESHUTDOWN)
			{
				// Do nothing, wait for shutdown complete notification.
				return;
			}
#endif
			else if (nError != WSAEWOULDBLOCK)
			{
				LogError(nError);
				CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
			}

			UpdateStatusBar(false);
			return;
		}

		int written = 0;
		m_LastActiveTime = CTime::GetCurrentTime();
		UpdateRecvLed();
		TRY
		{
#ifndef MPEXT_NO_ZLIB
			if (m_useZlib)
			{
				if (!m_pBuffer2)
					m_pBuffer2 = static_cast<char *>(nb_calloc(1, BUFSIZE));

				m_zlibStream.next_in = (Bytef *)m_pBuffer;
				m_zlibStream.avail_in = numread;
				m_zlibStream.next_out = (Bytef *)m_pBuffer2;
				m_zlibStream.avail_out = BUFSIZE;
				int res = inflate(&m_zlibStream, 0);
				while (res == Z_OK)
				{
					m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
					written += BUFSIZE - m_zlibStream.avail_out;
					m_zlibStream.next_out = (Bytef *)m_pBuffer2;
					m_zlibStream.avail_out = BUFSIZE;
					res = inflate(&m_zlibStream, 0);
				}
				if (res == Z_STREAM_END)
				{
					m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
					written += BUFSIZE - m_zlibStream.avail_out;
				}
				else if (res != Z_OK && res != Z_BUF_ERROR)
				{
					m_pOwner->ShowStatus(L"Compression error", FZ_LOG_ERROR);
					CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
					return;
				}
			}
			else
#endif
			{
				m_pFile->Write(m_pBuffer, numread);
				written = numread;
			}
		}
		CATCH(CFileException,e)
		{
			LPTSTR msg = static_cast<TCHAR *>(nb_calloc(BUFSIZE, sizeof(TCHAR)));
			if (e->GetErrorMessage(msg, BUFSIZE))
				m_pOwner->ShowStatus(msg, FZ_LOG_ERROR);
			nb_free(msg);
			CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
			return;
		}
		END_CATCH;
		m_transferdata.transferleft -= written;

		UpdateStatusBar(false);
	}
示例#14
0
CAsyncSocketExLayer::~CAsyncSocketExLayer()
{
  nb_free(m_lpszSocketAddress);
}
示例#15
0
BOOL AFXAPI AfxUnlockTempMaps(BOOL bDeleteTemps)
{
	AFX_MODULE_THREAD_STATE* pState = AfxGetModuleThreadState();
	if (pState->m_nTempMapLock != 0 && --pState->m_nTempMapLock == 0)
	{
		if (bDeleteTemps)
		{
			if (bDeleteTemps != -1)
			{
				// allow COM libraries to be freed
				CWinThread* pThread = AfxGetThread();
				if (pThread != NULL && pThread->m_lpfnOleTermOrFreeLib != NULL)
					(*pThread->m_lpfnOleTermOrFreeLib)(FALSE, FALSE);
			}

			// clean up temp objects
			// pState->m_pmapHGDIOBJ->DeleteTemp();
			// pState->m_pmapHDC->DeleteTemp();
			// pState->m_pmapHMENU->DeleteTemp();
			// pState->m_pmapHWND->DeleteTemp();
			// pState->m_pmapHIMAGELIST->DeleteTemp();
		}

#ifndef _AFX_PORTABLE
		CWinApp* pApp = AfxGetApp();
		_AFX_THREAD_STATE* pThreadState = _afxThreadState.GetDataNA();
		if( pThreadState != NULL )
		{
			// restore safety pool after temp objects destroyed
			if (pApp != NULL &&
				 (pThreadState->m_pSafetyPoolBuffer == NULL ||
				 _msize(pThreadState->m_pSafetyPoolBuffer) < pApp->m_nSafetyPoolSize) &&
				pApp->m_nSafetyPoolSize != 0)
			{
				// attempt to restore the safety pool to its max size
				size_t nOldSize = 0;
				if (pThreadState->m_pSafetyPoolBuffer != NULL)
				{
					nOldSize = _msize(pThreadState->m_pSafetyPoolBuffer);
					nb_free(pThreadState->m_pSafetyPoolBuffer);
				}

				// undo handler trap for the following allocation
				BOOL bEnable = AfxEnableMemoryTracking(FALSE);
				try
				{
					pThreadState->m_pSafetyPoolBuffer = nb_malloc(pApp->m_nSafetyPoolSize);
					if (pThreadState->m_pSafetyPoolBuffer == NULL)
					{
						// at least get the old buffer back
						if (nOldSize != 0)
						{
							//get it back
							pThreadState->m_pSafetyPoolBuffer = nb_malloc(nOldSize);
							ASSERT(pThreadState->m_pSafetyPoolBuffer != NULL);
						}
					}
				}
				catch( CException * )
				{
					AfxEnableMemoryTracking(bEnable);
					throw;
				}
				AfxEnableMemoryTracking(bEnable);
			}
		}
#endif  // !_AFX_PORTABLE
	}

	// return TRUE if temp maps still locked
	return pState->m_nTempMapLock != 0;
}