void ReadEx(T *x) { Read(x, sizeof(*x)); }
size_t Read(T* t) { return Read(t, sizeof(T)); }
bool CGPIBDevice::Query(const char *sWrite, int &nLen, char *sRead, int nTimeout) { return Write(sWrite) && Read(sRead, nLen, nTimeout); }
bool CMgProxySocket::DoV5Connect( const char* server , int port ) { unsigned char buf[ 512 ]; buf[ 0 ] = 0x05; buf[ 1 ] = 0x01; //connect buf[ 2 ] = 0x00; //reserve buf[ 3 ] = 0x03; buf[ 4 ] = strlen( server ); memcpy( buf + 5, server, strlen( server ) ); int pos = 5 + buf[ 4 ]; short sport = htons( ( short ) port ); memcpy( buf + pos, &sport, 2 ); pos += 2; if ( !Send( buf, pos ) ) { m_nLastError += ( 0x1A << 8 ); return false; } int nret = Read( buf, 512 ); if ( nret <= 0 ) { m_nLastError += ( 0x1B << 8 ); return false; } if ( nret < 10 ) { m_nLastError = ( 0x0F << 8 ); return false; } if ( buf[ 0 ] != 0x05 || buf[ 2 ] != 0x00 ) { m_nLastError = ( 0x10 << 8 ); return false; } /* # X'00' success # X'01' fail # X'02' not allow # X'03' net unreach # X'04' host unreach # X'05' connect refuse # X'06' TTL timeout # X'07' not support command # X'08' not support address # X'09' – X'FF' undef */ if ( buf[ 1 ] == 0 ) { return true; } else if ( buf[ 1 ] == 0x01 ) { m_nLastError = ( 0x11 << 8 ); return false; } else if ( buf[ 1 ] == 0x02 ) { m_nLastError = ( 0x12 << 8 ); return false; } else if ( buf[ 1 ] == 0x03 ) { m_nLastError = ( 0x13 << 8 ); return false; } else if ( buf[ 1 ] == 0x04 ) { m_nLastError = ( 0x14 << 8 ); return false; } else if ( buf[ 1 ] == 0x05 ) { m_nLastError = ( 0x15 << 8 ); return false; } else if ( buf[ 1 ] == 0x06 ) { m_nLastError = ( 0x16 << 8 ); return false; } else if ( buf[ 1 ] == 0x07 ) { m_nLastError = ( 0x17 << 8 ); return false; } else if ( buf[ 1 ] == 0x08 ) { m_nLastError = ( 0x18 << 8 ); return false; } else { m_nLastError = ( 0x19 << 8 ); return false; } return false; }
bool CMgProxySocket::DoV5Login() { unsigned char init[ 4 ] = {0x05, 0x02, 0x00, 0x02}; if ( !Send( init, 4 ) ) { m_nLastError = ( 0x03 << 8 ); return false; } unsigned char buf[ 256 ]; int nret = Read( buf, 256 ); if ( nret != 2 ) { m_nLastError = ( 0x04 << 8 ); return false; } if ( buf[ 0 ] != 0x05 ) { m_nLastError = ( 0x05 << 8 ); return false; } if ( buf[ 1 ] == 0xFF ) { m_nLastError = ( 0x06 << 8 ); return false; } if ( buf[ 1 ] != 0 && buf[ 1 ] != 1 && buf[ 1 ] != 2 ) { m_nLastError = ( 0x07 << 8 ); return false; } if ( buf[ 1 ] == 0 ) { //ok return true; } else if ( buf[ 1 ] == 1 ) { //GSSAPI m_nLastError = ( 0x08 << 8 ); return false; } else { //u/p int tl = 0; buf[ 0 ] = 0x01; tl++; buf[ tl ] = m_ProxyUser.length(); tl++; memcpy( buf + tl, m_ProxyUser.c_str(), m_ProxyUser.length() ); tl += m_ProxyUser.length(); buf[ tl ] = m_ProxyPass.length(); tl++; memcpy( buf + tl, m_ProxyPass.c_str(), m_ProxyPass.length() ); tl += m_ProxyPass.length(); if ( !Send( buf, tl ) ) { m_nLastError += ( 0x09 << 8 ); return false; } if ( Read( buf, 256 ) != 2 ) { m_nLastError = ( 0x0A << 8 ); return false; } if ( buf[ 0 ] != 0x01 ) { m_nLastError = ( 0x0B << 8 ); return false; } if ( buf[ 1 ] != 0x00 ) { m_nLastError = ( 0x0C << 8 ); return false; } return true; } return false; }
int main( int argc, char **argv ) { int listenfd, connfd, sockfd; int client[FD_SETSIZE]; int i, maxfd, maxi, nready; socklen_t clilen; ssize_t n; char buff[MAXLINE]; struct sockaddr_in servaddr, cliaddr; fd_set rset, allset; listenfd = Socket( AF_INET, SOCK_STREAM, 0 ); bzero( &servaddr, sizeof( servaddr ) ); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl( INADDR_ANY ); servaddr.sin_port = htons( SERV_PORT ); Bind( listenfd, ( struct sockaddr * )&servaddr, sizeof( servaddr ) ); Listen( listenfd, 10 ); maxfd = listenfd; maxi = -1; for ( i = 0; i < FD_SETSIZE; i++ ) { client[i] = -1; } FD_ZERO( &allset ); FD_SET( listenfd, &allset ); for ( ; ; ) { rset = allset; nready = Select( maxfd+1, &rset, NULL, NULL, NULL ); if ( FD_ISSET( listenfd, &rset ) ) { clilen = sizeof( cliaddr ); connfd = Accept( listenfd, ( struct sockaddr * )&cliaddr, &clilen ); for ( i = 0; i < FD_SETSIZE; i++ ) { if ( client[i] < 0 ) { client[i] = connfd; break; } } if ( i == FD_SETSIZE ) err_quit( "too many clients" ); FD_SET( connfd, &allset ); if ( connfd > maxfd ) maxfd = connfd; if ( i > maxi ) maxi = i; if ( --nready <= 0 ) continue; } for ( i = 0; i <= maxi; i++ ) { if ( ( sockfd = client[i] ) < 0 ) continue; if ( FD_ISSET( sockfd, &rset ) ) { if ( ( n = Read( sockfd, buff, MAXLINE ) ) == 0 ) { close( sockfd ); FD_CLR( sockfd, &allset ); client[i] = -1; } else writen( sockfd, buff, n ); if ( --nready <= 0 ) break; } } } }
int CSocketServer::WorkerThread::Run() { try { while ( true ) { /* * Continually loop to service io completion packets */ bool closeSocket = false; DWORD dwIoSize = 0; Socket *pSocket = 0; CIOBuffer *pBuffer = 0; try { m_iocp.GetStatus( (PDWORD_PTR)&pSocket, &dwIoSize, (OVERLAPPED **)&pBuffer ); } catch (const CWin32Exception &e) { if ( e.GetError() != ERROR_NETNAME_DELETED && e.GetError() != WSA_OPERATION_ABORTED ) { throw; } Output( _T("IOCP error [client connection dropped] - ") + GetLastErrorMessage( ::WSAGetLastError() ) ); closeSocket = true; } if ( !pSocket ) { /* * A completion key of 0 is posted to the iocp to request us to shut down... */ break; } /* * Call to unqualified virtual function */ OnBeginProcessing(); if ( pBuffer ) { const IO_Operation operation = static_cast<IO_Operation>( pBuffer->GetUserData() ); switch ( operation ) { case IO_Read_Request: Read( pSocket, pBuffer ); break; case IO_Read_Completed : if ( 0 != dwIoSize ) { pBuffer->Use( dwIoSize ); //DEBUG_ONLY( Output(_T("RX: ") + ToString(pBuffer) + _T("\n") + DumpData(reinterpret_cast<const BYTE*>( pBuffer->GetWSABUF()->buf), dwIoSize, 40) ) ); /* * Call to unqualified virtual function */ ReadCompleted( pSocket, pBuffer ); } else { /* * client connection dropped... */ Output( _T("ReadCompleted - 0 bytes - client connection dropped") ); closeSocket = true; } pSocket->Release(); pBuffer->Release(); break; case IO_Write_Request : Write( pSocket, pBuffer ); if ( dwIoSize != 0 ) { /* * final write, now shutdown send side of connection */ pSocket->Shutdown( SD_SEND ); } break; case IO_Write_Completed : pBuffer->Use( dwIoSize ); //DEBUG_ONLY( Output(_T("TX: ") + ToString(pBuffer) + _T("\n") + DumpData(reinterpret_cast<const BYTE*>( pBuffer->GetWSABUF()->buf), dwIoSize, 40) ) ); /* * Call to unqualified virtual function */ WriteCompleted( pSocket, pBuffer ); pSocket->Release(); pBuffer->Release(); break; case IO_Close : AbortiveClose( pSocket ); pSocket->Release(); pBuffer->Release(); break; default : /* * all to unqualified virtual function */ OnError( _T("CSocketServer::WorkerThread::Run() - Unexpected operation") ); break; } } else { /* * Call to unqualified virtual function */ OnError( _T("CSocketServer::WorkerThread::Run() - Unexpected - pBuffer is 0") ); } if ( closeSocket ) { pSocket->Close(); } /* * Call to unqualified virtual function */ OnEndProcessing(); } } catch(const CException &e) { /* * Call to unqualified virtual function */ OnError( _T("CSocketServer::WorkerThread::Run() - Exception: ") + e.GetWhere() + _T(" - ") + e.GetMessage() ); } catch(...) { /* * Call to unqualified virtual function */ OnError( _T("CSocketServer::WorkerThread::Run() - Unexpected exception") ); } return 0; }
uint In::Read16() { byte data[2]; Read( data, 2 ); return data[0] | uint(data[1]) << 8; }
dword In::Read32() { byte data[4]; Read( data, 4 ); return data[0] | uint(data[1]) << 8 | dword(data[2]) << 16 | dword(data[3]) << 24; }
int Buffer::Peek() { int curPos = GetPos(); int ch = Read(); SetPos(curPos); return ch; }
uint In::Read8() { byte data; Read( &data, 1 ); return data; }
FStatsThreadState::FStatsThreadState( FString const& Filename ) : HistoryFrames( MAX_int32 ) , MaxFrameSeen( -1 ) , MinFrameSeen( -1 ) , LastFullFrameMetaAndNonFrame( -1 ) , LastFullFrameProcessed( -1 ) , bWasLoaded( true ) , CurrentGameFrame( -1 ) , CurrentRenderFrame( -1 ) { const int64 Size = IFileManager::Get().FileSize( *Filename ); if( Size < 4 ) { UE_LOG( LogStats, Error, TEXT( "Could not open: %s" ), *Filename ); return; } TAutoPtr<FArchive> FileReader( IFileManager::Get().CreateFileReader( *Filename ) ); if( !FileReader ) { UE_LOG( LogStats, Error, TEXT( "Could not open: %s" ), *Filename ); return; } FStatsReadStream Stream; if( !Stream.ReadHeader( *FileReader ) ) { UE_LOG( LogStats, Error, TEXT( "Could not open, bad magic: %s" ), *Filename ); return; } // Test version only works for the finalized stats files. const bool bIsFinalized = Stream.Header.IsFinalized(); check( bIsFinalized ); TArray<FStatMessage> Messages; if( Stream.Header.bRawStatsFile ) { const int64 CurrentFilePos = FileReader->Tell(); // Read metadata. TArray<FStatMessage> MetadataMessages; Stream.ReadFNamesAndMetadataMessages( *FileReader, MetadataMessages ); ProcessMetaDataForLoad( MetadataMessages ); // Read frames offsets. Stream.ReadFramesOffsets( *FileReader ); // Verify frames offsets. for( int32 FrameIndex = 0; FrameIndex < Stream.FramesInfo.Num(); ++FrameIndex ) { const int64 FrameFileOffset = Stream.FramesInfo[FrameIndex].FrameFileOffset; FileReader->Seek( FrameFileOffset ); int64 TargetFrame; *FileReader << TargetFrame; } FileReader->Seek( Stream.FramesInfo[0].FrameFileOffset ); // Read the raw stats messages. FStatPacketArray IncomingData; for( int32 FrameIndex = 0; FrameIndex < Stream.FramesInfo.Num(); ++FrameIndex ) { int64 TargetFrame; *FileReader << TargetFrame; int32 NumPackets; *FileReader << NumPackets; for( int32 PacketIndex = 0; PacketIndex < NumPackets; PacketIndex++ ) { FStatPacket* ToRead = new FStatPacket(); Stream.ReadStatPacket( *FileReader, *ToRead, bIsFinalized ); IncomingData.Packets.Add( ToRead ); } FStatPacketArray NowData; // This is broken, do not use. // Exchange( NowData.Packets, IncomingData.Packets ); // ScanForAdvance( NowData ); // AddToHistoryAndEmpty( NowData ); // check( !NowData.Packets.Num() ); } } else { // Read the condensed stats messages. while( FileReader->Tell() < Size ) { FStatMessage Read( Stream.ReadMessage( *FileReader ) ); if( Read.NameAndInfo.GetField<EStatOperation>() == EStatOperation::SpecialMessageMarker ) { // Simply break the loop. // The profiler supports more advanced handling of this message. break; } else if( Read.NameAndInfo.GetField<EStatOperation>() == EStatOperation::AdvanceFrameEventGameThread ) { ProcessMetaDataForLoad( Messages ); if( CurrentGameFrame > 0 && Messages.Num() ) { check( !CondensedStackHistory.Contains( CurrentGameFrame ) ); TArray<FStatMessage>* Save = new TArray<FStatMessage>(); Exchange( *Save, Messages ); CondensedStackHistory.Add( CurrentGameFrame, Save ); GoodFrames.Add( CurrentGameFrame ); } } new (Messages)FStatMessage( Read ); } // meh, we will discard the last frame, but we will look for meta data } }
T Read() { T x; Read(&x, sizeof(T)); return x; }
void Read(T& x) { Read(&x, sizeof(T)); }
long CacheRead( CICell ih, char * buffer, long long offset, long length, long cache ) { long cnt, oldestEntry = 0, oldestTime, loadCache = 0; CacheEntry *entry; // See if the data can be cached. if (cache && (gCacheIH == ih) && (length == gCacheBlockSize)) { // Look for the data in the cache. for (cnt = 0; cnt < gCacheNumEntries; cnt++) { entry = &gCacheEntries[cnt]; if ((entry->ih == ih) && (entry->offset == offset)) { entry->time = ++gCacheTime; break; } } // If the data was found copy it to the caller. if (cnt != gCacheNumEntries) { bcopy(gCacheBuffer + cnt * gCacheBlockSize, buffer, gCacheBlockSize); #if CACHE_STATS gCacheHits++; #endif return gCacheBlockSize; } // Could not find the data in the cache. loadCache = 1; } // Read the data from the disk. Seek(ih, offset); Read(ih, (long)buffer, length); #if CACHE_STATS if (cache) gCacheMisses++; #endif // Put the data from the disk in the cache if needed. if (loadCache) { // Find a free entry. oldestTime = gCacheTime; for (cnt = 0; cnt < gCacheNumEntries; cnt++) { entry = &gCacheEntries[cnt]; // Found a free entry. if (entry->ih == 0) break; if (entry->time < oldestTime) { oldestTime = entry->time; oldestEntry = cnt; } } // If no free entry was found, use the oldest. if (cnt == gCacheNumEntries) { cnt = oldestEntry; #if CACHE_STATS gCacheEvicts++; #endif } // Copy the data from disk to the new entry. entry = &gCacheEntries[cnt]; entry->ih = ih; entry->time = ++gCacheTime; entry->offset = offset; bcopy(buffer, gCacheBuffer + cnt * gCacheBlockSize, gCacheBlockSize); } return length; }
bool CVolumeWiiCrypted::CheckIntegrity() const { // Get partition data size u32 partSizeDiv4; RAWRead(m_VolumeOffset + 0x2BC, 4, (u8*)&partSizeDiv4); u64 partDataSize = (u64)Common::swap32(partSizeDiv4) * 4; u32 nClusters = (u32)(partDataSize / 0x8000); for (u32 clusterID = 0; clusterID < nClusters; ++clusterID) { u64 clusterOff = m_VolumeOffset + dataOffset + (u64)clusterID * 0x8000; // Read and decrypt the cluster metadata u8 clusterMDCrypted[0x400]; u8 clusterMD[0x400]; u8 IV[16] = { 0 }; if (!m_pReader->Read(clusterOff, 0x400, clusterMDCrypted)) { NOTICE_LOG(DISCIO, "Integrity Check: fail at cluster %d: could not read metadata", clusterID); return false; } aes_crypt_cbc(m_AES_ctx, AES_DECRYPT, 0x400, IV, clusterMDCrypted, clusterMD); // Some clusters have invalid data and metadata because they aren't // meant to be read by the game (for example, holes between files). To // try to avoid reporting errors because of these clusters, we check // the 0x00 paddings in the metadata. // // This may cause some false negatives though: some bad clusters may be // skipped because they are *too* bad and are not even recognized as // valid clusters. To be improved. bool meaningless = false; for (u32 idx = 0x26C; idx < 0x280; ++idx) if (clusterMD[idx] != 0) meaningless = true; if (meaningless) continue; u8 clusterData[0x7C00]; if (!Read((u64)clusterID * 0x7C00, 0x7C00, clusterData)) { NOTICE_LOG(DISCIO, "Integrity Check: fail at cluster %d: could not read data", clusterID); return false; } for (u32 hashID = 0; hashID < 31; ++hashID) { u8 hash[20]; sha1(clusterData + hashID * 0x400, 0x400, hash); // Note that we do not use strncmp here if (memcmp(hash, clusterMD + hashID * 20, 20)) { NOTICE_LOG(DISCIO, "Integrity Check: fail at cluster %d: hash %d is invalid", clusterID, hashID); return false; } } } return true; }
bool Archive::IsArchive(bool EnableBroken) { Encrypted=false; #ifndef SFX_MODULE if (IsDevice()) { #ifndef SHELL_EXT Log(FileName,St(MInvalidName),FileName); #endif return(false); } #endif if (Read(MarkHead.Mark,SIZEOF_MARKHEAD)!=SIZEOF_MARKHEAD) return(false); SFXSize=0; ARCSIGN_TYPE Type; if ((Type=IsSignature(MarkHead.Mark,sizeof(MarkHead.Mark)))!=ARCSIGN_NONE) { OldFormat=(Type==ARCSIGN_OLD); if (OldFormat) Seek(0,SEEK_SET); } else { Array<char> Buffer(MAXSFXSIZE); long CurPos=(long)Tell(); int ReadSize=Read(&Buffer[0],Buffer.Size()-16); for (int I=0;I<ReadSize;I++) if (Buffer[I]==0x52 && (Type=IsSignature((byte *)&Buffer[I],ReadSize-I))!=ARCSIGN_NONE) { OldFormat=(Type==ARCSIGN_OLD); if (OldFormat && I>0 && CurPos<28 && ReadSize>31) { char *D=&Buffer[28-CurPos]; if (D[0]!=0x52 || D[1]!=0x53 || D[2]!=0x46 || D[3]!=0x58) continue; } SFXSize=CurPos+I; Seek(SFXSize,SEEK_SET); if (!OldFormat) Read(MarkHead.Mark,SIZEOF_MARKHEAD); break; } if (SFXSize==0) return false; } if (Type==ARCSIGN_FUTURE) { #if !defined(SHELL_EXT) && !defined(SFX_MODULE) Log(FileName,St(MNewRarFormat)); #endif return false; } ReadHeader(); SeekToNext(); #ifndef SFX_MODULE if (OldFormat) { NewMhd.Flags=OldMhd.Flags & 0x3f; NewMhd.HeadSize=OldMhd.HeadSize; } else #endif { if (HeaderCRC!=NewMhd.HeadCRC) { #ifndef SHELL_EXT Log(FileName,St(MLogMainHead)); #endif Alarm(); if (!EnableBroken) return(false); } } Volume=(NewMhd.Flags & MHD_VOLUME); Solid=(NewMhd.Flags & MHD_SOLID)!=0; MainComment=(NewMhd.Flags & MHD_COMMENT)!=0; Locked=(NewMhd.Flags & MHD_LOCK)!=0; Signed=(NewMhd.PosAV!=0); Protected=(NewMhd.Flags & MHD_PROTECT)!=0; Encrypted=(NewMhd.Flags & MHD_PASSWORD)!=0; if (NewMhd.EncryptVer>UNP_VER) { #ifdef RARDLL Cmd->DllError=ERAR_UNKNOWN_FORMAT; #else ErrHandler.SetErrorCode(RARX_WARNING); #if !defined(SILENT) && !defined(SFX_MODULE) Log(FileName,St(MUnknownMeth),FileName); Log(FileName,St(MVerRequired),NewMhd.EncryptVer/10,NewMhd.EncryptVer%10); #endif #endif return(false); } #ifdef RARDLL // If callback function is not set, we cannot get the password, // so we skip the initial header processing for encrypted header archive. // It leads to skipped archive comment, but the rest of archive data // is processed correctly. if (Cmd->Callback==NULL) SilentOpen=true; #endif // If not encrypted, we'll check it below. NotFirstVolume=Encrypted && (NewMhd.Flags & MHD_FIRSTVOLUME)==0; if (!SilentOpen || !Encrypted) { SaveFilePos SavePos(*this); int64 SaveCurBlockPos=CurBlockPos,SaveNextBlockPos=NextBlockPos; NotFirstVolume=false; while (ReadHeader()!=0) { int HeaderType=GetHeaderType(); if (HeaderType==NEWSUB_HEAD) { if (SubHead.CmpName(SUBHEAD_TYPE_CMT)) MainComment=true; if ((SubHead.Flags & LHD_SPLIT_BEFORE) || Volume && (NewMhd.Flags & MHD_FIRSTVOLUME)==0) NotFirstVolume=true; } else { if (HeaderType==FILE_HEAD && ((NewLhd.Flags & LHD_SPLIT_BEFORE)!=0 || Volume && NewLhd.UnpVer>=29 && (NewMhd.Flags & MHD_FIRSTVOLUME)==0)) NotFirstVolume=true; break; } SeekToNext(); } CurBlockPos=SaveCurBlockPos; NextBlockPos=SaveNextBlockPos; } if (!Volume || !NotFirstVolume) { strcpy(FirstVolumeName,FileName); wcscpy(FirstVolumeNameW,FileNameW); } return(true); }
void CCommSession::ServiceL(const RMessage2& aMessage) /** * Handle messages for this session. * * @param aMessage handle to the IPC message from the client */ { C32LOG5(KC32Detail,_L8("CCommSession::ServiceL(), Session : 0x%x, IPC: %d (%S). Message: %08x"), this, aMessage.Function(), &TC32Log::C32RequestStr(aMessage.Function()),aMessage.Handle()); iComplete = ETrue; const CC32WorkerThread& owner=C32WorkerThread(); CC32Dealer& c32Dealer = owner.DealerByRef(); if (c32Dealer.StartupFailed()) { SafeComplete(aMessage, KErrNotReady); return; } // TestImmediateShutdownPresent is only set when EImmediate shutdown is present, which is // used only in testing phase. if(c32Dealer.TestImmediateShutdownPresent()) { User::Leave(KErrServerTerminated); } if((aMessage.Function()==ECommOpen) || (aMessage.Function()==ECommOpenWhenAvailable)) { NewPortL(aMessage); return; } #if defined (_DEBUG) switch (aMessage.Function()) { case ECommDbgMarkHeap: __UHEAP_MARK; SafeComplete(aMessage, KErrNone); return; case ECommDbgCheckHeap: __UHEAP_CHECK(aMessage.Int0()); SafeComplete(aMessage, KErrNone); return; case ECommDbgMarkEnd: __UHEAP_MARKENDC(aMessage.Int0()); SafeComplete(aMessage, KErrNone); return; case ECommDbgFailNext: // We set the fail point for all heaps, rather than just the current Dealer. This could lead to a failure not related // directly to whatever the client test code is trying to exercise but it all helps find bugs c32Dealer.SetFailNextForAllHeaps(aMessage.Int0()); SafeComplete(aMessage, KErrNone); return; } #endif switch ((aMessage.Function())) { case ECommLoadCommModule: { TFileName fullCSYFilename; TInt ret = Read(0,aMessage,fullCSYFilename); if (ret != KErrNone) { C32LOG2(KC32Warning, _L8("ServiceL: LoadCommModule Read returned %d instead of KErrNone, cannot proceed"), ret); PanicClient(EBadDescriptor,aMessage); return; } ret = AddCSYExtension(fullCSYFilename,aMessage); if(ret != KErrNone) { C32LOG2(KC32Warning, _L8("ServiceL: LoadCommModule AddCSYExtension returned %d instead of KErrNone, cannot proceed"), ret); return; } CommsFW::TWorkerId worker; TBuf8<KMaxFileName> fileName8; fileName8.Copy(fullCSYFilename); TBool found = iThreadManager->FindThreadByFileName(fileName8, worker); if(!found) { worker = iThreadManager->iDefaultThreadIndex; } if(c32Dealer.WorkerExists(worker)) { LoadCommModuleL(aMessage,worker,!found,fullCSYFilename); } else { C32LOG2(KC32Dealer,_L8("ServiceL: LoadCommModule requires worker %d. This worker does not exist so starting"),worker); ret = c32Dealer.LoadCPMOnLoadCommModule(worker); if ((ret!=KErrNone) && (ret!=KErrInUse)) { // only likely return codes here are KErrNoMemory or KErrNotFound if // the RS server could not be found - which means system is probably in pretty bad state (ie, no memory) // luckily at this point there isn't anything to clean up! SafeComplete(aMessage,ret); } else { ret = c32Dealer.ParkRequest(this, aMessage); if(ret != KErrNone) { SafeComplete(aMessage, ret); } } } return; } case ECommCloseCommModule: CloseCommModuleL(aMessage); return; case ECommPortInfoByName: { TPortName name; TInt ret = Read(1,aMessage,name); if (ret != KErrNone) { C32LOG2(KC32Warning, _L8("ServiceL: LoadCommModule Read returned %d instead of KErrNone, cannot proceed"), ret); PanicClient(EBadDescriptor,aMessage); return; } PortInfoL(aMessage,name); return; } case ECommPortInfoByNumber: // original msg is not forwarded as global as aMessage.Int2() is not valid in player, instead CSerial* is wrapped in TC32PlayerGetPortInfoMsg PortInfo(aMessage,aMessage.Int2()); return; case ECommNumPorts: // get information from ThreadManager in dealer NumPorts(aMessage); return; case ECommStartServerThread: // KErrNotSupported C32LOG2(KC32Dealer, _L8("WARNING: deprecated function ECommStartServerThread called, CCommSession(%08x)"), this); SafeComplete(aMessage, KErrNotSupported); return; } // obtain subsession* from aMessage.Int3() CCommSubSession *p = SubSessionFromHandle(aMessage.Int3(), CCommSubSession::ECPort); if (aMessage.Function()==ECommClose) { if (p==NULL) // not a valid aMessage.Int3() { SafeComplete(aMessage, KErrBadHandle); return; } else { CloseSubSessionL(aMessage, CCommSubSession::ECPort); return; } } if (p==NULL) // not a valid aMessage.Int3() { PanicClient(EBadCommHandle, aMessage); return; } // Its OK to proceed with the dispatch of other requests switch (aMessage.Function()) { case ECommRead: case ECommReadCancel: case ECommQueryReceiveBuffer: case ECommResetBuffers: case ECommWrite: case ECommWriteCancel: case ECommBreak: case ECommBreakCancel: case ECommCancel: case ECommConfig: case ECommSetConfig: case ECommCaps: case ECommSetMode: case ECommGetMode: case ECommSignals: case ECommSetSignalsToMark: case ECommSetSignalsToSpace: case ECommReceiveBufferLength: case ECommSetReceiveBufferLength: case ECommSetAccess: case ECommOpenWhenAvailableCancel: #ifdef _DEBUG case ECommDebugState: #endif // Extensions to the CCommSession starts from here case ECommNotifySignals: case ECommNotifyFlowControl: case ECommNotifySignalsCancel: case ECommNotifyFlowControlCancel: case ECommGetFlowControl: case ECommNotifyConfigChange: case ECommNotifyConfigChangeCancel: case ECommNotifyBreak: case ECommNotifyBreakCancel: case ECommGetRole: case ECommNotifyDataAvailable: case ECommNotifyDataAvailableCancel: case ECommNotifyOutputEmpty: case ECommNotifyOutputEmptyCancel: ForwardMessageL(aMessage, *p); break; // Extensions to the CCommSession ends to here default: SafeComplete(aMessage, KErrNotSupported); break; } C32LOG(KC32Detail,_L8("CCommSession::ServiceL() end")); }
int Server::StdinProcess(){ std::string buf; if(Read(STDIN_FILENO, buf) <= 0) return -1; if(buf == "exit") Close(); return 0; }
wxArrayString ConfigManager::ReadArrayString(const wxString& name) { wxArrayString as; Read(name, &as); return as; }
void MainWND::OnEnter(wxCommandEvent &event) { // bool loop_check; if(Commandline->GetValue()== wxT("read")) { Clear_terminal(); SOFT_TRIG(); wxYield(); Read(true); wxYield(); } else if(Commandline->GetValue() == wxT("write0")) { Clear_terminal(); LOAD_RAM_DATA(0); LOAD_PATTERN(); SOFT_TRIG(); wxYield(); } else if(Commandline->GetValue() == wxT("write1")) { Clear_terminal(); LOAD_RAM_DATA(1); LOAD_PATTERN(); SOFT_TRIG(); wxYield(); } else if(Commandline->GetValue() == wxT("write2")) { Clear_terminal(); LOAD_RAM_DATA(2); LOAD_PATTERN(); SOFT_TRIG(); wxYield(); } else if(Commandline->GetValue() == wxT("write3")) { Clear_terminal(); LOAD_RAM_DATA(3); LOAD_PATTERN(); SOFT_TRIG(); wxYield(); } else if(Commandline->GetValue() == wxT("write4")) { Clear_terminal(); LOAD_RAM_DATA(4); LOAD_PATTERN(); SOFT_TRIG(); wxYield(); } else if(Commandline->GetValue() == wxT("write5")) { Clear_terminal(); LOAD_RAM_DATA(5); LOAD_PATTERN(); SOFT_TRIG(); wxYield(); } else if(Commandline->GetValue() == wxT("write6")) { Clear_terminal(); LOAD_RAM_DATA(6); LOAD_PATTERN(); SOFT_TRIG(); wxYield(); } else if(Commandline->GetValue() == wxT("write7")) { Clear_terminal(); LOAD_RAM_DATA(7); LOAD_PATTERN(); SOFT_TRIG(); wxYield(); } else if(Commandline->GetValue() == wxT("write8")) { Clear_terminal(); LOAD_RAM_DATA(8); LOAD_PATTERN(); SOFT_TRIG(); wxYield(); } else if(Commandline->GetValue() == wxT("write9")) { Clear_terminal(); LOAD_RAM_DATA(9); LOAD_PATTERN(); SOFT_TRIG(); wxYield(); } else if(Commandline->GetValue() == wxT("trig")) { SOFT_TRIG(); TextFrame->AppendText(wxString::Format(wxT("sending software trigger...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("bank0")) { set_register_bank_address(0); TextFrame->AppendText(wxString::Format(wxT("setting register bank address to 0...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("bank1")) { set_register_bank_address(1); TextFrame->AppendText(wxString::Format(wxT("setting register bank address to 1...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("bank2")) { set_register_bank_address(2); TextFrame->AppendText(wxString::Format(wxT("setting register bank address to 2...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("bank3")) { set_register_bank_address(3); TextFrame->AppendText(wxString::Format(wxT("setting register bank address to 3...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("writemode0")) { set_ram_write_mode(0); TextFrame->AppendText(wxString::Format(wxT("setting ram write mode to 0...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("writemode1")) { set_ram_write_mode(1); TextFrame->AppendText(wxString::Format(wxT("setting ram write mode to 1...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("writemode2")) { set_ram_write_mode(2); TextFrame->AppendText(wxString::Format(wxT("setting ram write mode to 2...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("writemode3")) { set_ram_write_mode(3); TextFrame->AppendText(wxString::Format(wxT("setting ram write mode to 3...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("readmode0")) { set_ram_read_mode(0); TextFrame->AppendText(wxString::Format(wxT("setting ram read mode to 0...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("readmode1")) { set_ram_read_mode(1); TextFrame->AppendText(wxString::Format(wxT("setting ram read mode to 1...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("readmode2")) { set_ram_read_mode(2); TextFrame->AppendText(wxString::Format(wxT("setting ram read mode to 2...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("readmode3")) { set_ram_read_mode(3); TextFrame->AppendText(wxString::Format(wxT("setting ram read mode to 3...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("trigger0")) { trigger_fiber_transfer(1); TextFrame->AppendText(wxString::Format(wxT("triggering fiber channel 0...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("trigger1")) { trigger_fiber_transfer(2); TextFrame->AppendText(wxString::Format(wxT("triggering fiber channel 1...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("trigger2")) { trigger_fiber_transfer(4); TextFrame->AppendText(wxString::Format(wxT("triggering fiber channel 2...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("trigger3")) { trigger_fiber_transfer(8); TextFrame->AppendText(wxString::Format(wxT("triggering fiber channel 3...\n"))); wxYield(); } else if(Commandline->GetValue() == wxT("run")) { TextFrame->AppendText(wxString::Format(wxT("running...\n"))); wxYield(); set_ram_read_mode(2); set_ram_write_mode(2); wxYield(); LOAD_RAM_DATA(6); LOAD_PATTERN(); SOFT_TRIG(); trigger_chipscope(); wxYield(); set_ram_read_mode(1); set_ram_write_mode(0); wxYield(); // trigger_fiber_transfer(8); // trigger_fiber_transfer(1); trigger_fiber_transfer(4); // trigger_fiber_transfer(0); // turn it back off wxYield(); set_ram_read_mode(2); set_ram_write_mode(2); wxYield(); SOFT_TRIG(); wxYield(); Read(true); wxYield(); TextFrame->AppendText(wxString::Format(wxT("done\n"))); wxYield(); } else { Send(); } }
ConfigManagerContainer::IntToStringMap ConfigManager::ReadISMap(const wxString& name) { ConfigManagerContainer::IntToStringMap ret; Read(name, &ret); return ret; }
bool CMgProxySocket::DoV4Connect( const char* server , int port ) { //resolv ip locally /* +----+----+----+----+----+----+----+----+----+----+....+----+ | VN | CD | DSTPORT | DSTIP | USERID |NULL| +----+----+----+----+----+----+----+----+----+----+....+----+ bytes: 1 1 2 4 variable 1 +----+----+----+----+----+----+----+----+ | VN | CD | DSTPORT | DSTIP | +----+----+----+----+----+----+----+----+ bytes: 1 1 2 4 VN is the version of the reply code and should be 0. CD is the result code with one of the following values: 90: request granted 91: request rejected or failed 92: request rejected becasue SOCKS server cannot connect to identd on the client 93: request rejected because the client program and identd report different user-ids. */ unsigned char buf[ 256 ]; struct hostent *hp; hp = gethostbyname( server ); if ( !hp ) { m_nLastError = 0x02; //?? return false; } if ( hp->h_addrtype != AF_INET ) { //neither AF_INET nor AF_INET6 m_nLastError = 0x03; //?? return false; } short iport = htons( ( short ) port ); buf[ 0 ] = 0x04; buf[ 1 ] = 0x01; memcpy( buf + 2, &iport, 2 ); memcpy( buf + 4, ( void* ) ( hp->h_addr ), 4 ); memcpy( buf + 8, m_ProxyUser.c_str(), m_ProxyUser.length() ); buf[ 8 + m_ProxyUser.length() ] = 0; if ( !Send( buf, 8 + m_ProxyUser.length() + 1 ) ) { return false; } int nret = Read( buf, 256 ); if ( nret != 8 ) { return false; } if ( buf[ 0 ] != 0 ) { return false; } if ( buf[ 1 ] == 90 ) { return true; } else if ( buf[ 1 ] == 91 ) { return false; } else if ( buf[ 1 ] == 92 ) { return false; } else if ( buf[ 1 ] == 93 ) { return false; } return false; }
ConfigManagerContainer::StringSet ConfigManager::ReadSSet(const wxString& name) { ConfigManagerContainer::StringSet ret; Read(name, &ret); return ret; }
/* This is sufficiently different from the TCP code (wrt SSL, etc) that it * resides in its own simpler function */ static int ncat_listen_dgram(int proto) { struct { int fd; union sockaddr_u addr; } sockfd[NUM_LISTEN_ADDRS]; int i, fdn = -1; int fdmax, nbytes, n, fds_ready; char buf[DEFAULT_UDP_BUF_LEN] = { 0 }; char *tempbuf = NULL; fd_set read_fds; union sockaddr_u remotess; socklen_t sslen = sizeof(remotess.storage); struct timeval tv; struct timeval *tvp = NULL; unsigned int num_sockets; for (i = 0; i < NUM_LISTEN_ADDRS; i++) { sockfd[i].fd = -1; sockfd[i].addr.storage.ss_family = AF_UNSPEC; } FD_ZERO(&read_fds); /* Initialize remotess struct so recvfrom() doesn't hit the fan.. */ zmem(&remotess.storage, sizeof(remotess.storage)); remotess.storage.ss_family = o.af; #ifdef WIN32 set_pseudo_sigchld_handler(decrease_conn_count); #else /* Reap on SIGCHLD */ Signal(SIGCHLD, sigchld_handler); /* Ignore the SIGPIPE that occurs when a client disconnects suddenly and we send data to it before noticing. */ Signal(SIGPIPE, SIG_IGN); #endif /* set for selecting udp listening sockets */ fd_set listen_fds; fd_list_t listen_fdlist; FD_ZERO(&listen_fds); init_fdlist(&listen_fdlist, num_listenaddrs); num_sockets = 0; for (i = 0; i < num_listenaddrs; i++) { /* create the UDP listen sockets */ sockfd[num_sockets].fd = do_listen(SOCK_DGRAM, proto, &listenaddrs[i]); if (sockfd[num_sockets].fd == -1) { if (o.debug > 0) logdebug("do_listen(\"%s\"): %s\n", inet_ntop_ez(&listenaddrs[i].storage, sizeof(listenaddrs[i].storage)), socket_strerror(socket_errno())); continue; } FD_SET(sockfd[num_sockets].fd, &listen_fds); add_fd(&listen_fdlist, sockfd[num_sockets].fd); sockfd[num_sockets].addr = listenaddrs[i]; num_sockets++; } if (num_sockets == 0) { if (num_listenaddrs == 1) bye("Unable to open listening socket on %s: %s", inet_ntop_ez(&listenaddrs[0].storage, sizeof(listenaddrs[0].storage)), socket_strerror(socket_errno())); else bye("Unable to open any listening sockets."); } if (o.idletimeout > 0) tvp = &tv; while (1) { int i, j, conn_count, socket_n; if (fdn != -1) { /*remove socket descriptor which is burnt */ FD_CLR(sockfd[fdn].fd, &listen_fds); rm_fd(&listen_fdlist, sockfd[fdn].fd); /* Rebuild the udp socket which got burnt */ sockfd[fdn].fd = do_listen(SOCK_DGRAM, proto, &sockfd[fdn].addr); if (sockfd[fdn].fd == -1) bye("do_listen: %s", socket_strerror(socket_errno())); FD_SET(sockfd[fdn].fd, &listen_fds); add_fd(&listen_fdlist, sockfd[fdn].fd); } fdn = -1; socket_n = -1; fd_set fds; FD_ZERO(&fds); while (1) { /* * We just select to get a list of sockets which we can talk to */ if (o.debug > 1) logdebug("selecting, fdmax %d\n", listen_fdlist.fdmax); fds = listen_fds; if (o.idletimeout > 0) ms_to_timeval(tvp, o.idletimeout); fds_ready = fselect(listen_fdlist.fdmax + 1, &fds, NULL, NULL, tvp); if (o.debug > 1) logdebug("select returned %d fds ready\n", fds_ready); if (fds_ready == 0) bye("Idle timeout expired (%d ms).", o.idletimeout); /* * Figure out which listening socket got a connection. This loop should * really call a function for each ready socket instead of breaking on * the first one. */ for (i = 0; i <= listen_fdlist.fdmax && fds_ready > 0; i++) { /* Loop through descriptors until there is something ready */ if (!FD_ISSET(i, &fds)) continue; /* Check each listening socket */ for (j = 0; j < num_sockets; j++) { if (i == sockfd[j].fd) { if (o.debug > 1) logdebug("Valid descriptor %d \n", i); fdn = j; socket_n = i; break; } } /* if we found a valid socket break */ if (fdn != -1) { fds_ready--; break; } } /* Make sure someone connected */ if (fdn == -1) continue; /* * We just peek so we can get the client connection details without * removing anything from the queue. Sigh. */ nbytes = recvfrom(socket_n, buf, sizeof(buf), MSG_PEEK, &remotess.sockaddr, &sslen); if (nbytes < 0) { loguser("%s.\n", socket_strerror(socket_errno())); close(socket_n); return 1; } /* Check conditions that might cause us to deny the connection. */ conn_count = get_conn_count(); if (conn_count >= o.conn_limit) { if (o.verbose) loguser("New connection denied: connection limit reached (%d)\n", conn_count); } else if (!allow_access(&remotess)) { if (o.verbose) loguser("New connection denied: not allowed\n"); } else { /* Good to go. */ break; } /* Dump the current datagram */ nbytes = recv(socket_n, buf, sizeof(buf), 0); if (nbytes < 0) { loguser("%s.\n", socket_strerror(socket_errno())); close(socket_n); return 1; } ncat_log_recv(buf, nbytes); } if (o.debug > 1) logdebug("Valid Connection from %d\n", socket_n); conn_inc++; /* * We're using connected udp. This has the down side of only * being able to handle one udp client at a time */ Connect(socket_n, &remotess.sockaddr, sslen); /* clean slate for buf */ zmem(buf, sizeof(buf)); /* are we executing a command? then do it */ if (o.cmdexec) { struct fdinfo info = { 0 }; info.fd = socket_n; if (o.keepopen) netrun(&info, o.cmdexec); else netexec(&info, o.cmdexec); continue; } FD_SET(socket_n, &read_fds); FD_SET(STDIN_FILENO, &read_fds); fdmax = socket_n; /* stdin -> socket and socket -> stdout */ while (1) { fd_set fds; fds = read_fds; if (o.debug > 1) logdebug("udp select'ing\n"); if (o.idletimeout > 0) ms_to_timeval(tvp, o.idletimeout); fds_ready = fselect(fdmax + 1, &fds, NULL, NULL, tvp); if (fds_ready == 0) bye("Idle timeout expired (%d ms).", o.idletimeout); if (FD_ISSET(STDIN_FILENO, &fds)) { nbytes = Read(STDIN_FILENO, buf, sizeof(buf)); if (nbytes < 0) { loguser("%s.\n", strerror(errno)); return 1; } else if (nbytes == 0) { return 0; } if (o.crlf) fix_line_endings((char *) buf, &nbytes, &tempbuf, &crlf_state); if (!o.recvonly) { if (tempbuf != NULL) n = send(socket_n, tempbuf, nbytes, 0); else n = send(socket_n, buf, nbytes, 0); if (n < nbytes) { loguser("%s.\n", socket_strerror(socket_errno())); close(socket_n); return 1; } ncat_log_send(buf, nbytes); } if (tempbuf != NULL) { free(tempbuf); tempbuf = NULL; } } if (FD_ISSET(socket_n, &fds)) { nbytes = recv(socket_n, buf, sizeof(buf), 0); if (nbytes < 0) { loguser("%s.\n", socket_strerror(socket_errno())); close(socket_n); return 1; } ncat_log_recv(buf, nbytes); if (!o.sendonly) Write(STDOUT_FILENO, buf, nbytes); } zmem(buf, sizeof(buf)); } } return 0; }
int main() { char *message = NULL; /*Déclaration et initialisation d'un pointeur message qui contiendra les messages envoyé par le serveur*/ /*Connexion entre le client et le serveur*/ if(Initialisation("localhost") != 1) { printf("Erreur d'initialisation\n"); return 1; } /*________________________________________Notre Partie__________________________________________*/ system("clear"); /*On efface le terminal pour un affichage plus clair*/ /*Déclaration et initialisation des variables*/ int choix = 0; /*Contiendra le choix de l'utilisateur pour les menus*/ int retourAuthentification = 1; /*Contiendra le retour de la fonction authentification*/ int retourDisconnect = 1; /*Contiendra le retour de la fonction Disconnect*/ int retourConsult = 1; /*Contiendra le retour de la fonction Consult*/ int retourDelete = 1; /*Contiendra le retour de la fonction Delete*/ int retourInbox = 1; /*Contiendra le retour de la fonction Inbox*/ int retourInbox_spy = 1; int retourRead = 1; /*Contiendra le retour de la fonction Read*/ int retourSend = 1; /*Contiendra le retour de la fonction Send*/ /*Boucle pour l'authentification du client*/ do { system("clear"); Menu_Authentification(); /*Affichage du menu de connexion*/ choix = Choix(); /*Recupération du choix de l'utilisateur que l'on stocke dans la variable choix*/ system("clear"); /*Boucle pour le choix de la fonction*/ switch (choix) { case 1: /*Connexion au serveur*/ retourAuthentification = Authentification(); break; case 2: /*Deconnexion*/ retourDisconnect = Disconnect(); if (retourDisconnect == 0) { /*Si il choisit la déconnexion, cela retourne 0 donc on sort de la boucle*/ return 0; } break; default : /*Si choix n'est ni 1, ni 2, affiche un message d'erreur et recommence la boucle*/ printf("Veuillez renseignez un choix valide.\n"); FreeBuffer(); system("sleep 3"); } system("clear"); printf("Chargement en cours, veuillez patientez.\n"); system("sleep 1"); } while(retourDisconnect != 0 && retourAuthentification != 0); /*On refait cette boucle tant que la fonction Disconnect retourne 1, c'est à dire que l'utilisateur veuille revenir au menu précedent et tant que l'authentification se passe mal.*/ /*Boucle principale pour l'éxecution de toutes les fonctions*/ if (retourAuthentification != 1) { /*On rentre dans la boucle que si l'authentification est correcte*/ do { system("clear"); Menu_Principal(); /*Affichage du menu de principal*/ choix = Choix(); /*Recupération du choix de l'utilisateur que l'on stocke dans la variable choix*/ system("clear"); switch (choix) { case 1: /*Appel de la fonction Lecture d'un mail*/ retourInbox = 0; retourInbox_spy = Inbox_spy(); retourConsult = Consult(retourInbox_spy); if (RetourMenuPrecedent() == 0) { /*Une fois la fonction est fini correctement, on execute la fonction RetourMenuPrincipal*/ break; } case 2: /*Appel de la fonction Lecture d'un mail*/ retourRead = Read(); if (RetourMenuPrecedent() == 0) { /*Une fois la fonction est fini correctement, on execute la fonction RetourMenuPrincipal*/ break; } case 3: /*Appel de la fonction Suppression d'un message*/ retourDelete = Delete(); if (RetourMenuPrecedent() == 0) { /*Une fois la fonction est fini correctement, on execute la fonction RetourMenuPrincipal*/ break; } case 4: /*Appel de la fonction Ecriture d'un message*/ retourSend = Send(); if (RetourMenuPrecedent_2() == 0) { /*Une fois la fonction est fini correctement, on execute la fonction RetourMenuPrincipal*/ break; } case 5: /*Appel de la fonction Nombre de messages*/ retourInbox = Inbox(); if (RetourMenuPrecedent() == 0) { /*Une fois la fonction est fini correctement, on execute la fonction RetourMenuPrincipal*/ break; } case 6: /*Appel de la fonction Déconnexion*/ retourDisconnect = Disconnect(); if (retourDisconnect == 0) { /*Si Deconnexion se passe bien, on retourne 0 pour sortir de la boucle*/ return 0; } break; default: /*Si choix différent de ceux-ci dessus, affiche un message d'erreur et recommence la boucle*/ printf("Veuillez renseignez un choix valide.\n"); FreeBuffer(); system("sleep 3"); } system("clear"); printf("Chargement en cours, veuillez patientez.\n"); system("sleep 1"); } while(retourDisconnect != 0); /*On sort pas de cette boucle tant que l'utilisateur ne choisit pas déconnexion et confirme la déconnexion ainsi la fonction Déconnxion retourne 1*/ } return 0; }
bool CGPIBDevice::Query(CString strWrite, int &nLen, CString &strRead, int nTimeout) { return Write(strWrite) && Read(strRead, nLen, nTimeout); }
int main(int argc, char **argv) { int fd; int n; struct fd_set* rset; int done=0; char buf[BUFFER_SIZE]; struct addrinfo *host, *buffer, hints; int error; rset = (struct fd_set *)malloc(sizeof(struct fd_set)); memset(&hints,0,sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = 0; hints.ai_protocol = IPPROTO_TCP; error = getaddrinfo(argv[1],argv[2],&hints,&host); if(error!=0){ fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error)); exit(EXIT_FAILURE); } for(buffer = host; buffer != NULL; buffer = buffer->ai_next){ fd = socket(buffer->ai_family, buffer->ai_socktype, buffer->ai_protocol); if(fd == -1){ continue; } error = connect(fd, buffer->ai_addr, buffer->ai_addrlen); if(error == 0){ break; } Close(fd); } if(buffer == NULL){ printf("Kein Zielhost gefunden!\n"); exit(EXIT_FAILURE); } printf("Connected\n"); memset((void *) buf, '\0', sizeof(buf)); FD_ZERO(rset); while(!done){ FD_SET(0, rset); FD_SET(fd, rset); Select(fd +1, rset, (fd_set *) NULL, (fd_set *) NULL, (struct timeval *) NULL); if(FD_ISSET(0, rset)) { n = Read(0, (void *) buf, sizeof (buf)); if(n==0) Shutdown(fd, SHUT_WR); else Send(fd, (void *) buf, (size_t) n, 0); } if(FD_ISSET(fd, rset)){ n =Recv(fd, (void *) buf, sizeof(buf), 0); if(n==0) done = 1; else Write(1, buf, n); } } close(fd); free(rset); return(0); }
inline Read ReadCollection :: getRead ( const String & readId ) const throw ( ErrorMsg ) { return Read ( ( ReadRef ) self -> getRead ( readId . c_str () ) ); }
unsigned Socket::Read(char* buf, unsigned nbrBytes, bool removeFromCache /* = true*/) { return Read(buf, nbrBytes, 0, removeFromCache); }