Beispiel #1
0
int ProcessBuffer(unsigned char* buffer, const char *section, const CONFENTRY *entrydef, const int entrycount, int* result, unsigned char* config, int maxbufsize)
{
	int done = FALSE;
	int len;

	if (TestBuffer(buffer)==UTF_16)
	{
		//TODO Do wide char with the ANSI 
		wchar_t *result1, *result2;
		result1 = (wchar_t*)buffer;
		if (section!=NULL)
		{
			//TODO Find a solution to the problem of different charactersets
			//result1 = FindSectionW(result1, section);
			if (result2==NULL)
				return NO_SECTION;
			result2 = FindSectionEndW(result1);
			if (result2!=NULL)
				result2[0] = 0;
		}
		while(!done)
		{
			result1 = wcschr(result1, L'*');
			if (result1!=NULL)
			{
				//TODO maybe do more checks

				result1+=1;
				result2 = wcschr(result1, L'=');
				if (result2!=NULL)
				{
					*result2 = 0;
					result2++;
				}
				else
					done = TRUE;

				result1 = ProcessKeyW(entrydef, entrycount, result, result1, result2, config);
				if (result1==NULL)
					done = TRUE;
			}
		}
	}
	else
	{
		char *result1, *result2;
		result1 = (char*)buffer;
		if (section != NULL)
		{
			result1 = FindSectionA(result1, section, NULL);
			if (result2==NULL)
				return NO_SECTION;
			result2 = FindSectionEndA(result1);
			if (result2 != NULL)
				result2[0] = 0;
		}

		/*
			Processes every key - a key starts with a * and ends with a =
			till it reaches the end of the buffer - or there is no data to be processed
			The key should be in ASCII - for highes compatibility
		*/
		while(!done)
		{
			result1 = strchr(result1, L'*');
			if (result1!=NULL)
			{
				//TODO maybe do more checks
				if (result1[-1]=='\n')
				{
					result1+=1;
					result2 = strchr(result1, L'=');
					if (result2!=NULL)
					{
						*result2 = 0;
						result2++;
					}
					else
						done = TRUE;

					result1 = ProcessKeyA(entrydef, entrycount, result, own_strtolower(result1), result2, config);
					if (result1==NULL)
						done = TRUE;
				}
				else
					result1++;
			}
			else
				break;
		}
	}
	return 0;
}
void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_fprintf_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 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
    }
    CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_fprintf_68_badData = data;
    CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_fprintf_68b_badSink();
}
/*
 * The main function implements a loader for applications which use UNO.
 *
 * <p>This code runs on the Windows platform only.</p>
 *
 * <p>The main function detects a UNO installation on the system and adds the
 * program directory of the UNO installation to the PATH environment variable.
 * After that, the application process is loaded and started, whereby the
 * new process inherits the environment of the calling process, including
 * the modified PATH environment variable. The application's executable name
 * must be the same as the name of this executable, prefixed by '_'.</p>
 *
 * <p>A UNO installation can be specified by the user by setting the UNO_PATH
 * environment variable to the program directory of the UNO installation.
 * If no installation is specified by the user, the default installation on
 * the system will be taken. The default installation is read from the
 * default value of the key "Software\LibreOffice\UNO\InstallPath" from the
 * root key HKEY_CURRENT_USER in the Windows Registry. If this key is missing,
 * the key is read from the root key HKEY_LOCAL_MACHINE.</p>
 */
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    LPWSTR lpCmdLine, int nCmdShow )
{
    (void) hInstance; /* unused */
    (void) hPrevInstance; /* unused */
    (void) nCmdShow; /* unused */

    /* get the path of the UNO installation */
    wchar_t* path = getPath();

    if ( path != NULL )
    {
        wchar_t cmd[
            MY_LENGTH(L"\"") + MAX_PATH +
            MY_LENGTH(L"\\unoinfo.exe\" c++")];
            /* hopefully does not overflow */
        cmd[0] = L'"';
        wcscpy(cmd + 1, path);
        if (wcschr(cmd + 1, L'"') != NULL) {
            free(path);
            writeError("Error: bad characters in UNO installation path!\n");
            closeErrorFile();
            return 1;
        }
        size_t pathsize = wcslen(cmd);
        wcscpy(
            cmd + pathsize,
            &L"\\unoinfo.exe\" c++"[
                pathsize == 1 || cmd[pathsize - 1] != L'\\' ? 0 : 1]);
        SECURITY_ATTRIBUTES sec;
        sec.nLength = sizeof (SECURITY_ATTRIBUTES);
        sec.lpSecurityDescriptor = NULL;
        sec.bInheritHandle = TRUE;
        HANDLE stdoutRead;
        HANDLE stdoutWrite;
        HANDLE temp;
        if (CreatePipe(&temp, &stdoutWrite, &sec, 0) == 0 ||
            DuplicateHandle(
                GetCurrentProcess(), temp, GetCurrentProcess(), &stdoutRead, 0,
                FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS) == 0)
        {
            free(path);
            writeError("Error: CreatePipe/DuplicateHandle failed!\n");
            closeErrorFile();
            return 1;
        }
        STARTUPINFOW startinfo;
        PROCESS_INFORMATION procinfo;
        memset(&startinfo, 0, sizeof(startinfo));
        startinfo.cb = sizeof(startinfo);
        startinfo.lpDesktop = L"";
        startinfo.dwFlags = STARTF_USESTDHANDLES;
        startinfo.hStdOutput = stdoutWrite;
        BOOL ret = CreateProcessW(
            NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &startinfo, &procinfo);
        if (ret != FALSE) {
            // Release result of GetPath()
            free(path);

            char * buf = NULL;
            char * tmp;
            DWORD n = 1000;
            DWORD k = 0;
            DWORD exitcode;
            CloseHandle(stdoutWrite);
            CloseHandle(procinfo.hThread);
            for (;;) {
                DWORD m;
                tmp = realloc(buf, n);
                if (tmp == NULL) {
                    free(buf);
                    writeError(
                        "Error: out of memory reading unoinfo output!\n");
                    closeErrorFile();
                    return 1;
                }
                buf = tmp;
                if (!ReadFile(stdoutRead, buf + k, n - k, &m, NULL))
                {
                    DWORD err = GetLastError();
                    if (err == ERROR_HANDLE_EOF || err == ERROR_BROKEN_PIPE) {
                        break;
                    }
                    writeError("Error: cannot read unoinfo output!\n");
                    closeErrorFile();
                    return 1;
                }
                if (m == 0) {
                    break;
                }
                k += m;
                if (k >= n) {
                    if (n >= MAXDWORD / 2) {
                        writeError(
                            "Error: out of memory reading unoinfo output!\n");
                        closeErrorFile();
                        return 1;
                    }
                    n *= 2;
                }
            }
            if ((k & 1) == 1) {
                writeError("Error: bad unoinfo output!\n");
                closeErrorFile();
                return 1;
            }
            CloseHandle(stdoutRead);
            if (!GetExitCodeProcess(procinfo.hProcess, &exitcode) ||
                exitcode != 0)
            {
                writeError("Error: executing unoinfo failed!\n");
                closeErrorFile();
                return 1;
            }
            path = (wchar_t*)realloc(buf, k + sizeof(wchar_t));
            if (path == NULL)
            {
                free(buf);
                writeError(
                    "Error: out of memory zero-terminating unoinfo output!\n");
                closeErrorFile();
                return 1;
            }
            path[k / 2] = L'\0';
        } else {
            if (GetLastError() != ERROR_FILE_NOT_FOUND) {
                free(path);
                writeError("Error: calling unoinfo failed!\n");
                closeErrorFile();
                return 1;
            }
            CloseHandle(stdoutRead);
            CloseHandle(stdoutWrite);
        }

        /* get the value of the PATH environment variable */
        const wchar_t* ENVVARNAME = L"PATH";
        const wchar_t* PATHSEPARATOR = L";";
        wchar_t* value = _wgetenv( ENVVARNAME );

        /*
         * add the UNO installation path to the PATH environment variable;
         * note that this only affects the environment variable of the current
         * process, the command processor's environment is not changed
         */
        size_t size = wcslen( ENVVARNAME ) + wcslen( L"=" ) + wcslen( path ) + 1;
        if ( value != NULL )
            size += wcslen( PATHSEPARATOR ) + wcslen( value );
        wchar_t* envstr = (wchar_t*) malloc( size*sizeof(wchar_t) );
        wcscpy( envstr, ENVVARNAME );
        wcscat( envstr, L"=" );
        wcscat( envstr, path );
        if ( value != NULL )
        {
            wcscat( envstr, PATHSEPARATOR );
            wcscat( envstr, value );
        }
        _wputenv( envstr );
        free( envstr );
        free( path );
    }
    else
    {
        writeError( "Warning: no UNO installation found!\n" );
    }

    /* create the command line for the application process */
    wchar_t* cmdline = createCommandLine( lpCmdLine );
    if ( cmdline == NULL )
    {
        writeError( "Error: cannot create command line!\n" );
        closeErrorFile();
        return 1;
    }

    /* create the application process */
    STARTUPINFOW startup_info;
    PROCESS_INFORMATION process_info;
    memset( &startup_info, 0, sizeof(startup_info) );
    startup_info.cb = sizeof(startup_info);
    BOOL bCreate = CreateProcessW( NULL, cmdline, NULL,  NULL, FALSE, 0, NULL, NULL,
        &startup_info, &process_info );
    free( cmdline );
    if ( !bCreate )
    {
        writeError( "Error: cannot create process!\n" );
        closeErrorFile();
        return 1;
    }

    /* close the error file */
    closeErrorFile();

    return 0;
}
void bad()
{
    wchar_t * data;
    wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
    data = dataBuffer;
    if(GLOBAL_CONST_FIVE==5)
    {
        {
#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
        }
    }
    {
        ifstream inputFile;
        /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
        inputFile.open((char *)data);
        inputFile.close();
    }
}
Beispiel #5
0
/******************************************************************************
 *                                                                            *
 * Function: zbx_win_getversion                                               *
 *                                                                            *
 * Purpose: get Windows version information                                   *
 *                                                                            *
 ******************************************************************************/
const OSVERSIONINFOEX		*zbx_win_getversion()
{
#	define ZBX_REGKEY_VERSION		"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
#	define ZBX_REGVALUE_CURRENTVERSION	"CurrentVersion"
#	define ZBX_REGVALUE_CURRENTBUILDNUMBER	"CurrentBuildNumber"
#	define ZBX_REGVALUE_CSDVERSION		"CSDVersion"

#	define ZBX_REGKEY_PRODUCT		"System\\CurrentControlSet\\Control\\ProductOptions"
#	define ZBX_REGVALUE_PRODUCTTYPE		"ProductType"

	static OSVERSIONINFOEX	vi = {sizeof(OSVERSIONINFOEX)};

	OSVERSIONINFOEX		*pvi = NULL;
	HKEY			h_key_registry = NULL;
	wchar_t			*key_value = NULL, *ptr;

	if (0 != vi.dwMajorVersion)
		return &vi;

	if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(ZBX_REGKEY_VERSION), 0, KEY_READ, &h_key_registry))
	{
		zabbix_log(LOG_LEVEL_DEBUG, "failed to open registry key '%s'", ZBX_REGKEY_VERSION);
		goto out;
	}

	if (NULL == (key_value = read_registry_value(h_key_registry, TEXT(ZBX_REGVALUE_CURRENTVERSION))))
	{
		zabbix_log(LOG_LEVEL_DEBUG, "failed to read registry value '%s'", ZBX_REGVALUE_CURRENTVERSION);
		goto out;
	}

	if (NULL != (ptr = wcschr(key_value, TEXT('.'))))
	{
		*ptr++ = L'\0';
		vi.dwMinorVersion = _wtoi(ptr);
	}

	vi.dwMajorVersion = _wtoi(key_value);

	zbx_free(key_value);

	if (6 > vi.dwMajorVersion || 2 > vi.dwMinorVersion)
	{
		GetVersionEx((OSVERSIONINFO *)&vi);
	}
	else
	{
		if (NULL != (key_value = read_registry_value(h_key_registry, TEXT(ZBX_REGVALUE_CSDVERSION))))
		{
			wcscpy_s(vi.szCSDVersion, sizeof(vi.szCSDVersion) / sizeof(*vi.szCSDVersion), key_value);

			zbx_free(key_value);
		}

		if (NULL == (key_value = read_registry_value(h_key_registry, TEXT(ZBX_REGVALUE_CURRENTBUILDNUMBER))))
		{
			zabbix_log(LOG_LEVEL_DEBUG, "failed to read registry value '%s'",
					ZBX_REGVALUE_CURRENTBUILDNUMBER);
			goto out;
		}

		vi.dwBuildNumber = _wtoi(key_value);
		zbx_free(key_value);

		RegCloseKey(h_key_registry);
		h_key_registry = NULL;

		if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(ZBX_REGKEY_PRODUCT), 0, KEY_READ,
				&h_key_registry))
		{
			zabbix_log(LOG_LEVEL_DEBUG, "failed to open registry key '%s'", ZBX_REGKEY_PRODUCT);
			goto out;
		}

		if (NULL == (key_value = read_registry_value(h_key_registry, TEXT(ZBX_REGVALUE_PRODUCTTYPE))))
		{
			zabbix_log(LOG_LEVEL_DEBUG, "failed to read registry value '%s'", ZBX_REGVALUE_PRODUCTTYPE);
			goto out;
		}

		if (0 == wcscmp(key_value, L"WinNT"))
			vi.wProductType = 1;
		else if (0 == wcscmp(key_value, L"LenmanNT"))
			vi.wProductType = 2;
		else if (0 == wcscmp(key_value, L"ServerNT"))
			vi.wProductType = 3;

		zbx_free(key_value);

		vi.dwPlatformId = VER_PLATFORM_WIN32_NT;
	}

	pvi = &vi;
out:
	if (NULL != h_key_registry)
		RegCloseKey(h_key_registry);

	return pvi;
}
Beispiel #6
0
BOOLEAN
vfatIsLongIllegal(WCHAR c)
{
  return wcschr(long_illegals, c) ? TRUE : FALSE;
}
Beispiel #7
0
int DriveMng::SetDriveID(const WCHAR *_root)
{
	if (!_root || !_root[0]) return -1;

	WCHAR	root[MAX_PATH];
	int		idx = -1;
	::CharUpperW(wcscpy(root, _root));

	if (root[1] == ':') {
		idx = DrvLetterToIndex(root[0]);
		if (idx < 0 || idx >= MAX_LOCAL_DRIVES) return -1;
	} else {
		// ネットワークドライブの場合、\\server\volume\ もしくは \\server\ (設定に依存)
		// を大文字にした文字列のハッシュ値を識別値(drvId[].data)とする
		ModifyNetRoot(root);
		uint64	hash_id = MakeHash64(root, (int)wcslen(root));
		if ((idx = shareInfo->RegisterNetDrive(hash_id)) < 0) return -1;
		if (drvID[idx].len) return idx; // already registerd

		RegisterDriveID(idx, &hash_id, sizeof(hash_id));
		return	idx;
	}

	if (drvID[idx].len) return idx; // already registerd

	if (::GetDriveTypeW(root) == DRIVE_REMOTE) {
		BYTE				buf[2048];
		DWORD				size = sizeof(buf);
		REMOTE_NAME_INFOW	*pni = (REMOTE_NAME_INFOW *)buf;

		if (::WNetGetUniversalNameW(root, REMOTE_NAME_INFO_LEVEL, pni, &size) != NO_ERROR) {
			//Debug("WNetGetUniversalNameW err=%d\n", GetLastError());
			return -1;
		}
		wcscpy(root, pni->lpUniversalName);
		::CharUpperW(root);
		ModifyNetRoot(root);
		uint64	hash_id = MakeHash64(root, (int)wcslen(root));
		RegisterDriveID(idx, &hash_id, sizeof(hash_id));

		int	net_idx = shareInfo->RegisterNetDrive(hash_id);
		if (net_idx >= 0) RegisterDriveID(net_idx, &hash_id, sizeof(hash_id));
		return	idx;
	}

	WCHAR	vol_name[MAX_PATH];
	if (::GetVolumeNameForVolumeMountPointW(root, vol_name, MAX_PATH)) {
		vol_name[wcslen(vol_name) -1] = 0;
		HANDLE	hFile = ::CreateFileW(vol_name, FILE_READ_ATTRIBUTES,
								FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
		if (hFile != INVALID_HANDLE_VALUE) {
			VOLUME_DISK_EXTENTS vde = {};
			DWORD	size;
			DWORD	val = 0;
			if (::DeviceIoControl(hFile, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0,
					&vde, sizeof(vde), &size, 0) || GetLastError() == ERROR_MORE_DATA) {
				if (vde.NumberOfDiskExtents >= 1) {
					// SetDriveMapが ID: 1~Nを利用するため、オフセット0x1000を加算
					val = vde.Extents[0].DiskNumber | 0x1000;
					//Debug("disk id = %d\n", vde.Extents[0].DiskNumber);
				}
			}
			::CloseHandle(hFile);
			if (val) {
				RegisterDriveID(idx, &val, sizeof(val));
				return idx;
			}
		}
	}
	TRegistry	reg(HKEY_LOCAL_MACHINE);
	if (reg.OpenKey(MOUNTED_DEVICES)) {
		char	reg_path[MAX_PATH * 2];
		BYTE	buf[1024];
		int		size = sizeof(buf);
		WCHAR	*wbuf = (WCHAR *)buf, *wp;
		DWORD	val = 0;

		::sprintf(reg_path, FMT_DOSDEVICES, root[0]);
		if (reg.GetByte(reg_path, buf, &size)) {
			if (wcsncmp(wbuf, L"\\??\\", 4) == 0 && (wp = wcschr(wbuf, '#'))
				&& (wp = wcschr(wp+1, '#')) && (wp = wcschr(wp, '&'))) {
				val = wcstoul(wp+1, 0, 16);
			}
			else if (wcsncmp(wbuf, L"_??_", 4) == 0 && (wp = wcschr(wbuf, '{'))) {
				val = wcstoul(wp+1, 0, 16);
			}
			else if (wcsncmp(wbuf, L"DMIO:ID:", 8) == 0) {
				val = *(DWORD *)(wbuf + 8);
			}
			else {
				val = *(DWORD *)buf;
			}
			if (val <= 30) val |= 0x88000000;
			RegisterDriveID(idx, &val, sizeof(val));
			return	idx;
		}
	}
	RegisterDriveID(idx, "", 1);
	return	idx;
}
Beispiel #8
0
wchar_t* GetShortFileNameEx(LPCWSTR asLong, BOOL abFavorLength/*=TRUE*/)
{
	if (!asLong)
		return NULL;

	int nSrcLen = lstrlenW(asLong); //-V303
	wchar_t* pszLong = lstrdup(asLong);

	int nMaxLen = nSrcLen + MAX_PATH; // "короткое" имя может более MAX_PATH
	wchar_t* pszShort = (wchar_t*)calloc(nMaxLen, sizeof(wchar_t)); //-V106

	wchar_t* pszResult = NULL;
	wchar_t* pszSrc = pszLong;
	//wchar_t* pszDst = pszShort;
	wchar_t* pszSlash;
	wchar_t* szName = (wchar_t*)malloc((MAX_PATH+1)*sizeof(wchar_t));
	bool     lbNetwork = false;
	int      nLen, nCurLen = 0;

	// Если путь сетевой (или UNC?) пропустить префиксы/серверы
	if (pszSrc[0] == L'\\' && pszSrc[1] == '\\')
	{
		// пропуск первых двух слешей
		pszSrc += 2;
		// формат "диска" не поддерживаем \\.\Drive\...
		if (pszSrc[0] == L'.' && pszSrc[1] == L'\\')
			goto wrap;
		// UNC
		if (pszSrc[0] == L'?' && pszSrc[1] == L'\\')
		{
			pszSrc += 2;
			if (pszSrc[0] == L'U' && pszSrc[1] == L'N' && pszSrc[2] == L'C' && pszSrc[3] == L'\\')
			{
				// UNC\Server\share\...
				pszSrc += 4; //-V112
				lbNetwork = true;
			}
			// иначе - ожидается диск
		}
		// Network (\\Server\\Share\...)
		else
		{
			lbNetwork = true;
		}
	}

	if (pszSrc[0] == 0)
		goto wrap;

	if (lbNetwork)
	{
		pszSlash = wcschr(pszSrc, L'\\');
		if (!pszSlash)
			goto wrap;
		pszSlash = wcschr(pszSlash+1, L'\\');
		if (!pszSlash)
			goto wrap;
		pszShort[0] = L'\\'; pszShort[1] = L'\\'; pszShort[2] = 0;
		_wcscatn_c(pszShort, nMaxLen, pszSrc, (pszSlash-pszSrc+1)); // память выделяется calloc! //-V303 //-V104
	}
	else
	{
		// <Drive>:\path...
		if (pszSrc[1] != L':')
			goto wrap;
		if (pszSrc[2] != L'\\' && pszSrc[2] != 0)
			goto wrap;
		pszSlash = pszSrc + 2;
		_wcscatn_c(pszShort, nMaxLen, pszSrc, (pszSlash-pszSrc+1)); // память выделяется calloc!
	}

	nCurLen = lstrlenW(pszShort);

	while (pszSlash && (*pszSlash == L'\\'))
	{
		pszSrc = pszSlash;
		pszSlash = wcschr(pszSrc+1, L'\\');
		if (pszSlash)
			*pszSlash = 0;

		if (!GetShortFileName(pszLong, MAX_PATH+1, szName, abFavorLength))
			goto wrap;
		nLen = lstrlenW(szName);
		if ((nLen + nCurLen) >= nMaxLen)
			goto wrap;
		//pszShort[nCurLen++] = L'\\'; pszShort[nCurLen] = 0;
		_wcscpyn_c(pszShort+nCurLen, nMaxLen-nCurLen, szName, nLen);
		nCurLen += nLen;

		if (pszSlash)
		{
			*pszSlash = L'\\';
			pszShort[nCurLen++] = L'\\'; // память выделяется calloc!
		}
	}

	nLen = lstrlenW(pszShort);

	if ((nLen > 0) && (pszShort[nLen-1] == L'\\'))
		pszShort[--nLen] = 0;

	if (nLen <= MAX_PATH)
	{
		pszResult = pszShort;
		pszShort = NULL;
		goto wrap;
	}

wrap:
	if (szName)
		free(szName);
	if (pszShort)
		free(pszShort);
	if (pszLong)
		free(pszLong);
	return pszResult;
}
Beispiel #9
0
/* Compute argv[0] which will be prepended to sys.argv */
PyObject*
_PyPathConfig_ComputeArgv0(int argc, wchar_t **argv)
{
    wchar_t *argv0;
    wchar_t *p = NULL;
    Py_ssize_t n = 0;
    int have_script_arg = 0;
    int have_module_arg = 0;
#ifdef HAVE_READLINK
    wchar_t link[MAXPATHLEN+1];
    wchar_t argv0copy[2*MAXPATHLEN+1];
    int nr = 0;
#endif
#if defined(HAVE_REALPATH)
    wchar_t fullpath[MAXPATHLEN];
#elif defined(MS_WINDOWS)
    wchar_t fullpath[MAX_PATH];
#endif

    argv0 = argv[0];
    if (argc > 0 && argv0 != NULL) {
        have_module_arg = (wcscmp(argv0, L"-m") == 0);
        have_script_arg = !have_module_arg && (wcscmp(argv0, L"-c") != 0);
    }

    if (have_module_arg) {
        #if defined(HAVE_REALPATH) || defined(MS_WINDOWS)
            _Py_wgetcwd(fullpath, Py_ARRAY_LENGTH(fullpath));
            argv0 = fullpath;
            n = wcslen(argv0);
        #else
            argv0 = L".";
            n = 1;
        #endif
    }

#ifdef HAVE_READLINK
    if (have_script_arg)
        nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
    if (nr > 0) {
        /* It's a symlink */
        link[nr] = '\0';
        if (link[0] == SEP)
            argv0 = link; /* Link to absolute path */
        else if (wcschr(link, SEP) == NULL)
            ; /* Link without path */
        else {
            /* Must join(dirname(argv0), link) */
            wchar_t *q = wcsrchr(argv0, SEP);
            if (q == NULL)
                argv0 = link; /* argv0 without path */
            else {
                /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
                wcsncpy(argv0copy, argv0, MAXPATHLEN);
                q = wcsrchr(argv0copy, SEP);
                wcsncpy(q+1, link, MAXPATHLEN);
                q[MAXPATHLEN + 1] = L'\0';
                argv0 = argv0copy;
            }
        }
    }
#endif /* HAVE_READLINK */

#if SEP == '\\'
    /* Special case for Microsoft filename syntax */
    if (have_script_arg) {
        wchar_t *q;
#if defined(MS_WINDOWS)
        /* Replace the first element in argv with the full path. */
        wchar_t *ptemp;
        if (GetFullPathNameW(argv0,
                           Py_ARRAY_LENGTH(fullpath),
                           fullpath,
                           &ptemp)) {
            argv0 = fullpath;
        }
#endif
        p = wcsrchr(argv0, SEP);
        /* Test for alternate separator */
        q = wcsrchr(p ? p : argv0, '/');
        if (q != NULL)
            p = q;
        if (p != NULL) {
            n = p + 1 - argv0;
            if (n > 1 && p[-1] != ':')
                n--; /* Drop trailing separator */
        }
    }
#else /* All other filename syntaxes */
    if (have_script_arg) {
#if defined(HAVE_REALPATH)
        if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
            argv0 = fullpath;
        }
#endif
        p = wcsrchr(argv0, SEP);
    }
    if (p != NULL) {
        n = p + 1 - argv0;
#if SEP == '/' /* Special case for Unix filename syntax */
        if (n > 1)
            n--; /* Drop trailing separator */
#endif /* Unix */
    }
#endif /* All others */

    return PyUnicode_FromWideChar(argv0, n);
}
Beispiel #10
0
bool CMatch::MatchAny(CRConDataGuard& data, int nFromLine)
{
	bool bFound = false;

	// В именах файлов недопустимы: "/\:|*?<>~t~r~n а для простоты - учитываем и рамки
	const wchar_t* pszBreak = gszBreak;
	const wchar_t* pszSpacing = gszSpacing; // Пробел, таб, остальные для режима "Show white spaces" в редакторе фара
	const wchar_t* pszSeparat = L" \t:(";
	const wchar_t* pszTermint = L":)],";
	const wchar_t* pszDigits  = L"0123456789";
	const wchar_t* pszSlashes = L"/\\";
	const wchar_t* pszUrl = L":/\\:%#ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz;?@&=+$,-_.!~*'()0123456789";
	const wchar_t* pszUrlTrimRight = L".,;";
	const wchar_t* pszProtocol = L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+-.";
	const wchar_t* pszEMail = L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+-.";
	const wchar_t* pszUrlDelim = L"\\\"<>{}[]^`'\r\n" MATCH_SPACINGS;
	const wchar_t* pszUrlFileDelim = L"\"<>^\r\n" MATCH_SPACINGS;
	const wchar_t* pszEndBrackets = L">])}";
	const wchar_t* pszPuctuators = L".,:;…!?";
	int nColons = 0;
	bool bUrlMode = false, bMaybeMail = false;
	SHORT MailX = -1;
	bool bDigits = false, bLineNumberFound = false, bWasSeparator = false;
	bool bWasPunctuator = false;
	bool bNakedFile = false;
	int nNakedFileLen = 0;
	enum {
		ef_NotFound = 0,
		ef_DotFound = 1,
		ef_ExtFound = 2,
	} iExtFound = ef_NotFound;
	int iBracket = 0;
	int iSpaces = 0;
	int iQuotStart = -1;
	const wchar_t* pszTest;

	mn_MatchLeft = mn_MatchRight = mn_SrcFrom;

	// Курсор над знаком препинания и за ним пробел? Допускать только ':' - это для строк/колонок с ошибками
	if ((wcschr(L";,.", m_SrcLine.ms_Val[mn_SrcFrom])) && (((mn_SrcFrom+1) >= mn_SrcLength) || wcschr(pszSpacing, m_SrcLine.ms_Val[mn_SrcFrom+1])))
	{
		MatchTestAlert();
		goto wrap;
	}

	// Курсор над протоколом? (http, etc)
	if (!CheckValidUrl(mn_MatchLeft, mn_MatchRight, bUrlMode, pszUrlDelim, pszUrl, pszProtocol, m_SrcLine.ms_Val, mn_SrcLength))
	{
		MatchTestAlert();
		goto wrap;
	}

	if (!bUrlMode)
	{
		// Not URL mode, restart searching
		mn_MatchLeft = mn_MatchRight = mn_SrcFrom;

		// Курсор над комментарием?
		// Попробуем найти начало имени файла
		if (!FindRangeStart(mn_MatchLeft, mn_MatchRight, bUrlMode, pszBreak, pszUrlDelim, pszSpacing, pszUrl, pszProtocol, m_SrcLine.ms_Val, mn_SrcLength))
		{
			MatchTestAlert();
			goto wrap;
		}

		// Try again with URL?
		if (mn_MatchLeft < mn_SrcFrom)
		{
			if (!CheckValidUrl(mn_MatchLeft, mn_MatchRight, bUrlMode, pszUrlDelim, pszUrl, pszProtocol, m_SrcLine.ms_Val, mn_SrcLength))
			{
				MatchTestAlert();
				goto wrap;
			}
		}
	}

	// Starts with quotation?
	if ((pszTest = wcschr(gszQuotStart, m_SrcLine.ms_Val[mn_MatchLeft])) != NULL)
	{
		iQuotStart = (int)(pszTest - gszQuotStart);
	}

	// Чтобы корректно флаги обработались (типа наличие расширения и т.п.)
	mn_MatchRight = mn_MatchLeft;

	// Теперь - найти конец.
	// Считаем, что для файлов конец это двоеточие, после которого идет описание ошибки
	// Для протоколов (http/...) - первый недопустимый символ

	TODO("Можно бы и просто открытие файлов прикрутить, без требования 'строки с ошибкой'");

	// -- VC
	// 1>c:\sources\conemu\realconsole.cpp(8104) : error C2065: 'qqq' : undeclared identifier
	// DefResolve.cpp(18) : error C2065: 'sdgagasdhsahd' : undeclared identifier
	// DefResolve.cpp(18): warning: note xxx
	// -- GCC
	// ConEmuC.cpp:49: error: 'qqq' does not name a type
	// 1.c:3: some message
	// file.cpp:29:29: error
	// CPP Check
	// [common\PipeServer.h:1145]: (style) C-style pointer casting
	// Delphi
	// c:\sources\FarLib\FarCtrl.pas(1002) Error: Undeclared identifier: 'PCTL_GETPLUGININFO'
	// FPC
	// FarCtrl.pas(1002,49) Error: Identifier not found "PCTL_GETPLUGININFO"
	// PowerShell
	// Script.ps1:35 знак:23
	// -- Possible?
	// abc.py (3): some message
	// ASM - подсвечивать нужно "test.asasm(1,1)"
	// [email protected](1239): test.asasm(1,1):
	// Issue 1594
	// /src/class.c:123:m_func(...)
	// /src/class.c:123: m_func(...)

	// -- URL's
	// file://c:\temp\qqq.html
	// http://www.farmanager.com
	// $ http://www.KKK.ru - левее слеша - не срабатывает
	// C:\ConEmu>http://www.KKK.ru - ...
	// -- False detects
	// 29.11.2011 18:31:47
	// C:\VC\unicode_far\macro.cpp  1251 Ln 5951/8291 Col 51 Ch 39 0043h 13:54
	// InfoW1900->SettingsControl(sc.Handle, SCTL_FREE, 0, 0);

	// Нас не интересуют строки типа "11.05.2010 10:20:35"
	// В имени файла должна быть хотя бы одна буква (расширение), причем английская
	// Поехали
	if (bUrlMode)
	{
		LPCWSTR pszDelim = (wcsncmp(m_SrcLine.ms_Val+mn_MatchLeft, L"file://", 7) == 0) ? pszUrlFileDelim : pszUrlDelim;
		int nextLine = 1;
		while (true)
		{
			if ((mn_MatchRight+1) >= mn_SrcLength && data.isValid())
			{
				if (!GetNextLine(data, nextLine+nFromLine))
					break;
				++nextLine;
			}

			if (((mn_MatchRight+1) >= mn_SrcLength) || wcschr(pszDelim, m_SrcLine.ms_Val[mn_MatchRight+1]))
			{
				break;
			}

			mn_MatchRight++;
		}
		DEBUGTEST(int i4break = 0);
	}
	else while ((mn_MatchRight+1) < mn_SrcLength)
	{
		if ((m_SrcLine.ms_Val[mn_MatchRight] == L'/') && ((mn_MatchRight+1) < mn_SrcLength) && (m_SrcLine.ms_Val[mn_MatchRight+1] == L'/')
			&& !((mn_MatchRight > 1) && (m_SrcLine.ms_Val[mn_MatchRight] == L':'))) // и НЕ URL адрес
		{
			MatchTestAlert();
			goto wrap; // Не оно (комментарий в строке)
		}

		if (bWasSeparator // " \t:("
			&& (isDigit(m_SrcLine.ms_Val[mn_MatchRight])
				|| (bDigits && (m_SrcLine.ms_Val[mn_MatchRight] == L',')))) // FarCtrl.pas(1002,49) Error:
		{
			if (!bDigits && (mn_MatchLeft < mn_MatchRight) /*&& (m_SrcLine.ms_Val[mn_MatchRight-1] == L':')*/)
			{
				bDigits = true;
				// Если перед разделителем был реальный файл - сразу выставим флажок "номер строки найден"
				if (IsValidFile(m_SrcLine.ms_Val+mn_MatchLeft, mn_MatchRight - mn_MatchLeft - 1, pszBreak, pszSpacing, nNakedFileLen))
				{
					bLineNumberFound = true;
				}
				// Skip leading quotation mark?
				else if ((iQuotStart >= 0)
					&& IsValidFile(m_SrcLine.ms_Val+mn_MatchLeft+1, mn_MatchRight - mn_MatchLeft - 2, pszBreak, pszSpacing, nNakedFileLen))
				{
					mn_MatchLeft++;
					bLineNumberFound = true;
				}
			}
		}
		else if (bWasSeparator && bLineNumberFound
			&& wcschr(L":)] \t", m_SrcLine.ms_Val[mn_MatchRight]))
		{
			//// gcc такие строки тоже может выкинуть
			//// file.cpp:29:29: error
			//mn_MatchRight--;
			break;
		}
		else
		{
			if (iExtFound != ef_ExtFound)
			{
				if (iExtFound == ef_NotFound)
				{
					if (m_SrcLine.ms_Val[mn_MatchRight] == L'.')
						iExtFound = ef_ExtFound;
				}
				else
				{
					// Не особо заморачиваясь с точками и прочим. Просто небольшая страховка от ложных срабатываний...
					if ((m_SrcLine.ms_Val[mn_MatchRight] >= L'a' && m_SrcLine.ms_Val[mn_MatchRight] <= L'z') || (m_SrcLine.ms_Val[mn_MatchRight] >= L'A' && m_SrcLine.ms_Val[mn_MatchRight] <= L'Z'))
					{
						iExtFound = ef_ExtFound;
						iBracket = 0;
					}
				}
			}

			if (iExtFound == 2)
			{
				if (m_SrcLine.ms_Val[mn_MatchRight] == L'.')
				{
					iExtFound = ef_DotFound;
					iBracket = 0;
				}
				else if (wcschr(pszSlashes, m_SrcLine.ms_Val[mn_MatchRight]) != NULL)
				{
					// Был слеш, значит расширения - еще нет
					iExtFound = ef_NotFound;
					iBracket = 0;
					bWasSeparator = false;
				}
				else if (wcschr(pszSpacing, m_SrcLine.ms_Val[mn_MatchRight]) && wcschr(pszSpacing, m_SrcLine.ms_Val[mn_MatchRight-1]))
				{
					// Слишком много пробелов
					iExtFound = ef_NotFound;
					iBracket = 0;
					bWasSeparator = false;
				}
				// Stop on naked file if we found space after it
				else if (!bLineNumberFound && !bMaybeMail && wcschr(pszSpacing, m_SrcLine.ms_Val[mn_MatchRight])
					// But don't stop if there is a line number: "abc.py (3): ..."
					&& !(((mn_MatchRight+3) < mn_SrcLength)
							&& (m_SrcLine.ms_Val[mn_MatchRight+1] == L'(')
							&& isDigit(m_SrcLine.ms_Val[mn_MatchRight+2]))
					// Is this a file without digits (line/col)?
					&& IsValidFile(m_SrcLine.ms_Val+mn_MatchLeft, mn_MatchRight - mn_MatchLeft + 1, pszBreak, pszSpacing, nNakedFileLen))
				{
					// File without digits, just for opening in the editor
					bNakedFile = true;
					break;
				}
				// Stop if after colon there is another letter but a digit
				else if (!bLineNumberFound && !bMaybeMail
					&& (m_SrcLine.ms_Val[mn_MatchRight] == L':')
							&& (((mn_MatchRight+1) >= mn_SrcLength)
								|| !isDigit(m_SrcLine.ms_Val[mn_MatchRight+1]))
					// Is this a file without digits (line/col)?
					&& IsValidFile(m_SrcLine.ms_Val+mn_MatchLeft, mn_MatchRight - mn_MatchLeft, pszBreak, pszSpacing, nNakedFileLen))
				{
					// File without digits, just for opening in the editor
					bNakedFile = true;
					mn_MatchRight--;
					break;
				}
				else
				{
					bWasSeparator = (wcschr(pszSeparat, m_SrcLine.ms_Val[mn_MatchRight]) != NULL);
				}
			}

			if ((iQuotStart >= 0) && (m_SrcLine.ms_Val[mn_MatchRight] == gszQuotEnd[iQuotStart]))
			{
				bNakedFile = IsValidFile(m_SrcLine.ms_Val+mn_MatchLeft+1, mn_MatchRight - mn_MatchLeft - 1, pszBreak, pszSpacing, nNakedFileLen);
				if (bNakedFile || bMaybeMail)
				{
					mn_MatchLeft++;
					mn_MatchRight--;
					break;
				}
			}

			if (bWasPunctuator && !bLineNumberFound)
			{
				if (bMaybeMail)
				{
					// Если после мейла нашли что-то кроме точки
					if ((m_SrcLine.ms_Val[mn_MatchRight-1] != L'.')
						// или после точки - пробельный символ
						|| wcschr(pszSpacing, m_SrcLine.ms_Val[mn_MatchRight]))
					{
						break;
					}
				}
				else if (wcschr(pszSpacing, m_SrcLine.ms_Val[mn_MatchRight]))
				{
					bNakedFile = IsValidFile(m_SrcLine.ms_Val+mn_MatchLeft, mn_MatchRight - mn_MatchLeft - 1, pszBreak, pszSpacing, nNakedFileLen);
					if (bNakedFile)
					{
						mn_MatchRight--;
						break;
					}
				}
			}

			bWasPunctuator = (wcschr(pszPuctuators, m_SrcLine.ms_Val[mn_MatchRight]) != NULL);

			// Рассчитано на закрывающие : или ) или ] или ,
			_ASSERTE(pszTermint[0]==L':' && pszTermint[1]==L')' && pszTermint[2]==L']' && pszTermint[3]==L',' && pszTermint[4]==0);
			// Script.ps1:35 знак:23
			if (bDigits && IsFileLineTerminator(m_SrcLine.ms_Val+mn_MatchRight, pszTermint))
			{
				// Validation
				if (((m_SrcLine.ms_Val[mn_MatchRight] == L':' || m_SrcLine.ms_Val[mn_MatchRight] == L' ')
						// Issue 1594: /src/class.c:123:m_func(...)
						/* && (wcschr(pszSpacing, m_SrcLine.ms_Val[mn_MatchRight+1])
							|| wcschr(pszDigits, m_SrcLine.ms_Val[mn_MatchRight+1]))*/)
				// Если номер строки обрамлен скобками - скобки должны быть сбалансированы
				|| ((m_SrcLine.ms_Val[mn_MatchRight] == L')') && (iBracket == 1)
						&& ((m_SrcLine.ms_Val[mn_MatchRight+1] == L':')
							|| wcschr(pszSpacing, m_SrcLine.ms_Val[mn_MatchRight+1])
							|| wcschr(pszDigits, m_SrcLine.ms_Val[mn_MatchRight+1])))
				// [file.cpp:1234]: (cppcheck)
				|| ((m_SrcLine.ms_Val[mn_MatchRight] == L']') && (m_SrcLine.ms_Val[mn_MatchRight+1] == L':'))
					)
				{
					//_ASSERTE(bLineNumberFound==false);
					//bLineNumberFound = true;
					break; // found?
				}
			}

			// Issue 1758: Support file/line format for php: C:\..\test.php:28
			if (bDigits && !wcschr(pszSpacing, m_SrcLine.ms_Val[mn_MatchRight]))
			{
				bDigits = false;
			}

			switch (m_SrcLine.ms_Val[mn_MatchRight])
			{
			// Пока регулярок нет...
			case L'(': iBracket++; break;
			case L')': iBracket--; break;
			case L'/': case L'\\': iBracket = 0; break;
			case L'@':
				if (MailX != -1)
				{
					bMaybeMail = false;
				}
				else if (((mn_MatchRight > 0) && wcschr(pszEMail, m_SrcLine.ms_Val[mn_MatchRight-1]))
					&& (((mn_MatchRight+1) < mn_SrcLength) && wcschr(pszEMail, m_SrcLine.ms_Val[mn_MatchRight+1])))
				{
					bMaybeMail = true;
					MailX = mn_MatchRight;
				}
				break;
			}

			if (m_SrcLine.ms_Val[mn_MatchRight] == L':')
				nColons++;
			else if (m_SrcLine.ms_Val[mn_MatchRight] == L'\\' || m_SrcLine.ms_Val[mn_MatchRight] == L'/')
				nColons = 0;
		}

		if (nColons >= 2)
			break;

		mn_MatchRight++;
		if (wcschr(pszBreak, m_SrcLine.ms_Val[mn_MatchRight]))
		{
			if (bMaybeMail)
				break;
			if ((bLineNumberFound) || !IsValidFile(m_SrcLine.ms_Val+mn_MatchLeft, mn_MatchRight - mn_MatchLeft + 1, pszBreak, pszSpacing, nNakedFileLen))
			{
				MatchTestAlert();
				goto wrap; // Не оно
			}
			// File without digits, just for opening in the editor
			_ASSERTE(!bLineNumberFound);
			bNakedFile = true;
			break;
		}
		else if (wcschr(pszSpacing, m_SrcLine.ms_Val[mn_MatchRight]))
		{
			if ((++iSpaces) > 1)
			{
				if ((bLineNumberFound) || !IsValidFile(m_SrcLine.ms_Val+mn_MatchLeft, mn_MatchRight - mn_MatchLeft + 1, pszBreak, pszSpacing, nNakedFileLen))
				{
					if (!bLineNumberFound && bMaybeMail)
						break;
					MatchTestAlert();
					goto wrap; // Не оно?
				}
				// File without digits, just for opening in the editor
				_ASSERTE(!bLineNumberFound);
				bNakedFile = true;
				break;
			}
		}
		else
		{
			iSpaces = 0;
		}
	} // end of 'while ((mn_MatchRight+1) < mn_SrcLength)'

	if (bUrlMode)
	{
		// Считаем, что OK
		bMaybeMail = false;
		// Cut off ending punctuators
		if (wcschr(pszPuctuators, m_SrcLine.ms_Val[mn_MatchRight]))
			mn_MatchRight--;
		// Cut off ending bracket if it is
		if (wcschr(pszEndBrackets, m_SrcLine.ms_Val[mn_MatchRight]))
			mn_MatchRight--;
	}
	else
	{
		if (!bNakedFile && !bMaybeMail && ((mn_MatchRight+1) == mn_SrcLength) && !bLineNumberFound && (iExtFound == ef_ExtFound))
		{
			bNakedFile = IsValidFile(m_SrcLine.ms_Val+mn_MatchLeft, mn_MatchRight - mn_MatchLeft + 1, pszBreak, pszSpacing, nNakedFileLen);
		}

		if (bLineNumberFound)
			bMaybeMail = false;

		if (bNakedFile)
		{
			// correct the end pos
			mn_MatchRight = mn_MatchLeft + nNakedFileLen - 1;
			_ASSERTE(mn_MatchRight > mn_MatchLeft);
			// and no need to check for colon
		}
		else if (bMaybeMail)
		{
			// no need to check for colon
		}
		else if ((m_SrcLine.ms_Val[mn_MatchRight] != L':'
				&& m_SrcLine.ms_Val[mn_MatchRight] != L' '
				&& !((m_SrcLine.ms_Val[mn_MatchRight] == L')') && iBracket == 1)
				&& !((m_SrcLine.ms_Val[mn_MatchRight] == L']') && (m_SrcLine.ms_Val[mn_MatchRight+1] == L':'))
			)
			|| !bLineNumberFound || (nColons > 2))
		{
			MatchTestAlert();
			goto wrap;
		}

		if (bMaybeMail || (!bMaybeMail && !bNakedFile && m_SrcLine.ms_Val[mn_MatchRight] != L')'))
			mn_MatchRight--;

		// Откатить ненужные пробелы
		while ((mn_MatchLeft < mn_MatchRight) && wcschr(pszSpacing, m_SrcLine.ms_Val[mn_MatchLeft]))
			mn_MatchLeft++;
		while ((mn_MatchRight > mn_MatchLeft) && wcschr(pszSpacing, m_SrcLine.ms_Val[mn_MatchRight]))
			mn_MatchRight--;

		if (bMaybeMail)
		{
			// Для мейлов - проверяем допустимые символы (чтобы пробелов не было и прочего мусора)
			int x = MailX - 1; _ASSERTE(x>=0);
			while ((x > 0) && wcschr(pszEMail, m_SrcLine.ms_Val[x-1]))
				x--;
			mn_MatchLeft = x;
			x = MailX + 1; _ASSERTE(x<mn_SrcLength);
			while (((x+1) < mn_SrcLength) && wcschr(pszEMail, m_SrcLine.ms_Val[x+1]))
				x++;
			mn_MatchRight = x;
		}
		else if (bNakedFile)
		{
			// ???
		}
		else
		{
			if ((mn_MatchLeft + 4) > mn_MatchRight) // 1.c:1: //-V112
			{
				// Слишком коротко, считаем что не оно
				MatchTestAlert();
				goto wrap;
			}

			// Проверить, чтобы был в наличии номер строки
			if (!(m_SrcLine.ms_Val[mn_MatchRight] >= L'0' && m_SrcLine.ms_Val[mn_MatchRight] <= L'9') // ConEmuC.cpp:49:
				&& !(m_SrcLine.ms_Val[mn_MatchRight] == L')' && (m_SrcLine.ms_Val[mn_MatchRight-1] >= L'0' && m_SrcLine.ms_Val[mn_MatchRight-1] <= L'9'))) // ConEmuC.cpp(49) :
			{
				MatchTestAlert();
				goto wrap; // Номера строки нет
			}
			// [file.cpp:1234]: (cppcheck) ?
			if ((m_SrcLine.ms_Val[mn_MatchRight+1] == L']') && (m_SrcLine.ms_Val[mn_MatchLeft] == L'['))
				mn_MatchLeft++;
			// Чтобы даты ошибочно не подсвечивать:
			// 29.11.2011 18:31:47
			{
				bool bNoDigits = false;
				for (int i = mn_MatchLeft; i <= mn_MatchRight; i++)
				{
					if (m_SrcLine.ms_Val[i] < L'0' || m_SrcLine.ms_Val[i] > L'9')
					{
						bNoDigits = true;
					}
				}
				if (!bNoDigits)
				{
					MatchTestAlert();
					goto wrap;
				}
			}
			// -- уже включены // Для красивости в VC включить скобки
			//if ((m_SrcLine.ms_Val[mn_MatchRight] == L')') && (m_SrcLine.ms_Val[mn_MatchRight+1] == L':'))
			//	mn_MatchRight++;
		}
	} // end "else / if (bUrlMode)"

	// Check mouse pos, it must be inside region
	if ((mn_SrcFrom < mn_MatchLeft) || (mn_MatchRight < mn_SrcFrom))
	{
		MatchTestAlert();
		goto wrap;
	}

	// Ok
	if (mn_MatchRight >= mn_MatchLeft)
	{
		bFound = true;

		_ASSERTE(!bMaybeMail || !bUrlMode); // Одновременно - флаги не могут быть выставлены!
		LPCWSTR pszPrefix = (bMaybeMail && !bUrlMode) ? L"mailto:" : NULL;
		if (bMaybeMail && !bUrlMode)
			bUrlMode = true;

		StoreMatchText(pszPrefix, bUrlMode ? pszUrlTrimRight : NULL);

		#ifdef _DEBUG
		if (!bUrlMode && wcsstr(ms_Match.ms_Val, L"//")!=NULL)
		{
			_ASSERTE(FALSE);
		}
		#endif
	}

	if (bUrlMode)
		m_Type = etr_Url;
	else
		m_Type = (bLineNumberFound ? etr_FileRow : etr_File);

wrap:
	return bFound;
}
Beispiel #11
0
// May comes from Task or ConEmu's -run switch
// or from Setting\Environment page where one line is a single command (bAlone == true)
bool CProcessEnvCmd::AddCommands(LPCWSTR asCommands, LPCWSTR* ppszEnd/*= NULL*/, bool bAlone /*= false*/, INT_PTR anBefore /*= -1*/)
{
	bool bNew = false;
	LPCWSTR lsCmdLine = asCommands;
	CEStr lsSet, lsAmp, lsCmd;

	if (ppszEnd)
		*ppszEnd = asCommands;

	// Example: "set PATH=C:\Program Files;%PATH%" & set abc=def & cmd
	while (NextArg(&lsCmdLine, lsSet) == 0)
	{
		bool bTokenOk = false;
		wchar_t* lsNameVal = NULL;

		// It may contains only "set" or "alias" if was not quoted
		if ((lstrcmpi(lsSet, L"set") == 0) || (lstrcmpi(lsSet, L"alias") == 0))
		{
			lsCmd.Set(lsSet);

			_ASSERTE(*lsCmdLine != L' ');

			// Now we shell get in lsSet "abc=def" token
			// Or to simplify usage, the rest of line is supported too,
			// so user may type in our Settings\Environment:
			//   set V1=From Settings
			// instead of
			//   set "V1=From Settings"
			bool bProcessed = false;
			if ((*lsCmdLine != L'"') || bAlone)
			{
				LPCWSTR pszAmp = bAlone ? NULL : wcschr(lsCmdLine, L'&');
				if (!pszAmp) // No ampersand or bAlone? Use var value as the rest of line
					pszAmp = lsCmdLine + lstrlen(lsCmdLine);
				// Set tail pointer
				LPCWSTR pszValEnd = pszAmp;
				// Trim trailing spaces (only \x20)
				while ((pszValEnd > lsCmdLine) && (*(pszValEnd-1) == L' '))
					pszValEnd--;
				// Trim possible leading/trailing quotes
				if (bAlone && (*lsCmdLine == L'"'))
				{
					lsCmdLine++;
					if (((pszValEnd-1) > lsCmdLine) && (*(pszValEnd-1) == L'"'))
					{
						_ASSERTE(*pszValEnd == 0);
						pszValEnd--;
					}
				}
				// OK, return it
				lsSet.Empty(); // to avoid debug asserts
				lsSet.Set(lsCmdLine, pszValEnd - lsCmdLine);
				lsCmdLine = SkipNonPrintable(pszAmp); // Leave possible '&' at pointer
				bProcessed = true;
			}
			// OK, lets get token like "name=var value"
			if (!bProcessed)
			{
				bProcessed = (NextArg(&lsCmdLine, lsSet) == 0);
			}
			if (bProcessed && (wcschr(lsSet, L'=') > lsSet.ms_Val))
			{
				lsNameVal = lsSet.ms_Val;
			}
		}
		// Or full "set PATH=C:\Program Files;%PATH%" command (without quotes ATM)
		else if (lstrcmpni(lsSet, L"set ", 4) == 0)
		{
			lsCmd = L"set";
			LPCWSTR psz = SkipNonPrintable(lsSet.ms_Val+4);
			if (wcschr(psz, L'=') > psz)
			{
				lsNameVal = (wchar_t*)psz;
			}
		}
		// Support "alias token=value" too
		else if (lstrcmpni(lsSet, L"alias ", 6) == 0)
		{
			lsCmd = L"alias";
			LPCWSTR psz = SkipNonPrintable(lsSet.ms_Val+6);
			if (wcschr(psz, L'=') > psz)
			{
				lsNameVal = (wchar_t*)psz;
			}
		}
		// Process "chcp <cp>" too
		else if (lstrcmpi(lsSet, L"chcp") == 0)
		{
			lsCmd = L"chcp";
			if (NextArg(&lsCmdLine, lsSet) == 0)
			{
				UINT nCP = GetCpFromString(lsSet);
				if (nCP > 0 && nCP <= 0xFFFF)
				{
					bTokenOk = true;
					_ASSERTE(lsNameVal == NULL);
					if (mp_CmdChCp)
					{
						SafeFree(mp_CmdChCp->pszName);
						mp_CmdChCp->pszName = lstrdup(lsSet);
					}
					else
					{
						bNew |= (NULL != Add(lsCmd, lsSet, NULL, anBefore));
					}
				}
			}
		}
		// Change title without need of cmd.exe
		else if (lstrcmpi(lsSet, L"title") == 0)
		{
			lsCmd = L"title";
			if (NextArg(&lsCmdLine, lsSet) == 0)
			{
				bTokenOk = true;
				_ASSERTE(lsNameVal == NULL);
				if (mp_CmdTitle)
				{
					SafeFree(mp_CmdTitle->pszName);
					mp_CmdTitle->pszName = lstrdup(lsSet);
				}
				else
				{
					bNew |= (NULL != Add(lsCmd, lsSet, NULL, anBefore));
				}
			}
		}
		// Echo the "text" before console starts
		// Type the "text file" before console starts
		else if ((lstrcmpi(lsSet, L"echo") == 0) || (lstrcmpi(lsSet, L"type") == 0))
		{
			lsCmd.Set(lsSet);
			// echo [-r] [-n] [-x] [-b] "String to echo"
			// type [-b] [-CP] "Path to text file to echo"
			CEStr lsSwitches;
			while (*lsCmdLine == L'-')
			{
				if (NextArg(&lsCmdLine, lsSet) != 0)
					break;
				lstrmerge(&lsSwitches.ms_Val, lsSwitches.IsEmpty() ? NULL : L" ", lsSet.ms_Val);
			}
			// Rest arguments are expected to be processed text or file
			CEStr lsAdd;
			while (NextArg(&lsCmdLine, lsSet) == 0)
			{
				bTokenOk = true;
				lstrmerge(&lsAdd.ms_Val,
					lsAdd.IsEmpty() ? NULL : L" ",
					lsSet.mb_Quoted ? L"\"" : NULL,
					lsSet.ms_Val,
					lsSet.mb_Quoted ? L"\"" : NULL);
				lsCmdLine = SkipNonPrintable(lsCmdLine);
				if (!*lsCmdLine || (*lsCmdLine == L'&') || (*lsCmdLine == L'|'))
					break;

			}
			if (!lsAdd.IsEmpty())
			{
				bNew |= (NULL != Add(lsCmd, lsSwitches, lsAdd, anBefore));
			}
		}
		else
		{
			lsCmd.Empty();
		}

		// Well, known command was detected. What is next?
		if (lsNameVal || bTokenOk)
		{
			lsAmp.GetPosFrom(lsSet);
			if (NextArg(&lsCmdLine, lsAmp) != 0)
			{
				// End of command? Use may call only "set" without following app? Run simple "cmd" in that case
				_ASSERTE(lsCmdLine!=NULL && *lsCmdLine==0);
				bTokenOk = true; // And process SetEnvironmentVariable
			}
			else
			{
				if (lstrcmp(lsAmp, L"&") == 0)
				{
					// Only simple conveyer is supported!
					bTokenOk = true; // And process SetEnvironmentVariable
				}
				// Update last pointer (debug and asserts purposes)
				lsSet.GetPosFrom(lsAmp);
			}
		}

		if (!bTokenOk)
		{
			break; // Stop processing command line
		}
		else if (lsNameVal)
		{
			// And split name/value
			_ASSERTE(lsNameVal!=NULL);

			wchar_t* pszEq = wcschr(lsNameVal, L'=');
			if (!pszEq)
			{
				_ASSERTE(pszEq!=NULL);
				break;
			}

			*(pszEq++) = 0;

			bNew |= (NULL != Add(lsCmd, lsNameVal, pszEq ? pszEq : L"", anBefore));
		}

		// Remember processed position
		if (ppszEnd)
		{
			*ppszEnd = lsCmdLine;
		}
	} // end of "while (NextArg(&lsCmdLine, lsSet) == 0)"

	// Fin
	if (ppszEnd && (!*ppszEnd || !**ppszEnd))
	{
		static wchar_t szSimple[] = L"cmd";
		*ppszEnd = szSimple;
	}

	return bNew;
}
Beispiel #12
0
bool CMatch::MatchWord(LPCWSTR asLine/*This may be NOT 0-terminated*/, int anLineLen/*Length of buffer*/, int anFrom/*Cursor pos*/, int& rnStart, int& rnEnd, CRConDataGuard& data, int nFromLine)
{
	rnStart = rnEnd = anFrom;

	TODO("Проверить на ошибки после добавления горизонтальной прокрутки");

	if (!asLine || !*asLine || (anFrom < 0) || (anLineLen <= anFrom))
		return false;

	TODO("Setting to define word-break characters (was gh-328 issue)");

	struct cmp {
		static bool isChar(ucs32 inChar)
		{
			return (isCharSpace(inChar) || isCharSeparate(inChar));
		}
	};

	bool (*cmpFunc)(ucs32 inChar) = isCharNonWord;
	// If user double-clicks on "═════════════" - try to select this block of characters?
	if (isCharNonWord(asLine[rnStart]))
		cmpFunc = cmp::isChar;

	while ((rnStart > 0)
		&& !(cmpFunc(asLine[rnStart-1])))
	{
		rnStart--;
	}

	const wchar_t szLeftBkt[] = L"<({[", szRightBkt[] = L">)}]";
	int iStopOnRghtBkt = -1;

	// Trim leading punctuation except of "." (accept dot-files like ".bashrc")
	while (((rnStart+1) < rnEnd)
		&& (asLine[rnStart] != L'.') && isCharPunctuation(asLine[rnStart]))
	{
		if (iStopOnRghtBkt == -1)
		{
			const wchar_t* pchLeftBkt = wcschr(szLeftBkt, asLine[rnStart]);
			if (pchLeftBkt)
			{
				iStopOnRghtBkt = (int)(pchLeftBkt - szLeftBkt);
				_ASSERTE(iStopOnRghtBkt > 0 && (size_t)iStopOnRghtBkt < wcslen(szRightBkt));
			}
		}
		rnStart++;
	}

	bool bStopOnBkt = false;

	while (((rnEnd+1) < anLineLen)
		&& !(cmpFunc(asLine[rnEnd+1])))
	{
		if ((iStopOnRghtBkt >= 0) && (asLine[rnEnd+1] == szRightBkt[iStopOnRghtBkt]))
		{
			bStopOnBkt = true;
			break;
		}
		rnEnd++;
	}

	if (!bStopOnBkt)
	{
		// Now trim trailing punctuation
		while (((rnEnd-1) > rnStart)
			&& isCharPunctuation(asLine[rnEnd]))
		{
			rnEnd--;
		}

		// If part contains (leading) brackets - don't trim trailing brackets
		for (int i = rnStart; i <= rnEnd; i++)
		{
			if (wcschr(szLeftBkt, asLine[i]))
			{
				// Include trailing brackets
				while (((rnEnd+1) < anLineLen)
					&& wcschr(szRightBkt, asLine[rnEnd+1]))
				{
					rnEnd++;
				}
				// Done
				break;
			}
		}
	}

	// Done
	StoreMatchText(NULL, NULL);

	return true;
}
Beispiel #13
0
bool CMatch::FindRangeStart(int& crFrom/*[In/Out]*/, int& crTo/*[In/Out]*/, bool& bUrlMode, LPCWSTR pszBreak, LPCWSTR pszUrlDelim, LPCWSTR pszSpacing, LPCWSTR pszUrl, LPCWSTR pszProtocol, LPCWSTR pChar, int nLen)
{
	bool lbRc = false;

	// Курсор над скобкой "(3): ..." из текста "abc.py (3): ..."
	//if ((crFrom > 2) && wcschr(L"([", pChar[crFrom]) && wcschr(pszSpacing, pChar[crFrom-1]) && !wcschr(pszSpacing, pChar[crFrom-2]))
	//	crFrom--;

	int iAlphas = 0;

	// Курсор над комментарием?
	// Попробуем найти начало имени файла
	// 131026 Allows '?', otherwise links like http://go.com/fwlink/?LinkID=1 may fail
	while ((crFrom > 0)
		&& ((pChar[crFrom-1]==L'?') || !wcschr(bUrlMode ? pszUrlDelim : pszBreak, pChar[crFrom-1])))
	{
		// Check this before pszSpacing comparison because otherwise we'll fail on smth like
		// Bla-bla-bla C:\your-file.txt
		// if the mouse was over "C:\"
		if (isAlpha(pChar[crFrom]))
		{
			iAlphas++;
		}

		if (iAlphas > 0)
		{
			TODO("Если вводить поддержку powershell 'Script.ps1:35 знак:23' нужно будет не прерываться перед национальными словами 'знак'");
			// Disallow leading spaces
			if (wcschr(pszSpacing, pChar[crFrom-1]))
				break;
		}

		if (!bUrlMode && pChar[crFrom] == L'/')
		{
			if ((crFrom >= 2) && ((crFrom + 1) < nLen)
				&& ((pChar[crFrom+1] == L'/') && (pChar[crFrom-1] == L':')
					&& wcschr(pszUrl, pChar[crFrom-2]))) // как минимум одна буква на протокол
			{
				crFrom++;
			}

			if ((crFrom >= 3)
				&& ((pChar[crFrom-1] == L'/') // как минимум одна буква на протокол
					&& (((pChar[crFrom-2] == L':') && wcschr(pszUrl, pChar[crFrom-3])) // http://www.ya.ru
						|| ((crFrom >= 4) && (pChar[crFrom-2] == L'/') && (pChar[crFrom-3] == L':') && wcschr(pszUrl, pChar[crFrom-4])) // file:///c:\file.html
					))
				)
			{
				bUrlMode = true;
				crTo = crFrom-2;
				crFrom -= 3;
				while ((crFrom > 0) && wcschr(pszProtocol, pChar[crFrom-1]))
					crFrom--;
				break;
			}
			else if ((pChar[crFrom] == L'/') && (crFrom >= 1) && (pChar[crFrom-1] == L'/'))
			{
				crFrom++;
				break; // Комментарий в строке?
			}
		}

		crFrom--;

		if (pChar[crFrom] == L':')
		{
			if (pChar[crFrom+1] == L' ')
			{
				// ASM - подсвечивать нужно "test.asasm(1,1)"
				// [email protected](1239): test.asasm(1,1):
				crFrom += 2;
				break;
			}
			else if (bUrlMode && pChar[crFrom+1] != L'\\' && pChar[crFrom+1] != L'/')
			{
				goto wrap; // Не оно
			}
		}
	}

	while (((crFrom+1) < nLen) && wcschr(pszSpacing, pChar[crFrom]))
		crFrom++;

	if (crFrom > crTo)
	{
		goto wrap; // Fail?
	}

	lbRc = true;
wrap:
	return lbRc;
}
void bad()
{
    wchar_t * data;
    map<int, wchar_t *> dataMap;
    wchar_t data_buf[100] = FULL_COMMAND;
    data = data_buf;
    {
#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
    }
    /* Put data in a map */
    dataMap[0] = data;
    dataMap[1] = data;
    dataMap[2] = data;
    badSink(dataMap);
}
void bad()
{
    wchar_t * data;
    wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
    data = dataBuffer;
    if(5==5)
    {
        {
#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) * (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 (connectSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(connectSocket);
            }
#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);
        }
    }
}
Beispiel #16
0
static void
get_progpath(void)
{
    extern wchar_t *Py_GetProgramName(void);
    wchar_t *path = _wgetenv(L"PATH");
    wchar_t *prog = Py_GetProgramName();

#ifdef MS_WINDOWS
#ifdef Py_ENABLE_SHARED
    extern HANDLE PyWin_DLLhModule;
    /* static init of progpath ensures final char remains \0 */
    if (PyWin_DLLhModule)
        if (!GetModuleFileNameW(PyWin_DLLhModule, dllpath, MAXPATHLEN))
            dllpath[0] = 0;
#else
    dllpath[0] = 0;
#endif
    if (GetModuleFileNameW(NULL, progpath, MAXPATHLEN))
        return;
#endif
    if (prog == NULL || *prog == '\0')
        prog = L"python";

    /* If there is no slash in the argv0 path, then we have to
     * assume python is on the user's $PATH, since there's no
     * other way to find a directory to start the search from.  If
     * $PATH isn't exported, you lose.
     */
#ifdef ALTSEP
    if (wcschr(prog, SEP) || wcschr(prog, ALTSEP))
#else
    if (wcschr(prog, SEP))
#endif
        wcsncpy(progpath, prog, MAXPATHLEN);
    else if (path) {
        while (1) {
            wchar_t *delim = wcschr(path, DELIM);

            if (delim) {
                size_t len = delim - path;
                /* ensure we can't overwrite buffer */
                len = min(MAXPATHLEN,len);
                wcsncpy(progpath, path, len);
                *(progpath + len) = '\0';
            }
            else
                wcsncpy(progpath, path, MAXPATHLEN);

            /* join() is safe for MAXPATHLEN+1 size buffer */
            join(progpath, prog);
            if (exists(progpath))
                break;

            if (!delim) {
                progpath[0] = '\0';
                break;
            }
            path = delim + 1;
        }
    }
    else
        progpath[0] = '\0';
}
void CWE78_OS_Command_Injection__wchar_t_connect_socket_execl_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 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
    }
    /* wexecl - specify the path where the command is located */
    /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
    EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
Beispiel #18
0
static void
calculate_path(void)
{
    wchar_t argv0_path[MAXPATHLEN+1];
    wchar_t *buf;
    size_t bufsz;
    wchar_t *pythonhome = Py_GetPythonHome();
    wchar_t *envpath = NULL;

#ifdef MS_WINDOWS
    int skiphome, skipdefault;
    wchar_t *machinepath = NULL;
    wchar_t *userpath = NULL;
    wchar_t zip_path[MAXPATHLEN+1];
    size_t len;

    if (!Py_IgnoreEnvironmentFlag) {
        envpath = _wgetenv(L"PYTHONPATH");
    }
#else
    char *_envpath = Py_GETENV("PYTHONPATH");
    wchar_t wenvpath[MAXPATHLEN+1];
    if (_envpath) {
        size_t r = mbstowcs(wenvpath, _envpath, MAXPATHLEN+1);
        envpath = wenvpath;
        if (r == (size_t)-1 || r >= MAXPATHLEN)
            envpath = NULL;
    }
#endif

    get_progpath();
    /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */
    wcscpy(argv0_path, progpath);
    reduce(argv0_path);
    if (pythonhome == NULL || *pythonhome == '\0') {
        if (search_for_prefix(argv0_path, LANDMARK))
            pythonhome = prefix;
        else
            pythonhome = NULL;
    }
    else
        wcsncpy(prefix, pythonhome, MAXPATHLEN);

    if (envpath && *envpath == '\0')
        envpath = NULL;


#ifdef MS_WINDOWS
    /* Calculate zip archive path */
    if (dllpath[0])             /* use name of python DLL */
        wcsncpy(zip_path, dllpath, MAXPATHLEN);
    else                        /* use name of executable program */
        wcsncpy(zip_path, progpath, MAXPATHLEN);
    zip_path[MAXPATHLEN] = '\0';
    len = wcslen(zip_path);
    if (len > 4) {
        zip_path[len-3] = 'z';          /* change ending to "zip" */
        zip_path[len-2] = 'i';
        zip_path[len-1] = 'p';
    }
    else {
        zip_path[0] = 0;
    }

    skiphome = pythonhome==NULL ? 0 : 1;
#ifdef Py_ENABLE_SHARED
    machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome);
    userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome);
#endif
    /* We only use the default relative PYTHONPATH if we havent
       anything better to use! */
    skipdefault = envpath!=NULL || pythonhome!=NULL || \
                  machinepath!=NULL || userpath!=NULL;
#endif

    /* We need to construct a path from the following parts.
       (1) the PYTHONPATH environment variable, if set;
       (2) for Win32, the zip archive file path;
       (3) for Win32, the machinepath and userpath, if set;
       (4) the PYTHONPATH config macro, with the leading "."
           of each component replaced with pythonhome, if set;
       (5) the directory containing the executable (argv0_path).
       The length calculation calculates #4 first.
       Extra rules:
       - If PYTHONHOME is set (in any way) item (3) is ignored.
       - If registry values are used, (4) and (5) are ignored.
    */

    /* Calculate size of return buffer */
    if (pythonhome != NULL) {
        wchar_t *p;
        bufsz = 1;
        for (p = PYTHONPATH; *p; p++) {
            if (*p == DELIM)
                bufsz++; /* number of DELIM plus one */
        }
        bufsz *= wcslen(pythonhome);
    }
    else
        bufsz = 0;
    bufsz += wcslen(PYTHONPATH) + 1;
    bufsz += wcslen(argv0_path) + 1;
#ifdef MS_WINDOWS
    if (userpath)
        bufsz += wcslen(userpath) + 1;
    if (machinepath)
        bufsz += wcslen(machinepath) + 1;
    bufsz += wcslen(zip_path) + 1;
#endif
    if (envpath != NULL)
        bufsz += wcslen(envpath) + 1;

    module_search_path = buf = malloc(bufsz*sizeof(wchar_t));
    if (buf == NULL) {
        /* We can't exit, so print a warning and limp along */
        fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n");
        if (envpath) {
            fprintf(stderr, "Using environment $PYTHONPATH.\n");
            module_search_path = envpath;
        }
        else {
            fprintf(stderr, "Using default static path.\n");
            module_search_path = PYTHONPATH;
        }
#ifdef MS_WINDOWS
        if (machinepath)
            free(machinepath);
        if (userpath)
            free(userpath);
#endif /* MS_WINDOWS */
        return;
    }

    if (envpath) {
        wcscpy(buf, envpath);
        buf = wcschr(buf, L'\0');
        *buf++ = DELIM;
    }
#ifdef MS_WINDOWS
    if (zip_path[0]) {
        wcscpy(buf, zip_path);
        buf = wcschr(buf, L'\0');
        *buf++ = DELIM;
    }
    if (userpath) {
        wcscpy(buf, userpath);
        buf = wcschr(buf, L'\0');
        *buf++ = DELIM;
        free(userpath);
    }
    if (machinepath) {
        wcscpy(buf, machinepath);
        buf = wcschr(buf, L'\0');
        *buf++ = DELIM;
        free(machinepath);
    }
    if (pythonhome == NULL) {
        if (!skipdefault) {
            wcscpy(buf, PYTHONPATH);
            buf = wcschr(buf, L'\0');
        }
    }
#else
    if (pythonhome == NULL) {
        wcscpy(buf, PYTHONPATH);
        buf = wcschr(buf, L'\0');
    }
#endif /* MS_WINDOWS */
    else {
        wchar_t *p = PYTHONPATH;
        wchar_t *q;
        size_t n;
        for (;;) {
            q = wcschr(p, DELIM);
            if (q == NULL)
                n = wcslen(p);
            else
                n = q-p;
            if (p[0] == '.' && is_sep(p[1])) {
                wcscpy(buf, pythonhome);
                buf = wcschr(buf, L'\0');
                p++;
                n--;
            }
            wcsncpy(buf, p, n);
            buf += n;
            if (q == NULL)
                break;
            *buf++ = DELIM;
            p = q+1;
        }
    }
    if (argv0_path) {
        *buf++ = DELIM;
        wcscpy(buf, argv0_path);
        buf = wcschr(buf, L'\0');
    }
    *buf = L'\0';
    /* Now to pull one last hack/trick.  If sys.prefix is
       empty, then try and find it somewhere on the paths
       we calculated.  We scan backwards, as our general policy
       is that Python core directories are at the *end* of
       sys.path.  We assume that our "lib" directory is
       on the path, and that our 'prefix' directory is
       the parent of that.
    */
    if (*prefix==L'\0') {
        wchar_t lookBuf[MAXPATHLEN+1];
        wchar_t *look = buf - 1; /* 'buf' is at the end of the buffer */
        while (1) {
            Py_ssize_t nchars;
            wchar_t *lookEnd = look;
            /* 'look' will end up one character before the
               start of the path in question - even if this
               is one character before the start of the buffer
            */
            while (look >= module_search_path && *look != DELIM)
                look--;
            nchars = lookEnd-look;
            wcsncpy(lookBuf, look+1, nchars);
            lookBuf[nchars] = L'\0';
            /* Up one level to the parent */
            reduce(lookBuf);
            if (search_for_prefix(lookBuf, LANDMARK)) {
                break;
            }
            /* If we are out of paths to search - give up */
            if (look < module_search_path)
                break;
            look--;
        }
    }
}
Beispiel #19
0
/*=========================================================================
	拡張 strtok()
		"" に出くわすと、"" の中身を取り出す
		token の前後に空白があれば取り除く
		それ以外は、strtok_r() と同じ
=========================================================================*/
WCHAR *strtok_pathW(WCHAR *str, const WCHAR *sep, WCHAR **p, BOOL remove_quote)
{
	const WCHAR	*quote=L"\"";
	const WCHAR	*org_sep = sep;

	if (str)
		*p = str;
	else
		str = *p;

	if (!*p)
		return	NULL;

	// 頭だし
	while (str[0] && (wcschr(sep, str[0]) || str[0] == ' '))
		str++;
	if (str[0] == 0)
		return	NULL;

	// 終端検出
	WCHAR	*in = str, *out = str;
	for ( ; in[0]; in++) {
		BOOL	is_set = FALSE;

		if (sep == org_sep) {	// 通常 mode
			if (wcschr(sep, in[0])) {
				break;
			}
			else if (in[0] == '"') {
				if (!remove_quote) {
					is_set = TRUE;
				}
				sep = quote;	// quote mode に遷移
			}
			else {
				is_set = TRUE;
			}
		}
		else {					// quote mode
			if (in[0] == '"') {
				sep = org_sep;	// 通常 mode に遷移
				if (!remove_quote) {
					is_set = TRUE;
				}
			}
			else {
				is_set = TRUE;
			}
		}
		if (is_set) {
			out[0] = in[0];
			out++;
		}
	}
	*p = in[0] ? in+1 : NULL;
	out[0] = 0;

	// 末尾の空白を取り除く
	for (out--; out >= str && out[0] == ' '; out--)
		out[0] = 0;

	return	str;
}
Beispiel #20
0
/* search_for_prefix requires that argv0_path be no more than MAXPATHLEN
   bytes long.
*/
static int
search_for_prefix(const _PyCoreConfig *core_config,
                  PyCalculatePath *calculate, wchar_t *prefix)
{
    size_t n;
    wchar_t *vpath;

    /* If PYTHONHOME is set, we believe it unconditionally */
    if (core_config->home) {
        wcsncpy(prefix, core_config->home, MAXPATHLEN);
        prefix[MAXPATHLEN] = L'\0';
        wchar_t *delim = wcschr(prefix, DELIM);
        if (delim) {
            *delim = L'\0';
        }
        joinpath(prefix, calculate->lib_python);
        joinpath(prefix, LANDMARK);
        return 1;
    }

    /* Check to see if argv[0] is in the build directory */
    wcsncpy(prefix, calculate->argv0_path, MAXPATHLEN);
    prefix[MAXPATHLEN] = L'\0';
    joinpath(prefix, L"Modules/Setup.local");
    if (isfile(prefix)) {
        /* Check VPATH to see if argv0_path is in the build directory. */
        vpath = Py_DecodeLocale(VPATH, NULL);
        if (vpath != NULL) {
            wcsncpy(prefix, calculate->argv0_path, MAXPATHLEN);
            prefix[MAXPATHLEN] = L'\0';
            joinpath(prefix, vpath);
            PyMem_RawFree(vpath);
            joinpath(prefix, L"Lib");
            joinpath(prefix, LANDMARK);
            if (ismodule(prefix)) {
                return -1;
            }
        }
    }

    /* Search from argv0_path, until root is found */
    copy_absolute(prefix, calculate->argv0_path, MAXPATHLEN+1);
    do {
        n = wcslen(prefix);
        joinpath(prefix, calculate->lib_python);
        joinpath(prefix, LANDMARK);
        if (ismodule(prefix)) {
            return 1;
        }
        prefix[n] = L'\0';
        reduce(prefix);
    } while (prefix[0]);

    /* Look at configure's PREFIX */
    wcsncpy(prefix, calculate->prefix, MAXPATHLEN);
    prefix[MAXPATHLEN] = L'\0';
    joinpath(prefix, calculate->lib_python);
    joinpath(prefix, LANDMARK);
    if (ismodule(prefix)) {
        return 1;
    }

    /* Fail */
    return 0;
}
Beispiel #21
0
static PyObject *
time_strftime(PyObject *self, PyObject *args)
{
    PyObject *tup = NULL;
    struct tm buf;
    const time_char *fmt;
#ifdef HAVE_WCSFTIME
    wchar_t *format;
#else
    PyObject *format;
#endif
    PyObject *format_arg;
    size_t fmtlen, buflen;
    time_char *outbuf = NULL;
    size_t i;
    PyObject *ret = NULL;

    memset((void *) &buf, '\0', sizeof(buf));

    /* Will always expect a unicode string to be passed as format.
       Given that there's no str type anymore in py3k this seems safe.
    */
    if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
        return NULL;

    if (tup == NULL) {
        time_t tt = time(NULL);
        buf = *localtime(&tt);
    }
    else if (!gettmarg(tup, &buf) || !checktm(&buf))
        return NULL;

    /* Normalize tm_isdst just in case someone foolishly implements %Z
       based on the assumption that tm_isdst falls within the range of
       [-1, 1] */
    if (buf.tm_isdst < -1)
        buf.tm_isdst = -1;
    else if (buf.tm_isdst > 1)
        buf.tm_isdst = 1;

#ifdef HAVE_WCSFTIME
    format = PyUnicode_AsWideCharString(format_arg, NULL);
    if (format == NULL)
        return NULL;
    fmt = format;
#else
    /* Convert the unicode string to an ascii one */
    format = PyUnicode_AsEncodedString(format_arg, TZNAME_ENCODING, NULL);
    if (format == NULL)
        return NULL;
    fmt = PyBytes_AS_STRING(format);
#endif

#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME)
    /* check that the format string contains only valid directives */
    for(outbuf = wcschr(fmt, L'%');
        outbuf != NULL;
        outbuf = wcschr(outbuf+2, L'%'))
    {
        if (outbuf[1]=='#')
            ++outbuf; /* not documented by python, */
        if (outbuf[1]=='\0' ||
            !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
        {
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
            return 0;
        }
    }
#endif

    fmtlen = time_strlen(fmt);

    /* I hate these functions that presume you know how big the output
     * will be ahead of time...
     */
    for (i = 1024; ; i += i) {
        outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
        if (outbuf == NULL) {
            PyErr_NoMemory();
            break;
        }
        buflen = format_time(outbuf, i, fmt, &buf);
        if (buflen > 0 || i >= 256 * fmtlen) {
            /* If the buffer is 256 times as long as the format,
               it's probably not failing for lack of room!
               More likely, the format yields an empty result,
               e.g. an empty format, or %Z when the timezone
               is unknown. */
#ifdef HAVE_WCSFTIME
            ret = PyUnicode_FromWideChar(outbuf, buflen);
#else
            ret = PyUnicode_Decode(outbuf, buflen,
                                   TZNAME_ENCODING, NULL);
#endif
            PyMem_Free(outbuf);
            break;
        }
        PyMem_Free(outbuf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        /* VisualStudio .NET 2005 does this properly */
        if (buflen == 0 && errno == EINVAL) {
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
            break;
        }
#endif
    }
#ifdef HAVE_WCSFTIME
    PyMem_Free(format);
#else
    Py_DECREF(format);
#endif
    return ret;
}
Beispiel #22
0
/* search_for_exec_prefix requires that argv0_path be no more than
   MAXPATHLEN bytes long.
*/
static int
search_for_exec_prefix(const _PyCoreConfig *core_config,
                       PyCalculatePath *calculate, wchar_t *exec_prefix)
{
    size_t n;

    /* If PYTHONHOME is set, we believe it unconditionally */
    if (core_config->home) {
        wchar_t *delim = wcschr(core_config->home, DELIM);
        if (delim) {
            wcsncpy(exec_prefix, delim+1, MAXPATHLEN);
        }
        else {
            wcsncpy(exec_prefix, core_config->home, MAXPATHLEN);
        }
        exec_prefix[MAXPATHLEN] = L'\0';
        joinpath(exec_prefix, calculate->lib_python);
        joinpath(exec_prefix, L"lib-dynload");
        return 1;
    }

    /* Check to see if argv[0] is in the build directory. "pybuilddir.txt"
       is written by setup.py and contains the relative path to the location
       of shared library modules. */
    wcsncpy(exec_prefix, calculate->argv0_path, MAXPATHLEN);
    exec_prefix[MAXPATHLEN] = L'\0';
    joinpath(exec_prefix, L"pybuilddir.txt");
    if (isfile(exec_prefix)) {
        FILE *f = _Py_wfopen(exec_prefix, L"rb");
        if (f == NULL) {
            errno = 0;
        }
        else {
            char buf[MAXPATHLEN+1];
            wchar_t *rel_builddir_path;
            n = fread(buf, 1, MAXPATHLEN, f);
            buf[n] = '\0';
            fclose(f);
            rel_builddir_path = _Py_DecodeUTF8_surrogateescape(buf, n);
            if (rel_builddir_path) {
                wcsncpy(exec_prefix, calculate->argv0_path, MAXPATHLEN);
                exec_prefix[MAXPATHLEN] = L'\0';
                joinpath(exec_prefix, rel_builddir_path);
                PyMem_RawFree(rel_builddir_path );
                return -1;
            }
        }
    }

    /* Search from argv0_path, until root is found */
    copy_absolute(exec_prefix, calculate->argv0_path, MAXPATHLEN+1);
    do {
        n = wcslen(exec_prefix);
        joinpath(exec_prefix, calculate->lib_python);
        joinpath(exec_prefix, L"lib-dynload");
        if (isdir(exec_prefix)) {
            return 1;
        }
        exec_prefix[n] = L'\0';
        reduce(exec_prefix);
    } while (exec_prefix[0]);

    /* Look at configure's EXEC_PREFIX */
    wcsncpy(exec_prefix, calculate->exec_prefix, MAXPATHLEN);
    exec_prefix[MAXPATHLEN] = L'\0';
    joinpath(exec_prefix, calculate->lib_python);
    joinpath(exec_prefix, L"lib-dynload");
    if (isdir(exec_prefix)) {
        return 1;
    }

    /* Fail */
    return 0;
}
Beispiel #23
0
/*
 * @implemented
 */
void _wsplitpath(const wchar_t* path, wchar_t* drive, wchar_t* dir, wchar_t* fname, wchar_t* ext)
{
  wchar_t* tmp_drive;
  wchar_t* tmp_dir;
  wchar_t* tmp_ext;

  tmp_drive = (wchar_t*)wcschr(path,L':');
  if (drive)
    {
      if (tmp_drive)
        {
          wcsncpy(drive,tmp_drive-1,2);
          *(drive+2) = 0;
        }
      else
        {
          *drive = 0;
        }
    }
  if (!tmp_drive)
    {
      tmp_drive = (wchar_t*)path - 1;
    }

  tmp_dir = (wchar_t*)wcsrchr(path,L'\\');
  if (dir)
    {
      if (tmp_dir)
        {
          wcsncpy(dir,tmp_drive+1,tmp_dir-tmp_drive);
          *(dir+(tmp_dir-tmp_drive)) = 0;
        }
      else
        {
          *dir =0;
        }
    }

  tmp_ext = (wchar_t*)wcsrchr(path,L'.');
  if (! tmp_ext)
    {
      tmp_ext = (wchar_t*)path+wcslen(path);
    }
  if (ext)
    {
      wcscpy(ext,tmp_ext);
    }

  if (fname)
    {
      if (tmp_dir)
        {
          wcsncpy(fname,tmp_dir+1,tmp_ext-tmp_dir-1);
          *(fname+(tmp_ext-tmp_dir-1)) = 0;
        }
      else
        {
          wcsncpy(fname,tmp_drive+1,tmp_ext-tmp_drive-1);
          *(fname+(tmp_ext-path))=0;
        }
    }
}
Beispiel #24
0
static _PyInitError
calculate_program_full_path(const _PyCoreConfig *core_config,
                            PyCalculatePath *calculate, _PyPathConfig *config)
{
    wchar_t program_full_path[MAXPATHLEN+1];
    memset(program_full_path, 0, sizeof(program_full_path));

#ifdef __APPLE__
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
    uint32_t nsexeclength = MAXPATHLEN;
#else
    unsigned long nsexeclength = MAXPATHLEN;
#endif
    char execpath[MAXPATHLEN+1];
#endif

    /* If there is no slash in the argv0 path, then we have to
     * assume python is on the user's $PATH, since there's no
     * other way to find a directory to start the search from.  If
     * $PATH isn't exported, you lose.
     */
    if (wcschr(core_config->program_name, SEP)) {
        wcsncpy(program_full_path, core_config->program_name, MAXPATHLEN);
    }
#ifdef __APPLE__
     /* On Mac OS X, if a script uses an interpreter of the form
      * "#!/opt/python2.3/bin/python", the kernel only passes "python"
      * as argv[0], which falls through to the $PATH search below.
      * If /opt/python2.3/bin isn't in your path, or is near the end,
      * this algorithm may incorrectly find /usr/bin/python. To work
      * around this, we can use _NSGetExecutablePath to get a better
      * hint of what the intended interpreter was, although this
      * will fail if a relative path was used. but in that case,
      * absolutize() should help us out below
      */
    else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) &&
            execpath[0] == SEP)
    {
        size_t len;
        wchar_t *path = Py_DecodeLocale(execpath, &len);
        if (path == NULL) {
            return DECODE_LOCALE_ERR("executable path", len);
        }
        wcsncpy(program_full_path, path, MAXPATHLEN);
        PyMem_RawFree(path);
    }
#endif /* __APPLE__ */
    else if (calculate->path_env) {
        wchar_t *path = calculate->path_env;
        while (1) {
            wchar_t *delim = wcschr(path, DELIM);

            if (delim) {
                size_t len = delim - path;
                if (len > MAXPATHLEN) {
                    len = MAXPATHLEN;
                }
                wcsncpy(program_full_path, path, len);
                program_full_path[len] = '\0';
            }
            else {
                wcsncpy(program_full_path, path, MAXPATHLEN);
            }

            joinpath(program_full_path, core_config->program_name);
            if (isxfile(program_full_path)) {
                break;
            }

            if (!delim) {
                program_full_path[0] = L'\0';
                break;
            }
            path = delim + 1;
        }
    }
    else {
        program_full_path[0] = '\0';
    }
    if (program_full_path[0] != SEP && program_full_path[0] != '\0') {
        absolutize(program_full_path);
    }

    config->program_full_path = _PyMem_RawWcsdup(program_full_path);
    if (config->program_full_path == NULL) {
        return _Py_INIT_NO_MEMORY();
    }
    return _Py_INIT_OK();
}
Beispiel #25
0
int main(int argc, char *argv[])
{
    TESTSUITE(fuse_opt_tests);
    TESTSUITE(posix_tests);
    TESTSUITE(eventlog_tests);
    TESTSUITE(path_tests);
    TESTSUITE(dirbuf_tests);
    TESTSUITE(version_tests);
    TESTSUITE(launch_tests);
    TESTSUITE(mount_tests);
    TESTSUITE(timeout_tests);
    TESTSUITE(memfs_tests);
    TESTSUITE(create_tests);
    TESTSUITE(info_tests);
    TESTSUITE(security_tests);
    TESTSUITE(rdwr_tests);
    TESTSUITE(flush_tests);
    TESTSUITE(lock_tests);
    TESTSUITE(dirctl_tests);
    TESTSUITE(exec_tests);
    TESTSUITE(reparse_tests);
    TESTSUITE(stream_tests);
    TESTSUITE(oplock_tests);

    atexit(exiting);
    signal(SIGABRT, abort_handler);
    SetUnhandledExceptionFilter(UnhandledExceptionHandler);

    for (int argi = 1; argc > argi; argi++)
    {
        const char *a = argv[argi];
        if ('-' == a[0])
        {
            if (0 == strcmp("--ntfs", a) || 0 == strcmp("--external", a))
            {
                OptExternal = TRUE;
                NtfsTests = 1;
                WinFspDiskTests = 0;
                WinFspNetTests = 0;
                rmarg(argv, argc, argi);
            }
            else if (0 == strcmp("--resilient", a))
            {
                OptResilient = TRUE;
                rmarg(argv, argc, argi);
            }
            else if (0 == strcmp("--case-insensitive-cmp", a))
            {
                OptCaseInsensitiveCmp = TRUE;
                rmarg(argv, argc, argi);
            }
            else if (0 == strcmp("--case-insensitive", a))
            {
                OptCaseInsensitive = TRUE;
                rmarg(argv, argc, argi);
            }
            else if (0 == strcmp("--case-randomize", a))
            {
                OptCaseRandomize = TRUE;
                OptCaseInsensitive = TRUE;
                OptCaseInsensitiveCmp = TRUE;
                rmarg(argv, argc, argi);
            }
            else if (0 == strcmp("--flush-and-purge-on-cleanup", a))
            {
                OptFlushAndPurgeOnCleanup = TRUE;
                rmarg(argv, argc, argi);
            }
            else if (0 == strcmp("--oplock=batch", a))
            {
                OptOplock = 'B';
                rmarg(argv, argc, argi);
            }
            else if (0 == strcmp("--oplock=filter", a))
            {
                OptOplock = 'F';
                rmarg(argv, argc, argi);
            }
            else if (0 == strncmp("--mountpoint=", a, sizeof "--mountpoint=" - 1))
            {
                if (0 != MultiByteToWideChar(CP_UTF8, 0,
                    a + sizeof "--mountpoint=" - 1, -1, OptMountPointBuf, MAX_PATH))
                {
                    OptMountPoint = OptMountPointBuf;
                    rmarg(argv, argc, argi);

                    if (!(testalpha(OptMountPoint[0]) &&
                        L':' == OptMountPoint[1] &&
                        L'\0' == OptMountPoint[2]))
                        WinFspNetTests = 0;
                }
            }
            else if (0 == strncmp("--share=", a, sizeof "--share=" - 1))
            {
                if (0 != MultiByteToWideChar(CP_UTF8, 0,
                    a + sizeof "--share=" - 1, -1, OptShareNameBuf, MAX_PATH))
                {
                    OptShareTarget = wcschr(OptShareNameBuf, L'=');
                    if (OptShareTarget)
                    {
                        *OptShareTarget++ = L'\0';
                        OptShareName = OptShareNameBuf;
                    }
                    else if (L'\\' == OptShareNameBuf[0] && L'\\' == OptShareNameBuf[1])
                    {
                        OptShareName = wcschr(OptShareNameBuf + 2, L'\\');
                        if (OptShareName)
                        {
                            OptShareName++;
                            memcpy(OptShareComputer, OptShareNameBuf,
                                (OptShareName - OptShareNameBuf) * sizeof(WCHAR));
                            OptShareComputer[OptShareName - OptShareNameBuf] = L'\0';
                        }
                    }
                }

                if (OptShareName)
                {
                    rmarg(argv, argc, argi);

                    OptSharePrefixLength = (ULONG)
                        ((wcslen(OptShareComputer) + wcslen(OptShareName) - 1) * sizeof(WCHAR));

                    WinFspDiskTests = 0;
                    WinFspNetTests = 0;
                }
            }
            else if (0 == strncmp("--share-prefix=", a, sizeof "--share-prefix=" - 1))
            {
                /* hack to allow name queries on network file systems with mapped drives */

                WCHAR SharePrefixBuf[MAX_PATH];

                if (0 != MultiByteToWideChar(CP_UTF8, 0,
                    a + sizeof "--share-prefix=" - 1, -1, SharePrefixBuf, MAX_PATH))
                {
                    rmarg(argv, argc, argi);

                    OptSharePrefixLength = (ULONG)(wcslen(SharePrefixBuf) * sizeof(WCHAR));
                }
            }
            else if (0 == strcmp("--no-traverse", a))
            {
                if (LookupPrivilegeValueW(0, SE_CHANGE_NOTIFY_NAME, &OptNoTraverseLuid) &&
                    OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &OptNoTraverseToken))
                {
                    rmarg(argv, argc, argi);
                }
            }
        }
    }

    if (!NtfsTests && OptShareName)
        ABORT("option --share requires --ntfs/--external");

    DisableBackupRestorePrivileges();

    AddNetShareIfNeeded();

    myrandseed = (unsigned)time(0);

    tlib_run_tests(argc, argv);
    return 0;
}
Beispiel #26
0
static _PyInitError
calculate_module_search_path(const _PyCoreConfig *core_config,
                             PyCalculatePath *calculate,
                             const wchar_t *prefix, const wchar_t *exec_prefix,
                             _PyPathConfig *config)
{
    /* Calculate size of return buffer */
    size_t bufsz = 0;
    if (core_config->module_search_path_env != NULL) {
        bufsz += wcslen(core_config->module_search_path_env) + 1;
    }

    wchar_t *defpath = calculate->pythonpath;
    size_t prefixsz = wcslen(prefix) + 1;
    while (1) {
        wchar_t *delim = wcschr(defpath, DELIM);

        if (defpath[0] != SEP) {
            /* Paths are relative to prefix */
            bufsz += prefixsz;
        }

        if (delim) {
            bufsz += delim - defpath + 1;
        }
        else {
            bufsz += wcslen(defpath) + 1;
            break;
        }
        defpath = delim + 1;
    }

    bufsz += wcslen(calculate->zip_path) + 1;
    bufsz += wcslen(exec_prefix) + 1;

    /* Allocate the buffer */
    wchar_t *buf = PyMem_RawMalloc(bufsz * sizeof(wchar_t));
    if (buf == NULL) {
        return _Py_INIT_NO_MEMORY();
    }
    buf[0] = '\0';

    /* Run-time value of $PYTHONPATH goes first */
    if (core_config->module_search_path_env) {
        wcscpy(buf, core_config->module_search_path_env);
        wcscat(buf, delimiter);
    }

    /* Next is the default zip path */
    wcscat(buf, calculate->zip_path);
    wcscat(buf, delimiter);

    /* Next goes merge of compile-time $PYTHONPATH with
     * dynamically located prefix.
     */
    defpath = calculate->pythonpath;
    while (1) {
        wchar_t *delim = wcschr(defpath, DELIM);

        if (defpath[0] != SEP) {
            wcscat(buf, prefix);
            if (prefixsz >= 2 && prefix[prefixsz - 2] != SEP &&
                defpath[0] != (delim ? DELIM : L'\0'))
            {
                /* not empty */
                wcscat(buf, separator);
            }
        }

        if (delim) {
            size_t len = delim - defpath + 1;
            size_t end = wcslen(buf) + len;
            wcsncat(buf, defpath, len);
            buf[end] = '\0';
        }
        else {
            wcscat(buf, defpath);
            break;
        }
        defpath = delim + 1;
    }
    wcscat(buf, delimiter);

    /* Finally, on goes the directory for dynamic-load modules */
    wcscat(buf, exec_prefix);

    config->module_search_path = buf;
    return _Py_INIT_OK();
}
void CWE606_Unchecked_Loop_Condition__wchar_t_listen_socket_02_bad()
{
    wchar_t * data;
    wchar_t dataBuffer[100] = L"";
    data = dataBuffer;
    if(1)
    {
        {
#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
        }
    }
    if(1)
    {
        {
            int i, n, intVariable;
            if (swscanf(data, L"%d", &n) == 1)
            {
                /* POTENTIAL FLAW: user-supplied value 'n' could lead to very large loop iteration */
                intVariable = 0;
                for (i = 0; i < n; i++)
                {
                    /* INCIDENTAL: CWE 561: Dead Code - non-avoidable if n <= 0 */
                    intVariable++; /* avoid a dead/empty code block issue */
                }
                printIntLine(intVariable);
            }
        }
    }
}
Beispiel #28
0
void k4_handle_wmnc_notify(k4_dlg_data * d,
                           WPARAM wParam,
                           LPARAM lParam) {
    switch(HIWORD(wParam)) {
    case WMNC_UPDATE_CREDTEXT:
        {
            if (d->nct->credtext) {
                PFREE(d->nct->credtext);
                d->nct->credtext = NULL;
            }

            if (d->nc->n_identities > 0 &&
                d->nc->identities[0]) {

                khm_int32 flags = 0;
                wchar_t idname[KCDB_IDENT_MAXCCH_NAME];
                wchar_t * atsign;
                wchar_t * realm;
                khm_size cb;

                kcdb_identity_get_flags(d->nc->identities[0], &flags);

                if (!(flags & KCDB_IDENT_FLAG_VALID)) {
                    break;
                }

                cb = sizeof(idname);
                kcdb_identity_get_name(d->nc->identities[0], idname,
                                       &cb);

                atsign = wcsrchr(idname, L'@');

                if (atsign == NULL || !atsign[1])
                    break;

                realm = ++atsign;

                if (d->k4_enabled) {
                    wchar_t wmethod[128];
                    wchar_t wfmt[128];
                    wchar_t wct[512];

                    LoadString(hResModule, IDS_CT_TGTFOR,
                               wfmt, ARRAYLENGTH(wfmt));

                    if (d->method == K4_METHOD_AUTO)
                        LoadString(hResModule, IDS_METHOD_AUTO, wmethod,
                                   ARRAYLENGTH(wmethod));
                    else if (d->method == K4_METHOD_PASSWORD)
                        LoadString(hResModule, IDS_METHOD_PWD, wmethod,
                                   ARRAYLENGTH(wmethod));
                    else if (d->method == K4_METHOD_K524)
                        LoadString(hResModule, IDS_METHOD_K524, wmethod,
                                   ARRAYLENGTH(wmethod));
                    else {
                        assert(FALSE);
                    }

                    StringCbPrintf(wct, sizeof(wct), wfmt, realm, wmethod);

                    StringCbLength(wct, sizeof(wct), &cb);
                    cb += sizeof(wchar_t);

                    d->nct->credtext = PMALLOC(cb);

                    StringCbCopy(d->nct->credtext, cb, wct);
                } else {
                    wchar_t wct[256];

                    LoadString(hResModule, IDS_CT_DISABLED,
                               wct, ARRAYLENGTH(wct));

                    StringCbLength(wct, sizeof(wct), &cb);
                    cb += sizeof(wchar_t);

                    d->nct->credtext = PMALLOC(cb);

                    StringCbCopy(d->nct->credtext, cb, wct);
                }
            }
            /* no identities were selected.  it is not the
               responsibility of krb4 to complain about this. */
        }
        break;

    case WMNC_IDENTITY_CHANGE:
        k4_read_identity_data(d);
        k4_update_display(d, TRUE);
        break;

    case WMNC_CREDTEXT_LINK:
        {
            wchar_t wid[KHUI_MAXCCH_HTLINK_FIELD];
            wchar_t * wids;
            khui_htwnd_link * l;

            l = (khui_htwnd_link *) lParam;

            StringCchCopyN(wid, ARRAYLENGTH(wid), l->id, l->id_len);
            wids = wcschr(wid, L':');

            if (!wids)
                break;
            else
                wids++;

            if (!wcscmp(wids, L"Enable")) {
                d->k4_enabled = TRUE;

                k4_update_display(d, TRUE);
                khui_cw_enable_type(d->nc, credtype_id_krb4, TRUE);
            }
        }
        break;
    }
}
/**
   Parse message msg
*/
static void parse_message( wchar_t *msg,
						   connection_t *src )
{
//	debug( 3, L"parse_message( %ls );", msg );
	
	if( msg[0] == L'#' )
		return;
	
	if( match( msg, SET_STR ) || match( msg, SET_EXPORT_STR ))
	{
		wchar_t *name, *tmp;
		int exportv = match( msg, SET_EXPORT_STR );
		
		name = msg+(exportv?wcslen(SET_EXPORT_STR):wcslen(SET_STR));
		while( wcschr( L"\t ", *name ) )
			name++;
		
		tmp = wcschr( name, L':' );
		if( tmp )
		{
			wchar_t *key;
			wchar_t *val;
			
			key = (wchar_t *)malloc( sizeof( wchar_t)*(tmp-name+1));
			memcpy( key, name, sizeof( wchar_t)*(tmp-name));
			key[tmp-name]=0;
			
			val = tmp+1;
			val = unescape( val, 0 );
			
			if (key && val)
			    env_universal_common_set( key, val, exportv );
			
			free( val );
			free( key );
		}
		else
		{
			debug( 1, PARSE_ERR, msg );
		}			
	}
	else if( match( msg, ERASE_STR ) )
	{
		wchar_t *name, *tmp;
		
		name = msg+wcslen(ERASE_STR);
		while( wcschr( L"\t ", *name ) )
			name++;
		
		tmp = name;
		while( iswalnum( *tmp ) || *tmp == L'_')
			tmp++;
		
		*tmp = 0;
		
		if( !wcslen( name ) )
		{
			debug( 1, PARSE_ERR, msg );
		}

		env_universal_common_remove( name );
		
		if( callback )
		{
			callback( ERASE, name, 0 );
		}
	}
	else if( match( msg, BARRIER_STR) )
	{
		message_t *msg = create_message( BARRIER_REPLY, 0, 0 );
		msg->count = 1;
        src->unsent->push(msg);
		try_send_all( src );
	}
	else if( match( msg, BARRIER_REPLY_STR ) )
	{
		if( callback )
		{
			callback( BARRIER_REPLY, 0, 0 );
		}
	}
	else
	{
		debug( 1, PARSE_ERR, msg );
	}		
}
	void CModelReaderNode093_Triangle::OnAttribute(_In_z_ const nfWChar * pAttributeName, _In_z_ const nfWChar * pAttributeValue)
	{
		__NMRASSERT(pAttributeName);
		__NMRASSERT(pAttributeValue);
		nfInt32 nValue;

		if (wcscmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_V1) == 0) {
			nValue = fnWStringToInt32(pAttributeValue);
			if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX))
				m_nIndex1 = nValue;
		}

		if (wcscmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_V2) == 0) {
			nValue = fnWStringToInt32(pAttributeValue);
			if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX))
				m_nIndex2 = nValue;
		}

		if (wcscmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_V3) == 0) {
			nValue = fnWStringToInt32(pAttributeValue);
			if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX))
				m_nIndex3 = nValue;
		}

		if (wcscmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_CV1) == 0) {
			nValue = fnWStringToInt32(pAttributeValue);
			if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX))
				m_nTextureIndex1 = nValue;
		}

		if (wcscmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_CV2) == 0) {
			nValue = fnWStringToInt32(pAttributeValue);
			if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX))
				m_nTextureIndex2 = nValue;
		}

		if (wcscmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_CV3) == 0) {
			nValue = fnWStringToInt32(pAttributeValue);
			if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX))
				m_nTextureIndex3 = nValue;
		}

		if (wcscmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_COLORID) == 0) {
			std::wstring sValue(pAttributeValue);
			std::wstring sSubStr = sValue.substr(0, 4);
			if (sSubStr == L"tex(") {
				if (sValue.length() > 4) {
					std::wstring sTexID = sValue.substr(4, sValue.length() - sSubStr.length() - 1);
					nfInt32 nValue = fnWStringToInt32(sTexID.c_str());
					if ((nValue < 0) || (nValue >= XML_3MF_MAXRESOURCEINDEX))
						throw CNMRException(NMR_ERROR_INVALIDTEXTUREREFERENCE);

					m_nTextureID = nValue + 1;

				}
				else {
					throw CNMRException(NMR_ERROR_INVALIDTEXTUREREFERENCE);
				}

			}
			else {
				const wchar_t * pCommaValue = wcschr(pAttributeValue, L',');

				// Check, if we have a single value
				if (pCommaValue == nullptr) {

					nValue = fnWStringToInt32(pAttributeValue);
					if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX)) {
						m_nColorID1 = nValue + 1;
						m_nColorID2 = nValue + 1;
						m_nColorID3 = nValue + 1;
					}
				}
				else {
					// Check, if we have a color triplet
					nfInt32 nColorID1 = -1;
					nfInt32 nColorID2 = -1;
					nfInt32 nColorID3 = -1;

					fnStringToCommaSeparatedIntegerTriplet(pAttributeValue, nColorID1, nColorID2, nColorID3);

					if ((nColorID1 >= 0) && (nColorID1 < XML_3MF_MAXRESOURCEINDEX))
						m_nColorID1 = nColorID1 + 1;
					if ((nColorID2 >= 0) && (nColorID2 < XML_3MF_MAXRESOURCEINDEX))
						m_nColorID2 = nColorID2 + 1;
					if ((nColorID3 >= 0) && (nColorID3 < XML_3MF_MAXRESOURCEINDEX))
						m_nColorID3 = nColorID3 + 1;
				}
			}
		}

		if (wcscmp(pAttributeName, XML_3MF_ATTRIBUTE_TRIANGLE_MATERIALID) == 0) {
			nValue = fnWStringToInt32(pAttributeValue);
			if ((nValue >= 0) && (nValue < XML_3MF_MAXRESOURCEINDEX))
				m_nMaterialID = nValue + 1;
		}

	}