//o---------------------------------------------------------------------------o //| Function : void completeTrade( CItem *tradeWindowOne, CItem *tradeWindowTwo, bool tradeSuccess ) //| Date : February 2, 2006 //| Programmer : giwo //o---------------------------------------------------------------------------o //| Purpose : Handles everything necesarry to complete a trade //o---------------------------------------------------------------------------o void completeTrade( CItem *tradeWindowOne, CItem *tradeWindowTwo, bool tradeSuccess ) { CChar *p1 = FindItemOwner( tradeWindowOne ); CChar *p2 = FindItemOwner( tradeWindowTwo ); if( !ValidateObject( p1 ) || !ValidateObject( p2 ) ) return; CSocket *mSock = p1->GetSocket(); if( mSock != NULL ) { CPSecureTrading cpstOne( (*tradeWindowOne) ); cpstOne.Action( 1 ); mSock->Send( &cpstOne ); } CSocket *nSock = p2->GetSocket(); if( nSock != NULL ) { CPSecureTrading cpstTwo( (*tradeWindowTwo) ); cpstTwo.Action( 1 ); nSock->Send( &cpstTwo ); } CItem *i = NULL; CItem *bp1 = p1->GetPackItem(); CItem *bp2 = p2->GetPackItem(); if( ValidateObject( bp1 ) && ValidateObject( bp2 ) ) { CDataList< CItem * > *c1Cont = tradeWindowOne->GetContainsList(); for( i = c1Cont->First(); !c1Cont->Finished(); i = c1Cont->Next() ) { if( ValidateObject( i ) ) { if( tradeSuccess ) i->SetCont( bp2 ); else i->SetCont( bp1 ); i->PlaceInPack(); } } CDataList< CItem * > *c2Cont = tradeWindowTwo->GetContainsList(); for( i = c2Cont->First(); !c2Cont->Finished(); i = c2Cont->Next() ) { if( ValidateObject( i ) ) { if( tradeSuccess ) i->SetCont( bp1 ); else i->SetCont( bp2 ); i->PlaceInPack(); } } } tradeWindowOne->Delete(); tradeWindowTwo->Delete(); }
void CTcpClientDlg::OnGetSource() { CSocket s; if(!s.Create()) { AfxMessageBox("소켓 생성 실패"); return; } if(!s.Connect("www.google.com", 80)) { AfxMessageBox("접속 실패!"); return ; } //GET 명령으로 데이터를 얻어옴 //GET 명령 형식 : GET 대상URL HTTP/1.0 <enter><enter> char * cmd = "GET / HTTP/1.0\r\n\r\n"; s.Send(cmd, strlen(cmd)); char buf[100]; ZeroMemory(buf, 100); while(s.Receive(buf, 1000)) { AfxMessageBox(buf); ZeroMemory(buf, 1000); } }
int main(int argc, char* argv[]){ CSocket csocket; cout<<"Input The Server IP: "; cin>>serverIp; bool connect=csocket.Connect(serverIp,serverPort); csocket.SetBlocking(false); if(connect) { csocket.printTime();cout<<"connected"<<endl; uintptr_t threadId=_beginthread(recv,0,&csocket);//启动一个线程接收数据的线程 while(1) { char buf[BUF_LEN]; cin>>buf; csocket.Send(buf,strlen(buf)); if(csocket.IsExit()) { csocket.Close(); cout<<"exit success"<<endl; break; } } }else {
//o---------------------------------------------------------------------------o //| Function : CItem *startTrade( CSocket *mSock, CChar *nChar ) //| Date : February 2, 2006 //| Programmer : giwo //o---------------------------------------------------------------------------o //| Purpose : Handles everything necesarry to start a secure trade //o---------------------------------------------------------------------------o CItem *startTrade( CSocket *mSock, CChar *nChar ) { if( mSock == NULL || !ValidateObject( nChar ) ) return NULL; CChar *mChar = mSock->CurrcharObj(); CSocket *nSock = nChar->GetSocket(); if( !ValidateObject( mChar ) || nSock == NULL ) return NULL; CItem *tradeWindowOne = CreateTradeWindow( mSock, nSock, mChar ); if( !ValidateObject( tradeWindowOne ) ) return NULL; CItem *tradeWindowTwo = CreateTradeWindow( nSock, mSock, nChar ); if( !ValidateObject( tradeWindowTwo ) ) { tradeWindowOne->Delete(); return NULL; } const SERIAL tw1Serial = tradeWindowOne->GetSerial(); const SERIAL tw2Serial = tradeWindowTwo->GetSerial(); tradeWindowOne->SetTempVar( CITV_MOREX, tw2Serial ); tradeWindowTwo->SetTempVar( CITV_MOREX, tw1Serial ); CPSecureTrading cpstOne( (*nChar), tw1Serial, tw2Serial ); cpstOne.Name( nChar->GetName() ); mSock->Send( &cpstOne ); CPSecureTrading cpstTwo( (*mChar), tw2Serial, tw1Serial ); cpstTwo.Name( mChar->GetName() ); nSock->Send( &cpstTwo ); CPWornItem toWear = (*tradeWindowOne); mSock->Send( &toWear ); nSock->Send( &toWear ); CPWornItem toWear2 = (*tradeWindowTwo); mSock->Send( &toWear2 ); nSock->Send( &toWear2 ); return tradeWindowOne; }
void OpenContact(char *s) { m_socket->Send("HTTP 200 OK\r\n\r\n"); int hContact; sscanf(s, "/fav/open/%d", &hContact); if (CallService(MS_DB_CONTACT_IS, hContact, 0)) CallServiceSync(MS_FAVCONTACTS_OPEN_CONTACT, (WPARAM)hContact, 0); }
void CNetworkTalkClientDlg::OnBtnSend() { // TODO: Add your control notification handler code here CSocket sockClient; sockClient.Create(); sockClient.Connect(m_serverIPAddress,8000); g_serverIPAddress=m_serverIPAddress; sockClient.Send(m_sendText,m_sendText.GetLength()); sockClient.Close(); }
uint32_t set_up_parameters(role_type role, uint32_t myneles, uint32_t* mybytelen, uint8_t** elements, uint8_t** pelements, CSocket& sock, crypto* crypt) { uint32_t pneles, nintersections, offset; //Exchange meta-information and equalize byte-length sock.Send(&myneles, sizeof(uint32_t)); sock.Receive(&pneles, sizeof(uint32_t)); if(role == SERVER) { sock.Send(mybytelen, sizeof(uint32_t)); } else { sock.Receive(mybytelen, sizeof(uint32_t)); } *elements = (uint8_t*) malloc(myneles * *mybytelen); *pelements = (uint8_t*) malloc(pneles * *mybytelen); crypt->gen_rnd(*elements, myneles * *mybytelen); //Exchange elements for later check if(role == SERVER) { sock.Send(*elements, myneles * *mybytelen); sock.Receive(*pelements, pneles * *mybytelen); } else { //have the client use some of the servers values s.t. the intersection is not disjoint sock.Receive(*pelements, pneles * *mybytelen); nintersections = rand() % min(myneles, pneles); offset = myneles / nintersections; for(uint32_t i = 0; i < nintersections; i++) { memcpy(*elements + i * offset * *mybytelen, *pelements + i * *mybytelen, *mybytelen); } sock.Send(*elements, myneles * *mybytelen); } return pneles; }
int main(int argc, char* argv[]){ CSocket csocket; CPacket packet; int Command; char* sendMessage = new char[BUF_LEN]; parse_arguments(argc, argv); if (!s_serverPort) { cout<<"! The server port number is not defined."<<endl; usage(argv[0]); return 1; } if (!s_serverIP) { cout<<"! The server ip address is not defined"<<endl; usage(argv[0]); return 1; } bool connect=csocket.Connect(s_serverIP,s_serverPort); csocket.SetBlocking(false);//设置阻塞模式 //on_login_reply(!connect); if(connect) { cout<<"Connect the server success,please login."<<endl; show_prompt(); uintptr_t threadId=_beginthread(recv,0,&csocket);//启动一个线程接收数据的线程 while(1) { char buf[BUF_LEN]; cin>>buf; if (Command = packet.paseArguement(buf)) { memset(sendMessage, 0, 1024); sendMessage = packet.getCommand(Command); } show_prompt(); csocket.Send(sendMessage,sizeof(buf)); //csocket.Receive(64); if(csocket.IsExit()) { csocket.Close(); cout<<"exit success"<<endl; break; } } } else {
void SendList() { TFavContacts favList; favList.build(); m_socket->Send( "HTTP 200 OK\r\n" "Content-Type: text/javascript\r\n" "\r\n"); Send("try {\r\n"); Send("SetContactCount("); Send(favList.getCount()); Send(");\r\n"); for (int i = 0; i < favList.getCount(); ++i) { HANDLE hContact = favList[i]->getHandle(); TCHAR *name = (TCHAR *)CallService(MS_CLIST_GETCONTACTDISPLAYNAME, (WPARAM)hContact, GCDNF_TCHAR); AVATARCACHEENTRY *avatar = (AVATARCACHEENTRY *)CallService(MS_AV_GETAVATARBITMAP, (WPARAM)hContact, 0); int status = db_get_w(hContact, GetContactProto(hContact), "Status", ID_STATUS_OFFLINE); Send("SetContact("); Send(i); Send(", "); Send((int)hContact); Send(", '"); SendQuoted(name); Send("', "); Send(status); Send(", '"); SendQuoted(avatar ? avatar->szFilename : _T("")); Send("');\r\n"); } Send("} catch(e) {}\r\n"); }
void SendList() { TFavContacts favList; favList.build(); m_socket->Send( "HTTP 200 OK\r\n" "Content-Type: text/javascript\r\n" "\r\n"); Send("try {\r\n"); Send("SetContactCount("); Send(favList.getCount()); Send(");\r\n"); for (int i = 0; i < favList.getCount(); ++i) { MCONTACT hContact = favList[i]->getHandle(); TCHAR *name = (TCHAR *)pcli->pfnGetContactDisplayName(hContact, 0); AVATARCACHEENTRY *avatar = (AVATARCACHEENTRY *)CallService(MS_AV_GETAVATARBITMAP, hContact, 0); int status = db_get_w(hContact, GetContactProto(hContact), "Status", ID_STATUS_OFFLINE); Send("SetContact("); Send(i); Send(", "); Send((int)hContact);// XXX: x64 broken!? Send(", '"); SendQuoted(name); Send("', "); Send(status); Send(", '"); SendQuoted(avatar ? avatar->szFilename : _T("")); Send("');\r\n"); } Send("} catch(e) {}\r\n"); }
int CPayment::SendPaymentData(LPCTSTR sfxm,LONG Money,LPCTSTR bz) { bool bIsStand = true; szPayState = "3";//请求正在处理 //组包 CIso8583Package *package = new CIso8583Package(); if (package == NULL) { szPayState = "E7"; return -1; //不成功,返回错误码 } char c48Field[255]; memset(c48Field,0,sizeof(c48Field)); if( strcmp(sfxm,"3001") == 0) { bIsStand = false; const char *split = "|"; char *pTemp = new char[128]; strcpy(pTemp,bz); char *pToken = strtok (pTemp,split); if( pToken == NULL ) return -1; int nOffset = strlen(pToken); memcpy(c48Field,pToken,strlen(pToken)); pToken = strtok(NULL,"|"); if( pToken == NULL ) return -1; memcpy(c48Field + nOffset,pToken,strlen(pToken)); nOffset += strlen(pToken); pToken = strtok(NULL,"|"); if( pToken == NULL ) return -1; memcpy(c48Field + nOffset,pToken,strlen(pToken)); nOffset += strlen(pToken); pToken = strtok(NULL,"|"); if( pToken == NULL ) return -1; memcpy(c48Field + nOffset,pToken,strlen(pToken)); nOffset += strlen(pToken); package->SetFieldData(48,nOffset,(BYTE *)c48Field);//48域,目前随便填写,银联无法处理该业务 } else {//处理其他收费项目 int nOffset = 0; nOffset = strlen(sfxm); memcpy(c48Field,sfxm,nOffset); memcpy(c48Field + nOffset,bz,strlen(bz)); nOffset += strlen(bz); package->SetFieldData(48,nOffset,(BYTE *)c48Field);//48域,目前随便填写,银联无法处理该业务 } int iRes = BuildPackage(package,Money); if (iRes != 0) { szPayState = "E7"; return iRes; //组包不成功,返回错误码 } BYTE cHeader[30]; int nOffset = 0; AscToBcd(cHeader + nOffset,(unsigned char *)szTPDU.GetBuffer(),szTPDU.GetLength()); nOffset += szTPDU.GetLength() / 2; AscToBcd(cHeader + nOffset,(unsigned char *)szHeader.GetBuffer(),szHeader.GetLength()); nOffset += szHeader.GetLength() / 2; cHeader[nOffset] = 0x02; nOffset += 1; cHeader[nOffset] = 0x00; nOffset += 1; BYTE cData[512]; memset(cData,0,512); unsigned int nLen = package->GetData(cData,512,cHeader,nOffset,false); delete package; char cLen[5] = {'\0'}; itoa_hex(nLen,cLen,2); unsigned char cDataLen[3] = {'\0'}; AscToBcd(cDataLen,(unsigned char *)cLen,4); BYTE cPackageData[512]; memset(cPackageData,0,sizeof(cPackageData)); memcpy(cPackageData,cDataLen,2); memcpy(cPackageData + 2,cData,nLen); TCHAR szCurPath[MAX_PATH]; GetCurrentDirectory(sizeof(szCurPath),szCurPath); _tcscat(szCurPath,TEXT("\\Reversal.ini")); CSocket client; if( client.InitSocket() == FALSE) { szPayState = "E7"; return -1; } if( client.Connect(szServerIP,atoi(szPort)) == false) { szPayState = "E7"; return -1; } gLog.Log(cPackageData,nLen + 2); client.Send(cPackageData,nLen + 2); BYTE RecvData[1024]; memset(RecvData,0,1024); nLen = client.Receive(RecvData,1024); if(nLen != 0) { gLog.Log(RecvData,nLen); CIso8583Parse *receivePackage = new CIso8583Parse(); char cResult[128]; memset(cResult,0,128); Read8583Package(receivePackage,RecvData,39,2,(BYTE *)cResult); delete receivePackage; LONG lProCode = atol(szTraceCode.GetBuffer()) + 1; unsigned char cAsciiBuff[12]; memset(cAsciiBuff,0,sizeof(cAsciiBuff)); BinToAsc(cAsciiBuff,lProCode,6); WritePrivateProfileString(TEXT("TraceCode"),TEXT("TraceCode"),(char *)cAsciiBuff,szCurPath); if(strcmp(cResult,"A0") == 0) //根据银联网络的说法,MAC错误也需要冲正 { WritePrivateProfileString(TEXT("Reversal"),TEXT("Ack"),"A0",szCurPath); WritePrivateProfileString(TEXT("Reversal"),TEXT("Flag"),"0",szCurPath);//0 -- 未处理 CReversalTransaction transaction; transaction.SendReversalTransactionData();//冲正处理 } else if( strcmp(cResult,"05") == 0) {//认证失败 szPayState = "E2"; return -1; } else if( strcmp(cResult,"51") == 0) { szPayState = "E5"; return -1; } else if( strcmp(cResult, "55") == 0) { szPayState = "E2"; return -1; } else if( strcmp(cResult, "75") == 0) { szPayState = "E1"; return -1; } szPayState = "1";//交易成功 } else {//网络原因,消费冲正 szPayState = "E6"; WritePrivateProfileString(TEXT("Reversal"),TEXT("Ack"),"98",szCurPath);//POS终端在时限内未能收到POS中心的应答消息而引发 WritePrivateProfileString(TEXT("Reversal"),TEXT("Flag"),"0",szCurPath);//0 -- 未处理 CReversalTransaction transaction; transaction.SendReversalTransactionData();//冲正处理 } return 1;//交易成功 }
void Send(WCHAR *ws) { char *s = mir_utf8encodeW(ws); m_socket->Send(s); mir_free(s); }
void Send(char *s) { m_socket->Send(s); }
int CReversalTransaction::SendReversalTransactionData(char *pAccount,LONG Money,char *cTraceCode,char *cAck) { //组包 CIso8583Package *package = new CIso8583Package(); int iRes = BuildPackage(package,pAccount,Money,cTraceCode,cAck); if (iRes != 0) return iRes; //组包不成功,返回错误码 BYTE cHeader[30]; int nOffset = 0; AscToBcd(cHeader + nOffset,(unsigned char *)szTPDU.GetBuffer(),szTPDU.GetLength()); nOffset += szTPDU.GetLength() / 2; AscToBcd(cHeader + nOffset,(unsigned char *)szHeader.GetBuffer(),szHeader.GetLength()); nOffset += szHeader.GetLength() / 2; cHeader[nOffset] = 0x04; nOffset += 1; cHeader[nOffset] = 0x00; nOffset += 1; BYTE cData[512]; memset(cData,0,512); unsigned int nLen = package->GetData(cData,512,cHeader,nOffset,false); delete package; char cLen[5] = {'\0'}; itoa_hex(nLen,cLen,2); unsigned char cDataLen[3] = {'\0'}; AscToBcd(cDataLen,(unsigned char *)cLen,4); BYTE cPackageData[512]; memset(cPackageData,0,sizeof(cPackageData)); memcpy(cPackageData,cDataLen,2); memcpy(cPackageData + 2,cData,nLen); CSocket client; if( client.InitSocket() == FALSE) return -1; if( client.Connect(szServerIP,atoi(szPort)) == false) return -1; gLog.Log(cData,nLen); client.Send(cData,nLen); BYTE RecvData[1024]; memset(RecvData,0,1024); nLen = client.Receive(RecvData,1024); if(nLen != 0) { gLog.Log(RecvData,nLen); CIso8583Parse *receivePackage = new CIso8583Parse(); char cResult[128]; memset(cResult,0,128); Read8583Package(receivePackage,RecvData,39,2,(BYTE *)cResult); delete receivePackage; if(strcmp(cResult,"00") == 0) { TCHAR szCurPath[MAX_PATH]; GetCurrentDirectory(sizeof(szCurPath),szCurPath); _tcscat(szCurPath,TEXT("\\Reversal.ini")); WritePrivateProfileString(TEXT("Reversal"),TEXT("Account"),"",szCurPath); WritePrivateProfileString(TEXT("Reversal"),TEXT("TraceCode"),"",szCurPath); WritePrivateProfileString(TEXT("Reversal"),TEXT("Money"),"",szCurPath); WritePrivateProfileString(TEXT("Reversal"),TEXT("Ack"),"",szCurPath); WritePrivateProfileString(TEXT("Reversal"),TEXT("Flag"),"1",szCurPath);//1 -- 已处理 } } return 1; }
void CIPServer::OnAccept(int nErrorCode) { CCardSwipeServiceApp* pApp = (CCardSwipeServiceApp*)AfxGetApp(); CSocket newSocket; SOCKADDR saddr; char ch[96]; CString sAddress; CString sIPAddress, sError; long nCardReaderId = -1; int iReturn; this->Accept(newSocket); memset(&saddr,0,sizeof(SOCKADDR)); int iLen = sizeof(saddr); newSocket.GetSockName(&saddr,&iLen); // get dotted ip address lstrcpyA(ch,inet_ntoa(((SOCKADDR_IN*)&saddr)->sin_addr)); sIPAddress = ch; sAddress.Format("%s:%d",ch,((SOCKADDR_IN*)&saddr)->sin_port); // is this address in the database? OysterClassLibrary::IOysterPtr pOyster; OysterClassLibrary::ICardReaderPtr pCardReader; HRESULT hr = pOyster.CreateInstance(OysterClassLibrary::CLSID_Oyster); if (hr != ERROR_SUCCESS) { GetLastErrorString(sError,hr); throw CGeneralException("CIPServer::OnAccept","Could not create OysterClassLibrary object (%d): %s",hr,sError); } memset(ch,0,sizeof(ch)); iReturn = newSocket.Receive(ch,sizeof(ch)); if (iReturn <= 0) { // either closed or an error occured GetError(sError,iReturn); throw CGeneralException("CIPServer::OnAccept","Receive function failed (%d): %s",iReturn,sError); } nCardReaderId = (long)&ch[0]; pCardReader = pOyster->GetCardReaderById(nCardReaderId); if (pCardReader) { CVirtualCardReaderSocket* pNewSocket = new CVirtualCardReaderSocket(nCardReaderId); pNewSocket->Attach(newSocket.m_hSocket); newSocket.Detach(); pNewSocket->Send(ECMD_COMMANDSTRING[ECMD_CONNECTSUCCESS],strlen(ECMD_COMMANDSTRING[ECMD_CONNECTSUCCESS])); pApp->m_mapCardSwipeIdToCardSwipe pApp->m_vClients.push_back(pNewSocket); DebugTell(_T("New client connection from %s\n"),(LPCTSTR)sAddress); } else { // invalid connection, send notification newSocket.Send(ECMD_COMMANDSTRING[ECMD_ERRORCONNECT],strlen(ECMD_COMMANDSTRING[ECMD_ERRORCONNECT])); } pOyster.Release(); UNREFERENCED_PARAMETER(nErrorCode); CSocket::OnAccept(nErrorCode); }
void CServerHandshake::Run() { VERIFY(AfxSocketInit()); CSocket socket; // führen Handshake innerhalb des Threads synchron aus socket.Attach(m_hSocket); clock_t end = clock() + HANDSHAKE_TIMEOUT * CLOCKS_PER_SEC; // (1.) auf eingehenden Identifizierungs-String (HANDSHAKE_CLIENTID) + Versionsnummer // vom Client warten UINT nCount = strlen(HANDSHAKE_CLIENTID) + 1 + sizeof(UINT) + 1; if (!RequestData(socket, nCount, end)) { DEBUG_MSG("client timed out, disconnected"); SetExitCode(1); return; } // Daten in Puffer übertragen BYTE *lpBuf = new BYTE[nCount]; int nDone = socket.Receive(lpBuf, nCount); if (nDone == SOCKET_ERROR) goto sockerror; else if (nDone < nCount) goto error; // Pufferinhalt prüfen if (memcmp(lpBuf, HANDSHAKE_CLIENTID, strlen(HANDSHAKE_CLIENTID)) != 0 || lpBuf[strlen(HANDSHAKE_CLIENTID)] != 0 || lpBuf[nCount - 1] != 0) { DEBUG_MSG("client is not a BotE client, disconnected"); delete[] lpBuf; SetExitCode(1); return; } // Puffer erfolgreich geprüft, Versionsnummer extrahieren UINT nClientVersion; memcpy(&nClientVersion, lpBuf + (strlen(HANDSHAKE_CLIENTID) + 1), sizeof(UINT)); TRACE("server: client has version %u\n", nClientVersion); delete[] lpBuf; lpBuf = NULL; // abbrechen, wenn andere Versionsnummer if (nClientVersion != m_nServerVersion) { DEBUG_MSG("client has incompatible version, disconnected"); SetExitCode(1); return; } // (2.) Server-Identifizierung + Versionsnummer senden nDone = socket.Send(HANDSHAKE_SERVERID, strlen(HANDSHAKE_SERVERID)); if (nDone == SOCKET_ERROR) goto sockerror; else if (nDone < strlen(HANDSHAKE_SERVERID)) goto error; lpBuf = new BYTE[nCount = 1 + sizeof(UINT) + 1]; lpBuf[0] = lpBuf[nCount - 1] = 0; memcpy(&lpBuf[1], &m_nServerVersion, sizeof(UINT)); nDone = socket.Send(lpBuf, nCount); if (nDone == SOCKET_ERROR) goto sockerror; else if (nDone < nCount) goto error; delete[] lpBuf; lpBuf = NULL; // (3.a) Bestätigung vom Client abwarten int nLen = 3 + sizeof(UINT); if (!RequestData(socket, nLen, end)) { DEBUG_MSG("client timed out, disconnected"); SetExitCode(1); return; } // Bestätigung prüfen lpBuf = new BYTE[3]; nDone = socket.Receive(lpBuf, 3); if (nDone == SOCKET_ERROR) goto sockerror; else if (nDone < 3) goto error; if (memcmp(lpBuf, "OK\0", 3) != 0) { DEBUG_MSG("client did not confirm, disconnected"); delete[] lpBuf; SetExitCode(1); return; } delete[] lpBuf; // Länge des Benutzernamens ermitteln lpBuf = new BYTE[sizeof(UINT)]; nDone = socket.Receive(lpBuf, sizeof(UINT)); if (nDone == SOCKET_ERROR) goto sockerror; else if (nDone < sizeof(UINT)) goto error; UINT nStrLen = 0; memcpy(&nStrLen, lpBuf, sizeof(UINT)); delete[] lpBuf; // (3.b) Benutzername empfangen if (!RequestData(socket, nStrLen, end)) { DEBUG_MSG("client timed out, disconnected"); SetExitCode(1); return; } // Benutzername lesen lpBuf = new BYTE[nStrLen + 1]; nDone = socket.Receive(lpBuf, nStrLen); if (nDone == SOCKET_ERROR) goto sockerror; else if (nDone < nStrLen) goto error; { lpBuf[nStrLen] = 0; CString strUserName((char *)lpBuf); strUserName.Trim(); // dem Server einen neuen Client melden; verwenden kleinere Versionsnummer zur // Kommunikation server.OnNewClient(socket.Detach(), min(m_nServerVersion, nClientVersion), strUserName); } delete[] lpBuf; return; sockerror: server.OnSocketError(socket.GetLastError()); error: if (lpBuf) delete[] lpBuf; SetExitCode(1); }
boolean CDNSClient::Resolve (const char *pHostname, CIPAddress *pIPAddress) { assert (pHostname != 0); if ('1' <= *pHostname && *pHostname <= '9') { return FALSE; } assert (m_pNetSubSystem != 0); CIPAddress DNSServer (m_pNetSubSystem->GetConfig ()->GetDNSServer ()->Get ()); CSocket Socket (m_pNetSubSystem, IPPROTO_UDP); if (Socket.Connect (DNSServer, 53) != 0) { return FALSE; } u8 Buffer[DNS_MAX_MESSAGE_SIZE]; memset (Buffer, 0, sizeof Buffer); TDNSHeader *pDNSHeader = (TDNSHeader *) Buffer; u16 nXID = s_nXID++; pDNSHeader->nID = le2be16 (nXID); pDNSHeader->nFlags = BE (DNS_FLAGS_OPCODE_QUERY | DNS_FLAGS_RD); pDNSHeader->nQDCount = BE (1); u8 *pQuery = Buffer + sizeof (TDNSHeader); char Hostname[MAX_HOSTNAME_SIZE]; strncpy (Hostname, pHostname, MAX_HOSTNAME_SIZE-1); Hostname[MAX_HOSTNAME_SIZE-1] = '\0'; char *pSavePtr; size_t nLength; char *pLabel = strtok_r (Hostname, ".", &pSavePtr); while (pLabel != 0) { nLength = strlen (pLabel); if ( nLength > 255 || (int) (nLength+1+1) >= DNS_MAX_MESSAGE_SIZE-(pQuery-Buffer)) { return FALSE; } *pQuery++ = (u8) nLength; strcpy ((char *) pQuery, pLabel); pQuery += nLength; pLabel = strtok_r (0, ".", &pSavePtr); } *pQuery++ = '\0'; TDNSQueryTrailer QueryTrailer; QueryTrailer.nQType = BE (DNS_QTYPE_A); QueryTrailer.nQClass = BE (DNS_QCLASS_IN); if ((int) (sizeof QueryTrailer) > DNS_MAX_MESSAGE_SIZE-(pQuery-Buffer)) { return FALSE; } memcpy (pQuery, &QueryTrailer, sizeof QueryTrailer); pQuery += sizeof QueryTrailer; int nSize = pQuery - Buffer; assert (nSize <= DNS_MAX_MESSAGE_SIZE); unsigned char RecvBuffer[DNS_MAX_MESSAGE_SIZE]; int nRecvSize; unsigned nTry = 1; do { if ( nTry++ > 3 || Socket.Send (Buffer, nSize, 0) != nSize) { return FALSE; } CScheduler::Get ()->MsSleep (1000); nRecvSize = Socket.Receive (RecvBuffer, DNS_MAX_MESSAGE_SIZE, MSG_DONTWAIT); assert (nRecvSize < DNS_MAX_MESSAGE_SIZE); } while (nRecvSize < (int) (sizeof (TDNSHeader)+sizeof (TDNSResourceRecordTrailerAIN))); pDNSHeader = (TDNSHeader *) RecvBuffer; if ( pDNSHeader->nID != le2be16 (nXID) || (pDNSHeader->nFlags & BE ( DNS_FLAGS_QR | DNS_FLAGS_OPCODE | DNS_FLAGS_TC | DNS_FLAGS_RCODE)) != BE (DNS_FLAGS_QR | DNS_FLAGS_OPCODE_QUERY | DNS_RCODE_SUCCESS) || pDNSHeader->nQDCount != BE (1) || pDNSHeader->nANCount == BE (0)) { return FALSE; } u8 *pResponse = RecvBuffer + sizeof (TDNSHeader); // parse the query section while ((nLength = *pResponse++) > 0) { pResponse += nLength; if (pResponse-RecvBuffer >= nRecvSize) { return FALSE; } } pResponse += sizeof (TDNSQueryTrailer); if (pResponse-RecvBuffer >= nRecvSize) { return FALSE; } TDNSResourceRecordTrailerAIN RRTrailer; // parse the answer section while (1) { nLength = *pResponse++; if ((nLength & 0xC0) == 0xC0) // check for compression { pResponse++; } else { if (pResponse-RecvBuffer >= nRecvSize) { return FALSE; } while ((nLength = *pResponse++) > 0) { pResponse += nLength; if (pResponse-RecvBuffer >= nRecvSize) { return FALSE; } } } if (pResponse-RecvBuffer > (int) (nRecvSize-sizeof RRTrailer)) { return FALSE; } memcpy (&RRTrailer, pResponse, sizeof RRTrailer); if ( RRTrailer.nType == BE (DNS_QTYPE_A) && RRTrailer.nClass == BE (DNS_QCLASS_IN) && RRTrailer.nRDLength == BE (DNS_RDLENGTH_AIN)) { break; } pResponse += DNS_RR_TRAILER_HEADER_LENGTH + BE (RRTrailer.nRDLength); if (pResponse-RecvBuffer >= nRecvSize) { return FALSE; } } assert (pIPAddress != 0); pIPAddress->Set (RRTrailer.RData); return TRUE; }
unsigned CNTPClient::GetTime (CIPAddress &rServerIP) { assert (m_pNetSubSystem != 0); CSocket Socket (m_pNetSubSystem, IPPROTO_UDP); if (Socket.Connect (rServerIP, 123) != 0) { return 0; } u8 NTPPacket[NTP_PACKET_SIZE]; memset (NTPPacket, 0, sizeof NTPPacket); NTPPacket[0] = 0xE3; // leap indicator: unknown, version: 4, mode: client NTPPacket[1] = 0; // stratum: unspecified NTPPacket[2] = 10; // poll: 1024 seconds NTPPacket[3] = 0; // precision: 1 second memcpy (NTPPacket+12, "XCIR", 4); unsigned char RecvPacket[NTP_PACKET_SIZE]; unsigned nTry; for (nTry = 1; nTry <= 3; nTry++) { if (Socket.Send (NTPPacket, sizeof NTPPacket, 0) != sizeof NTPPacket) { CLogger::Get ()->Write (FromNTPClient, LogError, "Send failed"); return 0; } CScheduler::Get ()->MsSleep (1000); int nResult = Socket.Receive (RecvPacket, sizeof RecvPacket, MSG_DONTWAIT); if (nResult < 0) { CLogger::Get ()->Write (FromNTPClient, LogError, "Receive failed"); return 0; } if (nResult >= 44) { break; } } if (nTry > 3) { CLogger::Get ()->Write (FromNTPClient, LogError, "Invalid or no response"); return 0; } unsigned nSecondsSince1900; nSecondsSince1900 = (unsigned) RecvPacket[40] << 24 | (unsigned) RecvPacket[41] << 16 | (unsigned) RecvPacket[42] << 8 | (unsigned) RecvPacket[43]; if (nSecondsSince1900 < SEVENTY_YEARS) { return 0; } unsigned nTime = nSecondsSince1900 - SEVENTY_YEARS; return nTime; }