/*
** A "local" function of main().  Handles a #messageType# message arrived on
** #sd# accompanied by #dataSize# bytes of data.
*/
static void
ProcessRequest(Socket *sd,
               MessageType messageType,
               size_t dataSize) {

  unsigned long timeOut;
  DataDescriptor timeOutDescriptor = SIMPLE_DATA(UNSIGNED_LONG_TYPE, 1);
  char *matching;
  char *object;
  DataDescriptor objectDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);
  char *pattern;
  DataDescriptor patternDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);

  switch(messageType) {

  case NS_REGISTER:
    objectDescriptor.repetitions =
      dataSize - HomogenousDataSize(UNSIGNED_LONG_TYPE, 1, NETWORK_FORMAT);
    object = (char *)malloc(objectDescriptor.repetitions + 1);
    if(object == NULL) {
      (void)SendMessage(*sd, NS_FAILED, PktTimeOut(*sd));
      ERROR("ProcessRequest: out of memory\n");
    }
    else {
      if(!RecvData(*sd,
                   object,
                   &objectDescriptor,
                   1,
                   PktTimeOut(*sd)) ||
         !RecvData(*sd,
                   &timeOut,
                   &timeOutDescriptor,
                   1,
                   PktTimeOut(*sd))) {
        DROP_SOCKET(sd);
        ERROR("ProcessRequest: receive failed\n");
      }
      else {
        object[objectDescriptor.repetitions] = '\0';
        (void)SendMessage(*sd, NS_REGISTERED, PktTimeOut(*sd));
        /* Change time-out period to an expiration time. */
        if(timeOut != 0) {
          timeOut += (unsigned long)CurrentTime();
        }
        DoRegister(object, timeOut);
      }
      free(object);
    }
    break;

  case NS_SEARCH:
  case NS_UNREGISTER:
    patternDescriptor.repetitions = dataSize;
    pattern = (char *)malloc(dataSize);
    if(pattern == NULL) {
      (void)SendMessage(*sd, NS_FAILED, PktTimeOut(*sd));
      ERROR("ProcessRequest: out of memory\n");
    }
    else {
      if(!RecvData(*sd,
                   pattern,
                   &patternDescriptor,
                   1,
                   PktTimeOut(*sd))) {
        DROP_SOCKET(sd);
        ERROR("ProcessRequest: receive failed\n");
      }
      else if(messageType == NS_SEARCH) {
        matching = DoSearch(pattern);
        if(matching == NULL) {
          (void)SendMessage(*sd, NS_FAILED, PktTimeOut(*sd));
          ERROR("ProcessRequest: out of memory\n");
        }
        else {
          objectDescriptor.repetitions = strlen(matching) + 1;
          (void)SendMessageAndData(*sd,
                                   NS_SEARCHED,
                                   matching,
                                   &objectDescriptor,
                                   1,
                                   PktTimeOut(*sd));
          free(matching);
        }
      }
      else {
        DoUnregister(pattern);
        (void)SendMessage(*sd, NS_UNREGISTERED, PktTimeOut(*sd));
      }
      free(pattern);
    }
    break;

  default:
    ERROR1("ProcessRequest: unknown message %d\n", messageType);

  }

}
Exemplo n.º 2
0
//childloop
int ChildLoop(int acc, char *client_address, char *greeting){
	fd_set read_mask;
	fd_set write_mask;
	fd_set mask;
	int width;
	struct timeval timeout;
	int end_flag;
	int i;
	int comm_ptr = 0;
	int comm_esc = 0;
	int flag_comm_end = 0;
	int skip = 0;
	int is_exec = 0;
	DB(fprintf(stderr,"ChildLoop\n"));

	//block mode
	SetBlock(acc,0);

	//mask
	width=0;
	FD_ZERO(&mask);
	DB(fprintf(stderr,"sizeof(fd_set):%ld:\n",sizeof(fd_set)));
	DB(fprintf(stderr,"size of fds_bits:%ld:\n",sizeof(mask.__fds_bits)));
	DB(fprintf(stderr,"fds_bits[0]:%ld:\n",mask.__fds_bits[0]));
	DB(fprintf(stderr,"acc before FD_SET:%d:\n",acc));
	FD_SET(acc,&mask);
	DB(fprintf(stderr,"acc after FD_SET:%d:\n",acc));
	width=acc+1; //acc: (maximam during read_mask and write_mask) + 1
	DB(fprintf(stderr,"width (acc+1):%d:\n",width));

	//init data for sending
	SendBuf.size=SHORT_BUFF_SIZE;
	if((SendBuf.buf=calloc(SendBuf.size,sizeof(char))) == NULL){perror("calloc"); exit(1);}
	sprintf(SendBuf.buf,"Ready %s",VersionString());
	SendBuf.len=strlen(SendBuf.buf);

	//send-secv loop
	end_flag=0;
	while(1){
		is_exec = 0;
		read_mask=mask;
		if(SendBuf.len>0){
			write_mask=mask;
		}else{
			FD_ZERO(&write_mask);
		}
		timeout.tv_sec=TIMEOUT_S;
		timeout.tv_usec=TIMEOUT_US;
		switch(select(width,(fd_set *)&read_mask,&write_mask,NULL,&timeout)){
			case -1:
			if(errno!=EINTR){
				perror("select");
			}
			break;

			case 0:
			break;

			default:
			//recv
			if(FD_ISSET(acc,&read_mask)){
				//end_flag=RecvData(acc);
				RecvData(acc);
			}
			//operation after recv
			DB(fprintf(stderr,"after RecvData() RecvBuf.buf:%s:\n",RecvBuf.buf));
			DB(fprintf(stderr,"after RecvData() RecvBuf.len:%d:\n",RecvBuf.len));
			if((CommBuf.size - CommBuf.len) > RecvBuf.size){
				for(i=0;i<RecvBuf.len;i++){
					//if((RecvBuf.buf[i] == ';')&&(comm_esc == 0)){
					if((RecvBuf.buf[i] == 0x04)&&(comm_esc == 0)){
						CommBuf.buf[comm_ptr + i] = '\0';
						CommBuf.len = comm_ptr + i;
						flag_comm_end = 1;
						comm_esc = 0;
					}else if((RecvBuf.buf[i] == '\\')&&(comm_esc == 0)){
						comm_ptr = comm_ptr - 1;
						comm_esc = 1;
					}else if((RecvBuf.buf[i] == '\\')&&(comm_esc > 0)){
						CommBuf.buf[comm_ptr + i] = '\\';
						CommBuf.len = comm_ptr + i;
						comm_esc = 0;
					}else{
						CommBuf.buf[comm_ptr + i] = RecvBuf.buf[i];
						comm_esc = 0;
					}
					/*
					if(RecvBuf.buf[i] == '\\'){
						comm_esc++;
					}
					*/
					DB(fprintf(stderr,"commesc:%d:%c:",comm_esc,RecvBuf.buf[i]));
				}
				//DB(fprintf(stderr,"COMMSIZE:%d:\n",CommBuf.len));
				//DB(fprintf(stderr,"COMM:"));
				//DB(fprintf(stderr,"%s",CommBuf.buf));
				//DB(fprintf(stderr,":\n"));
			}else{
				flag_comm_end = 2;
			}
			/*
			if(strncmp(CommBuf.buf,"end",3) == 0){
				end_flag = 1;
			}
			*/
			//command operation 
			if(flag_comm_end == 1){
				//preprocess
				skip=0;
				comm_esc = 0;
				for(i=0;i<CommBuf.len;i++){
					if((CommBuf.buf[i] >= 33)&&(CommBuf.buf[i] <= 126)){
						break;
					}else{
						skip++;
					}
				}
				for(i=skip; i<CommBuf.len; i++){
					CommBuf.buf[i - skip] = CommBuf.buf[i];
				}
				CommBuf.buf[i - skip] = '\0';
				CommBuf.len = CommBuf.len - skip;
				DB(fprintf(stderr,"preprocessed COMMSIZE:%d:\n",CommBuf.len));
				DB(fprintf(stderr,"preprocessed COMM:"));
				DB(fprintf(stderr,"%s",CommBuf.buf));
				DB(fprintf(stderr,":\n"));
	
				//exec comm
				is_exec = ExecComm();

				//create SendData
				if((SendBuf.buf = malloc(sizeof(char) * (CommBuf.len + 40))) == NULL){perror("malloc()"); exit(1);}
				sprintf(SendBuf.buf,"%s","comm:");
				sprintf(SendBuf.buf+5,"%s",CommBuf.buf);
				sprintf(SendBuf.buf+5+CommBuf.len,"%s",":\n");
				SendBuf.len = strlen(SendBuf.buf);
				if(is_exec > 0){
					sprintf(SendBuf.buf+SendBuf.len,"%s",RsltBuf.buf);
					SendBuf.len = strlen(SendBuf.buf);
					if(RsltBuf.buf != NULL){
						free(RsltBuf.buf);
						RsltBuf.buf = NULL;
						RsltBuf.size = 0;
						RsltBuf.len = 0;
					}
				}

			}else if(flag_comm_end == 2){
				if((SendBuf.buf = malloc(sizeof(char) * (40))) == NULL){perror("malloc()"); exit(1);}
				sprintf(SendBuf.buf,"%s","error: commsize over.\n");
				SendBuf.len = strlen(SendBuf.buf);
				
			}

			//cleaning
			if(flag_comm_end == 1){
				if((CommBuf.len > 0) && (strncmp(CommBuf.buf,"end;",4) == 0)){
					end_flag = 1;
				}
				for(i=0;i<CommBuf.len;i++){
					CommBuf.buf[i] = '\0';
				}
				for(i=0;i<RecvBuf.len;i++){
					RecvBuf.buf[i] = '\0';
				}
				comm_ptr = 0;
				flag_comm_end = 0;
			}else{
				comm_ptr = comm_ptr + i;
			}
			//send
			if(FD_ISSET(acc,&write_mask)){
				SendData(acc,&SendBuf);
			}
			break;
		}
		if(end_flag == 1){
			DB(fprintf(stderr,"session break.\n"));
			break;
		}
	}
	return(0);
}
Exemplo n.º 3
0
//-----------------------------------------------------------------------------
int main(int argc, char** argv) {
	if(SDL_Init(SDL_INIT_TIMER|SDL_INIT_EVENTS) != 0) {
		fprintf(stderr, "ER: SDL_Init: %s\n", SDL_GetError());
		exit(-1);
	}

	if(SDLNet_Init() == -1) {
		fprintf(stderr, "ER: SDLNet_Init: %s\n", SDLNet_GetError());
		exit(-1);
	}

	IPaddress ip;
	if(SDLNet_ResolveHost(&ip, NULL, 8099) == -1) {
		fprintf(stderr, "ER: SDLNet_ResolveHost: %s\n", SDLNet_GetError());
		exit(-1);
	}

	sockets[SERVER_SOCKET] = SDLNet_TCP_Open(&ip);
	if(sockets[SERVER_SOCKET] == NULL) {
		fprintf(stderr, "ER: SDLNet_TCP_Open: %s\n", SDLNet_GetError());
		exit(-1);
	}

	socket_set = SDLNet_AllocSocketSet(MAX_SOCKETS);
	if(socket_set == NULL) {
		fprintf(stderr, "ER: SDLNet_AllocSocketSet: %s\n", SDLNet_GetError());
		exit(-1);
	}

	if(SDLNet_TCP_AddSocket(socket_set, sockets[SERVER_SOCKET]) == -1) {
		fprintf(stderr, "ER: SDLNet_TCP_AddSocket: %s\n", SDLNet_GetError());
		exit(-1);
	}

	int running = 1;
	while(running) {
		int num_rdy = SDLNet_CheckSockets(socket_set, 1000);

		if(num_rdy <= 0) {
			// NOTE: none of the sockets are ready
			int ind;
			for(ind=0; ind<MAX_SOCKETS; ++ind) {
				if(!clients[ind].in_use) continue;

				/*
				if(clients[ind].questing &&
					(SDL_GetTicks()-clients[ind].timer_wood)>WOOD_WAIT_TIME
				) {
					
					clients[ind].questing = 0;
					clients[ind].amt_wood += 4;
					char msg[0xFF] = "> quest complete\n\r";
					SendData(ind, msg, (strlen(msg)+1));
					
				}
				*/

				clients[ind].amt_wood += 4;

				/*
				uint16_t length = 0;
				uint8_t data[MAX_PACKET];

				memcpy(data+length, &clients[ind].amt_wood, sizeof(uint8_t));
				length += sizeof(uint8_t);

				SendData(ind, data, length, FLAG_WOOD_UPDATE);
				*/
			}
		} else {
			int ind;
			for(ind=0; (ind<MAX_SOCKETS) && num_rdy; ++ind) {
				if(sockets[ind] == NULL) continue;
				if(!SDLNet_SocketReady(sockets[ind])) continue;

				if(ind == SERVER_SOCKET) {
					int got_socket = AcceptSocket(next_ind);
					if(!got_socket) {
						num_rdy--;
						continue;
					}

					// NOTE: get a new index
					int chk_count;
					for(chk_count=0; chk_count<MAX_SOCKETS; ++chk_count) {
						if(sockets[(next_ind+chk_count)%MAX_SOCKETS] == NULL) break;
					}

					next_ind = (next_ind+chk_count)%MAX_SOCKETS;
					printf("DB: new connection (next_ind = %d)\n", next_ind);

					num_rdy--;
				} else {
					uint8_t* data;
					uint16_t flag;
					uint16_t length;
					
					data = RecvData(ind, &length, &flag);
					if(data == NULL) {
						num_rdy--;
						continue;
					}

					switch(flag) {
						case FLAG_WOOD_UPDATE: {
							uint16_t offset = 0;
							uint8_t send_data[MAX_PACKET];

							memcpy(send_data+offset, &clients[ind].amt_wood, sizeof(uint8_t));
							offset += sizeof(uint8_t);

							SendData(ind, send_data, offset, FLAG_WOOD_UPDATE);
						} break;
					}

					/*
					uint8_t* data; int length;

					data = RecvData(ind, &length);
					if(data == NULL) {
						num_rdy--;
						continue;
					}

					int i;
					for(i=0; i<length; ++i) {
						if(data[i] == '\n') data[i] = '\0';
						if(data[i] == '\r') data[i] = '\0';
					}

					// TEMP: add a NULL terminator
					data = (uint8_t*) realloc(data, (length+1));
					data[length] = '\0';

					int was_processed = 0;
					if(!strcmp(data, "exit")) {

						was_processed = 1;
						running = 0;

					} else if(!strcmp(data, "quit")) {

						was_processed = 1;
						CloseSocket(ind);

					} else if(!strcmp(data, "get data")) {

						was_processed = 1;
						char msg[0xFF] = {};
						sprintf(msg, "> wood: %d\n\r", clients[ind].amt_wood);
						//SendData(ind, msg, (strlen(msg)+1));

					} else if(!strcmp(data, "quest")) {

						was_processed = 1;
						if(!clients[ind].questing) {
							clients[ind].questing = 1;
							clients[ind].timer_wood = SDL_GetTicks();
							char msg[0xFF] = "> started quest\n\r";
							//SendData(ind, msg, (strlen(msg)+1));
						} else {
							char msg[0xFF] = "> currently running quest\n\r";
							//SendData(ind, msg, (strlen(msg)+1));
						}

					}

					if(was_processed) printf("PR: %s\n", data);
					free(data);
					*/

					num_rdy--;
				}
			}
		}
	}

	int i;
	for(i=0; i<MAX_SOCKETS; ++i) {
		if(sockets[i] == NULL) continue;
		CloseSocket(i);
	}

	SDLNet_FreeSocketSet(socket_set);
	SDLNet_Quit();
	SDL_Quit();

	return 0;
}
Exemplo n.º 4
0
//处理输入事件
void Connection::OnRead()
{
    log::log(Info,"on read");
    //接收数据
    RecvData();
}
Exemplo n.º 5
0
void CProConnectClient::handle_read_stream(const ACE_Asynch_Read_Stream::Result &result)
{
	ACE_Message_Block& mb = result.message_block();
	uint32 u4PacketLen = (uint32)result.bytes_transferred();

	//OUR_DEBUG((LM_DEBUG,"[CProConnectClient::handle_read_stream] m_nServerID=%d, bytes_transferred=%d, this=0x%08x.\n", 
	//	m_nServerID, 
	//	u4PacketLen,
	//	this));
	
	if(!result.success() || u4PacketLen == 0)
	{
		mb.release();
		if(NULL != m_pClientMessage)
		{
			_ClientIPInfo objServerIPInfo;
			sprintf_safe(objServerIPInfo.m_szClientIP, MAX_BUFF_20, "%s", m_AddrRemote.get_host_addr());
			objServerIPInfo.m_nPort = m_AddrRemote.get_port_number();
			
			//这里只处理远端服务器断开连接的消息,回调ConnectError
			//服务器主动关闭不在回调ConnectError
			if(S2S_NEED_CALLBACK == m_ems2s)
			{
				m_pClientMessage->ConnectError((int)ACE_OS::last_error(), objServerIPInfo);
			}
		}
		//OUR_DEBUG((LM_INFO, "[CProConnectClient::handle_read_stream]m_ems2s=%d.\n", m_ems2s));
		Close();
		return;
	}
	else 
	{
		//处理接收数据(这里不区分是不是完整包,交给上层逻辑自己去判定)
		if(NULL != m_pClientMessage)
		{
			_ClientIPInfo objServerIPInfo;
			sprintf_safe(objServerIPInfo.m_szClientIP, MAX_BUFF_20, "%s", m_AddrRemote.get_host_addr());
			objServerIPInfo.m_nPort = m_AddrRemote.get_port_number();
			//m_pClientMessage->RecvData(&mb, objServerIPInfo);

			//这里处理一下是不是完整包
			uint16 u2CommandID             = 0;
			ACE_Message_Block* pRecvFinish = NULL;

			m_atvRecv     = ACE_OS::gettimeofday();
			m_emRecvState = SERVER_RECV_BEGIN;

			while(true)
			{
				bool blRet = m_pClientMessage->Recv_Format_data(&mb, App_MessageBlockManager::instance(), u2CommandID, pRecvFinish);
				if(true == blRet)
				{
					//调用数据包处理
					m_pClientMessage->RecvData(u2CommandID, pRecvFinish, objServerIPInfo);
					//回收处理包
					App_MessageBlockManager::instance()->Close(pRecvFinish);
				}
				else
				{
					break;
				}
			}

		}
		mb.release();
		m_emRecvState = SERVER_RECV_END;


		//接受下一个数据包
		RecvData(App_MainConfig::instance()->GetConnectServerRecvBuffer());
	}
}
void CListener::ProcessRead(SOCKET sock)
{
	MSG_HEADER	hdr;
	int			iError = 0;

	if (!RecvHeader(sock, (char*)&hdr, sizeof (MSG_HEADER), 0, &iError))
	{
		if (iError)
		{
			// check existence of the connection and close	
			CloseConnection(sock);
		}
		else	// nonfatal error -> don't close connection
		{
		}
		return;
	}
	else
	{
		hdr.ConvertNTOH();
	}

	if (hdr.Command < VCM_MIN || hdr.Command > VCM_MAX)
	{
		// invalid command
		// check existence of the connection and close
		CloseConnection(sock);
		return;
	}

	if (hdr.DataLen < 0)
	{
		// check existence of the connection and close
		CloseConnection(sock);
		return;
	}

#ifdef UNICODE
	if (hdr.DataLen % 2 != 0)
	{
		// invalid data (because data is a widechar string, number of bytes must be even)		
		// check existence of the connection and close
		CloseConnection(sock);
	}
#endif

	if (hdr.DataLen > 0)
	{
		int		iNumTChar = hdr.DataLen/sizeof(TCHAR);
		TCHAR	*pData;

		pData = new TCHAR[iNumTChar + 1];
		if (!pData)
		{
			CloseConnection(sock);
			return;
		}

		if (!RecvData(sock, (char*)pData, hdr.DataLen, 0, &iError))
		{
			delete []pData;
			if (iError)
			{
				// check existence of the connection and close
				CloseConnection(sock);
			}
			return;
		}

		pData[iNumTChar] = 0;
		ProcessCmd(hdr, pData, sock);
		delete []pData;
	}
	else
	{
		ProcessCmd(hdr, _T(""), sock);
	}
}
Exemplo n.º 7
0
LONG	CCardIssuer::TransmissionControl(BYTE bCommandCode, BYTE bParameterCode, PBYTE pbRecvBuff, PDWORD pcbRecvLength)
{
	BOOL bTimeOut;

	if (! PurgeComm(m_hDevice, PURGE_FLAGS))
		return F1_E_UNKNOWN_ERROR;

	// 发送命令
	//
	if (! SendData(m_bBuffer, m_cBuffer, &bTimeOut))
	{
		if (bTimeOut)
			return F1_E_COMM_TIMEOUT;
		else 
			return F1_E_UNKNOWN_ERROR;
	}

	if (! WaitForBytesAvailable(500))
		return F1_E_COMM_TIMEOUT;

	// 接受 ACK
	//
	if (! RecvData(m_bBuffer, m_bAddress == 0xff ? 1 : 3, &bTimeOut))
	{
		if (bTimeOut)
			return F1_E_COMM_TIMEOUT;
		else 
			return F1_E_UNKNOWN_ERROR;
	}

	if (m_bBuffer[0] != ACK)
		return F1_E_INTERNAL_ERROR;

	// 发送 ENQ
	//
	m_bBuffer[0] = ENQ;
	m_bBuffer[1] = (m_bAddress / 10) + 0x30;
	m_bBuffer[2] = (m_bAddress % 10) + 0x30;

	if (! SendData(m_bBuffer, m_bAddress == 0xff ? 1 : 3, &bTimeOut))
	{
		if (bTimeOut)
			return F1_E_COMM_TIMEOUT;
		else 
			return F1_E_UNKNOWN_ERROR;
	}

	if ( pbRecvBuff != NULL 
		&& pcbRecvLength != NULL )
	{
		if ( *pcbRecvLength > 0 )
		{
			if (! WaitForBytesAvailable( 5000 ) )
				return F1_E_COMM_TIMEOUT;

			m_cBuffer = *pcbRecvLength + (m_bAddress == 0xff ? 5: 7);
			if (! RecvData(m_bBuffer, m_cBuffer, &bTimeOut))
			{
				if (bTimeOut)
					return F1_E_COMM_TIMEOUT;
				else 
					return F1_E_UNKNOWN_ERROR;
			}

			BYTE bcc = GetBCC(m_bBuffer, m_cBuffer);
			if ( m_bBuffer[m_cBuffer - 1] != bcc)
				return F1_E_INTERNAL_ERROR;

			memcpy( pbRecvBuff, &m_bBuffer[ m_bAddress == 0xff ? 3 : 5], *pcbRecvLength);
		}
	}

	return 0;
}
Exemplo n.º 8
0
int CHttpDownLoad::UrlDownLoad()
{

	int iRet=S_ERRO;
	FormatRequestHeader();

	if(!Connect(m_szHost,m_wPort)) 
	{
		return S_PARTDOWN;
	}
	
	if(!SendRequest()) return S_PARTDOWN;

	char szValue[30]={0};

	if(GetField("Content-Length",szValue,30)==-1)
	{
		LOG((LEVEL_ERROR,"CHttpDownLoad::UrlDownLoad  Not Get Content_Lenth\r\n"));

		return iRet;
	}


	DWORD nFileSize = atoi(szValue);
	if (m_dwOffset==0){
		m_dwFileLen=nFileSize;
	}

	if (nFileSize==0||nFileSize>1024*1024*2){
		return iRet;
	}

	//Content-Range: bytes 1000-5000/5001
	memset(szValue,0,30);

	if(GetField("Content-Range",szValue,30)!=-1)
	{
		char *p=strstr(szValue,"/");
		if (!p)
		{
			return iRet;
		}
		p++;
		m_dwFileLen= atoi(p);
		if (m_dwFileLen==0)
		{
			return iRet;
		}
	}

	DWORD dwRecvLen=MAXHEADERSIZE;
	char *pData =new char [dwRecvLen];
	if (pData==NULL)
	{
		LOG((LEVEL_ERROR,"CHttpDownLoad::UrlDownLoad  new pData erro:%d\r\n",GetLastError()));
		return iRet;
	}

	int nReceSize = 0;
	DWORD nCompletedSize = 0;
	
	SetFilePointer(m_hOutFileHandle,0,0,FILE_END);
	DWORD iWriteFileSize;

	while(nCompletedSize < nFileSize)
	{
		memset(pData,0,dwRecvLen);
		nReceSize = RecvData((LPBYTE)pData,dwRecvLen);
		if(nReceSize<=0){
			LOG((LEVEL_ERROR,"CHttpDownLoad::UrlDownLoad- m_TcpSocket.RecvData erro :%d\r\n",WSAGetLastError()));
			break;
		}


		if ((DWORD)nReceSize>nFileSize-nCompletedSize){
			break;
		}

		WriteFile(m_hOutFileHandle,pData,nReceSize,&iWriteFileSize,NULL);

		nCompletedSize += nReceSize;
	}

	delete [] pData;

// 	if (m_dwFileLen){
// 		iRes=m_dwFileLen==GetFileSize(m_hOutFileHandle,0)?1:-1;
// 	}


	iRet=nCompletedSize==nFileSize?S_FULLDOWN:S_PARTDOWN;

	return iRet;

}
Exemplo n.º 9
0
int EvaluateStr(const string& scd_file_address, const string& p_init_str,
                const string& p_input_str, const string& init_str,
                const string& input_str, uint64_t clock_cycles,
                const string& output_mask, int64_t terminate_period,
                OutputMode output_mode, bool disable_OT, bool low_mem_foot,
                string* output_str, int connfd) {
  if (clock_cycles == 0) {
    return FAILURE;
  }

  GarbledCircuit garbled_circuit;
  if (ReadSCD(scd_file_address, &garbled_circuit) == FAILURE) {
    LOG(ERROR) << "Error while reading scd file: " << scd_file_address << endl;
    return FAILURE;
  }
  FillFanout(&garbled_circuit);

  if (terminate_period != 0 && garbled_circuit.terminate_id == 0) {
    LOG(ERROR) << "There is no terminate signal in the circuit."
               " The terminate period should be 0."
               << endl;
    return FAILURE;
  }

  // allocate init and input values and translate form string
  BIGNUM* p_init = BN_new();
  BIGNUM* p_input = BN_new();
  BIGNUM* e_init = BN_new();
  BIGNUM* e_input = BN_new();
  BIGNUM* output_bn = BN_new();
  CHECK(
      ParseInitInputStr(init_str, input_str, garbled_circuit.e_init_size,
                        garbled_circuit.e_input_size, clock_cycles, &e_init,
                        &e_input));
  CHECK(
      ParseInitInputStr(p_init_str, p_input_str, garbled_circuit.p_init_size,
                        garbled_circuit.p_input_size, clock_cycles, &p_init,
                        &p_input));

  // global key
  block global_key = RandomBlock();
  CHECK(RecvData(connfd, &global_key, sizeof(block)));  // receive global key

  if (low_mem_foot && clock_cycles > 1) {
    CHECK(
        EvaluateBNLowMem(garbled_circuit, p_init, p_input, e_init, e_input,
                         &clock_cycles, output_mask, terminate_period,
                         output_mode, output_bn, global_key, disable_OT,
                         connfd));
    CHECK(
        OutputBN2StrLowMem(garbled_circuit, output_bn, clock_cycles,
                           output_mode, output_str));
  } else {
    CHECK(
        EvaluateBNHighMem(garbled_circuit, p_init, p_input, e_init, e_input,
                          &clock_cycles, output_mask, terminate_period,
                          output_mode, output_bn, global_key, disable_OT,
                          connfd));
    CHECK(
        OutputBN2StrHighMem(garbled_circuit, output_bn, clock_cycles,
                            output_mode, output_str));
  }
  BN_free(p_init);
  BN_free(p_input);
  BN_free(e_init);
  BN_free(e_input);
  BN_free(output_bn);

  RemoveGarbledCircuit(&garbled_circuit);
  return SUCCESS;
}
Exemplo n.º 10
0
void CNetInstall::StartTask(std::vector<tagFileInfo> *pVecInfo)
{
	size_t nCount = pVecInfo->size();

	if (m_wFBIVer == MAKEWORD(2, 0))
	{
		size_t nRealCount = 0;
		for (size_t i = 0; i < nCount; ++i)
		{
			if ((*pVecInfo)[i].bSelected)
			{
				++nRealCount;
			}
		}
		UINT32 nTs = htonl(nRealCount);
		if (SendData((LPBYTE)&nTs, sizeof(nTs)))
		{
			UINT8 ack = 0;
			RecvData(&ack, sizeof(ack));
			bool bFailFlag = false;
			for (size_t i = 0; i < nCount; ++i)
			{
				(*pVecInfo)[i].dwBeginTime = GetTickCount();
				m_sProgressCallBack(&(*pVecInfo)[i], 0);
				if (!(*pVecInfo)[i].bSelected)
					continue;

				UINT64 SendNetNum = htonll((*pVecInfo)[i].uFileSize);
				if (SendData((LPBYTE)&SendNetNum, sizeof(SendNetNum)))
				{
					if (!TransFile(&(*pVecInfo)[i]))
					{
						bFailFlag = true;
						((*pVecInfo)[i]).dwError = ERR_FAIL;
						m_sProgressCallBack(&(*pVecInfo)[i], 0);
					}

				}
				else
				{
					bFailFlag = true;
					((*pVecInfo)[i]).dwError = ERR_FAIL;
					m_sProgressCallBack(&(*pVecInfo)[i], 0);
				}

				if (bFailFlag)
				{
					(*pVecInfo)[i].bSelected = false;
				}
			}
		}
		else
		{
			MessageBoxW(0, L"eeeerr", 0, 0);
		}
	}
	else if (m_wFBIVer == MAKEWORD(1, 0))
	{
		//under construction
		for (size_t i = 0; i < nCount; ++i)
		{
			m_sProgressCallBack(&(*pVecInfo)[i], 0);
			if (!(*pVecInfo)[i].bSelected)
				continue;

			UINT64 SendNetNum = htonll((*pVecInfo)[i].uFileSize);
			if (SendData((LPBYTE)&SendNetNum, sizeof(SendNetNum)))
			{
				if (!TransFile(&(*pVecInfo)[i]))
				{
					break;
				}
				
			}
			else
			{
				((*pVecInfo)[i]).dwError = ERR_FAIL;
				m_sProgressCallBack(&(*pVecInfo)[i], 0);
			}
		}
	}






	DisConnect();
}
Exemplo n.º 11
0
int main(int argc, char *argv[])
{
    FILE        *out;           /* Output data file                          */
    char        s[255];         /* Generic string                            */
    char        *memtmp;
    char        *memtmp1;

    int         c,              /* option index                              */
                i, j, n, nq,    /* Loop indices                              */
		asyncReceive=0, /* Pre-post a receive buffer?                */
                bufoffset=0,    /* Align buffer to this                      */
                bufalign=16*1024,/* Boundary to align buffer to              */
		errFlag,        /* Error occurred in inner testing loop      */
                nrepeat,        /* Number of time to do the transmission     */
                len,            /* Number of bytes to be transmitted         */
                inc=0,          /* Increment value                           */
                trans=-1,       /* Transmitter flag. 1 if transmitting.      */
                server=0,       /* Server flag. 1 if specifying server.      */
                detailflag=0,   /* Set to examine the signature curve detail */
                bufszflag=0,    /* Set to change the TCP socket buffer size  */
                pert,           /* Perturbation value                        */
                start=1,        /* Starting value for signature curve        */
                end=MAXINT,     /* Ending value for signature curve          */
                streamopt=0,    /* Streaming mode flag                       */
                printopt=0;     /* Debug print statements flag               */
   
    ArgStruct   args;           /* Argumentsfor all the calls                */

    double      t, t0, t1, t2,  /* Time variables                            */
                tlast,          /* Time for the last transmission            */
                latency;        /* Network message latency                   */

    Data        bwdata[NSAMP];  /* Bandwidth curve data                      */

    short       port=DEFPORT;   /* Port number for connection                */
#ifdef HAVE_GETRUSAGE
    struct rusage prev_rusage, curr_rusage; /* Resource usage                */
    double	utime, stime;	/* User & system time used                   */
    double	best_utime, best_stime; /* Total user & system time used     */
    double      ut1, ut2, st1, st2; /* User & system time ctrs for variance  */
    double	ut_var, st_var;	/* Variance in user & system time            */
#endif

#ifdef MPI
    MPI_Init(&argc, &argv);
#endif

    strcpy(s, "NetPIPE.out");
#ifndef MPI
    if(argc < 2)
     PrintUsage();
#endif
    /* Parse the arguments. See Usage for description */
    while ((c = getopt(argc, argv, "PstrhH:p:o:A:O:l:u:i:b:a")) != -1)
    {
        switch(c)
        {
            case 'o': strcpy(s,optarg);
                      break;

            case 't': trans = 1;
                      break;
            
            case 'r': trans = 0;
                      break;

            case 's': streamopt = 1;
                      break;

            case 'l': /*detailflag = 1;*/
                      start = atoi(optarg);
                      if (start < 1)
                      {
                        fprintf(stderr,"Need a starting value >= 1\n");
                        exit(743);
                      }
                      break;

            case 'u': /*detailflag = 1;*/
                      end = atoi(optarg);
                      break;

            case 'i': detailflag = 1;
                      inc = atoi(optarg);
                      break;

            case 'b': bufszflag = 1;
#ifdef TCP
                      args.prot.rcvbufsz=atoi(optarg);
                      args.prot.sndbufsz=args.prot.rcvbufsz;
#endif
                      break;

            case 'P': printopt = 1;
                      break;
            
            case 'A': bufalign = atoi(optarg);
                      break;

            case 'O': bufoffset = atoi(optarg);
                      break;

            case 'p': port = atoi(optarg);
                      break;
            
            case 'h': if (trans == 1)
                      {
                          args.host = (char *)malloc(strlen(optarg)+1);
                          strcpy(args.host, optarg);
			  printf("host is %s\n",args.host);
                      }
		      else
		      {
			  fprintf(stderr, "Error: -t must be specified before -h\n");
			  exit(-11);
		      }
                      break;

            case 'H': if (trans == 0)
                      {
                          args.server_host = (char *)malloc(strlen(optarg)+1);
                          strcpy(args.server_host, optarg);
			  printf("server is %s\n",args.server_host);
			  server = 1;
                      }
		      else
		      {
			  fprintf(stderr, "Error: -r must be specified before -H\n");
			  exit(-11);
		      }
                      break;

	    case 'a': asyncReceive = 1;
		      break;

            default:  PrintUsage(); 
                      exit(-12);
        }
    }
    if (start > end)
    {
        fprintf(stderr, "Start MUST be LESS than end\n");
        exit(420132);
    }
#if defined(TCP) || defined(PVM)
    /*
      It should be explicitly specified whether this is the transmitter
      or the receiver.
    */
    if (trans < 0)
    {
	fprintf(stderr, "Error: either -t or -r must be specified\n");
	exit(-11);
    }
#endif

    args.nbuff = TRIALS;
    args.tr = trans;
    args.sr = server;
    args.port = port;

#if defined(TCP)
    if (!bufszflag)
    {
        args.prot.sndbufsz = 0;
        args.prot.rcvbufsz = 0;
    }
    else
        fprintf(stderr,"Send and Recv Buffers are %d bytes\n",
                                                   args.prot.sndbufsz);
#endif

    Setup(&args);
    Establish(&args);

    if (args.tr)
    {
        if ((out = fopen(s, "w")) == NULL)
        {
            fprintf(stderr,"Can't open %s for output\n", s);
            exit(1);
        }
    }
    else
        out = stdout;

    args.bufflen = 1;
    args.buff = (char *)malloc(args.bufflen);
    args.buff1 = (char *)malloc(args.bufflen);
    if (asyncReceive)
	PrepareToReceive(&args);
    Sync(&args);
    t0 = When();
    t0 = When();
    t0 = When();
#ifdef HAVE_GETRUSAGE
    getrusage(RUSAGE_SELF, &prev_rusage);
#endif
    t0 = When();
    for (i = 0; i < LATENCYREPS; i++)
    {
        if (args.tr)
        {
            SendData(&args);
            RecvData(&args);
	    if (asyncReceive && (i < LATENCYREPS - 1))
	    {
		PrepareToReceive(&args);
	    }
        }
        else
        {
            RecvData(&args);
	    if (asyncReceive && (i < LATENCYREPS - 1))
	    {
		PrepareToReceive(&args);
	    }
            SendData(&args);
        }
    }
    latency = (When() - t0)/(2 * LATENCYREPS);
#ifdef HAVE_GETRUSAGE
    getrusage(RUSAGE_SELF, &curr_rusage);
#endif
    free(args.buff);
    free(args.buff1);


    if (args.tr)
    {
        SendTime(&args, &latency);
    }
    else
    {
        RecvTime(&args, &latency);
    }
    if (args.tr && printopt)
    {
        fprintf(stderr,"Latency: %.7f\n", latency);
        fprintf(stderr,"Now starting main loop\n");
    }
    tlast = latency;
    if (inc == 0)
    {
	/* Set a starting value for the message size increment. */
	inc = (start > 1) ? start / 2 : 1;
    }

    /* Main loop of benchmark */
    for (nq = n = 0, len = start, errFlag = 0; 
         n < NSAMP - 3 && tlast < STOPTM && len <= end && !errFlag; 
         len = len + inc, nq++ )
    {
        if (nq > 2 && !detailflag)
	  {
	    /*
	      This has the effect of exponentially increasing the block
	      size.  If detailflag is false, then the block size is
	      linearly increased (the increment is not adjusted).
	    */
            inc = ((nq % 2))? inc + inc: inc;
	  }
        
        /* This is a perturbation loop to test nearby values */
        for (pert = (!detailflag && inc > PERT+1)? -PERT: 0;
             pert <= PERT; 
             n++, pert += (!detailflag && inc > PERT+1)? PERT: PERT+1)
        {

            /* Calculate how many times to repeat the experiment. */
            if (args.tr)
            {
                nrepeat = MAX((RUNTM / ((double)args.bufflen /
                                 (args.bufflen - inc + 1.0) * tlast)), TRIALS);
                SendRepeat(&args, nrepeat);
            }
            else
            {
                RecvRepeat(&args, &nrepeat);
            }

            /* Allocate the buffer */
            args.bufflen = len + pert;
            if((args.buff=(char *)malloc(args.bufflen+bufalign))==(char *)NULL)
            {
                fprintf(stderr,"Couldn't allocate memory\n");
		errFlag = -1;
                break;
            }
            if((args.buff1=(char *)malloc(args.bufflen+bufalign))==(char *)NULL)
            {
                fprintf(stderr,"Couldn't allocate memory\n");
		errFlag = -1;
                break;
            }
            /*
	      Possibly align the data buffer: make memtmp and memtmp1
	      point to the original blocks (so they can be freed later),
	      then adjust args.buff and args.buff1 if the user requested it.
	    */
            memtmp = args.buff;
            memtmp1 = args.buff1;
            if (bufalign != 0)
                args.buff +=(bufalign - 
                        ((intptr_t)args.buff % bufalign) + bufoffset) % bufalign;

            if (bufalign != 0)
                args.buff1 +=(bufalign - 
                        ((intptr_t)args.buff1 % bufalign) + bufoffset) % bufalign;


            if (args.tr && printopt)
                fprintf(stderr,"%3d: %9d bytes %4d times --> ",
                                 n,args.bufflen,nrepeat);

            /* Finally, we get to transmit or receive and time */
            if (args.tr)
            {
		/*
		   This is the transmitter: send the block TRIALS times, and
		   if we are not streaming, expect the receiver to return each
		   block.
		*/
                bwdata[n].t = LONGTIME;
                t2 = t1 = 0;
#ifdef HAVE_GETRUSAGE
		ut1 = ut2 = st1 = st2 = 0.0;
		best_utime = best_stime = LONGTIME;
#endif
                for (i = 0; i < TRIALS; i++)
                {
                    Sync(&args);
#ifdef HAVE_GETRUSAGE
		    getrusage(RUSAGE_SELF, &prev_rusage);
#endif
                    t0 = When();
                    for (j = 0; j < nrepeat; j++)
                    {
			if (asyncReceive && !streamopt)
			{
			    PrepareToReceive(&args);
			}
                        SendData(&args);
                        if (!streamopt)
			{
                            RecvData(&args);
			}
                    }
                    t = (When() - t0)/((1 + !streamopt) * nrepeat);
#ifdef HAVE_GETRUSAGE
		    getrusage(RUSAGE_SELF, &curr_rusage);
		    utime = ((curr_rusage.ru_utime.tv_sec -
			      prev_rusage.ru_utime.tv_sec) + (double)
			     (curr_rusage.ru_utime.tv_usec -
			      prev_rusage.ru_utime.tv_usec) * 1.0E-6) /
		      ((1 + !streamopt) * nrepeat);
		    stime = ((curr_rusage.ru_stime.tv_sec -
			      prev_rusage.ru_stime.tv_sec) + (double)
			     (curr_rusage.ru_stime.tv_usec -
			      prev_rusage.ru_stime.tv_usec) * 1.0E-6) /
		      ((1 + !streamopt) * nrepeat);
		    ut2 += utime * utime;
		    st2 += stime * stime;
		    ut1 += utime;
		    st1 += stime;
		    if ((utime + stime) < (best_utime + best_stime))
		    {
			best_utime = utime;
			best_stime = stime;
		    }
#endif

                    if (!streamopt)
                    {
                        t2 += t*t;
                        t1 += t;
                        bwdata[n].t = MIN(bwdata[n].t, t);
                    }
                }
                if (!streamopt)
                    SendTime(&args, &bwdata[n].t);
                else
                    RecvTime(&args, &bwdata[n].t);

                if (!streamopt)
                    bwdata[n].variance = t2/TRIALS - t1/TRIALS * t1/TRIALS;

#ifdef HAVE_GETRUSAGE
		ut_var = ut2/TRIALS - (ut1/TRIALS) * (ut1/TRIALS);
		st_var = st2/TRIALS - (st1/TRIALS) * (st1/TRIALS);
#endif

            }
            else
            {
		/*
		   This is the receiver: receive the block TRIALS times, and
		   if we are not streaming, send the block back to the
		   sender.
		*/
                bwdata[n].t = LONGTIME;
                t2 = t1 = 0;
                for (i = 0; i < TRIALS; i++)
                {
		    if (asyncReceive)
		    {
		    	PrepareToReceive(&args);
		    }
                    Sync(&args);
                    t0 = When();
                    for (j = 0; j < nrepeat; j++)
                    {
                        RecvData(&args);
			if (asyncReceive && (j < nrepeat - 1))
			{
			    PrepareToReceive(&args);
			}
                        if (!streamopt)
                            SendData(&args);
                    }
                    t = (When() - t0)/((1 + !streamopt) * nrepeat);

                    if (streamopt)
                    {
                        t2 += t*t;
                        t1 += t;
                        bwdata[n].t = MIN(bwdata[n].t, t);
                    }
                }
                if (streamopt)
                    SendTime(&args, &bwdata[n].t);
                else
                    RecvTime(&args, &bwdata[n].t);

                if (streamopt)
                    bwdata[n].variance = t2/TRIALS - t1/TRIALS * t1/TRIALS;

            }
            tlast = bwdata[n].t;
            bwdata[n].bits = args.bufflen * CHARSIZE;
            bwdata[n].bps = bwdata[n].bits / (bwdata[n].t * 1024 * 1024);
            bwdata[n].repeat = nrepeat;
            
            if (args.tr)
	    {
		fprintf(out, "%.7f %.7f %d %d %.7f", bwdata[n].t, bwdata[n].bps,
			bwdata[n].bits, bwdata[n].bits / 8,
			bwdata[n].variance);
#ifdef HAVE_GETRUSAGE
		fprintf(out, " %.7f %.7f %.7f %.7f", ut1 / (double) TRIALS,
			st1 / (double) TRIALS, ut_var, st_var);
#endif
		fprintf(out, "\n");
	    }
            fflush(out);

            free(memtmp);
            free(memtmp1);

            if (args.tr && printopt)
	    {
        	fprintf(stderr," %6.3f Mbps in %.7f sec", bwdata[n].bps,
			tlast);
#ifdef HAVE_GETRUSAGE
		fprintf(stderr, ", avg utime=%.7f avg stime=%.7f, ",
			ut1 / (double) TRIALS,
			st1 / (double) TRIALS);
		fprintf(stderr, "min utime=%.7f stime=%.7f, ", best_utime,
			best_stime);
		fprintf(stderr, "utime var=%.7f stime var=%.7f", ut_var, st_var);
#endif
		fprintf(stderr, "\n");
	    }
        } /* End of perturbation loop */

    } /* End of main loop  */
        
    if (args.tr)
       fclose(out);
         
    CleanUp(&args);
    return(0);
}
Exemplo n.º 12
0
int main(int argc, char **argv)
{
    FILE        *out;           /* Output data file                          */
    char        s[255],s2[255],delim[255],*pstr; /* Generic strings          */
    int         *memcache;      /* used to flush cache                       */

    int         len_buf_align,  /* meaningful when args.cache is 0. buflen   */
                                /* rounded up to be divisible by 8           */
                num_buf_align;  /* meaningful when args.cache is 0. number   */
                                /* of aligned buffers in memtmp              */

    int         c,              /* option index                              */
                i, j, n, nq,    /* Loop indices                              */
                asyncReceive=0, /* Pre-post a receive buffer?                */
                bufalign=16*1024,/* Boundary to align buffer to              */
                errFlag,        /* Error occurred in inner testing loop      */
                nrepeat,        /* Number of time to do the transmission     */
                nrepeat_const=0,/* Set if we are using a constant nrepeat    */
                len,            /* Number of bytes to be transmitted         */
                inc=0,          /* Increment value                           */
                perturbation=DEFPERT, /* Perturbation value                  */
                pert,
                start= 1,       /* Starting value for signature curve        */
                end=MAXINT,     /* Ending value for signature curve          */
                streamopt=0,    /* Streaming mode flag                       */
                reset_connection;/* Reset the connection between trials      */
   
    ArgStruct   args;           /* Arguments for all the calls               */

    double      t, t0, t1, t2,  /* Time variables                            */
                tlast,          /* Time for the last transmission            */
                latency;        /* Network message latency                   */

    Data        bwdata[NSAMP];  /* Bandwidth curve data                      */

    int         integCheck=0;   /* Integrity check                           */

    /* Initialize vars that may change from default due to arguments */

    strcpy(s, "np.out");   /* Default output file */

    /* Let modules initialize related vars, and possibly call a library init
       function that requires argc and argv */


    Init(&args, &argc, &argv);   /* This will set args.tr and args.rcv */

    args.preburst = 0; /* Default to not bursting preposted receives */
    args.bidir = 0; /* Turn bi-directional mode off initially */
    args.cache = 1; /* Default to use cache */
    args.upper = end;
    args.host  = NULL;
    args.soffset=0; /* default to no offsets */
    args.roffset=0; 
    args.syncflag=0; /* use normal mpi_send */


    /* TCGMSG launches NPtcgmsg with a -master master_hostname
     * argument, so ignore all arguments and set them manually 
     * in netpipe.c instead.
     */

#if ! defined(TCGMSG)

    /* Parse the arguments. See Usage for description */
    while ((c = getopt(argc, argv, "SO:rIiPszgfaB2h:p:o:l:u:b:m:n:t:c:d:D:")) != -1)
    {
        switch(c)
        {
            case 'O':
                      strcpy(s2,optarg);
                      strcpy(delim,",");
                      if((pstr=strtok(s2,delim))!=NULL) {
                         args.soffset=atoi(pstr);
                         if((pstr=strtok((char *)NULL,delim))!=NULL)
                            args.roffset=atoi(pstr);
                         else /* only got one token */
                            args.roffset=args.soffset;
                      } else {
                         args.soffset=0; args.roffset=0;
                      }
                      printf("Transmit buffer offset: %d\nReceive buffer offset: %d\n",args.soffset,args.roffset);
                      break;
            case 'p': perturbation = atoi(optarg);
                      if( perturbation > 0 ) {
                         printf("Using a perturbation value of %d\n\n", perturbation);
                      } else {
                         perturbation = 0;
                         printf("Using no perturbations\n\n");
                      }
                      break;

            case 'B': if(integCheck == 1) {
                        fprintf(stderr, "Integrity check not supported with prepost burst\n");
                        exit(-1);
                      }
                      args.preburst = 1;
                      asyncReceive = 1;
                      printf("Preposting all receives before a timed run.\n");
                      printf("Some would consider this cheating,\n");
                      printf("but it is needed to match some vendor tests.\n"); fflush(stdout);
                      break;

            case 'I': args.cache = 0;
                      printf("Performance measured without cache effects\n\n"); fflush(stdout);
                      break;

            case 'o': memset(s,0,sizeof(s));strncpy(s,optarg,sizeof(s)-1);
                      printf("Sending output to %s\n", s); fflush(stdout);
                      break;

            case 's': streamopt = 1;
                      printf("Streaming in one direction only.\n\n");
#if defined(TCP) && ! defined(INFINIBAND) 
                      printf("Sockets are reset between trials to avoid\n");
                      printf("degradation from a collapsing window size.\n\n");
#endif
                      args.reset_conn = 1;
                      printf("Streaming does not provide an accurate\n");
                      printf("measurement of the latency since small\n");
                      printf("messages may get bundled together.\n\n");
                      if( args.bidir == 1 ) {
                        printf("You can't use -s and -2 together\n");
                        exit(0);
                      }
                      fflush(stdout);
                      break;

            case 'l': start = atoi(optarg);
                      if (start < 1)
                      {
                        fprintf(stderr,"Need a starting value >= 1\n");
                        exit(0);
                      }
                      break;

            case 'u': end = atoi(optarg);
                      break;

#if defined(TCP) && ! defined(INFINIBAND)
            case 'b': /* -b # resets the buffer size, -b 0 keeps system defs */
                      args.prot.sndbufsz = args.prot.rcvbufsz = atoi(optarg);
                      break;
#endif

            case '2': args.bidir = 1;    /* Both procs are transmitters */
                         /* end will be maxed at sndbufsz+rcvbufsz */
                      printf("Passing data in both directions simultaneously.\n");
                      printf("Output is for the combined bandwidth.\n");
#if defined(TCP) && ! defined(INFINIBAND)
                      printf("The socket buffer size limits the maximum test size.\n\n");
#endif
                      if( streamopt ) {
                        printf("You can't use -s and -2 together\n");
                        exit(0);
                      }
                      break;

            case 'h': args.tr = 1;       /* -h implies transmit node */
                      args.rcv = 0;
                      args.host = (char *)malloc(strlen(optarg)+1);
                      strcpy(args.host, optarg);
                      break;

#ifdef DISK
            case 'd': args.tr = 1;      /* -d to specify input/output file */
                      args.rcv = 0;
                      args.prot.read = 0;
                      args.prot.read_type = 'c';
                      args.prot.dfile_name = (char *)malloc(strlen(optarg)+1);
                      strcpy(args.prot.dfile_name, optarg);
                      break;

            case 'D': if( optarg[0] == 'r' )
                         args.prot.read = 1;
                      else
                         args.prot.read = 0;
                      args.prot.read_type = optarg[1];
                      break;
#endif

            case 'i': if(args.preburst == 1) {
                        fprintf(stderr, "Integrity check not supported with prepost burst\n");
                        exit(-1);
                      }
                      integCheck = 1;
                      perturbation = 0;
                      start = sizeof(int)+1; /* Start with integer size */
                      printf("Doing an integrity check instead of measuring performance\n"); fflush(stdout);
                      break;

#if defined(MPI)
            case 'z': args.source_node = -1;
                      printf("Receive using the ANY_SOURCE flag\n"); fflush(stdout);
                      break;

            case 'a': asyncReceive = 1;
                      printf("Preposting asynchronous receives\n"); fflush(stdout);
                      break;

            case 'S': args.syncflag=1;
                      fprintf(stderr,"Using synchronous sends\n");
                      break;
#endif
#if defined(MPI2)
            case 'g': if(args.prot.no_fence == 1) {
                        fprintf(stderr, "-f cannot be used with -g\n");
                        exit(-1);
                      } 
                      args.prot.use_get = 1;
                      printf("Using MPI-2 Get instead of Put\n");
                      break;

            case 'f': if(args.prot.use_get == 1) {
                         fprintf(stderr, "-f cannot be used with -g\n");
                         exit(-1);
                      }
                      args.prot.no_fence = 1;
                      bufalign = 0;
                      printf("Buffer alignment off (Required for no fence)\n");
                      break;
#endif /* MPI2 */

#if defined(INFINIBAND)
            case 'm': switch(atoi(optarg)) {
                        case 256: args.prot.ib_mtu = MTU256;
                          break;
                        case 512: args.prot.ib_mtu = MTU512;
                          break;
                        case 1024: args.prot.ib_mtu = MTU1024;
                          break;
                        case 2048: args.prot.ib_mtu = MTU2048;
                          break;
                        case 4096: args.prot.ib_mtu = MTU4096;
                          break;
                        default: 
                          fprintf(stderr, "Invalid MTU size, must be one of "
                                          "256, 512, 1024, 2048, 4096\n");
                          exit(-1);
                      }
                      break;

            case 't': if( !strcmp(optarg, "send_recv") ) {
                         printf("Using Send/Receive communications\n");
                         args.prot.commtype = NP_COMM_SENDRECV;
                      } else if( !strcmp(optarg, "send_recv_with_imm") ) {
                         printf("Using Send/Receive communications with immediate data\n");
                         args.prot.commtype = NP_COMM_SENDRECV_WITH_IMM;
                      } else if( !strcmp(optarg, "rdma_write") ) {
                         printf("Using RDMA Write communications\n");
                         args.prot.commtype = NP_COMM_RDMAWRITE;
                      } else if( !strcmp(optarg, "rdma_write_with_imm") ) {
                         printf("Using RDMA Write communications with immediate data\n");
                         args.prot.commtype = NP_COMM_RDMAWRITE_WITH_IMM;
                      } else {
                         fprintf(stderr, "Invalid transfer type "
                                 "specified, please choose one of:\n\n"
                                 "\tsend_recv\t\tUse Send/Receive communications\t(default)\n"
                                 "\tsend_recv_with_imm\tSame as above with immediate data\n"
                                 "\trdma_write\t\tUse RDMA Write communications\n"
                                 "\trdma_write_with_imm\tSame as above with immediate data\n\n");
                         exit(-1);
                      }
                      break;

            case 'c': if( !strcmp(optarg, "local_poll") ) {
                         printf("Using local polling completion\n");
                         args.prot.comptype = NP_COMP_LOCALPOLL;
                      } else if( !strcmp(optarg, "vapi_poll") ) {
                         printf("Using VAPI polling completion\n");
                         args.prot.comptype = NP_COMP_VAPIPOLL;
                      } else if( !strcmp(optarg, "event") ) {
                         printf("Using VAPI event completion\n");
                         args.prot.comptype = NP_COMP_EVENT;
                      } else {
                         fprintf(stderr, "Invalid completion type specified, "
                                 "please choose one of:\n\n"
                                 "\tlocal_poll\tWait for last byte of data\t(default)\n"
                                 "\tvapi_poll\tUse VAPI polling function\n"
                                 "\tevent\t\tUse VAPI event handling function\n\n");
                         exit(-1);
                      }
                      break;
#endif

            case 'n': nrepeat_const = atoi(optarg);
                      break;

#if defined(TCP) && ! defined(INFINIBAND)
            case 'r': args.reset_conn = 1;
                      printf("Resetting connection after every trial\n");
                      break;
#endif

            default: 
                     PrintUsage(); 
                     exit(-12);
       }
   }

#endif /* ! defined TCGMSG */

#if defined(INFINIBAND)
   asyncReceive = 1;
   fprintf(stderr, "Preposting asynchronous receives (required for Infiniband)\n");
   if(args.bidir && (
          (args.cache && args.prot.commtype == NP_COMM_RDMAWRITE) || /* rdma_write only works with no-cache mode */
          (!args.preburst && args.prot.commtype != NP_COMM_RDMAWRITE) || /* anything besides rdma_write requires prepost burst */
          (args.preburst && args.prot.comptype == NP_COMP_LOCALPOLL && args.cache) || /* preburst with local polling in cache mode doesn't work */
          0)) {

      fprintf(stderr, 
         "\n"
         "Bi-directional mode currently only works with a subset of the\n"
         "Infiniband options. Restrictions are:\n"
         "\n"
         "  RDMA write (-t rdma_write) requires no-cache mode (-I).\n"
         "\n"
         "  Local polling (-c local_poll, default if no -c given) requires\n"
         "    no-cache mode (-I), and if not using RDMA write communication,\n"
         "    burst mode (-B).\n"
         "\n"
         "  Any other communication type and any other completion type\n"
         "    require burst mode (-B). No-cache mode (-I) may be used\n"
         "    optionally.\n"
         "\n"
         "  All other option combinations will fail.\n"
         "\n");
               
      exit(-1);      

   }
#endif

   if (start > end)
   {
       fprintf(stderr, "Start MUST be LESS than end\n");
       exit(420132);
   }
   args.nbuff = TRIALS;
   args.port = DEFPORT;

   Setup(&args);

   if( args.bidir && end > args.upper ) {
      end = args.upper;
      if( args.tr ) {
         printf("The upper limit is being set to %d Bytes\n", end);
#if defined(TCP) && ! defined(INFINIBAND)
         printf("due to socket buffer size limitations\n\n");
#endif
   }  }

#if defined(GM)

   if(streamopt && (!nrepeat_const || nrepeat_const > args.prot.num_stokens)) {
     printf("\nGM is currently limited by the driver software to %d\n", 
            args.prot.num_stokens);
     printf("outstanding sends. The number of repeats will be set\n");
     printf("to this limit for every trial in streaming mode.  You\n");
     printf("may use the -n switch to set a smaller number of repeats\n\n");

     nrepeat_const = args.prot.num_stokens;
   }

#endif

   if( args.tr )                     /* Primary transmitter */
   {
       if ((out = fopen(s, "w")) == NULL)
       {
           fprintf(stderr,"Can't open %s for output\n", s);
           exit(1);
       }
   }
   else out = stdout;

      /* Set a starting value for the message size increment. */

   inc = (start > 1) ? start / 2 : 1;
   nq = (start > 1) ? 1 : 0;

      /* Test the timing to set tlast for the first test */

   args.bufflen = start;
   MyMalloc(&args, args.bufflen, 0, 0);
   InitBufferData(&args, args.bufflen, 0, 0);

   if(args.cache) args.s_buff = args.r_buff;
   
   args.r_ptr = args.r_buff_orig = args.r_buff;
   args.s_ptr = args.s_buff_orig = args.s_buff;
      
   AfterAlignmentInit(&args);  /* MPI-2 needs this to create a window */

   /* Infiniband requires use of asynchronous communications, so we need
    * the PrepareToReceive calls below
    */
   if( asyncReceive )
      PrepareToReceive(&args);
   
   Sync(&args);    /* Sync to prevent race condition in armci module */

   /* For simplicity's sake, even if the real test below will be done in
    * bi-directional mode, we still do the ping-pong one-way-at-a-time test
    * here to estimate the one-way latency. Unless it takes significantly
    * longer to send data in both directions at once than it does to send data
    * one way at a time, this shouldn't be too far off anyway.
    */
   t0 = When();
      for( n=0; n<100; n++) {
         if( args.tr) {
            SendData(&args);
            RecvData(&args);
            if( asyncReceive && n<99 )
               PrepareToReceive(&args);
         } else if( args.rcv) {
            RecvData(&args);
            if( asyncReceive && n<99 )
               PrepareToReceive(&args);
            SendData(&args);
         }
      }
   tlast = (When() - t0)/200;

   /* Sync up and Reset before freeing the buffers */

   Sync(&args); 

   Reset(&args);
   
   /* Free the buffers and any other module-specific resources. */
   if(args.cache)
      FreeBuff(args.r_buff_orig, NULL);
   else
      FreeBuff(args.r_buff_orig, args.s_buff_orig);

      /* Do setup for no-cache mode, using two distinct buffers. */

   if (!args.cache)
   {

       /* Allocate dummy pool of memory to flush cache with */

       if ( (memcache = (int *)malloc(MEMSIZE)) == NULL)
       {
           perror("malloc");
           exit(1);
       }
       mymemset(memcache, 0, MEMSIZE/sizeof(int)); 

       /* Allocate large memory pools */

       MyMalloc(&args, MEMSIZE+bufalign, args.soffset, args.roffset); 

       /* Save buffer addresses */
       
       args.s_buff_orig = args.s_buff;
       args.r_buff_orig = args.r_buff;

       /* Align buffers */

       args.s_buff = AlignBuffer(args.s_buff, bufalign);
       args.r_buff = AlignBuffer(args.r_buff, bufalign);

       /* Post alignment initialization */

       AfterAlignmentInit(&args);

       /* Initialize send buffer pointer */
       
/* both soffset and roffset should be zero if we don't have any offset stuff, so this should be fine */
       args.s_ptr = args.s_buff+args.soffset;
       args.r_ptr = args.r_buff+args.roffset;
   }

       /**************************
        * Main loop of benchmark *
        **************************/

   if( args.tr ) fprintf(stderr,"Now starting the main loop\n");

   for ( n = 0, len = start, errFlag = 0; 
        n < NSAMP - 3 && tlast < STOPTM && len <= end && !errFlag; 
        len = len + inc, nq++ )
   {

           /* Exponentially increase the block size.  */

       if (nq > 2) inc = ((nq % 2))? inc + inc: inc;
       
          /* This is a perturbation loop to test nearby values */

       for (pert = ((perturbation > 0) && (inc > perturbation+1)) ? -perturbation : 0;
            pert <= perturbation; 
            n++, pert += ((perturbation > 0) && (inc > perturbation+1)) ? perturbation : perturbation+1)
       {

           Sync(&args);    /* Sync to prevent race condition in armci module */

               /* Calculate how many times to repeat the experiment. */

           if( args.tr )
           {
               if (nrepeat_const) {
                   nrepeat = nrepeat_const;
/*               } else if (len == start) {*/
/*                   nrepeat = MAX( RUNTM/( 0.000020 + start/(8*1000) ), TRIALS);*/
               } else {
                   nrepeat = MAX((RUNTM / ((double)args.bufflen /
                                  (args.bufflen - inc + 1.0) * tlast)),TRIALS);
               }
               SendRepeat(&args, nrepeat);
           }
           else if( args.rcv )
           {
               RecvRepeat(&args, &nrepeat);
           }

           args.bufflen = len + pert;

           if( args.tr )
               fprintf(stderr,"%3d: %7d bytes %6d times --> ",
                       n,args.bufflen,nrepeat);

           if (args.cache) /* Allow cache effects.  We use only one buffer */
           {
               /* Allocate the buffer with room for alignment*/

               MyMalloc(&args, args.bufflen+bufalign, args.soffset, args.roffset); 

               /* Save buffer address */

               args.r_buff_orig = args.r_buff;
               args.s_buff_orig = args.r_buff;

               /* Align buffer */

               args.r_buff = AlignBuffer(args.r_buff, bufalign);
               args.s_buff = args.r_buff;
               
               /* Initialize buffer with data
                *
                * NOTE: The buffers should be initialized with some sort of
                * valid data, whether it is actually used for anything else,
                * to get accurate results.  Performance increases noticeably
                * if the buffers are left uninitialized, but this does not
                * give very useful results as realworld apps tend to actually
                * have data stored in memory.  We are not sure what causes
                * the difference in performance at this time.
                */

               InitBufferData(&args, args.bufflen, args.soffset, args.roffset);


               /* Post-alignment initialization */

               AfterAlignmentInit(&args);

               /* Initialize buffer pointers (We use r_ptr and s_ptr for
                * compatibility with no-cache mode, as this makes the code
                * simpler) 
                */
               /* offsets are zero by default so this saves an #ifdef */
               args.r_ptr = args.r_buff+args.roffset;
               args.s_ptr = args.r_buff+args.soffset;

           }
           else /* Eliminate cache effects.  We use two distinct buffers */
           {

               /* this isn't truly set up for offsets yet */
               /* Size of an aligned memory block including trailing padding */

               len_buf_align = args.bufflen;
               if(bufalign != 0)
                 len_buf_align += bufalign - args.bufflen % bufalign;
 
               /* Initialize the buffers with data
                *
                * See NOTE above.
                */
               InitBufferData(&args, MEMSIZE, args.soffset, args.roffset); 
               

               /* Reset buffer pointers to beginning of pools */
               args.r_ptr = args.r_buff+args.roffset;
               args.s_ptr = args.s_buff+args.soffset;
            }

            bwdata[n].t = LONGTIME;
/*            t2 = t1 = 0;*/

            /* Finally, we get to transmit or receive and time */

            /* NOTE: If a module is running that uses only one process (e.g.
             * memcpy), we assume that it will always have the args.tr flag
             * set.  Thus we make some special allowances in the transmit 
             * section that are not in the receive section.
             */

            if( args.tr || args.bidir )
            {
                /*
                   This is the transmitter: send the block TRIALS times, and
                   if we are not streaming, expect the receiver to return each
                   block.
                */

                for (i = 0; i < (integCheck ? 1 : TRIALS); i++)
                {                    
                    if(args.preburst && asyncReceive && !streamopt)
                    {

                      /* We need to save the value of the recv ptr so
                       * we can reset it after we do the preposts, in case
                       * the module needs to use the same ptr values again
                       * so it can wait on the last byte to change to indicate
                       * the recv is finished.
                       */

                      SaveRecvPtr(&args);

                      for(j=0; j<nrepeat; j++)
                      {
                        PrepareToReceive(&args);
                        if(!args.cache)
                          AdvanceRecvPtr(&args, len_buf_align);
                      }

                      ResetRecvPtr(&args);
                    }

                    /* Flush the cache using the dummy buffer */
                    if (!args.cache)
                      flushcache(memcache, MEMSIZE/sizeof(int));

                    Sync(&args);

                    t0 = When();

                    for (j = 0; j < nrepeat; j++)
                    {
                        if (!args.preburst && asyncReceive && !streamopt)
                        {
                            PrepareToReceive(&args);
                        }

                        if (integCheck) SetIntegrityData(&args);

                        SendData(&args);

                        if (!streamopt)
                        {
                            RecvData(&args);

                            if (integCheck) VerifyIntegrity(&args);

                            if(!args.cache)
                              AdvanceRecvPtr(&args, len_buf_align);

                        }
                        
                        /* Wait to advance send pointer in case RecvData uses
                         * it (e.g. memcpy module).
                         */
                        if (!args.cache)
                          AdvanceSendPtr(&args, len_buf_align);

                    }

                       /* t is the 1-directional trasmission time */

                    t = (When() - t0)/ nrepeat;

                    if( !streamopt && !args.bidir) t /= 2; /* Normal ping-pong */

                    Reset(&args);

/* NOTE: NetPIPE does each data point TRIALS times, bouncing the message
 * nrepeats times for each trial, then reports the lowest of the TRIALS
 * times.  -Dave Turner
 */
                    bwdata[n].t = MIN(bwdata[n].t, t);
/*                    t1 += t;*/
/*                    t2 += t*t;*/
                }

                if (streamopt){  /* Get time info from Recv node */
                    RecvTime(&args, &bwdata[n].t);
/*                    RecvTime(&args, &t1);*/
/*                    RecvTime(&args, &t2);*/
                }

                   /* Calculate variance after completing this set of trials */

/*                bwdata[n].variance = t2/TRIALS - t1/TRIALS * t1/TRIALS;*/

            }
            else if( args.rcv )
            {
                /*
                   This is the receiver: receive the block TRIALS times, and
                   if we are not streaming, send the block back to the
                   sender.
                */
                for (i = 0; i < (integCheck ? 1 : TRIALS); i++)
                {
                    if (asyncReceive)
                    {
                       if (args.preburst)
                       {

                         /* We need to save the value of the recv ptr so
                          * we can reset it after we do the preposts, in case
                          * the module needs to use the same ptr values again
                          * so it can wait on the last byte to change to 
                          * indicate the recv is finished.
                          */

                         SaveRecvPtr(&args);

                         for (j=0; j < nrepeat; j++)
                         {
                              PrepareToReceive(&args);
                              if (!args.cache)
                                 AdvanceRecvPtr(&args, len_buf_align);
                         }
                         
                         ResetRecvPtr(&args);
                         
                       }
                       else
                       {
                           PrepareToReceive(&args);
                       }
                      
                    }
                    
                    /* Flush the cache using the dummy buffer */
                    if (!args.cache)
                      flushcache(memcache, MEMSIZE/sizeof(int));

                    Sync(&args);

                    t0 = When();
                    for (j = 0; j < nrepeat; j++)
                    {
                        RecvData(&args);

                        if (integCheck) VerifyIntegrity(&args);

                        if (!args.cache)
                        { 
                            AdvanceRecvPtr(&args, len_buf_align);
                        }
                        
                        if (!args.preburst && asyncReceive && (j < nrepeat-1))
                        {
                            PrepareToReceive(&args);
                        }

                        if (!streamopt)
                        {
                            if (integCheck) SetIntegrityData(&args);
                            
                            SendData(&args);

                            if(!args.cache) 
                              AdvanceSendPtr(&args, len_buf_align);
                        }

                    }
                    t = (When() - t0)/ nrepeat;

                    if( !streamopt && !args.bidir) t /= 2; /* Normal ping-pong */

                    Reset(&args);
                    
                    bwdata[n].t = MIN(bwdata[n].t, t);
/*                    t1 += t;*/
/*                    t2 += t*t;*/
                }
                if (streamopt){  /* Recv proc calcs time and sends to Trans */
                    SendTime(&args, &bwdata[n].t);
/*                    SendTime(&args, &t1);*/
/*                    SendTime(&args, &t2);*/
                }
            }
            else  /* Just going along for the ride */
            {
                for (i = 0; i < (integCheck ? 1 : TRIALS); i++)
                {
                    Sync(&args);
                }
            }

            /* Streaming mode doesn't really calculate correct latencies
             * for small message sizes, and on some nics we can get
             * zero second latency after doing the math.  Protect against
             * this.
             */
            if(bwdata[n].t == 0.0) {
              bwdata[n].t = 0.000001;
            }
            
            tlast = bwdata[n].t;
            bwdata[n].bits = args.bufflen * CHARSIZE * (1+args.bidir);
            bwdata[n].bps = bwdata[n].bits / (bwdata[n].t * 1024 * 1024);
            bwdata[n].repeat = nrepeat;
            
            if (args.tr)
            {
                if(integCheck) {
                  fprintf(out,"%8d %d", bwdata[n].bits / 8, nrepeat);

                } else {
                  fprintf(out,"%8d %lf %12.8lf",
                        bwdata[n].bits / 8, bwdata[n].bps, bwdata[n].t);

                }
                fprintf(out, "\n");
                fflush(out);
            }
    
            /* Free using original buffer addresses since we may have aligned
               r_buff and s_buff */

            if (args.cache)
                FreeBuff(args.r_buff_orig, NULL);
            
            if ( args.tr ) {
               if(integCheck) {
                 fprintf(stderr, " Integrity check passed\n");

               } else {
                 fprintf(stderr," %8.2lf Mbps in %10.2lf usec\n", 
                         bwdata[n].bps, tlast*1.0e6);
               }
            }


        } /* End of perturbation loop */

    } /* End of main loop  */
 
   /* Free using original buffer addresses since we may have aligned
      r_buff and s_buff */

   if (!args.cache) {
        FreeBuff(args.s_buff_orig, args.r_buff_orig);
   }
    if (args.tr) fclose(out);
         
    CleanUp(&args);
    return 0;
}
Exemplo n.º 13
0
void ServerSocket::RecvAndDisplayMessage()
{
	char message[STRLEN];
	memset(message, 0, STRLEN);
	RecvData(message, STRLEN);
}
Exemplo n.º 14
0
//接收完成函数
bool CServerSocketItem::OnRecvCompleted(COverLappedRecv * pOverLappedRecv, DWORD dwThancferred)
{
	//效验数据
	ASSERT(m_bRecvIng==true);

	//设置变量
	m_bRecvIng=false;
	m_dwRecvTickCount=GetTickCount();

	//判断关闭
	if (m_hSocket==INVALID_SOCKET)
	{
		CloseSocket(m_wRountID);
		return true;
	}

	//接收数据
	int iRetCode=recv(m_hSocket,(char *)m_cbRecvBuf+m_wRecvSize,sizeof(m_cbRecvBuf)-m_wRecvSize,0);
	if (iRetCode<=0)
	{
		CloseSocket(m_wRountID);
		return true;
	}

	//接收完成
	m_wRecvSize+=iRetCode;
	BYTE cbBuffer[SOCKET_BUFFER];
	CMD_Head * pHead=(CMD_Head *)m_cbRecvBuf;

	//处理数据
	try
	{
		while (m_wRecvSize>=sizeof(CMD_Head))
		{
			//效验数据
			WORD wPacketSize=pHead->CmdInfo.wDataSize;
			if (wPacketSize>SOCKET_BUFFER) throw TEXT("数据包超长");
			if (wPacketSize<sizeof(CMD_Head)) throw TEXT("数据包非法");
			if (pHead->CmdInfo.cbMessageVer!=SOCKET_VER) throw TEXT("数据包版本错误");
			if (m_wRecvSize<wPacketSize) break;

			//提取数据
			CopyMemory(cbBuffer,m_cbRecvBuf,wPacketSize);
			WORD wRealySize=CrevasseBuffer(cbBuffer,wPacketSize);
			ASSERT(wRealySize>=sizeof(CMD_Head));
			m_dwRecvPacketCount++;

			//解释数据
			WORD wDataSize=wRealySize-sizeof(CMD_Head);
			void * pDataBuffer=cbBuffer+sizeof(CMD_Head);
			CMD_Command Command=((CMD_Head *)cbBuffer)->CommandInfo;

			//内核命令
			if (Command.wMainCmdID==MDM_KN_COMMAND)
			{
				switch (Command.wSubCmdID)
				{
				case SUB_KN_DETECT_SOCKET:	//网络检测
					{
						break;
					}
				default: throw TEXT("非法命令码");
				}
			}
			else 
			{
				//消息处理
				m_pIServerSocketItemSink->OnSocketReadEvent(Command,pDataBuffer,wDataSize,this);			
			}

			//删除缓存数据
			m_wRecvSize-=wPacketSize;
			MoveMemory(m_cbRecvBuf,m_cbRecvBuf+wPacketSize,m_wRecvSize);
		}
	}
	catch (...)
	{ 
		CloseSocket(m_wRountID);
		return false;
	}

	return RecvData();
}
/*
** A "local" function of main().  Handles a #messageType# message arrived on
** #sd# accompanied by #dataSize# bytes of data.
*/
static void
ProcessRequest(Socket *sd,
               MessageType messageType,
               size_t dataSize) {

  char *contents;
  DataDescriptor contentsDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);
  AutoFetchInfo *expandedAutoFetches;
  unsigned long expiration;
  DataDescriptor expirationDescriptor = SIMPLE_DATA(UNSIGNED_LONG_TYPE, 1);
  int i;
  struct state stateDesc;
  char *stateNames;
  DataDescriptor stateNamesDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);

  switch(messageType) {

  case FETCH_STATE:
    if(!RecvData(*sd,
                 &stateDesc,
                 stateDescriptor,
                 stateDescriptorLength,
                 PktTimeOut(*sd))) {
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: state receive failed\n");
      return;
    }
    contents = (char *)malloc(stateDesc.rec_count * MAX_RECORD_SIZE);
    if(contents == NULL) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      ERROR("ProcessRequest: out of memory\n");
    }
    else {
      if(ReadState(FileOfState(memoryDir, stateDesc.id),
                   contents,
                   stateDesc.rec_count,
                   stateDesc.rec_count * MAX_RECORD_SIZE,
                   stateDesc.seq_no,
                   &stateDesc.time_out,
                   &stateDesc.seq_no,
                   &stateDesc.rec_count,
                   &stateDesc.rec_size)) {
        if(stateDesc.rec_count > 0) {
          contentsDescriptor.repetitions =
            stateDesc.rec_size * stateDesc.rec_count;
          (void)SendMessageAndDatas(*sd,
                                    STATE_FETCHED,
                                    &stateDesc,
                                    stateDescriptor,
                                    stateDescriptorLength,
                                    contents,
                                    &contentsDescriptor,
                                    1,
                                    PktTimeOut(*sd));
        }
        else {
          (void)SendMessageAndData(*sd,
                                   STATE_FETCHED,
                                   &stateDesc,
                                   stateDescriptor,
                                   stateDescriptorLength,
                                   PktTimeOut(*sd));
        }
      }
      else {
        (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
        if(errno == EMFILE) {
          CheckConnections();
        }
      }
      free(contents);
    }
    break;

  case STORE_STATE:
    if(!RecvData(*sd,
                 &stateDesc,
                 stateDescriptor,
                 stateDescriptorLength,
                 PktTimeOut(*sd))) {
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: state receive failed\n");
      return;
    }
    contentsDescriptor.repetitions = stateDesc.rec_size * stateDesc.rec_count;
    contents = (char *)malloc(contentsDescriptor.repetitions + 1);
    if(contents == NULL) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      ERROR("ProcessRequest: out of memory\n");
    }
    else {
      contents[contentsDescriptor.repetitions] = '\0';
      if(!RecvData(*sd,
                   contents,
                   &contentsDescriptor,
                   1,
                   PktTimeOut(*sd))) {
        DROP_SOCKET(sd);
        ERROR("ProcessRequest: data receive failed\n");
      }
      else {
        (void)SendMessage(*sd,
                          KeepState(&memLogLocation,
                                    &stateDesc,
                                    contents,
                                    contentsDescriptor.repetitions) ?
                          STATE_STORED : MEMORY_FAILED,
                          PktTimeOut(*sd));
        for(i = 0; i < autoFetchCount; i++) {
          if(strstr(autoFetches[i].stateNames, stateDesc.id) != NULL) {
            if(!SendMessageAndDatas(autoFetches[i].clientSock,
                                    STATE_FETCHED,
                                    &stateDesc,
                                    stateDescriptor,
                                    stateDescriptorLength,
                                    contents,
                                    &contentsDescriptor,
                                    1,
                                    PktTimeOut(autoFetches[i].clientSock))) {
              DROP_SOCKET(&autoFetches[i].clientSock);
              free(autoFetches[i].stateNames);
              autoFetches[i] = autoFetches[--autoFetchCount];
            }
          }
        }
      }
      free(contents);
    }
    break;

  case AUTOFETCH_BEGIN:
    stateNamesDescriptor.repetitions = dataSize;
    stateNames = (char *)malloc(dataSize);
    if(stateNames == NULL) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: out of memory\n");
    }
    else if(!RecvData(*sd,
                      stateNames,
                      &stateNamesDescriptor,
                      1,
                      PktTimeOut(*sd))) {
      (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
      DROP_SOCKET(sd);
      free(stateNames);
      ERROR("ProcessRequest: data receive failed\n");
    }
    else if(*stateNames == '\0') {
      free(stateNames);
      EndAutoFetch(*sd);
      (void)SendMessage(*sd, AUTOFETCH_ACK, PktTimeOut(*sd));
    }
    else {
      for(i=0; (i < autoFetchCount) && (autoFetches[i].clientSock != *sd); i++)
        ; /* Nothing more to do. */
      if(i == autoFetchCount) {
        expandedAutoFetches =
          REALLOC(autoFetches, (autoFetchCount + 1) * sizeof(AutoFetchInfo));
        if(expandedAutoFetches == NULL) {
          (void)SendMessage(*sd, MEMORY_FAILED, PktTimeOut(*sd));
          DROP_SOCKET(sd);
          ERROR("ProcessRequest: out of memory\n");
          break;
        }
        autoFetches = expandedAutoFetches;
        autoFetches[i].clientSock = *sd;
        autoFetchCount++;
      }
      else {
        free(autoFetches[i].stateNames);
      }
      autoFetches[i].stateNames = stateNames;
      (void)SendMessage(*sd, AUTOFETCH_ACK, PktTimeOut(*sd));
    }
    break;

  case MEMORY_CLEAN:
    if(!RecvData(*sd, &expiration, &expirationDescriptor, 1, PktTimeOut(*sd))) {
      DROP_SOCKET(sd);
      ERROR("ProcessRequest: data receive failed\n");
    }
    else {
      (void)SendMessage(*sd, MEMORY_CLEANED, PktTimeOut(*sd));
      (void)DoClean(expiration);
    }
    break;

#ifdef WITH_NETLOGGER	  
  case MEMORY_LOGDEST: /* config message contains log location */
	  if(!RecvData(*sd,
		  &memLogLocation,
		  loglocationDescriptor,
		  loglocationDescriptorLength,
		  PktTimeOut(*sd))) {
		  DROP_SOCKET(sd);
		  ERROR("ProcessRequest: loglocation receive failed\n");
		  return;
	  }else
	  {
		  (void)SendMessage(*sd, MEMORY_LOGDEST_ACK, PktTimeOut(*sd));
	  }
	  LOG2("ProcessRequest: loglocation %d .%s.\n", memLogLocation.loc_type, memLogLocation.path);
 
	  break;
#endif /* WITH_NETLOGGER */	  	

  default:
    DROP_SOCKET(sd);
    ERROR1("ProcessRequest: unknown message %d\n", messageType);

  }

}
Exemplo n.º 16
0
/* This is always called from an IO thread. Either the server socket's thread, or a
 * special thread we create when we make an outbound connection. */
bool TCPConnection::Process() {
	char errbuf[TCPConnection_ErrorBufferSize];
	switch(GetState()) {
	case TCPS_Ready:
	case TCPS_Connecting:
		if (ConnectionType == Outgoing) {
			if (GetAsyncConnect()) {
				if (charAsyncConnect)
					rIP = ResolveIP(charAsyncConnect);
				ConnectIP(rIP, rPort);
			}
		}
		return(true);

	case TCPS_Connected:
		// only receive data in the connected state, no others...
		if (!RecvData(errbuf)) {
			struct in_addr	in;
			in.s_addr = GetrIP();
			//std::cout << inet_ntoa(in) << ":" << GetrPort() << ": " << errbuf << std::endl;
			return false;
		}
		/* we break to do the send */
		break;

	case TCPS_Disconnecting: {
		//waiting for any sending data to go out...
		MSendQueue.lock();
		if(sendbuf) {
			if(sendbuf_used > 0) {
				//something left to send, keep processing...
				MSendQueue.unlock();
				break;
			}
			//else, send buffer is empty.
			safe_delete_array(sendbuf);
		} //else, no send buffer, we are done.
		MSendQueue.unlock();
	}
		/* Fallthrough */

	case TCPS_Disconnected:
		FinishDisconnect();
		MRunLoop.lock();
		pRunLoop = false;
		MRunLoop.unlock();
//		SetState(TCPS_Ready);	//reset the state in case they want to use it again...
		return(false);

	case TCPS_Closing:
		//I dont understand this state...

	case TCPS_Error:
		MRunLoop.lock();
		pRunLoop = false;
		MRunLoop.unlock();
		return(false);
	}

	/* we get here in connected or disconnecting with more data to send */

	bool sent_something = false;
	if (!SendData(sent_something, errbuf)) {
		struct in_addr	in;
		in.s_addr = GetrIP();
		std::cout << inet_ntoa(in) << ":" << GetrPort() << ": " << errbuf << std::endl;
		return false;
	}

	return true;
}
Exemplo n.º 17
0
/**
* Receive data as a master on the IIC bus.  This function receives the data
* using polled I/O and blocks until the data has been received. It only
* supports 7 bit addressing mode of operation. The user is responsible for
* ensuring the bus is not busy if multiple masters are present on the bus.
*
* @param    BaseAddress contains the base address of the IIC device.
* @param    Address contains the 7 bit IIC address of the device to send the
*           specified data to.
* @param    BufferPtr points to the data to be sent.
* @param    ByteCount is the number of bytes to be sent.
* @param    Option indicates whether to hold or free the bus after reception
*           of data, XIIC_STOP = end with STOP condition, XIIC_REPEATED_START
*           = don't end with STOP condition.
*
* @return
*
* The number of bytes received.
*
* @note
*
* None
*
******************************************************************************/
unsigned XIic_Recv(u32 BaseAddress, u8 Address,
		   u8 *BufferPtr, unsigned ByteCount, u8 Option)
{
	u8 CntlReg;
	unsigned RemainingByteCount;
	volatile u8 StatusReg;

	/* Tx error is enabled incase the address (7 or 10) has no device to answer
	 * with Ack. When only one byte of data, must set NO ACK before address goes
	 * out therefore Tx error must not be enabled as it will go off immediately
	 * and the Rx full interrupt will be checked.  If full, then the one byte
	 * was received and the Tx error will be disabled without sending an error
	 * callback msg.
	 */
	XIic_mClearIisr(BaseAddress,
			XIIC_INTR_RX_FULL_MASK | XIIC_INTR_TX_ERROR_MASK |
			XIIC_INTR_ARB_LOST_MASK);

	/* Set receive FIFO occupancy depth for 1 byte (zero based)
	 */
	XIo_Out8(BaseAddress + XIIC_RFD_REG_OFFSET, 0);


	/* Check to see if already Master on the Bus.
	 * If Repeated Start bit is not set send Start bit by setting MSMS bit else
	 * Send the address.
	 */
	CntlReg = XIo_In8(BaseAddress + XIIC_CR_REG_OFFSET);
	if ((CntlReg & XIIC_CR_REPEATED_START_MASK) == 0) {
		/* 7 bit slave address, send the address for a read operation
		 * and set the state to indicate the address has been sent
		 */
		XIic_mSend7BitAddress(BaseAddress, Address,
				      XIIC_READ_OPERATION);


		/* MSMS gets set after putting data in FIFO. Start the master receive
		 * operation by setting CR Bits MSMS to Master, if the buffer is only one
		 * byte, then it should not be acknowledged to indicate the end of data
		 */
		CntlReg = XIIC_CR_MSMS_MASK | XIIC_CR_ENABLE_DEVICE_MASK;
		if (ByteCount == 1) {
			CntlReg |= XIIC_CR_NO_ACK_MASK;
		}

		/* Write out the control register to start receiving data and call the
		 * function to receive each byte into the buffer
		 */
		XIo_Out8(BaseAddress + XIIC_CR_REG_OFFSET, CntlReg);

		/* Clear the latched interrupt status for the bus not busy bit which must
		 * be done while the bus is busy
		 */
		StatusReg = XIo_In8(BaseAddress + XIIC_SR_REG_OFFSET);

		while ((StatusReg & XIIC_SR_BUS_BUSY_MASK) == 0) {
			StatusReg = XIo_In8(BaseAddress + XIIC_SR_REG_OFFSET);

		}

		XIic_mClearIisr(BaseAddress, XIIC_INTR_BNB_MASK);
	}
	else {
		/* Already owns the Bus indicating that its a Repeated Start call.
		 * 7 bit slave address, send the address for a read operation
		 * and set the state to indicate the address has been sent
		 */
		XIic_mSend7BitAddress(BaseAddress, Address,
				      XIIC_READ_OPERATION);
	}
	/* Try to receive the data from the IIC bus */

	RemainingByteCount =
		RecvData(BaseAddress, BufferPtr, ByteCount, Option);

	CntlReg = XIo_In8(BaseAddress + XIIC_CR_REG_OFFSET);
	if ((CntlReg & XIIC_CR_REPEATED_START_MASK) == 0) {
		/* The receive is complete, disable the IIC device if the Option is
		 * to release the Bus after Reception of data and return the number of
		 * bytes that was received
		 */
		XIo_Out8(BaseAddress + XIIC_CR_REG_OFFSET, 0);
	}

	/* Return the number of bytes that was received */

	return ByteCount - RemainingByteCount;
}
Exemplo n.º 18
0
void TcpSocket::RecvDataSlot() {
    emit RecvData(readAll());
}