void JabberFileServerConnection(JABBER_SOCKET hConnection, DWORD /*dwRemoteIP*/, void* extra) { CJabberProto *ppro = (CJabberProto*)extra; NETLIBCONNINFO connInfo = { sizeof(connInfo) }; CallService(MS_NETLIB_GETCONNECTIONINFO, (WPARAM)hConnection, (LPARAM)&connInfo); TCHAR szPort[10]; mir_sntprintf(szPort, _countof(szPort), _T("%d"), connInfo.wPort); ppro->debugLogA("File server incoming connection accepted: %s", connInfo.szIpPort); JABBER_LIST_ITEM *item = ppro->ListGetItemPtr(LIST_FILE, szPort); if (item == NULL) { ppro->debugLogA("No file is currently served, file server connection closed."); Netlib_CloseHandle(hConnection); return; } filetransfer *ft = item->ft; JABBER_SOCKET slisten = ft->s; ft->s = hConnection; ppro->debugLogA("Set ft->s to %d (saving %d)", hConnection, slisten); char* buffer = (char*)mir_alloc(JABBER_NETWORK_BUFFER_SIZE + 1); if (buffer == NULL) { ppro->debugLogA("Cannot allocate network buffer, file server connection closed."); Netlib_CloseHandle(hConnection); ft->state = FT_ERROR; if (ft->hFileEvent != NULL) SetEvent(ft->hFileEvent); return; } ppro->debugLogA("Entering recv loop for this file connection... (ft->s is hConnection)"); int datalen = 0; while (ft->state != FT_DONE && ft->state != FT_ERROR) { int recvResult, bytesParsed; recvResult = Netlib_Recv(hConnection, buffer + datalen, JABBER_NETWORK_BUFFER_SIZE - datalen, 0); if (recvResult <= 0) break; datalen += recvResult; buffer[datalen] = '\0'; ppro->debugLogA("RECV:%s", buffer); bytesParsed = ppro->FileSendParse(hConnection, ft, buffer, datalen); if (bytesParsed < datalen) memmove(buffer, buffer + bytesParsed, datalen - bytesParsed); datalen -= bytesParsed; } ppro->debugLogA("Closing connection for this file transfer... (ft->s is now hBind)"); Netlib_CloseHandle(hConnection); ft->s = slisten; ppro->debugLogA("ft->s is restored to %d", ft->s); if (ft->hFileEvent != NULL) SetEvent(ft->hFileEvent); mir_free(buffer); }
int TlenWsRecvAES(TlenProtocol *proto, char *data, long datalen, aes_context *aes_ctx, unsigned char *aes_iv) { int ret, len = 0, maxlen = datalen; unsigned char aes_input[16]; unsigned char *aes_output = (unsigned char *)data; if (proto->threadData == NULL) { return 0; } for (maxlen = maxlen & ~0xF; maxlen != 0; maxlen = maxlen & 0xF) { ret = Netlib_Recv(proto->threadData->s, data, maxlen, MSG_NODUMP); if (ret == SOCKET_ERROR) { proto->debugLogA("Netlib_Recv() failed, error=%d", WSAGetLastError()); return 0; } if (ret == 0) { proto->debugLogA("Connection closed gracefully"); return 0; } data += ret; len += ret; maxlen -= ret; } ret = len; while (len > 15) { memcpy(aes_input, aes_output, 16); aes_crypt_cbc(aes_ctx, AES_DECRYPT, 16, aes_iv, aes_input, aes_output); aes_output += 16; len -= 16; } return ret; }
void JabberByteSendConnection( HANDLE hConn, DWORD /*dwRemoteIP*/, void* extra ) { CJabberProto* ppro = ( CJabberProto* )extra; TCHAR szPort[8]; JABBER_BYTE_TRANSFER *jbt; int recvResult, bytesParsed; HANDLE hListen; JABBER_LIST_ITEM *item; char* buffer; int datalen; NETLIBCONNINFO connInfo = { sizeof(connInfo) }; CallService(MS_NETLIB_GETCONNECTIONINFO, (WPARAM)hConn, (LPARAM)&connInfo); mir_sntprintf( szPort, SIZEOF( szPort ), _T("%u"), connInfo.wPort ); ppro->Log( "bytestream_send_connection incoming connection accepted: %s", connInfo.szIpPort ); if (( item = ppro->ListGetItemPtr( LIST_BYTE, szPort )) == NULL ) { ppro->Log( "No bytestream session is currently active, connection closed." ); Netlib_CloseHandle( hConn ); return; } jbt = item->jbt; if (( buffer = ( char* )mir_alloc( JABBER_NETWORK_BUFFER_SIZE )) == NULL ) { ppro->Log( "bytestream_send cannot allocate network buffer, connection closed." ); jbt->state = JBT_ERROR; Netlib_CloseHandle( hConn ); if ( jbt->hEvent != NULL ) SetEvent( jbt->hEvent ); return; } hListen = jbt->hConn; jbt->hConn = hConn; jbt->state = JBT_INIT; datalen = 0; while ( jbt->state!=JBT_DONE && jbt->state!=JBT_ERROR ) { recvResult = Netlib_Recv( hConn, buffer+datalen, JABBER_NETWORK_BUFFER_SIZE-datalen, 0 ); if ( recvResult <= 0 ) break; datalen += recvResult; bytesParsed = ppro->ByteSendParse( hConn, jbt, buffer, datalen ); if ( bytesParsed < datalen ) memmove( buffer, buffer+bytesParsed, datalen-bytesParsed ); datalen -= bytesParsed; } if ( jbt->hConn ) Netlib_CloseHandle( jbt->hConn ); ppro->Log( "bytestream_send_connection closing connection" ); jbt->hConn = hListen; mir_free( buffer ); if ( jbt->hEvent != NULL ) SetEvent( jbt->hEvent ); }
int WASocketConnection::read(unsigned char *buf, int length) { int result = Netlib_Recv(this->hConn, (char*)buf, length, MSG_NODUMP); if (result <= 0) throw WAException(getLastErrorMsg(), WAException::SOCKET_EX, WAException::SOCKET_EX_RECV); return result; }
unsigned char WASocketConnection::read() { SetLastError(0); char c; int result = Netlib_Recv(this->hConn, &c, 1, 0); if (result <= 0) throw WAException(getLastErrorMsg(), WAException::SOCKET_EX, WAException::SOCKET_EX_RECV); return c; }
void upload_avt(int id, INT_PTR fd, int error, void *data) { struct yahoo_file_info *sf = (struct yahoo_file_info*) data; unsigned long size = 0; char buf[1024]; int rw; /* */ DWORD dw; /* needed for ReadFile */ HANDLE myhFile; if (fd < 1 || error) { LOG(("[get_fd] Connect Failed!")); return; } myhFile = CreateFileA(sf->filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0); if (myhFile == INVALID_HANDLE_VALUE) { LOG(("[get_fd] Can't open file for reading?!")); return; } LOG(("Sending file: %s size: %ld", sf->filename, sf->filesize)); do { rw = ReadFile(myhFile, buf, sizeof(buf), &dw, NULL); if (rw != 0) { rw = Netlib_Send((HANDLE)fd, buf, dw, MSG_NODUMP); if (rw < 1) { LOG(("Upload Failed. Send error?")); //ShowError(Translate("Yahoo Error"), Translate("Avatar upload failed!?!")); break; } size += rw; } } while (rw >= 0 && size < sf->filesize); CloseHandle(myhFile); do { rw = Netlib_Recv((HANDLE)fd, buf, sizeof(buf), 0); LOG(("Got: %d bytes", rw)); } while (rw > 0); LOG(("File send complete!")); }
void CLShareUser::CloseSocket() { SOCKET s = CallService(MS_NETLIB_GETSOCKET, (WPARAM) hConnection, 0); if (s != INVALID_SOCKET) { shutdown(s, SD_SEND); int nBytesRead; do { char szBuf[100]; nBytesRead = Netlib_Recv(hConnection, szBuf, sizeof(szBuf), 0); } while (nBytesRead && nBytesRead != SOCKET_ERROR); //shutdown( s, SD_RECEIVE ); } }
int JabberHttpGatewayInit( HANDLE /*hConn*/, NETLIBOPENCONNECTION* /*nloc*/, NETLIBHTTPREQUEST* /*nlhr*/ ) { #ifdef NNNN WORD wLen, wVersion, wType; WORD wIpLen; DWORD dwSid1, dwSid2, dwSid3, dwSid4; BYTE response[300], *buf; int responseBytes, recvResult; char szSid[33], szHttpServer[256], szHttpGetUrl[300], szHttpPostUrl[300]; NETLIBHTTPPROXYINFO nlhpi = {0}; for( responseBytes = 0; ; ) { recvResult = Netlib_Recv( hConn, response + responseBytes, sizeof( response ) - responseBytes, MSG_DUMPPROXY ); if( recvResult<=0 ) break; responseBytes += recvResult; if( responseBytes == sizeof( response )) break; } if( responseBytes < 31 ) { SetLastError( ERROR_INVALID_DATA ); return 0; } buf = response; unpackWord( &buf, &wLen ); unpackWord( &buf, &wVersion ); /* always 0x0443 */ unpackWord( &buf, &wType ); buf += 6; /* dunno */ unpackDWord( &buf, &dwSid1 ); unpackDWord( &buf, &dwSid2 ); unpackDWord( &buf, &dwSid3 ); unpackDWord( &buf, &dwSid4 ); sprintf( szSid, "%08x%08x%08x%08x", dwSid1, dwSid2, dwSid3, dwSid4 ); unpackWord( &buf, &wIpLen ); if( responseBytes < 30 + wIpLen || wIpLen == 0 || wIpLen > sizeof( szHttpServer ) - 1 ) { SetLastError( ERROR_INVALID_DATA ); return 0; } memcpy( szHttpServer, buf, wIpLen ); szHttpServer[wIpLen] = '\0'; nlhpi.cbSize = sizeof( nlhpi ); nlhpi.flags = NLHPIF_USEPOSTSEQUENCE; nlhpi.szHttpGetUrl = szHttpGetUrl; nlhpi.szHttpPostUrl = szHttpPostUrl; nlhpi.firstPostSequence = 1; sprintf( szHttpGetUrl, "http://%s/monitor?sid=%s", szHttpServer, szSid ); sprintf( szHttpPostUrl, "http://%s/data?sid=%s&seq=", szHttpServer, szSid ); return JCallService( MS_NETLIB_SETHTTPPROXYINFO, ( WPARAM )hConn, ( LPARAM )&nlhpi ); #endif return 1; }
unsigned char WASocketConnection::read() { char c; SetLastError(0); int result; //do { result = Netlib_Recv(this->hConn, &c, 1, 0 /*MSG_NOHTTPGATEWAYWRAP | MSG_NODUMP*/); //} while (WSAGetLastError() == EINTR); if (result <= 0) { throw WAException(getLastErrorMsg(), WAException::SOCKET_EX, WAException::SOCKET_EX_RECV); } return c; }
int TlenWsRecv(TlenProtocol *proto, HANDLE s, char *data, long datalen) { int ret; ret = Netlib_Recv(s, data, datalen, /*MSG_NODUMP|*/MSG_DUMPASTEXT); if (ret == SOCKET_ERROR) { proto->debugLogA("Netlib_Recv() failed, error=%d", WSAGetLastError()); return 0; } if (ret == 0) { proto->debugLogA("Connection closed gracefully"); return 0; } return ret; }
int WASocketConnection::read(std::vector<unsigned char>& b, int off, int length) { if (off < 0 || length < 0) throw new WAException("Out of bounds", WAException::SOCKET_EX, WAException::SOCKET_EX_RECV); char* buffer = (char*)_alloca(length); int result = Netlib_Recv(this->hConn, buffer, length, MSG_NOHTTPGATEWAYWRAP | MSG_NODUMP); if (result <= 0) throw WAException(getLastErrorMsg(), WAException::SOCKET_EX, WAException::SOCKET_EX_RECV); for (int i = 0; i < result; i++) b[off + i] = buffer[i]; return result; }
int CJabberProto::WsRecv(JABBER_SOCKET hConn, char* data, long datalen, int flags) { int ret; ret = Netlib_Recv(hConn, data, datalen, flags); if (ret == SOCKET_ERROR) { debugLogA("Netlib_Recv() failed, error=%d", WSAGetLastError()); return 0; } if (ret == 0) { debugLogA("Connection closed gracefully"); return 0; } return ret; }
int JabberWsRecv(JABBER_SOCKET hConn, char *data, long datalen) { int ret; ret = Netlib_Recv(hConn, data, datalen, /*MSG_NODUMP|*/MSG_DUMPASTEXT); if(ret == SOCKET_ERROR) { JabberLog("Netlib_Recv() failed, error=%d", WSAGetLastError()); return 0; } if(ret == 0) { JabberLog("Connection closed gracefully"); return 0; } return ret; }
int PASCAL recv(SOCKET s, char FAR *buf, int len, int flags) { int RecvResult = Netlib_Recv((HANDLE)s, buf, len, (len == 1) ? MSG_NODUMP : 0); if (RecvResult == 0) { LOG(("[recv] Connection closed gracefully.")); return 0; } if (RecvResult == SOCKET_ERROR) { LOG(("[recv] Connection abortively closed")); return -1; } return RecvResult; }
void FromServerToClient(LPVOID lParam) { char buf[1024] = { 0 }; HANDLE hConnection = (HANDLE)lParam; do { if (!hBindPort) return; int cbRead = Netlib_Recv(netlibcon, buf, sizeof(buf), 0); if (cbRead == SOCKET_ERROR) break; if (cbRead) { Netlib_Send(hConnection, buf, cbRead, 0); } } while (1); }
//xfireclient baut verbindung auf void XfireclientConnecting(HANDLE hConnection, DWORD, void* extra ) { char buf[1024]={0}; //verbindung zum richtigen xfire server aufbauen NETLIBOPENCONNECTION ncon = { 0 }; ncon.cbSize = sizeof(ncon); ncon.szHost = "206.220.42.147"; ncon.wPort = (WORD)atol("25999"); ncon.timeout=5; netlibcon = (HANDLE) CallService(MS_NETLIB_OPENCONNECTION, (WPARAM) hNetlib, (LPARAM) & ncon); if (!netlibcon) { Netlib_CloseHandle(hConnection); } mir_forkthread(FromServerToClient,(LPVOID)hConnection); //schleife behandelt empfangende daten do { int cbRead = Netlib_Recv(hConnection, buf, sizeof(buf), 0); if ( cbRead == SOCKET_ERROR) { Netlib_CloseHandle(hConnection); Netlib_CloseHandle(netlibcon); break; } if (cbRead) { if (!Netlib_Send(netlibcon, buf, cbRead, 0)) { Netlib_CloseHandle(hConnection); Netlib_CloseHandle(netlibcon); break; } } } while(1); }
DWORD CMraProto::MraMrimProxyConnect(HANDLE hMraMrimProxyData, HANDLE *phConnection) { DWORD dwRetErrorCode; if (hMraMrimProxyData && phConnection) { BOOL bIsHTTPSProxyUsed, bContinue; BYTE lpbBufferRcv[BUFF_SIZE_RCV_MIN_FREE]; DWORD dwBytesReceived, dwConnectReTryCount, dwCurConnectReTryCount; size_t dwRcvBuffSize = BUFF_SIZE_RCV_MIN_FREE, dwRcvBuffSizeUsed; NETLIBSELECT nls = {0}; MRA_MRIMPROXY_DATA *pmmpd = (MRA_MRIMPROXY_DATA*)hMraMrimProxyData; NETLIBOPENCONNECTION nloc = {0}; // адреса есть, значит инициаторы не мы if (pmmpd->malAddrList.dwAddrCount) { CMStringA szAddresses = MraAddrListGetToBuff(&pmmpd->malAddrList); MraProxyAck(PROXY_STATUS_OK, pmmpd->szEmail, pmmpd->dwIDRequest, pmmpd->dwDataType, pmmpd->lpszUserData, szAddresses, pmmpd->mguidSessionID); } // мы инициаторы else { pmmpd->hWaitHandle = CreateEvent(NULL, TRUE, FALSE, NULL); if (pmmpd->szEmail) if (MraProxy(pmmpd->szEmail, pmmpd->dwIDRequest, pmmpd->dwDataType, pmmpd->lpszUserData, "", pmmpd->mguidSessionID)) WaitForSingleObjectEx(pmmpd->hWaitHandle, INFINITE, FALSE); CloseHandle(pmmpd->hWaitHandle); pmmpd->hWaitHandle = NULL; } dwRetErrorCode = ERROR_NO_NETWORK; if (pmmpd->malAddrList.dwAddrCount) { pmmpd->hConnection = NULL; bIsHTTPSProxyUsed = IsHTTPSProxyUsed(m_hNetlibUser); dwConnectReTryCount = getDword("ConnectReTryCountMRIMProxy", MRA_DEFAULT_CONN_RETRY_COUNT_MRIMPROXY); nloc.cbSize = sizeof(nloc); nloc.flags = NLOCF_V2; nloc.timeout = ((MRA_TIMEOUT_DIRECT_CONN-1)/(pmmpd->malAddrList.dwAddrCount*dwConnectReTryCount));// -1 сек чтобы был запас if (nloc.timeout < MRA_TIMEOUT_CONN_MIN) nloc.timeout = MRA_TIMEOUT_CONN_MIN; if (nloc.timeout > MRA_TIMEOUT_CONN_MAX) nloc.timeout = MRA_TIMEOUT_CONN_MAX; // Set up the sockaddr structure for (size_t i = 0; i < pmmpd->malAddrList.dwAddrCount && dwRetErrorCode != NO_ERROR; i++) { // через https прокси только 443 порт if ((pmmpd->malAddrList.pMailAddress[i].dwPort == MRA_SERVER_PORT_HTTPS && bIsHTTPSProxyUsed) || bIsHTTPSProxyUsed == FALSE) { if (pmmpd->dwDataType == MRIM_PROXY_TYPE_FILES) ProtoBroadcastAck(MraHContactFromEmail(pmmpd->szEmail, FALSE, TRUE, NULL), ACKTYPE_FILE, ACKRESULT_CONNECTING, (HANDLE)pmmpd->dwIDRequest, 0); nloc.szHost = inet_ntoa((*((in_addr*)&pmmpd->malAddrList.pMailAddress[i].dwAddr))); nloc.wPort = (WORD)pmmpd->malAddrList.pMailAddress[i].dwPort; dwCurConnectReTryCount = dwConnectReTryCount; do { pmmpd->hConnection = (HANDLE)CallService(MS_NETLIB_OPENCONNECTION, (WPARAM)m_hNetlibUser, (LPARAM)&nloc); } while (--dwCurConnectReTryCount && pmmpd->hConnection == NULL); if (pmmpd->hConnection) { nls.cbSize = sizeof(nls); nls.dwTimeout = (MRA_TIMEOUT_DIRECT_CONN*1000*2); nls.hReadConns[0] = pmmpd->hConnection; bContinue = TRUE; dwRcvBuffSizeUsed = 0; if (pmmpd->dwDataType == MRIM_PROXY_TYPE_FILES) ProtoBroadcastAck(MraHContactFromEmail(pmmpd->szEmail, FALSE, TRUE, NULL), ACKTYPE_FILE, ACKRESULT_CONNECTED, (HANDLE)pmmpd->dwIDRequest, 0); MraSendPacket(nls.hReadConns[0], 0, MRIM_CS_PROXY_HELLO, &pmmpd->mguidSessionID, sizeof(MRA_GUID)); while (bContinue) { switch (CallService(MS_NETLIB_SELECT, 0, (LPARAM)&nls)) { case SOCKET_ERROR: case 0:// Time out dwRetErrorCode = GetLastError(); ShowFormattedErrorMessage(L"Disconnected, socket error", dwRetErrorCode); bContinue = FALSE; break; case 1: if (dwRcvBuffSizeUsed == BUFF_SIZE_RCV_MIN_FREE) { // bad packet bContinue = FALSE; _CrtDbgBreak(); } else { dwBytesReceived = Netlib_Recv(nls.hReadConns[0], (LPSTR)(lpbBufferRcv + dwRcvBuffSizeUsed), (int)(dwRcvBuffSize - dwRcvBuffSizeUsed), 0); if (dwBytesReceived && dwBytesReceived != SOCKET_ERROR) { // connected dwRcvBuffSizeUsed += dwBytesReceived; if (dwRcvBuffSizeUsed >= sizeof(mrim_packet_header_t)) { // packet header received if (((mrim_packet_header_t*)lpbBufferRcv)->magic == CS_MAGIC) { // packet OK if ((dwRcvBuffSizeUsed-sizeof(mrim_packet_header_t)) >= ((mrim_packet_header_t*)lpbBufferRcv)->dlen) { // full packet received, may be more than one if (((mrim_packet_header_t*)lpbBufferRcv)->msg == MRIM_CS_PROXY_HELLO_ACK) // connect OK! dwRetErrorCode = NO_ERROR; else // bad/wrong _CrtDbgBreak(); bContinue = FALSE; } else // not all packet received, continue receiving debugLogA("Not all packet received, continue receiving\n"); } else { // bad packet debugLogA("Bad packet\n"); _ASSERT(false); bContinue = FALSE; } } else // packet too small, continue receiving debugLogA("Packet to small, continue receiving\n"); } else { // disconnected dwRetErrorCode = GetLastError(); ShowFormattedErrorMessage(L"Disconnected, socket read error", dwRetErrorCode); bContinue = FALSE; } } break; }// end switch }// end while } else dwRetErrorCode = GetLastError(); }// filtered }// end for if (dwRetErrorCode != NO_ERROR) // кажется не туда подключились :) NETLIB_CLOSEHANDLE(pmmpd->hConnection); } *phConnection = pmmpd->hConnection; } else dwRetErrorCode = ERROR_INVALID_HANDLE; return dwRetErrorCode; }
void JabberFileServerConnection( JABBER_SOCKET hConnection, DWORD /*dwRemoteIP*/, void* extra ) { CJabberProto* ppro = ( CJabberProto* )extra; WORD localPort = 0; SOCKET s = JCallService( MS_NETLIB_GETSOCKET, ( WPARAM ) hConnection, 0 ); if ( s != INVALID_SOCKET ) { SOCKADDR_IN saddr; int len = sizeof( saddr ); if ( getsockname( s, ( SOCKADDR * ) &saddr, &len ) != SOCKET_ERROR ) { localPort = ntohs( saddr.sin_port ); } } if ( localPort == 0 ) { ppro->Log( "Unable to determine the local port, file server connection closed." ); Netlib_CloseHandle( hConnection ); return; } TCHAR szPort[20]; mir_sntprintf( szPort, SIZEOF( szPort ), _T("%d"), localPort ); ppro->Log( "File server incoming connection accepted: local_port=" TCHAR_STR_PARAM, szPort ); JABBER_LIST_ITEM *item = ppro->ListGetItemPtr( LIST_FILE, szPort ); if ( item == NULL ) { ppro->Log( "No file is currently served, file server connection closed." ); Netlib_CloseHandle( hConnection ); return; } filetransfer* ft = item->ft; JABBER_SOCKET slisten = ft->s; ft->s = hConnection; ppro->Log( "Set ft->s to %d ( saving %d )", hConnection, slisten ); char* buffer = ( char* )mir_alloc( JABBER_NETWORK_BUFFER_SIZE+1 ); if ( buffer == NULL ) { ppro->Log( "Cannot allocate network buffer, file server connection closed." ); Netlib_CloseHandle( hConnection ); ft->state = FT_ERROR; if ( ft->hFileEvent != NULL ) SetEvent( ft->hFileEvent ); return; } ppro->Log( "Entering recv loop for this file connection... ( ft->s is hConnection )" ); int datalen = 0; while ( ft->state!=FT_DONE && ft->state!=FT_ERROR ) { int recvResult, bytesParsed; recvResult = Netlib_Recv( hConnection, buffer+datalen, JABBER_NETWORK_BUFFER_SIZE-datalen, 0 ); if ( recvResult <= 0 ) break; datalen += recvResult; buffer[datalen] = '\0'; ppro->Log( "RECV:%s", buffer ); bytesParsed = ppro->FileSendParse( hConnection, ft, buffer, datalen ); if ( bytesParsed < datalen ) memmove( buffer, buffer+bytesParsed, datalen-bytesParsed ); datalen -= bytesParsed; } ppro->Log( "Closing connection for this file transfer... ( ft->s is now hBind )" ); Netlib_CloseHandle( hConnection ); ft->s = slisten; ppro->Log( "ft->s is restored to %d", ft->s ); if ( ft->hFileEvent != NULL ) SetEvent( ft->hFileEvent ); mir_free( buffer ); }
void __cdecl SessionThread(LPVOID param) { CSametimeProto* proto = (CSametimeProto*)param; HANDLE hNetlibUser = proto->m_hNetlibUser; proto->debugLog(_T("SessionThread() start")); continue_connect = true; //setup NETLIBOPENCONNECTION conn_data = { 0 }; conn_data.cbSize = sizeof(NETLIBOPENCONNECTION); conn_data.flags = NLOCF_V2; conn_data.szHost = proto->options.server_name; conn_data.wPort = proto->options.port; conn_data.timeout = 20; conn_data.waitcallback = waitcallback; proto->BroadcastNewStatus(ID_STATUS_CONNECTING); proto->server_connection = (HANDLE)CallService(MS_NETLIB_OPENCONNECTION, (WPARAM)hNetlibUser, (LPARAM)&conn_data); if (!proto->server_connection) { proto->BroadcastNewStatus(ID_STATUS_OFFLINE); if (continue_connect) { // real timeout - not user cancelled proto->showPopup(TranslateT("No server connection!"), SAMETIME_POPUP_ERROR); } proto->debugLog(_T("SessionThread() end, no server_connection, continue_connect=[%d]"), continue_connect); return; } mwSessionHandler handler = { 0 }; handler.clear = SessionClear; handler.io_write = SessionWrite; handler.io_close = SessionClose; handler.on_stateChange = SessionStateChange; handler.on_admin = SessionAdmin; handler.on_announce = SessionAnnounce; handler.on_setPrivacyInfo = SessionSetPrivacyInfo; handler.on_setUserStatus = SessionSetUserStatus; EnterCriticalSection(&proto->session_cs); proto->session = mwSession_new(&handler); proto->InitMeanwhileServices(); mwSession_start(proto->session); LeaveCriticalSection(&proto->session_cs); mir_forkthread(KeepAliveThread, (void*)proto); unsigned char* recv_buffer = (unsigned char*)mir_alloc(1024 * 32); int bytes; //while(session && server_connection && mwSession_getState(session) != mwSession_STOPPED) { while (proto->server_connection) {// && session) {// && !mwSession_isStopped(session)) { // break on error bytes = Netlib_Recv(proto->server_connection, (char *)recv_buffer, 1024 * 32, 0); proto->debugLog(_T("SessionThread() Netlib_Recv'ed bytes=[%d]"), bytes); if (bytes == 0) { break; } else if (bytes == SOCKET_ERROR) { // this is normal - e.g. socket closed due to log off, during blocking read above break; } else { EnterCriticalSection(&proto->session_cs); mwSession_recv(proto->session, recv_buffer, bytes); LeaveCriticalSection(&proto->session_cs); } } mir_free(recv_buffer); EnterCriticalSection(&proto->session_cs); proto->DeinitMeanwhileServices(); mwSession* old_session = proto->session; proto->session = 0; // kills keepalive thread, if awake mwSession_free(old_session); LeaveCriticalSection(&proto->session_cs); proto->BroadcastNewStatus(ID_STATUS_OFFLINE); proto->SetAllOffline(); proto->first_online = true; proto->debugLog(_T("SessionThread() end")); return; }
void __cdecl CMsnProto::MsnFileAckThread(void* arg) { filetransfer* ft = (filetransfer*)arg; TCHAR filefull[MAX_PATH]; mir_sntprintf(filefull, _T("%s\\%s"), ft->std.tszWorkingDir, ft->std.tszCurrentFile); replaceStrT(ft->std.tszCurrentFile, filefull); ResetEvent(ft->hResumeEvt); if (ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_FILERESUME, ft, (LPARAM)&ft->std)) WaitForSingleObject(ft->hResumeEvt, INFINITE); ft->create(); #ifdef OBSOLETE if (ft->tType != SERVER_HTTP) { if (ft->p2p_appID != 0) { if (fcrt) p2p_sendFeedStart(ft); p2p_sendStatus(ft, fcrt ? 200 : 603); } else msnftp_sendAcceptReject(ft, fcrt); } #endif ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_INITIALISING, ft, 0); if (ft->tType == SERVER_HTTP) { const char *pszSkypeToken; if (ft->fileId != -1 && (pszSkypeToken=authSkypeToken.Token())) { NETLIBHTTPHEADER nlbhHeaders[3] = { 0 }; NETLIBHTTPREQUEST nlhr = { 0 }, *nlhrReply; char szRange[32]; nlbhHeaders[0].szName = "User-Agent"; nlbhHeaders[0].szValue = (LPSTR)MSN_USER_AGENT; nlbhHeaders[1].szName = "Authorization"; nlbhHeaders[1].szValue = (char*)pszSkypeToken; nlhr.headersCount = 2; if (ft->std.currentFileProgress) { mir_snprintf(szRange, sizeof(szRange), "bytes=%I64d-", ft->std.currentFileProgress); nlbhHeaders[2].szName = "Range"; nlbhHeaders[2].szValue = szRange; nlhr.headersCount++; } nlhr.cbSize = sizeof(nlhr); nlhr.requestType = REQUEST_GET; nlhr.flags = NLHRF_GENERATEHOST | NLHRF_SMARTREMOVEHOST | NLHRF_SMARTAUTHHEADER | NLHRF_HTTP11; nlhr.szUrl = ft->szInvcookie; nlhr.headers = (NETLIBHTTPHEADER*)&nlbhHeaders; NETLIBOPENCONNECTION nloc = { 0 }; MyNetlibConnFromUrl(nlhr.szUrl, nloc); nloc.flags |= NLOCF_HTTP; if (nloc.flags & NLOCF_SSL) nlhr.flags |= NLHRF_SSL; HANDLE nlc = (HANDLE)CallService(MS_NETLIB_OPENCONNECTION, (WPARAM)m_hNetlibUser, (LPARAM)&nloc); if (nlc && CallService(MS_NETLIB_SENDHTTPREQUEST, (WPARAM)nlc, (LPARAM)&nlhr) != SOCKET_ERROR && (nlhrReply = (NETLIBHTTPREQUEST*)CallService(MS_NETLIB_RECVHTTPHEADERS, (WPARAM)nlc, 0))) { if (nlhrReply->resultCode == 200 || nlhrReply->resultCode == 206) { INT_PTR dw; char buf[1024]; ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_CONNECTED, ft, 0); while (!ft->bCanceled && ft->std.currentFileProgress < ft->std.currentFileSize && (dw = Netlib_Recv(nlc, buf, sizeof(buf), MSG_NODUMP))>0 && dw!=SOCKET_ERROR) { _write(ft->fileId, buf, dw); ft->std.totalProgress += dw; ft->std.currentFileProgress += dw; ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->std); } if (ft->std.currentFileProgress == ft->std.currentFileSize) ft->std.currentFileNumber++; } CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)nlhrReply); } Netlib_CloseHandle(nlc); mir_free((char*)nloc.szHost); if (ft->std.currentFileNumber >= ft->std.totalFiles) ft->complete(); } delete ft; } }
void CMraProto::MraAvatarsThreadProc(LPVOID lpParameter) { MRA_AVATARS_QUEUE *pmraaqAvatarsQueue = (MRA_AVATARS_QUEUE*)lpParameter; MRA_AVATARS_QUEUE_ITEM *pmraaqiAvatarsQueueItem; CMStringA szEmail, szServer; CMStringW wszFileName; BOOL bContinue, bKeepAlive, bUseKeepAliveConn, bFailed, bDownloadNew, bDefaultAvt; BYTE btBuff[BUFF_SIZE_RCV]; DWORD dwResultCode, dwAvatarFormat, dwReceived, dwServerPort, dwErrorCode; size_t dwAvatarSizeServer; FILETIME ftLastModifiedTimeServer, ftLastModifiedTimeLocal; SYSTEMTIME stAvatarLastModifiedTimeLocal; HANDLE hConnection = NULL; NETLIBSELECT nls = { 0 }; INTERNET_TIME itAvatarLastModifiedTimeServer; PROTO_AVATAR_INFORMATIONT pai; WCHAR szErrorText[2048]; nls.cbSize = sizeof(nls); pai.cbSize = sizeof(pai); InterlockedIncrement((volatile LONG*)&pmraaqAvatarsQueue->lThreadsRunningCount); while (InterlockedExchangeAdd((volatile LONG*)&pmraaqAvatarsQueue->bIsRunning, 0)) { if (FifoMTItemPop(pmraaqAvatarsQueue, NULL, (LPVOID*)&pmraaqiAvatarsQueueItem) != NO_ERROR) { // waiting until service stop or new task NETLIB_CLOSEHANDLE(hConnection); WaitForSingleObjectEx(pmraaqAvatarsQueue->hThreadEvent, MRA_AVT_DEFAULT_QE_CHK_INTERVAL, FALSE); continue; } /* Try download. */ bFailed = TRUE; bDownloadNew = FALSE; bDefaultAvt = FALSE; if (!DB_GetStringA(NULL, MRA_AVT_SECT_NAME, "Server", szServer)) szServer = MRA_AVT_DEFAULT_SERVER; dwServerPort = db_get_dw(NULL, MRA_AVT_SECT_NAME, "ServerPort", MRA_AVT_DEFAULT_SERVER_PORT); bUseKeepAliveConn = db_get_b(NULL, MRA_AVT_SECT_NAME, "UseKeepAliveConn", MRA_AVT_DEFAULT_USE_KEEPALIVE_CONN); if (mraGetStringA(pmraaqiAvatarsQueueItem->hContact, "e-mail", szEmail)) { szEmail.MakeLower(); int iStart = 0; CMStringA szUser = szEmail.Tokenize("@", iStart); CMStringA szDomain = szEmail.Tokenize("@", iStart); if (!szUser.IsEmpty() && !szDomain.IsEmpty()) { ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_CONNECTING, NULL, 0); if (hConnection == NULL) hConnection = MraAvatarsHttpConnect(pmraaqAvatarsQueue->hNetlibUser, szServer, dwServerPort); if (hConnection) { ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_CONNECTED, NULL, 0); ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_SENTREQUEST, NULL, 0); if (!MraAvatarsHttpTransaction(hConnection, REQUEST_HEAD, szUser, szDomain, szServer, MAHTRO_AVTMRIM, bUseKeepAliveConn, &dwResultCode, &bKeepAlive, &dwAvatarFormat, &dwAvatarSizeServer, &itAvatarLastModifiedTimeServer)) { switch (dwResultCode) { case 200: if (MraAvatarsGetContactTime(pmraaqiAvatarsQueueItem->hContact, "AvatarLastModifiedTime", &stAvatarLastModifiedTimeLocal)) { SystemTimeToFileTime(&itAvatarLastModifiedTimeServer.stTime, &ftLastModifiedTimeServer); SystemTimeToFileTime(&stAvatarLastModifiedTimeLocal, &ftLastModifiedTimeLocal); if ((*((DWORDLONG*)&ftLastModifiedTimeServer)) != (*((DWORDLONG*)&ftLastModifiedTimeLocal))) {// need check for update bDownloadNew = TRUE; //ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_STATUS, 0, 0); } else {// avatar is valid if (MraAvatarsGetFileName(pmraaqAvatarsQueue, pmraaqiAvatarsQueueItem->hContact, dwAvatarFormat, wszFileName) == NO_ERROR) { if (IsFileExist(wszFileName)) bFailed = FALSE; else bDownloadNew = TRUE; } } } else // need update bDownloadNew = TRUE; break; case 404:// return def avatar if (MraAvatarsGetFileName((HANDLE)pmraaqAvatarsQueue, NULL, PA_FORMAT_DEFAULT, wszFileName) == NO_ERROR) { if (IsFileExist(wszFileName)) { dwAvatarFormat = ProtoGetAvatarFormat(wszFileName); bFailed = FALSE; } else//loading default avatar bDownloadNew = TRUE; bDefaultAvt = TRUE; } break; default: mir_sntprintf(szErrorText, SIZEOF(szErrorText), TranslateT("Avatars: server return HTTP code: %lu"), dwResultCode); ShowFormattedErrorMessage(szErrorText, NO_ERROR); break; } } if (bUseKeepAliveConn == FALSE || bKeepAlive == FALSE) NETLIB_CLOSEHANDLE(hConnection); } if (bDownloadNew) { if (hConnection == NULL) hConnection = MraAvatarsHttpConnect(pmraaqAvatarsQueue->hNetlibUser, szServer, dwServerPort); if (hConnection) { ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_DATA, NULL, 0); if (MraAvatarsHttpTransaction(hConnection, REQUEST_GET, szUser, szDomain, szServer, MAHTRO_AVT, bUseKeepAliveConn, &dwResultCode, &bKeepAlive, &dwAvatarFormat, &dwAvatarSizeServer, &itAvatarLastModifiedTimeServer) == NO_ERROR && dwResultCode == 200) { if (bDefaultAvt) dwAvatarFormat = PA_FORMAT_DEFAULT; if (!MraAvatarsGetFileName(pmraaqAvatarsQueue, pmraaqiAvatarsQueueItem->hContact, dwAvatarFormat, wszFileName)) { HANDLE hFile = CreateFile(wszFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { DWORD dwWritten = 0; bContinue = TRUE; nls.dwTimeout = (1000 * db_get_dw(NULL, MRA_AVT_SECT_NAME, "TimeOutReceive", MRA_AVT_DEFAULT_TIMEOUT_RECV)); nls.hReadConns[0] = hConnection; while (bContinue) { switch (CallService(MS_NETLIB_SELECT, 0, (LPARAM)&nls)) { case SOCKET_ERROR: case 0:// Time out dwErrorCode = GetLastError(); ShowFormattedErrorMessage(L"Avatars: error on receive file data", dwErrorCode); bContinue = FALSE; break; case 1: dwReceived = Netlib_Recv(hConnection, (LPSTR)&btBuff, SIZEOF(btBuff), 0); if (dwReceived == 0 || dwReceived == SOCKET_ERROR) { dwErrorCode = GetLastError(); ShowFormattedErrorMessage(L"Avatars: error on receive file data", dwErrorCode); bContinue = FALSE; } else { if (WriteFile(hFile, (LPVOID)&btBuff, dwReceived, &dwReceived, NULL)) { dwWritten += dwReceived; if (dwWritten >= dwAvatarSizeServer) bContinue = FALSE; } else { dwErrorCode = GetLastError(); ShowFormattedErrorMessage(L"Avatars: cant write file data, error", dwErrorCode); bContinue = FALSE; } } break; } } CloseHandle(hFile); bFailed = FALSE; } else { dwErrorCode = GetLastError(); mir_sntprintf(szErrorText, SIZEOF(szErrorText), TranslateT("Avatars: can't open file %s, error"), wszFileName); ShowFormattedErrorMessage(szErrorText, dwErrorCode); } } } else _CrtDbgBreak(); if (bUseKeepAliveConn == FALSE || bKeepAlive == FALSE) NETLIB_CLOSEHANDLE(hConnection); } } } } if (bFailed) { DeleteFile(wszFileName); pai.hContact = pmraaqiAvatarsQueueItem->hContact; pai.format = PA_FORMAT_UNKNOWN; pai.filename[0] = 0; ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_FAILED, (HANDLE)&pai, 0); } else { pai.hContact = pmraaqiAvatarsQueueItem->hContact; pai.format = dwAvatarFormat; if (db_get_b(NULL, MRA_AVT_SECT_NAME, "ReturnAbsolutePath", MRA_AVT_DEFAULT_RET_ABC_PATH)) lstrcpyn(pai.filename, wszFileName, SIZEOF(pai.filename)); else PathToRelativeT(wszFileName, pai.filename); if (bDefaultAvt) dwAvatarFormat = PA_FORMAT_DEFAULT; SetContactAvatarFormat(pmraaqiAvatarsQueueItem->hContact, dwAvatarFormat); MraAvatarsSetContactTime(pmraaqiAvatarsQueueItem->hContact, "AvatarLastModifiedTime", &itAvatarLastModifiedTimeServer.stTime); // write owner avatar file name to DB if (pmraaqiAvatarsQueueItem->hContact == NULL) // proto avatar CallService(MS_AV_REPORTMYAVATARCHANGED, (WPARAM)m_szModuleName, 0); ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_SUCCESS, (HANDLE)&pai, 0); } mir_free(pmraaqiAvatarsQueueItem); } InterlockedDecrement((volatile LONG*)&pmraaqAvatarsQueue->lThreadsRunningCount); }
void CLHttpUser::HandleNewConnection() { /* { SOCKET s = CallService(MS_NETLIB_GETSOCKET, (WPARAM) hConnection, 0); sockaddr_in MyAddr; int nSize = sizeof( MyAddr ); getsockname( s, (sockaddr*)&MyAddr, &nSize ); ShowPopupWindow( "My IP address", inet_ntoa( MyAddr.sin_addr ) ); //OutputDebugString( ); }*/ /* { LINGER li; int nLenght = sizeof( li ); int ret = getsockopt( s, IPPROTO_TCP, SO_LINGER, (char *)&li, &nLenght ); if( ret ) { DWORD error = WSAGetLastError(); if( error WSANOTINITIALISED WSAENETDOWN The network subsystem has failed. WSAEFAULT One of the optval or the optlen parameters is not a valid part of the user address space, or the optlen parameter is too small. WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. WSAEINVAL The level parameter is unknown or invalid. WSAENOPROTOOPT The option is unknown or unsupported by the indicated protocol family. WSAENOTSOCK } nLenght = sizeof( li ); li.l_onoff = 1; li.l_linger = 0;// time is default ret = setsockopt( s, IPPROTO_TCP, SO_LINGER, (const char *)&li, nLenght ); if( ret ) { // error } int nLenght = sizeof( li ); int ret = getsockopt( s, IPPROTO_TCP, SO_LINGER, (char *)&li, &nLenght ); } */ char szBuf[1000]; int nCurPos = 0; while (sizeof(szBuf) - nCurPos > 10 && !bShutdownInProgress) { int nBytesRead = Netlib_Recv(hConnection, &szBuf[nCurPos], sizeof(szBuf) - nCurPos, 0); if (! nBytesRead) { // socket closed gracefully break; } if (nBytesRead == SOCKET_ERROR) { // socket closed with error // WSAGetLastError(); break; } int nOldCurPos = nCurPos; nCurPos += nBytesRead; if (nCurPos <= 5) continue; bool bIsGetCommand = memcmp(szBuf, "GET ", 4) == 0; if (!bIsGetCommand && memcmp(szBuf, "HEAD ", 5) != 0) { SendError(501, "Not Implemented"); break; // We only support GET and HEAD commands !! } if (nOldCurPos < 4) nOldCurPos = 4; // scan forward from end of "GET " to locate the next space ' ' bool bBreakWhile = false; for (; nOldCurPos < nCurPos; nOldCurPos++) { if (szBuf[nOldCurPos-2] == '\n' && szBuf[nOldCurPos-1] == '\r' && szBuf[nOldCurPos] == '\n') { // we have a walid request !!! scan to see if we have this file szBuf[nOldCurPos] = NULL; bProcessGetRequest(&szBuf[bIsGetCommand?4:5], bIsGetCommand); bBreakWhile = true; break; } } if (bBreakWhile) break; } }
void CJabberProto::ByteSendViaProxy( JABBER_BYTE_TRANSFER *jbt ) { TCHAR *szHost, *szPort; WORD port; HANDLE hConn; char data[3]; char* buffer; int datalen, bytesParsed, recvResult; BOOL validStreamhost; if ( jbt == NULL ) return; if (( buffer=( char* )mir_alloc( JABBER_NETWORK_BUFFER_SIZE )) == NULL ) { m_ThreadInfo->send( XmlNodeIq( _T("error"), jbt->iqId, jbt->srcJID ) << XCHILD( _T("error")) << XATTRI( _T("code"), 406 ) << XATTR( _T("type"), _T("auth")) << XCHILDNS( _T("not-acceptable"), _T("urn:ietf:params:xml:ns:xmpp-stanzas"))); return; } jbt->state = JBT_INIT; validStreamhost = FALSE; szPort = jbt->szProxyPort; szHost = jbt->szProxyHost; port = ( WORD )_ttoi( szPort ); if ( jbt->streamhostJID ) mir_free( jbt->streamhostJID ); jbt->streamhostJID = mir_tstrdup( jbt->szProxyJid ); NETLIBOPENCONNECTION nloc = { 0 }; nloc.cbSize = sizeof( nloc ); nloc.szHost = mir_t2a(szHost); nloc.wPort = port; hConn = ( HANDLE ) JCallService( MS_NETLIB_OPENCONNECTION, ( WPARAM ) m_hNetlibUser, ( LPARAM )&nloc ); mir_free((void*)nloc.szHost); if ( hConn != NULL ) { jbt->hConn = hConn; data[0] = 5; data[1] = 1; data[2] = 0; Netlib_Send( hConn, data, 3, 0 ); jbt->state = JBT_INIT; datalen = 0; while ( jbt->state!=JBT_DONE && jbt->state!=JBT_ERROR && jbt->state!=JBT_SOCKSERR ) { recvResult = Netlib_Recv( hConn, buffer+datalen, JABBER_NETWORK_BUFFER_SIZE-datalen, 0 ); if ( recvResult <= 0 ) break; datalen += recvResult; bytesParsed = ByteSendProxyParse( hConn, jbt, buffer, datalen ); if ( bytesParsed < datalen ) memmove( buffer, buffer+bytesParsed, datalen-bytesParsed ); datalen -= bytesParsed; if ( jbt->state == JBT_DONE ) validStreamhost = TRUE; } Netlib_CloseHandle( hConn ); } mir_free( buffer ); (this->*jbt->pfnFinal)(( jbt->state == JBT_DONE ) ? TRUE : FALSE, jbt->ft ); jbt->ft = NULL; if ( !validStreamhost ) m_ThreadInfo->send( XmlNodeIq( _T("error"), jbt->iqId, jbt->srcJID ) << XCHILD( _T("error")) << XATTRI( _T("code"), 404 ) << XATTR( _T("type"), _T("cancel")) << XCHILDNS( _T("item-not-found"), _T("urn:ietf:params:xml:ns:xmpp-stanzas"))); }
// wParam is zero // lParam is address of PINGADDRESS structure where ping result is placed (i.e. modifies 'responding' // and 'round_trip_time') int PluginPing(WPARAM wParam,LPARAM lParam) { PINGADDRESS *pa = (PINGADDRESS *)lParam; if(pa->port == -1) { if(use_raw_ping) { pa->round_trip_time = raw_ping(pa->pszName, options.ping_timeout * 1000); pa->responding = (pa->round_trip_time != -1); } else { // ICMP echo IP_ECHO_REPLY result; pa->responding = ICMP::get_instance()->ping(pa->pszName, result); if(pa->responding) pa->round_trip_time = (short)result.RoundTripTime; else pa->round_trip_time = -1; } } else if(hNetlibUser) { // TCP connect clock_t start_tcp = clock(); //GetLocalTime(&systime); NETLIBOPENCONNECTION conn = {0}; conn.cbSize = sizeof(NETLIBOPENCONNECTION); conn.szHost = pa->pszName; conn.wPort = pa->port; conn.flags = NLOCF_V2; conn.timeout = options.ping_timeout; HANDLE s = (HANDLE)CallService(MS_NETLIB_OPENCONNECTION, (WPARAM)hNetlibUser, (LPARAM)&conn); clock_t end_tcp = clock(); if(s) { LINGER l; char buf[1024]; SOCKET socket = (SOCKET)CallService(MS_NETLIB_GETSOCKET, (WPARAM)s, (LPARAM)NLOCF_HTTP); if(socket != INVALID_SOCKET) { l.l_onoff = 1; l.l_linger = 0; setsockopt(socket, SOL_SOCKET, SO_LINGER, (char *)&l, sizeof(l)); Netlib_Send(s, "OUT\r\n\r\n", 7, 0); //MSG_RAW); //Sleep(ICMP::get_instance()->get_timeout()); Sleep(options.ping_timeout * 1000); unsigned long bytes_remaining; ioctlsocket(socket, FIONBIO, &bytes_remaining); if(bytes_remaining > 0) { int retval, rx = 0; while((retval = Netlib_Recv(s, buf, 1024, 0)) != SOCKET_ERROR && (retval > 0) && rx < 2048) { rx += retval; // recv at most 2kb before closing connection } } //closesocket(socket); } Netlib_CloseHandle(s); pa->responding = true; pa->round_trip_time = (int)(((end_tcp - start_tcp) / (double)CLOCKS_PER_SEC) * 1000); } else { pa->responding = false; pa->round_trip_time = -1; } } return 0; }
void __cdecl CJabberProto::ByteReceiveThread( JABBER_BYTE_TRANSFER *jbt ) { HXML iqNode, queryNode = NULL, n; const TCHAR *sid = NULL, *from = NULL, *to = NULL, *szId = NULL, *szHost, *szPort, *str; int i; WORD port; HANDLE hConn; char data[3]; char* buffer; int datalen, bytesParsed, recvResult; BOOL validStreamhost = FALSE; if ( jbt == NULL ) return; jbt->state = JBT_INIT; if ( iqNode = jbt->iqNode ) { from = xmlGetAttrValue( iqNode, _T("from")); to = xmlGetAttrValue( iqNode, _T("to")); szId = xmlGetAttrValue( iqNode, _T("id")); queryNode = xmlGetChild( iqNode , "query" ); if ( queryNode ) sid = xmlGetAttrValue( queryNode, _T("sid")); } if ( szId && from && to && sid && ( n = xmlGetChild( queryNode , "streamhost" ))!=NULL ) { jbt->iqId = mir_tstrdup( szId ); jbt->srcJID = mir_tstrdup( from ); jbt->dstJID = mir_tstrdup( to ); jbt->sid = mir_tstrdup( sid ); if (( buffer=( char* )mir_alloc( JABBER_NETWORK_BUFFER_SIZE ))) { for ( i=1; ( n = xmlGetNthChild( queryNode, _T("streamhost"), i ))!=NULL; i++ ) { if (( szHost = xmlGetAttrValue( n, _T("host"))) != NULL && ( szPort = xmlGetAttrValue( n, _T("port"))) != NULL && ( str = xmlGetAttrValue( n, _T("jid"))) != NULL ) { port = ( WORD )_ttoi( szPort ); if ( jbt->streamhostJID ) mir_free( jbt->streamhostJID ); jbt->streamhostJID = mir_tstrdup( str ); Log( "bytestream_recv connecting to " TCHAR_STR_PARAM ":%d", szHost, port ); NETLIBOPENCONNECTION nloc = { 0 }; nloc.cbSize = sizeof( nloc ); nloc.szHost = mir_t2a(szHost); nloc.wPort = port; hConn = ( HANDLE ) JCallService( MS_NETLIB_OPENCONNECTION, ( WPARAM ) m_hNetlibUser, ( LPARAM )&nloc ); mir_free((void*)nloc.szHost); if ( hConn == NULL ) { Log( "bytestream_recv_connection connection failed ( %d ), try next streamhost", WSAGetLastError()); continue; } jbt->hConn = hConn; data[0] = 5; data[1] = 1; data[2] = 0; Netlib_Send( hConn, data, 3, 0 ); jbt->state = JBT_INIT; datalen = 0; while ( jbt->state!=JBT_DONE && jbt->state!=JBT_ERROR && jbt->state!=JBT_SOCKSERR ) { recvResult = Netlib_Recv( hConn, buffer+datalen, JABBER_NETWORK_BUFFER_SIZE-datalen, 0 ); if ( recvResult <= 0 ) break; datalen += recvResult; bytesParsed = ByteReceiveParse( hConn, jbt, buffer, datalen ); if ( bytesParsed < datalen ) memmove( buffer, buffer+bytesParsed, datalen-bytesParsed ); datalen -= bytesParsed; if ( jbt->state == JBT_RECVING ) validStreamhost = TRUE; } Netlib_CloseHandle( hConn ); Log( "bytestream_recv_connection closing connection" ); } if ( jbt->state==JBT_ERROR || validStreamhost==TRUE ) break; Log( "bytestream_recv_connection stream cannot be established, try next streamhost" ); } mir_free( buffer ); } } (this->*jbt->pfnFinal)(( jbt->state==JBT_DONE )?TRUE:FALSE, jbt->ft ); jbt->ft = NULL; if ( !validStreamhost && szId && from ) { Log( "bytestream_recv_connection session not completed" ); m_ThreadInfo->send( XmlNodeIq( _T("error"), szId, from ) << XCHILD( _T("error")) << XATTRI( _T("code"), 404 ) << XATTR( _T("type"), _T("cancel")) << XCHILDNS( _T("item-not-found"), _T("urn:ietf:params:xml:ns:xmpp-stanzas"))); } delete jbt; Log( "Thread ended: type=bytestream_recv" ); }
void JabberByteSendConnection( HANDLE hConn, DWORD /*dwRemoteIP*/, void* extra ) { CJabberProto* ppro = ( CJabberProto* )extra; SOCKET s; SOCKADDR_IN saddr; int len; WORD localPort; TCHAR szPort[8]; JABBER_BYTE_TRANSFER *jbt; int recvResult, bytesParsed; HANDLE hListen; JABBER_LIST_ITEM *item; char* buffer; int datalen; localPort = 0; if (( s = JCallService( MS_NETLIB_GETSOCKET, ( WPARAM ) hConn, 0 )) != INVALID_SOCKET ) { len = sizeof( saddr ); if ( getsockname( s, ( SOCKADDR * ) &saddr, &len ) != SOCKET_ERROR ) localPort = ntohs( saddr.sin_port ); } if ( localPort == 0 ) { ppro->Log( "bytestream_send_connection unable to determine the local port, connection closed." ); Netlib_CloseHandle( hConn ); return; } mir_sntprintf( szPort, SIZEOF( szPort ), _T("%d"), localPort ); ppro->Log( "bytestream_send_connection incoming connection accepted: local_port=" TCHAR_STR_PARAM, szPort ); if (( item = ppro->ListGetItemPtr( LIST_BYTE, szPort )) == NULL ) { ppro->Log( "No bytestream session is currently active, connection closed." ); Netlib_CloseHandle( hConn ); return; } jbt = item->jbt; if (( buffer = ( char* )mir_alloc( JABBER_NETWORK_BUFFER_SIZE )) == NULL ) { ppro->Log( "bytestream_send cannot allocate network buffer, connection closed." ); jbt->state = JBT_ERROR; Netlib_CloseHandle( hConn ); if ( jbt->hEvent != NULL ) SetEvent( jbt->hEvent ); return; } hListen = jbt->hConn; jbt->hConn = hConn; jbt->state = JBT_INIT; datalen = 0; while ( jbt->state!=JBT_DONE && jbt->state!=JBT_ERROR ) { recvResult = Netlib_Recv( hConn, buffer+datalen, JABBER_NETWORK_BUFFER_SIZE-datalen, 0 ); if ( recvResult <= 0 ) break; datalen += recvResult; bytesParsed = ppro->ByteSendParse( hConn, jbt, buffer, datalen ); if ( bytesParsed < datalen ) memmove( buffer, buffer+bytesParsed, datalen-bytesParsed ); datalen -= bytesParsed; } if ( jbt->hConn ) Netlib_CloseHandle( jbt->hConn ); ppro->Log( "bytestream_send_connection closing connection" ); jbt->hConn = hListen; mir_free( buffer ); if ( jbt->hEvent != NULL ) SetEvent( jbt->hEvent ); }