1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165 |
- //---------------------------------------------------------------------------
- #include "stdafx.h"
- #include "TransferSocket.h"
- #include "mainthread.h"
- #include "AsyncProxySocketLayer.h"
- #ifndef MPEXT_NO_GSS
- #include "AsyncGssSocketLayer.h"
- #endif
- #define BUFSIZE 16384
- #define STATE_WAITING 0
- #define STATE_STARTING 1
- #define STATE_STARTED 2
- /////////////////////////////////////////////////////////////////////////////
- // CTransferSocket
- CTransferSocket::CTransferSocket(CFtpControlSocket *pOwner, int nMode)
- {
- DebugAssert(pOwner);
- InitIntern(pOwner->GetIntern());
- m_pOwner = pOwner;
- m_nMode = nMode;
- m_nTransferState = STATE_WAITING;
- m_bCheckTimeout = FALSE;
- m_pBuffer = 0;
- #ifndef MPEXT_NO_ZLIB
- m_pBuffer2 = 0;
- #endif
- m_bufferpos = 0;
- m_pFile = 0;
- m_bListening = FALSE;
- m_bSentClose = FALSE;
- m_nInternalMessageID = 0;
- m_transferdata.transfersize = 0;
- m_transferdata.transferleft = 0;
- m_nNotifyWaiting = 0;
- m_bShutDown = FALSE;
- UpdateStatusBar(true);
- m_pProxyLayer = NULL;
- m_pSslLayer = NULL;
- #ifndef MPEXT_NO_GSS
- m_pGssLayer = NULL;
- #endif
- if (m_nMode & CSMODE_LIST)
- {
- m_pListResult = new CFtpListResult(pOwner->m_CurrentServer, &pOwner->m_bUTF8);
- m_pListResult->InitIntern(GetIntern());
- }
- else
- m_pListResult = 0;
- m_LastUpdateTime.QuadPart = 0;
- #ifndef MPEXT_NO_ZLIB
- memset(&m_zlibStream, 0, sizeof(m_zlibStream));
- m_useZlib = false;
- #endif
- }
- CTransferSocket::~CTransferSocket()
- {
- delete [] m_pBuffer;
- #ifndef MPEXT_NO_ZLIB
- delete [] m_pBuffer2;
- #endif
- GetIntern()->PostMessage(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
- }
- /////////////////////////////////////////////////////////////////////////////
- // 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 = new char[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 = new char[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 = new char[BUFSIZE];
- m_zlibStream.next_out = (Bytef *)out;
- m_zlibStream.avail_out = BUFSIZE;
- res = inflate(&m_zlibStream, 0);
- }
- delete [] buffer;
- if (res == Z_STREAM_END)
- m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
- else if (res != Z_OK && res != Z_BUF_ERROR)
- {
- delete [] out;
- CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
- return;
- }
- else
- delete [] 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()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
- }
- else
- delete [] 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 = new char[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 = new char[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 = new TCHAR[BUFSIZE];
- if (e->GetErrorMessage(msg, BUFSIZE))
- m_pOwner->ShowStatus(msg, FZ_LOG_ERROR);
- delete [] msg;
- CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
- return;
- }
- END_CATCH;
- m_transferdata.transferleft -= written;
- UpdateStatusBar(false);
- }
- }
- void CTransferSocket::SetBuffers()
- {
- /* Set internal socket send buffer
- * this should fix the speed problems some users have reported
- */
- DWORD value = 0;
- int len = sizeof(value);
- GetSockOpt(SO_SNDBUF, &value, &len);
- int sndbuf = GetOptionVal(OPTION_MPEXT_SNDBUF);
- if (value < sndbuf)
- {
- value = sndbuf;
- SetSockOpt(SO_SNDBUF, &value, sizeof(value));
- }
- // For now we increase receive buffer, whenever send buffer is set.
- // The size is not configurable. The constant taken from FZ.
- if (sndbuf > 0)
- {
- value = 0;
- len = sizeof(value);
- GetSockOpt(SO_RCVBUF, &value, &len);
- int rcvbuf = 4 * 1024 * 1024;
- if (value < rcvbuf)
- {
- value = rcvbuf;
- SetSockOpt(SO_RCVBUF, &value, sizeof(value));
- }
- }
- }
- void CTransferSocket::OnAccept(int nErrorCode)
- {
- m_bListening=FALSE;
- CAsyncSocketEx tmp;
- Accept(tmp);
- SOCKET socket=tmp.Detach();
- CAsyncSocketEx::Close();
- Attach(socket);
- SetBuffers();
- if (m_nTransferState == STATE_STARTING)
- {
- m_nTransferState = STATE_STARTED;
- if (m_pSslLayer)
- {
- AddLayer(m_pSslLayer);
- int res = m_pSslLayer->InitSSLConnection(true, m_pOwner->m_pSslLayer,
- GetOptionVal(OPTION_MPEXT_SSLSESSIONREUSE),
- GetOptionVal(OPTION_MPEXT_MIN_TLS_VERSION),
- GetOptionVal(OPTION_MPEXT_MAX_TLS_VERSION));
- if (res == SSL_FAILURE_INITSSL)
- m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
- if (res)
- {
- CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
- return;
- }
- }
- #ifndef MPEXT_NO_GSS
- if (m_pGssLayer)
- {
- AddLayer(m_pGssLayer);
- }
- #endif
- m_LastActiveTime = CTime::GetCurrentTime();
- }
- }
- void CTransferSocket::ConfigureSocket()
- {
- // Note that FileZilla re-enables Nagle's alg during TLS negotiation.
- // Following post claims that TCP_NODELAY
- // has to be set before connect()
- // http://stackoverflow.com/questions/22583941/what-is-the-workaround-for-tcp-delayed-acknowledgment/25871250#25871250
- int nodelay = GetOptionVal(OPTION_MPEXT_NODELAY);
- if (nodelay != 0)
- {
- BOOL bvalue = TRUE;
- SetSockOpt(TCP_NODELAY, &bvalue, sizeof(bvalue), IPPROTO_TCP);
- }
- CAsyncSocketEx::ConfigureSocket();
- }
- void CTransferSocket::OnConnect(int nErrorCode)
- {
- if (nErrorCode)
- {
- TCHAR buffer[1000];
- memset(buffer, 0, sizeof(buffer));
- FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, nErrorCode, 0, buffer, 999, 0);
- CString str;
- str.Format(IDS_ERRORMSG_CANTOPENTRANSFERCHANNEL,buffer);
- str.Replace( L"\n", L"\0" );
- str.Replace( L"\r", L"\0" );
- m_pOwner->ShowStatus(str, FZ_LOG_ERROR);
- CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
- }
- else
- {
- SetBuffers();
- m_pOwner->ShowStatus(L"Data connection opened", FZ_LOG_INFO);
- }
- if (m_nTransferState == STATE_WAITING)
- {
- // OnReceive (invoked by m_nNotifyWaiting including FD_READ)
- // will call back to OnConnected (as we won't be connected yet).
- // This is needed for file transfers only, where SetActive is
- // called only after 1xx response to RETR (and similar) arrives.
- // But we get FD_CONNECT earlier, hence we get to this branch.
- // With directory listing, SetActive is called before Connect,
- // so we are already STATE_STARTING on FD_CONNECT.
- // It should probably behave the same in both scenarios.
- m_nNotifyWaiting |= FD_READ;
- }
- else if (m_nTransferState == STATE_STARTING)
- {
- m_nTransferState = STATE_STARTED;
- m_LastActiveTime=CTime::GetCurrentTime();
- if (m_pSslLayer)
- {
- AddLayer(m_pSslLayer);
- int res = m_pSslLayer->InitSSLConnection(true, m_pOwner->m_pSslLayer,
- GetOptionVal(OPTION_MPEXT_SSLSESSIONREUSE),
- GetOptionVal(OPTION_MPEXT_MIN_TLS_VERSION),
- GetOptionVal(OPTION_MPEXT_MAX_TLS_VERSION));
- if (res == SSL_FAILURE_INITSSL)
- {
- m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
- }
- if (res)
- {
- CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
- return;
- }
- }
- #ifndef MPEXT_NO_GSS
- if (m_pGssLayer)
- {
- AddLayer(m_pGssLayer);
- }
- #endif
- }
- }
- void CTransferSocket::OnClose(int nErrorCode)
- {
- if (m_nTransferState == STATE_WAITING)
- {
- m_nNotifyWaiting |= FD_CLOSE;
- return;
- }
- m_pOwner->ShowStatus(L"Data connection closed", FZ_LOG_INFO);
- OnReceive(0);
- CloseAndEnsureSendClose(0);
- }
- int CTransferSocket::CheckForTimeout(int delay)
- {
- UpdateStatusBar(false);
- if (!m_bCheckTimeout)
- {
- // we are closed, so make sure the FTP control socket is itself checking for
- // timeout as we are not
- return 0;
- }
- CTimeSpan span = CTime::GetCurrentTime()-m_LastActiveTime;
- if (span.GetTotalSeconds()>=delay)
- {
- m_pOwner->ShowTimeoutError(IDS_DATA_CONNECTION);
- CloseAndEnsureSendClose(CSMODE_TRANSFERTIMEOUT);
- return 2;
- }
- return 1;
- }
- void CTransferSocket::SetActive()
- {
- if (m_nTransferState == STATE_WAITING)
- m_nTransferState = STATE_STARTING;
- m_bCheckTimeout = TRUE;
- m_LastActiveTime = CTime::GetCurrentTime();
- if (m_nNotifyWaiting & FD_READ)
- OnReceive(0);
- if (m_nNotifyWaiting & FD_WRITE)
- OnSend(0);
- if (m_nNotifyWaiting & FD_CLOSE)
- OnClose(0);
- }
- void CTransferSocket::OnSend(int nErrorCode)
- {
- if (m_nTransferState == STATE_WAITING)
- {
- m_nNotifyWaiting |= FD_WRITE;
- return;
- }
- if (m_bSentClose)
- {
- return;
- }
- if (m_bListening)
- {
- return;
- }
- if (!(m_nMode&CSMODE_UPLOAD))
- {
- return;
- }
- if (m_nTransferState == STATE_STARTING)
- {
- OnConnect(0);
- }
- #ifndef MPEXT_NO_ZLIB
- if (m_useZlib)
- {
- if (!m_pBuffer)
- {
- m_pBuffer = new char[BUFSIZE];
- m_bufferpos = 0;
- m_zlibStream.next_out = (Bytef *)m_pBuffer;
- m_zlibStream.avail_out = BUFSIZE;
- }
- if (!m_pBuffer2)
- {
- m_pBuffer2 = new char[BUFSIZE];
- m_zlibStream.next_in = (Bytef *)m_pBuffer2;
- }
- bool beenWaiting = false;
- while (true)
- {
- int numsend;
- if (!m_zlibStream.avail_in)
- {
- if (m_pFile)
- {
- DWORD numread;
- numread = ReadDataFromFile(m_pBuffer2, BUFSIZE);
- if (numread < 0)
- {
- return;
- }
- m_transferdata.transferleft -= numread;
- m_zlibStream.next_in = (Bytef *)m_pBuffer2;
- m_zlibStream.avail_in = numread;
- if (numread < BUFSIZE)
- m_pFile = 0;
- }
- }
- if (!m_zlibStream.avail_out)
- {
- if (m_bufferpos >= BUFSIZE)
- {
- m_bufferpos = 0;
- m_zlibStream.next_out = (Bytef *)m_pBuffer;
- m_zlibStream.avail_out = BUFSIZE;
- }
- }
- int res = Z_OK;
- if (m_zlibStream.avail_out)
- {
- res = deflate(&m_zlibStream, m_pFile ? 0 : Z_FINISH);
- if (res != Z_OK && (!m_pFile && res != Z_STREAM_END))
- {
- m_pOwner->ShowStatus("Decompression error", FZ_LOG_ERROR);
- CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
- return;
- }
- }
- numsend = BUFSIZE;
- int len = BUFSIZE - m_bufferpos - m_zlibStream.avail_out;
- if (!len && !m_pFile)
- {
- break;
- }
- if (len < BUFSIZE)
- numsend = len;
- int nLimit = (int)m_pOwner->GetAbleToTransferSize(CFtpControlSocket::upload, beenWaiting);
- if (nLimit != -1 && GetState() != closed && numsend > nLimit)
- numsend = nLimit;
- if (!numsend)
- {
- TriggerEvent(FD_WRITE);
- return;
- }
- int numsent = Send(m_pBuffer + m_bufferpos, numsend);
- if (numsent == 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)
- {
- CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
- }
- UpdateStatusBar(false);
- return;
- }
- m_pOwner->SpeedLimitAddTransferredBytes(CFtpControlSocket::upload, numsent);
- m_LastActiveTime = CTime::GetCurrentTime();
- m_bufferpos += numsent;
- UpdateStatusBar(false);
- if (!m_zlibStream.avail_in && !m_pFile && m_zlibStream.avail_out &&
- m_zlibStream.avail_out + m_bufferpos == BUFSIZE && res == Z_STREAM_END)
- {
- CloseOnShutDownOrError(0);
- return;
- }
- //Check if there are other commands in the command queue.
- MSG msg;
- if (PeekMessage(&msg,0, 0, 0, PM_NOREMOVE))
- {
- TriggerEvent(FD_WRITE);
- return;
- }
- }
- }
- else
- #endif
- {
- if (!m_pFile)
- {
- return;
- }
- if (!m_pBuffer)
- m_pBuffer = new char[BUFSIZE];
- int numread;
- bool beenWaiting = false;
- _int64 currentBufferSize;
- if (GetState() != closed)
- currentBufferSize = m_pOwner->GetAbleToTransferSize(CFtpControlSocket::upload, beenWaiting);
- else
- currentBufferSize = BUFSIZE;
- if (!currentBufferSize && !m_bufferpos)
- {
- // Not allowed to send yet, try later
- TriggerEvent(FD_WRITE);
- return;
- }
- else if (m_bufferpos < currentBufferSize)
- {
- numread = ReadDataFromFile(m_pBuffer + m_bufferpos, static_cast<int>(currentBufferSize - m_bufferpos));
- if (numread < 0 )
- {
- return;
- }
- else if (!numread && !m_bufferpos)
- {
- CloseOnShutDownOrError(0);
- return;
- }
- }
- else
- numread = 0;
- DebugAssert((numread+m_bufferpos) <= BUFSIZE);
- DebugAssert(numread>=0);
- DebugAssert(m_bufferpos>=0);
- if (numread+m_bufferpos <= 0)
- {
- CloseOnShutDownOrError(0);
- return;
- }
- int numsent = Send(m_pBuffer, numread + m_bufferpos);
- while (TRUE)
- {
- if (numsent != SOCKET_ERROR)
- {
- m_pOwner->SpeedLimitAddTransferredBytes(CFtpControlSocket::upload, numsent);
- m_LastActiveTime = CTime::GetCurrentTime();
- m_transferdata.transferleft -= numsent;
- }
- if (numsent==SOCKET_ERROR || !numsent)
- {
- int nError = GetLastError();
- if (nError == WSAENOTCONN)
- {
- //Not yet connected
- m_bufferpos += numread;
- return;
- }
- else if (nError == WSAEWOULDBLOCK)
- {
- m_bufferpos += numread;
- }
- else if (m_pSslLayer && nError == WSAESHUTDOWN)
- {
- m_bufferpos += numread;
- // Do nothing, wait for shutdown complete notification.
- return;
- }
- else
- {
- CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
- }
- UpdateStatusBar(false);
- return;
- }
- else
- {
- int pos = numread + m_bufferpos - numsent;
- if (pos < 0 || (numsent + pos) > BUFSIZE)
- {
- LogMessage(FZ_LOG_WARNING, L"Index out of range");
- CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
- return;
- }
- else if (!pos && numread < (currentBufferSize-m_bufferpos) && m_bufferpos != currentBufferSize)
- {
- CloseOnShutDownOrError(0);
- return;
- }
- else if (!pos)
- {
- m_bufferpos = 0;
- }
- else
- {
- memmove(m_pBuffer, m_pBuffer+numsent, pos);
- m_bufferpos=pos;
- }
- }
- //Check if there are other commands in the command queue.
- MSG msg;
- if (PeekMessage(&msg, 0, m_nInternalMessageID, m_nInternalMessageID, PM_NOREMOVE))
- {
- //Send resume message
- LogMessage(FZ_LOG_DEBUG, L"Message waiting in queue, resuming later");
- TriggerEvent(FD_WRITE);
- UpdateStatusBar(false);
- return;
- }
- UpdateStatusBar(false);
- if (GetState() != closed)
- currentBufferSize = m_pOwner->GetAbleToTransferSize(CFtpControlSocket::upload, beenWaiting);
- else
- currentBufferSize = BUFSIZE;
- if (m_bufferpos < currentBufferSize)
- {
- numread = ReadDataFromFile(m_pBuffer + m_bufferpos, static_cast<int>(currentBufferSize - m_bufferpos));
- if (numread < 0 )
- {
- return;
- }
- else if (!numread && !m_bufferpos)
- {
- CloseOnShutDownOrError(0);
- return;
- }
- }
- else
- {
- numread = 0;
- }
- if (!currentBufferSize && !m_bufferpos)
- {
- // Not allowed to send yet, try later
- TriggerEvent(FD_WRITE);
- return;
- }
- DebugAssert(numread>=0);
- DebugAssert(m_bufferpos>=0);
- numsent = Send(m_pBuffer, numread+m_bufferpos);
- }
- }
- }
- void CTransferSocket::UpdateStatusBar(bool forceUpdate)
- {
- if (m_nTransferState != STATE_STARTED)
- return;
- if (!forceUpdate)
- {
- //Don't flood the main window with messages
- //Else performance would be really low
- LARGE_INTEGER curtime;
- LARGE_INTEGER freq;
- QueryPerformanceFrequency(&freq);
- QueryPerformanceCounter(&curtime);
- if (((curtime.QuadPart-m_LastUpdateTime.QuadPart) < (freq.QuadPart/15) ) )
- return;
- m_LastUpdateTime = curtime;
- }
- //Update the statusbar
- t_ffam_transferstatus *status=new t_ffam_transferstatus;
- status->bFileTransfer = m_nMode & (CSMODE_DOWNLOAD | CSMODE_UPLOAD);
- status->transfersize = m_transferdata.transfersize;
- status->bytes=m_transferdata.transfersize-m_transferdata.transferleft;
- GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
- }
- BOOL CTransferSocket::Create(BOOL bUseSsl)
- {
- if (bUseSsl)
- {
- m_pSslLayer = new CAsyncSslSocketLayer;
- m_pSslLayer->SetClientCertificate(m_pOwner->m_CurrentServer.Certificate, m_pOwner->m_CurrentServer.PrivateKey);
- }
- int nProxyType = GetOptionVal(OPTION_PROXYTYPE);
- if (nProxyType != PROXYTYPE_NOPROXY)
- {
- USES_CONVERSION;
- m_pProxyLayer = new CAsyncProxySocketLayer;
- if (nProxyType == PROXYTYPE_SOCKS4)
- m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4, T2CA(GetOption(OPTION_PROXYHOST)), GetOptionVal(OPTION_PROXYPORT));
- else if (nProxyType == PROXYTYPE_SOCKS4A)
- m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4A, T2CA(GetOption(OPTION_PROXYHOST)), GetOptionVal(OPTION_PROXYPORT));
- else if (nProxyType == PROXYTYPE_SOCKS5)
- if (GetOptionVal(OPTION_PROXYUSELOGON))
- m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(GetOption(OPTION_PROXYHOST)),
- GetOptionVal(OPTION_PROXYPORT),
- T2CA(GetOption(OPTION_PROXYUSER)),
- T2CA(GetOption(OPTION_PROXYPASS)));
- else
- m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(GetOption(OPTION_PROXYHOST)),
- GetOptionVal(OPTION_PROXYPORT));
- else if (nProxyType == PROXYTYPE_HTTP11)
- if (GetOptionVal(OPTION_PROXYUSELOGON))
- m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(GetOption(OPTION_PROXYHOST)), GetOptionVal(OPTION_PROXYPORT),
- T2CA(GetOption(OPTION_PROXYUSER)),
- T2CA(GetOption(OPTION_PROXYPASS)));
- else
- m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(GetOption(OPTION_PROXYHOST)), GetOptionVal(OPTION_PROXYPORT));
- else
- DebugAssert(FALSE);
- AddLayer(m_pProxyLayer);
- }
- if (!GetOptionVal(OPTION_LIMITPORTRANGE))
- {
- if (!CAsyncSocketEx::Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetFamily()))
- return FALSE;
- return TRUE;
- }
- else
- {
- int min=GetOptionVal(OPTION_PORTRANGELOW);
- int max=GetOptionVal(OPTION_PORTRANGEHIGH);
- if (min>=max)
- {
- m_pOwner->ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
- return FALSE;
- }
- int startport=static_cast<int>(min+((double)rand()*(max-min))/(RAND_MAX+1));
- int port=startport;
- while (!CAsyncSocketEx::Create(port, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetFamily()))
- {
- port++;
- if (port>max)
- port=min;
- if (port==startport)
- {
- m_pOwner->ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
- return FALSE;
- }
- }
- }
- return TRUE;
- }
- void CTransferSocket::Close()
- {
- m_bCheckTimeout = FALSE;
- CAsyncSocketEx::Close();
- }
- int CTransferSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
- {
- for (std::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(FZ_LOG_INFO, L"Proxy layer changed state from %s to %s", state2Desc, state1Desc);
- else if (iter->pLayer == m_pSslLayer)
- LogMessage(FZ_LOG_INFO, L"TLS layer changed state from %s to %s", state2Desc, state1Desc);
- #ifndef MPEXT_NO_GSS
- else if (iter->pLayer == m_pGssLayer)
- LogMessage(FZ_LOG_INFO, L"GSS layer changed state from %s to %s", state2Desc, state1Desc);
- #endif
- else
- LogMessage(FZ_LOG_INFO, L"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:
- m_pOwner->ShowStatus(IDS_PROXY_CONNECTED, FZ_LOG_STATUS);
- break;
- case PROXYERROR_NOCONN:
- m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, FZ_LOG_ERROR);
- break;
- case PROXYERROR_REQUESTFAILED:
- m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, FZ_LOG_ERROR);
- break;
- case PROXYERROR_AUTHTYPEUNKNOWN:
- m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, FZ_LOG_ERROR);
- break;
- case PROXYERROR_AUTHFAILED:
- m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, FZ_LOG_ERROR);
- break;
- case PROXYERROR_AUTHNOLOGON:
- m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, FZ_LOG_ERROR);
- break;
- case PROXYERROR_CANTRESOLVEHOST:
- m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, FZ_LOG_ERROR);
- break;
- default:
- LogMessage(FZ_LOG_WARNING, L"Unknown proxy error");
- }
- }
- else if (iter->pLayer == m_pSslLayer)
- {
- switch (iter->nParam1)
- {
- case SSL_INFO:
- switch(iter->nParam2)
- {
- case SSL_INFO_SHUTDOWNCOMPLETE:
- CloseAndEnsureSendClose(0);
- break;
- case SSL_INFO_ESTABLISHED:
- m_pOwner->ShowStatus(IDS_STATUSMSG_SSLESTABLISHEDTRANSFER, FZ_LOG_STATUS);
- TriggerEvent(FD_FORCEREAD);
- break;
- }
- break;
- case SSL_FAILURE:
- switch (iter->nParam2)
- {
- case SSL_FAILURE_ESTABLISH:
- m_pOwner->ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, FZ_LOG_ERROR);
- break;
- case SSL_FAILURE_INITSSL:
- m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
- break;
- }
- EnsureSendClose(CSMODE_TRANSFERERROR);
- break;
- case SSL_VERIFY_CERT:
- t_SslCertData data;
- LPTSTR CertError = NULL;
- if (m_pSslLayer->GetPeerCertificateData(data, CertError))
- m_pSslLayer->SetNotifyReply(data.priv_data, SSL_VERIFY_CERT, 1);
- else
- {
- CString str;
- str.Format(TLS_CERT_DECODE_ERROR, CertError);
- m_pOwner->ShowStatus(str, FZ_LOG_ERROR);
- CloseAndEnsureSendClose(CSMODE_TRANSFERERROR);
- }
- break;
- }
- }
- #ifndef MPEXT_NO_GSS
- else if (iter->pLayer == m_pGssLayer)
- {
- USES_CONVERSION;
- 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_SHUTDOWN_COMPLETE:
- CloseAndEnsureSendClose(0);
- break;
- }
- }
- #endif
- }
- delete [] iter->str;
- }
- return 0;
- }
- #ifndef MPEXT_NO_GSS
- void CTransferSocket::UseGSS(CAsyncGssSocketLayer *pGssLayer)
- {
- m_pGssLayer = new CAsyncGssSocketLayer;
- m_pGssLayer->InitTransferChannel(pGssLayer);
- }
- #endif
- #ifndef MPEXT_NO_ZLIB
- bool CTransferSocket::InitZlib(int level)
- {
- int res;
- if (m_nMode & CSMODE_UPLOAD)
- res = deflateInit2(&m_zlibStream, level, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
- else
- res = inflateInit2(&m_zlibStream, 15);
- if (res == Z_OK)
- m_useZlib = true;
- return res == Z_OK;
- }
- #endif
- int CTransferSocket::ReadDataFromFile(char *buffer, int len)
- {
- TRY
- {
- // Comparing to Filezilla 2, we do not do any translation locally,
- // leaving it onto the server (what Filezilla 3 seems to do too)
- const char Bom[3] = "\xEF\xBB\xBF";
- int read = m_pFile->Read(buffer, len);
- if (GetOptionVal(OPTION_MPEXT_REMOVE_BOM) &&
- m_transferdata.bType && (read >= sizeof(Bom)) && (memcmp(buffer, Bom, sizeof(Bom)) == 0))
- {
- memcpy(buffer, buffer + sizeof(Bom), read - sizeof(Bom));
- read -= sizeof(Bom);
- int read2 = m_pFile->Read(buffer + read, sizeof(Bom));
- if (read2 > 0)
- {
- read += read2;
- }
- }
- return read;
- }
- CATCH_ALL(e)
- {
- TCHAR error[BUFSIZE];
- if (e->GetErrorMessage(error, BUFSIZE))
- m_pOwner->ShowStatus(error, FZ_LOG_ERROR);
- CloseOnShutDownOrError(CSMODE_TRANSFERERROR);
- return -1;
- }
- END_CATCH_ALL;
- }
- void CTransferSocket::LogSocketMessageRaw(int nMessageType, LPCTSTR pMsg)
- {
- LogMessageRaw(nMessageType, pMsg);
- }
- void CTransferSocket::EnsureSendClose(int Mode)
- {
- if (!m_bSentClose)
- {
- if (Mode != 0)
- {
- m_nMode |= Mode;
- }
- m_bSentClose = TRUE;
- VERIFY(m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode));
- }
- }
- void CTransferSocket::CloseAndEnsureSendClose(int Mode)
- {
- Close();
- EnsureSendClose(Mode);
- }
- void CTransferSocket::CloseOnShutDownOrError(int Mode)
- {
- if (ShutDown())
- {
- CloseAndEnsureSendClose(Mode);
- }
- else
- {
- int Error = GetLastError();
- if (Error != WSAEWOULDBLOCK)
- {
- // Log always or only when (Mode & CSMODE_TRANSFERERROR)?
- // Does it anyway make sense at all to call this with Mode == 0?
- LogError(Error);
- CloseAndEnsureSendClose(Mode);
- }
- }
- }
- void CTransferSocket::LogError(int Error)
- {
- wchar_t * Buffer;
- int Len = FormatMessage(
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS |
- FORMAT_MESSAGE_ARGUMENT_ARRAY |
- FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, Error, 0, (LPTSTR)&Buffer, 0, NULL);
- if (Len > 0)
- {
- m_pOwner->ShowStatus(Buffer, FZ_LOG_ERROR);
- LocalFree(Buffer);
- }
- }
|