/** * Method to send the bytes of a file to the client */ void getFile(int sock, char * filename) { printf("Looking for file %s\n", filename); FILE * fp = fopen(filename, "r"); if (fp == NULL) { // the file did not exist // close the socket perror("fopen"); closeSock(sock); return; } printf("Found the file %s, sending Found\n", filename); // Send bytes to say we found it sendBytes(sock, "Found", strlen("Found")); // Send the bytes of the file char buf[1024]; memset(buf, 0, 1024); ssize_t retVal = 1024; while (retVal == 1024) { retVal = fread(buf, 1, 1024, fp); sendBytes(sock, buf, strlen(buf)); } closeSock(sock); fclose(fp); }
/** * Executes a BINRPC request. * @param req BINRPC request to be executed; the function takes care of it's * disposal * @return Result returned by server; NULL in case of error. */ brpc_t *BrpcCtrlInterface::rpcExecute(brpc_t *req) { brpc_t *rpl = NULL; brpc_str_t *reason; brpc_int_t *code; brpc_addr_t from = serAddr; //avoid a syscall to find out socket type brpc_id_t req_id; if (getSerFd() < 0) { ERROR("no connection to SER available.\n"); goto end; } assert(0 <= serFd); if (! brpc_sendto(serFd, &serAddr, req, TX_TIMEOUT)) { ERROR("failed to send msg to SER: %s [%d].\n", brpc_strerror(), brpc_errno); closeSock(&serFd, &sndAddr); goto end; } else { req_id = req->id; brpc_finish(req); req = NULL; } /* receive from queue until empty, if IDs do not match */ while ((rpl = brpc_recvfrom(serFd, &from, RX_TIMEOUT))) { if (req_id == rpl->id) break; ERROR("received reply's ID (#%d) doesn't match request's - discarded (%d)", brpc_id(rpl), req_id); brpc_finish(rpl); } if (! rpl) { ERROR("failed to get reply: %s [%d].\n", brpc_strerror(), brpc_errno); closeSock(&serFd, &sndAddr); goto end; } if (brpc_is_fault(rpl)) { ERROR("RPC call ID#%d faulted.\n", brpc_id(rpl)); if (brpc_fault_status(rpl, &code, &reason)) { if (code) ERROR("RPC ID#%d failure code: %d.\n", brpc_id(rpl), *code); if (reason) ERROR("RPC ID#%d failure reason: %.*s.\n", brpc_id(rpl), BRPC_STR_FMT(reason)); } brpc_finish(rpl); rpl = NULL; goto end; } DBG("RPC successfully executed.\n"); end: if (req) brpc_finish(req); return rpl; }
/* * Open a TCP Server listening on Port port * Returns socket. (0xFF if can't) */ uint8_t MWiFi::openServerTCP(uint16_t port) { uint8_t ok=0; uint8_t socket=createSockTCP(); //create socket if (socket>=0xFE) return 0xFF; uint8_t mess[4]; memcpy(&mess[0],&port,2); mess[2]=socket;mess[3]=0; sendLongMess(112,mess,4); //cmd 112: bind socket to port receiveMessWait(1000); //response 24: response to cmd 112 if (rxcode==24) if (rxmbuff[2]>0) return 0XFF; uint8_t mess2[2]; mess2[0]=socket; mess2[1]=1; sendLongMess(114,mess2,2); //cmd 114: on listening status uint8_t i; for(i=0;i<250;i++) { receiveMessWait(1000); //response 26: response to cmd 114 if (rxcode==26) {ok=rxmbuff[0]; // 0xFE : connection in progress if (ok!=0xFE) break;} delay(100); } if ((ok==0xFF)|(ok==0xFE)) {closeSock(socket);return 0xFF;} //0xFF : no connection return socket; }
void sendBytes(int sock, char * bytes, size_t size) { if(send(sock, bytes, size, 0) == -1) { perror("send"); closeSock(sock); exit(EXIT_FAILURE); } }
string InterpreterDBG::receiveIncomingData() { char buffer[1024]; int received = 0; buffer[1023] = '\0'; string cmd; int msg_size; //retrieve msg size! int idx = 0; int rec; while(true) { rec = recv(clientsock, &buffer[idx], sizeof(char), 0); received += rec; if((rec == 0) || (rec < 1)) { return cmd; } if(buffer[idx] == '\0') { break; } idx++; } // cerr << "MESSAGE SIZE: " << buffer << ", received : " << received << endl; msg_size = atoi(buffer) * sizeof(char); received = recv(clientsock, buffer, msg_size, 0); if(received < 0) { cerr << PACKAGE << ": erro ao receber dados." << endl; return cmd; } else if((received == 0) || (received < msg_size)) { // cerr << "insuficient! received: " << received << ", msg_size: " << msg_size << endl; closeSock(); return cmd; } // cmd.assign(buffer, received); cmd = buffer; // cerr << "MESSAGE : " << cmd << ", assigned: " << received << endl; return cmd; }
bool DeleteVM::applySC2FreeDisk() { String request = "DEL NFS STOR:ID=" + vmID + ",TYPE=0"; int sock = connect2Server( scServerIP.c_str(), scServerPort); if( sock == -1 ) { log.write("connect sc node server error.", Log::ERROR); return false; } if( sendData( request.c_str(), request.size(), sock) == false ) { log.write("send request to sc node server error.", Log::ERROR); return false; } String ack; if( recvData( sock, ack) == false ) { log.write("recv ack message from sc node server error.", Log::ERROR); return false; } log.write("recv ack message:" + ack + " from sc node server.", Log::INFO); //分析结果 int iRetn; if( getIntParaValue( ack, "retn", iRetn) == false ) { log.write("get para ip error from ack message.", Log::ERROR); return false; } closeSock( sock ); if( iRetn == 0 ) { log.write("apply sc server to free disk success.", Log::INFO); return true; } log.write("apply sc server to free disk failed.", Log::ERROR); return false; }
bool PageNetTest::netTestStart_r( bool amThread, long num ) { long long endTime = 0; long long calcTime = 0; long count; long index = 0; m_running = true; m_startTime = gettimeofdayInMilliseconds(); endTime = gettimeofdayInMilliseconds(); if( (m_sock[num] = openSock( num, m_type[num], &m_name[num], m_port[num])) == -1 ) return false; while( (endTime - m_startTime) < (m_testDuration * 1000) ) { count = 0; calcTime = gettimeofdayInMilliseconds(); if( m_type[num] == TEST_READ ) count = readSock( m_sock[num] ); else if( m_type[num] == TEST_SEND ) count = sendSock( m_sock[num] ); endTime = gettimeofdayInMilliseconds(); float secs = (endTime - calcTime)/1000.0; float mb = (float)count * 8.0 / (1024.0 * 1024.0); float mbps = mb/secs; log( LOG_INFO, "net: nettest: took %lli ms to %s %li bytes at " "%.2f Mbps", endTime - calcTime, (m_type[num] == TEST_READ)?"receive":"send", count, mbps ); log( LOG_INFO, "net: nettest: run time %lli s", (endTime-m_startTime)/1000 ); m_calcTable[num][index] = (unsigned long)mbps; if( ++index >= AVG_TABLE_SIZE ) index = 0; if( !m_runNetTest ) break; } m_sock[num] = closeSock( m_sock[num] ); return true; }
/* * Open a TCP Socket to a remote IP and Port port * IP as a string n.n.n.n (where n= decimal number 0-255) * Returns socket if connection ok; 0xFF if it can't open socket. */ uint8_t MWiFi::openSockTCP(char *ipremote,uint16_t port) { sscanf(ipremote,"%3d.%3d.%3d.%3d",&REMOTEIP[0],&REMOTEIP[1],&REMOTEIP[2],&REMOTEIP[3]); uint8_t ok=0xFE; uint8_t socket=createSockTCP(); //allocate socket (cmd 110) if (socket>=0xFE) return 0xFF; uint8_t mess2[20];memset(mess2,0,20); mess2[0]=socket; memcpy(&mess2[2],&port,2); memcpy(&mess2[4],&REMOTEIP[0],4); uint8_t i; for(i=0;i<250;i++) { sendLongMess(113,mess2,20); //command 113: connect to IP and remote Port receiveMessWait(1000); //response 25: response to cmd 113 if (rxcode==25) {ok=rxmbuff[0];if (ok!=0xFE) break;}// 0xFE : connection in progress delay(100); } if ((ok==0xFF)|(ok==0xFE)) {closeSock(socket);return 0xFF;} //0xFF : no connection return socket; }
int CServerLinker::Link(void) { closeSock(); int iRtn = Q_RTN_OK; CNETAddr objAddr; int iKeepAlive = 1; iRtn = objAddr.setAddr(m_strDesIp.c_str(), m_usDesPort); if (Q_RTN_OK != iRtn) { return iRtn; } m_Sock = socket(AF_INET, SOCK_STREAM, 0); if (Q_INVALID_SOCK == m_Sock) { iRtn = Q_SockError(); Q_Printf("create socket error. error code %d, message %s", iRtn, Q_SockError2Str(iRtn)); return iRtn; } iRtn = connect(m_Sock, objAddr.getAddr(), objAddr.getAddrSize()); if (Q_RTN_OK != iRtn) { iRtn = Q_SockError(); Q_Printf("connect %s on port %d error. error code %d, message %s", objAddr.getIp().c_str(), objAddr.getPort(), iRtn, Q_SockError2Str(iRtn)); return iRtn; } (void)setsockopt(m_Sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&iKeepAlive, sizeof(iKeepAlive)); return Q_RTN_OK; }
/** * Method to send the file data to the client */ void sendList(int sock) { int numOfFiles; struct dirent **namelist; char buffer[1024]; // gather all the file names numOfFiles = scandir(".", &namelist, NULL, alphasort); if (numOfFiles == -1) { printf("There was an error reading the directory - Exiting\n"); exit(EXIT_FAILURE); } struct stat fileInfo; for (int i = 0; i < numOfFiles; i++) { // gather the file info if (stat(namelist[i]->d_name, &fileInfo) == -1) { perror("stat"); exit(EXIT_FAILURE); } // put the information into a buffer snprintf(buffer, 1024, "%s\n", namelist[i]->d_name); // send the info to the client sendBytes(sock, buffer, strlen(buffer)); //printf("%s %lld\n", namelist[i]->d_name, (long long) fileInfo.st_size); free(namelist[i]); } free(namelist); closeSock(sock); }
void *sctpSock(void *param) { PRINTD(1,"sctpSock: sctpSock started\n"); #ifdef WIN32 int first = 1; #endif HANDLE hComm = 0; paramThread *paraThread; paraThread = (paramThread *) param; int sock = 0; unsigned char payload[MAX_PAYLOAD_SIZE]; struct info *infos = (struct info *) calloc(logbuffer_size, sizeof(info)); struct addrinfo SrcAddress; in_port_t tmpPort = 0; int newSock = 0; int size = 0; unsigned char *ptrSeqNum = payload + sizeof(uint32_t); unsigned char *ptrTimeSec = ptrSeqNum + sizeof(uint32_t); unsigned char *ptrTimeUsec = ptrTimeSec + sizeof(uint32_t); struct timeval RcvTime; #ifdef WIN32 LARGE_INTEGER _tstart, _tend; unsigned long secs = 0, msecs = 0; #endif int sctpId; bool newSession = true; PRINTD(1,"sctpSock: Start of Function. logCheck = %d logRemote = %d \n", logCheck, logRemote); paraThread->addressInfos = infos; paraThread->count = 0; memset(payload, 0, MAX_PAYLOAD_SIZE); if (strcmp(paraThread->serial, "noSerial") != 0) { hComm = serialUp(paraThread->serial); if (hComm == INVALID_HANDLE_VALUE) printf("Error opening interface %s \n", paraThread->serial); } unsigned int port = 0; GET_PORT((&(paraThread->destHost)), port); MUTEX_THREAD_LOCK(mutexSctp); for (sctpId = 0; sctpId < sctpSessionCount; sctpId++) { if (sctpSessions[sctpId].parsedStreams > 0 && sctpSessions[sctpId].port == port) { newSession = false; break; } } if (newSession) { PRINTD(1,"sctpSock: Receiving new SCTP session on port %d...\n", ntohs(port)); sctpId = sctpSessionCount++; sctpSessions[sctpId].port = port; sctpSessions[sctpId].busyStreams = 0; sctpSessions[sctpId].parsedStreams = 1; sctpSessions[sctpId].sock = -1; } else sctpSessions[sctpId].parsedStreams++; PRINTD(1,"sctpSock: Receiving new SCTP stream...\n"); if (newSession) { sock = socket(paraThread->destHost.ai_family, SOCK_STREAM, IPPROTO_SCTP); if (sock < 0) { reportErrorAndExit("sctpSock", "socket", "Cannot create a STREAM socket on port"); } if (bind(sock, paraThread->destHost.ai_addr, paraThread->destHost.ai_addrlen) < 0) { struct pipeMsg msg; msg.code = MSG_FT_ERR1; msg.flowId = paraThread->flowId; if (sendPipeMsg(paraThread->rPipe, &msg) < 0) { printf(" sending msg error"); } sleep(INFINITE); } if (listen(sock, SOMAXCONN) < 0) { reportErrorAndExit("tcpSock", "listen", "Cannot listen on a port"); } else { #ifdef WIN32 int len = paraThread->destHost.ai_addrlen; getsockname(sock,paraThread->destHost.ai_addr, &len); paraThread->destHost.ai_addrlen = len; #else getsockname(sock, paraThread->destHost.ai_addr, &(paraThread->destHost.ai_addrlen)); #endif GET_PORT((&(paraThread->destHost)), tmpPort); fprintf(stderr, "Listening on STCP port : %d\n", ntohs(tmpPort)); fflush(stderr); struct pipeMsg msg; msg.code = MSG_FT_OK; msg.flowId = paraThread->flowId; if (sendPipeMsg(paraThread->rPipe, &msg) < 0) { printf("error into sending msg to signal manager"); } } SrcAddress.ai_family = paraThread->destHost.ai_family; if (SrcAddress.ai_family == PF_INET) { SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in)); SrcAddress.ai_addrlen = sizeof(struct sockaddr_in); } else if (SrcAddress.ai_family == PF_INET6) { SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in6)); SrcAddress.ai_addrlen = sizeof(struct sockaddr_in6); } if ((newSock = accept(sock, SrcAddress.ai_addr, (socklen_t *) &SrcAddress.ai_addrlen)) < 0) reportErrorAndExit("sctpSock", "accept", "Cannot accept connection"); if (closeSock(sock) == -1) reportErrorAndExit("sctpSock", "closeSock", "Cannot close socket sock"); paraThread->socketClose = newSock; sctpSessions[sctpId].sock = newSock; } else { newSock = sctpSessions[sctpId].sock; } MUTEX_THREAD_UNLOCK(mutexSctp); int firstpacket = 1; char HelpSrcAddress[INET6_ADDRSTRLEN]; char HelpDstAddress[INET6_ADDRSTRLEN]; int tmpPort_SrcPort = 0; int tmpPort_DstPort = 0; TSTART(_tstart, secs, msecs, first, 0, RECEIVER); PRINTD(1,"sctpSock: main loop\n"); while (1) { size = SCTPrecvPacket((unsigned char*) payload, newSock, sctpId, paraThread->preambleSize, paraThread->payloadLogType); PRINTD(2,"sctpSock: Received SCTP data. Size of the received data chinck: %d\n",size); if (hComm > 0) { DTR_Disable(hComm); DTR_Enable(hComm); } GET_TIME_OF_DAY(&RcvTime, _tend, _tstart, secs, msecs, 0, RECEIVER); if ((logCheck != 0) || (logRemote != 0)) { PRINTD(2,"sctpSock: Log received data \n"); if (firstpacket == 1) { getInfo(&SrcAddress, tmpPort_SrcPort, HelpSrcAddress); getInfo(¶Thread->destHost, tmpPort_DstPort, HelpDstAddress); firstpacket = 0; } if (logCheck != 0) { int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); if (paraThread->payloadLogType == PL_STANDARD) { writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload, *(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, net_TimeSec, RcvTime.tv_sec % 86400L, net_TimeUsec, RcvTime.tv_usec, size); } else if (paraThread->payloadLogType == PL_SHORT) { writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload, *(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } else { writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } } if (logRemote != 0) { int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); if (paraThread->payloadLogType == PL_STANDARD) { writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload, *(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, net_TimeSec, RcvTime.tv_sec % 86400L, net_TimeUsec, RcvTime.tv_usec, size); } else if (paraThread->payloadLogType == PL_SHORT) { writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload, *(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } else { writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } infosHostToNet(&infos[paraThread->count]); } paraThread->count++; if (paraThread->count == logbuffer_size) { if (logCheck != 0) flushBuffer((ofstream *) paraThread->fileLog, infos, paraThread->count); else if (logRemote != 0) { MUTEX_THREAD_LOCK(mutexLogRem); if (sendto(paraThread->logSock, (char *) infos, paraThread->count * sizeof(struct info), 0, paraThread->logHost->ai_addr, paraThread->logHost->ai_addrlen) < 0) reportErrorAndExit("sctpSock", "sendto", "Cannot send log infos to LogServer"); paraThread->count = 0; MUTEX_THREAD_UNLOCK(mutexLogRem); PRINTD(1,"sctpSock: Sent infos to LogServer\n"); } } } if (paraThread->meter == METER_RTTM) { if (sendto(newSock, (char *) payload, size, 0, SrcAddress.ai_addr, SrcAddress.ai_addrlen) < 0) reportErrorAndExit("sctpSock", "sendto", "Cannot send payload back for rttm"); PRINTD(2,"sctpSock: Sent RTTM infos\n"); } } MUTEX_THREAD_LOCK(mutexSctp); if (--sctpSessionCount == 0) free(SrcAddress.ai_addr); MUTEX_THREAD_UNLOCK(mutexSctp); return NULL; }
NetSock::~NetSock() { closeSock(); }
CSocket::~CSocket() { closeSock(); }
void InterpreterDBG::init(string host, int port) { if(host.length() == 0) return; #ifndef WIN32 struct sockaddr_in name; struct hostent *hostinfo = NULL; name.sin_family = AF_INET; name.sin_port = htons (port); hostinfo = gethostbyname (host.c_str()); if (hostinfo == NULL) { //cerr << "client: unknow host : " << hostname << endl; return; } name.sin_addr = *(struct in_addr *) hostinfo->h_addr; clientsock = socket(PF_INET, SOCK_STREAM, 0); if(clientsock < 0) { stringstream s; s << PACKAGE << ": não foi possível criar socket\n"; GPTDisplay::self()->showError(s); return; } if(connect(clientsock, (struct sockaddr*) &name,sizeof(name)) != 0) { //cerr << PACKAGE << ": unable to connect" << endl; //unable to connect closeSock(); } else { if(SIG_ERR == signal(SIGPIPE, sigPipeHandler)) { stringstream s; s << PACKAGE << ": erro interno em InterpreterDBG::init" << endl; GPTDisplay::self()->showError(s); } } #else WORD wVersionRequested = MAKEWORD(1,1); WSADATA wsaData; // // Initialize WinSock and check the version // WSAStartup(wVersionRequested, &wsaData); if (wsaData.wVersion != wVersionRequested) { //cerr << PACKAGE << ": weong winsock version" << endl; return; } LPHOSTENT lpHostEntry; lpHostEntry = gethostbyname(host.c_str()); if (lpHostEntry == NULL) { return; } // // Create a TCP/IP stream socket // clientsock = socket(AF_INET, // Address family SOCK_STREAM, // Socket type IPPROTO_TCP); // Protocol if (clientsock == INVALID_SOCKET) { return; } // // Fill in the address structure // SOCKADDR_IN saServer; saServer.sin_family = AF_INET; saServer.sin_addr = *((LPIN_ADDR)*lpHostEntry->h_addr_list); // ^ Server's address saServer.sin_port = htons(port); // Port number from command line // // connect to the server // if (connect(clientsock, (LPSOCKADDR)&saServer, sizeof(struct sockaddr)) == SOCKET_ERROR) { closesocket(clientsock); clientsock = INVALID_SOCKET; return; } #endif }
void logPacketTCP(int newSockSignal, ofstream *out) { int port; int newSockLog; struct sockaddr_in sockAddress; struct sockaddr_in srcAddress; int logSock, hold, hold2, dim2; struct info *infos = (struct info *) malloc(logbuffer_size * sizeof(info)); char *infosOffset; socklen_t sinLen = sizeof(srcAddress); fd_set activeSet; int dim_infos; #ifdef DEBUG int numRecvdPkt=0; int numTrip=0; #endif sockAddress.sin_family = AF_INET; sockAddress.sin_addr.s_addr = htonl(INADDR_ANY); createDataChannel(sockAddress,newSockSignal,logSock,port,"TCP"); if (listen(logSock, 5) < 0) reportErrorAndExit("logPacketTCP","listen","Error into listen on logSock"); newSockLog = accept(logSock, (struct sockaddr *) &srcAddress, &sinLen); PRINTD(1,"logPacketTCP: newSockLog TCP : %d \n",newSockLog); if (newSockLog < 0) reportErrorAndExit("logPacketTCP","accept","Error into accept on logSock"); while (1) { FD_ZERO(&activeSet); FD_SET((unsigned int)newSockSignal, &activeSet); FD_SET((unsigned int)newSockLog, &activeSet); if (select(FD_SETSIZE, &activeSet, NULL, NULL, 0) < 0) reportErrorAndExit("logPacketTCP","select", "Invalid file descriptor or operation interrupted by a signal - Close first Receiver"); if (FD_ISSET(newSockSignal, &activeSet)) { break; } else if (FD_ISSET(newSockLog, &activeSet)) { dim2 = logbuffer_size * sizeof(struct info); hold = 0; infosOffset = (char *)infos; do { hold2 = recv(newSockLog, (char *)infosOffset, dim2, 0); hold += hold2; dim2 -= hold2; infosOffset += hold2; } while (((hold % sizeof(struct info)) != 0) && (hold2 >= 0)); if (hold < 0) printf("** WARNING ** Data lost - Close First Receiver!\n"); else { dim_infos = hold / sizeof(struct info); infosntoh(infos, dim_infos); #ifdef DEBUG numRecvdPkt = numRecvdPkt + hold / sizeof(struct info); numTrip++; #endif if (!(*out).write((char *) infos, hold)) printf("** WARNING ** Can't write data!\n"); } } } #ifdef DEBUG char hostName[50]; char hostIP[20]; int rit1 = getnameinfo((sockaddr*)&senderLog,sizeof(senderLog),hostName, INET_ADDRSTRLEN, NULL, 0, NI_NOFQDN); int rit2 = getnameinfo((sockaddr*)&senderLog,sizeof(senderLog),hostIP, INET_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST); if ((rit1 == 0) & (rit2 == 0)) printf("Data transmission ended on TCP channel from %s(%s)\n",hostName,hostIP); else if ((rit1 != 0) & (rit2 == 0)) printf("Data transmission ended on TCP channel from %s\n",hostIP); else #endif printf("Data transmission ended on TCP channel!\n"); fflush(stdout); free(infos); if (closeSock(logSock) < 0) reportErrorAndExit("logPacketTCP","closeSock","Cannot close logSock"); if (closeSock(newSockLog) < 0) reportErrorAndExit("logPacketTCP","closeSock","Cannot close newLogSock"); PRINTD(1,"logPacketTCP: Number of received packets : %d \n",numRecvdPkt); PRINTD(1,"logPacketTCP: Number of received infos : %d \n",numTrip); }
IeParser::~IeParser() { closeSock(); }
int main(int argc, char * argv[]) { //check comand line paremeters if (argc < 10) { printf("usage: client ip port requestfilename requestNum cancelOrStop(1 is cancel, 0 is stop) netinterface filterExpression serverbandstatus sleepTime\n"); return 1; } // check cancel parameter int isCancel = 0; char *prefix = argv[8]; int sleepTime = atoi(argv[9]); if (strcmp(argv[5], "1") == 0) { isCancel = 1; } //init logFile char logFile[FILE_NAME_SIZE] = {0}; if (initLogFile(logFile, sizeof logFile -1, isCancel, prefix) != 0) { fprintf(stderr, "init logfile failed\n"); return 1; } printf("isCancel:%d\n", isCancel); printf("log file name is %s\n", logFile); struct ClientSockInfo sockInfo; if (initClientSockInfo(&sockInfo, argv[1], argv[2]) == 0) { printf("init client sockinfo successfully\n"); } else { fprintf(stderr, "init client sockinfo failed\n"); return 1; } char * requestFileName = argv[3]; int requestNum = atoi(argv[4]); //init sniffPanel struct SniffPanel sniffPanel; sniffPanel.device = argv[6]; sniffPanel.filterExpression = argv[7]; sniffPanel.liveReadTimeOut = 2000;//default 2000 ms sniffPanel.payloadFilePath = NULL; sniffPanel.payloadFile = NULL; sniffPanel.cbAfterSniff = &cbAfterSniff; sniffPanel.cbWhenError = &cbForSniffError; sniffPanel.cbLog = &cbForSniffLog; sniffPanel.afterSniffArgs = (void *)logFile; sniffPanel.errorArgs = NULL; sniffPanel.isStopped = 1; if (initSniff(&sniffPanel) != 0) { fprintf(stderr, "init packet sniff error\n"); return 1; } else { printf("finish initializing packet sniff\n"); } pthread_t sniffThread; int i = 0; while (i < requestNum) { if (!sniffPanel.isStopped) { printf("we need to stop the last sniff before starting new round\n"); if (stopSniff(&sniffPanel) != 0) { fprintf(stderr, "stop sniff failed\n"); continue; } else { printf("finish stopping the last sniff before starting new round\n"); } } i++; printf("round %d\n", i); //create connection to server //if (i == 1 || !isCancel) { // if (createNewConn(&sockInfo) != 0) { // fprintf(stderr, "create new connection failed \n"); // return 1; // } else { // printf("connect to server %s:%d successfully from port %d\n", sockInfo.serverIpStr, sockInfo.serverPort, sockInfo.clientPort); // } //} if (createNewConn(&sockInfo) != 0) { i--; fprintf(stderr, "create new connection failed \n"); continue; } else { printf("connect to server %s:%d successfully from port %d\n", sockInfo.serverIpStr, sockInfo.serverPort, sockInfo.clientPort); } //configure packet sniff and start thread sniffPanel.packetNum = 0; sniffPanel.payloadSize = 0; sniffPanel.isStopped = 0; pthread_create(&sniffThread, NULL, sniffThreadFunc, (void *)&sniffPanel); printf("finish starting thread for sniff\n"); //send request if (sendRequest(&sockInfo, requestFileName, strlen(requestFileName)) == 0) { printf("send request successfully\n"); } else { fprintf(stderr, "send request failed\n"); shutdown(sockInfo.clientSockFd, SHUT_RDWR); i--; continue; } //receive response within random time int randomSecs = generateRandom(RANDOM_RANGE); randomSecs += 10; sockInfo.recvedBytes = 0; printf("start to recv within %d seconds\n", randomSecs); if (recvWithInRandom(&sockInfo, randomSecs) == 0) { printf("recv %d KB in %d seconds\n", sockInfo.recvedBytes / 1024, randomSecs); } else { fprintf(stderr, "recv failed in round %d with random %d\n", i, randomSecs); shutdown(sockInfo.clientSockFd, SHUT_RDWR); i--; continue; } //send cancel or close signal const char *signal = isCancel? STOP_MSG : CLOSE_MSG; if (sendRequest(&sockInfo, signal, strlen(signal)) == 0) { printf("finish sending signal : %s\n", signal); } else { fprintf(stderr, "failed to send signal\n"); shutdown(sockInfo.clientSockFd, SHUT_RDWR); i--; continue; } //decide whether to close sock immediately after sending out cancel signal if (!isCancel) { printf("shutdown for close test\n"); closeSock(sockInfo.clientSockFd); printf("sleep for %d seconds in close test\n", sleepTime); sleep(sleepTime); } else { printf("continue receive for cancel test\n"); struct timeval timeout; timeout.tv_sec = 5; timeout.tv_usec = 0; int recvAfterCancel = receiveFromSockUtilTimeout(sockInfo.clientSockFd, &timeout); printf("recv %d KB after sending cancel signal", recvAfterCancel / 1024); printf("shutdown connection for cancel test\n"); closeSock(sockInfo.clientSockFd); } //record log if (appendLog(logFile, &sockInfo, randomSecs) == 0) { printf("finish appending new log\n"); } else { fprintf(stderr, "failed to append new log\n"); i--; continue; } if (stopSniff(&sniffPanel) != 0) { fprintf(stderr, "stop sniff failed\n"); i--; continue; } else { printf("finish stopping sniff with packets: %d, payloadSize: %d\n", sniffPanel.packetNum, sniffPanel.payloadSize / 1024); } } }
int main(int argc, char* argv[]) { // args should only be the port number and the name // of the program running if (argc != 2) { printf("Usage Error - provide port number\n"); exit(1); } char *port = argv[1]; // create the ./files dir createSubdir(); // getaddrinfo(): network address and service translation: struct addrinfo *socketaddrinfo = example_getaddrinfo(NULL, port); // socket(): create an endpoint for communication int sock = example_socket(socketaddrinfo); example_setsockopt(sock); example_bind(sock, socketaddrinfo); example_listen(sock, 128); freeaddrinfo(socketaddrinfo); // done with socketaddrinfo //printf("Press Ctrl+C to exit server.\n"); //printf("Run a web browser on the same computer as you run the server and point it to:\n"); //printf("http://127.0.0.1:%s\n", port); while(1) { printf("Waiting for connections...\n"); // Get a socket for a particular incoming connection. int newsock = accept(sock, NULL, NULL); if(newsock == -1) { perror("accept(): "); continue; // try again if accept failed. } printf("Client connected\n"); // Check the password of the client if (checkPass(newsock) == -1) { printf("Incorrect password - Connection aborted\n"); closeSock(newsock); continue; } else { printf("Password accepted - Continuing connection\n"); } sendBytes(newsock, "You connected!\n", strlen("You connected!\n")); char cmd[1024]; memset(cmd, 0, 1024); recvBytes(newsock, cmd, 1024); printf("Received command: %s\n", cmd); if (strcmp(cmd, "list") == 0) { sendBytes(newsock, "File listing:\n", strlen("File listing:\n")); // Scan the dirextory and send the file list sendList(newsock); continue; } if (strcmp(cmd, "get") == 0) { char retBuf[1024]; memset(retBuf, 0, 1024); // Read the name of the file recvBytes(newsock, retBuf, 1024); // Check if the file exists and send it getFile(newsock, retBuf); continue; } if (strcmp(cmd, "put") == 0) { char retBuf[1024]; memset(retBuf, 0, 1024); // Read the name of the file getLine(newsock, retBuf); // Check if the file exists and send it putFile(newsock, retBuf); continue; } // char http_body[] = "hello world"; // char http_headers[1024]; // snprintf(http_headers, 1024, // "HTTP/1.0 200 OK\r\n" // "Content-Length: %zu\r\n" // "Content-Type: text/html\r\n\r\n", // strlen(http_body)); // should check return value /* Note: send() does not guarantee that it will send all of * the data that we ask it too. To reliably send data, we * should inspect the return value from send() and then call * send() again on any bytes did not get sent. */ // Send the HTTP headers //if(send(newsock, http_headers, strlen(http_headers), 0) == -1) //{ // perror("send"); // close(newsock); // exit(EXIT_FAILURE); //} //// Send the HTTP body //if(send(newsock, http_body, strlen(http_body), 0) == -1) //{ // perror("send"); // close(newsock); // exit(EXIT_FAILURE); //} /* shutdown() (see "man 2 shutdown") can be used before close(). It allows you to partially close a socket (i.e., indicate that we are done sending data but still could receive). This could allow us to signal to a peer that we are done sending data while still allowing us to receive data. SHUT_RD will disallow reads from the socket, SHUT_WR will disallow writes, and SHUT_RDWR will disallow read and write. Also, unlike close(), shutdown() will affect all processes that are sharing the socket---while close() only affects the process that calls it. */ #if 0 if(shutdown(newsock, SHUT_RDWR) == -1) { perror("shutdown"); close(newsock); exit(EXIT_FAILURE); } #endif closeSock(newsock); } }
void *dccpSock(void *param) { PRINTD(1,"dccpSock: dccpSock started\n"); HANDLE hComm = 0; int sock = 0; int sendCheck = 0; unsigned char payload[MAX_PAYLOAD_SIZE]; struct info *infos = (struct info *) calloc(logbuffer_size, sizeof(info)); struct addrinfo SrcAddress; in_port_t tmpPort = 0; int newSock = 0; int size = 0; int optval = 0; struct timeval RcvTime; unsigned char *ptrSeqNum = payload + sizeof(uint32_t); unsigned char *ptrTimeSec = ptrSeqNum + sizeof(uint32_t); unsigned char *ptrTimeUsec = ptrTimeSec + sizeof(uint32_t); paramThread *paraThread; paraThread = (paramThread *) param; paraThread->addressInfos = infos; paraThread->count = 0; if (strcmp(paraThread->serial, "noSerial") != 0) { hComm = serialUp(paraThread->serial); if (hComm == INVALID_HANDLE_VALUE) printf("Error opening interface %s \n", paraThread->serial); } sock = socket(paraThread->destHost.ai_family, SOCK_DCCP, 0); if (sock < 0) reportErrorAndExit("dccpSock", "socket", "Cannot create a DCCP socket on port"); if (paraThread->dsByte && (paraThread->destHost.ai_family == AF_INET) && setsockopt(sock, SOL_IP, IP_TOS, (char *) ¶Thread->dsByte, sizeof(BYTE)) < 0) { printf("** WARNING ** Flow %d. Could not set DS byte to: %d\n", paraThread->flowId, paraThread->dsByte); } if (bind(sock, paraThread->destHost.ai_addr, paraThread->destHost.ai_addrlen) < 0) { printf(" Error into bind function\n"); struct pipeMsg msg; msg.code = MSG_FT_ERR1; msg.flowId = paraThread->flowId; if (sendPipeMsg(paraThread->rPipe, &msg) < 0) printf(" sending msg error"); sleep(INFINITE); } if (setsockopt(sock, SOL_DCCP, DCCP_SOCKOPT_SERVICE, &optval, sizeof(optval)) < 0) reportErrorAndExit("dccpSock", "setsockopt", "Cannot set option DCCP_SERVICE"); if (listen(sock, SOMAXCONN) < 0) reportErrorAndExit("dccpSock", "listen", "Cannot listen on a port"); else { #ifdef WIN32 int len=paraThread->destHost.ai_addrlen; getsockname(sock,paraThread->destHost.ai_addr,&len); paraThread->destHost.ai_addrlen=len; #else getsockname(sock, paraThread->destHost.ai_addr, &(paraThread->destHost.ai_addrlen)); #endif GET_PORT((&(paraThread->destHost)), tmpPort); fprintf(stderr, "Listening on DCCP port : %d\n", ntohs(tmpPort)); fflush(stderr); struct pipeMsg msg; msg.code = MSG_FT_OK; msg.flowId = paraThread->flowId; if (sendPipeMsg(paraThread->rPipe, &msg) < 0) { printf("error into sending msg to signal manager"); } } SrcAddress.ai_family = paraThread->destHost.ai_family; if (SrcAddress.ai_family == PF_INET) { SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in)); SrcAddress.ai_addrlen = sizeof(struct sockaddr_in); } else if (SrcAddress.ai_family == PF_INET6) { SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in6)); SrcAddress.ai_addrlen = sizeof(struct sockaddr_in6); } pthread_cleanup_push(free, SrcAddress.ai_addr); if ((newSock = accept(sock, SrcAddress.ai_addr, (socklen_t *) &SrcAddress.ai_addrlen)) < 0) reportErrorAndExit("dccpSock", "accept", "Cannot accept connection"); if (closeSock(sock) == -1) reportErrorAndExit("dccpSock", "closeSock", "Cannot close socket sock"); paraThread->socketClose = newSock; int firstpacket = 1; char HelpSrcAddress[INET6_ADDRSTRLEN]; char HelpDstAddress[INET6_ADDRSTRLEN]; int tmpPort_SrcPort = 0; int tmpPort_DstPort = 0; TSTART(_tstart, secs, msecs, first, 0, RECEIVER); PRINTD(1,"dccpSock: main loop\n"); while (1) { size = recv(newSock, (char *) payload, MAX_PAYLOAD_SIZE, 0); if (size < 0) reportErrorAndExit("udpSock", "recvfrom", "Cannot receive UDP packets"); else if (size > 0) { PRINTD(2,"dccpSock: Received DCCP packet, size %d\n", size); if (hComm > 0) { DTR_Disable(hComm); DTR_Enable(hComm); } GET_TIME_OF_DAY(&RcvTime, _tend, _tstart, secs, msecs, 0, RECEIVER); if ((logCheck != 0) || (logRemote != 0)) { if (firstpacket == 1) { getInfo(&SrcAddress, tmpPort_SrcPort, HelpSrcAddress); getInfo(¶Thread->destHost, tmpPort_DstPort, HelpDstAddress); firstpacket = 0; } if (logCheck != 0) { int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); if (paraThread->payloadLogType == PL_STANDARD) { writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload, *(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, net_TimeSec, RcvTime.tv_sec % 86400L, net_TimeUsec, RcvTime.tv_usec, size); } else if (paraThread->payloadLogType == PL_SHORT) { writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload, *(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } else { writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } } if (logRemote != 0) { int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); if (paraThread->payloadLogType == PL_STANDARD) { writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload, *(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, net_TimeSec, RcvTime.tv_sec % 86400L, net_TimeUsec, RcvTime.tv_usec, size); } else if (paraThread->payloadLogType == PL_SHORT) { writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload, *(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } else { writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } infosHostToNet(&infos[paraThread->count]); } paraThread->count++; if (paraThread->count == logbuffer_size) { if (logCheck != 0) flushBuffer((ofstream *) paraThread->fileLog, infos, paraThread->count); else if (logRemote != 0) { MUTEX_THREAD_LOCK(mutexLogRem); if (sendto(paraThread->logSock, (char *) infos, paraThread->count * sizeof(struct info), 0, paraThread->logHost->ai_addr, paraThread->logHost->ai_addrlen) < 0) reportErrorAndExit("dccpSock", "sendto", "Cannot send log infos to LogServer"); paraThread->count = 0; MUTEX_THREAD_UNLOCK(mutexLogRem); PRINTD(1,"dccpSock: Sent infos to LogServer\n"); } } } if (paraThread->meter == METER_RTTM) { do { PRINTD(2,"dccpSock: Trying to send RTTM infos\n"); sendCheck = sendto(newSock, (char *) payload, size, 0, SrcAddress.ai_addr, SrcAddress.ai_addrlen); } while (sendCheck < 0 && errno == EAGAIN); if (sendCheck < 0) reportErrorAndExit("dccpSock", "sendto", "Cannot send payload back for rttm"); PRINTD(2,"dccpSock: Sent RTTM infos\n"); } } } pthread_cleanup_pop(1); return NULL; }
int main(int argc,char **argv) { double wts, wte, all_s, all_e, calc_total=0, calc_head;; wts = get_wall_time(); ROT::SysInit(); setParam(argc, argv); wte = get_wall_time(); calc_head = wte - wts;; int sock0 = prepSSock(); while(1){ CPBWT::Server s; std::ifstream ifs; std::ofstream ofs; calc_total = calc_head; // all_s = get_wall_time(); int sock = acceptSSock(sock0); std::string file = tmp_dir_path + "c2s_pos"; recvFile(sock, (char *)file.c_str()); //receive positions from client all_s = get_wall_time(); wts = get_wall_time(); ifs.open(file.c_str(), std::ios::binary); int qlen, tmp; ifs >> qlen; while(1){ ifs >> tmp; if(tmp == -1){ break; } s.pos.push_back(tmp); } ifs.close(); std::cerr<<"read db\n"; int n=pbwt_n, m=pbwt_m; // DB size s.readPBWT(m,n,infile); s.makeLUTable(); file = tmp_dir_path + "param"; ofs.open(file.c_str(), std::ios::binary); // std::cerr<<s.v_length<<"\n"; ofs << s.samples <<"\n"; ofs << s.v_length <<"\n"; ofs << s.B0 <<"\n"; ofs << s.L0 <<"\n"; ofs << s.L1 <<"\n"; ofs.close(); wte = get_wall_time(); calc_total += wte - wts; sendFile(sock, (char *)file.c_str()); //send db parameters to client std::cerr<<"set db param, pubkey\n"; file = key_dir_path + "c2s_pubkey"; recvFile(sock, (char *)file.c_str()); //receive pubkey from client s.core = core; s.setParam(file); std::string queryf = tmp_dir_path + "squeryf"; std::string queryg = tmp_dir_path + "squeryg"; std::string resultf = tmp_dir_path + "sresultf"; std::string resultg = tmp_dir_path + "sresultg"; std::string ismatch = tmp_dir_path + "sismatch"; #ifdef DEBUG // std::string q = "1010101010"; std::string q = "1010101010111111111111111"; int select = 0; int f=select*(s.samples+1),g=(select+1)*(s.samples+1)-1; int blk = s.B0*s.L1; int zero = '0'; f += ('1'-zero)*blk; // fix query for debug g += ('1'-zero)*blk; std::cerr<<"f="<<f<<", g="<<g<<" ,ln="<<g-f<<"\n"; #endif for(int i=0;i<qlen;i++){ wts = get_wall_time(); std::cerr<<"round: "<<i<<"\n"; DBG_PRT("update table\n"); s.updtLUTable(); #ifdef DEBUG f=s.retV(f); g=s.retV(g); #endif int ranf0, ranf1, rang0, rang1; #pragma omp parallel #pragma omp sections { #pragma omp section { DBG_PRT("get resultf\n"); ranf0 = rand(); ranf1 = rand(); // ranf0=0; ranf1=0; //for debug if(i+1 == qlen){ ranf0=0; ranf1=0; } } #pragma omp section { DBG_PRT("get resultg\n"); rang0 = rand(); rang1 = rand(); // rang0=0; rang1=0; //for debug if(i+1 == qlen){ rang0=0; rang1=0; } } } wte = get_wall_time(); calc_total += wte - wts; DBG_PRT("recv queries\n"); recvFile(sock, (char *)queryf.c_str()); //receive query f from client recvFile(sock, (char *)queryg.c_str()); //receive query g from client wts = get_wall_time(); DBG_PRT("f:main server\n"); s.setPrevFr(); s.getOrgQuery(queryf, 0); s.getResult(queryf, ranf0, ranf1); s.storePrevFr(); s.makeResFile(resultf); DBG_PRT("g:main server\n"); s.setPrevGr(); s.getOrgQuery(queryg, 1); s.getResult(queryg, rang0, rang1); s.storePrevGr(); s.makeResFile(resultg); if(epsilon==0){ s.makeIsLongest(ismatch); }else{ s.makeIsELongest(ismatch, epsilon); } wte = get_wall_time(); calc_total += wte - wts; DBG_PRT("send results\n"); sendFile(sock, (char *)resultf.c_str()); //send result f to client sendFile(sock, (char *)resultg.c_str()); //send result g to client sendFile(sock, (char *)ismatch.c_str()); //send ismatch to client for(int j=0;j<s.pos.size();j++){ s.pos[j]++; } #ifdef DEBUG if(i+1 != qlen){ f += (q[i+1]-zero)*blk; g += (q[i+1]-zero)*blk; std::cerr<<"k="<<i+1<<", f="<<f<<", g="<<g<<", ln="<<g-f<<"\n"; } #endif } closeSock(sock); all_e = get_wall_time(); // std::cerr<<"server(Wall): "<<calc_total<<", "<<all_e-all_s<<"\n"; std::cerr<<"server(Wall): "<<all_e-all_s<<"\n"; } return(0); }
BrpcCtrlInterface::~BrpcCtrlInterface() { closeSock(&serFd, &sndAddr); closeSock(&semsFd, &semsAddr); }
void *tcpSock(void *param) { PRINTD(1,"tcpSock: tcpSock started\n"); #ifdef WIN32 int first = 1; #endif HANDLE hComm = 0; paramThread *paraThread; paraThread = (paramThread *) param; int sock = 0; unsigned char payload[MAX_PAYLOAD_SIZE]; struct info *infos = (struct info *) calloc(logbuffer_size, sizeof(info)); struct addrinfo SrcAddress; in_port_t tmpPort = 0; int newSock = 0; int size = 0; unsigned char *ptrSeqNum = payload + sizeof(uint32_t); unsigned char *ptrTimeSec = ptrSeqNum + sizeof(uint32_t); unsigned char *ptrTimeUsec = ptrTimeSec + sizeof(uint32_t); struct timeval RcvTime; #ifdef WIN32 LARGE_INTEGER _tstart, _tend; unsigned long secs = 0, msecs = 0; #endif paraThread->addressInfos = infos; paraThread->count = 0; memset(payload, 0, MAX_PAYLOAD_SIZE); if (strcmp(paraThread->serial, "noSerial") != 0) { hComm = serialUp(paraThread->serial); if (hComm == INVALID_HANDLE_VALUE) printf("Error opening interface %s \n", paraThread->serial); } bool socketAlreadyOpen = false; #ifdef MULTIPORT if ((passiveMode == false) && (paraThread->indexPort > 0)) { MUTEX_THREAD_LOCK(sharedTcpSockets[paraThread->indexPort].mutexSharedSockets); sock = sharedTcpSockets[paraThread->indexPort].socket; if (sock > 0) { socketAlreadyOpen = true; } } #endif if (socketAlreadyOpen == false) { sock = socket(paraThread->destHost.ai_family, SOCK_STREAM, 0); if (paraThread->dsByte && (paraThread->destHost.ai_family == AF_INET) && setsockopt(sock, SOL_IP, IP_TOS, (char *) ¶Thread->dsByte, sizeof(BYTE)) < 0) { printf("** WARNING ** Flow %d. Could not set DS byte to: %d\n", paraThread->flowId, paraThread->dsByte); } } if (sock < 0) reportErrorAndExit("tcpSock", "socket", "Cannot create a STREAM socket on port"); if ((passiveMode == false) && (socketAlreadyOpen == false)) { if (bind(sock, paraThread->destHost.ai_addr, paraThread->destHost.ai_addrlen) < 0) { struct pipeMsg msg; msg.code = MSG_FT_ERR1; msg.flowId = paraThread->flowId; if (sendPipeMsg(paraThread->rPipe, &msg) < 0) { printf(" sending msg error"); } sleep(INFINITE); } } //#if defined UNIX && ! defined BSD if ((paraThread->iface) && (socketAlreadyOpen == false)) { printf("Binding to device %s\n", paraThread->iface); if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, paraThread->iface, strlen(paraThread->iface)) < 0) { printf("** WARNING ** Cannot bind to device %s (hint: you must be root)\n", paraThread->iface); fflush(stdout); } } //#endif if ((passiveMode == false) && (socketAlreadyOpen == false)) { if (listen(sock, SOMAXCONN) < 0) reportErrorAndExit("tcpSock", "listen", "Cannot listen on a port"); else { #ifdef WIN32 int len=paraThread->destHost.ai_addrlen; getsockname(sock,paraThread->destHost.ai_addr,&len); paraThread->destHost.ai_addrlen=len; #else getsockname(sock, paraThread->destHost.ai_addr, &(paraThread->destHost.ai_addrlen)); #endif GET_PORT((&(paraThread->destHost)), tmpPort); printf("Listening on TCP port : %d\n", ntohs(tmpPort)); fflush(stdout); #ifdef MULTIPORT if (paraThread->indexPort == 0) { paraThread->indexPort = ntohs(tmpPort); MUTEX_THREAD_LOCK(sharedTcpSockets[paraThread->indexPort].mutexSharedSockets); } #endif struct pipeMsg msg; msg.code = MSG_FT_OK; msg.flowId = paraThread->flowId; if (sendPipeMsg(paraThread->rPipe, &msg) < 0) { printf("error into sending msg to signal manager"); } } } #ifdef MULTIPORT else if ((passiveMode == false) && (socketAlreadyOpen == true)) { struct pipeMsg msg; msg.code = MSG_FT_OK; msg.flowId = paraThread->flowId; if (sendPipeMsg(paraThread->rPipe, &msg) < 0) { printf("error into sending msg to signal manager"); } } #endif SrcAddress.ai_family = paraThread->destHost.ai_family; if (SrcAddress.ai_family == PF_INET) { SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in)); SrcAddress.ai_addrlen = sizeof(struct sockaddr_in); } else if (SrcAddress.ai_family == PF_INET6) { SrcAddress.ai_addr = (struct sockaddr *) malloc(sizeof(struct sockaddr_in6)); SrcAddress.ai_addrlen = sizeof(struct sockaddr_in6); } pthread_cleanup_push(free, SrcAddress.ai_addr); if (passiveMode == false) { if ((newSock = accept(sock, SrcAddress.ai_addr, (socklen_t *) &SrcAddress.ai_addrlen)) < 0) reportErrorAndExit("tcpSock", "accept", "Cannot accept connection"); #ifdef MULTIPORT if ((passiveMode == false) && (socketAlreadyOpen == false)) { sharedTcpSockets[paraThread->indexPort].socket = sock; } sharedTcpSockets[paraThread->indexPort].inUse++; MUTEX_THREAD_UNLOCK(sharedTcpSockets[paraThread->indexPort].mutexSharedSockets); #else if ( closeSock(sock) == -1) reportErrorAndExit("tcpSock","closeSock","Cannot close socket sock"); #endif paraThread->socketClose = newSock; } else { struct addrinfo *SrcAddrForConnect = NULL; //#if (defined WIN32 && defined IPv6RECV) || defined UNIX || defined BSD if (paraThread->destHost.ai_family == PF_INET6) { getaddrinfo("::", NULL, &hint, &SrcAddrForConnect); } else //#endif { getaddrinfo("0.0.0.0", NULL, &hint, &SrcAddrForConnect); } SET_PORT((SrcAddrForConnect), htons((paraThread->portForPssv))); if (bind(sock, SrcAddrForConnect->ai_addr, SrcAddrForConnect->ai_addrlen) < 0) { struct pipeMsg msg; msg.code = MSG_FT_ERR1; msg.flowId = paraThread->flowId; if (sendPipeMsg(paraThread->rPipe, &msg) < 0) { printf(" sending msg error"); } sleep(INFINITE); } if (connect(sock, paraThread->destHost.ai_addr, paraThread->destHost.ai_addrlen) < 0) reportErrorAndExit("tcpSock", "connect", "Cannot connect (Passive Mode)"); PRINTD(1,"tcpSock: Connection establishes (Passive Mode)\n"); freeaddrinfo(SrcAddrForConnect); newSock = sock; paraThread->socketClose = sock; #ifdef WIN32 int len=SrcAddress.ai_addrlen; getsockname(sock,SrcAddress.ai_addr,&len); SrcAddress.ai_addrlen=len; #else getsockname(sock, SrcAddress.ai_addr, &SrcAddress.ai_addrlen); #endif } int firstpacket = 1; char HelpSrcAddress[INET6_ADDRSTRLEN]; char HelpDstAddress[INET6_ADDRSTRLEN]; int tmpPort_SrcPort = 0; int tmpPort_DstPort = 0; TSTART(_tstart, secs, msecs, first, 0, RECEIVER); PRINTD(1,"tcpSock: main loop\n"); while (1) { PRINTD(2, "tcpSock: preambleSize = %d \n",paraThread->preambleSize); size = TCPrecvPacket((unsigned char*) payload, newSock, paraThread->preambleSize, paraThread->payloadLogType); if (size <= 0) { PRINTD(1,"tcpSock: TCPrecvPacket() = %d\n",size); if (size < 0) { struct pipeMsg msg; if (passiveMode == false) { GET_PORT((&(paraThread->destHost)), tmpPort_DstPort); } else { GET_PORT((&SrcAddress), tmpPort_DstPort); } printf("Error on TCP port : %d\n", ntohs(tmpPort_DstPort)); printf("Finish on TCP port : %d\n\n", ntohs(tmpPort_DstPort)); fflush(stdout); msg.code = MSG_FT_ERR_SOCK; msg.flowId = paraThread->flowId; if (sendPipeMsg(paraThread->rPipe, &msg) < 0) { printf(" sending msg error"); } } sleep(INFINITE); } if (hComm > 0) { DTR_Disable(hComm); DTR_Enable(hComm); } GET_TIME_OF_DAY(&RcvTime, _tend, _tstart, secs, msecs, 0, RECEIVER); if ((logCheck != 0) || (logRemote != 0)) { if (firstpacket == 1) { if (passiveMode == false) { getInfo(&SrcAddress, tmpPort_SrcPort, HelpSrcAddress); getInfo(¶Thread->destHost, tmpPort_DstPort, HelpDstAddress); } else { #ifdef WIN32 int len=SrcAddress.ai_addrlen; getsockname(sock,SrcAddress.ai_addr,&len); SrcAddress.ai_addrlen=len; #else getsockname(sock, SrcAddress.ai_addr, &SrcAddress.ai_addrlen); #endif getInfo(¶Thread->destHost, tmpPort_SrcPort, HelpSrcAddress); getInfo(&SrcAddress, tmpPort_DstPort, HelpDstAddress); } firstpacket = 0; } if (paraThread->l7Proto == L7_PROTO_TELNET) size = size - 20; if (logCheck != 0) { int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); if (paraThread->payloadLogType == PL_STANDARD) { writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload, *(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, net_TimeSec, RcvTime.tv_sec % 86400L, net_TimeUsec, RcvTime.tv_usec, size); } else if (paraThread->payloadLogType == PL_SHORT) { writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload, *(unsigned int *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } else { writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } } if (logRemote != 0) { int net_TimeSec = ntohl(*(uint32_t *) ptrTimeSec); int net_TimeUsec = ntohl(*(uint32_t *) ptrTimeUsec); if (paraThread->payloadLogType == PL_STANDARD) { writeInBufferStandard(&infos[paraThread->count], *(uint32_t *) payload, *(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, net_TimeSec, RcvTime.tv_sec % 86400L, net_TimeUsec, RcvTime.tv_usec, size); } else if (paraThread->payloadLogType == PL_SHORT) { writeInBufferShort(&infos[paraThread->count], *(uint32_t *) payload, *(uint32_t *) ptrSeqNum, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } else { writeInBufferNone(&infos[paraThread->count], paraThread->flowId, HelpSrcAddress, HelpDstAddress, tmpPort_SrcPort, tmpPort_DstPort, RcvTime.tv_sec % 86400L, RcvTime.tv_usec, size); } infosHostToNet(&infos[paraThread->count]); } if (size != 0) paraThread->count++; if (paraThread->count == logbuffer_size) { if (logCheck != 0) flushBuffer((ofstream *) paraThread->fileLog, infos, paraThread->count); else if (logRemote != 0) { MUTEX_THREAD_LOCK(mutexLogRem); if (sendto(paraThread->logSock, (char *) infos, paraThread->count * sizeof(struct info), 0, paraThread->logHost->ai_addr, paraThread->logHost->ai_addrlen) < 0) reportErrorAndExit("tcpSock", "sendto", "Cannot send log infos to LogServer"); paraThread->count = 0; MUTEX_THREAD_UNLOCK(mutexLogRem); PRINTD(1,"tcpSock: Sent infos to LogServer\n"); } } } if (paraThread->meter == METER_RTTM) { if (sendto(newSock, (char *) payload, size, 0, SrcAddress.ai_addr, SrcAddress.ai_addrlen) < 0) reportErrorAndExit("tcpSock", "sendto", "Cannot send payload back for rttm"); PRINTD(2,"tcpSock: Sent RTTM infos\n"); } } pthread_cleanup_pop(1); return NULL; }
/** used by thread to process new request*/ void * processRequest(void * param) { RequestInfo *requestInfo = (RequestInfo *) param; int sockFd = requestInfo->sockFd; char *clientIP = requestInfo->clientIP; int clientPort = requestInfo->clientPort; printf("start to serve request from %s:%d\n", clientIP, clientPort); //receive request file information char requestFile[1024] = {0}; int recvStatus = recvFromSock(sockFd, requestFile, sizeof requestFile - 1, 1); if (recvStatus < 0) { printf("recv request info failed\n"); closeSock(sockFd); free(requestInfo); return NULL; } else if (recvStatus == 0) { printf("client has closed this connection\n"); closeSock(sockFd); free(requestInfo); return NULL; } printf("requestInfo: %s\n", requestFile); // check File existence and open file if (!checkFileExist(requestFile)) { printf("file doesn't exist: %s\n", requestFile); closeSock(sockFd); free(requestInfo); return NULL; } FILE * fd = fopen(requestFile, "r"); if (!fd) { printf("open request file failed\n"); goto cleanAndQuit; } // send requested file char buffer[1024]; unsigned int requestFileSize = getFileSize(requestFile); unsigned int readSize = 0; unsigned int sentSize = 0; printf("start to send to client\n"); while (readSize < requestFileSize) { unsigned int tempReadLen = 0; memset(buffer, 0, sizeof buffer); if ((tempReadLen = fread(buffer, sizeof(char), sizeof buffer -1, fd)) < 0) { printf("read file failed %d\n", tempReadLen); goto cleanAndQuit; } readSize += tempReadLen; //send to socket if (sendToSock(sockFd, buffer, tempReadLen, 1) != 1) { printf("send to sock failed\n"); goto cleanAndQuit; } sentSize += tempReadLen; //printf("send to client with len %d, sumLen, %d\n", sumSentLen, sentSize); if (canRead(sockFd) != 1) { continue; } printf("start to receive cancel/close msg\n"); memset(buffer, 0, sizeof buffer); int recvLen = recvFromSock(sockFd, buffer, sizeof buffer - 1, 1); if (recvLen <= 0) {// the other side has close the sockfd or some error happens printf("failed to recv close/cancel signal\n"); goto cleanAndQuit; } printf("sent %d KB data\n", sentSize / 1024); printf("receive cancel/close msg: %s\n", buffer); if (strcmp(buffer, CANCEL_MSG) == 0) { printf("wait for close after receiving cancel msg\n"); if (waitForClose(sockFd) == 1) { printf("client close connection, quit right now\n"); } else { printf("waitForClose Failed, quit right now\n"); } } else { printf("close after receiving close msg\n"); } cleanAndQuit: closeSock(sockFd); if (requestInfo) { free(requestInfo); } if (fd) { fclose(fd); } return NULL; } }