Exemple #1
0
void win_cleanup_sockets()
{
	WSACleanup();
}
void CWE194_Unexpected_Sign_Extension__listen_socket_strncpy_32_bad()
{
    short data;
    short *dataPtr1 = &data;
    short *dataPtr2 = &data;
    /* Initialize data */
    data = 0;
    {
        short data = *dataPtr1;
        {
#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
        }
        *dataPtr1 = data;
    }
    {
        short data = *dataPtr2;
        {
            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 extension could result in a very large number */
                strncpy(dest, source, data);
                dest[data] = '\0'; /* strncpy() does not always NULL terminate */
            }
            printLine(dest);
        }
    }
}
void CWE134_Uncontrolled_Format_String__char_connect_socket_vfprintf_64_bad()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    {
#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) * (100 - 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
    }
    CWE134_Uncontrolled_Format_String__char_connect_socket_vfprintf_64b_badSink(&data);
}
Exemple #4
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR szCmdLine, int iCmdShow)
#endif
{

/*HMODULE hUser32 = LoadLibrary(_T("user32.dll"));
typedef BOOL(*SetProcessDPIAwareFunc)();
SetProcessDPIAwareFunc setDPIAware=NULL;
if (hUser32) setDPIAware = (SetProcessDPIAwareFunc)GetProcAddress(hUser32, "SetProcessDPIAware");
if (setDPIAware) setDPIAware();
if (hUser32) FreeLibrary(hUser32);*/

#ifdef IPP
	InitIpp();
#endif
#ifdef CRASHRPT
	CR_INSTALL_INFO info;
	memset(&info, 0, sizeof(CR_INSTALL_INFO));
	info.cb = sizeof(CR_INSTALL_INFO);
	info.pszAppName = _T("UVNC");
	info.pszAppVersion = _T("1.2.1.1");
	info.pszEmailSubject = _T("UVNC viewer 1.2.1.1 Error Report");
	info.pszEmailTo = _T("*****@*****.**");
	info.uPriorities[CR_SMAPI] = 1; // Third try send report over Simple MAPI    
	// Install all available exception handlers
	info.dwFlags |= CR_INST_ALL_POSSIBLE_HANDLERS;
	// Restart the app on crash 
	info.dwFlags |= CR_INST_APP_RESTART;
	info.dwFlags |= CR_INST_SEND_QUEUED_REPORTS;
	info.dwFlags |= CR_INST_AUTO_THREAD_HANDLERS;
	info.pszRestartCmdLine = _T("/restart");
	// Define the Privacy Policy URL 

	// Install crash reporting
	int nResult = crInstall(&info);
	if (nResult != 0)
	{
		// Something goes wrong. Get error message.
		TCHAR szErrorMsg[512] = _T("");
		crGetLastErrorMsg(szErrorMsg, 512);
		_tprintf_s(_T("%s\n"), szErrorMsg);
		return 1;
	}
#endif

  setbuf(stderr, 0);
  bool console = false;
  m_hInstResDLL = NULL;

  // [v1.0.2-jp1 fix]
  //m_hInstResDLL = LoadLibrary("lang.dll");
  HMODULE hmod;
  HKEY hkey;
  if((hmod=GetModuleHandle("kernel32.dll"))) 
  {
	MySetDllDirectory = (LPFNSETDLLDIRECTORY)GetProcAddress(hmod, "SetDllDirectoryA");
	if(MySetDllDirectory)  MySetDllDirectory("");
	else
	{
		OSVERSIONINFO osinfo;
		osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		GetVersionEx(&osinfo);
		if((osinfo.dwMajorVersion == 5 && osinfo.dwMinorVersion == 0 && strcmp(osinfo.szCSDVersion, "Service Pack 3") >= 0) ||
                   (osinfo.dwMajorVersion == 5 &&  osinfo.dwMinorVersion == 1 && strcmp(osinfo.szCSDVersion, "") >= 0)) 
		{
			DWORD regval = 1;
                        DWORD reglen = sizeof(DWORD);

                        vnclog.Print(3,"Using Win2k (SP3+) / WinXP (No SP).. Checking SafeDllSearch\n");
                        read_reg_string(HKEY_LOCAL_MACHINE,
                                        "System\\CurrentControlSet\\Control\\Session Manager",
                                        "SafeDllSearchMode",
                                        (LPBYTE)&regval,
                                        &reglen);

                        if(regval != 0) {
                                vnclog.Print(3,"Trying to set SafeDllSearchMode to 0\n");
                                regval = 0;
                                if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, 
                                                "System\\CurrentControlSet\\Control\\Session Manager", 
                                                0,  KEY_SET_VALUE, &hkey) == ERROR_SUCCESS) {
                                        if(RegSetValueEx(hkey, 
                                                         "SafeDllSearchMode",
                                                         0,
                                                         REG_DWORD,
                                                         (LPBYTE) &regval,
                                                         sizeof(DWORD)) != ERROR_SUCCESS)
                                                vnclog.Print(3,"Error writing SafeDllSearchMode. Error: %u\n",(UINT)GetLastError());
                                        RegCloseKey(hkey);
                                }
                                else
                                        vnclog.Print(3,"Error opening Session Manager key for writing. Error: %u\n",(UINT)GetLastError());
                        }
                        else
                                vnclog.Print(3,"SafeDllSearchMode is set to 0\n");


		}


	}
  }

  //limit the vnclang.dll searchpath to avoid
  char szCurrentDir[MAX_PATH]="";
  char szCurrentDir_vnclangdll[MAX_PATH]="";
  if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
	{
		char* p = strrchr(szCurrentDir, '\\');
		*p = '\0';
	}
  strcpy_s (szCurrentDir_vnclangdll,szCurrentDir);
  strcat_s (szCurrentDir_vnclangdll,"\\");
  strcat_s (szCurrentDir_vnclangdll,"vnclang.dll");
  m_hInstResDLL = LoadLibrary(szCurrentDir_vnclangdll);

  
  if (m_hInstResDLL==NULL)
  {
	  m_hInstResDLL = hInstance;
  }
  if (strcmp(szCmdLine,"")==0) command_line=false;
  LoadString(m_hInstResDLL, IDS_A1, sz_A1, 64 -1);
  LoadString(m_hInstResDLL, IDS_A2, sz_A2, 64 -1);
  LoadString(m_hInstResDLL, IDS_A3, sz_A3, 64 -1);
  LoadString(m_hInstResDLL, IDS_A4, sz_A4, 64 -1);
  LoadString(m_hInstResDLL, IDS_A5, sz_A5, 64 -1);
  LoadString(m_hInstResDLL, IDS_B1, sz_B1, 64 -1);
  LoadString(m_hInstResDLL, IDS_B2, sz_B2, 64 -1);
  LoadString(m_hInstResDLL, IDS_B3, sz_B3, 64 -1);
  LoadString(m_hInstResDLL, IDS_C1, sz_C1, 64 -1);
  LoadString(m_hInstResDLL, IDS_C2, sz_C2, 64 -1);
  LoadString(m_hInstResDLL, IDS_C3, sz_C3, 64 -1);
  LoadString(m_hInstResDLL, IDS_D1, sz_D1, 64 -1);
  LoadString(m_hInstResDLL, IDS_D2, sz_D2, 64 -1);
  LoadString(m_hInstResDLL, IDS_D3, sz_D3, 64 -1);
  LoadString(m_hInstResDLL, IDS_D4, sz_D4, 64 -1);
  LoadString(m_hInstResDLL, IDS_D5, sz_D5, 64 -1);
  LoadString(m_hInstResDLL, IDS_D6, sz_D6, 64 -1);
  LoadString(m_hInstResDLL, IDS_D7, sz_D7, 64 -1);
  LoadString(m_hInstResDLL, IDS_D8, sz_D8, 64 -1);
  LoadString(m_hInstResDLL, IDS_D9, sz_D9, 64 -1);
  LoadString(m_hInstResDLL, IDS_D10, sz_D10, 64 -1);
  LoadString(m_hInstResDLL, IDS_D11, sz_D11, 64 -1);
  LoadString(m_hInstResDLL, IDS_D12, sz_D12, 64 -1);
  LoadString(m_hInstResDLL, IDS_D13, sz_D13, 64 -1);
  LoadString(m_hInstResDLL, IDS_D14, sz_D14, 64 -1);
  LoadString(m_hInstResDLL, IDS_D15, sz_D15, 64 -1);
  LoadString(m_hInstResDLL, IDS_D16, sz_D16, 64 -1);
  LoadString(m_hInstResDLL, IDS_D17, sz_D17, 64 -1);
  LoadString(m_hInstResDLL, IDS_D18, sz_D18, 64 -1);
  LoadString(m_hInstResDLL, IDS_D19, sz_D19, 64 -1);
  LoadString(m_hInstResDLL, IDS_D20, sz_D20, 64 -1);
  LoadString(m_hInstResDLL, IDS_D21, sz_D21, 64 -1);
  LoadString(m_hInstResDLL, IDS_D22, sz_D22, 64 -1);
  LoadString(m_hInstResDLL, IDS_D23, sz_D23, 64 -1);
  LoadString(m_hInstResDLL, IDS_D24, sz_D24, 64 -1);
  LoadString(m_hInstResDLL, IDS_D25, sz_D25, 64 -1);
  LoadString(m_hInstResDLL, IDS_D26, sz_D26, 64 -1);
  LoadString(m_hInstResDLL, IDS_D27, sz_D27, 64 -1);
  LoadString(m_hInstResDLL, IDS_D28, sz_D28, 64 -1);
  LoadString(m_hInstResDLL, IDS_E1, sz_E1, 64 -1);
  LoadString(m_hInstResDLL, IDS_E2, sz_E2, 64 -1);
  LoadString(m_hInstResDLL, IDS_F1, sz_F1, 64 -1);
  LoadString(m_hInstResDLL, IDS_F3, sz_F3, 64 -1);
  LoadString(m_hInstResDLL, IDS_F4, sz_F4, 64 -1);
  LoadString(m_hInstResDLL, IDS_F5, sz_F5, 128 -1);
  LoadString(m_hInstResDLL, IDS_F6, sz_F6, 64 -1);
  LoadString(m_hInstResDLL, IDS_F7, sz_F7, 128 -1);
  LoadString(m_hInstResDLL, IDS_F8, sz_F8, 128 -1);
  LoadString(m_hInstResDLL, IDS_F10, sz_F10, 64 -1);
  LoadString(m_hInstResDLL, IDS_F11, sz_F11, 64 -1);
  LoadString(m_hInstResDLL, IDS_G1, sz_G1, 64 -1);
  LoadString(m_hInstResDLL, IDS_G1, sz_G2, 64 -1);
  LoadString(m_hInstResDLL, IDS_G1, sz_G3, 64 -1);

  LoadString(m_hInstResDLL, IDS_H1, sz_H1, 64 -1);
  LoadString(m_hInstResDLL, IDS_H2, sz_H2, 64 -1);
  LoadString(m_hInstResDLL, IDS_H3, sz_H3, 128 -1);
  LoadString(m_hInstResDLL, IDS_H4, sz_H4, 64 -1);
  LoadString(m_hInstResDLL, IDS_H5, sz_H5, 64 -1);
  LoadString(m_hInstResDLL, IDS_H6, sz_H6, 64 -1);
  LoadString(m_hInstResDLL, IDS_H7, sz_H7, 64 -1);
  LoadString(m_hInstResDLL, IDS_H8, sz_H8, 64 -1);
  LoadString(m_hInstResDLL, IDS_H9, sz_H9, 64 -1);
  LoadString(m_hInstResDLL, IDS_H10, sz_H10, 64 -1);
  LoadString(m_hInstResDLL, IDS_H11, sz_H11, 64 -1);
  LoadString(m_hInstResDLL, IDS_H12, sz_H12, 64 -1);
  LoadString(m_hInstResDLL, IDS_H13, sz_H13, 64 -1);
  LoadString(m_hInstResDLL, IDS_H14, sz_H14, 64 -1);
  LoadString(m_hInstResDLL, IDS_H15, sz_H15, 64 -1);
  LoadString(m_hInstResDLL, IDS_H16, sz_H16, 64 -1);
  LoadString(m_hInstResDLL, IDS_H17, sz_H17, 64 -1);
  LoadString(m_hInstResDLL, IDS_H18, sz_H18, 64 -1);
  LoadString(m_hInstResDLL, IDS_H19, sz_H19, 64 -1);
  LoadString(m_hInstResDLL, IDS_H20, sz_H20, 64 -1);
  LoadString(m_hInstResDLL, IDS_H21, sz_H21, 64 -1);
  LoadString(m_hInstResDLL, IDS_H22, sz_H22, 64 -1);
  LoadString(m_hInstResDLL, IDS_H23, sz_H23, 64 -1);
  LoadString(m_hInstResDLL, IDS_H24, sz_H24, 64 -1);
  LoadString(m_hInstResDLL, IDS_H25, sz_H25, 64 -1);
  LoadString(m_hInstResDLL, IDS_H26, sz_H26, 64 -1);
  LoadString(m_hInstResDLL, IDS_H27, sz_H27, 64 -1);
  LoadString(m_hInstResDLL, IDS_H28, sz_H28, 64 -1);
  LoadString(m_hInstResDLL, IDS_H29, sz_H29, 64 -1);
  LoadString(m_hInstResDLL, IDS_H30, sz_H30, 64 -1);
  LoadString(m_hInstResDLL, IDS_H31, sz_H31, 64 -1);
  LoadString(m_hInstResDLL, IDS_H32, sz_H32, 64 -1);
  LoadString(m_hInstResDLL, IDS_H33, sz_H33, 64 -1);
  LoadString(m_hInstResDLL, IDS_H34, sz_H34, 64 -1);
  LoadString(m_hInstResDLL, IDS_H35, sz_H35, 64 -1);
  LoadString(m_hInstResDLL, IDS_H36, sz_H36, 64 -1);
  LoadString(m_hInstResDLL, IDS_H37, sz_H37, 64 -1);
  LoadString(m_hInstResDLL, IDS_H38, sz_H38, 128 -1);
  LoadString(m_hInstResDLL, IDS_H39, sz_H39, 64 -1);
  LoadString(m_hInstResDLL, IDS_H40, sz_H40, 64 -1);
  LoadString(m_hInstResDLL, IDS_H41, sz_H41, 64 -1);
  LoadString(m_hInstResDLL, IDS_H42, sz_H42, 64 -1);
  LoadString(m_hInstResDLL, IDS_H43, sz_H43, 128 -1);
  LoadString(m_hInstResDLL, IDS_H44, sz_H44, 64 -1);
  LoadString(m_hInstResDLL, IDS_H45, sz_H45, 64 -1);
  LoadString(m_hInstResDLL, IDS_H46, sz_H46, 128 -1);
  LoadString(m_hInstResDLL, IDS_H47, sz_H47, 64 -1);
  LoadString(m_hInstResDLL, IDS_H48, sz_H48, 64 -1);
  LoadString(m_hInstResDLL, IDS_H49, sz_H49, 64 -1);
  LoadString(m_hInstResDLL, IDS_H50, sz_H50, 64 -1);
  LoadString(m_hInstResDLL, IDS_H51, sz_H51, 64 -1);
  LoadString(m_hInstResDLL, IDS_H52, sz_H52, 64 -1);
  LoadString(m_hInstResDLL, IDS_H53, sz_H53, 64 -1);
  LoadString(m_hInstResDLL, IDS_H54, sz_H54, 64 -1);
  LoadString(m_hInstResDLL, IDS_H55, sz_H55, 64 -1);
  LoadString(m_hInstResDLL, IDS_H56, sz_H56, 64 -1);
  LoadString(m_hInstResDLL, IDS_H57, sz_H57, 64 -1);

  LoadString(m_hInstResDLL, IDS_H58, sz_H58, 64 -1);
  LoadString(m_hInstResDLL, IDS_H59, sz_H59, 64 -1);
  LoadString(m_hInstResDLL, IDS_H60, sz_H60, 64 -1);
  LoadString(m_hInstResDLL, IDS_H61, sz_H61, 64 -1);
  LoadString(m_hInstResDLL, IDS_H62, sz_H62, 64 -1);
  LoadString(m_hInstResDLL, IDS_H63, sz_H63, 64 -1);
  LoadString(m_hInstResDLL, IDS_H64, sz_H64, 64 -1);
  LoadString(m_hInstResDLL, IDS_H65, sz_H65, 64 -1);
  LoadString(m_hInstResDLL, IDS_H66, sz_H66, 64 -1);
  LoadString(m_hInstResDLL, IDS_H67, sz_H67, 64 -1);
  LoadString(m_hInstResDLL, IDS_H68, sz_H68, 64 -1);
  LoadString(m_hInstResDLL, IDS_H69, sz_H69, 64 -1);
  LoadString(m_hInstResDLL, IDS_H70, sz_H70, 64 -1);
  LoadString(m_hInstResDLL, IDS_H71, sz_H71, 64 -1);
  LoadString(m_hInstResDLL, IDS_H72, sz_H72, 128 -1);
  LoadString(m_hInstResDLL, IDS_H73, sz_H73, 64 -1);

  
	LoadString(m_hInstResDLL, IDS_I1, sz_I1, 64 -1);
	LoadString(m_hInstResDLL, IDS_I2, sz_I2, 64 -1);
	LoadString(m_hInstResDLL, IDS_I3, sz_I3, 64 -1);

	LoadString(m_hInstResDLL, IDS_J1, sz_J1, 128 -1);
	LoadString(m_hInstResDLL, IDS_J2, sz_J2, 64 -1);

	LoadString(m_hInstResDLL, IDS_K1, sz_K1, 64 -1);
	LoadString(m_hInstResDLL, IDS_K2, sz_K2, 64 -1);
	LoadString(m_hInstResDLL, IDS_K3, sz_K3, sizeof(sz_K3)/sizeof(sz_K3[0]));
	LoadString(m_hInstResDLL, IDS_K4, sz_K4, 64 -1);
	LoadString(m_hInstResDLL, IDS_K5, sz_K5, 64 -1);
	LoadString(m_hInstResDLL, IDS_K6, sz_K6, 64 -1);

	LoadString(m_hInstResDLL, IDS_L1, sz_L1, 64 -1);
	LoadString(m_hInstResDLL, IDS_L2, sz_L2, 64 -1);
	LoadString(m_hInstResDLL, IDS_L3, sz_L3, 64 -1);
	LoadString(m_hInstResDLL, IDS_L4, sz_L4, 64 -1);
	LoadString(m_hInstResDLL, IDS_L5, sz_L5, 64 -1);
	LoadString(m_hInstResDLL, IDS_L6, sz_L6, 64 -1);
	LoadString(m_hInstResDLL, IDS_L7, sz_L7, 64 -1);
	LoadString(m_hInstResDLL, IDS_L8, sz_L8, 64 -1);
	LoadString(m_hInstResDLL, IDS_L9, sz_L9, 64 -1);
	LoadString(m_hInstResDLL, IDS_L10, sz_L10, 64 -1);
	LoadString(m_hInstResDLL, IDS_L11, sz_L11, 64 -1);
	LoadString(m_hInstResDLL, IDS_L12, sz_L12, 64 -1);
	LoadString(m_hInstResDLL, IDS_L13, sz_L13, 64 -1);
	LoadString(m_hInstResDLL, IDS_L14, sz_L14, 64 -1);
	LoadString(m_hInstResDLL, IDS_L15, sz_L15, 64 -1);
	LoadString(m_hInstResDLL, IDS_L16, sz_L16, 64 -1);
	LoadString(m_hInstResDLL, IDS_L17, sz_L17, 64 -1);
	LoadString(m_hInstResDLL, IDS_L18, sz_L18, 64 -1);
	LoadString(m_hInstResDLL, IDS_L19, sz_L19, 64 -1);
	LoadString(m_hInstResDLL, IDS_L20, sz_L20, 64 -1);
	LoadString(m_hInstResDLL, IDS_L21, sz_L21, 64 -1);
	LoadString(m_hInstResDLL, IDS_L22, sz_L22, 64 -1);
	LoadString(m_hInstResDLL, IDS_L23, sz_L23, 64 -1);
	LoadString(m_hInstResDLL, IDS_L24, sz_L24, 64 -1);
	LoadString(m_hInstResDLL, IDS_L25, sz_L25, 64 -1);
	LoadString(m_hInstResDLL, IDS_L26, sz_L26, 64 -1);
	LoadString(m_hInstResDLL, IDS_L27, sz_L27, 64 -1);
	LoadString(m_hInstResDLL, IDS_L28, sz_L28, 64 -1);
	LoadString(m_hInstResDLL, IDS_L29, sz_L29, 64 -1);
	LoadString(m_hInstResDLL, IDS_L30, sz_L30, 64 -1);
	LoadString(m_hInstResDLL, IDS_L31, sz_L31, 64 -1);
	LoadString(m_hInstResDLL, IDS_L32, sz_L32, 64 -1);
	LoadString(m_hInstResDLL, IDS_L33, sz_L33, 64 -1);
	LoadString(m_hInstResDLL, IDS_L34, sz_L34, 64 -1);
	LoadString(m_hInstResDLL, IDS_L35, sz_L35, 64 -1);
	LoadString(m_hInstResDLL, IDS_L36, sz_L36, 64 -1);
	LoadString(m_hInstResDLL, IDS_L37, sz_L37, 64 -1);
	LoadString(m_hInstResDLL, IDS_L38, sz_L38, 64 -1);
	LoadString(m_hInstResDLL, IDS_L39, sz_L39, 64 -1);
	LoadString(m_hInstResDLL, IDS_L40, sz_L40, 64 -1);
	LoadString(m_hInstResDLL, IDS_L41, sz_L41, 64 -1);
	LoadString(m_hInstResDLL, IDS_L42, sz_L42, 64 -1);
	LoadString(m_hInstResDLL, IDS_L43, sz_L43, 64 -1);
	LoadString(m_hInstResDLL, IDS_L44, sz_L44, 64 -1);
	LoadString(m_hInstResDLL, IDS_L45, sz_L45, 64 -1);
	LoadString(m_hInstResDLL, IDS_L46, sz_L46, 64 -1);
	LoadString(m_hInstResDLL, IDS_L47, sz_L47, 64 -1);
	LoadString(m_hInstResDLL, IDS_L48, sz_L48, 64 -1);
	LoadString(m_hInstResDLL, IDS_L49, sz_L49, 64 -1);
	LoadString(m_hInstResDLL, IDS_L50, sz_L50, 64 -1);
	LoadString(m_hInstResDLL, IDS_L51, sz_L51, 128 -1);
	LoadString(m_hInstResDLL, IDS_L52, sz_L52, 64 -1);
	LoadString(m_hInstResDLL, IDS_L53, sz_L53, 64 -1);
	LoadString(m_hInstResDLL, IDS_L54, sz_L54, 64 -1);
	LoadString(m_hInstResDLL, IDS_L55, sz_L55, 64 -1);
	LoadString(m_hInstResDLL, IDS_L56, sz_L56, 64 -1);
	LoadString(m_hInstResDLL, IDS_L57, sz_L57, 64 -1);
	LoadString(m_hInstResDLL, IDS_L58, sz_L58, 64 -1);
	LoadString(m_hInstResDLL, IDS_L59, sz_L59, 64 -1);
	LoadString(m_hInstResDLL, IDS_L60, sz_L60, 64 -1);
	LoadString(m_hInstResDLL, IDS_L61, sz_L61, 64 -1);
	LoadString(m_hInstResDLL, IDS_L62, sz_L62, 64 -1);
	LoadString(m_hInstResDLL, IDS_L63, sz_L63, 64 -1);
	LoadString(m_hInstResDLL, IDS_L64, sz_L64, 64 -1);
	LoadString(m_hInstResDLL, IDS_L65, sz_L65, 64 -1);
	LoadString(m_hInstResDLL, IDS_L66, sz_L66, 64 -1);
	LoadString(m_hInstResDLL, IDS_L67, sz_L67, 64 -1);
	LoadString(m_hInstResDLL, IDS_L68, sz_L68, 64 -1);
	LoadString(m_hInstResDLL, IDS_L69, sz_L69, 64 -1);
	LoadString(m_hInstResDLL, IDS_L70, sz_L70, 64 -1);
	LoadString(m_hInstResDLL, IDS_L71, sz_L71, 64 -1);
	LoadString(m_hInstResDLL, IDS_L72, sz_L72, 64 -1);
	LoadString(m_hInstResDLL, IDS_L73, sz_L73, 64 -1);
	LoadString(m_hInstResDLL, IDS_L74, sz_L74, 64 -1);
	LoadString(m_hInstResDLL, IDS_L75, sz_L75, 64 -1);
	LoadString(m_hInstResDLL, IDS_L76, sz_L76, 64 -1);
	LoadString(m_hInstResDLL, IDS_L77, sz_L77, 128 -1);
	LoadString(m_hInstResDLL, IDS_L78, sz_L78, 64 -1);
	LoadString(m_hInstResDLL, IDS_L79, sz_L79, 64 -1);
	LoadString(m_hInstResDLL, IDS_L80, sz_L80, 64 -1);
	LoadString(m_hInstResDLL, IDS_L81, sz_L81, 128 -1);
	LoadString(m_hInstResDLL, IDS_L82, sz_L82, 64 -1);
	LoadString(m_hInstResDLL, IDS_L83, sz_L83, 64 -1);
	LoadString(m_hInstResDLL, IDS_L84, sz_L84, 64 -1);
	LoadString(m_hInstResDLL, IDS_L85, sz_L85, 64 -1);
	LoadString(m_hInstResDLL, IDS_L86, sz_L86, 64 -1);
	LoadString(m_hInstResDLL, IDS_L87, sz_L87, 64 -1);
	LoadString(m_hInstResDLL, IDS_L88, sz_L88, 64 -1);
	LoadString(m_hInstResDLL, IDS_L89, sz_L89, 64 -1);
	LoadString(m_hInstResDLL, IDS_L90, sz_L90, 64 -1);
	LoadString(m_hInstResDLL, IDS_L91, sz_L91, 64 -1);
	LoadString(m_hInstResDLL, IDS_L92, sz_L92, 64 -1);
	LoadString(m_hInstResDLL, IDS_L93, sz_L93, 64 -1);
	LoadString(m_hInstResDLL, IDS_L94, sz_L94, 64 -1);

	LoadString(m_hInstResDLL, IDS_M1, sz_M1, 64 -1);
	LoadString(m_hInstResDLL, IDS_M2, sz_M2, 64 -1);
	LoadString(m_hInstResDLL, IDS_M3, sz_M3, 64 -1);
	LoadString(m_hInstResDLL, IDS_M4, sz_M4, 64 -1);
	LoadString(m_hInstResDLL, IDS_M5, sz_M5, 64 -1);
	LoadString(m_hInstResDLL, IDS_M6, sz_M6, 64 -1);
	LoadString(m_hInstResDLL, IDS_M7, sz_M7, 64 -1);
	LoadString(m_hInstResDLL, IDS_M8, sz_M8, 64 -1);  

    // 14 April 2008 jdp
	LoadString(m_hInstResDLL, IDS_H94, sz_H94, 64 -1);
	LoadString(m_hInstResDLL, IDS_H95, sz_H95, 64 -1);
	LoadString(m_hInstResDLL, IDS_H96, sz_H96, 64 -1);
	LoadString(m_hInstResDLL, IDS_H97, sz_H97, 64 -1);
	LoadString(m_hInstResDLL, IDS_H98, sz_H98, 64 -1);
	LoadString(m_hInstResDLL, IDS_H99, sz_H99, 64 -1);
    LoadString(m_hInstResDLL, IDS_H100, sz_H100, 64 -1);
    LoadString(m_hInstResDLL, IDS_H101, sz_H101, 64 -1);
    LoadString(m_hInstResDLL, IDS_H102, sz_H102, 128 -1);
//	RegisterLinkLabel(m_hInstResDLL);


	/////////////////////////////////////////////////////////////

	// The state of the application as a whole is contained in the one app object
		VNCviewerApp32 app(hInstance, szCmdLine);

    console = app.m_options.m_logToConsole;

	// Start a new connection if specified on command line, 
	// or if not in listening mode
	MSG msg;
	while(g_passwordfailed==true)
		{
			g_passwordfailed=false;
			if (app.m_options.m_connectionSpecified && !app.m_options.m_listening) {
				app.NewConnection(false,app.m_options.m_host_options, app.m_options.m_port);
			} else if (!app.m_options.m_listening) {
				// This one will also read from config file if specified
				app.NewConnection(false);
			}

			try
			{
					while ( GetMessage(&msg, NULL, 0,0) )
					{
						if (!TheAccelKeys.TranslateAccelKeys(&msg))
						{
							TranslateMessage(&msg);
							DispatchMessage(&msg);
						}
					} 
			}
			catch (Exception &e)
			{
                if (!g_ConnectionLossAlreadyReported)
				e.Report();
			}
		}
		// Clean up winsock
	WSACleanup();	
	vnclog.Print(3, _T("Exiting\n"));
#ifdef CRASHRPT
	crUninstall();
#endif
    if (console) Sleep(2000);	
	return msg.wParam;
}
Exemple #5
0
void Client::CloseConnection()
{
	// cleanup
	closesocket(_sockfd);
	WSACleanup();
}
Exemple #6
0
bool IrcBot::bot()
{
    char *text;
    char buf[1024];
    int bytes_read;
    int bytes_send;

    string sendCommands[5] = { "PONG", "USER "+userName+" 8 * :"+userName, "NICK "+nickName, "PRIVMSG nickserv identify "+userPass, "JOIN "+channelName };

    printf("Connecting to %s:%s\nNick: %s | Channel: %s\n", hostName.c_str(), portString.c_str(), nickName.c_str(), channelName.c_str());

    ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
                    *ptr = NULL,
                    hints;
    const char *sendbuf = "\nPONG :Bot\n";
    char recvbuf[DEFAULT_BUFLEN] = { };
    int recvbuflen = DEFAULT_BUFLEN;

    #ifdef WIN32
    // start WinSock Initialization
    WSADATA wsaData;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }
    #endif // WIN32

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

    // Resolve the server address and port
    iResult = getaddrinfo(hostName.c_str(), portString.c_str(), &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        #ifdef WIN32
        WSACleanup();
        #endif // WIN32
        return 1;
    }

    // Attempt to connect to an address until one succeeds
    for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {

        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            return 1;
        }

        // Connect to server.
        iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR)
        {
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);

    if (ConnectSocket == INVALID_SOCKET) {
        printf("Unable to connect to server!\n");
        #ifdef WIN32
        WSACleanup();
        #endif // WIN32
        return 1;
    }

    // Send an initial buffer
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if(DEBUG == true)
        printf("Sendbuf: %s\n", sendbuf);
    if (iResult == SOCKET_ERROR)
    {
        #ifdef WIN32
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        #endif // WIN32
        return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);

    // Receive until the peer closes the connection
    int count = 0;
    while(1)
    {
        count++;

        switch(count)
        {
            case 2:
                // we send data to server after 3 counts
                // nick
                sendCommand(ConnectSocket, "\nUSER %s Bot Bot : %s\n", userName.c_str(), userName.c_str());
                // user
                sendCommand(ConnectSocket, "\nNICK %s\r\n", nickName.c_str());
                break;
            case 11:
                // register
                sendCommand(ConnectSocket, "\nPRIVMSG nickserv identify %s\r\n", userPass.c_str());
                break;
            case 12:
                // we join channel
                sendCommand(ConnectSocket, "\nJOIN %s\r\n", channelName.c_str());
            default:
                break;
        }

        // Recv and print data
        bytes_read = recv(ConnectSocket, buf, MAXDATASIZE-1, 0);
        buf[bytes_read]='\0';
        cout << buf << endl;
        // buf is the data that is recieved

        // pass buffer to message handler
        msgHandler(buf);

        // if we get ping
        if(charSearch(buf,"PING"))
        {
            sendPong(buf);
        }

        //break if connection closed
        if(bytes_read == 0)
        {
            cout << "Connection closed!" << endl;
            cout << timeNow() << endl;

            break;
        }
    }
#ifdef WIN32
    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
#elif LINUX
    close(ConnectSocket);
#endif
    return true;
}
Exemple #7
0
int main(int argc, char **argv)
{
	const struct optstruct *opt;
#ifndef	C_WINDOWS
        struct passwd *user = NULL;
#endif
	time_t currtime;
	const char *dbdir, *cfgfile;
	char *pua_cats = NULL, *pt;
	int ret, tcpsock = 0, localsock = 0, i, min_port, max_port;
	unsigned int sigs = 0;
	int lsockets[2], nlsockets = 0;
	unsigned int dboptions = 0;
#ifdef C_LINUX
	struct stat sb;
#endif

#ifdef C_WINDOWS
    if(!pthread_win32_process_attach_np()) {
	mprintf("!Can't start the win32 pthreads layer\n");
        return 1;
    }
#endif

    if((opts = optparse(NULL, argc, argv, 1, OPT_CLAMD, 0, NULL)) == NULL) {
	mprintf("!Can't parse command line options\n");
	return 1;
    }

    if(optget(opts, "help")->enabled) {
    	help();
	optfree(opts);
	return 0;
    }

    if(optget(opts, "debug")->enabled) {
#if defined(C_LINUX)
	    /* [email protected]: create a dump if needed */
	    struct rlimit rlim;

	rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
	if(setrlimit(RLIMIT_CORE, &rlim) < 0)
	    perror("setrlimit");
#endif
	debug_mode = 1;
    }

    /* parse the config file */
    cfgfile = optget(opts, "config-file")->strarg;
    pt = strdup(cfgfile);
    if((opts = optparse(cfgfile, 0, NULL, 1, OPT_CLAMD, 0, opts)) == NULL) {
	fprintf(stderr, "ERROR: Can't open/parse the config file %s\n", pt);
	free(pt);
	return 1;
    }
    free(pt);

    if(optget(opts, "version")->enabled) {
	print_version(optget(opts, "DatabaseDirectory")->strarg);
	optfree(opts);
	return 0;
    }

    umask(0);

    /* drop privileges */
#if (!defined(C_OS2)) && (!defined(C_WINDOWS))
    if(geteuid() == 0 && (opt = optget(opts, "User"))->enabled) {
	if((user = getpwnam(opt->strarg)) == NULL) {
	    fprintf(stderr, "ERROR: Can't get information about user %s.\n", opt->strarg);
	    optfree(opts);
	    return 1;
	}

	if(optget(opts, "AllowSupplementaryGroups")->enabled) {
#ifdef HAVE_INITGROUPS
	    if(initgroups(opt->strarg, user->pw_gid)) {
		fprintf(stderr, "ERROR: initgroups() failed.\n");
		optfree(opts);
		return 1;
	    }
#else
	    mprintf("!AllowSupplementaryGroups: initgroups() is not available, please disable AllowSupplementaryGroups in %s\n", cfgfile);
	    optfree(opts);
	    return 1;
#endif
	} else {
#ifdef HAVE_SETGROUPS
	    if(setgroups(1, &user->pw_gid)) {
		fprintf(stderr, "ERROR: setgroups() failed.\n");
		optfree(opts);
		return 1;
	    }
#endif
	}

	if(setgid(user->pw_gid)) {
	    fprintf(stderr, "ERROR: setgid(%d) failed.\n", (int) user->pw_gid);
	    optfree(opts);
	    return 1;
	}

	if(setuid(user->pw_uid)) {
	    fprintf(stderr, "ERROR: setuid(%d) failed.\n", (int) user->pw_uid);
	    optfree(opts);
	    return 1;
	}
    }
#endif

    /* initialize logger */
    logg_lock = !optget(opts, "LogFileUnlock")->enabled;
    logg_time = optget(opts, "LogTime")->enabled;
    logok = optget(opts, "LogClean")->enabled;
    logg_size = optget(opts, "LogFileMaxSize")->numarg;
    logg_verbose = mprintf_verbose = optget(opts, "LogVerbose")->enabled;
    mprintf_send_timeout = optget(opts, "SendBufTimeout")->numarg;

    do { /* logger initialized */

    if((opt = optget(opts, "LogFile"))->enabled) {
	char timestr[32];
	logg_file = opt->strarg;
	if(strlen(logg_file) < 2 || (logg_file[0] != '/' && logg_file[0] != '\\' && logg_file[1] != ':')) {
	    fprintf(stderr, "ERROR: LogFile requires full path.\n");
	    ret = 1;
	    break;
	}
	time(&currtime);
	if(logg("#+++ Started at %s", cli_ctime(&currtime, timestr, sizeof(timestr)))) {
	    fprintf(stderr, "ERROR: Can't initialize the internal logger\n");
	    ret = 1;
	    break;
	}
    } else
	logg_file = NULL;

    if((ret = cl_init(CL_INIT_DEFAULT))) {
	logg("!Can't initialize libclamav: %s\n", cl_strerror(ret));
	ret = 1;
	break;
    }

    if(optget(opts, "Debug")->enabled) /* enable debug messages in libclamav */ {
	cl_debug();
	logg_verbose = 2;
    }

#if defined(USE_SYSLOG) && !defined(C_AIX)
    if(optget(opts, "LogSyslog")->enabled) {
	    int fac = LOG_LOCAL6;

	opt = optget(opts, "LogFacility");
	if((fac = logg_facility(opt->strarg)) == -1) {
	    logg("!LogFacility: %s: No such facility.\n", opt->strarg);
	    ret = 1;
	    break;
	}

	openlog("clamd", LOG_PID, fac);
	logg_syslog = 1;
    }
#endif

#ifdef C_LINUX
    procdev = 0;
    if(stat("/proc", &sb) != -1 && !sb.st_size)
	procdev = sb.st_dev;
#endif

    /* check socket type */

    if(optget(opts, "TCPSocket")->enabled)
	tcpsock = 1;

    if(optget(opts, "LocalSocket")->enabled)
	localsock = 1;

    if(!tcpsock && !localsock) {
	logg("!Please define server type (local and/or TCP).\n");
	ret = 1;
	break;
    }

    logg("#clamd daemon %s (OS: "TARGET_OS_TYPE", ARCH: "TARGET_ARCH_TYPE", CPU: "TARGET_CPU_TYPE")\n", get_version());

#ifndef C_WINDOWS
    if(user)
	logg("#Running as user %s (UID %u, GID %u)\n", user->pw_name, user->pw_uid, user->pw_gid);
#endif

    if(logg_size)
	logg("#Log file size limited to %d bytes.\n", logg_size);
    else
	logg("#Log file size limit disabled.\n");

    min_port = optget(opts, "StreamMinPort")->numarg;
    max_port = optget(opts, "StreamMaxPort")->numarg;
    if (min_port < 1024 || min_port > max_port || max_port > 65535) {
	logg("!Invalid StreamMinPort/StreamMaxPort: %d, %d\n", min_port, max_port);
	ret = 1;
	break;
    }

    if(!(engine = cl_engine_new())) {
	logg("!Can't initialize antivirus engine\n");
	ret = 1;
	break;
    }

    /* load the database(s) */
    dbdir = optget(opts, "DatabaseDirectory")->strarg;
    logg("#Reading databases from %s\n", dbdir);

    if(optget(opts, "DetectPUA")->enabled) {
	dboptions |= CL_DB_PUA;

	if((opt = optget(opts, "ExcludePUA"))->enabled) {
	    dboptions |= CL_DB_PUA_EXCLUDE;
	    i = 0;
	    logg("#Excluded PUA categories:");
	    while(opt) {
		if(!(pua_cats = realloc(pua_cats, i + strlen(opt->strarg) + 3))) {
		    logg("!Can't allocate memory for pua_cats\n");
		    cl_engine_free(engine);
		    ret = 1;
		    break;
		}
		logg("# %s", opt->strarg);
		sprintf(pua_cats + i, ".%s", opt->strarg);
		i += strlen(opt->strarg) + 1;
		pua_cats[i] = 0;
		opt = opt->nextarg;
	    }
	    if (ret)
		break;
	    logg("#\n");
	    pua_cats[i] = '.';
	    pua_cats[i + 1] = 0;
	}

	if((opt = optget(opts, "IncludePUA"))->enabled) {
	    if(pua_cats) {
		logg("!ExcludePUA and IncludePUA cannot be used at the same time\n");
		free(pua_cats);
		ret = 1;
		break;
	    }
	    dboptions |= CL_DB_PUA_INCLUDE;
	    i = 0;
	    logg("#Included PUA categories:");
	    while(opt) {
		if(!(pua_cats = realloc(pua_cats, i + strlen(opt->strarg) + 3))) {
		    logg("!Can't allocate memory for pua_cats\n");
		    ret = 1;
		    break;
		}
		logg("# %s", opt->strarg);
		sprintf(pua_cats + i, ".%s", opt->strarg);
		i += strlen(opt->strarg) + 1;
		pua_cats[i] = 0;
		opt = opt->nextarg;
	    }
	    if (ret)
		break;
	    logg("#\n");
	    pua_cats[i] = '.';
	    pua_cats[i + 1] = 0;
	}

	if(pua_cats) {
	    if((ret = cl_engine_set_str(engine, CL_ENGINE_PUA_CATEGORIES, pua_cats))) {
		logg("!cli_engine_set_str(CL_ENGINE_PUA_CATEGORIES) failed: %s\n", cl_strerror(ret));
		free(pua_cats);
		ret = 1;
		break;
	    }
	    free(pua_cats);
	}
    } else {
	logg("#Not loading PUA signatures.\n");
    }

    /* set the temporary dir */
    if((opt = optget(opts, "TemporaryDirectory"))->enabled) {
	if((ret = cl_engine_set_str(engine, CL_ENGINE_TMPDIR, opt->strarg))) {
	    logg("!cli_engine_set_str(CL_ENGINE_TMPDIR) failed: %s\n", cl_strerror(ret));
	    ret = 1;
	    break;
	}
    }

    if(optget(opts, "LeaveTemporaryFiles")->enabled)
	cl_engine_set_num(engine, CL_ENGINE_KEEPTMP, 1);

    if(optget(opts, "PhishingSignatures")->enabled)
	dboptions |= CL_DB_PHISHING;
    else
	logg("#Not loading phishing signatures.\n");

    if(optget(opts,"PhishingScanURLs")->enabled)
	dboptions |= CL_DB_PHISHING_URLS;
    else
	logg("#Disabling URL based phishing detection.\n");

    if(optget(opts,"DevACOnly")->enabled) {
	logg("#Only using the A-C matcher.\n");
	cl_engine_set_num(engine, CL_ENGINE_AC_ONLY, 1);
    }

    if((opt = optget(opts, "DevACDepth"))->enabled) {
        cl_engine_set_num(engine, CL_ENGINE_AC_MAXDEPTH, opt->numarg);
	logg("#Max A-C depth set to %u\n", (unsigned int) opt->numarg);
    }

    if((ret = cl_load(dbdir, engine, &sigs, dboptions))) {
	logg("!%s\n", cl_strerror(ret));
	ret = 1;
	break;
    }

    logg("#Loaded %u signatures.\n", sigs);
    if((ret = cl_engine_compile(engine)) != 0) {
	logg("!Database initialization error: %s\n", cl_strerror(ret));
	ret = 1;
	break;
    }

    if(tcpsock) {
#ifdef C_WINDOWS
	    WSADATA wsaData;

	if(WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) {
	    logg("!Error at WSAStartup(): %d\n", WSAGetLastError());
	    ret = 1;
	    break;
	}
#endif
	if ((lsockets[nlsockets] = tcpserver(opts)) == -1) {
	    ret = 1;
	    break;
	}
	nlsockets++;
    }

    if(localsock) {
	if ((lsockets[nlsockets] = localserver(opts)) == -1) {
	    ret = 1;
	    break;
	}
	nlsockets++;
    }

    /* fork into background */
    if(!optget(opts, "Foreground")->enabled) {
#ifdef C_BSD	    
	/* workaround for OpenBSD bug, see https://wwws.clamav.net/bugzilla/show_bug.cgi?id=885 */
	for(ret=0;ret<nlsockets;ret++) {
		fcntl(lsockets[ret], F_SETFL, fcntl(lsockets[ret], F_GETFL) | O_NONBLOCK);
	}
#endif
	if(daemonize() == -1) {
	    logg("!daemonize() failed\n");
	    ret = 1;
	    break;
	}
#ifdef C_BSD
	for(ret=0;ret<nlsockets;ret++) {
		fcntl(lsockets[ret], F_SETFL, fcntl(lsockets[ret], F_GETFL) & ~O_NONBLOCK);
	}
#endif
	if(!debug_mode)
	    if(chdir("/") == -1)
		logg("^Can't change current working directory to root\n");

    } else
        foreground = 1;

    ret = recvloop_th(lsockets, nlsockets, engine, dboptions, opts);

    } while (0);

    logg("*Closing the main socket%s.\n", (nlsockets > 1) ? "s" : "");

    for (i = 0; i < nlsockets; i++) {
	closesocket(lsockets[i]);
    }

#ifndef C_OS2
    if(nlsockets && localsock) {
	opt = optget(opts, "LocalSocket");
	if(unlink(opt->strarg) == -1)
	    logg("!Can't unlink the socket file %s\n", opt->strarg);
	else
	    logg("Socket file removed.\n");
    }
#endif

#ifdef C_WINDOWS
    if(tcpsock)
	WSACleanup();

    if(!pthread_win32_process_detach_np()) {
	logg("!Can't stop the win32 pthreads layer\n");
	logg_close();
	optfree(opts);
	return 1;
    }
#endif

    logg_close();
    optfree(opts);

    return ret;
}
Exemple #8
0
// This is the main server thread function.  As clients connect to the server,
// the HandleClientThreadFunction is called (within a new thread) to handle the
// new client.
void ServerThreadFunction(void * parameters){
	WSADATA winsock;
	SOCKET listenSocket, clientSocket;
	sockaddr_in socketAddress;
	BOOL bReuseAddr = TRUE;

	// Configure FreeImage error handler
	FreeImage_SetOutputMessage( FreeImageErrorHandler );

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

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

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

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

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

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

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

		// Start a new thread to handle the new client
		_beginthread(HandleClientThreadFunction, 0, (void*)clientSocket);
	}
	
	// Process cleanup
	MessageBox(NULL, "ServerThread finished", "USARSim Image Server", MB_OK);
	WSACleanup();
	return;
}
DWORD WINAPI RetranTreat(LPVOID lpParameter){

	WORD wVersionRequested; 
    WSADATA wsaData; 
    int err; 
    wVersionRequested = MAKEWORD(1,1); 
    err = WSAStartup(wVersionRequested,&wsaData); 
    if ( err != 0 ) { 
        return -1; 
    } 

    if ( LOBYTE( wsaData.wVersion ) != 1 || 
        HIBYTE( wsaData.wVersion ) != 1) { 
            WSACleanup( ); 
            return -1; 
    } 

    SOCKET retran_socket=socket(AF_INET,SOCK_DGRAM,0);

    SOCKADDR_IN  retran_addr;

	
	

    //retran_addr.sin_addr.S_un.S_addr=inet_addr("192.168.1.5");           //此处有修改
	retran_addr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
    retran_addr.sin_family=AF_INET;
    retran_addr.sin_port=htons(retranport);

    if(bind(retran_socket,(sockaddr*)&retran_addr,sizeof(SOCKADDR_IN))==-1){
		printf("bind error~~~~~~~~~~~~~~\n");
	}

	int priority=0;

	while(1) 
    { 
		SOCKADDR_IN client_socket; 
		int len = sizeof(SOCKADDR);
        char recvbuf[1500]; 
        int commd_size=recvfrom(retran_socket,recvbuf,1500,0,(SOCKADDR*)&client_socket,&len);
		if(commd_size<=0){
			//printf("Retan Comm error");
			continue;   //这个是自己加的9-24
		}
		printf("treat Retan %s to UPD server port %d  size:%d\n",inet_ntoa(client_socket.sin_addr),ntohs(client_socket.sin_port),commd_size);
		int pointer = 0;
		int userid ;
		memcpy(&userid,recvbuf,sizeof(int));
		pointer +=sizeof(int);
		while(1){
			priority++;
			long miss_top_id;
			int sqnum;
			int timestmp;
			memcpy(&miss_top_id,recvbuf+pointer,sizeof(long));
			pointer += sizeof(miss_top_id);
			memcpy(&sqnum,recvbuf+pointer,sizeof(int));
			pointer += sizeof(sqnum);
			memcpy(&timestmp,recvbuf+pointer,sizeof(int));
			pointer += sizeof(timestmp);

			RestoreCell rc;

			//printf("apply data id:%d sqnum:%d timestmp%d\n",miss_top_id,sqnum,timestmp);
			if(rsb.applyData(miss_top_id,sqnum,timestmp,&rc)>=0){
				//printf("finded data sqnum:%d\n",sqnum);

				KeyValue  *pkg=new KeyValue();
				memcpy(pkg->value,rc.data,rc.size+sizeof(long)+sizeof(int));
				pkg->pkgsize=rc.size;
				pkg->user_id=userid;
				pkg->key=priority;


				if(!retransQueue.isInSchedule(*pkg)){
				    retransQueue.priority_queue_enqueue(pkg);
				}
			}


			if(pointer+1>=commd_size)
				 break;


		}
    } 

	return 0;


}
void bad()
{
    wchar_t * data;
    unionType myUnion;
    wchar_t dataBuffer[FILENAME_MAX] = L"";
    data = dataBuffer;
    {
#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
    }
    myUnion.unionFirst = data;
    {
        wchar_t * data = myUnion.unionSecond;
        {
            ifstream inputFile;
            /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
            inputFile.open((char *)data);
            inputFile.close();
        }
    }
}
void TApplicationServer::nativeSocketCleanup()
{
    WSACleanup();
}
Exemple #12
0
/**
 * 	\brief	Free network ressources
 */
void net_exit(void)
{
#ifdef OS_WIN
    WSACleanup();
#endif
}
Exemple #13
0
void end_socklib ( void )
{
#ifdef WIN_TCP
  WSACleanup();
#endif
}
void CWE134_Uncontrolled_Format_String__wchar_t_listen_socket_snprintf_68_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    {
#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) * (100 - 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
    }
    CWE134_Uncontrolled_Format_String__wchar_t_listen_socket_snprintf_68_badData = data;
    CWE134_Uncontrolled_Format_String__wchar_t_listen_socket_snprintf_68b_badSink();
}
void IDAconnector::server_connect (void)
{
    hostent      *he;
    sockaddr_in  sin;
    in_addr      addr;
    WSADATA      wsa_data;

    char buf         [512];
    char message     [128];
    char password    [64];
    char project     [64];
    char server_addr [128];
    char username    [64];
    int  code;
    int  len;
    int  port = 5041;

    const char dialog_format[] =
        "STARTITEM 0\n"
        PLUGIN_NAME"\n"
        "Connect to IDA Sync server.\n\n"
        "Server / Port: \n<:A:512:30::> <:D:5:5::>\n"
        "Username:      \n<:A:128:40::>\n"
        "Password:      \n<:A:128:40::>\n"
        "Project Name:  \n<:A:128:40::>\n\n";

    memset(buf,         0, sizeof(buf));
    memset(message,     0, sizeof(message));
    memset(password,    0, sizeof(password));
    memset(project,     0, sizeof(project));
    memset(server_addr, 0, sizeof(server_addr));
    memset(username,    0, sizeof(username));

    // if we are already connected then do nothing.
    if (connected)
        return;

    // prompt the user for server connection information..
    if (!AskUsingForm_c(dialog_format, server_addr, &port, username, password, project))
    {
        msg("[!] "PLUGIN_NAME"> Connection cancelled.\n");
        return;
    }

    // initialize winsock.
    if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0)
    {
        msg("[!] "PLUGIN_NAME"> WSAStartup() failed.\n");
        return;
    }

    // confirm that the requested winsock version is supported.
    if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)
    {
        WSACleanup();
        msg("[!] "PLUGIN_NAME"> Winsock version 2.2 not found.\n");
        return;
    }

    // check if a valid IP address was provided, if not try to do gethostbyname().
    addr.s_addr = inet_addr(server_addr);

    if( addr.s_addr == INADDR_NONE )
    {
        if ((he = gethostbyname(server_addr)) == NULL)
        {
            msg("[!] "PLUGIN_NAME"> Unable to resolve name: %s\n", server_addr);
            return;
        }
    }
    // otherwise, use the numeric IP address with gethostbyaddr()
    else
    {
        if ((he = gethostbyaddr((char *)&addr, sizeof(struct in_addr), AF_INET)) == NULL)
        {
            msg("[!] "PLUGIN_NAME"> Unable to resolve address\n");
            return;
        }
    }

    // create a socket.
    if ((connection = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
    {
        WSACleanup();
        msg("[!] "PLUGIN_NAME"> Failed to create socket.\n");
        return;
    }

    // connect to the server.
    sin.sin_family = AF_INET;
    sin.sin_addr   = *((LPIN_ADDR)*he->h_addr_list);
    sin.sin_port   = htons(port);

    if (connect(connection, (SOCKADDR *) &sin, sizeof(sin)) == SOCKET_ERROR)
    {
        WSACleanup();
        msg("[!] "PLUGIN_NAME"> Failed to connect to server.\n");
        return;
    }

    // connection to server successful.

    // register the plugin with the console.
    qsnprintf(buf, sizeof(buf) - 1, PLUGIN_NAME":::%s:::%s:::%s", project, username, password);

    len = strlen(buf);

    // send the registration request.
    if (send(connection, buf, len, 0) != len)
    {
        closesocket(connection);
        WSACleanup();
        msg("[!] "PLUGIN_NAME"> Failed to register with server.\n");
        return;
    }

    // receive the registration confirmation.
    len = recv(connection, buf, sizeof(buf) - 1, 0);

    // connection closed.
    if (len == 0 || len == SOCKET_ERROR)
    {
        closesocket(connection);
        WSACleanup();
        msg("[!] "PLUGIN_NAME"> Failed to read registration response from server.\n");
        return;
    }

    // null terminate the received buffer.
    buf[len] = 0;

    // parse the server message. format: code:::message.
    // if we can't understand the response, then quit.
    if (sscanf(buf, "%d:::%127[^\0]", &code, message) != 2)
    {
        closesocket(connection);
        WSACleanup();
        msg("[!] "PLUGIN_NAME"> Registration failed.\n");
        return;
    }

    // registration failed. print why.
    if (code == 0)
    {
        closesocket(connection);
        WSACleanup();
        msg("[!] "PLUGIN_NAME"> Registration failed: %s\n", message);
        return;
    }

    // create an invisble window for hooking messages received by our socket.
    if ((socket_hwnd = CreateWindowEx(0, "STATIC", PLUGIN_NAME, 0, 0, 0, 0, 0, 0, 0, 0, 0)) == NULL)
    {
        closesocket(connection);
        WSACleanup();
        msg("[!] "PLUGIN_NAME"> CreateWindowEx() failed.\n");
        return;
    }

    // register the callback function for our invisible window.
    if (SetWindowLong(socket_hwnd, GWL_WNDPROC, (long) socket_proc_wrapper) == 0)
    {
        closesocket(connection);
        WSACleanup();
        DestroyWindow(socket_hwnd);
        msg("[!] "PLUGIN_NAME"> SetWindowLong() failed.\n");
        return;
    }

    // make the socket a non-blocking asynchronous socket hooked with our socket_proc handler.
    if (WSAAsyncSelect(connection, socket_hwnd, SOCKET_MSG, FD_READ | FD_CLOSE) == SOCKET_ERROR)
    {
        closesocket(connection);
        WSACleanup();
        DestroyWindow(socket_hwnd);
        msg("[!] "PLUGIN_NAME"> Failed to create asynchronous connection to server.\n");
        return;
    }

    // asynchronous connection to server established. raise the connected flag.
    msg("[*] "PLUGIN_NAME"> Successfully registered project '%s' with server as '%s'\n", project, username);
    connected = true;
}
Exemple #16
0
  int main()
  {
    setlocale(LC_ALL, "Russian");
	  char buffer[MAXBUF];

    //инициализация библиотеки Winsock
    if (WSAStartup(0x202,(WSADATA *)&buffer[0]))
    {
      printf("WSAStart error %d\n",WSAGetLastError());
	  _getch();
      return -1;
    }

    //создание сокета
    SOCKET sock;
    sock=socket(AF_INET,SOCK_STREAM,0);
    if (sock < 0)
    {
      printf("Socket() error %d\n",WSAGetLastError());
	  _getch();
      return -1;
    }

    //установка соединения
    // заполнение структуры sockaddr_in
    // указание адреса и порта сервера
    sockaddr_in dest_addr;
    dest_addr.sin_family=AF_INET;
    dest_addr.sin_port=htons(PORT);
    HOSTENT *hst;

    // преобразование IP адреса из символьного в
    // сетевой формат
    if (inet_addr(SERVERADDR)!=INADDR_NONE)
      dest_addr.sin_addr.s_addr=inet_addr(SERVERADDR);
    else
      // попытка получить IP адрес по доменному
      // имени сервера
      if (hst=gethostbyname(SERVERADDR))
      // hst->h_addr_list содержит не массив адресов,
      // а массив указателей на адреса
      ((unsigned long *)&dest_addr.sin_addr)[0]=
        ((unsigned long **)hst->h_addr_list)[0][0];
      else 
      {
        printf("Invalid address %s\n",SERVERADDR);
        closesocket(sock);
        WSACleanup();
		_getch();
        return -1;
      }

    if (connect(sock,(sockaddr *)&dest_addr,
                sizeof(dest_addr)))
    {
      printf("Connect error %d\n",WSAGetLastError());
	  _getch();
      return -1;
    }

	//-----------------------------------------------
	memset(buffer, 0, MAXBUF);
    recv(sock , buffer , MAXBUF , 0); // прием слова
    puts(buffer);
    printf("Для получения справки введите команду help\n");
    while(1){
		memset(buffer, 0, MAXBUF);
        printf("Cmd: ");
        scanf("%s" , buffer);
        // команды
        if(strcmp(buffer, "view") == 0)
			view_dir(buffer, sock, MAXBUF);
        else if(strcmp(buffer, "view_dir") == 0)
            view_dir(buffer, sock, MAXBUF);
        else if(strcmp(buffer, "help") == 0)
            get_help();
        else if(strcmp(buffer, "get_dir") == 0)
            get_dir(buffer, sock, MAXBUF);
        else if(strcmp(buffer, "ch_dir") == 0)
            ch_dir(buffer, sock, MAXBUF);
        else if(strcmp(buffer, "upload") == 0)
            upload(buffer, MAXBUF, sock);
		else if(strcmp(buffer, "download") == 0)
            download(buffer, MAXBUF, sock);
        else if(strcmp(buffer, "mk_dir") == 0)
            mk_dir(buffer, MAXBUF, sock);
        else if(strcmp(buffer, "rm_dir") == 0)
            rm_dir(buffer, MAXBUF, sock);
		else if(strcmp(buffer, "echo") == 0)
            echo(buffer, sock, MAXBUF);
		else if(strcmp(buffer, "disconnect") == 0){
            send(sock, "disconnect", 10, 0);
			break;
		}
        else
            printf("unknown comand\n");
        printf("Для получения справки введите команду help\n");
    }
	//-----------------------------------------------
	printf("\nExit\n");
    closesocket(sock);
    WSACleanup();
	_getch();
    return 0;
  }
int
main(int argc, char* argv[]) {
	int server_fd;
	int client_fd;
	int writer_len;
	struct sockaddr_in reader_addr; 
	struct sockaddr_in writer_addr;

#ifdef _WIN32
	WSADATA wsa;
	WSAStartup(MAKEWORD(2, 0), &wsa);
#endif

	if ((server_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
		perror("reader: socket");
		exit(1);
	}

	memset((char *) &reader_addr, 0, sizeof(reader_addr));
	reader_addr.sin_family = PF_INET;
	reader_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	//reader_addr.sin_port = htons(8000);
	reader_addr.sin_port = 0;

	if (bind(server_fd, (struct sockaddr *)&reader_addr, sizeof(reader_addr)) < 0) {
		perror("reader: bind");
		exit(1);
	}
	size_t socklen = sizeof(reader_addr);
	if (getsockname(server_fd, (struct sockaddr *)&reader_addr, &socklen) < 0) {
		perror("reader: bind");
		exit(1);
	}

	if (listen(server_fd, 5) < 0) {
		perror("reader: listen");
		close(server_fd);
		exit(1);
	}

	if ((client_fd = accept(server_fd,(struct sockaddr *)&writer_addr, &writer_len)) < 0) {
		perror("reader: accept");
		exit(1);
	}

	while (1) {
		char buf[256];
		size_t n = recv(client_fd, buf, sizeof(buf), 0);
		puts(buf);
		if (n == 0) {
			break;
		} else if (n == -1) {
			perror("recv");
			exit(EXIT_FAILURE);
		} else {
			send(client_fd, buf, n, 0);
		}
	}

	closesocket(server_fd);

#ifdef _WIN32
	WSACleanup();
#endif
}
int _cdecl
main(int argc, char *argv[]) {

#ifdef WIN32
  WSADATA	wsa_data ;
  
  /* Initialize the winsock lib do we still want version 2.2? */
  if ( WSAStartup(MAKEWORD(2,2), &wsa_data) == SOCKET_ERROR ){
    printf("WSAStartup() failed : %lu\n", GetLastError()) ;
    return -1 ;
  }
#endif /* WIN32 */

  /* Save away the program name */
  program = (char *)malloc(strlen(argv[0]) + 1);
  if (program == NULL) {
    printf("malloc for program name failed!\n");
    return -1 ;
  }
  strcpy(program, argv[0]);
  
  init_netserver_globals();

  netlib_init();
  
  strncpy(local_host_name,"",sizeof(local_host_name));
  local_address_family = AF_UNSPEC;
  strncpy(listen_port,TEST_PORT,sizeof(listen_port));
	  
  scan_netserver_args(argc, argv);

  check_if_inetd();

  if (child) {
    /* we are the child of either an inetd or parent netserver via
       spawning (Windows) rather than fork()ing. if we were fork()ed
       we would not be coming through this way. set_server_sock() must
       be called before open_debug_file() or there is a chance that
       we'll toast the descriptor when we do not wish it. */
    set_server_sock();
    open_debug_file();
    process_requests();
  }
  else if (daemon_parent) {
    /* we are the parent daemonized netserver
       process. accept_connections() will decide if we want to spawn a
       child process */
    accept_connections();
  }
  else {
    /* we are the top netserver process, so we have to create the
       listen endpoint(s) and decide if we want to daemonize */
    setup_listens(local_host_name,listen_port,local_address_family);
    if (want_daemonize) {
      daemonize();
    }
    accept_connections();
  }

  unlink_empty_debug_file();

#ifdef WIN32
  WSACleanup();
#endif

  return 0;
	  
}
void CWE78_OS_Command_Injection__wchar_t_connect_socket_w32_spawnv_01_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        wchar_t *replace;
        SOCKET connectSocket = 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 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(wchar_t) * (100 - 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 (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    {
        wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
        /* wspawnv - specify the path where the command is located */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        _wspawnv(_P_WAIT, COMMAND_INT_PATH, args);
    }
}
Win32Network::~Win32Network(){
	WSACleanup();
}
void CWE114_Process_Control__w32_wchar_t_listen_socket_18_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    goto source;
source:
    {
#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) * (100 - 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
    }
    {
        HMODULE hModule;
        /* POTENTIAL FLAW: If the path to the library is not specified, an attacker may be able to
         * replace his own file with the intended library */
        hModule = LoadLibraryW(data);
        if (hModule != NULL)
        {
            FreeLibrary(hModule);
            printLine("Library loaded and freed successfully");
        }
        else
        {
            printLine("Unable to load library");
        }
    }
}
Exemple #22
0
int main()
{

#ifdef WINDOWS_XP

	// Initialize the winsock library
	WSADATA wsaData;
    winLog << "system started ..." << endl;
	winLog << endl << "initialize the winsock library ... ";

	try 
	{
		if (WSAStartup(0x101, &wsaData))
		{
			myException* initializationException = new myException(0,"Error: calling WSAStartup()");
			throw initializationException;
        }
	}
	catch(myException* excp)
	{
		excp->response();
		delete excp;
		exit(1);
	}
	winLog << "successful" << endl;

#endif
        
	// get local information if neither the name or the address is given

	winLog << endl;
	winLog << "Retrieve the local host name and address:" << endl;
	
    myHostInfo uHostAddress;
	string localHostName = uHostAddress.getHostName();
    string localHostAddr = uHostAddress.getHostIPAddress();
	cout << "------------------------------------------------------" << endl;
	cout << "	My local host information:" << endl;
	cout << "		Name:    " << localHostName << endl;
    cout << "		Address: " << localHostAddr << endl;
	cout << "------------------------------------------------------" << endl;

	winLog << "		==> Name: " << localHostName << endl;
	winLog << "		==> Address: " << localHostAddr << endl;

	// open socket on the local host
	myTcpSocket myServer(PORTNUM);
	cout << myServer;
	winLog << "server configuation: " << endl;
	winLog << myServer;

    myServer.bindSocket();
	cout   << endl << "server finishes binding process... " << endl;
	winLog << endl << "server finishes binding process... " << endl;
	
	myServer.listenToClient();
	cout   << "server is listening to the port ... " << endl;
	winLog << "server is listening to the port ... " << endl;

    // wait to accept a client connection.  
	// processing is suspended until the client connects
	cout   << "server is waiting for client connecction ... " << endl;
	winLog << "server is waiting for client connnection ... " << endl;

    myTcpSocket* client;    // connection dedicated for client communication
    string clientHost;      // client name etc. 
    client = myServer.acceptClient(clientHost);
        
    cout   << endl << "==> A client from [" << clientHost << "] is connected!" << endl << endl;
	winLog << endl << "==> A client from [" << clientHost << "] is connected!" << endl << endl;

	while(1)
	{
		string clientMessageIn = "";
		
		// receive from the client

        int numBytes = client->recieveMessage(clientMessageIn);
		if ( numBytes == -99 ) break;

		cout   << "[RECV:" << clientHost << "]: " << clientMessageIn << endl;
		winLog << "[RECV:" << clientHost << "]: " << clientMessageIn << endl;

		// send to the clien

		char sendmsg[MAX_MSG_LEN+1];
		memset(sendmsg,0,sizeof(sendmsg));
		cout << "[" << localHostName << ":SEND] ";
		cin.getline(sendmsg,MAX_MSG_LEN);

		if ( numBytes == -99 ) break;
		string sendMsg(sendmsg);
		if ( sendMsg.compare("Bye") == 0 || sendMsg.compare("bye") == 0 )
			break;
		//cout   << "[" << localHostName << ": SEND] " << sendMsg << endl;
		winLog << "[" << localHostName << ": SEND] " << sendMsg << endl;
	
		client->sendMessage(sendMsg);
    }

#ifdef WINDOWS_XP

    // Close the winsock library
	winLog << endl << "system shut down ...";		
	
	try 
	{
		if (WSACleanup())
		{
			myException* cleanupException = new myException(0,"Error: calling WSACleanup()");
			throw cleanupException;
        }
	}
	catch(myException* excp)
	{
		excp->response();
		delete excp;
		exit(1);
	}
	winLog << "successful" << endl;

#endif

    return 1;
}
Exemple #23
0
int Client::ConnectToServer(const char* serverName, const char* portNumber)
{
	WSADATA wsaData;

	int iResult;

	// Initialize Winsock
	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != 0) {
		printf("WSAStartup failed: %d\n", iResult);
		return 1;
	}

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

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

	// Resolve the server address and port
	iResult = getaddrinfo(serverName, portNumber, &hints, &result);
	if (iResult != 0) {
		printf("getaddrinfo failed: %d\n", iResult);
		WSACleanup();
		return 1;
	}

	// Attempt to connect to the first address returned by
	// the call to getaddrinfo
	ptr = result;

	// Create a SOCKET for connecting to server
	_sockfd = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);

	if (_sockfd == INVALID_SOCKET) {
		printf("Error at socket(): %ld\n", WSAGetLastError());
		freeaddrinfo(result);
		WSACleanup();
		return 1;
	}

	// Connect to server.
	iResult = connect(_sockfd, ptr->ai_addr, (int)ptr->ai_addrlen);
	if (iResult == SOCKET_ERROR) {
		closesocket(_sockfd);
		_sockfd = INVALID_SOCKET;
	}

	// Should really try the next address returned by getaddrinfo
	// if the connect call failed
	// But for this simple example we just free the resources
	// returned by getaddrinfo and print an error message

	freeaddrinfo(result);

	if (_sockfd == INVALID_SOCKET) {
		printf("Unable to connect to server!\n");
		WSACleanup();
		return 1;
	}

	// shutdown the connection for sending since no more data will be sent
	// the client can still use the ConnectSocket for receiving data
	iResult = shutdown(_sockfd, SD_SEND);
	if (iResult == SOCKET_ERROR) {
		printf("shutdown failed: %d\n", WSAGetLastError());
		closesocket(_sockfd);
		WSACleanup();
		return 1;
	}

	return 0;
}
Exemple #24
0
void net_Destroy()
{
	if (sock!=INVALID_SOCKET) closesocket(sock);
	WSACleanup();
}
Exemple #25
0
bool echoscu(const QString &peerTitle, const QString &ourTitle,
             const QString &hostname, int port,
             QString &msg)
{
    T_ASC_Network *net;
    T_ASC_Parameters *params;
    T_ASC_Association *assoc;
    OFString temp_str;
    bool ret = false;

#ifdef HAVE_WINSOCK_H
    WSAData winSockData;
    /* we need at least version 1.1 */
    WORD winSockVersionNeeded = MAKEWORD( 1, 1 );
    WSAStartup(winSockVersionNeeded, &winSockData);
#endif

    /* initialize network, i.e. create an instance of T_ASC_Network*. */
    OFCondition cond = ASC_initializeNetwork(NET_REQUESTOR, 0, 6, &net);
    if (cond.bad()) {
        DimseCondition::dump(temp_str, cond);
        msg = QString::fromLatin1(temp_str.c_str());
        goto cleanup;
    }

    /* initialize asscociation parameters, i.e. create an instance of T_ASC_Parameters*. */
    cond = ASC_createAssociationParameters(&params, ASC_DEFAULTMAXPDU);
    if (cond.bad()) {
        DimseCondition::dump(temp_str, cond);
        msg = QString::fromLatin1(temp_str.c_str());
        goto cleanup;
    }

    ASC_setAPTitles(params, ourTitle.toLocal8Bit().data(), peerTitle.toLocal8Bit().data(), NULL);

    /* Set the transport layer type (type of network connection) in the params */
    /* strucutre. The default is an insecure connection; where OpenSSL is  */
    /* available the user is able to request an encrypted,secure connection. */
    cond = ASC_setTransportLayerType(params, OFFalse);
    if (cond.bad()) {
        DimseCondition::dump(temp_str, cond);
        msg = QString::fromLatin1(temp_str.c_str());
        goto cleanup;
    }

    /* Figure out the presentation addresses and copy the */
    /* corresponding values into the association parameters.*/
    DIC_NODENAME localHost;
    DIC_NODENAME peerHost;
    gethostname(localHost, sizeof(localHost) - 1);
    sprintf(peerHost, "%s:%d", hostname.toLocal8Bit().data(), port);

    ASC_setPresentationAddresses(params, localHost, peerHost);

    /* Set the presentation contexts which will be negotiated */
    /* when the network connection will be established */
    int presentationContextID = 1; /* odd byte value 1, 3, 5, .. 255 */
    for (unsigned long ii=0; ii<1; ii++)
    {
        cond = ASC_addPresentationContext(params, presentationContextID, UID_VerificationSOPClass,
                 transferSyntaxes, 3);
        presentationContextID += 2;
        if (cond.bad())
        {
            DimseCondition::dump(temp_str, cond);
            msg = QString::fromLatin1(temp_str.c_str());
            goto cleanup;
        }
    }

    /* create association, i.e. try to establish a network connection to another */
    /* DICOM application. This call creates an instance of T_ASC_Association*. */
    cond = ASC_requestAssociation(net, params, &assoc);
    if (cond.bad()) {
        if (cond == DUL_ASSOCIATIONREJECTED)
        {
            T_ASC_RejectParameters rej;

            ASC_getRejectParameters(params, &rej);
            ASC_printRejectParameters(temp_str, &rej);
            msg = QString("Association Rejected: %1").arg(temp_str.c_str());
            goto cleanup;
        } else {
            DimseCondition::dump(temp_str, cond);
            msg = QString("Association Request Failed: %1").arg(temp_str.c_str());
            goto cleanup;
        }
    }

    /* count the presentation contexts which have been accepted by the SCP */
    /* If there are none, finish the execution */
    if (ASC_countAcceptedPresentationContexts(params) == 0) {
        msg = QString("No Acceptable Presentation Contexts");
        goto cleanup;
    }

    /* do the real work, i.e. send a number of C-ECHO-RQ messages to the DICOM application */
    /* this application is connected with and handle corresponding C-ECHO-RSP messages. */
    DIC_US msgId = assoc->nextMsgID++;
    DIC_US status;
    DcmDataset *statusDetail = NULL;

    /* send C-ECHO-RQ and handle response */
    cond = DIMSE_echoUser(assoc, msgId, DIMSE_BLOCKING, 0, &status, &statusDetail);

    /* check for status detail information, there should never be any */
    if (statusDetail != NULL) {
        delete statusDetail;
    }

    /* tear down association, i.e. terminate network connection to SCP */
    if (cond == EC_Normal)
    {
        cond = ASC_releaseAssociation(assoc);
        ret = true;
    }
    else if (cond == DUL_PEERABORTEDASSOCIATION)
    {

    }
    else
    {
        DimseCondition::dump(temp_str, cond);
        msg = QString::fromLatin1(temp_str.c_str());
        cond = ASC_abortAssociation(assoc);
    }

cleanup:
    /* destroy the association, i.e. free memory of T_ASC_Association* structure. This */
    /* call is the counterpart of ASC_requestAssociation(...) which was called above. */
    cond = ASC_destroyAssociation(&assoc);

    /* drop the network, i.e. free memory of T_ASC_Network* structure. This call */
    /* is the counterpart of ASC_initializeNetwork(...) which was called above. */
    cond = ASC_dropNetwork(&net);

#ifdef HAVE_WINSOCK_H
    WSACleanup();
#endif

    return ret;
}
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_32_bad()
{
    size_t data;
    size_t *dataPtr1 = &data;
    size_t *dataPtr2 = &data;
    /* Initialize data */
    data = 0;
    {
        size_t data = *dataPtr1;
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            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
                /* 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, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* NUL-terminate the string */
                inputBuffer[recvResult] = '\0';
                /* Convert to unsigned int */
                data = strtoul(inputBuffer, NULL, 0);
            }
            while (0);
            if (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
        *dataPtr1 = data;
    }
    {
        size_t data = *dataPtr2;
        {
            char * myString;
            /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
             * for the strcpy() function to not cause a buffer overflow */
            /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
            if (data > strlen(HELLO_STRING))
            {
                myString = (char *)malloc(data*sizeof(char));
                /* Copy a small string into myString */
                strcpy(myString, HELLO_STRING);
                printLine(myString);
                free(myString);
            }
            else
            {
                printLine("Input is less than the length of the source string");
            }
        }
    }
}
int main(void)
{
    int tmp = 0;
    int cnt = 0;
    int iResult = 0;

    printf(WelcomeInfo);
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\r\n", iResult);
        return 1;
    }
    printf("Initial WinSock OK\r\r\n");

    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (ConnectSocket  == INVALID_SOCKET)
    {
        printf("socket failed with error: %ld\r\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }
    printf("Create Socket OK\r\n");

    //Connect to Server
    printf("Please Input Server IP:");
    scanf("%s", IP);
    getchar();
    ServerCfg.sin_family = AF_INET;
    ServerCfg.sin_port = htons(DEFAULT_PORT);
    ServerCfg.sin_addr.s_addr = inet_addr(IP);

    printf("Try to connect server\r\n");
    iResult = connect(ConnectSocket, (struct sockaddr *)&ServerCfg, sizeof(struct sockaddr));
    if (iResult == SOCKET_ERROR)
    {
        printf("Unable to connect to server!\n");
        WSACleanup();
        return 1;
    }
    printf("Connect to server!\r\n");
    printf("You can Send message Now!\r\n\r\n");
    // Send Message to Server
    while(1)
    {

        printf("-----------Sending Message---------\r\n");
        gets(SendBuf);

        iResult = send( ConnectSocket, SendBuf, strlen(SendBuf), 0 );
        if (iResult == SOCKET_ERROR)
        {
            printf("send failed with error: %d\r\n", WSAGetLastError());
        }

        printf("-----------Getting Message---------\r\n");
        iResult = recv( ConnectSocket, RecvBuf, DEFAULT_BUFLEN, 0 );
        if (iResult < 0)
        {
            printf("receive failed with error: %d\r\n", WSAGetLastError());
        }
        else if(iResult > 0)
        {
            puts(RecvBuf);
        }
    }
}
char * CWE78_OS_Command_Injection__char_listen_socket_execl_22_badSource(char * data)
{
    if(CWE78_OS_Command_Injection__char_listen_socket_execl_22_badGlobal)
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            char *replace;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET acceptSocket = 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 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(char) * (100 - 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 (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    return data;
}
Exemple #29
0
int main(int argc, char *argv[])
{

    int sd; // descritor de socket (socket descriptor)
    int rc; // retorno de funзгo (return code)
    int n;  // quantidade de bytes recebidos/enviados
    //int slen; // tamanho da struct sockaddr_in
    socklen_t slen;
    struct sockaddr_in client;   // informacoes do cliente
    struct sockaddr_in server;   // informacoes do servidor
    char msg[MAX_MSG]; // buffer de informacoes

#ifdef WINDOWS
    WSADATA wsaData;

    int wsret = WSAStartup(MAKEWORD(2, 1), &wsaData);

    if (wsret != 0)
    {
        fprintf(stderr,"\nErro: WSAStartup error (%d)\n",wsret);
        exit(-1);
    }
#endif

    sd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sd < 0)
    {
        perror("Socket(): ");
        exit(-2);
    }

    printf("\n-->Socket criado com sucesso");

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port = htons(LOCAL_SERVER_PORT);

    rc = bind(sd, (struct sockaddr *) &server,
              sizeof (server));
    if (rc < 0)
    {
        perror("bind(): ");
        exit(-3);
    }

    printf("\n-->Bind realizado com sucesso");

    printf("\n-->Aguardando dados pela porta UDP %u\n",
           LOCAL_SERVER_PORT);

    slen = sizeof(client);

    while (1)
    {
        memset(msg,0x0,MAX_MSG);

        n = recvfrom(sd, msg, MAX_MSG,0,(struct sockaddr *) &client, &slen);

        if (n < 0)
        {
            printf("\n-->Dados nao recebidos");
            continue;
        }
    printf("Recebido: %s",msg);


        printf("\n-->Dados recebidos de %s Porta UDP %u\n--> %s \n",
               inet_ntoa(client.sin_addr),
               ntohs(client.sin_port), msg);


    for (int indx=0; indx<100 && msg[indx-1] != 0xA; indx++){ msg[indx] = toupper(msg[indx]);}

    n = sendto(sd, msg, MAX_MSG, 0,(struct sockaddr *) &client,sizeof(server));
    printf("-->Enviando Resposta....");

    }


#ifdef WINDOWS
    WSACleanup();
    closesocket(sd);
#endif // WINDOWS
#ifdef LINUX
    close(sd);
#endif
}
Exemple #30
0
static void do_startup( void )
{
#else
static BOOL WINAPI _RawDllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
{
    (void)hinstDLL; /* avoid warnings */
    (void)lpvReserved; /* avoid warnings */

    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
            {
#endif

#if OSL_DEBUG_LEVEL < 2
                /* Suppress file error messages from system like "Floppy A: not inserted" */
                SetErrorMode( SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS );
#endif

                /* initialize global mutex */
                g_Mutex = osl_createMutex();

                /* initialize "current directory" mutex */
                g_CurrentDirectoryMutex = osl_createMutex();

                g_dwTLSTextEncodingIndex = TlsAlloc();
                InitializeCriticalSection( &g_ThreadKeyListCS );

                //We disable floating point exceptions. This is the usual state at program startup
                //but on Windows 98 and ME this is not always the case.
                _control87(_MCW_EM, _MCW_EM);
#ifdef __MINGW32__
        atexit(do_cleanup);
}

void do_cleanup( void )
{
#else
                break;
            }

        case DLL_PROCESS_DETACH:
#endif

            WSACleanup( );

            TlsFree( g_dwTLSTextEncodingIndex );
            DeleteCriticalSection( &g_ThreadKeyListCS );

            osl_destroyMutex( g_Mutex );

            osl_destroyMutex( g_CurrentDirectoryMutex );

#ifndef __MINGW32__

            /*

            On a product build memory management finalization might
            cause a crash without assertion (assertions off) if heap is
            corrupted. But a crash report won't help here because at
            this point all other threads have been terminated and only
            ntdll is on the stack. No chance to find the reason for the
            corrupted heap if so.

            So annoying the user with a crash report is completely useless.

            */

#ifndef DBG_UTIL
            __try
#endif
            {
                /* cleanup locale hashtable */
                rtl_locale_fini();

                /* finalize memory management */
                rtl_memory_fini();
                rtl_cache_fini();
                rtl_arena_fini();
            }
#ifndef DBG_UTIL
            __except( EXCEPTION_EXECUTE_HANDLER )
            {
            }
#endif
            break;
    }

    return TRUE;
#endif
}