void netstackUDPIPProcess(unsigned int len, udpip_hdr* packet) { uint16_t payloadlen = 0; uint8_t* payloaddata = 0; uint16_t i; // get UDP payload length payloadlen = htons(packet->udp.udplen); payloadlen -= 8; // subtract header // get UDP payload data payloaddata = &((unsigned char*)packet)[IP_HEADER_LEN+UDP_HEADER_LEN]; rprintf("UDP packet, len: %d\r\n", len); //debugPrintHexTable(len, (unsigned char*)packet); if (packet->udp.destport == HTONS(CONTROL_PORT)) { // command packet processCommand(payloadlen, payloaddata); } else if (packet->udp.destport == HTONS(SERIAL_PORT)) { // serial output for (i=0; i<payloadlen; i++) uartSendByte(payloaddata[i]); } else if (packet->udp.destport == HTONS(LOOPBACK_PORT)) { // loopback - return packet to sender udpSend(htonl(packet->ip.srcipaddr), LOOPBACK_PORT, payloadlen, payloaddata); } }
void dhcpRequest(void) { struct netDhcpHeader* packet; uint32_t val; packet = (struct netDhcpHeader*)&netstackGetBuffer()[ETH_HEADER_LEN+IP_HEADER_LEN+UDP_HEADER_LEN]; // build BOOTP/DHCP header packet->bootp.op = BOOTP_OP_BOOTREQUEST; // request type packet->bootp.htype = BOOTP_HTYPE_ETHERNET; packet->bootp.hlen = BOOTP_HLEN_ETHERNET; packet->bootp.ciaddr = htonl(ipGetConfig()->ip); packet->bootp.yiaddr = HTONL(0l); packet->bootp.siaddr = HTONL(0l); packet->bootp.giaddr = HTONL(0l); nicGetMacAddress(&packet->bootp.chaddr[0]); // fill client hardware address packet->bootp.xid = DhcpTransactID; packet->bootp.flags = HTONS(1); // build DHCP request // begin with magic cookie packet->cookie = 0x63538263; // set operation val = DHCP_MSG_DHCPDISCOVER; dhcpSetOption(packet->options, DHCP_OPT_DHCPMSGTYPE, 1, &val); #ifdef DHCP_DEBUG rprintfProgStrM("DHCP: Sending Query\r\n"); //dhcpPrintHeader(packet); #endif // send request udpSend(0xFFFFFFFF, DHCP_UDP_SERVER_PORT, DHCP_HEADER_LEN+3+1, (uint8_t*)packet); }
/// a useful function to write a UDP packet prefixed by a timestamp /// and formatted with printf semantics. void udpwrite(const char *s,...){ va_list args; va_start(args,s); char buf[1024]; sprintf(buf,"time=%f ",gettime()); vsnprintf(buf+strlen(buf),1024-strlen(buf),s,args); //printf("%s\n",buf); udpSend(serverAddr,outport,buf); // SEND TO va_end(args); }
void procPerMessage::dnsSend(int protocol_id, Message* msg) { //Add header and send dnsHeader *header = new dnsHeader; header->hlp = protocol_id; header->m_size = msg->msgLen(); msg->msgAddHdr((char *)header, sizeof(dnsHeader)); udpSend(DNS_ID, msg); delete header; }
// Thread function void* signalerTaskFunction(void *arg) { (void)arg; for (;;) { // Wait for notification from UDP sem_wait(¬ify_sem); udpSend("SIGNAL_ACK"); } return NULL; }
void serviceLocal(void) { int c; unsigned char buffer[100]; if ( (c = uartGetByte()) != -1) { // echo command to terminal rprintfChar(c); // process command switch (c) { case 'i': rprintfProgStrM("\r\nInitializing Ethernet Controller\r\n"); nicInit(); break; case 'd': rprintfProgStrM("\r\nEthernet Controller State\r\n"); nicRegDump(); break; case 't': rprintfProgStrM("\r\nCurrent Uptime: "); rprintfNum(10, 9, FALSE, ' ', UptimeMs); rprintfProgStrM("ms\r\n"); break; case 'c': rprintfProgStrM("\r\nCrashing System....\r\n"); while(1); break; case 'u': rprintfProgStrM("\r\nSending UDP packet\r\n"); strcpy((char*)&buffer[ETH_HEADER_LEN+IP_HEADER_LEN+UDP_HEADER_LEN], "hello"); udpSend((ipGetConfig()->ip|~ipGetConfig()->netmask), CONTROL_PORT, 6, &buffer[ETH_HEADER_LEN+IP_HEADER_LEN+UDP_HEADER_LEN]); break; case '?': rprintfProgStrM("\r\nCommands:\r\n"); rprintfProgStrM("(i) Initialize Ethernet Controller\r\n"); rprintfProgStrM("(d) Dump Ethernet Controller State\r\n"); rprintfProgStrM("(u) Send Broadcast UDP frame\r\n"); rprintfProgStrM("(t) Print current uptime\r\n"); rprintfProgStrM("(?) Help\r\n"); break; case '\n': default: break; } // print new prompt rprintfProgStrM("\r\ncmd>"); } }
void dhcpRelease(void) { struct netDhcpHeader* packet; uint32_t val; uint8_t* optptr; packet = (struct netDhcpHeader*)&netstackGetBuffer()[ETH_HEADER_LEN+IP_HEADER_LEN+UDP_HEADER_LEN]; // build BOOTP/DHCP header packet->bootp.op = BOOTP_OP_BOOTREQUEST; // request type packet->bootp.htype = BOOTP_HTYPE_ETHERNET; packet->bootp.hlen = BOOTP_HLEN_ETHERNET; packet->bootp.ciaddr = htonl(ipGetConfig()->ip); packet->bootp.yiaddr = HTONL(0l); packet->bootp.siaddr = HTONL(0l); packet->bootp.giaddr = HTONL(0l); nicGetMacAddress(&packet->bootp.chaddr[0]); // fill client hardware address packet->bootp.xid = DhcpTransactID; // set trans ID (use part of MAC address) packet->bootp.flags = HTONS(1); // build DHCP request // begin with magic cookie packet->cookie = 0x63538263; // set operation val = DHCP_MSG_DHCPRELEASE; optptr = dhcpSetOption(packet->options, DHCP_OPT_DHCPMSGTYPE, 1, &val); // set the server ID val = htonl(DhcpServerIP); optptr = dhcpSetOption(optptr, DHCP_OPT_SERVERID, 4, &val); // request the IP previously offered optptr = dhcpSetOption(optptr, DHCP_OPT_REQUESTEDIP, 4, &packet->bootp.ciaddr); #ifdef DHCP_DEBUG rprintfProgStrM("DHCP: Sending Release to "); netPrintIPAddr(DhcpServerIP); rprintfCRLF(); //dhcpPrintHeader(packet); #endif // send release udpSend(DhcpServerIP, DHCP_UDP_SERVER_PORT, DHCP_HEADER_LEN+3+6+6+1, (uint8_t*)packet); // deconfigure ip addressing ipSetConfig(0,0,0); DhcpLeaseTime = 0; }
void pwmCompleteMotorUpdate(uint8_t motorCount) { UNUSED(motorCount); // send to simulator // for gazebo8 ArduCopterPlugin remap, normal range = [0.0, 1.0], 3D rang = [-1.0, 1.0] double outScale = 1000.0; if (feature(FEATURE_3D)) { outScale = 500.0; } pwmPkt.motor_speed[3] = motorsPwm[0] / outScale; pwmPkt.motor_speed[0] = motorsPwm[1] / outScale; pwmPkt.motor_speed[1] = motorsPwm[2] / outScale; pwmPkt.motor_speed[2] = motorsPwm[3] / outScale; // get one "fdm_packet" can only send one "servo_packet"!! if (pthread_mutex_trylock(&updateLock) != 0) return; udpSend(&pwmLink, &pwmPkt, sizeof(servo_packet)); // printf("[pwm]%u:%u,%u,%u,%u\n", idlePulse, motorsPwm[0], motorsPwm[1], motorsPwm[2], motorsPwm[3]); }
int sendBuf( rbudpSender_t *rbudpSender, void * buffer, int bufSize, int sendRate, int packetSize ) { int done = 0; int status = 0; struct timeval curTime, startTime; double srate; gettimeofday( &curTime, NULL ); startTime = curTime; int lastRemainNumberOfPackets = 0; int noProgressCnt = 0; initSendRudp( rbudpSender, buffer, bufSize, sendRate, packetSize ); while ( !done ) { // blast UDP packets if ( rbudpSender->rbudpBase.verbose > 1 ) { TRACE_DEBUG( "sending UDP packets" ); } reportTime( &curTime ); status = udpSend( rbudpSender ); if ( status < 0 ) { return status; } srate = ( double ) rbudpSender->rbudpBase.remainNumberOfPackets * rbudpSender->rbudpBase.payloadSize * 8 / ( double ) reportTime( &curTime ); if ( rbudpSender->rbudpBase.verbose > 1 ) { TRACE_DEBUG( "real sending rate in this send is %f", srate ); } if ( lastRemainNumberOfPackets == 0 ) { lastRemainNumberOfPackets = rbudpSender->rbudpBase.remainNumberOfPackets; } // send end of UDP signal if ( rbudpSender->rbudpBase.verbose > 1 ) TRACE_DEBUG( "send to socket %d an end signal.", rbudpSender->rbudpBase.tcpSockfd ); if ( rbudpSender->rbudpBase.verbose > 1 ) { fprintf( stderr, "write %d bytes.\n", ( int ) sizeof( rbudpSender->rbudpBase.endOfUdp ) ); } int error_code = writen( rbudpSender->rbudpBase.tcpSockfd, ( char * )&rbudpSender->rbudpBase.endOfUdp, sizeof( rbudpSender->rbudpBase.endOfUdp ) ); if ( error_code < 0 ) { rodsLog( LOG_ERROR, "writen failed in sendBuf with error code %d", error_code ); } rbudpSender->rbudpBase.endOfUdp.round ++; reportTime( &curTime ); gettimeofday( &curTime, NULL ); if ( rbudpSender->rbudpBase.verbose > 1 ) { TRACE_DEBUG( "Current time: %d %ld", curTime.tv_sec, curTime.tv_usec ); } // receive error list if ( rbudpSender->rbudpBase.verbose > 1 ) { TRACE_DEBUG( "waiting for error bitmap" ); } int n = readn( rbudpSender->rbudpBase.tcpSockfd, rbudpSender->rbudpBase.errorBitmap, rbudpSender->rbudpBase.sizeofErrorBitmap ); if ( n < 0 ) { perror( "read" ); return errno ? ( -1 * errno ) : -1; } if ( ( unsigned char )rbudpSender->rbudpBase.errorBitmap[0] == 1 ) { done = 1; rbudpSender->rbudpBase.remainNumberOfPackets = 0; if ( rbudpSender->rbudpBase.verbose > 1 ) { TRACE_DEBUG( "done." ); } } else { rbudpSender->rbudpBase.remainNumberOfPackets = updateHashTable( &rbudpSender->rbudpBase ); if ( rbudpSender->rbudpBase.remainNumberOfPackets >= lastRemainNumberOfPackets ) { noProgressCnt++; if ( noProgressCnt >= MAX_NO_PROGRESS_CNT ) { return SYS_UDP_TRANSFER_ERR - errno; } } else { lastRemainNumberOfPackets = rbudpSender->rbudpBase.remainNumberOfPackets; noProgressCnt = 0; } } if ( rbudpSender->rbudpBase.isFirstBlast ) { rbudpSender->rbudpBase.isFirstBlast = 0; double lossRate = ( double )rbudpSender->rbudpBase.remainNumberOfPackets / ( double )rbudpSender->rbudpBase.totalNumberOfPackets; // if (rbudpSender->rbudpBase.remainNumberOfPackets > 0) // usecsPerPacket = (int) ((double)usecsPerPacket / (1.0 - lossRate - 0.05)); if ( rbudpSender->rbudpBase.verbose > 0 ) { float dt = ( curTime.tv_sec - startTime.tv_sec ) + 1e-6 * ( curTime.tv_usec - startTime.tv_usec ); float mbps = 1e-6 * 8 * bufSize / ( dt == 0 ? .01 : dt ); TRACE_DEBUG( "loss rate: %f on %dK in %.3f seconds (%.2f Mbits/s)", lossRate, ( int )bufSize >> 10, dt, mbps ); if ( rbudpSender->rbudpBase.verbose > 1 ) TRACE_DEBUG( "usecsPerPacket updated to %d", rbudpSender->rbudpBase.usecsPerPacket ); } }
void dhcpIn(unsigned int len, struct netDhcpHeader* packet) { uint8_t msgtype; uint32_t sid; uint8_t* optptr; uint32_t val; uint32_t netmask; uint32_t gateway; #if NET_DEBUG >= 3 dhcpPrintHeader(packet); #endif // check that this is a reply, and for me if ((packet->bootp.op != BOOTP_OP_BOOTREPLY) || (packet->bootp.xid != DhcpTransactID)) return; // process incoming packet // check reply type dhcpGetOption(packet->options, DHCP_OPT_DHCPMSGTYPE, 1, &msgtype); #if NET_DEBUG >= 2 rprintf("DHCP: Received msgtype = %d\r\n", msgtype); #endif if (msgtype == DHCP_MSG_DHCPOFFER) { // get DHCP server ID dhcpGetOption(packet->options, DHCP_OPT_SERVERID, 4, &sid); #ifdef DHCP_DEBUG rprintfProgStrM("DHCP: Got offer from server "); netPrintIPAddr(htonl(sid)); rprintfCRLF(); #endif // build DHCP request (on top of this reply) packet->bootp.op = BOOTP_OP_BOOTREQUEST; // request type // set operation val = DHCP_MSG_DHCPREQUEST; optptr = dhcpSetOption(packet->options, DHCP_OPT_DHCPMSGTYPE, 1, &val); // set the server ID optptr = dhcpSetOption(optptr, DHCP_OPT_SERVERID, 4, &sid); // request the IP previously offered optptr = dhcpSetOption(optptr, DHCP_OPT_REQUESTEDIP, 4, &packet->bootp.yiaddr); // request additional information ((uint8_t*)&val)[0] = DHCP_OPT_NETMASK; ((uint8_t*)&val)[1] = DHCP_OPT_ROUTERS; ((uint8_t*)&val)[2] = DHCP_OPT_DNSSERVERS; ((uint8_t*)&val)[3] = DHCP_OPT_DOMAINNAME; optptr = dhcpSetOption(optptr, DHCP_OPT_PARAMREQLIST, 4, &val); #ifdef DHCP_DEBUG rprintfProgStrM("DHCP: Sending request in response to offer\r\n"); #endif // send DHCP request DhcpServerIP = htonl(sid); udpSend(DhcpServerIP, DHCP_UDP_SERVER_PORT, DHCP_HEADER_LEN+3+6+6+6+1, (uint8_t*)packet); } else if (msgtype == DHCP_MSG_DHCPACK) { // get netmask dhcpGetOption(packet->options, DHCP_OPT_NETMASK, 4, &val); netmask = htonl(val); // get gateway dhcpGetOption(packet->options, DHCP_OPT_ROUTERS, 4, &val); gateway = htonl(val); // get lease time dhcpGetOption(packet->options, DHCP_OPT_LEASETIME, 4, &val); DhcpLeaseTime = htonl(val); // assign new network info ipSetConfig(htonl(packet->bootp.yiaddr), netmask, gateway); #ifdef DHCP_DBUG rprintf("DHCP: Got request ACK, bind complete\r\n"); //debugPrintHexTable(len-DHCP_HEADER_LEN, (packet->options)); // print info ipPrintConfig(ipGetConfig()) rprintfProgStrM("LeaseTm : "); rprintfNum(10, 8, FALSE, ' ', DhcpLeaseTime); rprintfCRLF(); #endif } }
void wmpImage(int *state) { int rc = 0; char *addr = (char *)wtpinfoGetACIPStr(); char *dir = (char *)wtpInfoGetBoardName(); char *file = S_img.name; char *imgdwn = "/sbin/imgdwn.sh %s %s %s"; char *imgwr = "/sbin/imgwr.sh %s"; char cmd[1024] = { 0 }; WMMSG msg; BUFF attr; uint16_t seqnum = 0; uint8_t *apid = NULL; if (snprintf(cmd, sizeof(cmd), imgdwn, addr, dir, file) < 1) { logError("snprintf : %s", strerror(errno)); rc = -1; goto out; } // 下载固件 if (utilDoCMD(cmd)) { logError("Down firmware error"); rc = -1; goto out; } // 对比固件MD5 if (imageFileMD5Chk(file, S_img.filehash)) { logError("Image file \"%s\" MD5 hash is error"); rc = -1; goto out; } // 写固件 memset(cmd, 0, sizeof(cmd)); if (snprintf(cmd, sizeof(cmd), imgwr, file) < 1) { logError("snprintf : %s", strerror(errno)); rc = -1; goto out; } if (utilDoCMD(cmd)) { logError("Write firmware error"); rc = -1; } out : apid = (uint8_t *)wtpidGetBytes(); seqnum = wtpInfoGetSEQNUM(); wmmClearInit(&msg, apid, seqnum, WMM_CODE_IMGUP_REP); if (0 == rc) { // 报告AC固件处理完毕,准备重启 wmmPackResCode(&attr, WMM_RESULT_CODE_OK); } else { // 报告AC固件处理出现错误,准备重启 wmmPackResCode(&attr, WMM_RESULT_CODE_FAILED); } wmmPutAttrBuff(&msg, &attr); if (udpSend(G_wmpsock, msg.buff, msg.offset, &G_wmpaddr) < 1) { logError("sendto : %s", strerror(errno)); } sleep(10); logError("Now Reboot!!!"); utilDoCMD("reboot"); }
void sendMotorUpdate() { udpSend(&pwmLink, &pwmPkt, sizeof(servo_packet)); }
/* Process a specific test case. File name is provided. * Needs to return 0 if all is OK, something else otherwise. */ int processTestFile(int fd, char *pszFileName) { FILE *fp; char *testdata = NULL; char *expected = NULL; int ret = 0; size_t lenLn; char buf[4096]; if((fp = fopen((char*)pszFileName, "r")) == NULL) { perror((char*)pszFileName); return(2); } /* skip comments at start of file */ while(!feof(fp)) { getline(&testdata, &lenLn, fp); while(!feof(fp)) { if(*testdata == '#') getline(&testdata, &lenLn, fp); else break; /* first non-comment */ } /* this is not perfect, but works ;) */ if(feof(fp)) break; ++iTests; /* increment test count, we now do one! */ testdata[strlen(testdata)-1] = '\0'; /* remove \n */ /* now we have the test data to send (we could use function pointers here...) */ unescapeTestdata(testdata); if(inputMode == inputUDP) { if(udpSend(testdata, strlen(testdata)) != 0) return(2); } else { if(tcpSend(testdata, strlen(testdata)) != 0) return(2); } /* next line is expected output * we do not care about EOF here, this will lead to a failure and thus * draw enough attention. -- rgerhards, 2009-03-31 */ getline(&expected, &lenLn, fp); expected[strlen(expected)-1] = '\0'; /* remove \n */ /* pull response from server and then check if it meets our expectation */ readLine(fd, buf); if(strcmp(expected, buf)) { ++iFailed; printf("\nExpected Response:\n'%s'\nActual Response:\n'%s'\n", expected, buf); ret = 1; } /* we need to free buffers, as we have potentially modified them! */ free(testdata); testdata = NULL; free(expected); expected = NULL; } free(expected); fclose(fp); return(ret); }
/* Main */ int main(int argc, char ** argv) { struct sockaddr_in inaddr; socklen_t inaddrlen; struct timeval timeout; ssl_t *ssl; serverDtls_t *dtlsCtx; SOCKET sock; fd_set readfd; unsigned char *sslBuf, *recvfromBuf, *CAstream; #ifdef USE_DTLS_DEBUG_TRACE unsigned char *addrstr; #endif #if !defined(ID_PSK) && !defined(ID_DHE_PSK) unsigned char *keyValue, *certValue; int32 keyLen, certLen; #endif sslKeys_t *keys; int32 freeBufLen, rc, val, recvLen, err, CAstreamLen; int32 sslBufLen, rcr, rcs, sendLen, recvfromBufLen; sslSessOpts_t options; #ifdef WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(1, 1), &wsaData); #endif rc = 0; ssl = NULL; dtlsCtx = NULL; sock = INVALID_SOCKET; /* parse input arguments */ if (0 != process_cmd_options(argc, argv)) { usage(); return 0; } if (sigsetup() < 0) { _psTrace("Init error creating signal handlers\n"); return DTLS_FATAL; } if (matrixSslOpen() < 0) { _psTrace("Init error opening MatrixDTLS library\n"); return DTLS_FATAL; } if (matrixSslNewKeys(&keys, NULL) < 0) { _psTrace("Init error allocating key structure\n"); matrixSslClose(); return DTLS_FATAL; } if ((rc = initClientList(MAX_CLIENTS)) < 0) { _psTrace("Init error opening client list\n"); goto MATRIX_EXIT; } recvfromBufLen = matrixDtlsGetPmtu(); if ((recvfromBuf = psMalloc(MATRIX_NO_POOL, recvfromBufLen)) == NULL) { rc = PS_MEM_FAIL; _psTrace("Init error allocating receive buffer\n"); goto CLIENT_EXIT; } #ifdef USE_HEADER_KEYS /* In-memory based keys Build the CA list first for potential client auth usage */ CAstreamLen = 0; #ifdef USE_RSA CAstreamLen += sizeof(RSACAS); #ifdef USE_ECC CAstreamLen += sizeof(ECDHRSACAS); #endif #endif #ifdef USE_ECC CAstreamLen += sizeof(ECCAS); #endif CAstream = psMalloc(NULL, CAstreamLen); CAstreamLen = 0; #ifdef USE_RSA memcpy(CAstream, RSACAS, sizeof(RSACAS)); CAstreamLen += sizeof(RSACAS); #ifdef USE_ECC memcpy(CAstream + CAstreamLen, ECDHRSACAS, sizeof(ECDHRSACAS)); CAstreamLen += sizeof(ECDHRSACAS); #endif #endif #ifdef USE_ECC memcpy(CAstream + CAstreamLen, ECCAS, sizeof(ECCAS)); CAstreamLen += sizeof(ECCAS); #endif #ifdef EXAMPLE_RSA_KEYS switch (g_rsaKeySize) { case 1024: certValue = (unsigned char *)RSA1024; certLen = sizeof(RSA1024); keyValue = (unsigned char *)RSA1024KEY; keyLen = sizeof(RSA1024KEY); break; case 2048: certValue = (unsigned char *)RSA2048; certLen = sizeof(RSA2048); keyValue = (unsigned char *)RSA2048KEY; keyLen = sizeof(RSA2048KEY); break; case 3072: certValue = (unsigned char *)RSA3072; certLen = sizeof(RSA3072); keyValue = (unsigned char *)RSA3072KEY; keyLen = sizeof(RSA3072KEY); break; case 4096: certValue = (unsigned char *)RSA4096; certLen = sizeof(RSA4096); keyValue = (unsigned char *)RSA4096KEY; keyLen = sizeof(RSA4096KEY); break; default: _psTraceInt("Invalid RSA key length (%d)\n", g_rsaKeySize); return -1; } if ((rc = matrixSslLoadRsaKeysMem(keys, (const unsigned char *)certValue, certLen, (const unsigned char *)keyValue, keyLen, CAstream, CAstreamLen)) < 0) { _psTrace("No certificate material loaded. Exiting\n"); psFree(CAstream, NULL); matrixSslDeleteKeys(keys); matrixSslClose(); return rc; } #endif #ifdef EXAMPLE_ECDH_RSA_KEYS switch (g_ecdhKeySize) { case 256: certValue = (unsigned char *)ECDHRSA256; certLen = sizeof(ECDHRSA256); keyValue = (unsigned char *)ECDHRSA256KEY; keyLen = sizeof(ECDHRSA256KEY); break; case 521: certValue = (unsigned char *)ECDHRSA521; certLen = sizeof(ECDHRSA521); keyValue = (unsigned char *)ECDHRSA521KEY; keyLen = sizeof(ECDHRSA521KEY); break; default: _psTraceInt("Invalid ECDH_RSA key length (%d)\n", g_ecdhKeySize); return -1; } if ((rc = matrixSslLoadEcKeysMem(keys, (const unsigned char *)certValue, certLen, (const unsigned char *)keyValue, keyLen, CAstream, CAstreamLen)) < 0) { _psTrace("No certificate material loaded. Exiting\n"); psFree(CAstream, NULL); matrixSslDeleteKeys(keys); matrixSslClose(); return rc; } #endif #ifdef EXAMPLE_EC_KEYS switch (g_eccKeySize) { case 192: certValue = (unsigned char *)EC192; certLen = sizeof(EC192); keyValue = (unsigned char *)EC192KEY; keyLen = sizeof(EC192KEY); break; case 224: certValue = (unsigned char *)EC224; certLen = sizeof(EC224); keyValue = (unsigned char *)EC224KEY; keyLen = sizeof(EC224KEY); break; case 256: certValue = (unsigned char *)EC256; certLen = sizeof(EC256); keyValue = (unsigned char *)EC256KEY; keyLen = sizeof(EC256KEY); break; case 384: certValue = (unsigned char *)EC384; certLen = sizeof(EC384); keyValue = (unsigned char *)EC384KEY; keyLen = sizeof(EC384KEY); break; case 521: certValue = (unsigned char *)EC521; certLen = sizeof(EC521); keyValue = (unsigned char *)EC521KEY; keyLen = sizeof(EC521KEY); break; default: _psTraceInt("Invalid ECC key length (%d)\n", g_eccKeySize); return -1; } if ((rc = matrixSslLoadEcKeysMem(keys, certValue, certLen, keyValue, keyLen, CAstream, CAstreamLen)) < 0) { _psTrace("No certificate material loaded. Exiting\n"); psFree(CAstream, NULL); matrixSslDeleteKeys(keys); matrixSslClose(); return rc; } #endif #ifdef REQUIRE_DH_PARAMS if (matrixSslLoadDhParamsMem(keys, DHPARAM2048, DHPARAM2048_SIZE) < 0) { _psTrace("Unable to load DH parameters\n"); } #endif /* DH_PARAMS */ psFree(CAstream, NULL); #else /* USE_HEADER_KEYS */ /* File based keys Build the CA list first for potential client auth usage */ CAstreamLen = 0; #ifdef USE_RSA if (g_rsaKeySize == 3072) CAstreamLen += (int32)strlen(rsaCA3072File) + 1; else CAstreamLen += (int32)strlen(rsaCAFile) + 1; #ifdef USE_ECC CAstreamLen += (int32)strlen(ecdhRsaCAFile) + 1; #endif #endif #ifdef USE_ECC CAstreamLen += (int32)strlen(ecCAFile) + 1; #endif CAstream = psMalloc(NULL, CAstreamLen); memset(CAstream, 0x0, CAstreamLen); CAstreamLen = 0; #ifdef USE_RSA if (g_rsaKeySize == 3072) { memcpy(CAstream, rsaCA3072File, strlen(rsaCA3072File)); CAstreamLen += strlen(rsaCA3072File); } else { memcpy(CAstream, rsaCAFile, strlen(rsaCAFile)); CAstreamLen += strlen(rsaCAFile); } #ifdef USE_ECC memcpy(CAstream + CAstreamLen, ";", 1); CAstreamLen++; memcpy(CAstream + CAstreamLen, ecdhRsaCAFile, strlen(ecdhRsaCAFile)); CAstreamLen += strlen(ecdhRsaCAFile); #endif #endif #ifdef USE_ECC if (CAstreamLen > 0) { memcpy(CAstream + CAstreamLen, ";", 1); CAstreamLen++; } memcpy(CAstream + CAstreamLen, ecCAFile, strlen(ecCAFile)); #endif /* Load Identiy */ #ifdef EXAMPLE_RSA_KEYS if ((rc = matrixSslLoadRsaKeys(keys, rsaCertFile, rsaPrivkeyFile, NULL, (char*)CAstream)) < 0) { _psTrace("No certificate material loaded. Exiting\n"); psFree(CAstream); matrixSslDeleteKeys(keys); matrixSslClose(); return rc; } #endif #ifdef EXAMPLE_ECDH_RSA_KEYS if ((rc = matrixSslLoadEcKeys(keys, ecdhRsaCertFile, ecdhRsaPrivkeyFile, NULL, (char*)CAstream)) < 0) { _psTrace("No certificate material loaded. Exiting\n"); psFree(CAstream); matrixSslDeleteKeys(keys); matrixSslClose(); return rc; } #endif #ifdef EXAMPLE_EC_KEYS if ((rc = matrixSslLoadEcKeys(keys, ecCertFile, ecPrivkeyFile, NULL, (char*)CAstream)) < 0) { _psTrace("No certificate material loaded. Exiting\n"); psFree(CAstream); matrixSslDeleteKeys(keys); matrixSslClose(); return rc; } #endif #ifdef REQUIRE_DH_PARAMS if (matrixSslLoadDhParams(keys, dhParamFile) < 0) { _psTrace("Unable to load DH parameters\n"); } #endif psFree(CAstream); #endif /* USE_HEADER_KEYS */ #ifdef USE_PSK_CIPHER_SUITE /* The first ID is considered as null-terminiated string for compatibility with OpenSSL's s_client default client identity "Client_identity" */ matrixSslLoadPsk(keys, PSK_HEADER_TABLE[0].key, sizeof(PSK_HEADER_TABLE[0].key), PSK_HEADER_TABLE[0].id, strlen((const char *)PSK_HEADER_TABLE[0].id)); for (rc = 1; rc < PSK_HEADER_TABLE_COUNT; rc++) { matrixSslLoadPsk(keys, PSK_HEADER_TABLE[rc].key, sizeof(PSK_HEADER_TABLE[rc].key), PSK_HEADER_TABLE[rc].id, sizeof(PSK_HEADER_TABLE[rc].id)); } #endif /* PSK */ if ((sock = newUdpSocket(NULL, DTLS_PORT, &err)) == INVALID_SOCKET) { _psTrace("Error creating UDP socket\n"); goto DTLS_EXIT; } _psTraceInt("DTLS server running on port %d\n", DTLS_PORT); /* Server loop */ for (exitFlag = 0; exitFlag == 0;) { timeout.tv_sec = 1; timeout.tv_usec = 0; FD_ZERO(&readfd); FD_SET(sock, &readfd); /* Always just wait a second for any incoming data. The primary loop mechanism reads data from one source and replies with handshake data if needed (that reply may be a resend if reading a repeat message). Individual client timeouts are then handled */ val = select(sock+1, &readfd, NULL, NULL, &timeout); if (val > 0 && FD_ISSET(sock, &readfd)) { psTraceIntDtls("Select woke %d\n", val); /* recvfrom data must always go into generic buffer becuase we don't yet know who it is from */ inaddrlen = sizeof(struct sockaddr_in); if ((recvLen = (int32)recvfrom(sock, recvfromBuf, recvfromBufLen, 0, (struct sockaddr *)&inaddr, &inaddrlen)) < 0) { #ifdef WIN32 if (SOCKET_ERRNO != EWOULDBLOCK && SOCKET_ERRNO != WSAECONNRESET) { #else if (SOCKET_ERRNO != EWOULDBLOCK) { #endif _psTraceInt("recvfrom error %d. Exiting\n", SOCKET_ERRNO); goto DTLS_EXIT; } continue; } #ifdef USE_DTLS_DEBUG_TRACE /* nice for debugging */ { const char *addrstr; addrstr = getaddrstring((struct sockaddr *)&inaddr, 1); psTraceIntDtls("Read %d bytes ", recvLen); psTraceStrDtls("from %s\n", (char*)addrstr); psFree(addrstr, NULL); } #endif /* Locate the SSL context of this receive and create a new session if not found */ if ((dtlsCtx = findClient(inaddr)) == NULL) { memset(&options, 0x0, sizeof(sslSessOpts_t)); options.versionFlag = SSL_FLAGS_DTLS; options.truncHmac = -1; if (matrixSslNewServerSession(&ssl, keys, certValidator, &options) < 0) { rc = DTLS_FATAL; goto DTLS_EXIT; } if ((dtlsCtx = registerClient(inaddr, sock, ssl)) == NULL) { /* Client list is full. Just have to ignore */ matrixSslDeleteSession(ssl); continue; } } ssl = dtlsCtx->ssl; /* Move socket data into internal buffer */ freeBufLen = matrixSslGetReadbuf(ssl, &sslBuf); psAssert(freeBufLen >= recvLen); psAssert(freeBufLen == matrixDtlsGetPmtu()); memcpy(sslBuf, recvfromBuf, recvLen); /* Notify SSL state machine that we've received more data into the ssl buffer retreived with matrixSslGetReadbuf. */ if ((rcr = matrixSslReceivedData(ssl, recvLen, &sslBuf, (uint32*)&freeBufLen)) < 0) { clearClient(dtlsCtx); continue; /* Next connection */ } /* Update last activity time and reset timeout*/ psGetTime(&dtlsCtx->lastRecvTime, NULL); dtlsCtx->timeout = MIN_WAIT_SECS; PROCESS_MORE_FROM_BUFFER: /* Process any incoming plaintext application data */ switch (rcr) { case MATRIXSSL_HANDSHAKE_COMPLETE: /* This is a resumed handshake case which means we are the last to receive handshake flights and we know the handshake is complete. However, the internal workings will not flag us officially complete until we receive application data from the peer so we need a local flag to handle this case so we are not resending our final flight */ dtlsCtx->connStatus = RESUMED_HANDSHAKE_COMPLETE; psTraceDtls("Got HANDSHAKE_COMPLETE out of ReceivedData\n"); break; case MATRIXSSL_APP_DATA: /* Now safe to clear the connStatus flag that was keeping track of the state between receiving the final flight of a resumed handshake and receiving application data. The reciept of app data has now internally disabled flight resends */ dtlsCtx->connStatus = 0; _psTrace("Client connected. Received...\n"); _psTraceStr("%s\n", (char*)sslBuf); break; case MATRIXSSL_REQUEST_SEND: /* Still handshaking with this particular client */ while ((sslBufLen = matrixDtlsGetOutdata(ssl, &sslBuf)) > 0) { if ((sendLen = udpSend(dtlsCtx->fd, sslBuf, sslBufLen, (struct sockaddr*)&inaddr, sizeof(struct sockaddr_in), dtlsCtx->timeout, packet_loss_prob, NULL)) < 0) { psTraceDtls("udpSend error. Ignoring\n"); } /* Always indicate the entire datagram was sent as there is no way for DTLS to handle partial records. Resends and timeouts will handle any problems */ rcs = matrixDtlsSentData(ssl, sslBufLen); if (rcs == MATRIXSSL_REQUEST_CLOSE) { psTraceDtls("Got REQUEST_CLOSE out of SentData\n"); clearClient(dtlsCtx); break; } if (rcs == MATRIXSSL_HANDSHAKE_COMPLETE) { /* This is the standard handshake case */ _psTrace("Got HANDSHAKE_COMPLETE from SentData\n"); break; } /* SSL_REQUEST_SEND is handled by loop logic */ } break; case MATRIXSSL_REQUEST_RECV: psTraceDtls("Got REQUEST_RECV from ReceivedData\n"); break; case MATRIXSSL_RECEIVED_ALERT: /* The first byte of the buffer is the level */ /* The second byte is the description */ if (*sslBuf == SSL_ALERT_LEVEL_FATAL) { psTraceIntDtls("Fatal alert: %d, closing connection.\n", *(sslBuf + 1)); clearClient(dtlsCtx); continue; /* Next connection */ } /* Closure alert is normal (and best) way to close */ if (*(sslBuf + 1) == SSL_ALERT_CLOSE_NOTIFY) { clearClient(dtlsCtx); continue; /* Next connection */ } psTraceIntDtls("Warning alert: %d\n", *(sslBuf + 1)); if ((rcr = matrixSslProcessedData(ssl, &sslBuf, (uint32*)&freeBufLen)) == 0) { continue; } goto PROCESS_MORE_FROM_BUFFER; default: continue; /* Next connection */ } } else if (val < 0) { if (SOCKET_ERRNO != EINTR) { psTraceIntDtls("unhandled error %d from select", SOCKET_ERRNO); } } /* Have either timed out waiting for a read or have processed a single recv. Now check to see if any timeout resends are required */ rc = handleResends(sock); } /* Main Select Loop */ DTLS_EXIT: psFree(recvfromBuf, NULL); CLIENT_EXIT: closeClientList(); MATRIX_EXIT: matrixSslDeleteKeys(keys); matrixSslClose(); if (sock != INVALID_SOCKET) close(sock); return rc; } /******************************************************************************/ /* Work through client list and resend handshake flight if haven't heard from them in a while */ static int32 handleResends(SOCKET sock) { serverDtls_t *dtlsCtx; ssl_t *ssl; psTime_t now; unsigned char *sslBuf; int16 i; int32 sendLen, rc; uint32 timeout, sslBufLen, clientCount; clientCount = 0; /* return code is number of active clients or < 0 on error */ psGetTime(&now, NULL); for (i = 0; i < tableSize; i++) { dtlsCtx = &clientTable[i]; if (dtlsCtx->ssl != NULL) { clientCount++; timeout = psDiffMsecs(dtlsCtx->lastRecvTime, now, NULL) / 1000; /* Haven't heard from this client in a while. Might need resend */ if (timeout > dtlsCtx->timeout) { /* if timeout is too great. clear conn */ if (dtlsCtx->timeout >= MAX_WAIT_SECS) { clearClient(dtlsCtx); clientCount--; break; } /* Increase the timeout for next pass */ dtlsCtx->timeout *= 2; /* If we are in a RESUMED_HANDSHAKE_COMPLETE state that means we are positive the handshake is complete so we don't want to resend no matter what. This is an interim state before the internal mechaism sees an application data record and flags us as complete officially */ if (dtlsCtx->connStatus == RESUMED_HANDSHAKE_COMPLETE) { psTraceDtls("Connected but awaiting data\n"); continue; } ssl = dtlsCtx->ssl; while ((sslBufLen = matrixDtlsGetOutdata(ssl, &sslBuf)) > 0) { if ((sendLen = udpSend(dtlsCtx->fd, sslBuf, sslBufLen, (struct sockaddr*)&dtlsCtx->addr, sizeof(struct sockaddr_in), dtlsCtx->timeout / 2, packet_loss_prob, NULL)) < 0) { psTraceDtls("udpSend error. Ignoring\n"); } /* Always indicate the entire datagram was sent as there is no way for DTLS to handle partial records. Resends and timeouts will handle any problems */ if ((rc = matrixDtlsSentData(ssl, sslBufLen)) < 0) { psTraceDtls("internal error\n"); clearClient(dtlsCtx); clientCount--; break; } if (rc == MATRIXSSL_REQUEST_CLOSE) { psTraceDtls("Got REQUEST_CLOSE out of SentData\n"); clearClient(dtlsCtx); clientCount--; break; } if (rc == MATRIXSSL_HANDSHAKE_COMPLETE) { /* This is the standard handshake case */ psTraceDtls("Got HANDSHAKE_COMPLETE out of SentData\n"); break; } /* SSL_REQUEST_SEND is handled by loop logic */ } } } } return clientCount; }
/* draw the the AR objects */ static int draw(ObjectData_T *object, int objectnum) { int i; double gl_para[16]; glClearDepth(1.0); glClear(GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_LIGHTING); /* calculate the viewing parameters - gl_para */ int count = 0; float x1, x2,x3; float y1, y2,y3; float z1, z2,z3; for (i = 0; i < objectnum; i++) { if (object[i].visible == 0)continue; count++; argConvGlpara(object[i].trans, gl_para); draw_object(object[i].id, gl_para); } x1 = object[0].trans[0][3], x2 = object[1].trans[0][3],x3 = object[2].trans[0][3]; y1 = object[0].trans[1][3], y2 = object[1].trans[1][3], y3 = object[2].trans[1][3]; z1 = object[0].trans[2][3], z2 = object[1].trans[2][3], z3 = object[2].trans[2][3]; int grid = object[0].visible && object[1].visible; if (grid == 1){ distX = fabs(x2 - x1); distY = fabs(y2 - y1); distZ = fabs(z2 - z1); //printf("grid distance %f %f %f \n ", distX, distY, distZ); } int controler = object[2].visible; if (object[0].visible && controler){ distX1 = fabs(x3 - x1); distY1 = fabs(y3 - y1); distX0 = fabs(x3 - x2); distY0 = fabs(y3 - y2); } if (nFrame++ == 50) { nFrame = 0; if (controler){ //calculate distance //printf("object id = %d || x = %f || y = %f || z = %f ||\n", object[0].id, x1, y1, z1); //printf("object id = %d || x = %f || y = %f || z = %f ||\n", object[1].id, x2, y2, z2); //printf("object id = %d || x = %f || y = %f || z = %f ||\n", object[2].id, x3, y3, z3); printf(" distancia 0 - - 1 x = %f || y = %f || z = %f ||\n", distX, distY, distZ); printf(" distancia 0-2 0-1 || x = %f - - %f || y = %f - - %f ||\n", distX1,distX0 , distY1, distY0); double x_send = distX1 / distX; double y_send = distY1 / distY; printf(" distancia norma x = %f || y = %f \n", x_send, y_send); /* // treat overflow if (x_send < 0.0) x_send = 0.0; else{ if (y_send < 0.0) y_send = 0.0; else{ if (x_send > 1.0) x_send = 1.0; else{ if (y_send > 1.0) y_send = 1.0; } } } */ //printf(" distancia normalizada x = %f || y = %f ||\n", x_send, y_send); prepare_msg(x_send, y_send); udpSend(buf2); // if relevante change in distance then udpSend } } glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); return(0); }
int main(int argc, char **argv) { int i; int iRet = 0; int iBufLen = 0; char sMsgInBuf[MSQ_MSG_SIZE_MAX]; char sMsgOutBuf[MSQ_MSG_SIZE_MAX]; int nMsgInLen=0; int nIntMsgLen=0; int nMsgOutLen=0; /* 进程初始化 */ iRet = MonSrvInit(argc, argv); if (iRet != 0) { HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "MonSrv Init err "); DbsDisconnect (); exit(-1); } /*设置信号处理*/ if ( sigset(SIGTERM, ShutDown_Main) == SIG_ERR) { HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "sigset SIGTERM error, %d.", errno); DbsDisconnect (); exit(-2); } HtLog (gsLogFile, HT_LOG_MODE_NORMAL, __FILE__,__LINE__, "[%s] start", gsSrvId); /*初始化socket*/ if( (gUpdSocket=udpConnectSocket())==-1 ) { HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "init socket error %d", gUpdSocket); DbsDisconnect (); exit(-3); } for (; ;) { memset(sMsgInBuf, 0, sizeof(sMsgInBuf)); sigrelse (SIGTERM); HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "recv begin[%s][%d][%d][%4.4s]",gsSrvId,gatSrvMsq[0].nMsqId,gatSrvMsq[0].lMsqType,gatSrvMsq[0].sSrvId); /* 从消息队列中获取消息 */ nMsgInLen = MSQ_MSG_SIZE_MAX; iRet = MsqRcv (gsSrvId, gatSrvMsq, 0, MSQ_RCV_MODE_BLOCK, &nMsgInLen, sMsgInBuf); sighold (SIGTERM); if (iRet != 0) { if (iRet != ERR_CODE_MSQ_BASE + EINTR) { HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "MsqRcv error %d", iRet); CloseSocket(gUpdSocket); DbsDisconnect (); exit(-4); } else { HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "MsqRcv error %d", iRet); continue; } } HtDebugString(gsLogFile, HT_LOG_MODE_NORMAL, __FILE__,__LINE__, sMsgInBuf, nMsgInLen); memset(&ptIpcIntTxn, 0, sizeof(T_IpcIntTxnDef)); memcpy(&ptIpcIntTxn,sMsgInBuf, nMsgInLen); memset(&ptTxn,0x00,sizeof(Tbl_txn_Def)); iRet = MonMoveIpc2Txn(&ptIpcIntTxn, &ptTxn ); if( iRet != 0 ) { HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "MoveIpc2Txn error %d", iRet); continue; } HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "InsertDayMoni begin "); iRet= InsertDayMoni(&ptTxn); if( iRet ) { HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "insert tbl_day_trans_monitor error"); } HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "WriteTnx2File begin "); iRet=WriteTxn2File(gsMoniTxnFile,&ptTxn); if(iRet != 0 ) { HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "WriteTnx2File error %d", iRet); continue; } HtLog (gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "udpSend begin "); /* 把通知报文发送给监控系统 */ memset(sMsgOutBuf,0x00,sizeof(sMsgOutBuf)); nMsgOutLen = sizeof(Tbl_txn_Def); sprintf(sMsgOutBuf,"%04d",nMsgOutLen); memcpy (sMsgOutBuf+4,(char *)&ptTxn, nMsgOutLen); nMsgOutLen =nMsgOutLen+4; sigset(SIGALRM, sTimeOut); alarm(60); iRet = udpSend(gUpdSocket, gsRmtIp, gUdpPort,sMsgOutBuf,nMsgOutLen); alarm(0); if( iRet == 0 ) { HtLog( gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "send to gsRmtIp[%s]: gUdpPort[%d] ok",gsRmtIp, gUdpPort,iRet ); } else { if (errno != EINTR) { HtLog( gsLogFile, HT_LOG_MODE_ERROR, __FILE__,__LINE__, "send to %s:%d error,errno=%d,%s", gsRmtIp, gUdpPort,errno,strerror(errno)); CloseSocket(gUpdSocket); exit(-5); DbsDisconnect (); } } } CloseSocket(gUpdSocket); DbsDisconnect (); return 0; } /* main end */