/** * Sdio test * \param iMci Controller number. */ static void SdioTest(uint8_t iMci) { sSdCard *pSd = &sdDrv[iMci]; uint32_t i; DumpSeperator(); /* SDIO always has FN1(IEN.1) and Mem(IEN.0), test with these bits */ printf("R/W Direct test:\n\r"); printf("CIA:\n\r"); SDIO_ReadDirect(pSd, SDIO_CIA, 0, &pBuffer[0], 0x14); DumpBuffer(pBuffer, 0x14); printf("Write 0x03 to IEN(CIA.4): rc %d\n\r", SDIO_WriteDirect(pSd, SDIO_CIA, SDIO_IEN_REG, 0x03)); printf("IEN After Write:"); SDIO_ReadDirect(pSd, SDIO_CIA, SDIO_IEN_REG, &pBuffer[1], 1); printf("0x%02X\n\r", pBuffer[1]); if (0x03 == pBuffer[1]) { printf("-- test OK\n\r"); } else { printf("-- test FAIL\n\r"); } SDIO_WriteDirect(pSd, SDIO_CIA, SDIO_IEN_REG, pBuffer[SDIO_IEN_REG]); printf("R/W Extended test:\n\r"); printf("Dump CIA:\n\r"); for (i = 0; i < 0x40; i ++) pBuffer[i] = 0xFF; /* Clear Buffer */ SDIO_ReadBytes(pSd, SDIO_CIA, 0, 0, pBuffer, 0x39, 0, 0); DumpBuffer(pBuffer, 0x14); #if 1 printf("Modify Some R/W bytes (2,4) for FN0 and write:\n\r"); pBuffer[0x2] = 0x2; /* IOE */ pBuffer[0x4] = 0x2; /* IEN */ /* Dont write to CIA.0x7, CIA.0xD or operation pause transfer */ SDIO_WriteBytes(pSd, SDIO_CIA, 2, 0, &pBuffer[2], 5/*(0xC-2)*/, 0, 0); printf("CIA after write:\n\r"); //SDIO_ReadDirect(pSd, SDIO_CIA, 0, pBuffer, 0x14); SDIO_ReadBytes(pSd, SDIO_CIA, 0, 0, pBuffer, 0x14, 0, 0); DumpBuffer(pBuffer, 0x14); if (pBuffer[0x2] != 0x2) { printf("-- CIA.2 Fail\n\r"); } else if (pBuffer[0x4] != 0x2) { printf("-- CIA.4 Fail\n\r"); } else { printf("-- test OK\n\r"); } /* Restore data to 0 */ SDIO_WriteDirect(pSd, SDIO_CIA, SDIO_IOE_REG, 0); SDIO_WriteDirect(pSd, SDIO_CIA, SDIO_IEN_REG, 0); #endif }
void SigCatch(int sig) { switch (sig) { case SIGQUIT: // We could print here... CTRL+4 DumpBuffer(); break; case SIGBUS: case SIGSEGV: printf("\nSYSTEM TERMINATION ..."); fflush(stdout); GoodBye(); exit(1); case SIGINT: case SIGHUP: case SIGTERM: // Ctrl+C DumpBuffer(); GoodBye(); exit(1); break; } }
void dumpSmbNtlmAuthResponse(FILE *fp, tSmbNtlmAuthResponse *response) { fprintf(fp,"NTLM Response:\n"); fprintf(fp," Ident = %s\n",response->ident); fprintf(fp," mType = %d\n",IVAL(&response->msgType,0)); fprintf(fp," LmResp = "); DumpBuffer(fp,response,lmResponse); fprintf(fp," NTResp = "); DumpBuffer(fp,response,ntResponse); fprintf(fp," Domain = %s\n",GetUnicodeString(response,uDomain)); fprintf(fp," User = %s\n",GetUnicodeString(response,uUser)); fprintf(fp," Wks = %s\n",GetUnicodeString(response,uWks)); fprintf(fp," sKey = "); DumpBuffer(fp, response,sessionKey); fprintf(fp," Flags = %08x\n",IVAL(&response->flags,0)); }
void Connection::SendResponse(short opcode, unsigned char *data, size_t length, long sequence_num) { //attempt to isolate why this crashes from time to time. *((short *) &m_SendBuffer[0]) = (short) length + sizeof(long); *((short *) &m_SendBuffer[2]) = opcode; if (length) { memcpy(m_SendBuffer + sizeof(long), data, length); } int bytes = length + sizeof(long); if (m_PacketLoggingEnabled) { LogMessage("Sending %d bytes (unencrypted)\n", bytes); DumpBuffer(m_SendBuffer, bytes); } //LogMessage("Sending opcode #%x: 0x%04x [%x]\n", sequence_num, opcode, length); /*if (m_ServerType != CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY) { m_CryptOut.RC4(m_SendBuffer, bytes); }*/ //send(m_Socket, (char *) m_SendBuffer, bytes, 0); Send(m_SendBuffer, bytes); }
static void test_read_data(int handle, int ntimes) { int readlen = -1; char readbuf[READSIZ]; int devarr[DEVARRSIZ]; int device = -1; int samplesize = -1; int nchan = -1; int ndev = -1; int i = 0, j=0; ndev = PasGetDevices(handle, devarr, DEVARRSIZ); if(ndev<0) { printf("test_read_data Error ndev = %d\n",ndev); return; } while(0<ntimes--) for(i=0; i < ndev ; i++) { printf("Reading one shot data from dev %d\n", i); device = devarr[i]; nchan = PasGetNumChannels(handle,device); for(j=0;j<nchan;j++) { printf("Reading one shot data from dev %d channel %d\n", i, j); if(1!=PasGetSensorDetected(handle,device,j)) continue; printf("Found sensor on channel\n"); samplesize = PasGetSampleSize(handle, device, j); printf("Device # %d, Channel %d, sample size: %d\n",device, j, samplesize); readbuf[0] = 0xFF; readlen = PasGetOneSample(handle, device, j,readbuf,READSIZ); if(readlen<0) { printf("Device # %d, Channel %d, error: %d \n",device,j,readlen); continue; } else { printf("Read %d bytes: ", readlen); DumpBuffer(readbuf,readlen); } } } printf("\n"); }
static int uplink( DEV *dev ) { u8 cmq, len, st; u8 *p; int idx; u32 cport, rport; dbg8("%s(): dev=%08X", __FUNCTION__, (uint)dev); cport = dev->cport; rport = dev->rport; HS; if( !NIN ) return 0; // Pass token HS; len = NIN; HS; cmq = NIN; if(cmq == 0xC0) return 1; // niACK received idx = dev->intail; // uplink p = dev->inbuf[idx]; #if 0 *p++ = len; *p++ = cmq; len--; #else *p++ = cmq; len--; *p++ = len; #endif // printk(KERN_DEBUG "<len=%02X cmq=%02X\n", len, cmq); while( len-- ) { HS; *p++ = NIN; } if (debug & DEBUG_DUMP2) { p = dev->inbuf[idx]; len = p[1]; DumpBuffer("<<", p, len+2); } idx++; if(idx >= NUM_INBUF) idx=0; if(idx != dev->inhead) { dev->intail = idx; dbg8(" %s(): before waitqueue_active()", __FUNCTION__); if (waitqueue_active(&dev->rd_wait)) { dbg8(" %s(): before wake_up_interruptible()", __FUNCTION__); wake_up_interruptible( &dev->rd_wait ); } else dbg8(" %s(): waitqueue_active()=0", __FUNCTION__); } return 0; }
void Connection::SendDataFile(unsigned char *buffer, short length) { if (buffer) { DumpBuffer(buffer, length); //m_CryptOut.RC4(buffer, length); Send(buffer, length); } }
void dumpSmbNtlmAuthResponse (FILE * fp, tSmbNtlmAuthResponse * response) { unsigned char buf1[NTLM_BUFSIZE], buf2[NTLM_BUFSIZE], buf3[NTLM_BUFSIZE]; fprintf (fp, "NTLM Response:\n" " Ident = %.8s\n" " mType = %d\n" " LmResp = ", response->ident, UI32LE (response->msgType)); DumpBuffer (fp, response, lmResponse); fprintf (fp, " Domain = %s\n" " User = %s\n" " Wks = %s\n" " sKey = ", GetUnicodeString (response, uDomain, buf1), GetUnicodeString (response, uUser, buf2), GetUnicodeString (response, uWks, buf3)); DumpBuffer (fp, response, sessionKey); fprintf (fp, " Flags = %08x\n", UI32LE (response->flags)); }
void Connection::Send(unsigned char *Buffer, int length) { if (m_PacketLoggingEnabled) { LogMessage("[%d] Adding packet to Send Queue, length=%d\n", m_RecvThreadHandle, length); DumpBuffer(Buffer, length); } // Mutexed, so thread safe. Not sure about DumpBuffer... (didn't look) m_SendQueue->Add(Buffer, length, m_AvatarID); }
int worker(int dev, SOCKET sock, SSL *sslSession, const char *certFile, const char *keyFile, const char *caCertFile) { int bytes; char buffer[1024]; INFO("Loop started\n"); while (isRunning()) { bytes = ReadPortTimeout(dev, buffer, sizeof(buffer), 1000); if (bytes == -1) break; if (bytes > 0) { DBG("device has data\n"); DumpBuffer(buffer, bytes); if (sslSession != NULL) SSL_write(sslSession, buffer, bytes); else send(sock, buffer, bytes, 0); continue; } bytes = ReadSockTimeout(sock, sslSession, buffer, sizeof(buffer), 1000); if (bytes == -1) break; if (bytes > 0) { DBG("socket has data\n"); DumpBuffer(buffer, bytes); write(dev, buffer, bytes); continue; } _sleep(10); } INFO("Loop ended\n"); return 0; }
bool DumpResource(int Id, const TCHAR* Caption, const TCHAR* Type) { HGLOBAL hGlobal; int Size; const BYTE* Data; if (!LoadResource(Id, Type, hGlobal, Data, Size)) return false; DumpBuffer(Caption, Data, Size); UnlockAndFreeResource(hGlobal); return true; }
static ssize_t lpc_write( struct file *file, const char *buf, size_t count, loff_t *off ) { u8 *p; int idx; int len; // int flags; register DEV *dev = (DEV *)(file->private_data); dbg1("%s(): dev=%08X", __FUNCTION__, (uint)dev); // DbgFlush(); if(count < 0) return -EINVAL; if(count > 256) return -EINVAL; idx = dev->outtail + 1; if(idx >= NUM_OUTBUF) idx = 0; // CLI; if(idx == dev->outhead) { // STI; dbg1("%s(): dev=%08X return -EWOULDBLOCK", __FUNCTION__, (uint)dev); return -EWOULDBLOCK; } // STI; p = dev->outbuf[ dev->outtail ]; if (copy_from_user(p, buf, count)) return -EFAULT; if (debug & DEBUG_DUMP1) DumpBuffer("> ", p, count); #if 0 // app layer -> link layer len = p[1] + 1; p[1] = p[0]; p[0] = (u8)len; len++; #else len = p[1] + 2; #endif dev->outtail = idx; if( dev->state == ST_IDLE ) { del_timer( &dev->drvtimer ); sm_stub( dev ); } dbg1("%s(): dev=%08X return %d", __FUNCTION__, (uint)dev, len); return len; }
static int downlink( DEV *dev ) { u8 cmq, len, st; u8 *p; int idx; u32 cport, wport; dbg8("%s(): dev=%08X", __FUNCTION__, (uint)dev); cport = dev->cport; wport = dev->wport; idx = dev->outhead; p = dev->outbuf[idx]; #if 0 len = *p++; cmq = *p++; #else cmq = *p++; len = *p++; // len ++; #endif if (debug & DEBUG_DUMP2) DumpBuffer(">>", p-2, len+2); // printk(KERN_DEBUG ">len=%02X cmq=%02X\n", len, cmq); HS; NOUT(CMD_XFER); HS; NOUT(len+1); HS; NOUT(cmq); HS; // printk(KERN_DEBUG "len=%02X Loop: ", len); while(len--) { // printk ("%.2x ", *p); HS; NOUT(*p++); } // printk ("\n"); HS; NOUT(EOM); idx++; if(idx >= NUM_OUTBUF) idx=0; dev->outhead = idx; return 0; }
void Connection::SendResponse(short opcode, unsigned char *data, size_t length) { //if (!this) return; if (m_ServerType == CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY && m_AvatarID == 0) { LogMessage("[%d] Invalid attempt to send via TCP: Last Owner = %s\n", m_RecvThreadHandle, m_LastOwner); return; } *((short *) &m_SendBuffer[0]) = (short) length + sizeof(long); *((short *) &m_SendBuffer[2]) = opcode; if ((length + 4) < MAX_BUFFER) { memcpy(m_SendBuffer + sizeof(long), data, length); } else { LogMessage("[%d] Message too long to send via Connection: opcode %04x length %d\n", m_RecvThreadHandle, opcode, length); return; } int bytes = length + sizeof(long); if (m_PacketLoggingEnabled) { LogMessage("[%d] Sending %d bytes (unencrypted)\n", m_RecvThreadHandle, bytes); DumpBuffer(m_SendBuffer, bytes); } if (m_ServerType != CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY && m_ServerType != CONNECTION_TYPE_GLOBAL_PROXY_TO_SERVER) { m_CryptOut.RC4(m_SendBuffer, bytes); } Send(m_SendBuffer, bytes); }
int main (int argc, char **argv){ unsigned int beacon_time = 30; //30 mins unsigned int jitter_time = 5; //5 mins unsigned short local_port = 8443; unsigned char *remoteURL = NULL; unsigned char *outFile = NULL; unsigned char *proxyFile = NULL; unsigned char *groupName = "default"; //Parse out the args int ch; while ((ch = getopt(argc, argv, "b:j:p:r:g:o:m:")) != -1) { switch (ch) { case 'b': beacon_time = strtol(optarg,NULL,10); break; case 'j': jitter_time = strtol(optarg,NULL,10); break; case 'p': local_port = strtol(optarg,NULL,10); break; case 'r': remoteURL = optarg; break; case 'g': groupName = optarg; break; case 'm': proxyFile = optarg; break; case 'o': outFile = optarg; break; case '?': default: usage(argv[0]); } } argc -= optind; argv += optind; printf("Beacon time: %d\n",beacon_time); printf("Jitter: %d\n",jitter_time); printf("Port: %d\n",local_port); printf("Remote URL: %s\n",remoteURL); printf("Group Name: %s\n",groupName); printf("Proxy file: %s\n",proxyFile); printf("Outfile: %s\n",outFile); PPROXY_VARS vars; //Allocate and initialize the variable structure vars = InitVars(); if(!vars){ printf("Invalid Variable structure\n"); return 2; } //Add the beacon and jitter vars->beacon_time = beacon_time; vars->beacon_jitter = jitter_time; vars->port = local_port; //Add the URL if(VarsAddURL(vars,remoteURL) == 0){ printf("Failed to add URL\n"); return 4; } //Add the Group if(VarsAddGroup(vars,groupName) == 0){ printf("Failed to add the group\n"); return 5; } //Add the Proxy if there is one if(VarsAddProxy(vars,proxyFile) == 0){ printf("Failed to add Proxy\n"); } PrintVars(vars); //Serialize the vars unsigned char *buf; int bufSize = 0; buf = SerializeVars(vars,&bufSize); if(buf == NULL){ printf("Failed to Serialize Var struct\n"); return 6; } //Write them out if ( DumpBuffer(buf,bufSize,outFile) == 0){ printf("Failed to write out vars\n"); return 7; } return 0; }
static DWORD ClientEstablishContext( IN PCSTR pSPN, IN INT nSocket, IN PCSTR pServiceName, IN PCSTR pServicePassword, IN PCSTR pServiceRealm, IN ULONG DelegFlag, OUT CtxtHandle *pSspiContext, IN PCSTR pSecPkgName, OUT ULONG *pRetFlags ) { DWORD dwError = ERROR_SUCCESS; DWORD dwLoopError = ERROR_SUCCESS; PCtxtHandle pContextHandle = NULL; INT nCredentialsAcquired = 0; INT nContextAcquired = 0; SecBuffer SendTokenBuffer; SecBuffer RecvTokenBuffer; SecBufferDesc InputDesc; SecBufferDesc OutputDesc; CredHandle CredHandle; TimeStamp Expiry; SEC_WINNT_AUTH_IDENTITY AuthIdentity; PSEC_WINNT_AUTH_IDENTITY pAuthId = NULL; memset(&SendTokenBuffer, 0, sizeof(SecBuffer)); memset(&RecvTokenBuffer, 0, sizeof(SecBuffer)); memset(&InputDesc, 0, sizeof(SecBufferDesc)); memset(&OutputDesc, 0, sizeof(SecBufferDesc)); memset(&CredHandle, 0, sizeof(CredHandle)); memset(&Expiry, 0, sizeof(TimeStamp)); memset(&AuthIdentity, 0, sizeof(AuthIdentity)); memset(pSspiContext, 0, sizeof(CtxtHandle)); *pRetFlags = 0; InputDesc.cBuffers = 1; InputDesc.pBuffers = &RecvTokenBuffer; InputDesc.ulVersion = SECBUFFER_VERSION; RecvTokenBuffer.BufferType = SECBUFFER_TOKEN; RecvTokenBuffer.cbBuffer = 0; RecvTokenBuffer.pvBuffer = NULL; OutputDesc.cBuffers = 1; OutputDesc.pBuffers = &SendTokenBuffer; OutputDesc.ulVersion = SECBUFFER_VERSION; SendTokenBuffer.BufferType = SECBUFFER_TOKEN; SendTokenBuffer.cbBuffer = 0; SendTokenBuffer.pvBuffer = NULL; CredHandle.dwLower = 0; CredHandle.dwUpper = 0; if (pServiceName) { AuthIdentity.User = (PBYTE) pServiceName; AuthIdentity.UserLength = (DWORD)strlen(pServiceName); pAuthId = &AuthIdentity; } if (pServicePassword) { AuthIdentity.Password = (PBYTE) pServicePassword; AuthIdentity.PasswordLength = (DWORD)strlen(pServicePassword); pAuthId = &AuthIdentity; } if (pServiceRealm) { AuthIdentity.Domain = (PBYTE) pServiceRealm; AuthIdentity.DomainLength = (DWORD)strlen(pServiceRealm); pAuthId = &AuthIdentity; } AuthIdentity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; dwError = AcquireCredentialsHandle( NULL, // no principal name (PSTR) pSecPkgName, // package name SECPKG_CRED_OUTBOUND, NULL, // no logon id pAuthId, NULL, // no get key fn NULL, // noget key arg &CredHandle, &Expiry ); BAIL_ON_ERROR(dwError); nCredentialsAcquired = 1; /* * Perform the context-establishement loop. */ pSspiContext->dwLower = 0; pSspiContext->dwUpper = 0; do { // we need to use dwLoopErr in this case because we may get // back a "continue" command. In those cases, we still // need dwError to be used and set seperatly based on other // calls. dwLoopError = InitializeSecurityContext( &CredHandle, pContextHandle, (PSTR) pSPN, DelegFlag, 0, // reserved SECURITY_NATIVE_DREP, &InputDesc, 0, // reserved pSspiContext, &OutputDesc, pRetFlags, &Expiry ); if (SEC_E_OK != dwLoopError && SEC_I_CONTINUE_NEEDED != dwLoopError) { dwError = dwLoopError; BAIL_ON_ERROR(dwError); } nContextAcquired = 1; if (SEC_I_CONTINUE_NEEDED == dwLoopError) { PNTLM_NEGOTIATE_MESSAGE pMsg = (PNTLM_NEGOTIATE_MESSAGE) SendTokenBuffer.pvBuffer; // Adjust any flags for debugging // pMsg->NtlmFlags |= NTLM_FLAG_SEAL; printf("Context partially initialized...\n"); DumpBuffer(SendTokenBuffer.pvBuffer, SendTokenBuffer.cbBuffer); DumpNtlmMessage(SendTokenBuffer.pvBuffer, SendTokenBuffer.cbBuffer); printf("\n"); printf("Flags returned:\n"); DumpIscRetFlags(*pRetFlags); printf("\n"); } else { PNTLM_RESPONSE_MESSAGE pMsg = (PNTLM_RESPONSE_MESSAGE) SendTokenBuffer.pvBuffer; // Adjust any flags for debugging //pMsg->NtlmFlags |= NTLM_FLAG_SEAL; printf("Context FULLY initialized!\n"); DumpBuffer(SendTokenBuffer.pvBuffer, SendTokenBuffer.cbBuffer); DumpNtlmMessage(SendTokenBuffer.pvBuffer, SendTokenBuffer.cbBuffer); printf("\n"); printf("Flags returned:\n"); DumpIscRetFlags(*pRetFlags); printf("\n"); } pContextHandle = pSspiContext; if (RecvTokenBuffer.pvBuffer) { free(RecvTokenBuffer.pvBuffer); RecvTokenBuffer.pvBuffer = NULL; RecvTokenBuffer.cbBuffer = 0; } if (SendTokenBuffer.cbBuffer != 0) { dwError = SendToken(nSocket, &SendTokenBuffer); BAIL_ON_ERROR(dwError); } FreeContextBuffer(SendTokenBuffer.pvBuffer); SendTokenBuffer.pvBuffer = NULL; SendTokenBuffer.cbBuffer = 0; if (SEC_I_CONTINUE_NEEDED == dwLoopError) { dwError = RecvToken(nSocket, &RecvTokenBuffer); BAIL_ON_ERROR(dwError); printf("RECEIVED:\n"); DumpBuffer(RecvTokenBuffer.pvBuffer, RecvTokenBuffer.cbBuffer); DumpNtlmMessage(RecvTokenBuffer.pvBuffer, RecvTokenBuffer.cbBuffer); printf("\n"); } } while (dwLoopError == SEC_I_CONTINUE_NEEDED); FreeCredentialsHandle(&CredHandle); finish: return dwError; error: if (nCredentialsAcquired) { FreeCredentialsHandle(&CredHandle); } if (nContextAcquired) { DeleteSecurityContext(pSspiContext); memset(pSspiContext, 0, sizeof(CtxtHandle)); } if (RecvTokenBuffer.pvBuffer) { free(RecvTokenBuffer.pvBuffer); } if (SendTokenBuffer.cbBuffer) { FreeContextBuffer(SendTokenBuffer.pvBuffer); } goto finish; }
int Poll(void) { register int a, b, c, d, ret, go = 1; if ((ret = read(Port, IB + IBCP, (IBS - IBCP))) < 1) return (0); IBCP += ret; a = IBCP; #ifdef COMM_DEBUG printf("STS"); fflush(stdout); DumpBuffer(); #endif while (go) { a = IBCP; for (b = 0; b < a; b++) { if ((IB[b] == 13) || (IB[b] == 7)) // Terminator { #ifdef COMM_DEBUG printf("\n%d/%d : ", b, IBCP); fflush(stdout); #endif switch (IB[0]) // 0 is OK, because we tidy up the buffer as we go... { case 'V': // version for (c = 0; c < 4; c++) Version[c] = IB[c + 1]; #ifdef COMM_DEBUG printf("Version Recognized"); fflush(stdout); #endif break; case 'N': for (c = 0; c < 4; c++) Serial[c] = IB[c + 1]; break; case 'F': // Status if (IB[1] >= 'A') StatusFlag = (IB[1] - 'A') + 10; else StatusFlag = (IB[1] - '0'); StatusFlag <<= 4; if (IB[2] >= 'A') StatusFlag += (IB[2] - 'A') + 10; else StatusFlag += (IB[2] - '0'); CRSignal = 1; break; case 'z': // transmission ack case 'Z': #ifdef COMM_DEBUG printf("Transmission Success"); fflush(stdout); #endif CRSignal = 1; break; case 13: CRSignal = 1; break; case 7: printf("\n***** ERROR BELL RECEIVED..."); fflush(stdout); CRSignal = 1; break; default: #ifdef COMM_DEBUG printf("Header Byte : '%c' ", IB[0]); fflush(stdout); for (c = 0; c < b; c++) printf("'%c'", IB[c]); fflush(stdout); #endif break; } // Tidy up... if (IBCP == (b + 1)) // This is the only message, so no copy req. IBCP = 0; else { a = b + 1; // from here c = IBCP - b; // this many #ifdef COMM_DEBUG printf(" => %d/%d : ", a, c); fflush(stdout); #endif for (d = 0; d < c; d++) { IB[d] = IB[d + a]; } IBCP -= (b + 1); #ifdef COMM_DEBUG printf(" -> %d", IBCP); fflush(stdout); #endif } b = a + 2; // quit from loop in 'C' fashion... } #ifdef COMM_DEBUG DumpBuffer(); #endif } if (b == a) go = 0; } #ifdef COMM_DEBUG printf("RET"); fflush(stdout); #endif return (ret); }
void Connection::RunRecvThread() { bool isSocketReady = false; // Used for checking Socket state int numretries = 0; int received; unsigned short bytes; short opcode; EnbTcpHeader header; char *ptr_hdr = (char*)&header; memset(&header, 0, sizeof(header)); while (!g_ServerShutdown && !m_TcpThreadTerminated) { while (m_TcpThreadRunning) { // Do the key exchange if it hasn't been done yet if (!m_KeysExchanged) { if (!RunKeyExchange()) { // Key Exchange failed. KillConnection(); break; } else { m_KeysExchanged = true; } } // Main Loop isSocketReady = SocketReady(1); // One Second Timeout if ( isSocketReady && (recv(m_Socket, ptr_hdr, 4, 0) == 4) ) { m_InactivityTimer = 0; if (m_PacketLoggingEnabled) { LogMessage("[%d] Received 4 byte header (encrypted):\n", m_RecvThreadHandle); DumpBuffer((unsigned char *) &header, 4); } if (m_ServerType != CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY && m_ServerType != CONNECTION_TYPE_GLOBAL_PROXY_TO_SERVER) { m_CryptIn.RC4((unsigned char *) &header, 4); } if (m_PacketLoggingEnabled) { LogMessage("[%d] Received 4 byte header (decrypted):\n", m_RecvThreadHandle); DumpBuffer((unsigned char *) &header, 4); } bytes = header.size - sizeof(EnbTcpHeader); // Bytes to fetch opcode = header.opcode; // Opcode for this packet // This buffer check MUST be in place if ( (bytes > MAX_BUFFER) ) { LogMessage("[%d] Received packet with incorrect payload length: opcode = 0x%02x, length = %d. Aborting.\n", m_RecvThreadHandle, opcode, bytes); KillConnection(); // We're not permitting a 2nd chance. break; } //LogMessage("Received packet: opcode = 0x%02x, length = %d\n", opcode, bytes); received = recv(m_Socket, (char *) m_RecvBuffer, bytes, 0); numretries = 0; while ( received != bytes && // Did we fetch everything? SocketReady() && // Can we still get more? numretries < MAX_RETRIES && // Can we still retry to get more? m_TcpThreadRunning ) // And we haven't been told to stop? { int rcv = recv(m_Socket, (char *) (m_RecvBuffer + received), bytes - received, 0); if (rcv > 0) { received += rcv; } else break; numretries++; // Prevent an infinite loop } if ( received == bytes && m_TcpThreadRunning ) // We got the whole package and we haven't been told top stop { if (m_ServerType != CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY && m_ServerType != CONNECTION_TYPE_GLOBAL_PROXY_TO_SERVER) { m_CryptIn.RC4(m_RecvBuffer, bytes); } if (m_PacketLoggingEnabled) { LogMessage("[%d] Received %d byte packet\n", m_RecvThreadHandle, received); DumpBuffer(m_RecvBuffer,bytes); } switch (m_ServerType) { case CONNECTION_TYPE_CLIENT_TO_GLOBAL_SERVER : ProcessGlobalServerOpcode(opcode, bytes); break; case CONNECTION_TYPE_CLIENT_TO_MASTER_SERVER : ProcessMasterServerOpcode(opcode, bytes); break; case CONNECTION_TYPE_CLIENT_TO_SECTOR_SERVER : //ProcessSectorServerOpcode(opcode, bytes); LogMessage("[%d] ERROR!!: Sector Server opcode received!\n", m_RecvThreadHandle); break; case CONNECTION_TYPE_MASTER_SERVER_TO_SECTOR_SERVER : ProcessMasterServerToSectorServerOpcode(opcode, bytes); break; case CONNECTION_TYPE_SECTOR_SERVER_TO_SECTOR_SERVER : ProcessSectorServerToSectorServerOpcode(opcode, bytes); break; case CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY: ProcessProxyClientOpcode(opcode, bytes); break; case CONNECTION_TYPE_GLOBAL_PROXY_TO_SERVER: ProcessProxyGlobalOpcode(opcode, bytes); break; default: LogMessage("[%d] ERROR: Unknown type of connection.\n", m_RecvThreadHandle); m_TcpThreadRunning = false; // Shouldn't happen (but was able to with a buffer overflow). break; } } else { // Error Stage if (m_TcpThreadRunning) // We weren't told to stop, but never got our whole packet { LogMessage("[%d] Error receiving TCP packet on port %d, got %d bytes, expecting %d -- aborting!\n", m_RecvThreadHandle,m_TcpPort, received, bytes); if (received > 0 && g_Debug && received < 10000) DumpBuffer(m_RecvBuffer, received); } m_TcpThreadRunning = false; } } else { // Check Connection Status DWORD error = WSAGetLastError(); if ( !isSocketReady && error == 0 ) { m_InactivityTimer++; if ( (m_MaxInactivityTime > 0) && (m_InactivityTimer > m_MaxInactivityTime) ) { LogMessage("[%d] TCP connection on port %d exceeded maximum inactivity. Aborting.\n", m_RecvThreadHandle, m_TcpPort); m_TcpThreadRunning = false; } } else { switch (error) { case 0: LogMessage("[%d] TCP connection on port %d gracefully closed\n", m_RecvThreadHandle, m_TcpPort); break; case WSAECONNRESET: LogMessage("[%d] TCP connection on port %d was reset\n", m_RecvThreadHandle, m_TcpPort); break; default: LogMessage("[%d] TCP error on port %d (Error %d). Aborting.\n", m_RecvThreadHandle, m_TcpPort, error); break; } m_TcpThreadRunning = false; } } } KillConnection(); // m_TcpThreadRunning was set to false. Go to sleep... #ifdef WIN32 SuspendThread(m_RecvThreadHandle); #else pthread_cond_wait(&m_RecvThreadCond, &m_RecvThreadMtx); #endif } m_TcpThreadTerminated = true; }
// // Dump data buffer // void BaseStringBuffer::RealDumpBuffer() { if (iBufferPos != 0) { DumpBuffer(); } iBufferPos = 0; }
// This function implements the NcpFrameBuffer tests void TestNcpFrameBuffer(void) { unsigned i, j; uint8_t buffer[kTestBufferSize]; NcpFrameBuffer ncpBuffer(buffer, kTestBufferSize); Message *message; CallbackContext context; CallbackContext oldContext; uint8_t readBuffer[16]; uint16_t readLen, readOffset; for (i = 0; i < sizeof(buffer); i++) { buffer[i] = 0; } context.mEmptyCount = 0; context.mNonEmptyCount = 0; // Set the callbacks. ncpBuffer.SetCallbacks(BufferDidGetEmptyCallback, BufferDidGetNonEmptyCallback, &context); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 1: Write a frame 1 "); WriteTestFrame1(ncpBuffer); DumpBuffer("\nBuffer after frame1", buffer, kTestBufferSize); printf("\nFrameLen is %u", ncpBuffer.OutFrameGetLength()); VerifyAndRemoveFrame1(ncpBuffer); printf("\nIterations: "); // Repeat this multiple times. for (j = 0; j < kTestIterationAttemps; j++) { printf("*"); WriteTestFrame1(ncpBuffer); VerifyOrQuit(ncpBuffer.IsEmpty() == false, "IsEmpty() is incorrect when buffer is non-empty"); VerifyAndRemoveFrame1(ncpBuffer); VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty."); } printf(" -- PASS\n"); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 2: Multiple frames write and read "); WriteTestFrame2(ncpBuffer); WriteTestFrame3(ncpBuffer); WriteTestFrame2(ncpBuffer); WriteTestFrame2(ncpBuffer); DumpBuffer("\nBuffer after multiple frames", buffer, kTestBufferSize); VerifyAndRemoveFrame2(ncpBuffer); VerifyAndRemoveFrame3(ncpBuffer); VerifyAndRemoveFrame2(ncpBuffer); VerifyAndRemoveFrame2(ncpBuffer); printf("\nIterations: "); // Repeat this multiple times. for (j = 0; j < kTestIterationAttemps; j++) { printf("*"); WriteTestFrame2(ncpBuffer); WriteTestFrame3(ncpBuffer); WriteTestFrame2(ncpBuffer); VerifyAndRemoveFrame2(ncpBuffer); VerifyAndRemoveFrame3(ncpBuffer); WriteTestFrame2(ncpBuffer); WriteTestFrame3(ncpBuffer); VerifyAndRemoveFrame2(ncpBuffer); VerifyAndRemoveFrame2(ncpBuffer); VerifyAndRemoveFrame3(ncpBuffer); VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty."); } printf(" -- PASS\n"); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 3: Frame discard when buffer full and partial read restart"); for (j = 0; j < kTestIterationAttemps; j++) { WriteTestFrame2(ncpBuffer); WriteTestFrame3(ncpBuffer); ncpBuffer.InFrameBegin(); ncpBuffer.InFrameFeedData(sHelloText, sizeof(sHelloText)); message = sMessagePool.New(Message::kTypeIp6, 0); VerifyOrQuit(message != NULL, "Null Message"); SuccessOrQuit(message->SetLength(sizeof(sMysteryText)), "Could not set the length of message."); message->Write(0, sizeof(sMysteryText), sMysteryText); ncpBuffer.InFrameFeedMessage(*message); // Now cause a restart the current frame and test if it's discarded ok. WriteTestFrame2(ncpBuffer); if (j == 0) { DumpBuffer("\nAfter frame gets discarded", buffer, kTestBufferSize); printf("\nIterations: "); } else { printf("*"); } VerifyAndRemoveFrame2(ncpBuffer); // Start reading few bytes from the frame ncpBuffer.OutFrameBegin(); ncpBuffer.OutFrameReadByte(); ncpBuffer.OutFrameReadByte(); ncpBuffer.OutFrameReadByte(); // Now reset the read pointer and read/verify the frame from start. VerifyAndRemoveFrame3(ncpBuffer); VerifyAndRemoveFrame2(ncpBuffer); VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty."); } printf(" -- PASS\n"); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 4: Callbacks "); printf("\nIterations: "); // Repeat this multiple times. for (j = 0; j < kTestIterationAttemps; j++) { printf("*"); oldContext = context; WriteTestFrame2(ncpBuffer); VerifyOrQuit(ncpBuffer.IsEmpty() == false, "IsEmpty() is incorrect when buffer is non-empty"); VerifyOrQuit(oldContext.mEmptyCount == context.mEmptyCount, "Empty callback called incorrectly"); VerifyOrQuit(oldContext.mNonEmptyCount + 1 == context.mNonEmptyCount, "NonEmpty callback was not invoked."); oldContext = context; WriteTestFrame3(ncpBuffer); VerifyOrQuit(oldContext.mEmptyCount == context.mEmptyCount, "Empty callback called incorrectly"); VerifyOrQuit(oldContext.mNonEmptyCount == context.mNonEmptyCount, "NonEmpty callback called incorrectly."); oldContext = context; ncpBuffer.OutFrameRemove(); VerifyOrQuit(ncpBuffer.IsEmpty() == false, "IsEmpty() is incorrect when buffer is non empty."); VerifyOrQuit(oldContext.mEmptyCount == context.mEmptyCount, "Empty callback called incorrectly"); VerifyOrQuit(oldContext.mNonEmptyCount == context.mNonEmptyCount, "NonEmpty callback called incorrectly."); oldContext = context; ncpBuffer.OutFrameRemove(); VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty."); VerifyOrQuit(oldContext.mEmptyCount + 1 == context.mEmptyCount, "Empty callback was not invoked."); VerifyOrQuit(oldContext.mNonEmptyCount == context.mNonEmptyCount, "NonEmpty callback called incorrectly."); } printf(" -- PASS\n"); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 5: Clear() and empty buffer method tests"); WriteTestFrame1(ncpBuffer); oldContext = context; ncpBuffer.Clear(); VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty."); VerifyOrQuit(ncpBuffer.OutFrameHasEnded() == true, "OutFrameHasEnded() is incorrect when no data in buffer."); VerifyOrQuit(ncpBuffer.OutFrameRemove() == kThreadError_NotFound, "Remove() returned incorrect error status when buffer is empty."); VerifyOrQuit(ncpBuffer.OutFrameGetLength() == 0, "OutFrameGetLength() returned non-zero length when buffer is empty."); VerifyOrQuit(oldContext.mEmptyCount + 1 == context.mEmptyCount, "Empty callback was not invoked."); VerifyOrQuit(oldContext.mNonEmptyCount == context.mNonEmptyCount, "NonEmpty callback called incorrectly."); WriteTestFrame1(ncpBuffer); oldContext = context; VerifyAndRemoveFrame1(ncpBuffer); VerifyOrQuit(ncpBuffer.IsEmpty() == true, "IsEmpty() is incorrect when buffer is empty."); VerifyOrQuit(ncpBuffer.OutFrameHasEnded() == true, "OutFrameHasEnded() is incorrect when no data in buffer."); VerifyOrQuit(ncpBuffer.OutFrameRemove() == kThreadError_NotFound, "Remove() returned incorrect error status when buffer is empty."); VerifyOrQuit(ncpBuffer.OutFrameGetLength() == 0, "OutFrameGetLength() returned non-zero length when buffer is empty."); VerifyOrQuit(oldContext.mEmptyCount + 1 == context.mEmptyCount, "Empty callback was not invoked."); VerifyOrQuit(oldContext.mNonEmptyCount == context.mNonEmptyCount, "NonEmpty callback called incorrectly."); printf(" -- PASS\n"); printf("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"); printf("\nTest 6: OutFrameRead() in parts\n"); ncpBuffer.InFrameBegin(); ncpBuffer.InFrameFeedData(sMottoText, sizeof(sMottoText)); ncpBuffer.InFrameEnd(); ncpBuffer.OutFrameBegin(); readOffset = 0; while ((readLen = ncpBuffer.OutFrameRead(sizeof(readBuffer), readBuffer)) != 0) { DumpBuffer("Read() returned", readBuffer, readLen); VerifyOrQuit(memcmp(readBuffer, sMottoText + readOffset, readLen) == 0, "Read() does not match expected content."); readOffset += readLen; } VerifyOrQuit(readOffset == sizeof(sMottoText), "Read len does not match expected length."); printf("\n -- PASS\n"); }
static DWORD ServerEstablishContext( IN INT nSocket, IN CredHandle *pServerCreds, OUT CtxtHandle *pContext, IN ULONG AscFlags ) { DWORD dwError = ERROR_SUCCESS; DWORD dwLoopError = ERROR_SUCCESS; ULONG nRetFlags = 0; SecBufferDesc InputDesc; SecBufferDesc OutputDesc; SecBuffer SendTokenBuffer; SecBuffer RecvTokenBuffer; TimeStamp Expiry; PCtxtHandle pContextHandle = NULL; INT nContextAcquired = 0; memset(&InputDesc, 0, sizeof(SecBufferDesc)); memset(&OutputDesc, 0, sizeof(SecBufferDesc)); memset(&SendTokenBuffer, 0, sizeof(SecBuffer)); memset(&RecvTokenBuffer, 0, sizeof(SecBuffer)); memset(&Expiry, 0, sizeof(TimeStamp)); memset(pContext, 0, sizeof(CtxtHandle)); InputDesc.cBuffers = 1; InputDesc.ulVersion = SECBUFFER_VERSION; InputDesc.pBuffers = &RecvTokenBuffer; OutputDesc.cBuffers = 1; OutputDesc.ulVersion = SECBUFFER_VERSION; OutputDesc.pBuffers = &SendTokenBuffer; printf("ASC flags requested (0x%08x):\n", AscFlags); DumpAscReqFlags(AscFlags); do { dwError = RecvToken(nSocket, &RecvTokenBuffer); BAIL_ON_ERROR(dwError); printf("RECEIVED:\n"); DumpBuffer(RecvTokenBuffer.pvBuffer, RecvTokenBuffer.cbBuffer); DumpNtlmMessage(RecvTokenBuffer.pvBuffer, RecvTokenBuffer.cbBuffer); printf("\n"); RecvTokenBuffer.BufferType = SECBUFFER_TOKEN; SendTokenBuffer.cbBuffer = 0; SendTokenBuffer.pvBuffer = NULL; SendTokenBuffer.BufferType = SECBUFFER_TOKEN; // we need to use dwLoopErr in this case because we may get // back a "continue" command. In those cases, we still // need dwError to be used and set seperatly based on other // calls. dwLoopError = AcceptSecurityContext( pServerCreds, pContextHandle, &InputDesc, AscFlags, SECURITY_NATIVE_DREP, pContext, &OutputDesc, &nRetFlags, &Expiry ); if (SEC_E_OK != dwLoopError && SEC_I_CONTINUE_NEEDED != dwLoopError) { dwError = dwLoopError; BAIL_ON_ERROR(dwError); } if (SEC_I_CONTINUE_NEEDED == dwLoopError) { printf("Context partially accepted...\n"); DumpBuffer(SendTokenBuffer.pvBuffer, SendTokenBuffer.cbBuffer); DumpNtlmMessage(SendTokenBuffer.pvBuffer, SendTokenBuffer.cbBuffer); if (nRetFlags) { printf("ASC flags returned (0x%08x):\n", nRetFlags); DumpAscRetFlags(nRetFlags); } printf("\n"); } else { printf("Context FULLY accepted!\n"); printf("ASC flags returned (0x%08x):\n", nRetFlags); DumpAscRetFlags(nRetFlags); printf("\n"); } nContextAcquired = 1; pContextHandle = pContext; free(RecvTokenBuffer.pvBuffer); RecvTokenBuffer.pvBuffer = NULL; if (SendTokenBuffer.cbBuffer != 0) { dwError = SendToken(nSocket, &SendTokenBuffer); BAIL_ON_ERROR(dwError); FreeContextBuffer(SendTokenBuffer.pvBuffer); SendTokenBuffer.pvBuffer = NULL; } } while (dwLoopError == SEC_I_CONTINUE_NEEDED); finish: return dwError; error: if (RecvTokenBuffer.pvBuffer) { free(RecvTokenBuffer.pvBuffer); RecvTokenBuffer.pvBuffer = NULL; } if (SendTokenBuffer.cbBuffer) { FreeContextBuffer(SendTokenBuffer.pvBuffer); SendTokenBuffer.pvBuffer = NULL; SendTokenBuffer.cbBuffer = 0; } if (nContextAcquired) { DeleteSecurityContext(pContext); } goto finish; }
static DWORD SignServer( IN INT nSocket, IN CredHandle *pServerCreds, IN ULONG AscFlags ) { DWORD dwError = ERROR_SUCCESS; ULONG ulQop = 0; INT nContextAcquired = 0; ULONG nIndex = 0; SecBuffer TransmitBuffer; SecBuffer MsgBuffer; SecBuffer WrapBuffers[2] = {0}; SecBufferDesc WrapBufferDesc; CtxtHandle Context; SecPkgContext_Names Names; SecPkgContext_Sizes Sizes; SecPkgContext_SessionKey SessionKey; memset(&TransmitBuffer, 0, sizeof(SecBuffer)); memset(&MsgBuffer, 0, sizeof(SecBuffer)); memset(&WrapBufferDesc, 0, sizeof(SecBufferDesc)); memset(&Context, 0, sizeof(CtxtHandle)); memset(&Names, 0, sizeof(SecPkgContext_Names)); memset(&Sizes, 0, sizeof(SecPkgContext_Sizes)); memset(&SessionKey, 0, sizeof(SecPkgContext_SessionKey)); /* Establish a context with the client */ dwError = ServerEstablishContext( nSocket, pServerCreds, &Context, AscFlags ); BAIL_ON_ERROR(dwError); dwError = QueryContextAttributes( &Context, SECPKG_ATTR_NAMES, &Names ); if (dwError) { printf("Unable to query context: %d\n", dwError); } else { printf("Context is for user: %s\n", Names.sUserName); } dwError = QueryContextAttributes( &Context, SECPKG_ATTR_SESSION_KEY, &SessionKey ); if (dwError) { printf("Unable to query context: %X\n", dwError); } else { printf("Session Key: "); for(nIndex = 0; nIndex < SessionKey.SessionKeyLength; nIndex++) { printf("%02X ", SessionKey.SessionKey[nIndex]); } printf("\n\n"); } printf("Server accepted context successfully!\n"); // for clean up... once we've established a context, we must clean it up on // future failures. nContextAcquired = 1; dwError = QueryContextAttributes ( &Context, SECPKG_ATTR_SIZES, &Sizes ); BAIL_ON_ERROR(dwError); /* Receive the sealed message token */ dwError = RecvToken(nSocket, &TransmitBuffer); BAIL_ON_ERROR(dwError); printf("RECEIVED:\n"); DumpBuffer(TransmitBuffer.pvBuffer, TransmitBuffer.cbBuffer); printf("\n"); WrapBufferDesc.cBuffers = 2; WrapBufferDesc.pBuffers = WrapBuffers; WrapBufferDesc.ulVersion = SECBUFFER_VERSION; WrapBuffers[0].BufferType = SECBUFFER_TOKEN; WrapBuffers[0].pvBuffer = TransmitBuffer.pvBuffer; WrapBuffers[0].cbBuffer = Sizes.cbMaxSignature; WrapBuffers[1].BufferType = SECBUFFER_DATA; WrapBuffers[1].cbBuffer = TransmitBuffer.cbBuffer - Sizes.cbMaxSignature; WrapBuffers[1].pvBuffer = (PBYTE)TransmitBuffer.pvBuffer + Sizes.cbMaxSignature; dwError = DecryptMessage( &Context, &WrapBufferDesc, 0, // no sequence number &ulQop ); if (dwError) { // When we bail, this var will try to be freed which is a bad thing... // the memory will be freed when TransmitBuffer is freed, so it's ok // to set this buffer to NULL here. WrapBuffers[1].pvBuffer = NULL; printf("Unable to decrypt message\n"); } BAIL_ON_ERROR(dwError); MsgBuffer = WrapBuffers[1]; printf("Received message '%.*s' from client\n", MsgBuffer.cbBuffer, MsgBuffer.pvBuffer); /* Produce a signature block for the message */ WrapBuffers[0] = MsgBuffer; WrapBuffers[1].BufferType = SECBUFFER_TOKEN; WrapBuffers[1].cbBuffer = Sizes.cbMaxSignature; WrapBuffers[1].pvBuffer = malloc(Sizes.cbMaxSignature); if (WrapBuffers[1].pvBuffer == NULL) { dwError = ERROR_NOT_ENOUGH_MEMORY; BAIL_ON_ERROR(dwError); } dwError = MakeSignature( &Context, 0, &WrapBufferDesc, 0 ); if (dwError) { printf("Unable to MakeSignature"); } BAIL_ON_ERROR(dwError); free(TransmitBuffer.pvBuffer); TransmitBuffer = WrapBuffers[1]; WrapBuffers[1].pvBuffer = NULL; WrapBuffers[1].cbBuffer = 0; /* Send the signature block to the client */ dwError = SendToken(nSocket, &TransmitBuffer); BAIL_ON_ERROR(dwError); free(TransmitBuffer.pvBuffer); TransmitBuffer.pvBuffer = NULL; TransmitBuffer.cbBuffer = 0; /* Delete context */ dwError = DeleteSecurityContext( &Context ); BAIL_ON_ERROR(dwError); finish: return dwError; error: if (Names.sUserName) { FreeContextBuffer(Names.sUserName); } if (TransmitBuffer.pvBuffer) { free(TransmitBuffer.pvBuffer); TransmitBuffer.pvBuffer = NULL; TransmitBuffer.cbBuffer = 0; } if (WrapBuffers[1].pvBuffer) { free(WrapBuffers[1].pvBuffer); WrapBuffers[1].pvBuffer = NULL; WrapBuffers[1].cbBuffer = 0; } if (nContextAcquired) { DeleteSecurityContext(&Context); } goto finish; }
static void test_read_continuous_data(int handle, int ntimes) { int readlen = -1; char readbuf[READSIZ]; int devarr[DEVARRSIZ]; int device = -1; int ratemin = -1, ratedef = -1, ratemax = -1, rate=-1; int total_bytes_read = 0; int samplesize = -1; int nchan = -1; int ndev = -1; int i = 0, j=0; int sample_period = 100; int prevdot = 0; ndev = PasGetDevices(handle, devarr, DEVARRSIZ); if(ndev<0) { printf("\n Number of devices unknown. Not doing read continuous test. Error ndev = %d\n",ndev); return; } while(0<ntimes--) for(i=0; i < ndev ; i++) { device = devarr[i]; nchan = PasGetNumChannels(handle,device); for(j=0;j<nchan;j++) { if(1 != PasGetSensorDetected(handle,device,j)) continue; /** Print info about the sensor */ { char strbuf[STRSIZ]; strbuf[0] = 0x00; PasGetName(handle, device, j,strbuf,STRSIZ); printf("\n\nStart sampling, Device # %d, Channel %d, name: \"%s\"\n",device, j, strbuf); } /** Sample rate */ readbuf[0] = 0xFF; ratemin = PasGetSampleRateMinimum(handle, device, j); ratedef = PasGetSampleRateDefault(handle, device, j); ratemax = PasGetSampleRateMaximum(handle, device, j); if(ratemin==-1||ratedef==-1||ratemax==-1) { printf("Could not read rates, device %d, channel %d, min %d, default %d, max %d (this is OK if no HW plugged in to the port)\n", device, j,ratemin,ratedef,ratemax); continue; } else { // convert to millisecond period ratemin = pasco_rate_ms(ratemin); ratedef = pasco_rate_ms(ratedef); ratemax = pasco_rate_ms(ratemax); printf("Data rates: min %dms, default %dms, max %dms\n", ratemin, ratedef,ratemax); } sample_period = ratedef; /*set the rate to be the default*/ printf( "Set Sample Period %d ms (%d Hz)\n", sample_period, (1000/sample_period) ); /* *********************************************************************************** Read the data. NOTE: You can only call PasGetSampleData() in the loop Other API calls may cause failures, and possibly leave HW in a bad state. //Also Ctrl-C in the middle of the loop may do the same. IE: PasStartContinuousSampling() While() PasGetSampleData(); PasStopContinuousSampling(); *********************************************************************************** */ /* Start */ samplesize = PasStartContinuousSampling(handle, device, j, sample_period); if(samplesize<=0) { printf("Could not start sampling, device %d, channel %d, sample size %d, rate %d (this is OK if no HW plugged in to the port)\n", device, j, samplesize,rate); continue; } total_bytes_read = 0; while(total_bytes_read<(512)) /* total_bytes_read: May be more than 512 +sample size -- reads are not one sample at a time*/ { PasMSsleep(sample_period); /* OK to call --just a utility function */ memset(readbuf,'z',READSIZ); /* Read */ readlen = PasGetSampleData (handle,device,j, samplesize, readbuf, READSIZ); if(readlen>0) { if(prevdot) { printf("\n"); prevdot = 0; } DumpBuffer(readbuf,readlen); total_bytes_read += readlen; } if(readlen == 0) { /* did not read any bytes */ printf("-"); prevdot = 1; } if(readlen <0 ) { printf("Failed to read data error: %d (OK if HW removed)....bailing\n",readlen); break; } } /* Stop */ PasStopContinuousSampling (handle, device,j); printf("Read %d bytes \n\n", total_bytes_read); } } printf("\n\n"); }
static void test_print_some_good_stuff_for_all_sensors(int handle) { int retcode = -1; char strbuf[STRSIZ]; int devarr[DEVARRSIZ]; int device = -1; int samplesize = -1; int ratemin = -1, ratedef = -1, ratemax = -1; int nchan = -1; int ndev = -1; int i = 0, j=0, k=0; int nmeasurements = -1; int probe_validity_return = -1; char probe_validity_bits[4]; ndev = PasGetDevices(handle, devarr, DEVARRSIZ); if(ndev<0) { printf("test_print_some_good_stuff_for_all_sensors Error %d\n",ndev); return; } for(i=0; i < ndev ; i++) { device = devarr[i]; printf("Device # %d, ProductID %d\n", device, PasGetDeviceProductID(handle, device)); nchan = PasGetNumChannels(handle,device); for(j=0;j<nchan;j++) { if(1!=PasGetExistChannel(handle,device,j)) continue; samplesize = PasGetSampleSize(handle, device, j); printf("Device # %d, Channel %d, sample size: %d\n",device, j, samplesize); ratemin = PasGetSampleRateMinimum(handle, device, j); ratedef = PasGetSampleRateDefault(handle, device, j); ratemax = PasGetSampleRateMaximum(handle, device, j); printf(" Sample rates: min %d, default %d, max %d\n",ratemin,ratedef, ratemax); strbuf[0] = 0x00; retcode = PasGetName(handle, device, j,strbuf,STRSIZ); if(retcode>-1) printf("Device # %d, Channel %d, name: \"%s\"\n",device, j, strbuf); else printf("Device # %d, Channel %d, error: %d ( if -1 == just no Sensor)\n",device,j,retcode); nmeasurements = PasGetNumMeasurements(handle, device, j); for(k=0;k<nmeasurements;k++) { strbuf[0] = 0x00; retcode = PasGetMeasurementName(handle, device, j, k, strbuf, STRSIZ); if(retcode>-1) { printf("Device # %d, Channel %d, Measurement %d, name \"%s\"\n", device, j, k, strbuf); } else { printf("Device # %d, Channel %d, Measurement %d, error: %d\n", device, j, k, retcode); } } probe_validity_return = PasGetSupportsProbeValidityDetection(handle, device, j); printf("Device # %d, Channel %d, SupportsProbeValidity return %d\n", device, j, probe_validity_return); if(probe_validity_return>0){ memset(probe_validity_bits, 0, 4); retcode = PasCheckMeasurementValidity(handle, device, j, probe_validity_return, probe_validity_bits); if (retcode > -1) { printf("Device # %d, Channel %d, CheckMeasurementValidity bits ", device, j); DumpBuffer(probe_validity_bits, probe_validity_return); } else { printf("Device # %d, Channel %d, CheckMeasurementValidity error %d\n", device, j, retcode); } } printf("Device # %d, Channel %d, SensorDetected %d\n", device, j, PasGetSensorDetected(handle, device, j)); // Read data sheet { int dataSheetSize = -1; char *dataSheetBuffer = NULL; int dataSheetReadSize = -1; dataSheetSize = PasGetSensorDataSheetSize(handle,device, j); if(dataSheetSize < 0){ printf("Device # %d, Channel %d, couldn't read datasheet size, error: %d\n",device,j,retcode); return; } dataSheetBuffer =(char *) malloc(dataSheetSize); dataSheetReadSize = PasReadSensorDataSheet(handle, device, j, dataSheetBuffer, dataSheetSize); if(dataSheetReadSize < 0){ printf("Device # %d, Channel %d, couldn't read datasheet, error: %d\n",device,j,dataSheetReadSize); return; } printf(" DataSheet:\n"); DumpBuffer(dataSheetBuffer, dataSheetReadSize); } // check which measurements are valid which indicates if the external sensor is plugged in // this requires parsing the datasheet which currently isn't exposed // we could add a method for returning the number of measurements } } }
void Connection::RunRecvThread() { if (m_ServerType == CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY) { LogMessage("TCP login link established.\n"); } else if (m_ServerType < CONNECTION_TYPE_MASTER_SERVER_TO_SECTOR_SERVER) { if (!DoKeyExchange()) { m_ConnectionActive = false; LogMessage("Client key exchange failed. Connection thread exiting\n"); return; } } else { if (!DoClientKeyExchange()) { m_ConnectionActive = false; LogMessage("Server/Server key exchange failed. Connection thread exiting\n"); return; } } m_TcpThreadRunning = true; // Launch the Send Thread #ifdef WIN32 UINT uiThreadId = 0; m_SendThreadHandle = (HANDLE)_beginthreadex(NULL, 0, SocketSendThread, this, CREATE_SUSPENDED, &uiThreadId); //_beginthread(&LaunchSendThread, 0, this); #else pthread_create(&m_Thread, NULL, &LaunchSendThread, (void *) this); #endif EnbTcpHeader header; memset(&header, 0, sizeof(header)); char *ptr_hdr = (char*)&header; while (!g_ServerShutdown && m_TcpThreadRunning && !g_ShuttingDown) { // Read the opcode and the message length Sleep(1); int length = 0; int repeats = 0; length = recv(m_Socket, ptr_hdr, 4, 0); while(length < 4 && length > 0) { length += recv(m_Socket, (ptr_hdr + length), 4-length, 0); if(length == -1 || repeats++ > 3) { //break out and let the program handle it normally. break; } else if(length != 4) { LogMessage("Format error, length = %d\n", length); } LogMessage("%s Receive header: %d\n", (m_ServerType == CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY ? "server->proxy" : "client->proxy"), length); repeats++; } if (length == 4) { if (m_PacketLoggingEnabled) { LogMessage("Received 4 byte header (encrypted):\n"); DumpBuffer((unsigned char *) &header, length); } if (m_ServerType != CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY && m_ServerType != CONNECTION_TYPE_GLOBAL_PROXY_TO_SERVER) { m_CryptIn.RC4((unsigned char *) &header, length); } if (m_PacketLoggingEnabled) { LogMessage("Received 4 byte header (decrypted):\n"); DumpBuffer((unsigned char *) &header, length); } unsigned short bytes = header.size - sizeof(EnbTcpHeader); short opcode = header.opcode; // Read the message // TODO: peek to determine if we have enough data... // TODO: wait if we don't have enough data Sleep(1); int received = recv(m_Socket, (char *) m_RecvBuffer, bytes, 0); while (received < bytes) { int rcv = recv(m_Socket, (char *) (m_RecvBuffer + received), bytes - received, 0); if (rcv > 0) { received += rcv; } else { break; } } if (received == bytes) { if (m_ServerType != CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY && m_ServerType != CONNECTION_TYPE_GLOBAL_PROXY_TO_SERVER) { m_CryptIn.RC4(m_RecvBuffer, bytes); } if (m_PacketLoggingEnabled) { LogMessage("Received %d byte packet\n", received); DumpBuffer(m_RecvBuffer,bytes); } switch (m_ServerType) { case CONNECTION_TYPE_CLIENT_TO_GLOBAL_SERVER : //LogMessage("ERROR!!: Global Server opcode received!\n"); //LogMessage("Received Client to Global Opcode: 0x%x\n", opcode); ProcessGlobalServerOpcode(opcode, bytes); break; case CONNECTION_TYPE_CLIENT_TO_MASTER_SERVER : //LogMessage("Received Client to Master Opcode: 0x%x\n", opcode); ProcessMasterServerOpcode(opcode, bytes); break; case CONNECTION_TYPE_CLIENT_TO_SECTOR_SERVER : ProcessSectorServerOpcode(opcode, bytes); //LogMessage("Received SS Opcode: 0x%x\n", opcode); break; case CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY : //send these opcodes straight to the client ProcessProxyServerOpcode(opcode, bytes); break; case CONNECTION_TYPE_SECTOR_SERVER_TO_SECTOR_SERVER : //ProcessSectorServerToSectorServerOpcode(opcode, bytes); break; case CONNECTION_TYPE_GLOBAL_PROXY_TO_SERVER: ProcessProxyGlobalOpcode(opcode, bytes); break; } } else { LogMessage("Error receiving TCP packet on port %d, got %d bytes, expecting %d -- aborting!\n", m_TcpPort, received, bytes); if (received > 0 && g_Debug && received < 10000) { DumpBuffer(m_RecvBuffer, received); } m_TcpThreadRunning = false; } } else if (length == 0) { LogMessage("TCP connection on port %d closed gracefully\n", m_TcpPort); m_TcpThreadRunning = false; } else if (length == -1) { DWORD error = WSAGetLastError(); if (error == WSAECONNRESET) { LogMessage("TCP connection on port %d was reset\n", m_TcpPort); } else { LogMessage("Error receiving header on port %d, error=%d -- aborting\n", m_TcpPort, error); } m_TcpThreadRunning = false; } else { LogMessage("Error receiving 4 byte header on port %d, length = %d bytes -- aborting\n", m_TcpPort, length); m_TcpThreadRunning = false; } } LogDebug("Connection thread exiting\n"); switch (m_ServerType) { case CONNECTION_TYPE_CLIENT_TO_SECTOR_SERVER: g_ServerMgr->m_ConnectionCount--; if (g_ServerMgr->m_ConnectionCount == 0) { LogMessage("Client connections terminated\n"); g_ServerMgr->m_SectorConnection = (0); } break; case CONNECTION_TYPE_CLIENT_TO_MASTER_SERVER: g_ServerMgr->m_MasterConnection = (0); break; case CONNECTION_TYPE_SECTOR_SERVER_TO_PROXY: case CONNECTION_TYPE_GLOBAL_PROXY_TO_SERVER: g_ServerMgr->m_UDPConnection->BlankTCPConnection(); break; default: break; } m_TcpThreadRunning = false; m_ConnectionActive = false; ResumeThread(m_SendThreadHandle); }
/* 输出TCP会话信息 */ void OutputTcplSession( struct TcplStatEnv *p_env , const struct pcap_pkthdr *pcaphdr , struct TcplSession *p_tcpl_session , unsigned char before_free_flag ) { struct TcplPacket *p_tcpl_packet = NULL ; struct TcplPacket *p_next_tcpl_packet = NULL ; if( p_env->cmd_line_para.output_session ) { struct timeval total_elapse ; double avg_packet_elapse ; double avg_oppo_packet_elapse ; /* 计算连接总耗时 */ COPY_TIMEVAL( total_elapse , p_env->fixed_timestamp ); DIFF_TIMEVAL( total_elapse , p_tcpl_session->begin_timestamp ) if( p_tcpl_session->total_packet_trace_count > 0 ) avg_packet_elapse = (p_tcpl_session->total_packet_elapse_for_avg.tv_sec*1000000+p_tcpl_session->total_packet_elapse_for_avg.tv_usec) / p_tcpl_session->total_packet_trace_count ; else avg_packet_elapse = 0 ; if( p_tcpl_session->total_packet_trace_count > 0 ) avg_oppo_packet_elapse = (p_tcpl_session->total_oppo_packet_elapse_for_avg.tv_sec*1000000+p_tcpl_session->total_oppo_packet_elapse_for_avg.tv_usec) / p_tcpl_session->total_packet_trace_count ; else avg_oppo_packet_elapse = 0 ; /* 输出TCP会话统计信息 */ fprintf( p_env->fp , "S %c [%s:%d]->[%s:%d] | %s.%06ld | %ld.%06ld | %ld.%06ld %ld.%06ld , %ld.%06ld %.6lf %ld.%06ld %ld.%06ld %.6lf %ld.%06ld , %ld.%06ld %ld.%06ld %ld.%06ld | %u %u\n" , p_tcpl_session->continue_trace_flag==0?'|':'-' , p_tcpl_session->tcpl_addr_hr.src_ip , p_tcpl_session->tcpl_addr_hr.src_port , p_tcpl_session->tcpl_addr_hr.dst_ip , p_tcpl_session->tcpl_addr_hr.dst_port , ConvDateTimeHumanReadable(p_tcpl_session->begin_timestamp.tv_sec) , p_tcpl_session->begin_timestamp.tv_usec , total_elapse.tv_sec , total_elapse.tv_usec , p_tcpl_session->wait_for_second_syn_and_first_ack_elapse.tv_sec , p_tcpl_session->wait_for_second_syn_and_first_ack_elapse.tv_usec , p_tcpl_session->wait_for_after_syn_and_second_ack_elapse.tv_sec , p_tcpl_session->wait_for_after_syn_and_second_ack_elapse.tv_usec , p_tcpl_session->min_packet_elapse.tv_sec , p_tcpl_session->min_packet_elapse.tv_usec , avg_packet_elapse/1000000 , p_tcpl_session->max_packet_elapse.tv_sec , p_tcpl_session->max_packet_elapse.tv_usec , p_tcpl_session->min_oppo_packet_elapse.tv_sec , p_tcpl_session->min_oppo_packet_elapse.tv_usec , avg_oppo_packet_elapse/1000000 , p_tcpl_session->max_oppo_packet_elapse.tv_sec , p_tcpl_session->max_oppo_packet_elapse.tv_usec , p_tcpl_session->wait_for_first_fin_elapse.tv_sec , p_tcpl_session->wait_for_first_fin_elapse.tv_usec , p_tcpl_session->wait_for_second_fin_and_first_ack_elapse.tv_sec , p_tcpl_session->wait_for_second_fin_and_first_ack_elapse.tv_usec , p_tcpl_session->wait_for_second_ack_elapse.tv_sec , p_tcpl_session->wait_for_second_ack_elapse.tv_usec , p_tcpl_session->total_packet_trace_count , p_tcpl_session->total_packet_trace_data_len ); } /* 输出TCP分组明细统计信息 */ list_for_each_entry_safe( p_tcpl_packet , p_next_tcpl_packet , & (p_tcpl_session->tcpl_packets_trace_list.this_node) , struct TcplPacket , this_node ) { char *direct_string = NULL ; if( p_env->cmd_line_para.output_session_packet && p_tcpl_packet->is_outputed == 0 ) { if( p_tcpl_packet->direction_flag == 1 ) direct_string = "->" ; else direct_string = "<-" ; fprintf( p_env->fp , "P | %s.%06ld | %ld.%06ld %ld.%06ld | [%s:%d]%s[%s:%d] | %s %u\n" , ConvDateTimeHumanReadable(p_tcpl_packet->timestamp.tv_sec) , p_tcpl_packet->timestamp.tv_usec , p_tcpl_packet->last_packet_elapse.tv_sec , p_tcpl_packet->last_packet_elapse.tv_usec , p_tcpl_packet->last_oppo_packet_elapse.tv_sec , p_tcpl_packet->last_oppo_packet_elapse.tv_usec , p_tcpl_session->tcpl_addr_hr.src_ip , p_tcpl_session->tcpl_addr_hr.src_port , direct_string , p_tcpl_session->tcpl_addr_hr.dst_ip , p_tcpl_session->tcpl_addr_hr.dst_port , p_tcpl_packet->packet_flags , p_tcpl_packet->packet_data_len_actually ); if( p_env->cmd_line_para.output_session_packet_data ) { if( p_tcpl_packet->packet_data_len_intercepted > 0 ) { DumpBuffer( p_env->fp , "D | " , p_tcpl_packet->packet_data_len_intercepted , p_tcpl_packet->packet_data_intercepted ); } } p_tcpl_packet->is_outputed = 1 ; } if( before_free_flag || ( p_tcpl_packet != p_tcpl_session->p_recent_packet && p_tcpl_packet != p_tcpl_session->p_recent_oppo_packet ) ) { /* 每输出一条明细,删除一条 */ p_tcpl_session->total_packet_trace_count--; p_tcpl_session->total_packet_trace_data_len -= p_tcpl_packet->packet_data_len_actually ; if( p_env->unused_tcpl_packet_count < PENV_MAX_UNUSED_TCPLPACKET_COUNT ) { RECYCLING_TCPL_PACKET( p_env , p_tcpl_packet ) } else { DELETE_TCPL_PACKET( p_env , p_tcpl_packet ) } } }
static ssize_t lpc_read( struct file *file, char *buf, size_t count, loff_t *off ) { // int flags; int idx; int len; u8 *p; register DEV *dev = (DEV *)(file->private_data); if(count < 0) return -EINVAL; dbg1("%s(): dev=%08X", __FUNCTION__, (uint)dev); // DbgFlush(); idx = dev->inhead; #if 0 CLI; if( idx == dev->intail ) { if(file->f_flags & O_NONBLOCK) { STI; return -EWOULDBLOCK; } interruptible_sleep_on( &dev->rd_wait ); /* The next line produces compiling errors, so I use a workaround if( current->signal & ~current->blocked ) return -ERESTARTSYS; */ if( idx == dev->intail ) return -ERESTARTSYS; } STI; #else // if (qempty(&dev->ReadBufferQueue)) if (idx == dev->intail) { dbg1("%s(): qempty", __FUNCTION__); // up (&dev->sem); if (file->f_flags & O_NONBLOCK) { dbg1("%s()=-EAGAIN !!!", __FUNCTION__); return -EAGAIN; // -EWOULDBLOCK; } // if (wait_event_interruptible(dev->rd_wait, qhasdata(&dev->ReadBufferQueue))) if (wait_event_interruptible(dev->rd_wait, (idx != dev->intail) )) { dbg1("%s(): dev=%08X return -ERESTARTSYS", __FUNCTION__, (uint)dev); return -ERESTARTSYS; /* signal: tell the fs layer to handle it */ } dbg8("%s(): nach wait_event_interruptible(rd_wait)", __FUNCTION__); // if (down_interruptible(&dev->sem)) // return -ERESTARTSYS; } #endif p = dev->inbuf[idx]; #if 0 // link layer -> app layer len = p[0]; p[0] = p[1]; p[1] = (u8)(len - 1); if( count > len + 1 ) count = len + 1; #else len = p[1]+2; if (count > len) count = len; #endif if (debug & DEBUG_DUMP1) DumpBuffer("< ", p, count); if (copy_to_user(buf, p, count)) return -EFAULT; idx++; if(idx >= NUM_INBUF) idx = 0; dev->inhead = idx; dbg1("%s(): dev=%08X return %d", __FUNCTION__, (uint)dev, count); return count; }