/* Internal function to send a message via Extended MAPI. Wrapper around the Simple MAPI function MAPISendMail. */ static ULONG sendmail_extended_mapi(LHANDLE mapi_session, ULONG_PTR uiparam, lpMapiMessageW message, FLAGS flags) { ULONG tags[] = {1, 0}; char *subjectA = NULL, *bodyA = NULL; ULONG retval = MAPI_E_FAILURE; IMAPISession *session = NULL; BOOL unicode_aware = FALSE; IMAPITable* msg_table; LPSRowSet rows = NULL; IMsgStore* msg_store; IMAPIFolder* folder = NULL, *draft_folder = NULL; LPENTRYID entry_id; LPSPropValue props; ULONG entry_len; DWORD obj_type; IMessage* msg; ULONG values; HRESULT ret; TRACE("Using Extended MAPI wrapper for MAPISendMail\n"); /* Attempt to log on via Extended MAPI */ ret = MAPILogonEx(0, NULL, NULL, MAPI_EXTENDED | MAPI_USE_DEFAULT | MAPI_NEW_SESSION, &session); TRACE("MAPILogonEx: %x\n", ret); if (ret != S_OK) { retval = MAPI_E_LOGIN_FAILURE; goto cleanup; } /* Open the default message store */ if (IMAPISession_GetMsgStoresTable(session, 0, &msg_table) == S_OK) { /* We want the default store */ SizedSPropTagArray(2, columns) = {2, {PR_ENTRYID, PR_DEFAULT_STORE}}; /* Set the columns we want */ if (IMAPITable_SetColumns(msg_table, (LPSPropTagArray) &columns, 0) == S_OK) { while (1) { if (IMAPITable_QueryRows(msg_table, 1, 0, &rows) != S_OK) { MAPIFreeBuffer(rows); rows = NULL; } else if (rows->cRows != 1) { FreeProws(rows); rows = NULL; } else { /* If it's not the default store, try the next row */ if (!rows->aRow[0].lpProps[1].Value.b) { FreeProws(rows); continue; } } break; } } IMAPITable_Release(msg_table); } /* Did we manage to get the right store? */ if (!rows) goto logoff; /* Open the message store */ IMAPISession_OpenMsgStore(session, 0, rows->aRow[0].lpProps[0].Value.bin.cb, (ENTRYID *) rows->aRow[0].lpProps[0].Value.bin.lpb, NULL, MDB_NO_DIALOG | MAPI_BEST_ACCESS, &msg_store); /* We don't need this any more */ FreeProws(rows); /* Check if the message store supports Unicode */ tags[1] = PR_STORE_SUPPORT_MASK; ret = IMsgStore_GetProps(msg_store, (LPSPropTagArray) tags, 0, &values, &props); if ((ret == S_OK) && (props[0].Value.l & STORE_UNICODE_OK)) unicode_aware = TRUE; else { /* Don't convert to ANSI */ if (flags & MAPI_FORCE_UNICODE) { WARN("No Unicode-capable mail client, and MAPI_FORCE_UNICODE is specified. MAPISendMail failed.\n"); retval = MAPI_E_UNICODE_NOT_SUPPORTED; IMsgStore_Release(msg_store); goto logoff; } } /* First open the inbox, from which the drafts folder can be opened */ if (IMsgStore_GetReceiveFolder(msg_store, NULL, 0, &entry_len, &entry_id, NULL) == S_OK) { IMsgStore_OpenEntry(msg_store, entry_len, entry_id, NULL, 0, &obj_type, (LPUNKNOWN*) &folder); MAPIFreeBuffer(entry_id); } tags[1] = PR_IPM_DRAFTS_ENTRYID; /* Open the drafts folder, or failing that, try asking the message store for the outbox */ if ((folder == NULL) || ((ret = IMAPIFolder_GetProps(folder, (LPSPropTagArray) tags, 0, &values, &props)) != S_OK)) { TRACE("Unable to open Drafts folder; opening Outbox instead\n"); tags[1] = PR_IPM_OUTBOX_ENTRYID; ret = IMsgStore_GetProps(msg_store, (LPSPropTagArray) tags, 0, &values, &props); } if (ret != S_OK) goto logoff; IMsgStore_OpenEntry(msg_store, props[0].Value.bin.cb, (LPENTRYID) props[0].Value.bin.lpb, NULL, MAPI_MODIFY, &obj_type, (LPUNKNOWN *) &draft_folder); /* Create a new message */ if (IMAPIFolder_CreateMessage(draft_folder, NULL, 0, &msg) == S_OK) { ULONG token; SPropValue p; /* Define message properties */ p.ulPropTag = PR_MESSAGE_FLAGS; p.Value.l = MSGFLAG_FROMME | MSGFLAG_UNSENT; IMessage_SetProps(msg, 1, &p, NULL); p.ulPropTag = PR_SENTMAIL_ENTRYID; p.Value.bin.cb = props[0].Value.bin.cb; p.Value.bin.lpb = props[0].Value.bin.lpb; IMessage_SetProps(msg, 1,&p, NULL); /* Set message subject */ if (message->lpszSubject) { if (unicode_aware) { p.ulPropTag = PR_SUBJECT_W; p.Value.lpszW = message->lpszSubject; } else { subjectA = convert_from_unicode(message->lpszSubject); p.ulPropTag = PR_SUBJECT_A; p.Value.lpszA = subjectA; } IMessage_SetProps(msg, 1, &p, NULL); } /* Set message body */ if (message->lpszNoteText) { LPSTREAM stream = NULL; if (IMessage_OpenProperty(msg, unicode_aware ? PR_BODY_W : PR_BODY_A, &IID_IStream, 0, MAPI_MODIFY | MAPI_CREATE, (LPUNKNOWN*) &stream) == S_OK) { if (unicode_aware) IStream_Write(stream, message->lpszNoteText, (lstrlenW(message->lpszNoteText)+1) * sizeof(WCHAR), NULL); else { bodyA = convert_from_unicode(message->lpszNoteText); IStream_Write(stream, bodyA, strlen(bodyA)+1, NULL); } IStream_Release(stream); } } /* Add message attachments */ if (message->nFileCount > 0) { ULONG num_attach = 0; unsigned int i; for (i = 0; i < message->nFileCount; i++) { IAttach* attachment = NULL; char *filenameA = NULL; SPropValue prop[4]; LPCWSTR filename; HANDLE file; if (!message->lpFiles[i].lpszPathName) continue; /* Open the attachment for reading */ file = CreateFileW(message->lpFiles[i].lpszPathName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (file == INVALID_HANDLE_VALUE) continue; /* Check if a display filename has been given; if not, get one ourselves from path name */ filename = message->lpFiles[i].lpszFileName; if (!filename) { int j; filename = message->lpFiles[i].lpszPathName; for (j = lstrlenW(message->lpFiles[i].lpszPathName)-1; j >= 0; j--) { if (message->lpFiles[i].lpszPathName[i] == '\\' || message->lpFiles[i].lpszPathName[i] == '/') { filename = &message->lpFiles[i].lpszPathName[i+1]; break; } } } TRACE("Attachment %u path: '%s'; filename: '%s'\n", i, debugstr_w(message->lpFiles[i].lpszPathName), debugstr_w(filename)); /* Create the attachment */ if (IMessage_CreateAttach(msg, NULL, 0, &num_attach, &attachment) != S_OK) { TRACE("Unable to create attachment\n"); CloseHandle(file); continue; } /* Set the attachment properties */ ZeroMemory(prop, sizeof(prop)); prop[0].ulPropTag = PR_ATTACH_METHOD; prop[0].Value.ul = ATTACH_BY_VALUE; if (unicode_aware) { prop[1].ulPropTag = PR_ATTACH_LONG_FILENAME_W; prop[1].Value.lpszW = (LPWSTR) filename; prop[2].ulPropTag = PR_ATTACH_FILENAME_W; prop[2].Value.lpszW = (LPWSTR) filename; } else { filenameA = convert_from_unicode(filename); prop[1].ulPropTag = PR_ATTACH_LONG_FILENAME_A; prop[1].Value.lpszA = (LPSTR) filenameA; prop[2].ulPropTag = PR_ATTACH_FILENAME_A; prop[2].Value.lpszA = (LPSTR) filenameA; } prop[3].ulPropTag = PR_RENDERING_POSITION; prop[3].Value.l = -1; if (IAttach_SetProps(attachment, 4, prop, NULL) == S_OK) { LPSTREAM stream = NULL; if (IAttach_OpenProperty(attachment, PR_ATTACH_DATA_BIN, &IID_IStream, 0, MAPI_MODIFY | MAPI_CREATE, (LPUNKNOWN*) &stream) == S_OK) { BYTE data[READ_BUF_SIZE]; DWORD size = 0, read, written; while (ReadFile(file, data, READ_BUF_SIZE, &read, NULL) && (read != 0)) { IStream_Write(stream, data, read, &written); size += read; } TRACE("%d bytes written of attachment\n", size); IStream_Commit(stream, STGC_DEFAULT); IStream_Release(stream); prop[0].ulPropTag = PR_ATTACH_SIZE; prop[0].Value.ul = size; IAttach_SetProps(attachment, 1, prop, NULL); IAttach_SaveChanges(attachment, KEEP_OPEN_READONLY); num_attach++; } } CloseHandle(file); IAttach_Release(attachment); HeapFree(GetProcessHeap(), 0, filenameA); } } IMessage_SaveChanges(msg, KEEP_OPEN_READWRITE); /* Prepare the message form */ if (IMAPISession_PrepareForm(session, NULL, msg, &token) == S_OK) { ULONG access = 0, status = 0, message_flags = 0, pc = 0; ULONG pT[2] = {1, PR_MSG_STATUS}; /* Retrieve message status, flags, access rights and class */ if (IMessage_GetProps(msg, (LPSPropTagArray) pT, 0, &pc, &props) == S_OK) { status = props->Value.ul; MAPIFreeBuffer(props); } pT[1] = PR_MESSAGE_FLAGS; if (IMessage_GetProps(msg, (LPSPropTagArray) pT, 0, &pc, &props) == S_OK) { message_flags = props->Value.ul; MAPIFreeBuffer(props); } pT[1] = PR_ACCESS; if (IMessage_GetProps(msg, (LPSPropTagArray) pT, 0, &pc, &props) == S_OK) { access = props->Value.ul; MAPIFreeBuffer(props); } pT[1] = PR_MESSAGE_CLASS_A; if (IMessage_GetProps(msg, (LPSPropTagArray) pT, 0, &pc, &props) == S_OK) { /* Show the message form (edit window) */ ret = IMAPISession_ShowForm(session, 0, msg_store, draft_folder, NULL, token, NULL, 0, status, message_flags, access, props->Value.lpszA); switch (ret) { case S_OK: retval = SUCCESS_SUCCESS; break; case MAPI_E_USER_CANCEL: retval = MAPI_E_USER_ABORT; break; default: TRACE("ShowForm failure: %x\n", ret); break; } } } IMessage_Release(msg); } /* Free up the resources we've used */ IMAPIFolder_Release(draft_folder); if (folder) IMAPIFolder_Release(folder); IMsgStore_Release(msg_store); HeapFree(GetProcessHeap(), 0, subjectA); HeapFree(GetProcessHeap(), 0, bodyA); logoff: ; IMAPISession_Logoff(session, 0, 0, 0); IMAPISession_Release(session); cleanup: ; MAPIUninitialize(); return retval; }
HRESULT WINAPI SHGetItemFromDataObject(IDataObject *pdtobj, DATAOBJ_GET_ITEM_FLAGS dwFlags, REFIID riid, void **ppv) { FORMATETC fmt; STGMEDIUM medium; HRESULT ret; TRACE("%p, %x, %s, %p\n", pdtobj, dwFlags, debugstr_guid(riid), ppv); if(!pdtobj) return E_INVALIDARG; fmt.cfFormat = RegisterClipboardFormatW(CFSTR_SHELLIDLISTW); fmt.ptd = NULL; fmt.dwAspect = DVASPECT_CONTENT; fmt.lindex = -1; fmt.tymed = TYMED_HGLOBAL; ret = IDataObject_GetData(pdtobj, &fmt, &medium); if(SUCCEEDED(ret)) { LPIDA pida = GlobalLock(medium.u.hGlobal); if((pida->cidl > 1 && !(dwFlags & DOGIF_ONLY_IF_ONE)) || pida->cidl == 1) { LPITEMIDLIST pidl; /* Get the first pidl (parent + child1) */ pidl = ILCombine((LPCITEMIDLIST) ((LPBYTE)pida+pida->aoffset[0]), (LPCITEMIDLIST) ((LPBYTE)pida+pida->aoffset[1])); ret = SHCreateItemFromIDList(pidl, riid, ppv); ILFree(pidl); } else { ret = E_FAIL; } GlobalUnlock(medium.u.hGlobal); GlobalFree(medium.u.hGlobal); } if(FAILED(ret) && !(dwFlags & DOGIF_NO_HDROP)) { TRACE("Attempting to fall back on CF_HDROP.\n"); fmt.cfFormat = CF_HDROP; fmt.ptd = NULL; fmt.dwAspect = DVASPECT_CONTENT; fmt.lindex = -1; fmt.tymed = TYMED_HGLOBAL; ret = IDataObject_GetData(pdtobj, &fmt, &medium); if(SUCCEEDED(ret)) { DROPFILES *df = GlobalLock(medium.u.hGlobal); LPBYTE files = (LPBYTE)df + df->pFiles; BOOL multiple_files = FALSE; ret = E_FAIL; if(!df->fWide) { WCHAR filename[MAX_PATH]; PCSTR first_file = (PCSTR)files; if(*(files + lstrlenA(first_file) + 1) != 0) multiple_files = TRUE; if( !(multiple_files && (dwFlags & DOGIF_ONLY_IF_ONE)) ) { MultiByteToWideChar(CP_ACP, 0, first_file, -1, filename, MAX_PATH); ret = SHCreateItemFromParsingName(filename, NULL, riid, ppv); } } else { PCWSTR first_file = (PCWSTR)files; if(*((PCWSTR)files + lstrlenW(first_file) + 1) != 0) multiple_files = TRUE; if( !(multiple_files && (dwFlags & DOGIF_ONLY_IF_ONE)) ) ret = SHCreateItemFromParsingName(first_file, NULL, riid, ppv); } GlobalUnlock(medium.u.hGlobal); GlobalFree(medium.u.hGlobal); } } if(FAILED(ret) && !(dwFlags & DOGIF_NO_URL)) { FIXME("Failed to create item, should try CF_URL.\n"); } return ret; }
HRESULT CIEFrameAuto::Navigate(BSTR URL, VARIANT * Flags, VARIANT * TargetFrameName, VARIANT * PostData, VARIANT * Headers) { HRESULT hres; LPITEMIDLIST pidl = NULL; CStubBindStatusCallback * pStubCallback = NULL; LPBINDCTX pBindCtx = NULL; // BUGBUG:: need to handle location and history... WCHAR wszPath[MAX_URL_STRING+2]; // note stomping below if changed to dynalloc SAFEARRAY * pPostDataArray = NULL; DWORD cbPostData = 0; LPCWSTR pwzHeaders = NULL; DWORD dwInFlags=0,dwFlags = 0; LPCBYTE pPostData = NULL; BOOL fOpenWithFrameName = FALSE; DWORD grBindFlags = 0; // get target frame name out of variant LPCWSTR pwzTargetFrameName = NULL; LPCWSTR pwzUnprefixedTargetFrameName = NULL; hres = E_FAIL; TraceMsg(TF_SHDAUTO, "Shell automation: CIEFrameAuto::Navigate %s called", URL); if (FAILED(hres)) { hres = _PidlFromUrlEtc(CP_ACP, (LPCWSTR)URL, NULL, &pidl); if (FAILED(hres)) goto exit; } // to perform the navigation, we either call an internal method // (_pbs->NavigateToPidl) or an external interface (IHlinkFrame::Navigate), // depending on what data we need to pass. NavigateToPidl is faster // and cheaper, but does not allow us to pass headers or post data, just // the URL! So what we do is call the fast and cheap way if only the URL // was specified (the 90% case), and if either headers or post data were // specified then we call the external interface. We have to do a bunch // of wrapping of parameters in IMonikers and IHlinks and whatnot only to // unwrap them at the other end, so we won't call this unless we need to. // if we have either headers or post data or need to open the page in a // new window or pass HLNF_CREATENOHISTORY, we have to do the navigation // the hard way (through IHlinkFrame::Navigate) -- here we have to do // a bunch of wrapping of parameters into COM objects that IHlinkFrame:: // Navigate wants. if (pwzHeaders || pPostData || dwFlags || grBindFlags) { // Check to see if this frame is offline. // This is the same as doing a get_Offline // BUGBUG rgardner Should use TO_VARIANT_BOOL VARIANT_BOOL vtbFrameIsOffline = m_bOffline ? TRUE : FALSE; VARIANT_BOOL vtbFrameIsSilent = m_bSilent ? TRUE : FALSE; // make a "stub" bind status callback to hold that data and pass it // to the URL moniker when requested hres=CStubBindStatusCallback_Create(pwzHeaders,pPostData,cbPostData, vtbFrameIsOffline, vtbFrameIsSilent, TRUE, grBindFlags, &pStubCallback); if (FAILED(hres)) goto exit; // get the canonicalized name back out of the pidl. Note this is // different than the URL passed in... it has been auto-protocol-ized, // canonicalized and generally munged in the process of creating the pidl, // which is what we want to use. hres = _pbs->IEGetDisplayName(pidl, wszPath, SHGDN_FORPARSING); if (FAILED(hres)) { TraceMsg(DM_ERROR, "CIEFrameAuto::Navigate _pbs->IEGetDisplayName failed %x", hres); goto exit; } WCHAR *pwzLocation = (WCHAR *)UrlGetLocationW(wszPath); if (pwzLocation) { // NOTE: we allocated a extra char, just so we could do the following MoveMemory(pwzLocation+1, pwzLocation, (lstrlenW(pwzLocation)+1)*sizeof(WCHAR)); *pwzLocation++ = TEXT('\0'); // we own wszPath, so we can do this. } // create a bind context to pass to IHlinkFrame::Navigate hres=CreateBindCtx(0,&pBindCtx); if (FAILED(hres)) goto exit; // we have either post data or headers (or we need to open in a new window) to pass in addition // to URL // call IHlinkFrame::Navigate to do the navigation hres = NavigateHack(dwFlags, pBindCtx, pStubCallback, fOpenWithFrameName ? pwzTargetFrameName:NULL, wszPath, pwzLocation); } else { ASSERT(dwFlags==0); // // NOTES: We used to call _pbs->NavigatePidl (in IE3.0), now we call // _psb->BrowseObject, so that we ALWAYS hit that code path. // hres = _BrowseObject(pidl, SBSP_SAMEBROWSER|SBSP_ABSOLUTE); } }
HRESULT create_monodata(REFIID riid, LPVOID *ppObj ) { static const WCHAR wszCodebase[] = {'C','o','d','e','B','a','s','e',0}; static const WCHAR wszClass[] = {'C','l','a','s','s',0}; static const WCHAR wszFileSlash[] = {'f','i','l','e',':','/','/','/',0}; static const WCHAR wszCLSIDSlash[] = {'C','L','S','I','D','\\',0}; static const WCHAR wszInprocServer32[] = {'\\','I','n','p','r','o','c','S','e','r','v','e','r','3','2',0}; WCHAR path[CHARS_IN_GUID + ARRAYSIZE(wszCLSIDSlash) + ARRAYSIZE(wszInprocServer32) - 1]; MonoDomain *domain; MonoAssembly *assembly; ICLRRuntimeInfo *info; RuntimeHost *host; HRESULT hr; HKEY key; LONG res; int offset = 0; WCHAR codebase[MAX_PATH + 8]; WCHAR classname[350]; WCHAR filename[MAX_PATH]; DWORD dwBufLen = 350; lstrcpyW(path, wszCLSIDSlash); StringFromGUID2(riid, path + lstrlenW(wszCLSIDSlash), CHARS_IN_GUID); lstrcatW(path, wszInprocServer32); TRACE("Registry key: %s\n", debugstr_w(path)); res = RegOpenKeyExW(HKEY_CLASSES_ROOT, path, 0, KEY_READ, &key); if (res == ERROR_FILE_NOT_FOUND) return CLASS_E_CLASSNOTAVAILABLE; res = RegGetValueW( key, NULL, wszClass, RRF_RT_REG_SZ, NULL, classname, &dwBufLen); if(res != ERROR_SUCCESS) { WARN("Class value cannot be found.\n"); hr = CLASS_E_CLASSNOTAVAILABLE; goto cleanup; } TRACE("classname (%s)\n", debugstr_w(classname)); dwBufLen = MAX_PATH + 8; res = RegGetValueW( key, NULL, wszCodebase, RRF_RT_REG_SZ, NULL, codebase, &dwBufLen); if(res != ERROR_SUCCESS) { WARN("CodeBase value cannot be found.\n"); hr = CLASS_E_CLASSNOTAVAILABLE; goto cleanup; } /* Strip file:/// */ if(strncmpW(codebase, wszFileSlash, strlenW(wszFileSlash)) == 0) offset = strlenW(wszFileSlash); strcpyW(filename, codebase + offset); TRACE("codebase (%s)\n", debugstr_w(filename)); *ppObj = NULL; hr = get_runtime_info(filename, NULL, NULL, 0, 0, FALSE, &info); if (SUCCEEDED(hr)) { hr = ICLRRuntimeInfo_GetRuntimeHost(info, &host); if (SUCCEEDED(hr)) hr = RuntimeHost_GetDefaultDomain(host, &domain); if (SUCCEEDED(hr)) { MonoImage *image; MonoClass *klass; MonoObject *result; IUnknown *unk = NULL; char *filenameA, *ns; char *classA; hr = CLASS_E_CLASSNOTAVAILABLE; host->mono->mono_thread_attach(domain); filenameA = WtoA(filename); assembly = host->mono->mono_domain_assembly_open(domain, filenameA); HeapFree(GetProcessHeap(), 0, filenameA); if (!assembly) { ERR("Cannot open assembly %s\n", filenameA); goto cleanup; } image = host->mono->mono_assembly_get_image(assembly); if (!image) { ERR("Couldn't get assembly image\n"); goto cleanup; } classA = WtoA(classname); ns = strrchr(classA, '.'); *ns = '\0'; klass = host->mono->mono_class_from_name(image, classA, ns+1); HeapFree(GetProcessHeap(), 0, classA); if (!klass) { ERR("Couldn't get class from image\n"); goto cleanup; } /* * Use the default constructor for the .NET class. */ result = host->mono->mono_object_new(domain, klass); host->mono->mono_runtime_object_init(result); hr = RuntimeHost_GetIUnknownForObject(host, result, &unk); if (SUCCEEDED(hr)) { hr = IUnknown_QueryInterface(unk, &IID_IUnknown, ppObj); IUnknown_Release(unk); } else hr = CLASS_E_CLASSNOTAVAILABLE; } else hr = CLASS_E_CLASSNOTAVAILABLE; } else hr = CLASS_E_CLASSNOTAVAILABLE; cleanup: if(info) ICLRRuntimeInfo_Release(info); RegCloseKey(key); return hr; }
HRESULT ScaWriteWebError(IMSAdminBase* piMetabase, int iParentType, LPCWSTR wzRoot, SCA_WEB_ERROR* psweList) { // AssertSz(0, "Debug ScaWriteWebError here"); Assert(*wzRoot && psweList); HRESULT hr = S_OK; ExitOnNull(piMetabase, hr, E_INVALIDARG, "Failed to write web error, because no metabase was provided"); ExitOnNull(wzRoot, hr, E_INVALIDARG, "Failed to write web error, because no root was provided"); DWORD cchData = 0; BOOL fFoundDefault = FALSE; LPWSTR pwzSearchKey = NULL; LPWSTR pwz = NULL; LPWSTR pwzErrors = NULL; LPWSTR pwzCodeSubCode = NULL; LPWSTR pwzAcceptableCodeSubCode = NULL; LPCWSTR wzFoundCodeSubCode = NULL; DWORD_PTR dwFoundCodeSubCodeIndex = -1; BOOL fOldValueFound = FALSE; LPWSTR pwzAcceptableErrors = NULL; LPWSTR pwzNewError = NULL; METADATA_RECORD mr; ::ZeroMemory(&mr, sizeof(mr)); // get the set of all valid custom errors from the metabase mr.dwMDIdentifier = MD_CUSTOM_ERROR_DESC; mr.dwMDAttributes = METADATA_INHERIT; mr.dwMDUserType = IIS_MD_UT_SERVER; mr.dwMDDataType = ALL_METADATA; mr.dwMDDataLen = cchData = 0; mr.pbMDData = NULL; hr = MetaGetValue(piMetabase, METADATA_MASTER_ROOT_HANDLE, L"/LM/W3SVC/Info", &mr); ExitOnFailure(hr, "Unable to get set of acceptable error codes for this server."); pwzAcceptableErrors = reinterpret_cast<LPWSTR>(mr.pbMDData); // Check if web errors already exist here mr.dwMDIdentifier = MD_CUSTOM_ERROR; mr.dwMDAttributes = METADATA_INHERIT; mr.dwMDUserType = IIS_MD_UT_SERVER; mr.dwMDDataType = ALL_METADATA; mr.dwMDDataLen = cchData = 0; mr.pbMDData = NULL; hr = MetaGetValue(piMetabase, METADATA_MASTER_ROOT_HANDLE, wzRoot, &mr); if (HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr || MD_ERROR_DATA_NOT_FOUND == hr) { // // If we don't have one already, find an appropriate one to start with // // we can walk up key by key and look for custom errors to inherit hr = StrAllocConcat(&pwzSearchKey, wzRoot, 0); ExitOnFailure1(hr, "Failed to copy root string: %ls", wzRoot); pwz = pwzSearchKey + lstrlenW(pwzSearchKey); while (NULL == pwzErrors) { // find the last slash while (*pwz != '/' && pwz != pwzSearchKey) pwz --; if (pwz == pwzSearchKey) break; *pwz = L'\0'; // Try here. If it's not found, keep walking up the path hr = MetaGetValue(piMetabase, METADATA_MASTER_ROOT_HANDLE, pwzSearchKey, &mr); if (HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr || MD_ERROR_DATA_NOT_FOUND == hr) hr = S_FALSE; ExitOnFailure1(hr, "failed to discover default error values to start with for web root: %ls while walking up the tree", wzRoot); if (S_OK == hr) { pwzErrors = reinterpret_cast<LPWSTR>(mr.pbMDData); break; } // Don't keep going if we're at the root if (0 == lstrcmpW(pwz + 1, L"W3SVC")) break; } } else { pwzErrors = reinterpret_cast<LPWSTR>(mr.pbMDData); } ExitOnFailure1(hr, "failed to discover default error values to start with for web root: %ls", wzRoot); // The above code should have come up with some value to start pwzErrors off with. Make sure it did. if (NULL == pwzErrors) { ExitOnFailure1(hr = E_UNEXPECTED, "failed to discover default error values to start with for web root: %ls", wzRoot); } // Loop through the web errors for (SCA_WEB_ERROR* pswe = psweList; pswe; pswe = pswe->psweNext) { // Assume that we will have to replace fOldValueFound = TRUE; // If the subcode is 0, that means "*" in MD_CUSTOM_ERROR (thus the special formatting logic) if (0 == pswe->iSubCode) { hr = StrAllocFormatted(&pwzCodeSubCode, L"%d,*", pswe->iErrorCode); ExitOnFailure(hr, "failed to create error code string while installing web error"); } else { hr = StrAllocFormatted(&pwzCodeSubCode, L"%d,%d", pswe->iErrorCode, pswe->iSubCode); ExitOnFailure(hr, "failed to create error code,subcode string while installing web error"); } hr = MultiSzFindSubstring(pwzErrors, pwzCodeSubCode, &dwFoundCodeSubCodeIndex, &wzFoundCodeSubCode); ExitOnFailure1(hr, "failed to find existing error code,subcode: %ls", pwzCodeSubCode); // If we didn't find this error code/sub code pair in the list already, make sure it's acceptable to add if (S_FALSE == hr) { // // Make sure this error code/sub code pair is in the "acceptable" list // // If the subcode is 0, that means "0" in MD_CUSTOM_ERROR_DESC (no special formatting logic needed) hr = StrAllocFormatted(&pwzAcceptableCodeSubCode, L"%d,%d", pswe->iErrorCode, pswe->iSubCode); ExitOnFailure(hr, "failed to create error code,subcode string while installing web error"); // We don't care where it is, just whether it's there or not hr = MultiSzFindSubstring(pwzAcceptableErrors, pwzAcceptableCodeSubCode, NULL, NULL); ExitOnFailure1(hr, "failed to find whether or not error code, subcode: %ls is supported", pwzCodeSubCode); if (S_FALSE == hr) { WcaLog(LOGMSG_VERBOSE, "Skipping error code, subcode: %ls because it is not supported by the server.", pwzCodeSubCode); continue; } // If we didn't find it (and its an acceptable error) then we have nothing to replace fOldValueFound = FALSE; } // Set up the new error string if needed if (*(pswe->wzFile)) { hr = StrAllocFormatted(&pwzNewError, L"%s,FILE,%s", pwzCodeSubCode, pswe->wzFile); ExitOnFailure2(hr, "failed to create new error code string with code,subcode: %ls, file: %ls", pwzCodeSubCode, pswe->wzFile); } else if (*(pswe->wzURL)) { hr = StrAllocFormatted(&pwzNewError, L"%s,URL,%s", pwzCodeSubCode, pswe->wzURL); ExitOnFailure2(hr, "failed to create new error code string with code,subcode: %ls, file: %ls", pwzCodeSubCode, pswe->wzFile); } else if (fOldValueFound) { // If no File or URL was specified, they want a default error so remove the old value from the MULTISZ and move on hr = MultiSzRemoveString(&pwzErrors, dwFoundCodeSubCodeIndex); ExitOnFailure1(hr, "failed to remove string for error code sub code: %ls in order to make it 'default'", pwzCodeSubCode); continue; } // If we have something to replace, replace it, otherwise, put it at the beginning (order shouldn't matter) if (fOldValueFound) { hr = MultiSzReplaceString(&pwzErrors, dwFoundCodeSubCodeIndex, pwzNewError); ExitOnFailure1(hr, "failed to replace old error string with new error string for error code,subcode: %ls", pwzCodeSubCode); } else { hr = MultiSzPrepend(&pwzErrors, NULL, pwzNewError); ExitOnFailure1(hr, "failed to prepend new error string for error code,subcode: %ls", pwzCodeSubCode); } } // now write the CustomErrors to the metabase if (weptWeb == iParentType) { hr = ScaWriteMetabaseValue(piMetabase, wzRoot, L"/Root", MD_CUSTOM_ERROR, METADATA_INHERIT, IIS_MD_UT_FILE, MULTISZ_METADATA, pwzErrors); ExitOnFailure(hr, "Failed to write Web Error to /Root"); } else { hr = ScaWriteMetabaseValue(piMetabase, wzRoot, NULL, MD_CUSTOM_ERROR, METADATA_INHERIT, IIS_MD_UT_FILE, MULTISZ_METADATA, pwzErrors); ExitOnFailure(hr, "Failed to write Web Error"); } LExit: ReleaseStr(pwzErrors); ReleaseStr(pwzSearchKey); ReleaseStr(pwzCodeSubCode); ReleaseStr(pwzAcceptableCodeSubCode); ReleaseStr(pwzAcceptableErrors); return hr; }
HRESULT ScaWebAppExtensionsWrite( __in IMSAdminBase* piMetabase, __in LPCWSTR wzRootOfWeb, __in SCA_WEB_APPLICATION_EXTENSION* pswappextList ) { HRESULT hr = S_OK; LPWSTR wzAppExt = NULL; DWORD cchAppExt; WCHAR wzAppExtension[1024]; WCHAR wzAppExtensions[65536]; SCA_WEB_APPLICATION_EXTENSION* pswappext = NULL; if (!pswappextList) { ExitFunction(); } ::ZeroMemory(wzAppExtensions, sizeof(wzAppExtensions)); wzAppExt = wzAppExtensions; cchAppExt = countof(wzAppExtensions); pswappext = pswappextList; while (pswappext) { // if all (represented by "*" or blank) if (0 == lstrcmpW(pswappext->wzExtension, L"*") || 0 == lstrlenW(pswappext->wzExtension)) { hr = ::StringCchPrintfW(wzAppExtension, countof(wzAppExtension), L"*,%s,%d", pswappext->wzExecutable, pswappext->iAttributes); ExitOnFailure(hr, "Failed to format *,executable,attributes string"); } else { hr = ::StringCchPrintfW(wzAppExtension, countof(wzAppExtension), L".%s,%s,%d", pswappext->wzExtension, pswappext->wzExecutable, pswappext->iAttributes); ExitOnFailure(hr, "Failed to format extension,executable,attributes string"); } // if verbs were specified and not the keyword "all" if (pswappext->wzVerbs[0] && CSTR_EQUAL != CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, pswappext->wzVerbs, -1, L"all", -1)) { hr = ::StringCchCatW(wzAppExtension, countof(wzAppExtension), L","); ExitOnFailure(hr, "Failed to concatenate comma to app extension string"); hr = ::StringCchCatW(wzAppExtension, countof(wzAppExtension), pswappext->wzVerbs); ExitOnFailure(hr, "Failed to concatenate verb to app extension string"); } hr = ::StringCchCopyW(wzAppExt, cchAppExt, wzAppExtension); ExitOnFailure(hr, "Failed to copy app extension string"); wzAppExt += lstrlenW(wzAppExtension) + 1; cchAppExt -= lstrlenW(wzAppExtension) + 1; pswappext = pswappext->pswappextNext; } if (*wzAppExtensions) { hr = ScaWriteMetabaseValue(piMetabase, wzRootOfWeb, NULL, MD_SCRIPT_MAPS, METADATA_INHERIT, IIS_MD_UT_FILE, MULTISZ_METADATA, wzAppExtensions); ExitOnFailure1(hr, "Failed to write AppExtension: '%ls'", wzAppExtension); } LExit: return hr; }
/***************************************************** * localmon_XcvDataPort [exported through MONITOREX] * * Execute command through a Communication-Channel * * PARAMS * hXcv [i] The Handle to work with * pszDataName [i] Name of the command to execute * pInputData [i] Buffer for extra Input Data (needed only for some commands) * cbInputData [i] Size in Bytes of Buffer at pInputData * pOutputData [o] Buffer to receive additional Data (needed only for some commands) * cbOutputData [i] Size in Bytes of Buffer at pOutputData * pcbOutputNeeded [o] PTR to receive the minimal Size in Bytes of the Buffer at pOutputData * * RETURNS * Success: ERROR_SUCCESS * Failure: win32 error code * * NOTES * * Minimal List of commands, that every Printmonitor DLL should support: * *| "MonitorUI" : Return the Name of the Userinterface-DLL as WSTR in pOutputData *| "AddPort" : Add a Port (Name as WSTR in pInputData) *| "DeletePort": Delete a Port (Name as WSTR in pInputData) * * */ static DWORD WINAPI localmon_XcvDataPort(HANDLE hXcv, LPCWSTR pszDataName, PBYTE pInputData, DWORD cbInputData, PBYTE pOutputData, DWORD cbOutputData, PDWORD pcbOutputNeeded) { WCHAR buffer[16]; /* buffer for a decimal number */ LPWSTR ptr; DWORD res; DWORD needed; HKEY hroot; TRACE("(%p, %s, %p, %d, %p, %d, %p)\n", hXcv, debugstr_w(pszDataName), pInputData, cbInputData, pOutputData, cbOutputData, pcbOutputNeeded); if (!lstrcmpW(pszDataName, cmd_AddPortW)) { TRACE("InputData (%d): %s\n", cbInputData, debugstr_w( (LPWSTR) pInputData)); res = RegOpenKeyW(HKEY_LOCAL_MACHINE, WinNT_CV_PortsW, &hroot); if (res == ERROR_SUCCESS) { if (does_port_exist((LPWSTR) pInputData)) { RegCloseKey(hroot); TRACE("=> %u\n", ERROR_ALREADY_EXISTS); return ERROR_ALREADY_EXISTS; } res = RegSetValueExW(hroot, (LPWSTR) pInputData, 0, REG_SZ, (const BYTE *) emptyW, sizeof(emptyW)); RegCloseKey(hroot); } TRACE("=> %u\n", res); return res; } if (!lstrcmpW(pszDataName, cmd_ConfigureLPTPortCommandOKW)) { TRACE("InputData (%d): %s\n", cbInputData, debugstr_w( (LPWSTR) pInputData)); res = RegCreateKeyW(HKEY_LOCAL_MACHINE, WinNT_CV_WindowsW, &hroot); if (res == ERROR_SUCCESS) { res = RegSetValueExW(hroot, TransmissionRetryTimeoutW, 0, REG_SZ, pInputData, cbInputData); RegCloseKey(hroot); } return res; } if (!lstrcmpW(pszDataName, cmd_DeletePortW)) { TRACE("InputData (%d): %s\n", cbInputData, debugstr_w( (LPWSTR) pInputData)); res = RegOpenKeyW(HKEY_LOCAL_MACHINE, WinNT_CV_PortsW, &hroot); if (res == ERROR_SUCCESS) { res = RegDeleteValueW(hroot, (LPWSTR) pInputData); RegCloseKey(hroot); TRACE("=> %u with %u\n", res, GetLastError() ); return res; } return ERROR_FILE_NOT_FOUND; } if (!lstrcmpW(pszDataName, cmd_GetDefaultCommConfigW)) { TRACE("InputData (%d): %s\n", cbInputData, debugstr_w( (LPWSTR) pInputData)); *pcbOutputNeeded = cbOutputData; res = GetDefaultCommConfigW((LPWSTR) pInputData, (LPCOMMCONFIG) pOutputData, pcbOutputNeeded); TRACE("got %u with %u\n", res, GetLastError() ); return res ? ERROR_SUCCESS : GetLastError(); } if (!lstrcmpW(pszDataName, cmd_GetTransmissionRetryTimeoutW)) { * pcbOutputNeeded = sizeof(DWORD); if (cbOutputData >= sizeof(DWORD)) { /* the w2k resource kit documented a default of 90, but that's wrong */ *((LPDWORD) pOutputData) = 45; res = RegOpenKeyW(HKEY_LOCAL_MACHINE, WinNT_CV_WindowsW, &hroot); if (res == ERROR_SUCCESS) { needed = sizeof(buffer) - sizeof(WCHAR); res = RegQueryValueExW(hroot, TransmissionRetryTimeoutW, NULL, NULL, (LPBYTE) buffer, &needed); if ((res == ERROR_SUCCESS) && (buffer[0])) { *((LPDWORD) pOutputData) = strtoulW(buffer, NULL, 0); } RegCloseKey(hroot); } return ERROR_SUCCESS; } return ERROR_INSUFFICIENT_BUFFER; } if (!lstrcmpW(pszDataName, cmd_MonitorUIW)) { * pcbOutputNeeded = sizeof(dllnameuiW); if (cbOutputData >= sizeof(dllnameuiW)) { memcpy(pOutputData, dllnameuiW, sizeof(dllnameuiW)); return ERROR_SUCCESS; } return ERROR_INSUFFICIENT_BUFFER; } if (!lstrcmpW(pszDataName, cmd_PortIsValidW)) { TRACE("InputData (%d): %s\n", cbInputData, debugstr_w( (LPWSTR) pInputData)); res = get_type_from_name((LPCWSTR) pInputData); TRACE("detected as %u\n", res); /* names, that we have recognized, are valid */ if (res) return ERROR_SUCCESS; /* ERROR_ACCESS_DENIED, ERROR_PATH_NOT_FOUND or something else */ TRACE("=> %u\n", GetLastError()); return GetLastError(); } if (!lstrcmpW(pszDataName, cmd_SetDefaultCommConfigW)) { /* get the portname from the Handle */ ptr = strchrW(((xcv_t *)hXcv)->nameW, ' '); if (ptr) { ptr++; /* skip the space */ } else { ptr = ((xcv_t *)hXcv)->nameW; } lstrcpynW(buffer, ptr, sizeof(buffer)/sizeof(WCHAR)); if (buffer[0]) buffer[lstrlenW(buffer)-1] = '\0'; /* remove the ':' */ res = SetDefaultCommConfigW(buffer, (LPCOMMCONFIG) pInputData, cbInputData); TRACE("got %u with %u\n", res, GetLastError() ); return res ? ERROR_SUCCESS : GetLastError(); } FIXME("command not supported: %s\n", debugstr_w(pszDataName)); return ERROR_INVALID_PARAMETER; }
void browser::parsingURL(WCHAR* message) { initialize(); WCHAR* p = NULL; char* mtempURL = NULL; lstrcpyW(buf, message); //http 파싱 p = wcsstr(buf, TEXT("http://")); if ((p = wcsstr(buf, TEXT("http://"))) != NULL || (p = wcsstr(buf, TEXT("https://"))) != NULL) //http나 https로 시작하면 { lstrcpyW(buf, buf + lstrlenW(TEXT("http://"))); p = NULL; //도메인이면 p = wcsstr(buf, TEXT("www")); if (p != NULL) { WCHAR tempURL[MAXLEN] = { '\0', }; lstrcpyW(tempURL, p); p = wcstok(p, TEXT(":")); lstrcpyW(tempURL, p); mtempURL = (char*)malloc(sizeof(char) * lstrlenW(tempURL) + 1); memset(mtempURL, '\0', lstrlenW(tempURL) + 1); mtempURL = convertUnicodeToMultibyte(tempURL); p = wcstok(NULL, TEXT("\r\n")); if (p == NULL) // 포트가 없을 때 { unsigned long hostaddr = inet_addr(mtempURL); if (hostaddr == INADDR_NONE) { host = gethostbyname(mtempURL); } lstrcpyW(port, TEXT("80")); //well known port(DNS) } else //포트가 있을 때 { unsigned long hostaddr = inet_addr(mtempURL); if (hostaddr == INADDR_NONE) { host = gethostbyname(mtempURL); } if (p != NULL) { lstrcpyW(port, p); } } } else //도메인이 아니면 { p = wcstok(buf, TEXT(":")); //ip lstrcpyW(ip, p); p = wcstok(NULL, TEXT("/")); //port lstrcpyW(port, p); //uri p = wcstok(NULL, TEXT(" ")); lstrcpyW(uri, p); } } else//http로 시작하지않으면 { //www.~~~이면 p = wcsstr(buf, TEXT("www")); if (p != NULL) { WCHAR tempURL[MAXLEN] = { '\0', }; lstrcpyW(tempURL, p); p = wcstok(p, TEXT(":")); lstrcpyW(tempURL, p); mtempURL = (char*)malloc(sizeof(char) * lstrlenW(tempURL) + 1); memset(mtempURL, '\0', lstrlenW(tempURL) + 1); mtempURL = convertUnicodeToMultibyte(tempURL); p = wcstok(NULL, TEXT("\r\n")); if (p == NULL) // 포트가 없을 때 { unsigned long hostaddr = inet_addr(mtempURL); if (hostaddr == INADDR_NONE) { host = gethostbyname(mtempURL); } lstrcpyW(port, TEXT("80")); } else //포트가 있을 때 { unsigned long hostaddr = inet_addr(mtempURL); if (hostaddr == INADDR_NONE) { host = gethostbyname(mtempURL); } if (p != NULL) { lstrcpyW(port, p); } } } else { p = wcstok(buf, TEXT(":")); //ip if (p != NULL) lstrcpyW(ip, p); p = wcstok(NULL, TEXT("/")); //port if (p != NULL) lstrcpyW(port, p); //uri p = wcstok(NULL, TEXT(" ")); if (p != NULL) lstrcpyW(uri, p); } } }
WCHAR* browser::connection(WCHAR* URL) { initialize(); wstring msg = TEXT(""); char* mBuf = NULL; char mrBuf[MAXLEN] = { '\0', }; parsingURL(URL); //URL을 파싱한다. if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { return TEXT("-1"); } /*잘못된 정보일 때 다시 정보 입력받기*/ DWORD sock_timeout = 1 * 1000; setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)sock_timeout, sizeof(sock_timeout)); if (host != NULL) //DNS일때 (host는 DNS의 주소를 입력받은 변수) { if (lstrlenW(uri) != 0) { wsprintfW(buf, TEXT("GET /%s HTTP/1.1\r\n\r\nAccept:text/html, application/xhtml+xml, */*\r\nAccept-Language: ko-KR\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko\r\nAccept-Encoding: gzip, deflate\r\nHost: %s:80\r\nDNT:1\r\nConnection: Keep-Alive\r\n"), uri, inet_ntoa(*((struct in_addr *)host->h_addr_list[0]))); } else { wsprintfW(buf, TEXT("GET / HTTP/1.1\r\n\r\nAccept:text/html, application/xhtml+xml, */*\r\nAccept-Language: ko-KR\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko\r\nAccept-Encoding: gzip, deflate\r\nHost: %s:80\r\nDNT:1\r\nConnection: Keep-Alive\r\n"), inet_ntoa(*((struct in_addr *)host->h_addr_list[0]))); } memset((void*)&addr, 0x00, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.S_un.S_addr = inet_addr(inet_ntoa(*((struct in_addr *)host->h_addr_list[0]))); char* mPort = NULL; mPort = (char*)malloc(sizeof(char) * lstrlenW(port) + 1); memset(mPort, '\0', lstrlenW(port) + 1); mPort = convertUnicodeToMultibyte(port); addr.sin_port = htons(atoi(mPort)); } else //DNS가 아닐 때 { if (ip != NULL && port != NULL) { memset((void*)&addr, 0x00, sizeof(addr)); wsprintfW(buf, TEXT("GET /%s HTTP/1.1\r\nAccept:text/html, application/xhtml+xml, */*\r\nAccept-Language: ko-KR\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko\r\nAccept-Encoding: gzip, deflate\r\nHost: 52.192.132.151:8777\r\nDNT:1\r\nConnection: Keep-Alive\r\n"), uri); addr.sin_family = AF_INET; char* mIp = NULL; mIp = (char*)malloc(sizeof(char) * lstrlenW(ip) + 1); memset(mIp, '\0', lstrlenW(ip) + 1); mIp = convertUnicodeToMultibyte(ip); addr.sin_addr.S_un.S_addr = inet_addr(mIp); char* mPort = NULL; mPort = (char*)malloc(sizeof(char) * lstrlenW(port) + 1); memset(mIp, '\0', lstrlenW(port) + 1); mPort = convertUnicodeToMultibyte(port); addr.sin_port = htons(atoi(mPort)); } } if (connect(sockfd, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) { return TEXT("-1"); } mBuf = (char*)malloc(sizeof(char) * lstrlenW(buf)); mBuf = convertUnicodeToMultibyte(buf); send(sockfd, mBuf, strlen(mBuf), 0); memset(mrBuf, '\0', MAXLEN); int ret = 0; int i = 0; printf("here is conneciton\n"); while (recv(sockfd, mrBuf, MAXLEN, 0) > 0) { printf("%s\n", mrBuf); msg += convertMultibyteToUnicode(mrBuf);//rbuf; if (strstr(mrBuf, "</html>")) { break; } memset(rbuf, '\0', MAXLEN); memset(mrBuf, '\0', MAXLEN); } printf("here is end of connection\n"); WCHAR* returnMsg = (WCHAR*)malloc(sizeof(WCHAR) * msg.length()); memset(returnMsg, '\0', sizeof(WCHAR) * msg.length()); wcscpy(returnMsg, msg.c_str()); closesocket(sockfd); return returnMsg; }
void XAP_Win32Slurp::stuffRegistry(const char * szSuffix, const char * szApplicationName, LPCWSTR szExePathname, const char * szContentType) { // load the system registry if there's no info // for us already present for the given suffix. // we assume that the string contains the dot. // // TODO consider raising a dialog asking if they // TODO want us to override any existing settings // TODO if they currently don't point to us. like // TODO MSFT and NSCP currently (politely) fight // TODO for the .html suffix.... // // we construct the following pattern in the registry: // // HKEY_CLASSES_ROOT\<suffix> = <foo> // HKEY_CLASSES_ROOT\<suffix>\Content Type = <content_type> // HKEY_CLASSES_ROOT\<foo> = <application_name> ## " Document" // HKEY_CLASSES_ROOT\<foo>\shell\open\command = <exe_pathname> // HKEY_CLASSES_ROOT\<foo>\shell\open\ddeexec = [Open("%1")] // HKEY_CLASSES_ROOT\<foo>\shell\open\ddeexec\application = <application_name> // HKEY_CLASSES_ROOT\<foo>\shell\open\ddeexec\topic = System // HKEY_CLASSES_ROOT\<foo>\DefaultIcon = <exe_pathname,2> #define VALUE_DDEEXEC_OPEN "[Open(\"%1\")]" #define FORMAT_OUR_INDIRECTION "AbiSuite.%s" #define CONTENT_TYPE_KEY "Content Type" #define DOCUMENT_ICON_POSITION 2 #define xx(s) ((LPBYTE)(s)),(strlen(s)+1) #define xxw(s) ((LPBYTE)(s)),((lstrlenW(s)+1)<<1) char buf[1024]; char bufOurFoo[1024]; WCHAR bufOurFooValue[1024]; WCHAR bufDefaultIconValue[1024]; DWORD dType; LONG eResult; ULONG len; bool bUpdateContentType; bool bCreateOrOverwrite = false; HKEY hKeyFoo = 0; HKEY hKeySuffix = 0; HKEY hKeyShell = 0; HKEY hKeyCommand = 0; HKEY hKeyOpen = 0; HKEY hKeyDdeExec = 0; HKEY hKeyApplication = 0; HKEY hKeyTopic = 0; HKEY hKeyDefaultIcon = 0; sprintf(bufOurFoo,"AbiSuite.%s",szApplicationName); strtok(bufOurFoo," "); // trim key at first whitespace const XAP_StringSet *pSS = XAP_App::getApp()->getStringSet(); const gchar *pStr = "%s Document"; UT_Win32LocaleString tmpl; char tdbuf[512]; sprintf(tdbuf,pStr,szApplicationName); tmpl.fromUTF8(tdbuf); wcscpy(bufOurFooValue,tmpl.c_str()); /////////////////////////////////////////////////////////////////// // See if someone has claimed this suffix. // HKEY_CLASSES_ROOT\<suffix> = <foo> /////////////////////////////////////////////////////////////////// switch ( _fetchKey(HKEY_CLASSES_ROOT,szSuffix,&hKeySuffix) ) { case X_Error: goto CleanupMess; case X_CreatedKey: // we are free to create what we want. bCreateOrOverwrite = true; break; case X_ExistingKey: // see what's already there { /////////////////////////////////////////////////////////////////// // HKEY_CLASSES_ROOT\<suffix> = <foo> // was already present. Verify the value. /////////////////////////////////////////////////////////////////// len = G_N_ELEMENTS(buf); eResult = RegQueryValueEx(hKeySuffix,NULL,NULL,&dType,(LPBYTE)buf,&len); if ((eResult != ERROR_SUCCESS) || (dType != REG_SZ) || (len==0)) break; // bogus data, overwrite it. UT_DEBUGMSG(("Registry: suffix [HKEY_CLASSES_ROOT\\%s] --> [%s]\n", szSuffix,buf)); if (g_ascii_strcasecmp(buf,bufOurFoo) != 0) // we didn't create this so ask first. { if (!_askForStealFromAnotherApplication()) goto CleanupMess; bCreateOrOverwrite = true; break; } } } if (bCreateOrOverwrite) { /////////////////////////////////////////////////////////////////// // Set the value <foo> in // HKEY_CLASSES_ROOT\<suffix> = <foo> /////////////////////////////////////////////////////////////////// UT_ASSERT(hKeySuffix); eResult = RegSetValueEx(hKeySuffix,NULL,0,REG_SZ,xx(bufOurFoo)); UT_DEBUGMSG(("Register: HKEY_CLASSES_ROOT\\%s <-- %s [error %d]\n", szSuffix,bufOurFoo,eResult)); if (eResult != ERROR_SUCCESS) goto CleanupMess; } /////////////////////////////////////////////////////////////////// // See if "HKEY_CLASSES_ROOT\<suffix>\Content Type" is present // as a value under the current key. /////////////////////////////////////////////////////////////////// bUpdateContentType = true; len = G_N_ELEMENTS(buf); eResult = RegQueryValueEx(hKeySuffix,CONTENT_TYPE_KEY,NULL,&dType,(LPBYTE)buf,&len); if ((eResult == ERROR_SUCCESS) && (dType == REG_SZ)) { UT_DEBUGMSG(("Registry: Existing ContentType [%s]\n",buf)); if (g_ascii_strcasecmp(buf,szContentType) == 0) bUpdateContentType = false; else // we didn't create this so ask first. bUpdateContentType = (_askForStealMimeFromAnotherApplication()); } if (bUpdateContentType) // bogus or stale data, overwrite it. { /////////////////////////////////////////////////////////////////// // Set the value <content_type> in // HKEY_CLASSES_ROOT\<suffix>\Content Type = <content_type> /////////////////////////////////////////////////////////////////// UT_ASSERT(hKeySuffix); eResult = RegSetValueEx(hKeySuffix,CONTENT_TYPE_KEY,0,REG_SZ,xx(szContentType)); UT_DEBUGMSG(("Register: HKEY_CLASSES_ROOT\\%s\\Content Type <-- %s [error %d]\n", szSuffix,szContentType,eResult)); // content-type is not a critical field, so if it fails we just go on. // if (eResult != ERROR_SUCCESS) goto CleanupMess; } /////////////////////////////////////////////////////////////////// // Verify that the suffix indirection is defined. // HKEY_CLASSES_ROOT\<foo> = ... /////////////////////////////////////////////////////////////////// switch ( _fetchKey(HKEY_CLASSES_ROOT,bufOurFoo,&hKeyFoo) ) { case X_Error: goto CleanupMess; case X_ExistingKey: UT_ASSERT(hKeyFoo); len = G_N_ELEMENTS(buf); eResult = RegQueryValueExW(hKeyFoo,NULL,0,&dType,(LPBYTE)buf,&len); if ((eResult==ERROR_SUCCESS) && (dType==REG_SZ) && (lstrcmpiW((LPCWSTR)buf,bufOurFooValue)==0)) break; // already has correct value, no need to overwrite. /* otherwise, replace the value */ /* fall thru intended */ case X_CreatedKey: UT_ASSERT(hKeyFoo); eResult = RegSetValueExW(hKeyFoo,NULL,0,REG_SZ,xxw(bufOurFooValue)); if (eResult != ERROR_SUCCESS) goto CleanupMess; break; } /////////////////////////////////////////////////////////////////// // Inspect the command path // HKEY_CLASSES_ROOT\<foo>\shell\open\command = <exe_pathname> /////////////////////////////////////////////////////////////////// WCHAR commandPathWithParam[1024]; wcscpy ( commandPathWithParam, szExePathname ); wcscat ( commandPathWithParam, L" \"%1\"" ); if (_fetchKey(hKeyFoo,"shell",&hKeyShell) == X_Error) goto CleanupMess; if (_fetchKey(hKeyShell,"open",&hKeyOpen) == X_Error) goto CleanupMess; switch ( _fetchKey(hKeyOpen,"command",&hKeyCommand) ) { case X_Error: goto CleanupMess; case X_ExistingKey: UT_ASSERT(hKeyCommand); len = G_N_ELEMENTS((LPWSTR)buf); eResult = RegQueryValueExW(hKeyCommand,NULL,0,&dType,(LPBYTE)buf,&len); if ((eResult==ERROR_SUCCESS) && (dType==REG_SZ)) { if (lstrcmpiW((LPCWSTR)buf,commandPathWithParam) == 0) break; // already has correct value, no need to overwrite. if(memcmp(buf, commandPathWithParam, lstrlenW(commandPathWithParam)<<1) == 0) { // Path name is the same but has extra at the end. // Probably "%1" // Fall throught to update path name. } else { if (!_askForUpdateExePathname()) goto CleanupMess; } } /* otherwise, replace the value */ /* fall thru intended */ case X_CreatedKey: UT_ASSERT(hKeyCommand); eResult = RegSetValueExW(hKeyCommand,NULL,0,REG_SZ,xxw(commandPathWithParam)); if (eResult != ERROR_SUCCESS) goto CleanupMess; break; } /////////////////////////////////////////////////////////////////// // Inspect the ddeexec key // HKEY_CLASSES_ROOT\<foo>\shell\open\ddeexec = [Open(%1)] /////////////////////////////////////////////////////////////////// switch ( _fetchKey(hKeyOpen,"ddeexec",&hKeyDdeExec) ) { case X_Error: goto CleanupMess; case X_ExistingKey: UT_ASSERT(hKeyDdeExec); len = G_N_ELEMENTS(buf); eResult = RegQueryValueEx(hKeyDdeExec,NULL,0,&dType,(LPBYTE)buf,&len); if ((eResult==ERROR_SUCCESS) && (dType==REG_SZ) && (g_ascii_strcasecmp(buf,VALUE_DDEEXEC_OPEN)==0)) break; // already has correct value, no need to overwrite. /* otherwise, replace the value */ /* fall thru intended */ case X_CreatedKey: UT_ASSERT(hKeyDdeExec); eResult = RegSetValueEx(hKeyDdeExec,NULL,0,REG_SZ,xx(VALUE_DDEEXEC_OPEN)); if (eResult != ERROR_SUCCESS) goto CleanupMess; break; } /////////////////////////////////////////////////////////////////// // Inspect the application key // HKEY_CLASSES_ROOT\<foo>\shell\open\ddeexec\application = <application_name> /////////////////////////////////////////////////////////////////// switch ( _fetchKey(hKeyDdeExec,"application",&hKeyApplication) ) { case X_Error: goto CleanupMess; case X_ExistingKey: UT_ASSERT(hKeyApplication); len = G_N_ELEMENTS(buf); eResult = RegQueryValueEx(hKeyApplication,NULL,0,&dType,(LPBYTE)buf,&len); if ((eResult==ERROR_SUCCESS) && (dType==REG_SZ) && (g_ascii_strcasecmp(buf,szApplicationName)==0)) break; // already has correct value, no need to overwrite. /* otherwise, replace the value */ /* fall thru intended */ case X_CreatedKey: UT_ASSERT(hKeyApplication); eResult = RegSetValueEx(hKeyApplication,NULL,0,REG_SZ,xx(szApplicationName)); if (eResult != ERROR_SUCCESS) goto CleanupMess; break; } /////////////////////////////////////////////////////////////////// // Inspect the topic key // HKEY_CLASSES_ROOT\<foo>\shell\open\ddeexec\topic = System /////////////////////////////////////////////////////////////////// switch ( _fetchKey(hKeyDdeExec,"topic",&hKeyTopic) ) { case X_Error: goto CleanupMess; case X_ExistingKey: UT_ASSERT(hKeyTopic); len = G_N_ELEMENTS((LPWSTR)buf); eResult = RegQueryValueExW(hKeyTopic,NULL,0,&dType,(LPBYTE)buf,&len); if ((eResult==ERROR_SUCCESS) && (dType==REG_SZ) && (wcsicmp((LPWSTR)buf,MY_DDE_TOPICNAME)==0)) break; // already has correct value, no need to overwrite. /* otherwise, replace the value */ /* fall thru intended */ case X_CreatedKey: UT_ASSERT(hKeyTopic); eResult = RegSetValueExW(hKeyTopic,NULL,0,REG_SZ,xxw(MY_DDE_TOPICNAME)); if (eResult != ERROR_SUCCESS) goto CleanupMess; break; } /////////////////////////////////////////////////////////////////// // Set the default icon for the suffix (this is for Explorer et al. // HKEY_CLASSES_ROOT\<foo>\DefaultIcon = <exe_pathname,2> /////////////////////////////////////////////////////////////////// wsprintfW(bufDefaultIconValue,L"%s,%d",szExePathname,DOCUMENT_ICON_POSITION); switch ( _fetchKey(hKeyFoo,"DefaultIcon",&hKeyDefaultIcon) ) { case X_Error: goto CleanupMess; case X_ExistingKey: UT_ASSERT(hKeyDefaultIcon); len = G_N_ELEMENTS((LPWSTR)buf); eResult = RegQueryValueExW(hKeyDefaultIcon,NULL,0,&dType,(LPBYTE)buf,&len); if ((eResult==ERROR_SUCCESS) && (dType==REG_SZ) && (lstrcmpiW((LPWSTR)buf,bufDefaultIconValue)==0)) break; // already has correct value, no need to overwrite. /* otherwise, replace the value */ /* fall thru intended */ case X_CreatedKey: UT_ASSERT(hKeyDefaultIcon); eResult = RegSetValueExW(hKeyDefaultIcon,NULL,0,REG_SZ,xxw(bufDefaultIconValue)); if (eResult != ERROR_SUCCESS) goto CleanupMess; break; } /////////////////////////////////////////////////////////////////// // Success. /////////////////////////////////////////////////////////////////// UT_DEBUGMSG(("Successfully stuffed the registry for suffix [%s].\n",szSuffix)); CleanupMess: #define KILLKEY(k) do { if (k) RegCloseKey(k); (k) = 0; } while (0) KILLKEY(hKeyFoo); KILLKEY(hKeySuffix); KILLKEY(hKeyShell); KILLKEY(hKeyCommand); KILLKEY(hKeyOpen); KILLKEY(hKeyDdeExec); KILLKEY(hKeyApplication); KILLKEY(hKeyTopic); KILLKEY(hKeyDefaultIcon); return; }
int Songs::LoadHistory(const char *userId) { //ここでサーバに接続して前回と前々回の点数を受信 HINTERNET hSession, hConnect, hRequest; URL_COMPONENTS urlComponents; WCHAR szHostName[256], szUrlPath[2048]; //URL WCHAR szUrl[256] = L"http://globalstudios.jp/mai-archive/api_history.php?user="******"%d, %d, %d, %d, %d, %d, %d, %d\n", userId[0], userId[1],userId[2],userId[3],userId[4],userId[5], userId[6], userId[7]); // printfDx("%d, %d, %d, %d, %d, %d\n", 'd', 'a', 'i', 'c', 'h', 'i'); mbstowcs(szUserId, userId, 256); wcscat(szUrl, szUserId); LPBYTE lpData; DWORD dwSize; hSession = WinHttpOpen(L"Sample Application/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (hSession == NULL) return -1; ZeroMemory(&urlComponents, sizeof(URL_COMPONENTS)); urlComponents.dwStructSize = sizeof(URL_COMPONENTS); urlComponents.lpszHostName = szHostName; urlComponents.dwHostNameLength = sizeof(szHostName) / sizeof(WCHAR); urlComponents.lpszUrlPath = szUrlPath; urlComponents.dwUrlPathLength = sizeof(szUrlPath) / sizeof(WCHAR); if (!WinHttpCrackUrl(szUrl, lstrlenW(szUrl), 0, &urlComponents)) { WinHttpCloseHandle(hSession); return -1; } //接続 hConnect = WinHttpConnect(hSession, szHostName, INTERNET_DEFAULT_PORT, 0); if (hConnect == NULL) { WinHttpCloseHandle(hSession); return -1; } hRequest = WinHttpOpenRequest(hConnect, L"GET", szUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (hRequest == NULL) { WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return -1; } if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, 0)) { WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return 0; } WinHttpReceiveResponse(hRequest, NULL); //ボディ取得 lpData = ReadData(hRequest, &dwSize); // printfDx((char*)lpData); for (int i = 0; i < NUMSONGS; i++) { char* temp = NULL; char* ctx;//内部的に使用するので深く考えない if (i == 0) { temp = strtok_s((char*)lpData, "\n", &ctx); } else { temp = strtok_s(0, "\n", &ctx); } if (temp == NULL)break; int history[2]; int hoge; sscanf_s(temp, "%d||%d||%d", &hoge, &history[0], &history[1]); //以下の式を実行することによってデータを保存 //song[Search(<曲ID>)]->songHistory->Set(<前回と前々回の点数(配列ポインタ)>); song[Search(hoge)]->songHistory->Set(history); } HeapFree(GetProcessHeap(), 0, lpData); WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return 0; }
BOOL apxJavaLoadMainClass(APXHANDLE hJava, LPCSTR szClassName, LPCSTR szMethodName, LPCVOID lpArguments) { LPWSTR *lpArgs = NULL; DWORD nArgs; LPAPXJAVAVM lpJava; jclass jClazz; LPCSTR szSignature = "([Ljava/lang/String;)V"; if (hJava->dwType != APXHANDLE_TYPE_JVM) return FALSE; lpJava = APXHANDLE_DATA(hJava); if (!lpJava) return FALSE; if (IS_EMPTY_STRING(szMethodName)) szMethodName = "main"; if (lstrcmpA(szClassName, "java/lang/System") == 0) { /* Usable only for exit method, so force */ szSignature = "(I)V"; szMethodName = "exit"; } lstrlcpyA(lpJava->clWorker.sClazz, 1024, szClassName); lstrlcpyA(lpJava->clWorker.sMethod, 512, szMethodName); jClazz = JNICALL_1(FindClass, JAVA_CLASSSTRING); if (!jClazz) { JVM_EXCEPTION_CLEAR(lpJava); apxLogWrite(APXLOG_MARK_ERROR "FindClass " JAVA_CLASSSTRING " failed"); return FALSE; } lpJava->clString.jClazz = JNICALL_1(NewGlobalRef, jClazz); JNI_LOCAL_UNREF(jClazz); /* Find the class */ jClazz = JNICALL_1(FindClass, szClassName); if (!jClazz) { JVM_EXCEPTION_CLEAR(lpJava); apxLogWrite(APXLOG_MARK_ERROR "FindClass %s failed", szClassName); return FALSE; } /* Make the class global so that worker thread can attach */ lpJava->clWorker.jClazz = JNICALL_1(NewGlobalRef, jClazz); JNI_LOCAL_UNREF(jClazz); lpJava->clWorker.jMethod = JNICALL_3(GetStaticMethodID, lpJava->clWorker.jClazz, szMethodName, szSignature); if (!lpJava->clWorker.jMethod) { JVM_EXCEPTION_CLEAR(lpJava); apxLogWrite(APXLOG_MARK_ERROR "Method 'static void %s(String[])' not found in Class %s", szMethodName, szClassName); return FALSE; } if (lstrcmpA(szClassName, "java/lang/System")) { nArgs = apxMultiSzToArrayW(hJava->hPool, lpArguments, &lpArgs); lpJava->clWorker.jArgs = JNICALL_3(NewObjectArray, nArgs, lpJava->clString.jClazz, NULL); if (nArgs) { DWORD i; for (i = 0; i < nArgs; i++) { jstring arg = JNICALL_2(NewString, lpArgs[i], lstrlenW(lpArgs[i])); JNICALL_3(SetObjectArrayElement, lpJava->clWorker.jArgs, i, arg); apxLogWrite(APXLOG_MARK_DEBUG "argv[%d] = %S", i, lpArgs[i]); } } apxFree(lpArgs); } return TRUE; }
/* ANSI version only */ DWORD apxJavaCmdInitialize(APXHANDLE hPool, LPCWSTR szClassPath, LPCWSTR szClass, LPCWSTR szOptions, DWORD dwMs, DWORD dwMx, DWORD dwSs, LPCWSTR szCmdArgs, LPWSTR **lppArray) { DWORD i, nJVM, nCmd, nTotal, lJVM, lCmd; LPWSTR p; /* Calculate the number of all arguments */ nTotal = 0; if (szClassPath) ++nTotal; if (szClass) ++nTotal; lJVM = __apxGetMultiSzLengthW(szOptions, &nJVM); nTotal += nJVM; lCmd = __apxGetMultiSzLengthW(szCmdArgs, &nCmd); nTotal += nCmd; if (dwMs) ++nTotal; if (dwMx) ++nTotal; if (dwSs) ++nTotal; if (nTotal == 0) return 0; /* Allocate the array to store all arguments' pointers */ *lppArray = (LPWSTR *)apxPoolAlloc(hPool, (nTotal + 2) * sizeof(LPWSTR)); /* Process JVM options */ if (nJVM && lJVM) { p = (LPWSTR)apxPoolAlloc(hPool, (lJVM + 1) * sizeof(WCHAR)); AplCopyMemory(p, szOptions, (lJVM + 1) * sizeof(WCHAR) + sizeof(WCHAR)); for (i = 0; i < nJVM; i++) { (*lppArray)[i] = p; while (*p) p++; p++; } } /* Process the 3 extra JVM options */ if (dwMs) { p = (LPWSTR)apxPoolAlloc(hPool, 64 * sizeof(WCHAR)); wsprintfW(p, L"-Xms%dm", dwMs); (*lppArray)[i++] = p; } if (dwMx) { p = (LPWSTR)apxPoolAlloc(hPool, 64 * sizeof(WCHAR)); wsprintfW(p, L"-Xmx%dm", dwMx); (*lppArray)[i++] = p; } if (dwSs) { p = (LPWSTR)apxPoolAlloc(hPool, 64 * sizeof(WCHAR)); wsprintfW(p, L"-Xss%dk", dwSs); (*lppArray)[i++] = p; } /* Process the classpath and class */ if (szClassPath) { p = (LPWSTR)apxPoolAlloc(hPool, (lstrlenW(JAVA_CLASSPATH_W) + lstrlenW(szClassPath)) * sizeof(WCHAR)); lstrcpyW(p, JAVA_CLASSPATH_W); lstrcatW(p, szClassPath); (*lppArray)[i++] = p; } if (szClass) { p = (LPWSTR)apxPoolAlloc(hPool, (lstrlenW(szClass)) * sizeof(WCHAR)); lstrcpyW(p, szClass); (*lppArray)[i++] = p; } /* Process command arguments */ if (nCmd && lCmd) { p = (LPWSTR)apxPoolAlloc(hPool, (lCmd + 1) * sizeof(WCHAR)); AplCopyMemory(p, szCmdArgs, (lCmd + 1) * sizeof(WCHAR) + sizeof(WCHAR)); for (; i < nTotal; i++) { (*lppArray)[i] = p; while (*p) p++; p++; } } (*lppArray)[++i] = NULL; return nTotal; }
static BOOL __apxLoadJvmDll(LPCWSTR szJvmDllPath) { UINT errMode; WCHAR jreAltPath[SIZ_PATHLEN]; LPWSTR dllJvmPath = (LPWSTR)szJvmDllPath; DYNLOAD_FPTR_DECLARE(SetDllDirectoryW); if (!IS_INVALID_HANDLE(_st_sys_jvmDllHandle)) return TRUE; /* jvm.dll is already loaded */ if (!dllJvmPath || *dllJvmPath == L'\0') dllJvmPath = apxGetJavaSoftRuntimeLib(NULL); if (!dllJvmPath) return FALSE; if (GetFileAttributesW(dllJvmPath) == INVALID_FILE_ATTRIBUTES) { /* DAEMON-184: RuntimeLib registry key is invalid. * Check from Jre JavaHome directly */ LPWSTR szJreHome = apxGetJavaSoftHome(NULL, TRUE); apxLogWrite(APXLOG_MARK_DEBUG "Invalid RuntimeLib '%S'", dllJvmPath); if (szJreHome) { apxLogWrite(APXLOG_MARK_DEBUG "Using Jre JavaHome '%S'", szJreHome); lstrlcpyW(jreAltPath, SIZ_PATHLEN, szJreHome); lstrlcatW(jreAltPath, SIZ_PATHLEN, L"\\bin\\server\\jvm.dll"); dllJvmPath = jreAltPath; } } /* Suppress the not found system popup message */ errMode = SetErrorMode(SEM_FAILCRITICALERRORS); apxLogWrite(APXLOG_MARK_DEBUG "loading jvm '%S'", dllJvmPath); _st_sys_jvmDllHandle = LoadLibraryExW(dllJvmPath, NULL, 0); if (IS_INVALID_HANDLE(_st_sys_jvmDllHandle) && GetFileAttributesW(dllJvmPath) != INVALID_FILE_ATTRIBUTES) { /* There is a file but cannot be loaded. * Try to load the MSVCRTxx.dll before JVM.dll */ WCHAR jreBinPath[SIZ_PATHLEN]; WCHAR crtBinPath[SIZ_PATHLEN]; DWORD i, l = 0; lstrlcpyW(jreBinPath, SIZ_PATHLEN, dllJvmPath); for (i = lstrlenW(jreBinPath); i > 0, l < 2; i--) { if (jreBinPath[i] == L'\\' || jreBinPath[i] == L'/') { jreBinPath[i] = L'\0'; lstrlcpyW(crtBinPath, SIZ_PATHLEN, jreBinPath); lstrlcatW(crtBinPath, SIZ_PATHLEN, MSVCRT71_DLLNAME); if (GetFileAttributesW(crtBinPath) != INVALID_FILE_ATTRIBUTES) { if (LoadLibraryW(crtBinPath)) { /* Found MSVCRTxx.dll */ apxLogWrite(APXLOG_MARK_DEBUG "preloaded '%S'", crtBinPath); break; } } l++; } } } /* This shuldn't happen, but try to search in %PATH% */ if (IS_INVALID_HANDLE(_st_sys_jvmDllHandle)) _st_sys_jvmDllHandle = LoadLibraryExW(dllJvmPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); if (IS_INVALID_HANDLE(_st_sys_jvmDllHandle)) { WCHAR jreBinPath[SIZ_PATHLEN]; DWORD i, l = 0; lstrlcpyW(jreBinPath, SIZ_PATHLEN, dllJvmPath); DYNLOAD_FPTR_ADDRESS(SetDllDirectoryW, KERNEL32); for (i = lstrlenW(jreBinPath); i > 0, l < 2; i--) { if (jreBinPath[i] == L'\\' || jreBinPath[i] == L'/') { jreBinPath[i] = L'\0'; DYNLOAD_CALL(SetDllDirectoryW)(jreBinPath); apxLogWrite(APXLOG_MARK_DEBUG "Setting DLL search path to '%S'", jreBinPath); l++; } } _st_sys_jvmDllHandle = LoadLibraryExW(dllJvmPath, NULL, 0); if (IS_INVALID_HANDLE(_st_sys_jvmDllHandle)) _st_sys_jvmDllHandle = LoadLibraryExW(dllJvmPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); } /* Restore the error mode signalization */ SetErrorMode(errMode); if (IS_INVALID_HANDLE(_st_sys_jvmDllHandle)) { apxLogWrite(APXLOG_MARK_SYSERR); return FALSE; } DYNLOAD_FPTR_LOAD(JNI_GetDefaultJavaVMInitArgs, _st_sys_jvmDllHandle); DYNLOAD_FPTR_LOAD(JNI_CreateJavaVM, _st_sys_jvmDllHandle); DYNLOAD_FPTR_LOAD(JNI_GetCreatedJavaVMs, _st_sys_jvmDllHandle); if (!DYNLOAD_FPTR(JNI_GetDefaultJavaVMInitArgs) || !DYNLOAD_FPTR(JNI_CreateJavaVM) || !DYNLOAD_FPTR(JNI_GetCreatedJavaVMs)) { apxLogWrite(APXLOG_MARK_SYSERR); FreeLibrary(_st_sys_jvmDllHandle); _st_sys_jvmDllHandle = NULL; return FALSE; } /* Real voodo ... */ return TRUE; }
HRESULT RetrieveFromFileStore( CTransCache *pTransCache ) { HRESULT hr=S_OK; TRANSCACHEINFO *pTCInfo = NULL; DWORD dwCache = 0; WCHAR wzParentDirName[MAX_PATH+1]; WCHAR wzSubDirName[MAX_PATH+1]; DWORD dwLen =0; WCHAR wzCacheLocation[MAX_PATH+1]; ASSERT(pTransCache); pTCInfo = (TRANSCACHEINFO*) pTransCache->_pInfo; dwCache = pTransCache->GetCacheType(); dwLen = MAX_PATH; if(FAILED(hr = CreateAssemblyDirPath( pTransCache->GetCustomPath(), 0, pTransCache->GetCacheType(), 0, wzCacheLocation, &dwLen))) goto exit; hr = GetCacheDirsFromTransCache(pTransCache, 0, wzParentDirName, wzSubDirName); if(FAILED(hr)) goto exit; if( (lstrlenW(wzCacheLocation) + lstrlenW(wzParentDirName) + lstrlenW(wzSubDirName) + lstrlenW(g_szDotDLL) + max(lstrlenW(wzParentDirName), lstrlen(pTCInfo->pwzName)) + 4) >= MAX_PATH) { hr = HRESULT_FROM_WIN32(FUSION_E_INVALID_NAME); goto exit; } PathAddBackslash(wzCacheLocation); StrCat(wzCacheLocation, wzParentDirName); PathAddBackslash(wzCacheLocation); StrCat(wzCacheLocation, wzSubDirName); if(GetFileAttributes(wzCacheLocation) == (DWORD) -1) { hr = DB_S_NOTFOUND; goto exit; } else { hr = DB_S_FOUND; } PathAddBackslash(wzCacheLocation); { StrCat(wzCacheLocation, pTCInfo->pwzName); dwLen = lstrlenW(wzCacheLocation); StrCat(wzCacheLocation, g_szDotDLL); if(GetFileAttributes(wzCacheLocation) == (DWORD) -1) { // there is no AsmName.dll look for AsmName.exe StrCpy(wzCacheLocation+dwLen, g_szDotEXE); } } SAFEDELETEARRAY(pTCInfo->pwzPath); pTCInfo->pwzPath = WSTRDupDynamic(wzCacheLocation); if(!pTCInfo->pwzPath) { hr = E_OUTOFMEMORY; goto exit; } exit : return hr; }
void browser::tagParsing(WCHAR* message, HDC hdc, HWND mainhWnd, int yPos) { WCHAR tempIp[MAXLEN] = { '\0', }; WCHAR tempPort[MAXLEN] = { '\0', }; if (ip != NULL && port != NULL) { lstrcpyW(tempIp, ip); lstrcpyW(tempPort, port); } initialize(); if (ip != NULL && port != NULL) { lstrcpyW(ip, tempIp); lstrcpyW(port, tempPort); } unsigned int i = 0; int tagFlag = 0; //tag시작을 알림 int outTagFlag = 0; //태그의 종료를 알리는 변수 int headerFlag = 0; int tempBodyFlag = 0; //body안에서 tag의 시작을 알림 int bodyFlag = 0; //body의 시작을 알림 int fontHeight = 0; int styleFlag = 0; int htempX = 0; int htempY = 0; WCHAR htempUri[MAXLEN] = { '\0', }; WCHAR* tempMessage = NULL; wstring fileName = TEXT(""); wstring tempTag = TEXT(""); //tag내용 저장 wstring body = TEXT(""); //tag사이의 내용 담기 wstring hTag[] = { TEXT("<h1>"), TEXT("<h2>"), TEXT("<h3>"), TEXT("<h4>"), TEXT("<h5>"), TEXT("<h6>") }; RECT rect = {0, }; HFONT hFont = 0, oldFont = 0; GetClientRect(mainhWnd, &rect); x = rect.left; y = rect.top; y += 100 - yPos; //메시지만큼 배열 생성 tempMessage = (WCHAR*)malloc(sizeof(WCHAR) * (lstrlenW(message) + 1)); memset(tempMessage, '\0', (lstrlenW(message) + 1)); lstrcpyW(tempMessage, message); //에러일 경우 if (lstrcmpW(tempMessage, TEXT("HTTP/1.1 404 Not Found")) == 0) { TextOut(hdc, x, y, tempMessage, lstrlenW(tempMessage)); return; } else if (lstrcmpW(tempMessage, TEXT("HTTP/1.1 400 Bad Request")) == 0) { TextOut(hdc, x, y, tempMessage, lstrlenW(tempMessage)); return; } while (1) { //body가 나왔을때의 동작 정의 if (tempMessage[i] == '<' && bodyFlag == 1) { tempTag += tempMessage[i]; i++; tagFlag = 1; continue; } if (tempMessage[i] == '>' && bodyFlag == 1) { tempTag += tempMessage[i]; if (outTagFlag == 0) // </~>이 아닐때 { ///////////////////////////////////////////////////////////////////// const WCHAR* p = NULL; p = wcsstr(tempTag.c_str(), TEXT("img src")); /* 이미지 파일 이름 찾기*/ if (p != NULL) { //파일이 나왔을 때 그 전 바디 내용 출력 TextOut(hdc, x, y, body.c_str(), body.length()); x += (body.length() * 10); int pivot = 0; for (int j = 0; tempTag[j] != NULL; j++) { if (tempTag[j] != '\"' && pivot == 1) { fileName += tempTag[j]; } if (tempTag[j] == '\"' && pivot == 0) { j++; fileName += tempTag[j]; pivot = 1; } else if (tempTag[j] == '\"' && pivot == 1) { break; } } //파일 처리 함수 fileProcess(fileName, hdc); //변수 초기화 fileName = TEXT(""); body = TEXT(""); tempTag = TEXT(""); tagFlag = 0; i++; continue; } ///////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// p = wcsstr(tempTag.c_str(), TEXT("form action")); if (p != NULL) //form action 일 때 { WCHAR formTag[MAXLEN] = { '\0', }; lstrcpyW(formTag, tempTag.c_str()); p = wcstok(formTag, TEXT("\"")); p = wcstok(NULL, TEXT("\"")); printf("%s\n", p); //파일 p = wcstok(NULL, TEXT("\"")); p = wcstok(NULL, TEXT("\"")); printf("%s\n", p); //메시지 } //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// p = wcsstr(tempTag.c_str(), TEXT("input type")); if (p != NULL) { TextOut(hdc, x, y, body.c_str(), body.length()); WCHAR inputTag[MAXLEN] = { '\0', }; lstrcpyW(inputTag, tempTag.c_str()); p = wcstok(inputTag, TEXT("=")); p = wcstok(NULL, TEXT(" "));//edit p = wcstok(NULL, TEXT("\"")); p = wcstok(NULL, TEXT("\""));//name } ////////////////////////////////////////////////////// p = wcsstr(tempTag.c_str(), TEXT("a href")); if (p != NULL) { TextOut(hdc, x, y, body.c_str(), body.length()); x += (body.length() * 10); WCHAR inputTag[MAXLEN] = { '\0', }; lstrcpyW(inputTag, tempTag.c_str()); p = wcstok(inputTag, TEXT("\"")); p = wcstok(NULL, TEXT("\"")); htempX = x; htempY = y; wcscpy(htempUri, p); tagStack.push(TEXT("<a>")); } ////////////////////////////////////////////// //h~태그일때 h 확인 for (int j = 0; j < sizeof(hTag) / sizeof(hTag[0]); j++) { if (lstrcmpW(tempTag.c_str(), hTag[j].c_str()) == 0) //h태그라 판단 { switch (j) { case 0: fontHeight = 40; break; case 1: fontHeight = 35; break; case 2: fontHeight = 30; break; case 3: fontHeight = 25; break; case 4: fontHeight = 20; break; case 5: fontHeight = 15; break; } hFont = CreateFont(fontHeight, 0, 0, 0, 0, 0, 0, 0, DEFAULT_CHARSET, 0, 0, 0, VARIABLE_PITCH | FF_ROMAN, TEXT("Impect")); oldFont = (HFONT)SelectObject(hdc, hFont); tagStack.push(tempTag); } } //<br>, <h~>, ...등등 일 때 정의 if (lstrcmpW(tempTag.c_str(), TEXT("<br>")) == 0) { TextOut(hdc, x, y, body.c_str(), body.length()); x = rect.left; y += 30; } body = TEXT(""); tempTag = TEXT(""); outTagFlag = 0; tagFlag = 0; i++; continue; } else//새로나온 태그가 end tag일 때 { //</br>, </body> 일 때 정의 if (lstrcmpW(tempTag.c_str(), TEXT("<br>")) == 0) { TextOut(hdc, x, y, body.c_str(), body.length()); y += 30; tempTag = TEXT(""); body = TEXT(""); outTagFlag = 0; i++; continue; } /////////////////////////////////////////////////////// if (lstrcmpW(tempTag.c_str(), TEXT("<p>")) == 0) { TextOut(hdc, x, y, body.c_str(), body.length()); y += 30; tempTag = TEXT(""); body = TEXT(""); outTagFlag = 0; i++; continue; } if (!tagStack.empty()) { if (lstrcmpW(tagStack.top().c_str(), tempTag.c_str()) == 0) { //body짝일 때 if (lstrcmpW(tempTag.c_str(), TEXT("<body>")) == 0) { TextOut(hdc, x, y, body.c_str(), body.length()); bodyFlag = 0; tagStack.pop(); } //h~ 짝일 때 for (int j = 0; j < sizeof(hTag) / sizeof(hTag[0]); j++) { if (lstrcmpW(tempTag.c_str(), hTag[j].c_str()) == 0) //h태그라 판단 { TextOut(hdc, x, y, body.c_str(), body.length()); y += fontHeight; fontHeight = 0; SelectObject(hdc, oldFont); DeleteObject(hFont); tagStack.pop(); } } if (lstrcmpW(tempTag.c_str(), TEXT("<a>")) == 0) { SetTextColor(hdc, RGB(0, 0, 255)); TextOut(hdc, x, y, body.c_str(), body.length()); struct hyperLink tempLink = { 0, }; tempLink.x = htempX; tempLink.y = htempY; tempLink.width = body.length()*20; tempLink.height = 20; wsprintfW(tempLink.uri,TEXT("%s:%s/%s"),ip, port, htempUri); linker.push_back(tempLink); htempX = 0; htempY = 0; memset(htempUri, '\0', MAXLEN); x += (body.length() * 15); SetTextColor(hdc, RGB(0, 0, 0)); tagStack.pop(); } } else// 짝이 안 맞아서 종료 { break; } } } tempTag = TEXT(""); tagFlag = 0; body = TEXT(""); outTagFlag = 0; i++; continue; } ///////////////////////////////////////////////// if (tempMessage[i] == '<' && bodyFlag == 0) { tagFlag = 1; tempTag += tempMessage[i]; i++; continue; } if (tempMessage[i] == '>' && bodyFlag == 0) { tempTag += tempMessage[i]; if (outTagFlag == 0) { if (lstrcmpW(tempTag.c_str(), TEXT("<body>")) == 0) //body인지 판별 { bodyFlag = 1; tagStack.push(tempTag); } else if (lstrcmpW(tempTag.c_str(), TEXT("<center>")) == 0) //center인지 판별 { x = (rect.top + rect.right) / 2; tagStack.push(tempTag); } else if (lstrcmpW(tempTag.c_str(), TEXT("<title>")) == 0) { //no action tagStack.push(tempTag); } else if (lstrcmpW(tempTag.c_str(), TEXT("<style>")) == 0) { //no action tagStack.push(tempTag); } else if (lstrcmpW(tempTag.c_str(), TEXT("<span>")) == 0) { //no action tagStack.push(tempTag); } else if (lstrcmpW(tempTag.c_str(), TEXT("<br>")) == 0) { y += 30; x = rect.left; } else if (lstrcmpW(tempTag.c_str(), TEXT("<li>")) == 0) { tagStack.push(tempTag); } else { tagStack.push(tempTag); } } else //순서쌍 확인 { if (!tagStack.empty()) { if (lstrcmpW(tagStack.top().c_str(), tempTag.c_str()) == 0) { if (lstrcmpW(tagStack.top().c_str(), TEXT("<title>")) == 0) //title 짝 { SetWindowTextW(mainhWnd, body.c_str()); //타이틀의 내용으로 window 타이틀 변경 tagStack.pop(); } else if (lstrcmpW(tagStack.top().c_str(), TEXT("<center>")) == 0) //center 짝 { x = rect.top; //SetTextAlign(hdc, TA_LEFT); tagStack.pop(); } else if (lstrcmpW(tagStack.top().c_str(), TEXT("<style>")) == 0) { styleParsing(body, mainhWnd); tagStack.pop(); } else if (lstrcmpW(tagStack.top().c_str(), TEXT("<span>")) == 0) { TextOut(hdc, x, y, body.c_str(), body.length()); x += (body.length() * 16); tagStack.pop(); } else if (lstrcmpW(tagStack.top().c_str(), TEXT("<li>")) == 0) { TextOut(hdc, x, y, body.c_str(), body.length()); x = rect.left; y += 30; tagStack.pop(); }else if (lstrcmpW(tagStack.top().c_str(), TEXT("<html>")) == 0) { break; } } } } tempTag = TEXT(""); body = TEXT(""); tagFlag = 0; outTagFlag = 0; i++; continue; } if (tagFlag == 0) //tag가 아니면 body 변수에 모든 내용 저장 { body += tempMessage[i]; i++; continue; } if (tagFlag == 1) //태그 내용 저장 { if (tempMessage[i] == '/') { tagFlag = 1; outTagFlag = 1; //끝 태그 i++; continue; } if (tempMessage[i] >= 'A' && tempMessage[i] <= 'Z') //소문자로 만들기 { tempTag += tempMessage[i] + 32; } else { tempTag += tempMessage[i]; } i++; continue; } //////////////////////////////////////////////////// i++; } }
SYSLIBFUNC(DWORD) StrSplitToStringsExW(LPCWSTR lpSource,DWORD dwSourceSize,LPWSTR **lpppStrings,DWORD dwFlags,WCHAR wSeparator) { DWORD dwCount=0; do { if (!SYSLIB_SAFE::CheckStrParamW(lpSource,dwSourceSize)) break; if (!dwSourceSize) { dwSourceSize=lstrlenW(lpSource); if (!dwSourceSize) break; } LPCWSTR lpStrEnd=lpSource+dwSourceSize; LPWSTR *lppStrings=NULL; while (lpSource < lpStrEnd) { LPCWSTR lpStrStart=lpSource; DWORD dwStrSize; if (dwFlags & STRSPLIT_USE_SEPARATOR) { LPCWSTR lpCurEnd=lpSource; while ((lpCurEnd < lpStrEnd) && (*lpCurEnd != wSeparator)) lpCurEnd++; dwStrSize=(DWORD)(lpCurEnd-lpSource); lpSource=lpCurEnd+1; } else dwStrSize=GetStringSizeW(&lpSource,lpStrEnd); if (!dwStrSize) break; lppStrings=(LPWSTR *)MemRealloc(lppStrings,(dwCount+1)*sizeof(*lppStrings)); if (!lppStrings) { dwCount=0; break; } lppStrings[dwCount]=StrDuplicateW(lpStrStart,dwStrSize); if (!lppStrings[dwCount]) { MemFreeArrayOfPointers((LPVOID*)lppStrings,dwCount); dwCount=0; break; } dwCount++; } if (!dwCount) break; *lpppStrings=lppStrings; } while (false); return dwCount; }
void browser::fileProcess(wstring fileName, HDC hdc) { FILE *checkFile = NULL; string mFileName = ""; char* mFileBuf = NULL; char mrBuf[MAXLEN] = { '\0', }; mFileName.assign(fileName.begin(), fileName.end()); printf("here is fileProcess\n"); if ((checkFile = fopen(mFileName.c_str(), "r")) == NULL) //파일이 없을때 파일 저장 { WCHAR filebuf[MAXLEN] = { '\0', }; //파일 이름을 포함하여 리퀘스트 요청 wsprintfW(filebuf, TEXT("GET /%s HTTP/1.1\r\nAccept:text/html, application/xhtml+xml, */*\r\nAccept-Language: ko-KR\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko\r\nAccept-Encoding: gzip, deflate\r\nHost: 52.192.132.151:8777:80\r\nDNT:1\r\nConnection: Keep-Alive\r\n"), fileName.c_str()); if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { return; } if (connect(sockfd, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) { return; } mFileBuf = (char*)malloc(sizeof(char) * lstrlenW(filebuf) + 1); memset(mFileBuf, '\0', lstrlenW(filebuf) + 1); mFileBuf = convertUnicodeToMultibyte(filebuf); send(sockfd, mFileBuf, lstrlenW(filebuf), 0); FILE* save = fopen(mFileName.c_str(), "wb"); int ret = 0; int filelength = 0; int headerFlag = 0; int mimeFlag = 0; int i = 0; while (1) { ret = recv(sockfd, mrBuf, 1024, 0); if (ret > 0) { i++; if (i == 2) //마임헤더 제거 { const char* p = NULL; p = strstr(mrBuf, "\r\n\r\n"); fwrite(p + strlen("\r\n\r\n"), ret - (p - mrBuf) - strlen("\r\n\r\n"), 1, save); //\r\n\r\n 이 후로 파일 저장 memset(mrBuf, '\0', 1024); continue; } if (i >= 3) { fwrite(mrBuf, ret, 1, save); } memset(mrBuf, '\0', 1024); } else { break; } } /* while (1) { ret = recv(sockfd, mrBuf, 1024, 0); if (ret > 0) { if (mimeFlag == 0) //마임헤더 제거 { const char* p = NULL; p = strstr(mrBuf, "\r\n\r\n"); printf("%s\n", p); fwrite(p + strlen("\r\n\r\n"), ret - (p - mrBuf) - strlen("\r\n\r\n"), 1, save); //\r\n\r\n 이 후로 파일 저장 mimeFlag = 1; memset(mrBuf, '\0', 1024); continue; } if (mimeFlag == 1) { fwrite(mrBuf, ret, 1, save); } memset(mrBuf, '\0', 1024); } else { break; } } */ fclose(save); closesocket(sockfd); } wstring fileExt = fileName.substr(fileName.find('.') + 1, fileName.length()); if (fileExt == TEXT("jpg")) //파일 확장자가 jpg이면 { if(checkFile != NULL) fclose(checkFile); jpgShow(fileName, hdc); } else if (fileExt == TEXT("bmp")) //bmp이면 { if (checkFile != NULL) fclose(checkFile); bmpShow(fileName, hdc); } }
VOID PRINT_RECORD(PEVENTLOGRECORD pRec) { UINT i; WCHAR *str; SYSTEMTIME time; DPRINT("Length = %lu\n", pRec->Length); DPRINT("Reserved = 0x%x\n", pRec->Reserved); DPRINT("RecordNumber = %lu\n", pRec->RecordNumber); EventTimeToSystemTime(pRec->TimeGenerated, &time); DPRINT("TimeGenerated = %hu.%hu.%hu %hu:%hu:%hu\n", time.wDay, time.wMonth, time.wYear, time.wHour, time.wMinute, time.wSecond); EventTimeToSystemTime(pRec->TimeWritten, &time); DPRINT("TimeWritten = %hu.%hu.%hu %hu:%hu:%hu\n", time.wDay, time.wMonth, time.wYear, time.wHour, time.wMinute, time.wSecond); DPRINT("EventID = %lu\n", pRec->EventID); switch (pRec->EventType) { case EVENTLOG_ERROR_TYPE: DPRINT("EventType = EVENTLOG_ERROR_TYPE\n"); break; case EVENTLOG_WARNING_TYPE: DPRINT("EventType = EVENTLOG_WARNING_TYPE\n"); break; case EVENTLOG_INFORMATION_TYPE: DPRINT("EventType = EVENTLOG_INFORMATION_TYPE\n"); break; case EVENTLOG_AUDIT_SUCCESS: DPRINT("EventType = EVENTLOG_AUDIT_SUCCESS\n"); break; case EVENTLOG_AUDIT_FAILURE: DPRINT("EventType = EVENTLOG_AUDIT_FAILURE\n"); break; default: DPRINT("EventType = %hu\n", pRec->EventType); } DPRINT("NumStrings = %hu\n", pRec->NumStrings); DPRINT("EventCategory = %hu\n", pRec->EventCategory); DPRINT("ReservedFlags = 0x%x\n", pRec->ReservedFlags); DPRINT("ClosingRecordNumber = %lu\n", pRec->ClosingRecordNumber); DPRINT("StringOffset = %lu\n", pRec->StringOffset); DPRINT("UserSidLength = %lu\n", pRec->UserSidLength); DPRINT("UserSidOffset = %lu\n", pRec->UserSidOffset); DPRINT("DataLength = %lu\n", pRec->DataLength); DPRINT("DataOffset = %lu\n", pRec->DataOffset); DPRINT("SourceName: %S\n", (WCHAR *) (((PBYTE) pRec) + sizeof(EVENTLOGRECORD))); i = (lstrlenW((WCHAR *) (((PBYTE) pRec) + sizeof(EVENTLOGRECORD))) + 1) * sizeof(WCHAR); DPRINT("ComputerName: %S\n", (WCHAR *) (((PBYTE) pRec) + sizeof(EVENTLOGRECORD) + i)); if (pRec->StringOffset < pRec->Length && pRec->NumStrings) { DPRINT("Strings:\n"); str = (WCHAR *) (((PBYTE) pRec) + pRec->StringOffset); for (i = 0; i < pRec->NumStrings; i++) { DPRINT("[%u] %S\n", i, str); str = str + lstrlenW(str) + 1; } } DPRINT("Length2 = %lu\n", *(PDWORD) (((PBYTE) pRec) + pRec->Length - 4)); }
extern "C" HRESULT DAPI CertInstallSingleCertificate( __in HCERTSTORE hStore, __in PCCERT_CONTEXT pCertContext, __in LPCWSTR wzName ) { HRESULT hr = S_OK; CERT_BLOB blob = { }; DWORD dwKeySpec = 0; HCRYPTPROV hCsp = NULL; LPWSTR pwszTmpContainer = NULL; LPWSTR pwszProviderName = NULL; DWORD dwProviderType = 0; BOOL fAcquired = TRUE; SECURITY_DESCRIPTOR* pSecurity = NULL; SECURITY_DESCRIPTOR* pSecurityNew = NULL; // Update the friendly name of the certificate to be configured. blob.pbData = (BYTE*)wzName; blob.cbData = (lstrlenW(wzName) + 1) * sizeof(WCHAR); // including terminating null if (!::CertSetCertificateContextProperty(pCertContext, CERT_FRIENDLY_NAME_PROP_ID, 0, &blob)) { ExitWithLastError(hr, "Failed to set the friendly name of the certificate: %ls", wzName); } if (!::CertAddCertificateContextToStore(hStore, pCertContext, CERT_STORE_ADD_REPLACE_EXISTING, NULL)) { ExitWithLastError(hr, "Failed to add certificate to the store."); } // if the certificate has a private key, grant Administrators access if (CertHasPrivateKey(pCertContext, &dwKeySpec)) { if (AT_KEYEXCHANGE == dwKeySpec || AT_SIGNATURE == dwKeySpec) { // We added a CSP key hr = GetCryptProvFromCert(NULL, pCertContext, &hCsp, &dwKeySpec, &fAcquired, &pwszTmpContainer, &pwszProviderName, &dwProviderType); ExitOnFailure(hr, "Failed to get handle to CSP"); hr = GetProvSecurityDesc(hCsp, &pSecurity); ExitOnFailure(hr, "Failed to get security descriptor of CSP"); hr = AclAddAdminToSecurityDescriptor(pSecurity, &pSecurityNew); ExitOnFailure(hr, "Failed to create new security descriptor"); hr = SetProvSecurityDesc(hCsp, pSecurityNew); ExitOnFailure(hr, "Failed to set Admin ACL on CSP"); } if (CERT_NCRYPT_KEY_SPEC == dwKeySpec) { // We added a CNG key // TODO change ACL on CNG key } } LExit: if (hCsp) { FreeCryptProvFromCert(fAcquired, hCsp, NULL, dwProviderType, NULL); } ReleaseMem(pSecurity); if (pSecurityNew) { AclFreeSecurityDescriptor(pSecurityNew); } return hr; }
void ME_InsertTextFromCursor(ME_TextEditor *editor, int nCursor, const WCHAR *str, int len, ME_Style *style) { const WCHAR *pos; ME_Cursor *p = NULL; int oldLen; /* FIXME really HERE ? */ if (ME_IsSelection(editor)) ME_DeleteSelection(editor); /* FIXME: is this too slow? */ /* Didn't affect performance for WM_SETTEXT (around 50sec/30K) */ oldLen = ME_GetTextLength(editor); /* text operations set modified state */ editor->nModifyStep = 1; assert(style); assert(nCursor>=0 && nCursor<editor->nCursors); if (len == -1) len = lstrlenW(str); /* grow the text limit to fit our text */ if(editor->nTextLimit < oldLen +len) editor->nTextLimit = oldLen + len; pos = str; while (len) { /* FIXME this sucks - no respect for unicode (what else can be a line separator in unicode?) */ while(pos - str < len && *pos != '\r' && *pos != '\n' && *pos != '\t') pos++; if (pos != str) { /* handle text */ ME_InternalInsertTextFromCursor(editor, nCursor, str, pos-str, style, 0); } else if (*pos == '\t') { /* handle tabs */ WCHAR tab = '\t'; ME_InternalInsertTextFromCursor(editor, nCursor, &tab, 1, style, MERF_TAB); pos++; } else { /* handle EOLs */ ME_DisplayItem *tp, *end_run; ME_Style *tmp_style; int eol_len = 0; /* Find number of CR and LF in end of paragraph run */ if (*pos =='\r') { if (len > 1 && pos[1] == '\n') eol_len = 2; else if (len > 2 && pos[1] == '\r' && pos[2] == '\n') eol_len = 3; else eol_len = 1; } else { assert(*pos == '\n'); eol_len = 1; } pos += eol_len; if (!editor->bEmulateVersion10 && eol_len == 3) { /* handle special \r\r\n sequence (richedit 2.x and higher only) */ WCHAR space = ' '; ME_InternalInsertTextFromCursor(editor, nCursor, &space, 1, style, 0); } else { const WCHAR cr = '\r', *eol_str = str; if (!editor->bEmulateVersion10) { eol_str = &cr; eol_len = 1; } p = &editor->pCursors[nCursor]; if (p->nOffset) ME_SplitRunSimple(editor, p); tmp_style = ME_GetInsertStyle(editor, nCursor); /* ME_SplitParagraph increases style refcount */ tp = ME_SplitParagraph(editor, p->pRun, p->pRun->member.run.style, eol_str, eol_len, 0); p->pRun = ME_FindItemFwd(tp, diRun); p->pPara = tp; end_run = ME_FindItemBack(tp, diRun); ME_ReleaseStyle(end_run->member.run.style); end_run->member.run.style = tmp_style; p->nOffset = 0; } } len -= pos - str; str = pos; } }
static PDH_STATUS PdhiExpandCounterPath ( IN LPCWSTR szWildCardPath, IN LPVOID pExpandedPathList, IN LPDWORD pcchPathListLength, IN BOOL bUnicode ) { PPERF_MACHINE pMachine; PPDHI_COUNTER_PATH pWildCounterPath = NULL; WCHAR szWorkBuffer[MAX_PATH]; WCHAR szCounterName[MAX_PATH]; WCHAR szInstanceName[MAX_PATH]; LPWSTR szEndOfObjectString; LPWSTR szInstanceString; LPWSTR szCounterString; LPVOID szNextUserString; PERF_OBJECT_TYPE *pObjectDef; PERF_OBJECT_TYPE *pParentObjectDef; PERF_COUNTER_DEFINITION *pCounterDef; PERF_INSTANCE_DEFINITION *pInstanceDef; PERF_INSTANCE_DEFINITION *pParentInstanceDef; DWORD dwBufferRemaining; DWORD dwSize; DWORD dwSizeReturned = 0; PDH_STATUS pdhStatus = ERROR_SUCCESS; DWORD dwCtrNdx, dwInstNdx; BOOL bMoreData = FALSE; // allocate buffers pWildCounterPath = G_ALLOC (GPTR, PDHI_COUNTER_PATH_BUFFER_SIZE); if (pWildCounterPath == NULL) { // unable to allocate memory so bail out pdhStatus = PDH_MEMORY_ALLOCATION_FAILURE; } else { __try { dwBufferRemaining = *pcchPathListLength; szNextUserString = pExpandedPathList; } __except (EXCEPTION_EXECUTE_HANDLER) { pdhStatus = PDH_INVALID_ARGUMENT; } } if (pdhStatus == ERROR_SUCCESS) { // Parse wild card Path dwSize = G_SIZE (pWildCounterPath); if (ParseFullPathNameW (szWildCardPath, &dwSize, pWildCounterPath)) { // get the machine referenced in the path pMachine = GetMachine (pWildCounterPath->szMachineName, 0); if (pMachine != NULL) { if (wcsncmp (cszDoubleBackSlash, szWildCardPath, 2) == 0) { // the caller wants the machine name in the path so // copy it to the work buffer lstrcpyW (szWorkBuffer, pWildCounterPath->szMachineName); } else { *szWorkBuffer = 0; } // append the object name (since wild card objects are not // currently supported. lstrcatW (szWorkBuffer, cszBackSlash); lstrcatW (szWorkBuffer, pWildCounterPath->szObjectName); szEndOfObjectString = &szWorkBuffer[lstrlenW(szWorkBuffer)]; // get object pointer (since objects are not wild) pObjectDef = GetObjectDefByName ( pMachine->pSystemPerfData, pMachine->dwLastPerfString, pMachine->szPerfStrings, pWildCounterPath->szObjectName); if (pObjectDef != NULL) { // for each counters and identify matches pCounterDef = FirstCounter (pObjectDef); for (dwCtrNdx = 0; dwCtrNdx < pObjectDef->NumCounters; dwCtrNdx++) { // for each counter check instances (if supported) // and keep matches if ((pCounterDef->CounterNameTitleIndex > 0) && (pCounterDef->CounterNameTitleIndex < pMachine->dwLastPerfString ) && (!((pCounterDef->CounterType & PERF_DISPLAY_NOSHOW) && // this is a hack because this type is not defined correctly (pCounterDef->CounterType != PERF_AVERAGE_BULK)))) { // look up name of each object & store size lstrcpyW (szCounterName, pMachine->szPerfStrings[pCounterDef->CounterNameTitleIndex]); if (WildStringMatchW(pWildCounterPath->szCounterName, szCounterName)) { // if this object has instances, then walk down // the instance list and save any matches if (pObjectDef->NumInstances != PERF_NO_INSTANCES) { // then walk instances to find matches pInstanceDef = FirstInstance (pObjectDef); if (pObjectDef->NumInstances > 0) { for (dwInstNdx = 0; dwInstNdx < (DWORD)pObjectDef->NumInstances; dwInstNdx++) { szInstanceString = szEndOfObjectString; if (pInstanceDef->ParentObjectTitleIndex > 0) { // then add in parent instance name pParentObjectDef = GetObjectDefByTitleIndex ( pMachine->pSystemPerfData, pInstanceDef->ParentObjectTitleIndex); if (pParentObjectDef != NULL) { pParentInstanceDef = GetInstance ( pParentObjectDef, pInstanceDef->ParentObjectInstance); if (pParentInstanceDef != NULL) { GetInstanceNameStr (pParentInstanceDef, szInstanceName, pObjectDef->CodePage); if (WildStringMatchW (pWildCounterPath->szParentName, szInstanceName)) { // add this string szInstanceString = szEndOfObjectString; lstrcpyW (szInstanceString, cszLeftParen); lstrcatW (szInstanceString, szInstanceName); lstrcatW (szInstanceString, cszSlash); } else { // get next instance and continue pInstanceDef = NextInstance(pInstanceDef); continue; } } else { // unable to locate parent instance // so cancel this one, then // get next instance and continue pInstanceDef = NextInstance(pInstanceDef); continue; } } else { // unable to locate parent object // so cancel this one, then // get next instance and continue pInstanceDef = NextInstance(pInstanceDef); continue; } } else { // no parent name so continue szInstanceString = szEndOfObjectString; lstrcpyW (szInstanceString, cszSlash); } GetInstanceNameStr (pInstanceDef, szInstanceName, pObjectDef->CodePage); // // BUGBUG: need to do something with indexes. // // if this instance name matches, then keep it if (WildStringMatchW (pWildCounterPath->szInstanceName, szInstanceName)) { lstrcatW (szInstanceString, szInstanceName); lstrcatW (szInstanceString, cszRightParenBackSlash); // now append this counter name lstrcatW (szInstanceString, szCounterName); // add it to the user's buffer if there's room dwSize = lstrlenW(szWorkBuffer) + 1; if (!bMoreData && (dwSize < dwBufferRemaining)) { if (bUnicode) { lstrcpyW ((LPWSTR)szNextUserString, szWorkBuffer); (LPBYTE)szNextUserString += dwSize * sizeof(WCHAR); } else { wcstombs ((LPSTR)szNextUserString, szWorkBuffer, dwSize); (LPBYTE)szNextUserString += dwSize * sizeof(CHAR); } dwSizeReturned += dwSize; dwBufferRemaining -= dwSize; } else { // they've run out of buffer so just update the size required bMoreData = TRUE; dwSizeReturned += dwSize; } } else { // they don't want this instance so skip it } pInstanceDef = NextInstance (pInstanceDef); } // end for each instance in object } else { // this object supports instances, // but doesn't currently have any // so do nothing. } } else { // this object does not use instances so copy this // counter to the caller's buffer. szCounterString = szEndOfObjectString; lstrcpyW (szCounterString, cszBackSlash); lstrcatW (szCounterString, szCounterName); dwSize = lstrlenW(szWorkBuffer) + 1; if (!bMoreData && (dwSize < dwBufferRemaining)) { if (bUnicode) { lstrcpyW ((LPWSTR)szNextUserString, szWorkBuffer); (LPBYTE)szNextUserString += dwSize * sizeof(WCHAR); } else { wcstombs ((LPSTR)szNextUserString, szWorkBuffer, dwSize); (LPBYTE)szNextUserString += dwSize * sizeof(CHAR); } dwSizeReturned += dwSize; dwBufferRemaining -= dwSize; } else { // they've run out of buffer so bail out of this loop bMoreData = TRUE; dwSizeReturned += dwSize; } } } else { // this counter doesn't match so skip it } } else { // this counter string is not available } pCounterDef = NextCounter(pCounterDef); } // end for each counter in this object if (bUnicode) { *(LPWSTR)szNextUserString = 0; // MSZ terminator } else { *(LPSTR)szNextUserString = 0; // MSZ terminator } *pcchPathListLength = dwSizeReturned; if (bMoreData) { pdhStatus = PDH_MORE_DATA; } else { pdhStatus = ERROR_SUCCESS; } } else { // unable to find object pdhStatus = PDH_INVALID_PATH; } } else { // unable to connect to machine. pdhStatus = PDH_CANNOT_CONNECT_MACHINE; } } else { // unable to read input path string pdhStatus = PDH_INVALID_PATH; } } if (pWildCounterPath != NULL) G_FREE (pWildCounterPath); return pdhStatus; }
bool create_bob_txt() { wchar_t *buf = NULL; uint32_t buflen = 0; buflen = GetCurrentDirectoryW(buflen, buf); if (buflen == 0) { printf("[error] GetCurrentDirectoryW() failed!!! gle = 0x%08x\n", GetLastError()); return false; } buf = (PWSTR)malloc(sizeof(WCHAR)*buflen); if (GetCurrentDirectoryW(buflen, buf) == 0) { printf("[error] GetCurrentDirectoryW() failed!!! gle = 0x%08x\n", GetLastError()); free(buf); return false; } // current directory\\bob.txt 생성 wchar_t file_name[260]; if (!SUCCEEDED(StringCbPrintfW( file_name, sizeof(file_name), L"%ws\\bob.txt", buf))) { printf("[error] can not create bob.txt\n"); free(buf); return false; } free(buf); buf = NULL; if (is_file_existsW(file_name)) { DeleteFileW(file_name); } // 파일 생성 HANDLE file_handle = CreateFileW( file_name, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); ///////////////////////////////////////////////////////// DWORD numberOfBytesWritten; int result; unsigned char mark[3]; mark[0] = 0xEF; mark[1] = 0xBB; // UTF-8 mark[2] = 0xBF; wchar_t strUnicode[256] = L"안녕하세요 굳 굳굳 HelloWorld"; char strUtf8[256] = { 0, }; if (file_handle == INVALID_HANDLE_VALUE) { printf("[error] can not CreateFile, gle=0x%08x\n", GetLastError()); return false; } int nlen = WideCharToMultiByte(CP_UTF8, 0, strUnicode, lstrlenW(strUnicode), NULL, 0, NULL, NULL); WideCharToMultiByte(CP_UTF8, 0, strUnicode, lstrlenW(strUnicode), strUtf8, nlen, NULL, NULL); result = WriteFile(file_handle, &mark, 3, &numberOfBytesWritten, NULL); result = WriteFile(file_handle, strUtf8, strlen(strUtf8), &numberOfBytesWritten, NULL); // bob.txt -> bob2.txt 파일 복사 LPCWSTR file_name2 = L"C:\\Users\\kahissa\\Documents\\Visual Studio 2013\\Projects\\Console_test1\\bob2.txt"; CopyFile(file_name, file_name2, false); // bob2.txt 파일 내용 읽기 char readBuf[256] = { 0, }; DWORD dwRead = 0; BOOL readOK; HANDLE file_handle2 = CreateFileW(file_name2, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (file_handle2 == INVALID_HANDLE_VALUE) { printf("[error] can not file open, gle=0x%08x\n", GetLastError()); } readOK = ReadFile(file_handle2, readBuf, 256, &dwRead, NULL); // 파일 내용 읽어서 rBuf에 저장 if (readOK && dwRead == 0) printf("[error] can not read file, gle=0x%08x\n", GetLastError()); //readBuf에 UTF8 적용 int len = MultiByteToWideChar(CP_UTF8, 0, readBuf, strlen(readBuf), NULL, NULL); wchar_t MultiByte[256] = { 0, }; // UTF8 -> 유니코드 MultiByteToWideChar(CP_UTF8, 0, readBuf, strlen(readBuf), MultiByte, len); char MultiByte2[256] = { 0, }; /// 유니코드 -> 멀티바이트 len = WideCharToMultiByte(CP_ACP, 0, MultiByte, -1, NULL, 0, NULL, NULL); WideCharToMultiByte(CP_ACP, 0, MultiByte, -1, MultiByte2, len, NULL, NULL); printf("%s\n", MultiByte2 + 1); // header 다음부터 출력 CloseHandle(file_handle); CloseHandle(file_handle2); DeleteFile(file_name); DeleteFile(file_name2); return true; }
HRESULT StoreFusionInfo(IAssemblyName *pName, LPWSTR pszDir, DWORD *pdwFileSizeLow) { HRESULT hr = S_OK; WCHAR pszFilePath[MAX_PATH+1]; PBYTE pMVID=NULL; PBYTE pCustom=NULL; LPWSTR pszCustomString=NULL; LPWSTR pszURL=NULL; LPWSTR pszDisplayName=NULL; DWORD cbSize=0; BOOL fRet = FALSE; DWORD dwSize; LPWSTR pszBuf=NULL; HINI hIni=NULL; if(( lstrlenW(pszDir) + lstrlenW(g_FusionInfoFile) + 1) >= MAX_PATH) { hr = HRESULT_FROM_WIN32(FUSION_E_INVALID_NAME); goto exit; } StrCpy(pszFilePath, pszDir); PathAddBackslash(pszFilePath); StrCat(pszFilePath, g_FusionInfoFile); if ((hIni = PAL_IniCreate()) == NULL) { hr = FusionpHresultFromLastError(); goto exit; } #define _WriteString(section, key, value) PAL_IniWriteString(hIni, section, key, value) pszBuf = NEW(WCHAR[MAX_URL_LENGTH+1]); if (!pszBuf) { hr = E_OUTOFMEMORY; goto exit; } cbSize = 0; if(FAILED(hr = NameObjGetWrapper(pName, ASM_NAME_MVID, &pMVID, &cbSize))) goto exit; if(cbSize && (cbSize == MVID_LENGTH)) { CParseUtils::BinToUnicodeHex(pMVID, cbSize, pszBuf); pszBuf[MVID_LENGTH*2] = L'\0'; fRet = _WriteString(ASSEMBLY_INFO_STRING, MVID_KEY_STRING, pszBuf); if (!fRet) { hr = FusionpHresultFromLastError(); goto exit; } } cbSize = 0; if(FAILED(hr = NameObjGetWrapper(pName, ASM_NAME_CUSTOM, &pCustom, &cbSize))) goto exit; if(cbSize) { pszCustomString = (LPWSTR) pCustom; fRet = _WriteString(ASSEMBLY_INFO_STRING, CUSTOM_BLOB_STRING, pszCustomString); if (!fRet) { hr = FusionpHresultFromLastError(); goto exit; } } else { // if there is no Custom Blob try storing URL. cbSize = 0; if(FAILED(hr = NameObjGetWrapper(pName, ASM_NAME_CODEBASE_URL, (LPBYTE*) &pszURL, &cbSize))) goto exit; if(cbSize) { fRet = _WriteString(ASSEMBLY_INFO_STRING, URL_STRING, pszURL); if (!fRet) { hr = FusionpHresultFromLastError(); goto exit; } } dwSize = 0; hr = pName->GetDisplayName(NULL, &dwSize, 0); if (hr != HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)) { ASSERT(0); hr = E_UNEXPECTED; goto exit; } pszDisplayName = NEW(WCHAR[dwSize]); if (!pszDisplayName) { hr = E_OUTOFMEMORY; goto exit; } hr = pName->GetDisplayName(pszDisplayName, &dwSize, 0); if (FAILED(hr)) { goto exit; } cbSize = dwSize * sizeof(WCHAR); if(cbSize) { fRet = _WriteString(ASSEMBLY_INFO_STRING, DISPLAY_NAME_STRING, pszDisplayName); if (!fRet) { hr = FusionpHresultFromLastError(); goto exit; } } } if (!PAL_IniSave(hIni, pszFilePath, TRUE)) { hr = FusionpHresultFromLastError(); goto exit; } { DWORD dwSizeHigh=0; *pdwFileSizeLow = 512; // hard-code info file size. hr = GetFileSizeRoundedToCluster(INVALID_HANDLE_VALUE, pdwFileSizeLow, &dwSizeHigh); } exit: if (hIni != NULL) PAL_IniClose(hIni); SAFEDELETEARRAY(pszBuf); SAFEDELETEARRAY(pszDisplayName); SAFEDELETEARRAY(pMVID); SAFEDELETEARRAY(pCustom); SAFEDELETEARRAY(pszURL); return hr; }
DWORD cert_name_to_str_with_indent(DWORD dwCertEncodingType, DWORD indentLevel, const CERT_NAME_BLOB *pName, DWORD dwStrType, LPWSTR psz, DWORD csz) { static const DWORD unsupportedFlags = CERT_NAME_STR_NO_QUOTING_FLAG | CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG; static const WCHAR commaSep[] = { ',',' ',0 }; static const WCHAR semiSep[] = { ';',' ',0 }; static const WCHAR crlfSep[] = { '\r','\n',0 }; static const WCHAR plusSep[] = { ' ','+',' ',0 }; static const WCHAR spaceSep[] = { ' ',0 }; DWORD ret = 0, bytes = 0; BOOL bRet; CERT_NAME_INFO *info; if (dwStrType & unsupportedFlags) FIXME("unsupported flags: %08x\n", dwStrType & unsupportedFlags); bRet = CryptDecodeObjectEx(dwCertEncodingType, X509_NAME, pName->pbData, pName->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &info, &bytes); if (bRet) { DWORD i, j, sepLen, rdnSepLen; LPCWSTR sep, rdnSep; BOOL reverse = dwStrType & CERT_NAME_STR_REVERSE_FLAG; const CERT_RDN *rdn = info->rgRDN; if(reverse && info->cRDN > 1) rdn += (info->cRDN - 1); if (dwStrType & CERT_NAME_STR_SEMICOLON_FLAG) sep = semiSep; else if (dwStrType & CERT_NAME_STR_CRLF_FLAG) sep = crlfSep; else sep = commaSep; sepLen = lstrlenW(sep); if (dwStrType & CERT_NAME_STR_NO_PLUS_FLAG) rdnSep = spaceSep; else rdnSep = plusSep; rdnSepLen = lstrlenW(rdnSep); for (i = 0; (!psz || ret < csz) && i < info->cRDN; i++) { for (j = 0; (!psz || ret < csz) && j < rdn->cRDNAttr; j++) { DWORD chars; LPCSTR prefixA = NULL; LPCWSTR prefixW = NULL; if ((dwStrType & 0x000000ff) == CERT_OID_NAME_STR) prefixA = rdn->rgRDNAttr[j].pszObjId; else if ((dwStrType & 0x000000ff) == CERT_X500_NAME_STR) { PCCRYPT_OID_INFO oidInfo = CryptFindOIDInfo( CRYPT_OID_INFO_OID_KEY, rdn->rgRDNAttr[j].pszObjId, CRYPT_RDN_ATTR_OID_GROUP_ID); if (oidInfo) prefixW = oidInfo->pwszName; else prefixA = rdn->rgRDNAttr[j].pszObjId; } if (dwStrType & CERT_NAME_STR_CRLF_FLAG) { DWORD k; for (k = 0; k < indentLevel; k++) { if (psz) { chars = min(strlenW(indent), csz - ret - 1); memcpy(psz + ret, indent, chars * sizeof(WCHAR)); } else chars = strlenW(indent); ret += chars; } } if (prefixW) { /* - 1 is needed to account for the NULL terminator. */ chars = CRYPT_AddPrefixW(prefixW, psz ? psz + ret : NULL, psz ? csz - ret - 1 : 0); ret += chars; } else if (prefixA) { /* - 1 is needed to account for the NULL terminator. */ chars = CRYPT_AddPrefixAToW(prefixA, psz ? psz + ret : NULL, psz ? csz - ret - 1 : 0); ret += chars; } /* FIXME: handle quoting */ chars = CertRDNValueToStrW( rdn->rgRDNAttr[j].dwValueType, &rdn->rgRDNAttr[j].Value, psz ? psz + ret : NULL, psz ? csz - ret : 0); if (chars) ret += chars - 1; if (j < rdn->cRDNAttr - 1) { if (psz && ret < csz - rdnSepLen - 1) memcpy(psz + ret, rdnSep, rdnSepLen * sizeof(WCHAR)); ret += rdnSepLen; } } if (i < info->cRDN - 1) { if (psz && ret < csz - sepLen - 1) memcpy(psz + ret, sep, sepLen * sizeof(WCHAR)); ret += sepLen; } if(reverse) rdn--; else rdn++; } LocalFree(info); } if (psz && csz) { *(psz + ret) = '\0'; ret++; } else ret++; return ret; }
HRESULT SetDownLoadDir() { HRESULT hr = S_OK; LPWSTR pszCacheLoc = NULL; if(FAILED(hr = GetCacheLoc(ASM_CACHE_DOWNLOAD, &pszCacheLoc))) goto exit; if( (lstrlen(pszCacheLoc) + lstrlen(FUSION_CACHE_DIR_DOWNLOADED_SZ)) > MAX_PATH ) { hr = HRESULT_FROM_WIN32(FUSION_E_INVALID_NAME); goto exit; } StrCpy(g_DownloadDir, pszCacheLoc); PathRemoveBackslash(g_DownloadDir); StrCat(g_DownloadDir, FUSION_CACHE_DIR_DOWNLOADED_SZ); PathAddBackslash(g_DownloadDir); #define DOWNLOAD_CACHE_OBFUSCATION_LENGTH 16 WIN32_FIND_DATA findData; WCHAR wzPath[MAX_PATH]; HANDLE hFind; BOOL bFoundObfuscated; if (lstrlenW(g_DownloadDir) + (DOWNLOAD_CACHE_OBFUSCATION_LENGTH * 2) + 1 >= MAX_PATH) { hr = HRESULT_FROM_WIN32(ERROR_BUFFER_OVERFLOW); goto exit; } bFoundObfuscated = FALSE; memset(&findData, 0, sizeof(findData)); wnsprintfW(wzPath, MAX_PATH, L"%ws*.*", g_DownloadDir); hFind = FindFirstFile(wzPath, &findData); if (hFind != INVALID_HANDLE_VALUE) { do { if (!lstrcmpW(findData.cFileName, L".") || !lstrcmpW(findData.cFileName, L"..")) { continue; } if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { lstrcatW(g_DownloadDir, findData.cFileName); bFoundObfuscated = TRUE; break; } } while (FindNextFile(hFind, &findData)); FindClose(hFind); } if (!bFoundObfuscated) { WCHAR wzRandom[(DOWNLOAD_CACHE_OBFUSCATION_LENGTH * 2) + 1]; BYTE bBuffer[DOWNLOAD_CACHE_OBFUSCATION_LENGTH]; if (!PAL_Random(FALSE, bBuffer, DOWNLOAD_CACHE_OBFUSCATION_LENGTH)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto exit; } wzRandom[0] = L'\0'; CParseUtils::BinToUnicodeHex(bBuffer, DOWNLOAD_CACHE_OBFUSCATION_LENGTH, wzRandom); lstrcatW(g_DownloadDir, wzRandom); } // StrCat(g_DownloadDir, szCorVer); exit : return hr; }
/************************************************************************** * FindMRUStringW [COMCTL32.402] * * See FindMRUStringA. */ INT WINAPI FindMRUStringW (HANDLE hList, LPCWSTR lpszString, LPINT lpRegNum) { return FindMRUData(hList, lpszString, (lstrlenW(lpszString) + 1) * sizeof(WCHAR), lpRegNum); }
HRESULT ParseAsmDir(LPWSTR pszAsmDir, CTransCache *pTC) { HRESULT hr=S_OK; TRANSCACHEINFO *pTCInfo = pTC->_pInfo; WCHAR wzDirName[MAX_PATH+1]; LPWSTR pwzTemp=NULL, pwzStringLeft=NULL,pwzCulture=NULL ; DWORD dwLen =0; WORD wVerA, wVerB, wVerC, wVerD; PBYTE lpByte=NULL; ASSERT(pTC); pTCInfo = pTC->_pInfo; StrCpy(wzDirName, pszAsmDir); pwzStringLeft = wzDirName; pwzTemp = StrChrW(pwzStringLeft, ATTR_SEPARATOR_CHAR); if(!pwzTemp) { hr = E_UNEXPECTED; goto exit; } *pwzTemp = '\0'; hr = VersionFromString(pwzStringLeft, &wVerA, &wVerB, &wVerC, &wVerD); if(FAILED(hr)) goto exit; pTCInfo->dwVerHigh = MAKELONG(wVerB, wVerA); pTCInfo->dwVerLow = MAKELONG(wVerD, wVerC); pwzStringLeft = ++pwzTemp; pwzTemp = StrChrW(pwzStringLeft, ATTR_SEPARATOR_CHAR); if(!pwzTemp) { hr = E_UNEXPECTED; goto exit; } *pwzTemp = '\0'; dwLen = lstrlenW(pwzStringLeft)+1; pwzCulture = NEW(WCHAR[dwLen]); if(!pwzCulture) { hr = E_OUTOFMEMORY; goto exit; } StrCpy(pwzCulture, pwzStringLeft); pwzStringLeft = ++pwzTemp; pwzTemp = StrChrW(pwzStringLeft, ATTR_SEPARATOR_CHAR); if(pwzTemp) { *pwzTemp = '\0'; // we don't parse beyond this point. } dwLen = lstrlenW(pwzStringLeft)/2; if(dwLen) { lpByte = NEW(BYTE[dwLen]); if(!lpByte) { hr = E_OUTOFMEMORY; goto exit; } CParseUtils::UnicodeHexToBin(pwzStringLeft, lstrlenW(pwzStringLeft), lpByte ); } pTCInfo->blobPKT.pBlobData = lpByte; lpByte = NULL; pTCInfo->blobPKT.cbSize = dwLen ; pTCInfo->pwzCulture = pwzCulture; pwzCulture = NULL; exit: SAFEDELETEARRAY(lpByte); SAFEDELETEARRAY(pwzCulture); return hr; }
static void CALLCONV FillTreeCtrl(HWND hTreeCtrl, LPCWSTR szPath, HTREEITEM hRoot) { SIZE_T i, nPathLen = lstrlenW(szPath); WIN32_FIND_DATAW fd; HANDLE hFind; LPWSTR szMask = PLUGIN_ALLOC(MAX_PATH*sizeof(WCHAR)); if(!szMask) return; lstrcpyW(szMask,szPath); lstrcatW(szMask,L"\\"); lstrcatW(szMask,TEMPLATES_MASK); hFind = FindFirstFileW(szMask,&fd); if(hFind != INVALID_HANDLE_VALUE) { LPWSTR szItem = PLUGIN_ALLOC(MAX_PATH*sizeof(szItem)); LPCWSTR p = szPath; UINT_PTR tail = 0; SHFILEINFOW sfi,sfis; while(*p){ szItem[tail] = *p++;tail++;}; szItem[tail]=L'\\';tail++; do { if(fd.cFileName[0] != L'.') { i=0; while(fd.cFileName[i]) {szItem[tail+i]=fd.cFileName[i];i++;} szItem[tail+i]=0; SHGetFileInfoW(szItem,0,&sfi,sizeof(sfi),SHGFI_SYSICONINDEX|SHGFI_SMALLICON|SHGFI_OPENICON); SHGetFileInfoW(szItem,0,&sfis,sizeof(sfis),SHGFI_SYSICONINDEX|SHGFI_SMALLICON|SHGFI_OPENICON); if(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { TVINSERTSTRUCTW tvi; HTREEITEM hNode=NULL; WCHAR szChild[MAX_PATH],szLabel[MAX_PATH]; p = fd.cFileName; tvi.hParent = hRoot; tvi.hInsertAfter = TVI_LAST; szLabel[0]=L'['; i=0; while(*p) {szLabel[1+i]=*p++;i++;} szLabel[1+i]=L']'; szLabel[1+i+1]=0; tvi.item.pszText = szLabel; tvi.item.cchTextMax = MAX_PATH; tvi.item.lParam = TVNT_DIR; tvi.item.iImage = sfi.iIcon; tvi.item.iSelectedImage = sfis.iIcon; tvi.item.mask = TVIF_TEXT|TVIF_PARAM|TVIF_IMAGE|TVIF_SELECTEDIMAGE; hNode = TreeView_InsertItem(hTreeCtrl,&tvi); //! Что-бы не "оптимизировало" в вызов memcpy пришлось установить опцию //! компилятора "Inline Function Expansion" в /Ob1 //! На значение по-умолчанию "Default" в Win32 всё нормально, в x64 - вылазит memcpy xmemcpy(szChild,szPath,nPathLen*sizeof(WCHAR)); i = nPathLen; szChild[i]=L'\\'; i++; p = fd.cFileName; while(*p) {szChild[i]=*p++;i++;} szChild[i]=0; FillTreeCtrl(hTreeCtrl,szChild,hNode); TreeView_SortChildren(hTreeCtrl,hNode,FALSE); TreeView_Expand(hTreeCtrl,hNode,TVE_EXPAND); } else { TVINSERTSTRUCTW tvi; tvi.hParent = hRoot; tvi.hInsertAfter = TVI_LAST; tvi.item.pszText = fd.cFileName; tvi.item.cchTextMax = MAX_PATH; tvi.item.lParam = TVNT_FILE; tvi.item.iImage = sfi.iIcon; tvi.item.iSelectedImage = sfis.iIcon; tvi.item.mask = TVIF_TEXT|TVIF_PARAM|TVIF_IMAGE|TVIF_SELECTEDIMAGE; TreeView_InsertItem(hTreeCtrl,&tvi); } } } while(FindNextFileW(hFind, &fd)); FindClose(hFind); PLUGIN_FREE(szItem); } PLUGIN_FREE(szMask); }
/******************************************************************************* * GAMEUX_buildGameRegistryPath * * Internal helper function. Description available in gameux_private.h file */ HRESULT GAMEUX_buildGameRegistryPath(GAME_INSTALL_SCOPE installScope, LPCGUID gameInstanceId, LPWSTR* lpRegistryPath) { static const WCHAR sGameUxRegistryPath[] = {'S','O','F','T','W','A','R','E','\\', 'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\', 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','G','a','m','e','U','X',0}; static const WCHAR sGames[] = {'G','a','m','e','s',0}; static const WCHAR sBackslash[] = {'\\',0}; HRESULT hr = S_OK; HANDLE hToken = NULL; PTOKEN_USER pTokenUser = NULL; DWORD dwLength; LPWSTR lpSID = NULL; WCHAR sInstanceId[40]; WCHAR sRegistryPath[8192]; TRACE("(0x%x, %s, %p)\n", installScope, debugstr_guid(gameInstanceId), lpRegistryPath); /* this will make freeing it easier for user */ *lpRegistryPath = NULL; lstrcpyW(sRegistryPath, sGameUxRegistryPath); lstrcatW(sRegistryPath, sBackslash); if(installScope == GIS_CURRENT_USER) { /* build registry path containing user's SID */ if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) hr = HRESULT_FROM_WIN32(GetLastError()); if(SUCCEEDED(hr)) { if(!GetTokenInformation(hToken, TokenUser, NULL, 0, &dwLength) && GetLastError()!=ERROR_INSUFFICIENT_BUFFER) hr = HRESULT_FROM_WIN32(GetLastError()); if(SUCCEEDED(hr)) { pTokenUser = HeapAlloc(GetProcessHeap(), 0, dwLength); if(!pTokenUser) hr = E_OUTOFMEMORY; } if(SUCCEEDED(hr)) if(!GetTokenInformation(hToken, TokenUser, (LPVOID)pTokenUser, dwLength, &dwLength)) hr = HRESULT_FROM_WIN32(GetLastError()); if(SUCCEEDED(hr)) if(!ConvertSidToStringSidW(pTokenUser->User.Sid, &lpSID)) hr = HRESULT_FROM_WIN32(GetLastError()); if(SUCCEEDED(hr)) { lstrcatW(sRegistryPath, lpSID); LocalFree(lpSID); } HeapFree(GetProcessHeap(), 0, pTokenUser); CloseHandle(hToken); } } else if(installScope == GIS_ALL_USERS) /* build registry path without SID */ lstrcatW(sRegistryPath, sGames); else hr = E_INVALIDARG; /* put game's instance id on the end of path, only if instance id was given */ if(gameInstanceId) { if(SUCCEEDED(hr)) hr = (StringFromGUID2(gameInstanceId, sInstanceId, sizeof(sInstanceId)/sizeof(sInstanceId[0])) ? S_OK : E_FAIL); if(SUCCEEDED(hr)) { lstrcatW(sRegistryPath, sBackslash); lstrcatW(sRegistryPath, sInstanceId); } } if(SUCCEEDED(hr)) { *lpRegistryPath = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(sRegistryPath)+1)*sizeof(WCHAR)); if(!*lpRegistryPath) hr = E_OUTOFMEMORY; } if(SUCCEEDED(hr)) lstrcpyW(*lpRegistryPath, sRegistryPath); TRACE("result: 0x%x, path: %s\n", hr, debugstr_w(*lpRegistryPath)); return hr; }