HRESULT TunnelReceive(int *lpNbBytesRecvd, LPSTR *lpBuffer) { HRESULT hRes=S_OK; int iResult; errno_t err; *lpNbBytesRecvd = 0; if(FAILED(hRes=TunnelIsUp())) { dbgout("[sync] TunnelReceive: tunnel is not available\n"); return hRes; } iResult = recv(g_Sock, RecvBuffer, MAX_SEND, 0); if ( iResult == SOCKET_ERROR ) { iResult = WSAGetLastError(); if (iResult == WSAEWOULDBLOCK) { return hRes; } else { dbgout("[sync] recv failed with error: %d, 0x%x\n", iResult, g_Sock); WsaErrMsg(iResult); goto error_close; } } else if ( iResult == 0 ) { dbgout("[sync] recv: connection closed\n"); goto error_close; } *lpBuffer = (LPSTR) calloc(iResult+1, sizeof(CHAR)); if (lpBuffer == NULL) { dbgout("[sync] failed at allocate buffer: %d\n", GetLastError()); return E_FAIL; } err = memcpy_s(*lpBuffer, iResult+1, RecvBuffer, iResult); if (err) { dbgout("[sync] memcpy_s failed to copy received buffer\n"); free(*lpBuffer); *lpBuffer = NULL; hRes = E_FAIL; } else { *lpNbBytesRecvd = iResult; } return hRes; error_close: g_Synchronized = FALSE; TunnelClose(); return E_FAIL; }
HRESULT TunnelSend(PCSTR Format, ...) { HRESULT hRes=S_OK; va_list Args; int iResult; size_t cbRemaining; if (FAILED(hRes=TunnelIsUp())) { dprintf("[sync] TunnelSend: tunnel is unavailable\n"); return hRes; } va_start(Args, Format); hRes = StringCbVPrintfEx(SendBuffer, MAX_SEND, NULL, &cbRemaining, STRSAFE_NULL_ON_FAILURE, Format, Args); va_end(Args); if (FAILED(hRes)){ return hRes; } #if VERBOSE >= 2 dprintf("[sync] send 0x%x bytes, %s\n", MAX_SEND-cbRemaining, SendBuffer); #endif iResult = send(g_Sock, (const char *)SendBuffer, MAX_SEND-((unsigned int)cbRemaining), 0); if (iResult == SOCKET_ERROR) { iResult = WSAGetLastError(); dprintf("[sync] send failed with error %d, 0x%x\n", iResult, g_Sock); WsaErrMsg(iResult); g_Synchronized = FALSE; TunnelClose(); hRes=E_FAIL; } return hRes; }