Example #1
0
BOOL
OnNotify(
    HWND    ParentHwnd,
    LPNMHDR NmHdr,
    PTOASTER_PROP_PARAMS Params
    )
{
    SP_DEVINSTALL_PARAMS spDevInstall = {0};
    TCHAR                friendlyName[LINE_LEN] ={0};
    size_t  charCount;
    BOOL    fSuccess;

    switch (NmHdr->code) {
    case PSN_APPLY:
        //
        // Sent when the user clicks on Apply OR OK !!
        //

        GetDlgItemText(ParentHwnd, IDC_FRIENDLYNAME, friendlyName,
                                        LINE_LEN-1 );
        friendlyName[LINE_LEN-1] = UNICODE_NULL;
        if(friendlyName[0]) {

            if (FAILED(StringCchLength(friendlyName,
                         STRSAFE_MAX_CCH,
                         &charCount))) {
                DbgOut("StringCchLength failed!");                   
                break;
            }
            fSuccess = SetupDiSetDeviceRegistryProperty(Params->DeviceInfoSet, 
                         Params->DeviceInfoData,
                         SPDRP_FRIENDLYNAME,
                         (BYTE *)friendlyName,
                         (DWORD)((charCount + 1) * sizeof(TCHAR))
                         );
            if(!fSuccess) {
                DbgOut("SetupDiSetDeviceRegistryProperty failed!");                   
                break;
            }

            //
            // Inform setup about property change so that it can
            // restart the device.
            //

            spDevInstall.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
     
            if (Params && SetupDiGetDeviceInstallParams(Params->DeviceInfoSet,
                                              Params->DeviceInfoData,
                                              &spDevInstall)) {
                //
                // If your device requires a reboot to restart, you can
                // specify that by setting DI_NEEDREBOOT as shown below
                //
                // if(NeedReboot) {
                //    spDevInstall.Flags |= DI_PROPERTIES_CHANGE | DI_NEEDREBOOT;
                // }
                //
                spDevInstall.FlagsEx |= DI_FLAGSEX_PROPCHANGE_PENDING;
                
                SetupDiSetDeviceInstallParams(Params->DeviceInfoSet,
                                              Params->DeviceInfoData,
                                              &spDevInstall);
            }
        
        }
        return TRUE;

    default:
        return FALSE;
    }
    return FALSE;   
} 
Example #2
0
void khm_cred_obtain_new_creds(wchar_t * title)
{
    khui_new_creds * nc;
    LPNETID_DLGINFO pdlginfo;
    khm_size cb;

    if (!khm_cred_begin_dialog())
        return;

    khui_cw_create_cred_blob(&nc);
    nc->subtype = KMSG_CRED_NEW_CREDS;
    dialog_nc = nc;

    khui_context_get(&nc->ctx);

    kcdb_identpro_get_ui_cb((void *) &nc->ident_cb);

    if (nc->ident_cb == NULL) {
        wchar_t title[256];
        wchar_t msg[512];
        wchar_t suggestion[512];
        khui_alert * a;

        LoadString(khm_hInstance, IDS_ERR_TITLE_NO_IDENTPRO,
                   title, ARRAYLENGTH(title));
        LoadString(khm_hInstance, IDS_ERR_MSG_NO_IDENTPRO,
                   msg, ARRAYLENGTH(msg));
        LoadString(khm_hInstance, IDS_ERR_SUGG_NO_IDENTPRO,
                   suggestion, ARRAYLENGTH(suggestion));

        khui_alert_create_simple(title,
                                 msg,
                                 KHERR_ERROR,
                                 &a);
        khui_alert_set_suggestion(a, suggestion);

        khui_alert_show(a);

        khui_alert_release(a);

        khui_context_release(&nc->ctx);
        nc->result = KHUI_NC_RESULT_CANCEL;
        khm_cred_end_dialog(nc);
        khui_cw_destroy_cred_blob(nc);
        return;
    }

    if (title) {
        if (SUCCEEDED(StringCbLength(title, KHUI_MAXCB_TITLE, &cb))) {
            cb += sizeof(wchar_t);

            nc->window_title = PMALLOC(cb);
#ifdef DEBUG
            assert(nc->window_title);
#endif
            StringCbCopy(nc->window_title, cb, title);
        }
    } else if (nc->ctx.cb_vparam == sizeof(NETID_DLGINFO) &&
               (pdlginfo = nc->ctx.vparam) &&
               pdlginfo->size == NETID_DLGINFO_V1_SZ &&
               pdlginfo->in.title[0] &&
               SUCCEEDED(StringCchLength(pdlginfo->in.title,
                                         NETID_TITLE_SZ,
                                         &cb))) {

        cb = (cb + 1) * sizeof(wchar_t);
        nc->window_title = PMALLOC(cb);
#ifdef DEBUG
        assert(nc->window_title);
#endif
        StringCbCopy(nc->window_title, cb, pdlginfo->in.title);
    }

    khm_create_newcredwnd(khm_hwnd_main, nc);

    if (nc->hwnd != NULL) {
        _begin_task(KHERR_CF_TRANSITIVE);
        _report_sr0(KHERR_NONE, IDS_CTX_NEW_CREDS);
        _describe();

        kmq_post_message(KMSG_CRED, KMSG_CRED_NEW_CREDS, 0, 
                         (void *) nc);

        _end_task();
    } else {
        khui_context_release(&nc->ctx);
        nc->result = KHUI_NC_RESULT_CANCEL;
        khm_cred_end_dialog(nc);
        khui_cw_destroy_cred_blob(nc);
    }
}
Example #3
0
// MW-2005-05-15: Updated for new answer command restructuring
int MCA_folder(MCStringRef p_title, MCStringRef p_prompt, MCStringRef p_initial, unsigned int p_options, MCStringRef &r_value, MCStringRef &r_result)
{
	if (MCmajorosversion >= 0x0600 && MCModeMakeLocalWindows())
		return MCA_file(p_title, p_prompt, nil, p_initial, p_options | MCA_OPTION_FOLDER_DIALOG, r_value, r_result);

// MW-2005-05-27: We'll use a static (I know bad me) to store the version
//   of the shell dll.
	static int s_shell_version = -1;
	static MCStringRef s_last_folder = MCValueRetain(kMCEmptyString);

	MCAutoStringRef t_native_filename;

	if (p_initial != NULL)
	{
		MCAutoStringRef t_std_path;

		/* UNCHECKED */ MCS_pathfromnative(p_initial, &t_std_path);
		t_native_filename = *t_std_path;
	}
	else
		t_native_filename = MCValueRetain(s_last_folder);

	if (!MCModeMakeLocalWindows())
    {
		MCAutoStringRef t_answer_path;
		MCRemoteFolderDialog(p_title, p_prompt, *t_native_filename, &t_answer_path);
        if (*t_answer_path != nil)
		{
			MCAutoStringRef t_std_path;

			/* UNCHECKED */ MCS_pathfromnative(*t_answer_path, &t_std_path);
			MCValueAssign(s_last_folder, *t_std_path);
		}
		r_value = MCValueRetain(*t_answer_path);
		return 0;
	}

	if (s_shell_version == -1)
		s_shell_version = get_dll_version(L"shell32.dll");

	bool sheet = (p_options & MCA_OPTION_SHEET) != 0;

	BROWSEINFOW bi;
	memset(&bi, 0, sizeof(BROWSEINFOW));

	Window pw;
	pw = MCModeGetParentWindow();

	if (pw != DNULL)
		bi.hwndOwner = (HWND)pw->handle.window;

	MCAutoStringRefAsWString t_prompt_wstr;
	MCAutoStringRefAsWString t_native_filename_wstr;
	/* UNCHECKED */ t_prompt_wstr.Lock(p_prompt);

	bi.pidlRoot = NULL;
	bi.lpszTitle = *t_prompt_wstr;
	bi.ulFlags = BIF_RETURNONLYFSDIRS;
	if (s_shell_version >= 500)
		bi.ulFlags |= BIF_NEWDIALOGSTYLE;
	if (*t_native_filename != nil && !MCStringIsEmpty(*t_native_filename))
	{
		t_native_filename_wstr.Lock(*t_native_filename);
		
		bi . lpfn = BrowseCallbackProc;
		bi . lParam = (LPARAM)*t_native_filename_wstr;
	}
	else
	{
		bi.lpfn = NULL;
		bi.lParam = NULL;
	}
	LPITEMIDLIST lpiil;
	LPMALLOC lpm;
	SHGetMalloc(&lpm);

	DWORD t_error;
	lpiil = SHBrowseForFolderW(&bi);
	if (lpiil == NULL)
	{
		t_error = GetLastError();
	}
	
	MCAutoArray<unichar_t> t_buffer;
	/* UNCHECKED */ t_buffer.New(MAX_PATH);

	if (lpiil != NULL && SHGetPathFromIDListW(lpiil, t_buffer.Ptr()))
	{
		if (s_last_folder != NULL)
			MCValueRelease(s_last_folder);

		size_t t_length;
		/* UNCHECKED */ StringCchLength(t_buffer.Ptr(), t_buffer.Size(), &t_length);
		/* UNCHECKED */ MCStringCreateWithChars(t_buffer.Ptr(), t_length, s_last_folder);

		MCAutoStringRef t_std_path;
		/* UNCHECKED */ MCS_pathfromnative(s_last_folder, &t_std_path);

		r_value = MCValueRetain(*t_std_path);
	}
	else
		r_result = MCSTR(MCcancelstring);

	//  SMR 1880 clear shift and button state
	waitonbutton();

	lpm->Free(lpiil);
	lpm->Release();

	return 0;
}
MI_Result UpdateTask(
    _In_z_ MI_Char* taskName,
    _In_z_ MI_Char* taskTime,
    _In_ MI_Uint32 refreshFrequencyInSeconds,
    _Outptr_result_maybenull_ MI_Instance **extendedError)
{
    MI_Result r = MI_RESULT_OK;
    PROCESS_INFORMATION ProcInfo;
    STARTUPINFO si;
    HRESULT hr = S_OK;
    MI_Uint32 dwExitCode = 0;
    BOOL bRes = MI_TRUE;
    UINT retVal = 0;
    HANDLE hXmlFileHandle = NULL;
    BOOL bHandleUsageSuccess = FALSE;
    const char BOM [] = {0xFF, 0xFE};
    MI_Uint32 dwWmiMethodArg = 0;
    size_t sFormattedXMLFileLength = 0;

    // The task scheduler filename
    // This will double as the buffer for GetTempPath and for the command
    wchar_t wSchedTaskPath[MAX_PATH];
    wchar_t wTmpFilePath[MAX_PATH];
    wchar_t wSchedTaskFile[(sizeof(LocalConfigManagerTaskXMLFormatString)+sizeof(L"2013-04-11T18:10:48")+sizeof("2678400"))/sizeof(wchar_t)];
    wchar_t wSchedTaskParam[LCM_MAX_PATH];
    MI_Uint32 len = 0;

    LPWSTR wCommandFormat = NULL;

    if (extendedError == NULL)
    {
        return MI_RESULT_INVALID_PARAMETER;
    }
    *extendedError = NULL;  // Explicitly set *extendedError to NULL as _Outptr_ requires setting this at least once.

    wSchedTaskPath[0] = L'\0';
    wTmpFilePath[0] = L'\0';
    wSchedTaskFile[0] = L'\0';
    wSchedTaskParam[0] = L'\0';
    memset(&si,0,sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags = STARTF_FORCEOFFFEEDBACK;

    if (refreshFrequencyInSeconds > THIRTY_ONE_DAYS_IN_SECONDS)
    {
        refreshFrequencyInSeconds = THIRTY_ONE_DAYS_IN_SECONDS;
    }
    if (refreshFrequencyInSeconds < FIFTEEN_MINUTES_IN_SECONDS)
    {
        refreshFrequencyInSeconds = THIRTY_ONE_DAYS_IN_SECONDS;
    }



    wCommandFormat = LocalConfigManagerTaskConsistencyCommand;
    dwWmiMethodArg = 1;

    retVal = GetTempPath(MAX_PATH, wSchedTaskPath);
    if (!retVal)
    {
        hr = E_FAIL;
        return GetCimError(hr, extendedError, ID_LCMHELPER_GETTEMPPATH_ERROR);
    }

    // 0 here signifies our willingness to let the system create and close the file for us
    // This means we cannot specify FILE_ATTRIBUTE_TEMPORARY to CreateFile
    // but in return we can be sure that nobody will take our filename in the microsecond before we use it
    retVal = GetTempFileName(wSchedTaskPath, L"LCM", 0u, wTmpFilePath);
    if (!retVal)
    {
        hr = E_FAIL;
        return GetCimError(hr, extendedError, ID_LCMHELPER_GETTEMPFILENAME_ERROR);
    }

    hr = StringCchPrintf(wSchedTaskParam, sizeof(wSchedTaskParam)/sizeof(wchar_t), wCommandFormat, wTmpFilePath);
    if (FAILED(hr) || NitsShouldFault(NitsHere(), NitsAutomatic))
    {
        if (SUCCEEDED(hr)) hr = E_FAIL;
        return GetCimError(hr, extendedError, ID_LCMHELPER_PRINTF_ERROR);
    }

    if (GetEnvironmentVariable(L"windir", wSchedTaskPath, MAX_PATH) ==0 )
    {
        return  GetCimWin32Error(GetLastError(), extendedError, ID_MODMAN_WINDIRENV_FAILED);
    }

    hr = StringCchCatW(wSchedTaskPath, MAX_PATH, L"\\system32\\schtasks.exe");
    if (FAILED(hr))
    {
        return GetCimError(hr, extendedError, ID_ENGINEHELPER_CAT_ERROR);
    }

    hr = StringCchPrintf(wSchedTaskFile, sizeof(wSchedTaskFile)/sizeof(wchar_t), LocalConfigManagerTaskXMLFormatString, refreshFrequencyInSeconds, taskTime, dwWmiMethodArg);
    if (FAILED(hr) || NitsShouldFault(NitsHere(), NitsAutomatic))
    {
        if( SUCCEEDED(hr)) hr = E_FAIL;
        return GetCimError(hr, extendedError, ID_LCMHELPER_PRINTF_ERROR);
    }

    hr = StringCchLength(wSchedTaskFile, STRSAFE_MAX_CCH, &sFormattedXMLFileLength);
    if (FAILED(hr) || NitsShouldFault(NitsHere(), NitsAutomatic))
    {
        if( SUCCEEDED(hr)) hr = E_FAIL;
        return GetCimError(hr, extendedError, ID_LCMHELPER_STRLEN_ERROR);
    }

    // We've done everything we can do ahead of time. Now we actually start changing the system

    hXmlFileHandle = CreateFile(wTmpFilePath, GENERIC_WRITE, 0 /* Prevent sharing */, NULL /* Children don't inherit */, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL /* No template */);
    if (hXmlFileHandle == INVALID_HANDLE_VALUE)
    {
        return GetCimWin32Error(GetLastError(), extendedError, ID_ENGINEHELPER_OPENFILE_ERROR);
    }

    bHandleUsageSuccess = WriteFile(hXmlFileHandle, BOM, sizeof(BOM), (LPDWORD)&len, NULL);
    if (!bHandleUsageSuccess)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        CloseHandle(hXmlFileHandle);
        DeleteFile(wTmpFilePath);
        return GetCimError(hr, extendedError, ID_LCMHELPER_WRITEFILE_ERROR);
    }

    bHandleUsageSuccess = WriteFile(hXmlFileHandle, wSchedTaskFile, (DWORD)(sFormattedXMLFileLength*sizeof(wchar_t)), (LPDWORD)&len, NULL);
    if (!bHandleUsageSuccess)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        CloseHandle(hXmlFileHandle);
        DeleteFile(wTmpFilePath);
        return GetCimError(hr, extendedError, ID_LCMHELPER_WRITEFILE_ERROR);
    }

    bHandleUsageSuccess = CloseHandle(hXmlFileHandle);
    if (!bHandleUsageSuccess)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        DeleteFile(wTmpFilePath);
        return GetCimError(hr, extendedError, ID_LCMHELPER_CLOSEHANDLE_ERROR);
    }

    bRes = CreateProcess(wSchedTaskPath, wSchedTaskParam, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &ProcInfo);
    if (!bRes)
    {
        CloseHandle(hXmlFileHandle);
        DeleteFile(wTmpFilePath);
        return GetCimWin32Error(GetLastError(), extendedError, ID_ENGINEHELPER_CREATEPROCESS_ERROR);
    }

    WaitForSingleObject(ProcInfo.hProcess, INFINITE);
    if (GetExitCodeProcess(ProcInfo.hProcess,(LPDWORD)&dwExitCode) && dwExitCode != 0)
    {
        r = GetCimMIError(MI_RESULT_FAILED, extendedError, ID_ENGINEHELPER_CREATEPROCESS_ERROR);
    }

    bHandleUsageSuccess = DeleteFile(wTmpFilePath);
    if (!bHandleUsageSuccess && r == MI_RESULT_OK)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        return GetCimError(hr, extendedError, ID_LCMHELPER_DELETEFILE_ERROR);
    }

    CloseHandle(ProcInfo.hThread);
    CloseHandle(ProcInfo.hProcess);

    return r;
}
Example #5
0
void khm_cred_change_password(wchar_t * title)
{
    khui_new_creds * nc;
    LPNETID_DLGINFO pdlginfo;
    khm_size cb;

    if (!khm_cred_begin_dialog())
        return;

    khui_cw_create_cred_blob(&nc);
    nc->subtype = KMSG_CRED_PASSWORD;
    dialog_nc = nc;

    khui_context_get(&nc->ctx);

    kcdb_identpro_get_ui_cb((void *) &nc->ident_cb);

    assert(nc->ident_cb);

    if (title) {

        if (SUCCEEDED(StringCbLength(title, KHUI_MAXCB_TITLE, &cb))) {
            cb += sizeof(wchar_t);

            nc->window_title = PMALLOC(cb);
#ifdef DEBUG
            assert(nc->window_title);
#endif
            StringCbCopy(nc->window_title, cb, title);
        }
    } else if (nc->ctx.cb_vparam == sizeof(NETID_DLGINFO) &&
               (pdlginfo = nc->ctx.vparam) &&
               pdlginfo->size == NETID_DLGINFO_V1_SZ &&
               pdlginfo->in.title[0] &&
               SUCCEEDED(StringCchLength(pdlginfo->in.title,
                                         NETID_TITLE_SZ,
                                         &cb))) {

        cb = (cb + 1) * sizeof(wchar_t);
        nc->window_title = PMALLOC(cb);
#ifdef DEBUG
        assert(nc->window_title);
#endif
        StringCbCopy(nc->window_title, cb, pdlginfo->in.title);
    }

    khm_create_newcredwnd(khm_hwnd_main, nc);

    if (nc->hwnd != NULL) {
        _begin_task(KHERR_CF_TRANSITIVE);
        _report_sr0(KHERR_NONE, IDS_CTX_PASSWORD);
        _describe();

        kmq_post_message(KMSG_CRED, KMSG_CRED_PASSWORD, 0,
                         (void *) nc);

        _end_task();
    } else {
        khui_cw_destroy_cred_blob(nc);
    }
}
DWORD WINAPI InjectDLLThreadFunc(LPVOID lpParam) 
{
	InjectDLLThreadFuncInfo* info = (InjectDLLThreadFuncInfo*)lpParam;
	HANDLE hProcess = info->hInjectProcess;
	DWORD dwInjectProcessID = info->dwInjectProcessID;
	HANDLE hInjectThread = info->hInjectThread;
	DWORD dwInjectThreadID = info->dwInjectThreadID;
	TCHAR* dllPath = info->injectDllPath;
	bool runDllLast = info->runDllLast;
	DWORD dwThread = 0;
	size_t dwPathLength = 1024;
	StringCchLength(dllPath, dwPathLength, &dwPathLength);

	dwPathLength *= sizeof(WCHAR);

	if (hProcess == NULL)
	{
		PrintLastError("CreateProcess", GetLastError());
		terminateRequest = true;
	}


	// modify the IDT (import directory table) (though the IAT is more commonly referred to)
	// so that Windows thinks the game needs to load our DLL first
	bool injected = InjectDLLIntoIDT(dwInjectProcessID, hProcess, hInjectThread, dllPath, !runDllLast);

	if(injected)
	{
		debugprintf("Injecting \"%s\" by IAT (method %d) apparently succeeded.\n", dllPath, runDllLast?2:1);
		info->injectIsAsyncReady = TRUE;
		goto done;
	} 

	DWORD exitCode = 0;

	if(exitCode == 0)
	{
		terminateRequest = true;
		if(hProcess != NULL)
		{
			debugprintf("Injection failed...\n");
			CustomMessageBox("Injection failed...\nYou can (hopefully) find more information in the debug log .txt file.", "Error", MB_OK | MB_ICONERROR);
		}
		else
		{
			CustomMessageBox("The game could not be launched...\nYou can (hopefully) find more information in the debug log .txt file.", "Error", MB_OK | MB_ICONERROR);
		}
	}
	else // Why is this here??
	{
		debugprintf("Injection probably succeeded (0x%X)...\n", exitCode);
	}

done:
	while(!info->injectAllowedToFinish)
	{
		Sleep(5);
	}
	delete info;

	return 0;
}
Example #7
0
//+---------------------------------------------------------------------------
//
// Function:  HrInstallNetComponent
//
// Purpose:   Install the specified net component
//
// Arguments:
//    pnc           [in]  pointer to INetCfg object
//    szComponentId [in]  component to install
//    pguidClass    [in]  class guid of the component
//
// Returns:   S_OK or NETCFG_S_REBOOT on success, otherwise an error code
//
// Notes:
//
HRESULT HrInstallNetComponent(IN INetCfg* pnc,
                              IN PCTSTR szComponentId,
                              IN const GUID* pguidClass)
{
    HRESULT hr=S_OK;
    OBO_TOKEN OboToken;
    INetCfgClassSetup* pncClassSetup;
    INetCfgComponent* pncc;
	WCHAR szComponentIdW[256] ;
	int cnt ;


#ifdef _MBCS

	// @hootch@
	// 
	//
	size_t cchLen;
	StringCchLength(szComponentId, 256, &cchLen);
	cnt = MultiByteToWideChar(
		CP_ACP,						// code page
		0,							// character-type options
		szComponentId,				// string to map
		cchLen, // number of bytes in string
		szComponentIdW,				// wide-character buffer
		256							// size of buffer
	);
	if(cnt == 0) {
		// error
		return S_FALSE ;
	}

#endif

    // OBO_TOKEN specifies the entity on whose behalf this
    // component is being installed

    // set it to OBO_USER so that szComponentId will be installed
    // On-Behalf-Of "user"
    ZeroMemory (&OboToken, sizeof(OboToken));
    OboToken.Type = OBO_USER;

    hr = pnc->QueryNetCfgClass (pguidClass, IID_INetCfgClassSetup,
                                (void**)&pncClassSetup);
    if (SUCCEEDED(hr))
    {
#ifdef _MBCS
        hr = pncClassSetup->Install(szComponentIdW,
                                    &OboToken,
                                    NSF_POSTSYSINSTALL,
                                    0,       // <upgrade-from-build-num>
                                    NULL,    // answerfile name
                                    NULL,    // answerfile section name
                                    &pncc);
#else
        hr = pncClassSetup->Install(szComponentId,
                                    &OboToken,
                                    NSF_POSTSYSINSTALL,
                                    0,       // <upgrade-from-build-num>
                                    NULL,    // answerfile name
                                    NULL,    // answerfile section name
                                    &pncc);
#endif
        if (S_OK == hr)
        {
            // we dont want to use pncc (INetCfgComponent), release it
            ReleaseObj(pncc);
        }

        ReleaseObj(pncClassSetup);
    }

    return hr;
}
HRESULT SetupRichSavedGamesW( WCHAR* strSavedGameExtension, WCHAR* strLaunchPath, 
                             WCHAR* strCommandLineToLaunchSavedGame ) 
{
    HKEY hKey = NULL;
    LONG lResult;
    DWORD dwDisposition;
    WCHAR strExt[256];
    WCHAR strType[256];
    WCHAR strCmdLine[256];
    WCHAR strTemp[512];
    size_t nStrLength = 0;

    // Validate args 
    if( strLaunchPath == NULL || strSavedGameExtension == NULL )
    {
        return E_INVALIDARG;
    }
    
    // Setup saved game extension arg - make sure there's a period at the start
    if( strSavedGameExtension[0] == L'.' )
    {
        StringCchCopy( strExt, 256, strSavedGameExtension );
        StringCchPrintf( strType, 256, L"%sType", strSavedGameExtension+1 );
    }
    else
    {
        StringCchPrintf( strExt, 256, L".%s", strSavedGameExtension );
        StringCchPrintf( strType, 256, L"%sType", strSavedGameExtension );
    }

    // Create default command line arg if none supplied
    if( strCommandLineToLaunchSavedGame )
        StringCchCopy( strCmdLine, 256, strCommandLineToLaunchSavedGame );
    else
        StringCchCopy( strCmdLine, 256, L"\"%1\"" );

    // Create file association & metadata regkeys
    lResult = RegCreateKeyEx( HKEY_CLASSES_ROOT, strExt, 0, NULL, 0, KEY_WRITE, NULL, &hKey, &dwDisposition );
    if( ERROR_SUCCESS == lResult ) 
    {
        // Create the following regkeys:
        //
        // [HKEY_CLASSES_ROOT\.ExampleGameSave]
        // (Default)="ExampleGameSaveFileType"
        //
        StringCchLength( strType, 256, &nStrLength );
        RegSetValueEx( hKey, L"", 0, REG_SZ, (BYTE*)strType, (DWORD)((nStrLength + 1)*sizeof(WCHAR)) );

        // Create the following regkeys:
        //
        // [HKEY_CLASSES_ROOT\.ExampleGameSave\ShellEx\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}]
        // (Default)="{4E5BFBF8-F59A-4e87-9805-1F9B42CC254A}"
        //
        HKEY hSubKey = NULL;
        lResult = RegCreateKeyEx( hKey, L"ShellEx\\{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}", 0, NULL, 0, KEY_WRITE, NULL, &hSubKey, &dwDisposition );
        if( ERROR_SUCCESS == lResult ) 
        {
            StringCchPrintf( strTemp, 512, L"{4E5BFBF8-F59A-4e87-9805-1F9B42CC254A}" );
            StringCchLength( strTemp, 256, &nStrLength );
            RegSetValueEx( hSubKey, L"", 0, REG_SZ, (BYTE*)strTemp, (DWORD)((nStrLength + 1)*sizeof(WCHAR)) );
        }
        if( hSubKey ) RegCloseKey( hSubKey );
    }
    if( hKey ) RegCloseKey( hKey );

    lResult = RegCreateKeyEx( HKEY_CLASSES_ROOT, strType, 0, NULL, 0, KEY_WRITE, NULL, &hKey, &dwDisposition );
    if( ERROR_SUCCESS == lResult ) 
    {
        // Create the following regkeys:
        //
        // [HKEY_CLASSES_ROOT\ExampleGameSaveFileType]
        // PreviewTitle="prop:System.Game.RichSaveName;System.Game.RichApplicationName"
        // PreviewDetails="prop:System.Game.RichLevel;System.DateChanged;System.Game.RichComment;System.DisplayName;System.DisplayType"
        //
        size_t nPreviewDetails = 0, nPreviewTitle = 0;
        WCHAR* strPreviewTitle = L"prop:System.Game.RichSaveName;System.Game.RichApplicationName";
        WCHAR* strPreviewDetails = L"prop:System.Game.RichLevel;System.DateChanged;System.Game.RichComment;System.ItemNameDisplay;System.ItemType";
        StringCchLength( strPreviewTitle, 256, &nPreviewTitle );
        StringCchLength( strPreviewDetails, 256, &nPreviewDetails );
        RegSetValueEx( hKey, L"PreviewTitle", 0, REG_SZ, (BYTE*)strPreviewTitle, (DWORD)((nPreviewTitle + 1)*sizeof(WCHAR)) );
        RegSetValueEx( hKey, L"PreviewDetails", 0, REG_SZ, (BYTE*)strPreviewDetails, (DWORD)((nPreviewDetails + 1)*sizeof(WCHAR)) );

        // Create the following regkeys:
        //
        // [HKEY_CLASSES_ROOT\ExampleGameSaveFileType\Shell\Open\Command]
        // (Default)=""%ProgramFiles%\ExampleGame.exe" "%1""
        //
        HKEY hSubKey = NULL;
        lResult = RegCreateKeyEx( hKey, L"Shell\\Open\\Command", 0, NULL, 0, KEY_WRITE, NULL, &hSubKey, &dwDisposition );
        if( ERROR_SUCCESS == lResult ) 
        {
            StringCchPrintf( strTemp, 512, L"%s %s", strLaunchPath, strCmdLine );
            StringCchLength( strTemp, 256, &nStrLength );
            RegSetValueEx( hSubKey, L"", 0, REG_SZ, (BYTE*)strTemp, (DWORD)((nStrLength + 1)*sizeof(WCHAR)) );
        }
        if( hSubKey ) RegCloseKey( hSubKey );
    }
    if( hKey ) RegCloseKey( hKey );

    // Create the following regkeys:
    //
    // [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\PropertySystem\PropertyHandlers\.ExampleGameSave]
    // (Default)="{ECDD6472-2B9B-4b4b-AE36-F316DF3C8D60}"
    //
    StringCchPrintf( strTemp, 512, L"Software\\Microsoft\\Windows\\CurrentVersion\\PropertySystem\\PropertyHandlers\\%s", strExt );
    lResult = RegCreateKeyEx( HKEY_LOCAL_MACHINE, strTemp, 0, NULL, 0, KEY_WRITE, NULL, &hKey, &dwDisposition );
    if( ERROR_SUCCESS == lResult ) 
    {
        StringCchCopy( strTemp, 512, L"{ECDD6472-2B9B-4B4B-AE36-F316DF3C8D60}" );
        StringCchLength( strTemp, 256, &nStrLength );
        RegSetValueEx( hKey, L"", 0, REG_SZ, (BYTE*)strTemp, (DWORD)((nStrLength + 1)*sizeof(WCHAR)) );
    }
    if( hKey ) RegCloseKey( hKey );

    return S_OK;
}
Example #9
0
DWORD APIENTRY NPLogonNotify(
	PLUID lpLogonId,
	LPCWSTR lpAuthentInfoType,
	LPVOID lpAuthentInfo,
	LPCWSTR lpPreviousAuthentInfoType,
	LPVOID lpPreviousAuthentInfo,
	LPWSTR lpStationName,
	LPVOID StationHandle,
	LPWSTR *lpLogonScript)
{
    char uname[MAX_USERNAME_LENGTH]="";
    char password[MAX_PASSWORD_LENGTH]="";
    char logonDomain[MAX_DOMAIN_LENGTH]="";
    char cell[256]="<non-integrated logon>";
    char homePath[MAX_PATH]="";
    char szLogonId[128] = "";

    MSV1_0_INTERACTIVE_LOGON *IL;

    DWORD code = 0, code2;

    int pw_exp;
    char *reason;
    char *ctemp;

    BOOLEAN interactive;
    BOOLEAN flag;
    DWORD LSPtype, LSPsize;
    HKEY NPKey;

    HWND hwndOwner = (HWND)StationHandle;

    BOOLEAN afsWillAutoStart;

    BOOLEAN lowercased_name = TRUE;

    LogonOptions_t opt; /* domain specific logon options */
    int retryInterval;
    int sleepInterval;

    /* Are we interactive? */
    interactive = (wcsicmp(lpStationName, L"WinSta0") == 0);

#ifdef DISABLE_NON_INTERACTIVE
    /* Do not do anything if the logon session is not interactive. */
    if (!interactive)
	return 0;
#endif

    (void) RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
                         0, KEY_QUERY_VALUE, &NPKey);
    LSPsize=sizeof(TraceOption);
    RegQueryValueEx(NPKey, REG_CLIENT_TRACE_OPTION_PARM, NULL,
                     &LSPtype, (LPBYTE)&TraceOption, &LSPsize);

    RegCloseKey (NPKey);

    DebugEvent("NPLogonNotify - LoginId(%d,%d)", lpLogonId->HighPart, lpLogonId->LowPart);

    /* Make sure the AFS Libraries are initialized */
    AfsLogonInit();

    /* Initialize Logon Script to none */
    *lpLogonScript=NULL;
    
    /* MSV1_0_INTERACTIVE_LOGON and KERB_INTERACTIVE_LOGON are equivalent for
     * our purposes */

    if ( wcsicmp(lpAuthentInfoType,L"MSV1_0:Interactive") && 
         wcsicmp(lpAuthentInfoType,L"Kerberos:Interactive") )
    {
        DebugEvent("Unsupported Authentication Info Type: %S",
                   lpAuthentInfoType);
        return 0;
    }

    IL = (MSV1_0_INTERACTIVE_LOGON *) lpAuthentInfo;

    /* Convert from Unicode to ANSI */

    /*TODO: Use SecureZeroMemory to erase passwords */
    if (!UnicodeStringToANSI(IL->UserName, uname, MAX_USERNAME_LENGTH) ||
	 !UnicodeStringToANSI(IL->Password, password, MAX_PASSWORD_LENGTH) ||
	 !UnicodeStringToANSI(IL->LogonDomainName, logonDomain, MAX_DOMAIN_LENGTH))
 	return 0;

    /* Make sure AD-DOMANS sent from login that is sent to us is striped */
    ctemp = strchr(uname, '@');
    if (ctemp) *ctemp = 0;

    /* is the name all lowercase? */
    for ( ctemp = uname; *ctemp ; ctemp++) {
        if ( !islower(*ctemp) ) {
            lowercased_name = FALSE;
            break;
        }
    }

    /*
     * Get Logon options
     */

    GetDomainLogonOptions( lpLogonId, uname, logonDomain, &opt );
    retryInterval = opt.retryInterval;
    sleepInterval = opt.sleepInterval;
    *lpLogonScript = opt.logonScript;

    if (retryInterval < sleepInterval)
        sleepInterval = retryInterval;

    DebugEvent("Got logon script: %S",opt.logonScript);

    afsWillAutoStart = AFSWillAutoStart();

    DebugEvent("LogonOption[%x], Service AutoStart[%d]",
                opt.LogonOption,afsWillAutoStart);
    
    /* Check for zero length password if integrated logon*/
    if ( ISLOGONINTEGRATED(opt.LogonOption) )  {
        if ( password[0] == 0 ) {
            DebugEvent0("Password is the empty string");
            code = GT_PW_NULL;
            reason = "zero length password is illegal";
            code=0;
        }

        /* Get cell name if doing integrated logon.  
           We might overwrite this if we are logging into an AD realm and we find out that
           the user's home dir is in some other cell. */
        DebugEvent("About to call cm_GetRootCellName(%s)",cell);
        code = cm_GetRootCellName(cell);
        if (code < 0) { 
            DebugEvent0("Unable to obtain Root Cell");
            code = KTC_NOCELL;
            reason = "unknown cell";
            code=0;
        } else {
            DebugEvent("Cell is %s",cell);
        }       

        /* We get the user's home directory path, if applicable, though we can't lookup the
           cell right away because the client service may not have started yet. This call
           also sets the AD_REALM flag in opt.flags if applicable. */
        if (ISREMOTE(opt.flags)) {
            DebugEvent0("Is Remote");
            GetAdHomePath(homePath,MAX_PATH,lpLogonId,&opt);
        }
    }

    /* loop until AFS is started. */
    if (afsWillAutoStart) {
	while (IsServiceRunning() || IsServiceStartPending()) {
	    DebugEvent("while(autostart) LogonOption[%x], Service AutoStart[%d]",
			opt.LogonOption,afsWillAutoStart);

	    if (ISADREALM(opt.flags)) {
		code = GetFileCellName(homePath,cell,256);
		if (!code) {
		    DebugEvent("profile path [%s] is in cell [%s]",homePath,cell);
		}
		/* Don't bail out if GetFileCellName failed.
		 * The home dir may not be in AFS after all. 
		 */
	    } else
		code=0;
		
	    /* if Integrated Logon  */
	    if (ISLOGONINTEGRATED(opt.LogonOption))
	    {			
		if ( KFW_is_available() ) {
		    SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, "");
                    if (opt.realm) {
			char * principal, *p;
			size_t len, tlen;

			StringCchLength(opt.realm, MAX_DOMAIN_LENGTH, &tlen);
			len = tlen;
			StringCchLength(uname, MAX_USERNAME_LENGTH, &tlen);
			len += tlen + 2;

			/* tlen is now the length of uname in characters */
			principal = (char *)malloc(len * sizeof(char));
			if ( principal ) {
			    StringCchCopy(principal, len, uname);
			    p = principal + tlen;
			    *p++ = '@';
                            StringCchCopy(p, len - tlen -1, opt.realm);
                            code = KFW_AFS_get_cred(principal, cell, password, 0, opt.smbName, &reason);
                            DebugEvent("KFW_AFS_get_cred  uname=[%s] smbname=[%s] cell=[%s] code=[%d]",
					    principal,opt.smbName,cell,code);
			    free(principal);
			}
                    } else {
                        code = KFW_AFS_get_cred(uname, cell, password, 0, opt.smbName, &reason);
                        DebugEvent("KFW_AFS_get_cred  uname=[%s] smbname=[%s] cell=[%s] code=[%d]",
                                    uname,opt.smbName,cell,code);
                    }
		    SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, NULL);
		    if (code == 0 && opt.theseCells) { 
			char * principal, *p;
			size_t len, tlen;

			StringCchLength(opt.realm ? opt.realm : cell, MAX_DOMAIN_LENGTH, &tlen);
			len = tlen;
			StringCchLength(uname, MAX_USERNAME_LENGTH, &tlen);
			len += tlen + 2;

			/* tlen is now the length of uname in characters */
			principal = (char *)malloc(len * sizeof(char));
			if ( principal ) {
			    StringCchCopy(principal, len, uname);
			    p = principal + tlen;
			    *p++ = '@';
                            if (opt.realm) {
                                StringCchCopy(p, len - tlen -1, opt.realm);
                            } else {
                                StringCchCopy(p, len - tlen - 1, cell);
                                for ( ;*p; p++) {
                                    *p = toupper(*p);
                                }
                            }
			    p = opt.theseCells;
			    while ( *p ) {
                                if ( cm_stricmp_utf8(p, cell) ) {
                                    SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, "");
                                    code2 = KFW_AFS_get_cred(principal, p, 0, 0, opt.smbName, &reason);
                                    SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, NULL);
                                    DebugEvent("KFW_AFS_get_cred  uname=[%s] smbname=[%s] cell=[%s] code=[%d]",
                                               principal,opt.smbName,p,code2);
                                }
				p += strlen(p) + 1;
			    }
			    free(principal);
			}
		    }
		} else {
		    code = ka_UserAuthenticateGeneral2(KA_USERAUTH_VERSION+KA_USERAUTH_AUTHENT_LOGON,
							uname, "", cell, password, opt.smbName, 0, &pw_exp, 0,
							&reason);
		    DebugEvent("AFS AfsLogon - (INTEGRATED only)ka_UserAuthenticateGeneral2 Code[%x] uname[%s] smbname=[%s] Cell[%s] PwExp=[%d] Reason=[%s]",
				code,uname,opt.smbName,cell,pw_exp,reason?reason:"");
		}       
		if ( code && code != KTC_NOCM && code != KTC_NOCMRPC && !lowercased_name ) {
		    for ( ctemp = uname; *ctemp ; ctemp++) {
			*ctemp = tolower(*ctemp);
		    }
		    lowercased_name = TRUE;
		    goto sleeping;
		}

		/* is service started yet?*/

		/* If we've failed because the client isn't running yet and the
		 * client is set to autostart (and therefore it makes sense for
		 * us to wait for it to start) then sleep a while and try again. 
		 * If the error was something else, then give up. */
		if (code != KTC_NOCM && code != KTC_NOCMRPC)
		    break;
	    }
	    else {  
		/*JUST check to see if its running*/
		if (IsServiceRunning())
		    break;
		if (!IsServiceStartPending()) {
		    code = KTC_NOCMRPC;
		    reason = "AFS Service start failed";
		    break;
		}
	    }

	    /* If the retry interval has expired and we still aren't
	     * logged in, then just give up if we are not in interactive
	     * mode or the failSilently flag is set, otherwise let the
	     * user know we failed and give them a chance to try again. */
	    if (retryInterval <= 0) {
		reason = "AFS not running";
		if (!interactive || opt.failSilently)
		    break;
		flag = MessageBox(hwndOwner,
				   "AFS is still starting.  Retry?",
				   "AFS Logon",
				   MB_ICONQUESTION | MB_RETRYCANCEL);
		if (flag == IDCANCEL)
		    break;

		/* Wait just a little while and try again */
		retryInterval = opt.retryInterval;
	    }

	  sleeping:
	    Sleep(sleepInterval * 1000);
	    retryInterval -= sleepInterval;
	}
    }
    DebugEvent0("while loop exited");

    /* remove any kerberos 5 tickets currently held by the SYSTEM account
     * for this user 
     */

    if (ISLOGONINTEGRATED(opt.LogonOption) && KFW_is_available()) {
#ifdef KFW_LOGON
	sprintf(szLogonId,"%d.%d",lpLogonId->HighPart, lpLogonId->LowPart);
	KFW_AFS_copy_cache_to_system_file(uname, szLogonId);
#endif
	KFW_AFS_destroy_tickets_for_principal(uname);
    }

    if (code) {
	char msg[128];
	HANDLE h;
	char *ptbuf[1];

	StringCbPrintf(msg, sizeof(msg), "Integrated login failed: %s", reason);

	if (ISLOGONINTEGRATED(opt.LogonOption) && interactive && !opt.failSilently)
	    MessageBox(hwndOwner, msg, "AFS Logon", MB_OK);

	h = RegisterEventSource(NULL, AFS_LOGON_EVENT_NAME);
	ptbuf[0] = msg;
	ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1008, NULL,
		     1, 0, ptbuf, NULL);
	DeregisterEventSource(h);
	    
        code = MapAuthError(code);
        SetLastError(code);

        if (ISLOGONINTEGRATED(opt.LogonOption) && (code!=0))
        {
            if (*lpLogonScript)
                LocalFree(*lpLogonScript);
            *lpLogonScript = NULL;
            if (!afsWillAutoStart)	// its not running, so if not autostart or integrated logon then just skip
                code = 0;
        }
    }

    if (opt.theseCells) free(opt.theseCells);
    if (opt.smbName) free(opt.smbName);
    if (opt.realm) free(opt.realm);

    DebugEvent("AFS AfsLogon - Exit","Return Code[%x]",code);
    return code;
}       
Example #10
0
BOOL ScanUDisk(IN LPCTSTR lpUDisk,IN BOOL bDelSuspicious)
{
	size_t dwLen = 0;
	size_t dwDirNameLen = 0;

	LPTSTR lpSearchDisk = NULL;		//The U Disk to search
	LPTSTR lpDirName = NULL;		//Full file path
	LPTSTR lpFileName = NULL;		//File with the same name as a directory, but has a ".exe" type extension

	HANDLE hFind = INVALID_HANDLE_VALUE;
	WIN32_FIND_DATA FindFileData;

	//Build the search string
	StringCchLength(lpUDisk,20/*set this to 4 later*/,&dwLen);
	lpSearchDisk = (LPTSTR)LocalAlloc(LPTR,(dwLen+2) * sizeof(TCHAR));
	StringCchPrintf(lpSearchDisk,dwLen+3,TEXT("%s%s"),lpUDisk,TEXT("*"));

	hFind = FindFirstFile(lpSearchDisk, &FindFileData);
	if (hFind != INVALID_HANDLE_VALUE)
	{
		do
		{
			if ( IsDotsDirectory(FindFileData.cFileName) )
				continue;

			//construct the directory or file full path
			StringCchLength(FindFileData.cFileName,MAX_PATH,&dwDirNameLen);	//get the directory name length
			dwDirNameLen += dwLen + 2;
			lpDirName = (LPTSTR)LocalAlloc(LPTR,dwDirNameLen * sizeof(TCHAR));	
			StringCchPrintf(lpDirName,LocalSize((HLOCAL)lpDirName),TEXT("%s%s"),lpUDisk,FindFileData.cFileName);
			
			//construct the full suspicious file path
			lpFileName = (LPTSTR)LocalAlloc(LPTR,(dwDirNameLen + 4) * sizeof(TCHAR));
			StringCchPrintf(lpFileName,LocalSize((HLOCAL)lpFileName),TEXT("%s.exe"),lpDirName);

			if ( (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY )
			{
				//it's a directory
				SetFileAttributes(lpDirName,FindFileData.dwFileAttributes & ~FILE_ATTRIBUTE_HIDDEN & ~FILE_ATTRIBUTE_SYSTEM);
				
				if( bDelSuspicious )
				{
					//delete suspicious file
					DelSuspiciousFile(lpFileName,FindFileData.dwFileAttributes);
				}
			}
			else		//it's a file
			{	
				if( bDelSuspicious )
				{
					//delete "autorun.inf"
					if( !_tcsicmp(FindFileData.cFileName,TEXT("autorun.inf")) )
						DelSuspiciousFile(lpDirName,FILE_ATTRIBUTE_NORMAL);
						
					//delete other malicious files
					if( IsFileMalicious(FindFileData.cFileName) )
					{						
						DelSuspiciousFile(lpDirName,FindFileData.dwFileAttributes);
					}
				}
			}

		} while (FindNextFile(hFind, &FindFileData));
	}
	FindClose(hFind);
	hFind = NULL;

	LocalFree((HLOCAL)lpDirName);
	LocalFree((HLOCAL)lpSearchDisk);
	lpSearchDisk = NULL;
	lpDirName = NULL;	
	
	return TRUE;
}
/**
 @helper_function="HlprEthernetMACAddressStringIsValidFormat"
 
   Purpose: Determine if a string may be an Ethernet MAC address by verifying the string:       <br>
               is at least 17 characters                                                        <br>
               has at least 5 colons(':') or hyphens('-')                                       <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref:                                                                                    <br>
*/
BOOLEAN HlprEthernetMACAddressStringIsValidFormat(_In_ PCWSTR pEthernetMACAddressString)
{
   BOOLEAN isEthernetMACAddress = FALSE;

   if(pEthernetMACAddressString)
   {
      UINT32 status       = NO_ERROR;
      size_t stringLength = 0;

      status = StringCchLength(pEthernetMACAddressString,
                               STRSAFE_MAX_CCH,
                               &stringLength);
      if(status != ERROR_SUCCESS)
      {
         HlprLogError(L"HlprEthernetMACAddressStringIsValidFormat : StringCchLength() [status: %#x]",
                      status);

         HLPR_BAIL;
      }
      else if(stringLength <= IEEE_802_ADDRESS_STRING_BUFFER)
      {
         if(wcschr(pEthernetMACAddressString,
                   L':'))
         {
            UINT32 numColons = 0;

            for(UINT32 index = 0;
                index < stringLength;
                index++)
            {
               if(pEthernetMACAddressString[index] == L':')
                 numColons++;
            }

            if(numColons == 5)
               isEthernetMACAddress = TRUE;
         }
         else
         {
            if(wcschr(pEthernetMACAddressString,
                      L'-'))
            {
               UINT32 numHyphens = 0;

               for(UINT32 index = 0;
                   index < stringLength;
                   index++)
               {
                  if(pEthernetMACAddressString[index] == L'-')
                     numHyphens++;
               }

               if(numHyphens == 5)
                  isEthernetMACAddress = TRUE;
            }
         }
      }
   }

   HLPR_BAIL_LABEL:

   if(!isEthernetMACAddress)
      HlprLogError(L"HlprEthernetMACAddressStringIsValidFormat() [status: %#x][pEthernetMACAddressString: %s]",
                   ERROR_INVALID_DATA,
                   pEthernetMACAddressString);

   return isEthernetMACAddress;
}
Example #12
0
/*!
	選択範囲を指定文字列で塗りつぶす
	@param[in]	ptBrush	ブラシ文字列・NULLなら空白
	@param[in]	pdDot	キャレットドット位置・書き換える必要がある
	@param[in]	pdLine	行番号・書き換える必要がある
	@return	非0塗った 0してない
*/
INT DocSelectedBrushFilling( LPTSTR ptBrush, PINT pdDot, PINT pdLine )
{
	UINT_PTR	iMozis;
	UINT_PTR	cchSize;
	INT			i, j, dBeginX = 0, dBeginY = 0;
	INT			iLct, dTgtDot, dBgnDot, dNowDot;
	BOOLEAN		bFirst;

	LPTSTR		ptReplc = NULL, ptDeled;
//	INT			dZenSp, dHanSp, dUniSp;

	wstring		wsBuffer;
	LETR_ITR	itLtr, itEnd, itHead, itTail;

	LINE_ITR	itLine;

	bFirst = TRUE;

	i = (*gitFileIt).vcCont.at( gixFocusPage ).dSelLineTop;
	j = (*gitFileIt).vcCont.at( gixFocusPage ).dSelLineBottom;
	TRACE( TEXT("範囲確認[T%d - B%d]"), i, j );
	if( 0 > i ){	return 0;	}	//	選択範囲が無かった

	dBeginY = i;	//	選択肢のある行
	dBeginX = 0;

	//	壱行ずつ処理していく
	itLine = (*gitFileIt).vcCont.at( gixFocusPage ).ltPage.begin();
	std::advance( itLine, i );

	for( iLct = i; j >= iLct; iLct++, itLine++ )
	{
		//	文字数確認して
		iMozis = itLine->vcLine.size( );
		if( 0 < iMozis )
		{
			itLtr = itLine->vcLine.begin(  );
			itEnd = itLine->vcLine.end(  );
			itHead = itEnd;
			itTail = itEnd;

			dBgnDot = 0;
			dTgtDot = 0;

			//	最初の選択部分を検索
			for( ; itLtr != itEnd; itLtr++ )
			{
				if( CT_SELECT & itLtr->mzStyle )
				{
					itHead =  itLtr;
					dTgtDot = itLtr->rdWidth;
					itLtr++;	//	次の文字を参照
					break;
				}

				dBgnDot += itLtr->rdWidth;
			}
			if( iLct == i ){	dBeginX = dBgnDot;	}	//	意味があるのは最後のところ

			//	選択されてない所まで検索
			for( ; itLtr != itEnd; itLtr++ )
			{
				if( !(CT_SELECT & itLtr->mzStyle) )
				{
					itTail =  itLtr;
					break;
				}
				dTgtDot += itLtr->rdWidth;	//	ドット数を確認
			}

			//	当てはめるアレを計算する
			if( ptBrush )
			{
				ptReplc = BrushStringMake( dTgtDot, ptBrush );
			}
			else	//	空白指定ということ
			{
				ptReplc = DocPaddingSpaceMake( dTgtDot );
			}

			//	ここで、埋め文字列が作成不可なら、この行の処理は飛ばす
			if( !(ptReplc) )	continue;


			//	該当部分の内容を記録<アンドゥ用
			wsBuffer.clear();
			for( itLtr = itHead; itLtr != itTail; itLtr++ )
			{
				wsBuffer += itLtr->cchMozi;
			}

			cchSize = wsBuffer.size( ) + 1;
			ptDeled = (LPTSTR)malloc( cchSize * sizeof(TCHAR) );
			StringCchCopy( ptDeled, cchSize, wsBuffer.c_str( ) );

			//	該当部分を削除
			itLine->vcLine.erase( itHead, itTail );
			//	ブラシ文字列で埋める
			StringCchLength( ptReplc, STRSAFE_MAX_CCH, &cchSize );
			dNowDot = dBgnDot;
			DocStringAdd( &dNowDot, &iLct, ptReplc, cchSize );

			SqnAppendString( &((*gitFileIt).vcCont.at( gixFocusPage ).stUndoLog), DO_DELETE, ptDeled, dBgnDot, iLct, bFirst );	bFirst = FALSE;
			SqnAppendString( &((*gitFileIt).vcCont.at( gixFocusPage ).stUndoLog), DO_INSERT, ptReplc, dBgnDot, iLct, bFirst );

			FREE( ptDeled );

			FREE( ptReplc );

			ViewRedrawSetLine( iLct );
		}

	}

	ViewSelPageAll( -1 );	//	選択範囲無くなる

	//	カーソル位置移動せないかん
	*pdDot = dBeginX;	*pdLine = dBeginY;

	return 1;
}
Example #13
0
KHMEXP khm_int32 KHMAPI
kcdb_identpro_canon_name_ex(khm_handle vidpro,
                            const wchar_t * name_in,
                            wchar_t * name_out,
                            khm_size * cb_name_out)
{
    khm_handle sub;
    kcdb_ident_name_xfer namex;
    wchar_t name_tmp[KCDB_IDENT_MAXCCH_NAME];
    khm_int32 rv = KHM_ERROR_SUCCESS;
    khm_size cch;

    if(cb_name_out == 0 ||
       FAILED(StringCchLength(name_in, KCDB_IDENT_MAXCCH_NAME, &cch)))
        return KHM_ERROR_INVALID_NAME;

    sub = identpro_get_sub(vidpro);

    if(sub != NULL) {
        ZeroMemory(&namex, sizeof(namex));
        ZeroMemory(name_tmp, sizeof(name_tmp));

        namex.name_src = name_in;
        namex.name_dest = name_tmp;
        namex.cb_name_dest = sizeof(name_tmp);
        namex.result = KHM_ERROR_NOT_IMPLEMENTED;

        rv = kmq_send_sub_msg(sub,
                              KMSG_IDENT,
                              KMSG_IDENT_CANON_NAME,
                              0,
                              (void *) &namex);

        if(KHM_SUCCEEDED(namex.result)) {
            const wchar_t * name_result;
            khm_size cb;

            if(name_in[0] != 0 && name_tmp[0] == 0)
                name_result = name_tmp;
            else
                name_result = name_in;
			
            if(FAILED(StringCbLength(name_result, KCDB_IDENT_MAXCB_NAME, &cb)))
                rv = KHM_ERROR_UNKNOWN;
            else {
                cb += sizeof(wchar_t);
                if(name_out == 0 || *cb_name_out < cb) {
                    rv = KHM_ERROR_TOO_LONG;
                    *cb_name_out = cb;
                } else {
                    StringCbCopy(name_out, *cb_name_out, name_result);
                    *cb_name_out = cb;
                    rv = KHM_ERROR_SUCCESS;
                }
            }
        }
    } else {
        rv = KHM_ERROR_NO_PROVIDER;
    }

    return rv;
}
Example #14
0
LRESULT WINAPI MessageHandlerProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch(message)
	{
		case LM_GETREVID:
		{
			UINT uLength;
			StringCchPrintf((char*)lParam, 64, "%s %s", V_NAME, V_VERSION);
			
			if (SUCCEEDED(StringCchLength((char*)lParam, 64, &uLength)))
				return uLength;

			lParam = NULL;
			return 0;
		}
		
		case LM_REFRESH:
		{
			StringList labelNames = GetRCNameList("Labels");

			// refresh the "AllLabels" configuration
			delete defaultSettings;
			defaultSettings = new LabelSettings();

			for(LabelListIterator iter = labelList.begin(); iter != labelList.end(); iter++)
			{
				if(!(*iter)->getBox())
				{
					// destroy all labels that no longer exist and that are not in a box
					for(StringListIterator it = labelNames.begin(); it != labelNames.end(); it++)
					{
						if(_stricmp((*it).c_str(), (*iter)->getName().c_str()) == 0)
							break;
					}
					if (it == labelNames.end())
					{
						labelList.remove(*iter);
						delete *iter;
						continue;
					}
				}

				// we can reconfigure all other labels, even if they are "boxed"
				(*iter)->reconfigure();
			}

			// create the rest
			for(StringListIterator it = labelNames.begin(); it != labelNames.end(); it++)
			{
				Label *label = lookupLabel(*it);
				
				if (!label) 
				{
					label = new Label(*it);
					label->load(hInstance);
					labelList.insert(labelList.end(), label);
				}
			}
			return 0;
		}

		case LM_UPDATEBG:
		{
			PaintDesktopEx(0, 0, 0, 0, 0, 0, 0, TRUE);

			for(LabelListIterator i = labelList.begin(); i != labelList.end(); i++)
			{
				Label *label = *i;

				if(label->getBox() == 0)
					label->repaint(true);
			}

			return 0;
		}

		case WM_DISPLAYCHANGE:
		case WM_SETTINGCHANGE:
		{
			PostMessage(hWnd, LM_UPDATEBG, 0, 0);
			return 0;
		}
	}

	return DefWindowProc(hWnd, message, wParam, lParam);
}
Example #15
0
/*!
	ユーザ定義のアレを読み込む
	@param[in]	hWnd	メインウインドウハンドル
	@param[in]	bFirst	今回が最初であるか
	@return	非0中身取った処理した 0ファイルなかった
*/
INT UserDefInitialise( HWND hWnd, UINT bFirst )
{
	CONST WCHAR rtHead = 0xFEFF;	//	ユニコードテキストヘッダ
	WCHAR	rtUniBuf;

	HANDLE	hFile;
	DWORD	readed;

	LPVOID	pBuffer;	//	文字列バッファ用ポインター
	INT		iByteSize;

	LPTSTR	ptString;
	LPSTR	pcText;
	UINT	cchSize;

	if( bFirst )	//	最初ならパス作っておく
	{
		ZeroMemory( gatUsDfPath, sizeof(gatUsDfPath) );
		StringCchCopy( gatUsDfPath, MAX_PATH, ExePathGet() );
		PathAppend( gatUsDfPath, TEMPLATE_DIR );
		PathAppend( gatUsDfPath, USER_ITEM_FILE );
	}

	hFile = CreateFile( gatUsDfPath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
	if( INVALID_HANDLE_VALUE == hFile ){	return 0;	}

	//	今の内容破棄
	UserDefObliterate( hWnd );

	iByteSize = GetFileSize( hFile, NULL );
	pBuffer = malloc( iByteSize + 2 );
	ZeroMemory( pBuffer, iByteSize + 2 );
	//	中身をいただく
	SetFilePointer( hFile, 0, NULL, FILE_BEGIN );
	ReadFile( hFile, pBuffer, iByteSize, &readed, NULL );
	CloseHandle( hFile );	//	内容全部取り込んだから開放

	//	ユニコードチャック
	CopyMemory( &rtUniBuf, pBuffer, 2 );
	if( rtHead == rtUniBuf )	//	ユニコードヘッダがあれば
	{
		ptString = (LPTSTR)pBuffer;
		ptString++;	//	ユニコードヘッダ分進めておく
	}
	else
	{
		pcText = (LPSTR)pBuffer;
		//	シフトJISを開く場合、&#0000;の部分をどうにかせんといかん
		ptString = SjisDecodeAlloc( pcText );	//	SJISの内容をユニコードにする

		FREE( pBuffer );	//	こっちで開放
		pBuffer = ptString;	//	ポイントするところを変更
	}

	StringCchLength( ptString, STRSAFE_MAX_CCH, &cchSize );

	//	ASTじゃなきゃダメ
	if( !( StrCmpN( AST_SEPARATERW, ptString, 4 ) ) )
	{
		DocStringSplitAST( ptString , cchSize, UserDefItemLoad );
	}

	FREE( pBuffer );

	UserDefAppendMenu( hWnd );

	return 1;
}
Example #16
0
//+---------------------------------------------------------------------------
//
// Function:  HrInstallNetComponent
//
// Purpose:   Install the specified net component
//
// Arguments:
//    szComponentId [in]  component to install
//    nc            [in]  class of the component
//    szInfFullPath [in]  full path to primary INF file
//                        required if the primary INF and other
//                        associated files are not pre-copied to
//                        the right destination dirs.
//                        Not required when installing MS components
//                        since the files are pre-copied by
//                        Windows NT Setup.
//
// Returns:   S_OK or NETCFG_S_REBOOT on success, otherwise an error code
//
// Notes:
//
HRESULT HrInstallNetComponent(IN PCTSTR szComponentId,
                              IN enum NetClass nc,
                              IN PCTSTR szInfFullPath)
{
    HRESULT hr=S_OK;
    INetCfg* pnc;

    // cannot install net adapters this way. they have to be
    // enumerated/detected and installed by PnP

    if ((nc == NC_NetProtocol) ||
        (nc == NC_NetService) ||
        (nc == NC_NetClient))
    {
        LogPrintf(_T("Trying to install '%s'...\n"), szComponentId);

        // if full path to INF has been specified, the INF
        // needs to be copied using Setup API to ensure that any other files
        // that the primary INF copies will be correctly found by Setup API
        //
		size_t cchPath;
		StringCchLength(szInfFullPath, MAX_PATH, &cchPath);
        if (szInfFullPath && cchPath)
        {
            TCHAR szInfNameAfterCopy[MAX_PATH+1];
            if (SetupCopyOEMInf(
                    szInfFullPath,
                    NULL,               // other files are in the
                                        // same dir. as primary INF
                    SPOST_PATH,         // first param. contains path to INF
                    0,                  // default copy style
                    szInfNameAfterCopy, // receives the name of the INF
                                        // after it is copied to %windir%\inf
                    MAX_PATH,           // max buf. size for the above
                    NULL,               // receives required size if non-null
                    NULL))              // optionally retrieves filename
                                        // component of szInfNameAfterCopy
            {
                LogPrintf(_T("...%s was copied to %s\n"),
                            szInfFullPath,
                            szInfNameAfterCopy);
            }
            else
            {
                DWORD dwError = GetLastError();
				LogPrintf(_T("Error on SetupCopyOEMInf, error %d"), dwError);
                hr = HRESULT_FROM_WIN32(dwError);
            }
        }

        if (S_OK == hr)
        {
            // get INetCfg interface
            hr = HrGetINetCfg(TRUE, &pnc);

            if (SUCCEEDED(hr))
            {
                // install szComponentId
		        LogPrintf(_T("Installing %s\n"), szComponentId);
                hr = HrInstallNetComponent(pnc, szComponentId,
                                           c_aguidClass[nc]);
		        LogPrintf(_T("Installed successfully\n"));
                if (SUCCEEDED(hr))
                {
                    // Apply the changes
			        LogPrintf(_T("Applying changes\n"));
                    hr = pnc->Apply();
				    LogPrintf(_T("Applied successfully\n"));
                }

                // release INetCfg
                (void) HrReleaseINetCfg(TRUE, pnc);
            }
        }
        // show success/failure message
        ShowHrMessage(hr);
    }

    return hr;
}
Example #17
0
KHMEXP khm_int32   KHMAPI
kmm_register_plugin(kmm_plugin_reg * plugin, khm_int32 config_flags)
{
    khm_int32 rv = KHM_ERROR_SUCCESS;
    khm_handle csp_plugin = NULL;
    khm_handle csp_module = NULL;
    size_t cch;

    /* avoid accidently creating the module key if it doesn't exist */
    config_flags &= ~KHM_FLAG_CREATE;

    if((plugin == NULL) ||
       (plugin->dependencies &&
        KHM_FAILED(multi_string_length_cch(plugin->dependencies,
                                           KMM_MAXCCH_DEPS, &cch))) ||
       FAILED(StringCchLength(plugin->module, KMM_MAXCCH_NAME, &cch)) ||
       (plugin->description &&
        FAILED(StringCchLength(plugin->description,
                               KMM_MAXCCH_DESC, &cch))) ||
       FAILED(StringCchLength(plugin->name, KMM_MAXCCH_NAME, &cch)))
    {
        return KHM_ERROR_INVALID_PARAM;
    }

    /* note that we are retaining the length of the plugin name in
       chars in cch */
    cch ++;

#define CKRV if(KHM_FAILED(rv)) goto _exit

    rv = kmm_get_plugin_config(plugin->name,
                               config_flags | KHM_FLAG_CREATE, &csp_plugin);
    CKRV;

    /* should fail if the module key doesn't exist */
    rv = kmm_get_module_config(plugin->module, config_flags, &csp_module);
    CKRV;

    /*TODO: Make sure that the module registration is in the same
      config store as the one in which the plugin is going to be
      registered */

    rv = khc_write_string(csp_plugin, L"Module", plugin->module);
    CKRV;
    if(plugin->description) {
        rv = khc_write_string(csp_plugin, L"Description", plugin->description);
        CKRV;
    }

    if(plugin->dependencies) {
        rv = khc_write_multi_string(csp_plugin, L"Dependencies",
                                    plugin->dependencies);
        CKRV;
    }

    rv = khc_write_int32(csp_plugin, L"Type", plugin->type);
    CKRV;
    rv = khc_write_int32(csp_plugin, L"Disabled",
                         !!(plugin->flags & KMM_PLUGIN_FLAG_DISABLED));
    CKRV;

    {
        khm_size cb = 0;
        wchar_t * pl = NULL;
        size_t scb = 0;

        rv = khc_read_multi_string(csp_module, L"PluginList", NULL, &cb);
        if(rv != KHM_ERROR_TOO_LONG) {
            if (rv == KHM_ERROR_NOT_FOUND) {

                scb = cb = (cch + 1) * sizeof(wchar_t);
                pl = PMALLOC(cb);
                multi_string_init(pl, cb);
                rv = KHM_ERROR_SUCCESS;

                goto add_plugin_to_list;

            } else {
                goto _exit;
            }
        }

        cb += cch * sizeof(wchar_t);
        scb = cb;

        pl = PMALLOC(cb);

        rv = khc_read_multi_string(csp_module, L"PluginList", pl, &cb);
        if(KHM_FAILED(rv)) {
            if(pl)
                PFREE(pl);
            goto _exit;
        }

    add_plugin_to_list:

        if(!multi_string_find(pl, plugin->name, 0)) {
            multi_string_append(pl, &scb, plugin->name);
            rv = khc_write_multi_string(csp_module, L"PluginList", pl);
        }

        PFREE(pl);
        CKRV;
    }

#undef CKRV

_exit:
    if(csp_plugin)
        khc_close_space(csp_plugin);
    if(csp_module)
        khc_close_space(csp_module);

    return rv;
}
Example #18
0
    0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
    0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x1a, 0x1b,
    0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
    0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
    0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33
};

// allocates output buffer with new
// delete with delete[]
// suprisingly, this algorithm works in a unicode build as well
_Check_return_ HRESULT Base64Decode(_In_z_ LPCTSTR szEncodedStr, _Inout_ size_t* cbBuf, _Out_ _Deref_post_cap_(*cbBuf) LPBYTE* lpDecodedBuffer)
{
    HRESULT hRes = S_OK;
    size_t	cchLen = 0;

    EC_H(StringCchLength(szEncodedStr, STRSAFE_MAX_CCH, &cchLen));

    if (cchLen % 4) return MAPI_E_INVALID_PARAMETER;

    // look for padding at the end
    static const TCHAR szPadding[] = _T("=="); // STRING_OK
    const TCHAR* szPaddingLoc = NULL;
    szPaddingLoc = _tcschr(szEncodedStr, szPadding[0]);
    size_t cchPaddingLen = 0;
    if (NULL != szPaddingLoc)
    {
        // check padding length
        EC_H(StringCchLength(szPaddingLoc, STRSAFE_MAX_CCH, &cchPaddingLen));
        if (cchPaddingLen >= 3) return MAPI_E_INVALID_PARAMETER;

        // check for bad characters after the first '='