void CWebServer::OnRequest(CWebClientSocket* pClient, CStringA& hdr, CStringA& body) { const CAppSettings& s = AfxGetAppSettings(); CPath p(AToT(pClient->m_path)); CStringA ext = p.GetExtension().MakeLower(); CStringA mime; if (ext.IsEmpty()) { mime = "text/html"; } else { m_mimes.Lookup(ext, mime); } hdr = "HTTP/1.0 200 OK\r\n"; bool fHandled = false, fCGI = false; if (m_webroot.IsDirectory()) { CStringA tmphdr; fHandled = fCGI = CallCGI(pClient, tmphdr, body, mime); if (fHandled) { tmphdr.Replace("\r\n", "\n"); CAtlList<CStringA> hdrlines; ExplodeMin(tmphdr, hdrlines, '\n'); POSITION pos = hdrlines.GetHeadPosition(); while (pos) { POSITION cur = pos; CAtlList<CStringA> sl; CStringA key = Explode(hdrlines.GetNext(pos), sl, ':', 2); if (sl.GetCount() < 2) { continue; } key.Trim().MakeLower(); if (key == "content-type") { mime = sl.GetTail().Trim(); hdrlines.RemoveAt(cur); } else if (key == "content-length") { hdrlines.RemoveAt(cur); } } tmphdr = Implode(hdrlines, "\r\n"); hdr += tmphdr + "\r\n"; } } RequestHandler rh = nullptr; if (!fHandled && m_internalpages.Lookup(pClient->m_path, rh) && (pClient->*rh)(hdr, body, mime)) { if (mime.IsEmpty()) { mime = "text/html"; } CString redir; if (pClient->m_get.Lookup("redir", redir) || pClient->m_post.Lookup("redir", redir)) { if (redir.IsEmpty()) { redir = '/'; } hdr = "HTTP/1.0 302 Found\r\n" "Location: " + CStringA(redir) + "\r\n"; return; } fHandled = true; } if (!fHandled && m_webroot.IsDirectory()) { fHandled = LoadPage(0, body, UTF8To16(pClient->m_path)); } UINT resid; if (!fHandled && m_downloads.Lookup(pClient->m_path, resid) && (LoadResource(resid, body, _T("FILE")) || LoadResource(resid, body, _T("PNG")))) { if (mime.IsEmpty()) { mime = "application/octet-stream"; } fHandled = true; } if (!fHandled) { hdr = mime == "text/html" ? "HTTP/1.0 301 Moved Permanently\r\n" "Location: /404.html\r\n" : "HTTP/1.0 404 Not Found\r\n"; return; } /* Don't cache html, js and css files */ if ((mime == "text/html" || mime == "text/javascript" || mime == "text/css") && !fCGI) { if (mime == "text/html") { hdr += "Expires: Thu, 19 Nov 1981 08:52:00 GMT\r\n" "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n" "Pragma: no-cache\r\n"; CStringA debug; if (s.fWebServerPrintDebugInfo) { debug += "<br><hr><pre>\r\n"; CStringA key; POSITION pos; { CStringA value; pos = pClient->m_hdrlines.GetStartPosition(); while (pos) { pClient->m_hdrlines.GetNextAssoc(pos, key, value); debug += "HEADER[" + key + "] = " + value + "\r\n"; } } debug += "cmd: " + pClient->m_cmd + "\r\n"; debug += "path: " + pClient->m_path + "\r\n"; debug += "ver: " + pClient->m_ver + "\r\n"; { CString value; pos = pClient->m_get.GetStartPosition(); while (pos) { pClient->m_get.GetNextAssoc(pos, key, value); debug += "GET[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n"; } pos = pClient->m_post.GetStartPosition(); while (pos) { pClient->m_post.GetNextAssoc(pos, key, value); debug += "POST[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n"; } pos = pClient->m_cookie.GetStartPosition(); while (pos) { pClient->m_cookie.GetNextAssoc(pos, key, value); debug += "COOKIE[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n"; } pos = pClient->m_request.GetStartPosition(); while (pos) { pClient->m_request.GetNextAssoc(pos, key, value); debug += "REQUEST[" + HtmlSpecialChars(key) + "] = " + HtmlSpecialChars(UTF8(value)) + "\r\n"; } } debug += "</pre>"; } body.Replace("[debug]", debug); } body.Replace("[browserpath]", "/browser.html"); body.Replace("[commandpath]", "/command.html"); body.Replace("[controlspath]", "/controls.html"); body.Replace("[indexpath]", "/index.html"); body.Replace("[path]", pClient->m_path); body.Replace("[setposcommand]", CMD_SETPOS); body.Replace("[setvolumecommand]", CMD_SETVOLUME); body.Replace("[wmcname]", "wm_command"); // TODO: add more general tags to replace } // gzip if (s.fWebServerUseCompression && !body.IsEmpty() && hdr.Find("Content-Encoding:") < 0 && ext != ".png" && ext != ".jpeg" && ext != ".gif") do { CStringA accept_encoding; pClient->m_hdrlines.Lookup("accept-encoding", accept_encoding); accept_encoding.MakeLower(); CAtlList<CStringA> sl; ExplodeMin(accept_encoding, sl, ','); if (!sl.Find("gzip")) { break; } // Allocate deflate state z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; int ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY); if (ret != Z_OK) { ASSERT(0); break; } int gzippedBuffLen = body.GetLength(); BYTE* gzippedBuff = DEBUG_NEW BYTE[gzippedBuffLen]; // Compress strm.avail_in = body.GetLength(); strm.next_in = (Bytef*)(LPCSTR)body; strm.avail_out = gzippedBuffLen; strm.next_out = gzippedBuff; ret = deflate(&strm, Z_FINISH); if (ret != Z_STREAM_END || strm.avail_in != 0) { ASSERT(0); deflateEnd(&strm); delete [] gzippedBuff; break; } gzippedBuffLen -= strm.avail_out; memcpy(body.GetBufferSetLength(gzippedBuffLen), gzippedBuff, gzippedBuffLen); // Clean up deflateEnd(&strm); delete [] gzippedBuff; hdr += "Content-Encoding: gzip\r\n"; } while (0); CStringA content; content.Format( "Content-Type: %s\r\n" "Content-Length: %d\r\n", mime, body.GetLength()); hdr += content; }
void CLocalSearch::WriteTrailerG1(CG1Packet* pPacket, CSchemaMap& pSchemas, BYTE nHits) { // Prepare XML CStringA sXML; for ( POSITION pos1 = pSchemas.GetStartPosition() ; pos1 ; ) { CXMLElement* pGroup; CSchemaPtr pSchema; pSchemas.GetNextAssoc( pos1, pSchema, pGroup ); sXML += UTF8Encode( pGroup->ToString( TRUE, FALSE ) ); delete pGroup; } pSchemas.RemoveAll(); // Compress XML DWORD nXMLLength = sXML.GetLength(); DWORD nCompressedXMLLength = 0; auto_array< BYTE > pCompressedXML; if ( nXMLLength ) { pCompressedXML = CZLib::Compress( (LPCSTR)sXML, nXMLLength, &nCompressedXMLLength ); } // Flags: 'I understand' first byte, 'Yes/No' - second byte // REMEMBER THAT THE PUSH BIT IS SET OPPOSITE THAN THE OTHERS BYTE nFlags[ 2 ] = { G1_QHD_BUSY | G1_QHD_STABLE | G1_QHD_SPEED | G1_QHD_GGEP, G1_QHD_PUSH }; if ( Network.IsFirewalled() ) nFlags[ 0 ] |= G1_QHD_PUSH; if ( Uploads.m_bStable ) nFlags[ 1 ] |= G1_QHD_STABLE; if ( Uploads.m_bStable ) nFlags[ 1 ] |= G1_QHD_SPEED; if ( ! UploadQueues.IsTransferAvailable() ) nFlags[ 1 ] |= G1_QHD_BUSY; if ( Settings.Gnutella1.EnableGGEP ) nFlags[ 1 ] |= G1_QHD_GGEP; // Correct the number of files sent pPacket->m_pBuffer[ 0 ] = nHits; // Write client vendor code pPacket->WriteString( _T(VENDOR_CODE), FALSE ); // Write public info pPacket->WriteByte( 4 ); // Public size: flags (2 bytes) + xml size (2 bytes) pPacket->WriteByte( nFlags[ 0 ] ); pPacket->WriteByte( nFlags[ 1 ] ); if ( pCompressedXML.get() && nCompressedXMLLength + 9 < nXMLLength + 2 ) { // "{deflate}" (9 bytes) + NUL pPacket->WriteShortLE( (WORD)( nCompressedXMLLength + 9 + 1 ) ); } else if ( nXMLLength ) { // "{}" (2 bytes) + NUL pPacket->WriteShortLE( WORD( nXMLLength + 2 + 1 ) ); pCompressedXML.reset(); nCompressedXMLLength = 0; } else { // NUL pPacket->WriteShortLE( WORD( 1 ) ); } // Write Chat flag pPacket->WriteByte( Settings.Community.ChatEnable ? G1_QHD_CHAT : 0 ); // Write GGEP block if ( Settings.Gnutella1.EnableGGEP ) { CGGEPBlock pBlock; // Write Browse flag if ( Settings.Community.ServeFiles ) { pBlock.Add( GGEP_HEADER_BROWSE_HOST ); } if ( Settings.Community.ChatEnable ) { pBlock.Add( GGEP_HEADER_CHAT ); } if ( m_bUDP && m_pSearch->m_nHops == 0 ) { pBlock.Add( GGEP_HEADER_MULTICAST_RESPONSE ); } pBlock.Write( pPacket ); } // Write XML if ( nCompressedXMLLength ) { pPacket->Write( "{deflate}", 9 ); pPacket->Write( pCompressedXML.get(), nCompressedXMLLength ); pPacket->WriteByte( 0 ); } else if ( nXMLLength ) { pPacket->Write( "{}", 2 ); pPacket->Write( (LPCSTR)sXML, nXMLLength ); pPacket->WriteByte( 0 ); } else { pPacket->WriteByte( 0 ); } // Client GUID pPacket->Write( Hashes::Guid( MyProfile.oGUID ) ); #ifdef _DEBUG // Test created hit if ( CQueryHit* pDebugHit = CQueryHit::FromG1Packet( pPacket ) ) { pDebugHit->Delete(); pPacket->m_nPosition = 0; } else theApp.Message( MSG_ERROR | MSG_FACILITY_SEARCH, _T("[G1] Shareaza produced search packet above but cannot parse it back!") ); #endif // _DEBUG }
void CDSMMuxerFilter::MuxHeader(IBitStream* pBS) { CString muxer; muxer.Format(_T("DSM Muxer (%s)"), CString(__TIMESTAMP__)); SetProperty(L"MUXR", CStringW(muxer)); SetProperty(L"DATE", CStringW(CTime::GetCurrentTime().FormatGmt(_T("%Y-%m-%d %H:%M:%S")))); MuxFileInfo(pBS); POSITION pos = m_pPins.GetHeadPosition(); while (pos) { CBaseMuxerInputPin* pPin = m_pPins.GetNext(pos); const CMediaType& mt = pPin->CurrentMediaType(); ASSERT((mt.lSampleSize >> 30) == 0); // you don't need >1GB samples, do you? MuxPacketHeader(pBS, DSMP_MEDIATYPE, 5 + sizeof(GUID) * 3 + mt.FormatLength()); pBS->BitWrite(pPin->GetID(), 8); pBS->ByteWrite(&mt.majortype, sizeof(mt.majortype)); pBS->ByteWrite(&mt.subtype, sizeof(mt.subtype)); pBS->BitWrite(mt.bFixedSizeSamples, 1); pBS->BitWrite(mt.bTemporalCompression, 1); pBS->BitWrite(mt.lSampleSize, 30); pBS->ByteWrite(&mt.formattype, sizeof(mt.formattype)); pBS->ByteWrite(mt.Format(), mt.FormatLength()); MuxStreamInfo(pBS, pPin); } // resources & chapters CInterfaceList<IDSMResourceBag> pRBs; pRBs.AddTail(this); CComQIPtr<IDSMChapterBag> pCB = (IUnknown*)(INonDelegatingUnknown*)this; pos = m_pPins.GetHeadPosition(); while (pos) { for (CComPtr<IPin> pPin = m_pPins.GetNext(pos)->GetConnected(); pPin; pPin = GetUpStreamPin(GetFilterFromPin(pPin))) { if (m_fAutoRes) { CComQIPtr<IDSMResourceBag> pPB = GetFilterFromPin(pPin); if (pPB && !pRBs.Find(pPB)) { pRBs.AddTail(pPB); } } if (m_fAutoChap) { if (!pCB || pCB->ChapGetCount() == 0) { pCB = GetFilterFromPin(pPin); } } } } // resources pos = pRBs.GetHeadPosition(); while (pos) { IDSMResourceBag* pRB = pRBs.GetNext(pos); for (DWORD i = 0, j = pRB->ResGetCount(); i < j; i++) { CComBSTR name, desc, mime; BYTE* pData = NULL; DWORD len = 0; if (SUCCEEDED(pRB->ResGet(i, &name, &desc, &mime, &pData, &len, NULL))) { CStringA utf8_name = UTF16To8(name); CStringA utf8_desc = UTF16To8(desc); CStringA utf8_mime = UTF16To8(mime); MuxPacketHeader(pBS, DSMP_RESOURCE, 1 + utf8_name.GetLength() + 1 + utf8_desc.GetLength() + 1 + utf8_mime.GetLength() + 1 + len); pBS->BitWrite(0, 2); pBS->BitWrite(0, 6); // reserved pBS->ByteWrite(utf8_name, utf8_name.GetLength() + 1); pBS->ByteWrite(utf8_desc, utf8_desc.GetLength() + 1); pBS->ByteWrite(utf8_mime, utf8_mime.GetLength() + 1); pBS->ByteWrite(pData, len); CoTaskMemFree(pData); } } } // chapters if (pCB) { CAtlList<CDSMChapter> chapters; REFERENCE_TIME rtPrev = 0; int len = 0; pCB->ChapSort(); for (DWORD i = 0; i < pCB->ChapGetCount(); i++) { CDSMChapter c; CComBSTR name; if (SUCCEEDED(pCB->ChapGet(i, &c.rt, &name))) { REFERENCE_TIME rtDiff = c.rt - rtPrev; rtPrev = c.rt; c.rt = rtDiff; c.name = name; len += 1 + GetByteLength(myabs(c.rt)) + UTF16To8(c.name).GetLength() + 1; chapters.AddTail(c); } } if (chapters.GetCount()) { MuxPacketHeader(pBS, DSMP_CHAPTERS, len); pos = chapters.GetHeadPosition(); while (pos) { CDSMChapter& c = chapters.GetNext(pos); CStringA name = UTF16To8(c.name); int irt = GetByteLength(myabs(c.rt)); pBS->BitWrite(c.rt < 0, 1); pBS->BitWrite(irt, 3); pBS->BitWrite(0, 4); pBS->BitWrite(myabs(c.rt), irt << 3); pBS->ByteWrite((LPCSTR)name, name.GetLength() + 1); } } } }
) = HttpSendRequestW; BOOL WINAPI MyHttpSendRequestW( __in HINTERNET hRequest, __in_ecount_opt(dwHeadersLength) LPCWSTR lpszHeaders, __in DWORD dwHeadersLength, __in_bcount_opt(dwOptionalLength) LPVOID lpOptional, __in DWORD dwOptionalLength ) { CStringA strInternetUrl; UrlRecorder.GetRecordData(hRequest,&strInternetUrl); CHAR chCookieData[4000]={0}; CommonGetCookie(strInternetUrl,chCookieData,3999,FALSE); CStringA strCookieHeader; strCookieHeader = "Cookie: "; strCookieHeader += chCookieData; BOOL bRes = HttpAddRequestHeadersA(hRequest,strCookieHeader.GetBuffer(),strCookieHeader.GetLength(),HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE); BOOL TReturn = pHttpSendRequestW( hRequest, lpszHeaders, dwHeadersLength, lpOptional, dwOptionalLength ); return TReturn; };
void CWebSocket::OnRequestReceived(char* pHeader, DWORD dwHeaderLen, char* pData, DWORD dwDataLen, in_addr inad) { CStringA sHeader(pHeader, dwHeaderLen); CStringA sData(pData, dwDataLen); CStringA sURL; bool filereq=false; if(sHeader.Left(3) == "GET") sURL = sHeader.Trim(); else if(sHeader.Left(4) == "POST") sURL = "?" + sData.Trim(); // '?' to imitate GET syntax for ParseURL if(sURL.Find(" ") > -1) sURL = sURL.Mid(sURL.Find(" ")+1, sURL.GetLength()); if(sURL.Find(" ") > -1) sURL = sURL.Left(sURL.Find(" ")); if (sURL.GetLength()>4 && // min length (for valid extentions) (sURL.Right(4).MakeLower()==".gif" || sURL.Right(4).MakeLower()==".jpg" || sURL.Right(4).MakeLower()==".png" || sURL.Right(4).MakeLower()==".ico" ||sURL.Right(4).MakeLower()==".css" ||sURL.Right(3).MakeLower()==".js" || sURL.Right(4).MakeLower()==".bmp" || sURL.Right(5).MakeLower()==".jpeg" ) && sURL.Find("..")==-1 // dont allow leaving the emule-webserver-folder for accessing files ) filereq=true; ThreadData Data; Data.sURL = sURL; Data.pThis = m_pParent; Data.inadr = inad; Data.pSocket = this; if (!filereq) m_pParent->ProcessURL(Data); else m_pParent->ProcessFileReq(Data); Disconnect(); }
// ==> IP Filter White List [Stulle] - Stulle void CIPFilter::AddFromFileWhite(LPCTSTR pszFilePath) { FILE* readFile = _tfsopen(pszFilePath, _T("r"), _SH_DENYWR); if (readFile != NULL) { _setmode(fileno(readFile), _O_TEXT); int iLine = 0; CStringA sbuffer; CHAR szBuffer[1024]; while (fgets(szBuffer, _countof(szBuffer), readFile) != NULL) { iLine++; sbuffer = szBuffer; // ignore comments & too short lines if (sbuffer.GetAt(0) == '#' || sbuffer.GetAt(0) == '/' || sbuffer.GetLength() < 5) { sbuffer.Trim(" \t\r\n"); DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter (white): ignored line %u\n", iLine) : 0 ); continue; } bool bValid = false; uint32 start = 0; uint32 end = 0; UINT level = 0; CStringA desc; bValid = ParseFilterLine1(sbuffer, start, end, level, desc); // add a filter if (bValid) { AddIPRangeWhite(start, end, level, desc); DEBUG_ONLY( TRACE("Added White Entry - start: %u end: %u level: %u desc: %s\n", start, end, level, desc)); } else { sbuffer.Trim(" \t\r\n"); DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter (white list): ignored line %u\n", iLine) : 0 ); } } fclose(readFile); // sort the IP filter list by IP range start addresses qsort(m_iplist_White.GetData(), m_iplist_White.GetCount(), sizeof(m_iplist_White[0]), CmpSIPFilterByStartAddr); // merge overlapping and adjacent filter ranges if (m_iplist_White.GetCount() >= 2) { // On large IP-filter lists there is a noticeable performance problem when merging the list. // The 'CIPFilterArray::RemoveAt' call is way too expensive to get called during the merging, // thus we use temporary helper arrays to copy only the entries into the final list which // are not get deleted. // Reserve a byte array (its used as a boolean array actually) as large as the current // IP-filter list, so we can set a 'to delete' flag for each entry in the current IP-filter list. char* pcToDelete = new char[m_iplist_White.GetCount()]; memset(pcToDelete, 0, m_iplist_White.GetCount()); int iNumToDelete = 0; SIPFilter* pPrv = m_iplist_White[0]; int i = 1; while (i < m_iplist_White.GetCount()) { SIPFilter* pCur = m_iplist_White[i]; if ( pCur->start >= pPrv->start && pCur->start <= pPrv->end // overlapping || pCur->start == pPrv->end+1 && pCur->level == pPrv->level) // adjacent { if (pCur->start != pPrv->start || pCur->end != pPrv->end) // don't merge identical entries { //TODO: not yet handled, overlapping entries with different 'level' if (pCur->end > pPrv->end) pPrv->end = pCur->end; //pPrv->desc += _T("; ") + pCur->desc; // this may create a very very long description string... } else { // if we have identical entries, use the lowest 'level' if (pCur->level < pPrv->level) pPrv->level = pCur->level; } delete pCur; //m_iplist_White.RemoveAt(i); // way too expensive (read above) pcToDelete[i] = 1; // mark this entry as 'to delete' iNumToDelete++; i++; continue; } pPrv = pCur; i++; } // Create new IP-filter list which contains only the entries from the original IP-filter list // which are not to be deleted. if (iNumToDelete > 0) { CIPFilterArray newList; newList.SetSize(m_iplist_White.GetCount() - iNumToDelete); int iNewListIndex = 0; for (int i = 0; i < m_iplist_White.GetCount(); i++) { if (!pcToDelete[i]) newList[iNewListIndex++] = m_iplist_White[i]; } ASSERT( iNewListIndex == newList.GetSize() ); // Replace current list with new list. Dump, but still fast enough (only 1 memcpy) m_iplist_White.RemoveAll(); m_iplist_White.Append(newList); newList.RemoveAll(); m_bModified = true; } delete[] pcToDelete; } } if(m_iplist_White.GetCount()>0) AddLogLine(false, GetResString(IDS_IPFILTERWHITELOADED), m_iplist_White.GetCount()); return; }
// 10进制逗号分隔字符串或16进制字符串转换为Color对象 Color CDuiObject::StringToColor(LPCTSTR lpszValue, Color clrDefault) { CStringA strValue; strValue = lpszValue; // 字符串为空则返回默认值 if(strValue.IsEmpty()) { return clrDefault; } // 没有逗号,则按照10进制处理 if(strValue.Find(",") == -1) { return HexStringToColor(lpszValue); } BYTE c1,c2,c3,c4; CStringA s1 = ""; CStringA s2 = ""; CStringA s3 = ""; CStringA s4 = ""; int nPos = strValue.Find(","); if(nPos != -1) { s1 = strValue.Left(nPos); strValue.Delete(0, nPos+1); nPos = strValue.Find(","); if(nPos != -1) { s2 = strValue.Left(nPos); strValue.Delete(0, nPos+1); nPos = strValue.Find(","); if(nPos != -1) { s3 = strValue.Left(nPos); strValue.Delete(0, nPos+1); s4 = strValue; }else { s3 = strValue; } } } c1 = atoi(s1); c2 = atoi(s2); c3 = atoi(s3); c4 = atoi(s4); if(s4.IsEmpty()) { return Color(c1, c2, c3); }else { return Color(c1, c2, c3, c4); } }
BOOL CFileTextLines::Save(const CString& sFilePath, bool bSaveAsUTF8, DWORD dwIgnoreWhitespaces /*=0*/, BOOL bIgnoreCase /*= FALSE*/, bool bBlame /*= false*/) { try { CString destPath = sFilePath; // now make sure that the destination directory exists int ind = 0; while (destPath.Find('\\', ind)>=2) { if (!PathIsDirectory(destPath.Left(destPath.Find('\\', ind)))) { if (!CreateDirectory(destPath.Left(destPath.Find('\\', ind)), NULL)) return FALSE; } ind = destPath.Find('\\', ind)+1; } CStdioFile file; // Hugely faster than CFile for big file writes - because it uses buffering if (!file.Open(sFilePath, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary)) { m_sErrorString.Format(IDS_ERR_FILE_OPEN, (LPCTSTR)sFilePath); return FALSE; } if ((!bSaveAsUTF8)&&(m_UnicodeType == CFileTextLines::UNICODE_LE)) { //first write the BOM UINT16 wBOM = 0xFEFF; file.Write(&wBOM, 2); for (int i=0; i<GetCount(); i++) { CString sLine = GetAt(i); EOL ending = GetLineEnding(i); StripWhiteSpace(sLine,dwIgnoreWhitespaces, bBlame); if (bIgnoreCase) sLine = sLine.MakeLower(); file.Write((LPCTSTR)sLine, sLine.GetLength()*sizeof(TCHAR)); if (ending == EOL_AUTOLINE) ending = m_LineEndings; switch (ending) { case EOL_CR: sLine = _T("\x0d"); break; case EOL_CRLF: case EOL_AUTOLINE: sLine = _T("\x0d\x0a"); break; case EOL_LF: sLine = _T("\x0a"); break; case EOL_LFCR: sLine = _T("\x0a\x0d"); break; default: sLine.Empty(); break; } if ((m_bReturnAtEnd)||(i != GetCount()-1)) file.Write((LPCTSTR)sLine, sLine.GetLength()*sizeof(TCHAR)); } } else if ((!bSaveAsUTF8)&&((m_UnicodeType == CFileTextLines::ASCII)||(m_UnicodeType == CFileTextLines::AUTOTYPE))) { for (int i=0; i< GetCount(); i++) { // Copy CString to 8 bit without conversion CString sLineT = GetAt(i); CStringA sLine = CStringA(sLineT); EOL ending = GetLineEnding(i); StripAsciiWhiteSpace(sLine,dwIgnoreWhitespaces, bBlame); if (bIgnoreCase) sLine = sLine.MakeLower(); if ((m_bReturnAtEnd)||(i != GetCount()-1)) { if (ending == EOL_AUTOLINE) ending = m_LineEndings; switch (ending) { case EOL_CR: sLine += '\x0d'; break; case EOL_CRLF: case EOL_AUTOLINE: sLine.Append("\x0d\x0a", 2); break; case EOL_LF: sLine += '\x0a'; break; case EOL_LFCR: sLine.Append("\x0a\x0d", 2); break; } } file.Write((LPCSTR)sLine, sLine.GetLength()); } } else if ((bSaveAsUTF8)||((m_UnicodeType == CFileTextLines::UTF8BOM)||(m_UnicodeType == CFileTextLines::UTF8))) { if (m_UnicodeType == CFileTextLines::UTF8BOM) { //first write the BOM UINT16 wBOM = 0xBBEF; file.Write(&wBOM, 2); UINT8 uBOM = 0xBF; file.Write(&uBOM, 1); } for (int i=0; i<GetCount(); i++) { CStringA sLine = CUnicodeUtils::GetUTF8(GetAt(i)); EOL ending = GetLineEnding(i); StripAsciiWhiteSpace(sLine,dwIgnoreWhitespaces, bBlame); if (bIgnoreCase) sLine = sLine.MakeLower(); if ((m_bReturnAtEnd)||(i != GetCount()-1)) { if (ending == EOL_AUTOLINE) ending = m_LineEndings; switch (ending) { case EOL_CR: sLine += '\x0d'; break; case EOL_CRLF: case EOL_AUTOLINE: sLine.Append("\x0d\x0a",2); break; case EOL_LF: sLine += '\x0a'; break; case EOL_LFCR: sLine.Append("\x0a\x0d",2); break; } } file.Write((LPCSTR)sLine, sLine.GetLength()); } } file.Close(); } catch (CException * e) { e->GetErrorMessage(m_sErrorString.GetBuffer(4096), 4096); m_sErrorString.ReleaseBuffer(); e->Delete(); return FALSE; } return TRUE; }
void CpeepmBrowser::OnBnClickedBrowserButton() { CStringA tmp = "http://"; tmp.Append(Server); CString server(tmp); CString content = _T(""); m_Edit.GetWindowText(content); if (content.GetLength() > 0 && content.Find(server) > -1) { TCHAR tmp[1024] = {0}; GetModuleFileName(NULL, tmp, sizeof(tmp)); CString path = tmp; path = path.Left(path.ReverseFind('\\')); path.Append(_T("\\")); CFileDialog open(TRUE); open.m_ofn.lpstrTitle = _T("选择账号"); open.m_ofn.lpstrInitialDir = path; INT_PTR resp = open.DoModal(); if (resp == IDOK) { CString path = open.GetPathName(); char* url = CpeepmUtil::WideCharToChar(content, content.GetLength()); if (url == NULL) return; char* p = CpeepmUtil::WideCharToChar(path, path.GetLength()); CpeepmDlg* parent = (CpeepmDlg*)GetParent(); m_ThreadMax = 1; DWORD delay = parent->GetDelay(); BOOL* success = new BOOL; *success = FALSE; CCriticalSection* section = new CCriticalSection(); CEvent* event = new CEvent(FALSE, TRUE, NULL, NULL); PeepmBrowser* browser = new PeepmBrowser(); browser->path = p; browser->username = NULL; browser->password = NULL; browser->next = NULL; browser->use = FALSE; browser->section = NULL; m_Crack = new CpeepmCrack*[m_ThreadMax]; for (UINT i = 0; i < m_ThreadMax; i++) { CpeepmCrack* crack = new CUrlBrowser(browser, url, success, i, m_ThreadMax, delay, section, event, NULL, *this); m_Crack[i] = crack; CWinThread* thread = AfxBeginThread(CpeepmCrack::OnThread, crack); crack->SetThread(thread); } CWinThread* thread = AfxBeginThread(CUrlBrowser::InitAccount, m_Crack[0]); m_Button.EnableWindow(FALSE); } } }
BOOL CStubbornFiles::_SaveToFile() { BOOL retval = FALSE; CDataFileLoader dataLoader; TiXmlDocument xmlDoc; TiXmlElement* pXmlItem = NULL; TiXmlElement* pXmlTime = NULL; TiXmlElement* pXmlItems = NULL; TiXmlText* pXmlText = NULL; TCHAR szConfPathTemp[MAX_PATH] = { 0 }; TCHAR szConfPath[MAX_PATH] = { 0 }; TiXmlDeclaration *pXmlDecl = new TiXmlDeclaration("1.0", "utf-8", "yes"); POSITION pos = NULL; CStringW strPathUtf16; CStringA strPathUtf8; CString strXmlUtf16; CStringA strXmlAnsi; LARGE_INTEGER ver; BOOL fRetCode; FILE* pFile = NULL; SYSTEMTIME sysTime = { 0 }; CStringA strTime; GetModuleFileName(NULL, szConfPath, MAX_PATH); PathRemoveFileSpec(szConfPath); _tcscpy_s(szConfPathTemp, MAX_PATH, szConfPath); PathAppend(szConfPathTemp, _T("data\\~strash.dat")); PathAppend(szConfPath, _T("data\\strash.dat")); xmlDoc.LinkEndChild(pXmlDecl); pXmlItems = new TiXmlElement("items"); if (!pXmlItems) goto clean0; pos = m_fileList.GetHeadPosition(); while (pos) { strPathUtf16 = m_fileList.GetNext(pos); strPathUtf8 = KUTF16_To_UTF8(strPathUtf16); pXmlText = new TiXmlText(strPathUtf8); if (!pXmlText) goto clean0; pXmlItem = new TiXmlElement("item"); if (!pXmlItem) goto clean0; pXmlItem->LinkEndChild(pXmlText); pXmlItems->LinkEndChild(pXmlItem); } xmlDoc.LinkEndChild(pXmlItems); GetLocalTime(&sysTime); strTime.Format("%d.%d.%d", sysTime.wYear, sysTime.wMonth, sysTime.wDay); pXmlTime = new TiXmlElement("time"); if (!pXmlTime) goto clean0; pXmlText = new TiXmlText(strTime); if (!pXmlText) goto clean0; pXmlTime->LinkEndChild(pXmlText); xmlDoc.LinkEndChild(pXmlTime); if (!xmlDoc.SaveFile(KUTF16_To_ANSI(szConfPathTemp))) goto clean0; pFile = _wfopen(szConfPathTemp, L"r"); if (!pFile) goto clean0; { fseek(pFile, 0, SEEK_END); int nSize = ftell(pFile); fseek(pFile, 0, SEEK_SET); char* pXml = strXmlAnsi.GetBuffer(nSize + 1); memset(pXml, 0, nSize + 1); fread(pXml, 1, nSize, pFile); fclose(pFile); pFile = NULL; strXmlAnsi.ReleaseBuffer(); strXmlUtf16 = KANSI_TO_UTF16(strXmlAnsi); } { ver.QuadPart = 1; fRetCode = dataLoader.Save( szConfPath, BkDatLibEncodeParam2(enumLibTypePlugine, ver, strXmlUtf16, 1).GetEncodeParam() ); } if (!fRetCode) goto clean0; retval = TRUE; clean0: if (pFile) { fclose(pFile); pFile = NULL; } if (GetFileAttributes(szConfPathTemp) != INVALID_FILE_ATTRIBUTES) { ::DeleteFile(szConfPathTemp); } return retval; }
BOOL CTortoiseProcApp::InitInstance() { CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": InitInstance\n")); CheckUpgrade(); CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); CMFCButton::EnableWindowsTheming(); CHistoryCombo::m_nGitIconIndex = SYS_IMAGE_LIST().AddIcon((HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDI_GITCONFIG), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE)); Gdiplus::GdiplusStartupInput gdiplusStartupInput; Gdiplus::GdiplusStartup(&m_gdiplusToken,&gdiplusStartupInput,NULL); //set the resource dll for the required language CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033); long langId = loc; { CString langStr; langStr.Format(_T("%ld"), langId); CCrashReport::Instance().AddUserInfoToReport(L"LanguageID", langStr); } CString langDll; CStringA langpath = CStringA(CPathUtils::GetAppParentDirectory()); langpath += "Languages"; do { langDll.Format(_T("%sLanguages\\TortoiseProc%ld.dll"), (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId); CString sVer = _T(STRPRODUCTVER); CString sFileVer = CPathUtils::GetVersionFromFile(langDll); if (sFileVer == sVer) { HINSTANCE hInst = LoadLibrary(langDll); if (hInst != NULL) { CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Load Language DLL %s\n"), langDll); AfxSetResourceHandle(hInst); break; } } { DWORD lid = SUBLANGID(langId); lid--; if (lid > 0) { langId = MAKELANGID(PRIMARYLANGID(langId), lid); } else langId = 0; } } while (langId != 0); TCHAR buf[6] = { 0 }; _tcscpy_s(buf, _T("en")); langId = loc; // MFC uses a help file with the same name as the application by default, // which means we have to change that default to our language specific help files CString sHelppath = CPathUtils::GetAppDirectory() + _T("TortoiseGit_en.chm"); free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseGit_en.chm"); do { CString sLang = _T("_"); if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf))) { sLang += buf; sHelppath.Replace(_T("_en"), sLang); if (PathFileExists(sHelppath)) { free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); break; } } sHelppath.Replace(sLang, _T("_en")); if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf))) { sLang += _T("_"); sLang += buf; sHelppath.Replace(_T("_en"), sLang); if (PathFileExists(sHelppath)) { free((void*)m_pszHelpFilePath); m_pszHelpFilePath=_tcsdup(sHelppath); break; } } sHelppath.Replace(sLang, _T("_en")); DWORD lid = SUBLANGID(langId); lid--; if (lid > 0) { langId = MAKELANGID(PRIMARYLANGID(langId), lid); } else langId = 0; } while (langId); CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Set Help Filename %s\n"), m_pszHelpFilePath); setlocale(LC_ALL, ""); if (!g_Git.CheckMsysGitDir()) { UINT ret = CMessageBox::Show(NULL, IDS_PROC_NOMSYSGIT, IDS_APPNAME, 3, IDI_HAND, IDS_PROC_SETMSYSGITPATH, IDS_PROC_GOTOMSYSGITWEBSITE, IDS_ABORTBUTTON); if(ret == 2) { ShellExecute(NULL, NULL, _T("http://msysgit.github.io/"), NULL, NULL, SW_SHOW); } else if(ret == 1) { // open settings dialog CSinglePropSheetDlg(CString(MAKEINTRESOURCE(IDS_PROC_SETTINGS_TITLE)), new CSetMainPage(), this->GetMainWnd()).DoModal(); } return FALSE; } if (CAppUtils::GetMsysgitVersion() < 0x01070a00) { int ret = CMessageBox::ShowCheck(NULL, IDS_PROC_OLDMSYSGIT, IDS_APPNAME, 1, IDI_EXCLAMATION, IDS_PROC_GOTOMSYSGITWEBSITE, IDS_ABORTBUTTON, IDS_IGNOREBUTTON, _T("OldMsysgitVersionWarning"), IDS_PROC_NOTSHOWAGAINIGNORE); if (ret == 1) { CMessageBox::RemoveRegistryKey(_T("OldMsysgitVersionWarning")); // only store answer if it is "Ignore" ShellExecute(NULL, NULL, _T("http://msysgit.github.io/"), NULL, NULL, SW_SHOW); return FALSE; } else if (ret == 2) { CMessageBox::RemoveRegistryKey(_T("OldMsysgitVersionWarning")); // only store answer if it is "Ignore" return FALSE; } } { CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Registering Crash Report ...\n")); CCrashReport::Instance().AddUserInfoToReport(L"msysGitDir", CGit::ms_LastMsysGitDir); CString versionString; versionString.Format(_T("%d"), CGit::ms_LastMsysGitVersion); CCrashReport::Instance().AddUserInfoToReport(L"msysGitVersion", versionString); } CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Initializing UI components ...\n")); // InitCommonControls() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX used = { sizeof(INITCOMMONCONTROLSEX), ICC_ANIMATE_CLASS | ICC_BAR_CLASSES | ICC_COOL_CLASSES | ICC_DATE_CLASSES | ICC_HOTKEY_CLASS | ICC_INTERNET_CLASSES | ICC_LISTVIEW_CLASSES | ICC_NATIVEFNTCTL_CLASS | ICC_PAGESCROLLER_CLASS | ICC_PROGRESS_CLASS | ICC_TAB_CLASSES | ICC_TREEVIEW_CLASSES | ICC_UPDOWN_CLASS | ICC_USEREX_CLASSES | ICC_WIN95_CLASSES }; InitCommonControlsEx(&used); AfxOleInit(); AfxEnableControlContainer(); AfxInitRichEdit5(); CWinAppEx::InitInstance(); SetRegistryKey(_T("TortoiseGit")); AfxGetApp()->m_pszProfileName = _tcsdup(_T("TortoiseProc")); // w/o this ResizableLib will store data under TortoiseGitProc which is not compatible with older versions CCmdLineParser parser(AfxGetApp()->m_lpCmdLine); hWndExplorer = NULL; CString sVal = parser.GetVal(_T("hwnd")); if (!sVal.IsEmpty()) hWndExplorer = (HWND)_wcstoui64(sVal, nullptr, 16); while (GetParent(hWndExplorer)!=NULL) hWndExplorer = GetParent(hWndExplorer); if (!IsWindow(hWndExplorer)) { hWndExplorer = NULL; } // if HKCU\Software\TortoiseGit\Debug is not 0, show our command line // in a message box if (CRegDWORD(_T("Software\\TortoiseGit\\Debug"), FALSE)==TRUE) AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION); if (parser.HasKey(_T("urlhandler"))) { CString url = parser.GetVal(_T("urlhandler")); if (url.Find(_T("tgit://clone/")) == 0) { url = url.Mid(13); // 21 = "tgit://clone/".GetLength() } else if (url.Find(_T("github-windows://openRepo/")) == 0) { url = url.Mid(26); // 26 = "github-windows://openRepo/".GetLength() int questioMark = url.Find('?'); if (questioMark > 0) url = url.Left(questioMark); } else if (url.Find(_T("smartgit://cloneRepo/")) == 0) { url = url.Mid(21); // 21 = "smartgit://cloneRepo/".GetLength() } else { CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR); return FALSE; } CString newCmd; newCmd.Format(_T("/command:clone /url:\"%s\" /hasurlhandler"), url); parser = CCmdLineParser(newCmd); } if ( parser.HasKey(_T("path")) && parser.HasKey(_T("pathfile"))) { CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR); return FALSE; } CTGitPath cmdLinePath; CTGitPathList pathList; if (g_sGroupingUUID.IsEmpty()) g_sGroupingUUID = parser.GetVal(L"groupuuid"); if ( parser.HasKey(_T("pathfile")) ) { CString sPathfileArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("pathfile"))); cmdLinePath.SetFromUnknown(sPathfileArgument); if (pathList.LoadFromFile(cmdLinePath)==false) return FALSE; // no path specified! if ( parser.HasKey(_T("deletepathfile")) ) { // We can delete the temporary path file, now that we've loaded it ::DeleteFile(cmdLinePath.GetWinPath()); } // This was a path to a temporary file - it's got no meaning now, and // anybody who uses it again is in for a problem... cmdLinePath.Reset(); } else { CString sPathArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("path"))); if (parser.HasKey(_T("expaths"))) { // an /expaths param means we're started via the buttons in our Win7 library // and that means the value of /expaths is the current directory, and // the selected paths are then added as additional parameters but without a key, only a value // because of the "strange treatment of quotation marks and backslashes by CommandLineToArgvW" // we have to escape the backslashes first. Since we're only dealing with paths here, that's // a save bet. // Without this, a command line like: // /command:commit /expaths:"D:\" "D:\Utils" // would fail because the "D:\" is treated as the backslash being the escape char for the quotation // mark and we'd end up with: // argv[1] = /command:commit // argv[2] = /expaths:D:" D:\Utils // See here for more details: http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx CString cmdLine = GetCommandLineW(); cmdLine.Replace(L"\\", L"\\\\"); int nArgs = 0; LPWSTR *szArglist = CommandLineToArgvW(cmdLine, &nArgs); if (szArglist) { // argument 0 is the process path, so start with 1 for (int i = 1; i < nArgs; ++i) { if (szArglist[i][0] != '/') { if (!sPathArgument.IsEmpty()) sPathArgument += '*'; sPathArgument += szArglist[i]; } } sPathArgument.Replace(L"\\\\", L"\\"); } LocalFree(szArglist); } if (sPathArgument.IsEmpty() && parser.HasKey(L"path")) { CMessageBox::Show(hWndExplorer, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR); return FALSE; } int asterisk = sPathArgument.Find('*'); cmdLinePath.SetFromUnknown(asterisk >= 0 ? sPathArgument.Left(asterisk) : sPathArgument); pathList.LoadFromAsteriskSeparatedString(sPathArgument); } if (pathList.IsEmpty()) { pathList.AddPath(CTGitPath::CTGitPath(g_Git.m_CurrentDir)); } // Set CWD to temporary dir, and restore it later { DWORD len = GetCurrentDirectory(0, NULL); if (len) { std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]); if (GetCurrentDirectory(len, originalCurrentDirectory.get())) { sOrigCWD = originalCurrentDirectory.get(); sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD); } } TCHAR pathbuf[MAX_PATH] = {0}; GetTortoiseGitTempPath(MAX_PATH, pathbuf); SetCurrentDirectory(pathbuf); } CheckForNewerVersion(); CAutoGeneralHandle TGitMutex = ::CreateMutex(NULL, FALSE, _T("TortoiseGitProc.exe")); if (!g_Git.SetCurrentDir(cmdLinePath.GetWinPathString(), parser.HasKey(_T("submodule")) == TRUE)) { for (int i = 0; i < pathList.GetCount(); ++i) if(g_Git.SetCurrentDir(pathList[i].GetWinPath())) break; } if(!g_Git.m_CurrentDir.IsEmpty()) { sOrigCWD = g_Git.m_CurrentDir; SetCurrentDirectory(g_Git.m_CurrentDir); } if (g_sGroupingUUID.IsEmpty()) { CRegStdDWORD groupSetting = CRegStdDWORD(_T("Software\\TortoiseGit\\GroupTaskbarIconsPerRepo"), 3); switch (DWORD(groupSetting)) { case 1: case 2: // implemented differently to TortoiseSVN atm break; case 3: case 4: { CString wcroot; if (g_GitAdminDir.HasAdminDir(g_Git.m_CurrentDir, true, &wcroot)) { git_oid oid; CStringA wcRootA(wcroot + CPathUtils::GetAppDirectory()); if (!git_odb_hash(&oid, wcRootA, wcRootA.GetLength(), GIT_OBJ_BLOB)) { CStringA hash; git_oid_tostr(hash.GetBufferSetLength(GIT_OID_HEXSZ + 1), GIT_OID_HEXSZ + 1, &oid); hash.ReleaseBuffer(); g_sGroupingUUID = hash; } ProjectProperties pp; pp.ReadProps(); CString icon = pp.sIcon; icon.Replace('/', '\\'); if (icon.IsEmpty()) g_bGroupingRemoveIcon = true; g_sGroupingIcon = icon; } } } } CString sAppID = GetTaskIDPerUUID(g_sGroupingUUID).c_str(); InitializeJumpList(sAppID); EnsureGitLibrary(false); { CString err; try { // requires CWD to be set CGit::m_LogEncode = CAppUtils::GetLogOutputEncode(); // make sure all config files are read in order to check that none contains an error g_Git.GetConfigValue(_T("doesnot.exist")); } catch (char* msg) { err = CString(msg); } if (!err.IsEmpty()) { UINT choice = CMessageBox::Show(hWndExplorer, err, _T("TortoiseGit"), 1, IDI_ERROR, CString(MAKEINTRESOURCE(IDS_PROC_EDITLOCALGITCONFIG)), CString(MAKEINTRESOURCE(IDS_PROC_EDITGLOBALGITCONFIG)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))); if (choice == 1) { // open the config file with alternative editor CAppUtils::LaunchAlternativeEditor(g_Git.GetGitLocalConfig()); } else if (choice == 2) { // open the global config file with alternative editor CAppUtils::LaunchAlternativeEditor(g_Git.GetGitGlobalConfig()); } return FALSE; } } // execute the requested command CommandServer server; Command * cmd = server.GetCommand(parser.GetVal(_T("command"))); if (cmd) { cmd->SetExplorerHwnd(hWndExplorer); cmd->SetParser(parser); cmd->SetPaths(pathList, cmdLinePath); retSuccess = cmd->Execute(); delete cmd; } // Look for temporary files left around by TortoiseSVN and // remove them. But only delete 'old' files because some // apps might still be needing the recent ones. { DWORD len = GetTortoiseGitTempPath(0, NULL); std::unique_ptr<TCHAR[]> path(new TCHAR[len + 100]); len = GetTortoiseGitTempPath (len + 100, path.get()); if (len != 0) { CDirFileEnum finder(path.get()); FILETIME systime_; ::GetSystemTimeAsFileTime(&systime_); __int64 systime = (((_int64)systime_.dwHighDateTime)<<32) | ((__int64)systime_.dwLowDateTime); bool isDir; CString filepath; while (finder.NextFile(filepath, &isDir)) { HANDLE hFile = ::CreateFile(filepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, isDir ? FILE_FLAG_BACKUP_SEMANTICS : NULL, NULL); if (hFile != INVALID_HANDLE_VALUE) { FILETIME createtime_; if (::GetFileTime(hFile, &createtime_, NULL, NULL)) { ::CloseHandle(hFile); __int64 createtime = (((_int64)createtime_.dwHighDateTime)<<32) | ((__int64)createtime_.dwLowDateTime); if ((createtime + 864000000000) < systime) //only delete files older than a day { ::SetFileAttributes(filepath, FILE_ATTRIBUTE_NORMAL); if (isDir) ::RemoveDirectory(filepath); else ::DeleteFile(filepath); } } else ::CloseHandle(hFile); } } } } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
BOOL CStubbornFiles::_LoadFromFile() { BOOL retval = FALSE; CDataFileLoader dataLoader; TiXmlDocument xmlDoc; const TiXmlElement* pXmlItems = NULL; const TiXmlElement* pXmlItem = NULL; const TiXmlElement* pXmlTime = NULL; TCHAR szConfPath[MAX_PATH] = { 0 }; CStringA strXmlAnsi; CStringW strPathUtf16; CStringA strPathAnsi; SYSTEMTIME sysTime = { 0 }; CStringA strTime; GetLocalTime(&sysTime); strTime.Format("%d.%d.%d", sysTime.wYear, sysTime.wMonth, sysTime.wDay); GetModuleFileName(NULL, szConfPath, MAX_PATH); PathRemoveFileSpec(szConfPath); PathAppend(szConfPath, _T("data\\strash.dat")); if (!dataLoader.LoadFile(szConfPath, strXmlAnsi)) goto clean0; if (!xmlDoc.LoadBuffer((LPSTR)(LPCSTR)strXmlAnsi, strXmlAnsi.GetLength(), TIXML_ENCODING_UTF8)) goto clean0; pXmlTime = xmlDoc.FirstChildElement("time"); if (!pXmlTime) goto clean0; if (strTime.Compare(pXmlTime->GetText())) goto clean0; pXmlItems = xmlDoc.FirstChildElement("items"); if (!pXmlItems) goto clean0; pXmlItem = pXmlItems->FirstChildElement("item"); while (pXmlItem) { strPathAnsi = pXmlItem->GetText(); if (strPathAnsi.GetLength()) { strPathUtf16 = KUTF8_To_UTF16(strPathAnsi); if (GetFileAttributes(strPathUtf16) != INVALID_FILE_ATTRIBUTES) { m_fileList.AddTail(strPathUtf16); m_fileMap[strPathUtf16] = TRUE; } } pXmlItem = pXmlItem->NextSiblingElement("item"); } retval = TRUE; clean0: return retval; }
LRESULT CMainFrame::OnReadGroup( WPARAM wParam, LPARAM lParam ) { int nGroupCount = 0; CUserDatas* lpUserDatas = ((CIFuzzMakerDoc*)GetActiveDocument())->GetUserDatas(); lpUserDatas->GetPatternGroupDataArray().RemoveAllWithDelete(); CPatternGroupInfoLoader PatternGroupInfoLoader; CPatternGroupInfoArray PatternGroupInfoArray; if( !PatternGroupInfoLoader.LoadText( lpUserDatas->GetGroupFileName(), &PatternGroupInfoArray ) ) return FALSE; for( nGroupCount=0; nGroupCount<PatternGroupInfoArray.GetSize(); nGroupCount++ ) { CPatternGroupInfo *lpPatternGroupInfo = PatternGroupInfoArray.GetAt( nGroupCount ); CPatternInfoLoader PatternInfoLoader; if( !PatternInfoLoader.LoadText( lpPatternGroupInfo->GetFileName(), lpPatternGroupInfo->GetPatternInfoArray() ) ) { } } for( nGroupCount=0; nGroupCount<PatternGroupInfoArray.GetSize(); nGroupCount++ ) { CPatternGroupInfo *lpPatternGroupInfo = PatternGroupInfoArray.GetAt( nGroupCount ); if( lpPatternGroupInfo->GetDispFlag() ) { CPatternGroupData* lpPatternGroupData = NULL; lpUserDatas->GetPatternGroupDataArray().AddWithNew( lpPatternGroupData ); lpPatternGroupData->SetDispName( lpPatternGroupInfo->GetDispName() ); for(int nPatternInfoCnt=0; nPatternInfoCnt<lpPatternGroupInfo->GetPatternInfoArray()->GetSize(); nPatternInfoCnt++ ) { CPatternInfo* lpPatternInfo = lpPatternGroupInfo->GetPatternInfoArray()->GetAt(nPatternInfoCnt); CPatternData* lpPatternData = NULL; CReadBufferArray BinaryDataArray; CStringA szValue = CT2A(lpPatternInfo->GetValue()); BYTE nDecValueByte = 0; unsigned short nDecValueShort = 0; unsigned int nDecValueInteger = 0; unsigned char* lpBuffer = NULL; if( lpPatternInfo->GetDataType() == CPatternData::DATATYPE_TEXT ) { // BinaryDataArray.SetSize( szValue.GetLength() * (!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()) ); lpBuffer = BinaryDataArray.GetData(); for( int nRepeat=0; nRepeat<(!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()); nRepeat++ ) { CopyMemory( &lpBuffer[nRepeat*szValue.GetLength()], szValue.GetBuffer(), szValue.GetLength() ); } }else if( lpPatternInfo->GetDataType() == CPatternData::DATATYPE_DEC_8 ) { nDecValueByte = (BYTE)strtoul( szValue, NULL, 10 ); BinaryDataArray.SetSize( sizeof(nDecValueByte) * (!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()) ); lpBuffer = BinaryDataArray.GetData(); for( int nRepeat=0; nRepeat<(!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()); nRepeat++ ) { CopyMemory( &lpBuffer[nRepeat*sizeof(nDecValueByte)], &nDecValueByte, sizeof(nDecValueByte) ); } }else if( lpPatternInfo->GetDataType() == CPatternData::DATATYPE_DEC_16_LITTLE ) { nDecValueShort = (unsigned short)strtoul( szValue, NULL, 10 ); nDecValueShort = CEndianConverter::ConvertToShort( (unsigned char*)&nDecValueShort, FALSE ); BinaryDataArray.SetSize( sizeof(nDecValueShort) * (!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()) ); lpBuffer = BinaryDataArray.GetData(); for( int nRepeat=0; nRepeat<(!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()); nRepeat++ ) { CopyMemory( &lpBuffer[nRepeat*sizeof(nDecValueShort)], &nDecValueShort, sizeof(nDecValueShort) ); } }else if( lpPatternInfo->GetDataType() == CPatternData::DATATYPE_DEC_16_BIG ) { nDecValueShort = (unsigned short)strtoul( szValue, NULL, 10 ); nDecValueShort = CEndianConverter::ConvertToShort( (unsigned char*)&nDecValueShort, TRUE ); BinaryDataArray.SetSize( sizeof(nDecValueShort) * (!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()) ); lpBuffer = BinaryDataArray.GetData(); for( int nRepeat=0; nRepeat<(!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()); nRepeat++ ) { CopyMemory( &lpBuffer[nRepeat*sizeof(nDecValueShort)], &nDecValueShort, sizeof(nDecValueShort) ); } }else if( lpPatternInfo->GetDataType() == CPatternData::DATATYPE_DEC_32_LITTLE ) { nDecValueInteger = (unsigned int)strtoul( szValue, NULL, 10 ); nDecValueInteger = CEndianConverter::ConvertToInteger( (unsigned char*)&nDecValueInteger, FALSE ); BinaryDataArray.SetSize( sizeof(nDecValueInteger) * (!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()) ); lpBuffer = BinaryDataArray.GetData(); for( int nRepeat=0; nRepeat<(!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()); nRepeat++ ) { CopyMemory( &lpBuffer[nRepeat*sizeof(nDecValueInteger)], &nDecValueInteger, sizeof(nDecValueInteger) ); } }else if( lpPatternInfo->GetDataType() == CPatternData::DATATYPE_DEC_32_BIG ) { nDecValueInteger = (unsigned int)strtoul( szValue, NULL, 10 ); nDecValueInteger = CEndianConverter::ConvertToInteger( (unsigned char*)&nDecValueInteger, TRUE ); BinaryDataArray.SetSize( sizeof(nDecValueInteger) * (!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()) ); lpBuffer = BinaryDataArray.GetData(); for( int nRepeat=0; nRepeat<(!lpPatternInfo->GetRepeat()?1:lpPatternInfo->GetRepeat()); nRepeat++ ) { CopyMemory( &lpBuffer[nRepeat*sizeof(nDecValueInteger)], &nDecValueInteger, sizeof(nDecValueInteger) ); } }else if( lpPatternInfo->GetDataType() == CPatternData::DATATYPE_HEX ) { // BinaryDataArray.SetSize( (int)(szValue.GetLength()/2) ); for( int cCnt=0; cCnt<(int)(szValue.GetLength()/2); cCnt++ ) { unsigned int nVal = strtol( szValue.Mid( cCnt*2, 2 ),NULL,16 ); BinaryDataArray.SetAt(cCnt, nVal); } }else if( lpPatternInfo->GetDataType() == CPatternData::DATATYPE_BIN ) { // CFileReader fl; if( !fl.ReadFile( lpPatternInfo->GetFileName(), BinaryDataArray ) ) continue; } lpPatternGroupData->GetPatternDataArray()->AddWithNew( lpPatternData ); lpPatternData->SetCheck( lpPatternInfo->GetSelectFlag() ); lpPatternData->SetDispName( lpPatternInfo->GetDispName() ); lpPatternData->SetDataType( lpPatternInfo->GetDataType() ); lpPatternData->SetValue( lpPatternInfo->GetValue() ); lpPatternData->SetRepeat( lpPatternInfo->GetRepeat() ); lpPatternData->SetWriteMode( lpPatternInfo->GetWriteMode() ); lpPatternData->SetFuzzArea( lpPatternInfo->GetFuzzArea() ); lpPatternData->SetSearchField( lpPatternInfo->GetSearchField() ); lpPatternData->SetFieldKey( lpPatternInfo->GetFieldKey() ); lpPatternData->SetDescription( lpPatternInfo->GetDescription() ); lpPatternData->SetBinaryDataArray( BinaryDataArray ); if( lpPatternInfo->GetFuzzArea() == CPatternData::FUZZAREA_FILE ) { TCHAR* endptr = NULL; int nFilePos = _tcstol( lpPatternInfo->GetFieldKey(), &endptr, 10 ); if( _tcslen(endptr) ) continue; lpPatternData->SetFilePos( nFilePos ); } if( lpPatternData->GetSearchField() == CPatternData::SEARCHFIELD_TAG || lpPatternData->GetSearchField() == CPatternData::SEARCHFIELD_TYPE || lpPatternData->GetSearchField() == CPatternData::SEARCHFIELD_SEGMENT ) { POSITION pos = NULL; CString szKey; CImageFileDirectoryInfo *lpImageFileDirectoryInfo = NULL; CFealdEntryInfo* lpFealdEntryInfo = NULL; CSegmentItemInfo* lpSegmentItemInfo = NULL; CTagTypeInfo* lpTagTypeInfo = NULL; int nFieldKey = 0; switch(lpPatternData->GetSearchField()) { case CPatternData::SEARCHFIELD_TAG: pos = m_FixedDatas.GetImageFileDirectoryInfoMap().GetStartPosition(); while(pos) { m_FixedDatas.GetImageFileDirectoryInfoMap().GetNextAssoc( pos, szKey, lpImageFileDirectoryInfo ); if( lpImageFileDirectoryInfo->GetFealdEntryInfoMap()->Lookup( lpPatternData->GetFieldKey(), lpFealdEntryInfo ) ) break; } break; case CPatternData::SEARCHFIELD_TYPE: nFieldKey = _tstol(lpPatternData->GetFieldKey()); m_FixedDatas.GetTagTypeInfoMap().Lookup( nFieldKey, lpTagTypeInfo ); break; case CPatternData::SEARCHFIELD_SEGMENT: m_FixedDatas.GetSegmentItemInfoMap().Lookup( lpPatternData->GetFieldKey(), lpSegmentItemInfo ); break; } lpPatternData->SetFealdEntryInfo( lpFealdEntryInfo ); lpPatternData->SetTagTypeInfo( lpTagTypeInfo ); lpPatternData->SetSegmentItemInfo( lpSegmentItemInfo ); } } } } SendMessageToDescendants( WM_APP_GROUP_DISP, NULL, NULL ); return TRUE; }
bool CWebServer::CallCGI(CWebClientSocket* pClient, CStringA& hdr, CStringA& body, CStringA& mime) { CString path = pClient->m_path, redir = path; if (!ToLocalPath(path, redir)) { return false; } CString ext = CPath(path).GetExtension().MakeLower(); CPath dir(path); dir.RemoveFileSpec(); CString cgi; if (!m_cgi.Lookup(ext, cgi) || !CPath(cgi).FileExists()) { return false; } HANDLE hProcess = GetCurrentProcess(); HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup = nullptr; HANDLE hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup = nullptr; SECURITY_ATTRIBUTES saAttr; ZeroMemory(&saAttr, sizeof(saAttr)); saAttr.nLength = sizeof(saAttr); saAttr.bInheritHandle = TRUE; if (CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) { BOOL fSuccess = DuplicateHandle(hProcess, hChildStdoutRd, hProcess, &hChildStdoutRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS); UNREFERENCED_PARAMETER(fSuccess); CloseHandle(hChildStdoutRd); } if (CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) { BOOL fSuccess = DuplicateHandle(hProcess, hChildStdinWr, hProcess, &hChildStdinWrDup, 0, FALSE, DUPLICATE_SAME_ACCESS); UNREFERENCED_PARAMETER(fSuccess); CloseHandle(hChildStdinWr); } STARTUPINFO siStartInfo; ZeroMemory(&siStartInfo, sizeof(siStartInfo)); siStartInfo.cb = sizeof(siStartInfo); siStartInfo.hStdError = hChildStdoutWr; siStartInfo.hStdOutput = hChildStdoutWr; siStartInfo.hStdInput = hChildStdinRd; siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; siStartInfo.wShowWindow = SW_HIDE; PROCESS_INFORMATION piProcInfo; ZeroMemory(&piProcInfo, sizeof(piProcInfo)); CStringA envstr; LPVOID lpvEnv = GetEnvironmentStrings(); if (lpvEnv) { CAtlList<CString> env; for (LPTSTR lpszVariable = (LPTSTR)lpvEnv; *lpszVariable; lpszVariable += _tcslen(lpszVariable) + 1) { if (lpszVariable != (LPTSTR)lpvEnv) { env.AddTail(lpszVariable); } } env.AddTail(_T("GATEWAY_INTERFACE=CGI/1.1")); env.AddTail(_T("SERVER_SOFTWARE=MPC-HC/") + VersionInfo::GetVersionString()); env.AddTail(_T("SERVER_PROTOCOL=") + AToT(pClient->m_ver)); env.AddTail(_T("REQUEST_METHOD=") + AToT(pClient->m_cmd)); env.AddTail(_T("PATH_INFO=") + redir); env.AddTail(_T("PATH_TRANSLATED=") + path); env.AddTail(_T("SCRIPT_NAME=") + redir); env.AddTail(_T("QUERY_STRING=") + AToT(pClient->m_query)); { CStringA str; if (pClient->m_hdrlines.Lookup("content-type", str)) { env.AddTail(_T("CONTENT_TYPE=") + AToT(str)); } if (pClient->m_hdrlines.Lookup("content-length", str)) { env.AddTail(_T("CONTENT_LENGTH=") + AToT(str)); } } POSITION pos = pClient->m_hdrlines.GetStartPosition(); while (pos) { CString key = pClient->m_hdrlines.GetKeyAt(pos); CString value = pClient->m_hdrlines.GetNextValue(pos); key.Replace(_T("-"), _T("_")); key.MakeUpper(); env.AddTail(_T("HTTP_") + key + _T("=") + value); } CString str, name; UINT port; if (pClient->GetPeerName(name, port)) { str.Format(_T("%u"), port); env.AddTail(_T("REMOTE_ADDR=") + name); env.AddTail(_T("REMOTE_HOST=") + name); env.AddTail(_T("REMOTE_PORT=") + str); } if (pClient->GetSockName(name, port)) { str.Format(_T("%u"), port); env.AddTail(_T("SERVER_NAME=") + name); env.AddTail(_T("SERVER_PORT=") + str); } env.AddTail(_T("\0")); str = Implode(env, '\0'); envstr = CStringA(str, str.GetLength()); FreeEnvironmentStrings((LPTSTR)lpvEnv); } TCHAR* cmdln = DEBUG_NEW TCHAR[32768]; _sntprintf_s(cmdln, 32768, 32768, _T("\"%s\" \"%s\""), cgi, path); if (hChildStdinRd && hChildStdoutWr) if (CreateProcess( nullptr, cmdln, nullptr, nullptr, TRUE, 0, envstr.GetLength() ? (LPVOID)(LPCSTR)envstr : nullptr, dir, &siStartInfo, &piProcInfo)) { DWORD ThreadId; VERIFY(CreateThread(nullptr, 0, KillCGI, (LPVOID)piProcInfo.hProcess, 0, &ThreadId)); static const int BUFFSIZE = 1024; DWORD dwRead, dwWritten = 0; int i = 0, len = pClient->m_data.GetLength(); for (; i < len; i += dwWritten) { if (!WriteFile(hChildStdinWrDup, (LPCSTR)pClient->m_data + i, std::min(len - i, BUFFSIZE), &dwWritten, nullptr)) { break; } } CloseHandle(hChildStdinWrDup); CloseHandle(hChildStdoutWr); body.Empty(); CStringA buff; while (i == len && ReadFile(hChildStdoutRdDup, buff.GetBuffer(BUFFSIZE), BUFFSIZE, &dwRead, nullptr) && dwRead) { buff.ReleaseBufferSetLength(dwRead); body += buff; } int hdrend = body.Find("\r\n\r\n"); if (hdrend >= 0) { hdr = body.Left(hdrend + 2); body = body.Mid(hdrend + 4); } CloseHandle(hChildStdinRd); CloseHandle(hChildStdoutRdDup); CloseHandle(piProcInfo.hProcess); CloseHandle(piProcInfo.hThread); } else { body = _T("CGI Error"); } delete [] cmdln; return true; }
HRESULT CSubtitleStream::FillBuffer(IMediaSample* pSample) { HRESULT hr; { CAutoLock cAutoLockShared(&m_cSharedState); BYTE* pData = NULL; if (FAILED(hr = pSample->GetPointer(&pData)) || !pData) { return S_FALSE; } AM_MEDIA_TYPE* pmt; if (SUCCEEDED(pSample->GetMediaType(&pmt)) && pmt) { CMediaType mt(*pmt); SetMediaType(&mt); DeleteMediaType(pmt); } int len = 0; REFERENCE_TIME rtStart, rtStop; if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_ARGB32) { rtStart = (REFERENCE_TIME)((m_nPosition * _ATPF - m_rtStart) / m_dRateSeeking); rtStop = (REFERENCE_TIME)(((m_nPosition + 1) * _ATPF - m_rtStart) / m_dRateSeeking); if (m_rtStart + rtStart >= m_rtDuration) { return S_FALSE; } BITMAPINFOHEADER& bmi = ((VIDEOINFOHEADER*)m_mt.pbFormat)->bmiHeader; SubPicDesc spd; spd.w = _WIDTH; spd.h = _HEIGHT; spd.bpp = 32; spd.pitch = bmi.biWidth * 4; spd.bits = pData; len = spd.h * spd.pitch; for (int y = 0; y < spd.h; y++) { memsetd((DWORD*)(pData + spd.pitch * y), 0xff000000, spd.w * 4); } RECT bbox; m_rts.Render(spd, m_nPosition * _ATPF, 10000000.0 / _ATPF, bbox); for (int y = 0; y < spd.h; y++) { DWORD* p = (DWORD*)(pData + spd.pitch * y); for (int x = 0; x < spd.w; x++, p++) { *p = (0xff000000 - (*p & 0xff000000)) | (*p & 0xffffff); } } } else if (m_mt.majortype == MEDIATYPE_Video && m_mt.subtype == MEDIASUBTYPE_RGB32) { const STSSegment* stss = m_rts.GetSegment(m_nPosition); if (!stss) { return S_FALSE; } BITMAPINFOHEADER& bmi = ((VIDEOINFOHEADER*)m_mt.pbFormat)->bmiHeader; SubPicDesc spd; spd.w = _WIDTH; spd.h = _HEIGHT; spd.bpp = 32; spd.pitch = bmi.biWidth * 4; spd.bits = pData; len = spd.h * spd.pitch; for (int y = 0; y < spd.h; y++) { DWORD c1 = 0xff606060, c2 = 0xffa0a0a0; if (y & 32) { c1 ^= c2, c2 ^= c1, c1 ^= c2; } DWORD* p = (DWORD*)(pData + spd.pitch * y); for (int x = 0; x < spd.w; x += 32, p += 32) { memsetd(p, (x & 32) ? c1 : c2, min(spd.w - x, 32) * 4); } } RECT bbox; m_rts.Render(spd, 10000i64 * (stss->start + stss->end) / 2, 10000000.0 / _ATPF, bbox); rtStart = (REFERENCE_TIME)((10000i64 * stss->start - m_rtStart) / m_dRateSeeking); rtStop = (REFERENCE_TIME)((10000i64 * stss->end - m_rtStart) / m_dRateSeeking); } else { if ((size_t)m_nPosition >= m_rts.GetCount()) { return S_FALSE; } STSEntry& stse = m_rts[m_nPosition]; if (stse.start >= m_rtStop / 10000) { return S_FALSE; } if (m_mt.majortype == MEDIATYPE_Subtitle && m_mt.subtype == MEDIASUBTYPE_UTF8) { CStringA str = UTF16To8(m_rts.GetStrW(m_nPosition, false)); memcpy((char*)pData, str, len = str.GetLength()); } else if (m_mt.majortype == MEDIATYPE_Subtitle && (m_mt.subtype == MEDIASUBTYPE_SSA || m_mt.subtype == MEDIASUBTYPE_ASS)) { CStringW line; line.Format(L"%d,%d,%s,%s,%d,%d,%d,%s,%s", stse.readorder, stse.layer, CStringW(stse.style), CStringW(stse.actor), stse.marginRect.left, stse.marginRect.right, (stse.marginRect.top + stse.marginRect.bottom) / 2, CStringW(stse.effect), m_rts.GetStrW(m_nPosition, true)); CStringA str = UTF16To8(line); memcpy((char*)pData, str, len = str.GetLength()); } else if (m_mt.majortype == MEDIATYPE_Text && m_mt.subtype == MEDIASUBTYPE_NULL) { CStringA str = m_rts.GetStrA(m_nPosition, false); memcpy((char*)pData, str, len = str.GetLength()); } else { return S_FALSE; } rtStart = (REFERENCE_TIME)((10000i64 * stse.start - m_rtStart) / m_dRateSeeking); rtStop = (REFERENCE_TIME)((10000i64 * stse.end - m_rtStart) / m_dRateSeeking); } pSample->SetTime(&rtStart, &rtStop); pSample->SetActualDataLength(len); m_nPosition++; } pSample->SetSyncPoint(TRUE); if (m_bDiscontinuity) { pSample->SetDiscontinuity(TRUE); m_bDiscontinuity = FALSE; } return S_OK; }
void CClientDlg::SendHttp() { USES_CONVERSION; if(!CheckStarted(TRUE)) return; CString strMethod; CString strSchema; CString strAddress; CString strPort; CString strPath; m_Method.GetWindowText(strMethod); m_Schema.GetWindowText(strSchema); m_Address.GetWindowText(strAddress); m_Port.GetWindowText(strPort); if(m_Method.GetCurSel() != 8) { m_Path.GetWindowText(strPath); strPath.Trim(); if(strPath.IsEmpty() || strPath.GetAt(0) != '/') strPath.Insert(0, '/'); } THttpHeaderMap headers; int iCount = m_Headers.GetCount(); for(int i = 0; i < iCount; i++) { CString strHeader; m_Headers.GetText(i, strHeader); int j = 0; CString strName = strHeader.Tokenize(_T(": "), j); CString strValue = strHeader.Mid(j + 1); headers.emplace(THttpHeaderMap::value_type(T2A(strName), T2A(strValue))); } CStringA strBodyA; CStringA strPathA; if(m_Method.GetCurSel() <= 2) { CString strBody; m_Body.GetWindowText(strBody); strBodyA = T2A(strBody); } else if(m_Method.GetCurSel() == 8) { THttpHeaderMapCI it = headers.find("Host"); if(it != headers.end() && !it->second.IsEmpty()) strPathA = it->second; else { CString strHost; strHost.Format(_T("%s:%s"), strAddress, strPort); strPathA = strHost; } } if(strPathA.IsEmpty()) strPathA = T2A(strPath); DWORD dwIndex = 0; DWORD dwSize = (DWORD)headers.size(); unique_ptr<THeader[]> szHeaders(new THeader[dwSize]); for(THttpHeaderMapCI it = headers.begin(), end = headers.end(); it != end; ++it, ++dwIndex) { szHeaders[dwIndex].name = it->first; szHeaders[dwIndex].value = it->second; } CONNID dwConnID = m_pClient->GetConnectionID(); if(m_pClient->SendRequest(T2A(strMethod), strPathA, szHeaders.get(), dwSize, (const BYTE*)(LPCSTR)strBodyA, strBodyA.GetLength())) { CString strContent; strContent.Format(_T("[%s] %s://%s:%s%s"), strMethod, strSchema, strAddress, strPort, strPath); ::LogSend(dwConnID, strContent); if(!m_bListener) { CStringA strSummary = GetHeaderSummary(m_pClient.get(), " ", 0, TRUE); ::PostOnHeadersComplete(dwConnID, strSummary); } LPCBYTE pData = nullptr; int iLength = 0; m_pClient->GetResponseBody(&pData, &iLength); if(iLength > 0) { if(!m_bListener) ::PostOnBody(dwConnID, pData, iLength); LPCSTR lpszEnc = m_pClient->GetContentEncoding(); if(lpszEnc && ::StrStrIA(lpszEnc, "gzip")) { int rs = 0; DWORD dwLen = ::GZipGuessUncompressBound(pData, iLength); if(dwLen == 0 || dwLen > 5 * 1024 * 1024) rs = -10; else { CBufferPtr szBuff(dwLen); rs = ::GZipUncompress(pData, iLength, szBuff, dwLen); } if(rs == 0) ::PostUncompressBody(dwConnID, dwLen); else { ::PostUncompressBodyFail(dwConnID, rs); if(!m_bListener) ::PostOnMessageComplete(dwConnID); OnBnClickedStop(); return; } } } if(!m_bListener) ::PostOnMessageComplete(dwConnID); EnHttpUpgradeType enUpgrade = m_pClient->GetUpgradeType(); if(enUpgrade == HUT_WEB_SOCKET) { if(!m_bListener) ::PostOnUpgrade(dwConnID, enUpgrade); m_bWebSocket = TRUE; OnCbnSelchangeMethod(); } } else { ::LogSendFail(dwConnID, ::GetLastError(), ::GetSocketErrorDesc(SE_DATA_SEND)); SetAppState(ST_STOPPED); } m_pClient->CleanupRequestResult(); }
HRESULT CPixelShaderCompiler::InternalCompile( LPCSTR pSrcData, SIZE_T SrcDataSize, LPCSTR pSourceName, LPCSTR pEntrypoint, LPCSTR pProfile, DWORD Flags, IDirect3DPixelShader9** ppPixelShader, CString* pDisasm, CString* pErrMsg) { if (!m_pD3DCompile) { return E_FAIL; } if (pDisasm && !m_pD3DDisassemble) { return E_FAIL; } if (ppPixelShader && !m_pD3DDev) { return E_FAIL; } LPCSTR pSelProfile = pProfile; if (!pSelProfile || *pSelProfile == '\0') { D3DCAPS9 caps; if (m_pD3DDev && m_pD3DDev->GetDeviceCaps(&caps) == D3D_OK) { switch (D3DSHADER_VERSION_MAJOR(caps.PixelShaderVersion)) { case 2: if (caps.PS20Caps.NumInstructionSlots < 512) { pSelProfile = "ps_2_0"; } else if (caps.PS20Caps.Caps > 0) { pSelProfile = "ps_2_a"; } else { pSelProfile = "ps_2_b"; } break; case 3: pSelProfile = "ps_3_0"; break; } } else { ASSERT(FALSE); } } if (!pSelProfile || *pSelProfile == '\0') { return E_FAIL; } LPCSTR defProfile = "MPC_HC_SHADER_PROFILE"; LPCSTR defProfileVal; if (!strcmp(pSelProfile, "ps_2_0")) { defProfileVal = "0"; } else if (!strcmp(pSelProfile, "ps_2_b")) { defProfileVal = "1"; } else if (!strcmp(pSelProfile, "ps_2_a") || !strcmp(pSelProfile, "ps_2_sw")) { defProfileVal = "2"; } else if (!strcmp(pSelProfile, "ps_3_0") || !strcmp(pSelProfile, "ps_3_sw")) { defProfileVal = "3"; } else { defProfileVal = "-1"; } D3D_SHADER_MACRO macros[] = { { defProfile, defProfileVal }, { 0 } }; CComPtr<ID3DBlob> pShaderBlob, pErrorBlob; HRESULT hr = m_pD3DCompile(pSrcData, SrcDataSize, pSourceName, macros, nullptr, pEntrypoint, pSelProfile, Flags, 0, &pShaderBlob, &pErrorBlob); if (pErrMsg) { CStringA msg; if (pErrorBlob) { auto len = pErrorBlob->GetBufferSize(); VERIFY(memcpy_s(msg.GetBufferSetLength((int)len), len, pErrorBlob->GetBufferPointer(), len) == 0); msg.ReleaseBuffer((int)len); } *pErrMsg = msg; } if (FAILED(hr)) { return hr; } if (ppPixelShader) { hr = m_pD3DDev->CreatePixelShader((DWORD*)pShaderBlob->GetBufferPointer(), ppPixelShader); if (FAILED(hr)) { return hr; } } if (pDisasm) { CComPtr<ID3DBlob> pDisasmBlob; CStringA defs; for (auto pMacro = macros; pMacro && pMacro->Name && pMacro->Definition; pMacro++) { defs.Append("// #define "); defs.Append(pMacro->Name); defs.Append(" "); defs.Append(pMacro->Definition); defs.Append("\n"); } hr = m_pD3DDisassemble(pShaderBlob->GetBufferPointer(), pShaderBlob->GetBufferSize(), 0, defs, &pDisasmBlob); if (SUCCEEDED(hr)) { CStringA disasm; auto len = pDisasmBlob->GetBufferSize(); VERIFY(memcpy_s(disasm.GetBufferSetLength((int)len), len, pDisasmBlob->GetBufferPointer(), len) == 0); disasm.ReleaseBuffer((int)len); *pDisasm = disasm; } } return S_OK; }
void CClientDlg::SendWebSocket() { static LPCSTR CLOSE_FLAG = "$close"; static const BYTE MASK_KEY[] = {0x1, 0x2, 0x3, 0x4}; USES_CONVERSION; if(!CheckStarted(FALSE)) return; CString strBody; m_Body.GetWindowText(strBody); CStringA strBodyA = T2A(strBody); BYTE* pData = (BYTE*)(LPCSTR)strBodyA; int iLength = strBodyA.GetLength(); CONNID dwConnID = m_pClient->GetConnectionID(); if(strBodyA.CompareNoCase(CLOSE_FLAG) != 0) { if(m_pClient->SendWSMessage(TRUE, 0, 0x1, MASK_KEY, pData, iLength)) { CString strContent; strContent.Format(_T("[WebSocket] (len: %d)"), iLength); ::LogSend(dwConnID, strContent); BOOL bFinal; BYTE iReserved; BYTE iOperationCode; LPCBYTE lpszMask; ULONGLONG ullBodyLen; VERIFY(m_pClient->GetWSMessageState(&bFinal, &iReserved, &iOperationCode, &lpszMask, &ullBodyLen, nullptr)); if(!m_bListener) ::PostOnWSMessageHeader(dwConnID, bFinal, iReserved, iOperationCode, lpszMask, ullBodyLen); if(ullBodyLen > 0) { m_pClient->GetResponseBody((LPCBYTE*)&pData, &iLength); if(!m_bListener) ::PostOnWSMessageBody(dwConnID, pData, iLength); } if(!m_bListener) ::PostOnWSMessageComplete(dwConnID); if(iOperationCode == 0x8) OnBnClickedStop(); } else { ::LogSendFail(dwConnID, ::GetLastError(), ::GetSocketErrorDesc(SE_DATA_SEND)); SetAppState(ST_STOPPED); } } else { if(m_pClient->SendWSMessage(TRUE, 0, 0x8, MASK_KEY, nullptr, 0)) { ::LogSend(dwConnID, _T("[WebSocket] (OP: close)")); } m_Body.SetWindowText(_T("")); OnBnClickedStop(); } m_pClient->CleanupRequestResult(); }
int CIPFilter::AddFromFile(LPCTSTR pszFilePath, bool bShowResponse) { DWORD dwStart = GetTickCount(); // ==> Show (un-)loading status of IPFilter [Stulle] - Stulle int iLineCount = 0; int iLastPercent = 0; CStdioFile countFile; if(countFile.Open(pszFilePath, CFile::modeRead)==TRUE) { CString strBuffer; while(countFile.ReadString(strBuffer)!=FALSE) iLineCount++; countFile.Close(); } // <== Show (un-)loading status of IPFilter [Stulle] - Stulle FILE* readFile = _tfsopen(pszFilePath, _T("r"), _SH_DENYWR); if (readFile != NULL) { enum EIPFilterFileType { Unknown = 0, FilterDat = 1, // ipfilter.dat/ip.prefix format PeerGuardian = 2, // PeerGuardian text format PeerGuardian2 = 3 // PeerGuardian binary format } eFileType = Unknown; setvbuf(readFile, NULL, _IOFBF, 32768); TCHAR szNam[_MAX_FNAME]; TCHAR szExt[_MAX_EXT]; _tsplitpath(pszFilePath, NULL, NULL, szNam, szExt); if (_tcsicmp(szExt, _T(".p2p")) == 0 || (_tcsicmp(szNam, _T("guarding.p2p")) == 0 && _tcsicmp(szExt, _T(".txt")) == 0)) eFileType = PeerGuardian; else if (_tcsicmp(szExt, _T(".prefix")) == 0) eFileType = FilterDat; else { VERIFY( _setmode(_fileno(readFile), _O_BINARY) != -1 ); static const BYTE _aucP2Bheader[] = "\xFF\xFF\xFF\xFFP2B"; BYTE aucHeader[sizeof _aucP2Bheader - 1]; if (fread(aucHeader, sizeof aucHeader, 1, readFile) == 1) { if (memcmp(aucHeader, _aucP2Bheader, sizeof _aucP2Bheader - 1)==0) eFileType = PeerGuardian2; else { (void)fseek(readFile, 0, SEEK_SET); VERIFY( _setmode(_fileno(readFile), _O_TEXT) != -1 ); // ugly! } } } int iFoundRanges = 0; int iLine = 0; if (eFileType == PeerGuardian2) { // Version 1: strings are ISO-8859-1 encoded // Version 2: strings are UTF-8 encoded uint8 nVersion; if (fread(&nVersion, sizeof nVersion, 1, readFile)==1 && (nVersion==1 || nVersion==2)) { while (!feof(readFile)) { CHAR szName[256]; int iLen = 0; for (;;) // read until NUL or EOF { int iChar = getc(readFile); if (iChar == EOF) break; if (iLen < sizeof szName - 1) szName[iLen++] = (CHAR)iChar; if (iChar == '\0') break; } szName[iLen] = '\0'; uint32 uStart; if (fread(&uStart, sizeof uStart, 1, readFile) != 1) break; uStart = ntohl(uStart); uint32 uEnd; if (fread(&uEnd, sizeof uEnd, 1, readFile) != 1) break; uEnd = ntohl(uEnd); iLine++; // ==> Show (un-)loading status of IPFilter [Stulle] - Stulle if(iLineCount) { int iPercent = (int)((float(iLine)*100.0f)/float(iLineCount)); if(iPercent - iLastPercent > 1) { CString strPercent; strPercent.Format(_T("Loading IPfilter (%i %%) ..."),iPercent); if(theApp.IsSplash()) theApp.UpdateSplash(strPercent); else if (theApp.emuledlg->statusbar->m_hWnd) theApp.emuledlg->statusbar->SetText(strPercent,0,0); iLastPercent = iPercent; } } // <== Show (un-)loading status of IPFilter [Stulle] - Stulle // (nVersion == 2) ? OptUtf8ToStr(szName, iLen) : AddIPRange(uStart, uEnd, DFLT_FILTER_LEVEL, CStringA(szName, iLen)); iFoundRanges++; } } } else { CStringA sbuffer; CHAR szBuffer[1024]; while (fgets(szBuffer, _countof(szBuffer), readFile) != NULL) { iLine++; // ==> Show (un-)loading status of IPFilter [Stulle] - Stulle if(iLineCount) { int iPercent = (int)((float(iLine)*100.0f)/float(iLineCount)); if(iPercent - iLastPercent > 1) { CString strPercent; strPercent.Format(_T("Loading IPfilter (%i %%) ..."),iPercent); if(theApp.IsSplash()) theApp.UpdateSplash(strPercent); else if (theApp.emuledlg->statusbar->m_hWnd) theApp.emuledlg->statusbar->SetText(strPercent,0,0); iLastPercent = iPercent; } } // <== Show (un-)loading status of IPFilter [Stulle] - Stulle sbuffer = szBuffer; // ignore comments & too short lines if (sbuffer.GetAt(0) == '#' || sbuffer.GetAt(0) == '/' || sbuffer.GetLength() < 5) { sbuffer.Trim(" \t\r\n"); DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter: ignored line %u\n", iLine) : 0 ); continue; } if (eFileType == Unknown) { // looks like html if (sbuffer.Find('>') > -1 && sbuffer.Find('<') > -1) sbuffer.Delete(0, sbuffer.ReverseFind('>') + 1); // check for <IP> - <IP> at start of line UINT u1, u2, u3, u4, u5, u6, u7, u8; if (sscanf(sbuffer, "%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8) == 8) { eFileType = FilterDat; } else { // check for <description> ':' <IP> '-' <IP> int iColon = sbuffer.Find(':'); if (iColon > -1) { CStringA strIPRange = sbuffer.Mid(iColon + 1); UINT u1, u2, u3, u4, u5, u6, u7, u8; if (sscanf(strIPRange, "%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8) == 8) { eFileType = PeerGuardian; } } } } bool bValid = false; uint32 start = 0; uint32 end = 0; UINT level = 0; CStringA desc; if (eFileType == FilterDat) bValid = ParseFilterLine1(sbuffer, start, end, level, desc); else if (eFileType == PeerGuardian) bValid = ParseFilterLine2(sbuffer, start, end, level, desc); // add a filter if (bValid) { AddIPRange(start, end, level, desc); iFoundRanges++; } else { sbuffer.Trim(" \t\r\n"); DEBUG_ONLY( (!sbuffer.IsEmpty()) ? TRACE("IP filter: ignored line %u\n", iLine) : 0 ); } } } fclose(readFile); // sort the IP filter list by IP range start addresses qsort(m_iplist.GetData(), m_iplist.GetCount(), sizeof(m_iplist[0]), CmpSIPFilterByStartAddr); // merge overlapping and adjacent filter ranges int iDuplicate = 0; int iMerged = 0; if (m_iplist.GetCount() >= 2) { // On large IP-filter lists there is a noticeable performance problem when merging the list. // The 'CIPFilterArray::RemoveAt' call is way too expensive to get called during the merging, // thus we use temporary helper arrays to copy only the entries into the final list which // are not get deleted. // Reserve a byte array (its used as a boolean array actually) as large as the current // IP-filter list, so we can set a 'to delete' flag for each entry in the current IP-filter list. char* pcToDelete = new char[m_iplist.GetCount()]; memset(pcToDelete, 0, m_iplist.GetCount()); int iNumToDelete = 0; SIPFilter* pPrv = m_iplist[0]; int i = 1; while (i < m_iplist.GetCount()) { SIPFilter* pCur = m_iplist[i]; if ( pCur->start >= pPrv->start && pCur->start <= pPrv->end // overlapping || pCur->start == pPrv->end+1 && pCur->level == pPrv->level) // adjacent { if (pCur->start != pPrv->start || pCur->end != pPrv->end) // don't merge identical entries { //TODO: not yet handled, overlapping entries with different 'level' if (pCur->end > pPrv->end) pPrv->end = pCur->end; //pPrv->desc += _T("; ") + pCur->desc; // this may create a very very long description string... iMerged++; } else { // if we have identical entries, use the lowest 'level' if (pCur->level < pPrv->level) pPrv->level = pCur->level; iDuplicate++; } delete pCur; //m_iplist.RemoveAt(i); // way too expensive (read above) pcToDelete[i] = 1; // mark this entry as 'to delete' iNumToDelete++; i++; continue; } pPrv = pCur; i++; } // Create new IP-filter list which contains only the entries from the original IP-filter list // which are not to be deleted. if (iNumToDelete > 0) { CIPFilterArray newList; newList.SetSize(m_iplist.GetCount() - iNumToDelete); int iNewListIndex = 0; for (int i = 0; i < m_iplist.GetCount(); i++) { if (!pcToDelete[i]) newList[iNewListIndex++] = m_iplist[i]; } ASSERT( iNewListIndex == newList.GetSize() ); // Replace current list with new list. Dump, but still fast enough (only 1 memcpy) m_iplist.RemoveAll(); m_iplist.Append(newList); newList.RemoveAll(); m_bModified = true; } delete[] pcToDelete; } if (thePrefs.GetVerbose()) { DWORD dwEnd = GetTickCount(); AddDebugLogLine(false, _T("Loaded IP filters from \"%s\""), pszFilePath); AddDebugLogLine(false, _T("Parsed lines/entries:%u Found IP ranges:%u Duplicate:%u Merged:%u Time:%s"), iLine, iFoundRanges, iDuplicate, iMerged, CastSecondsToHM((dwEnd-dwStart+500)/1000)); } AddLogLine(bShowResponse, GetResString(IDS_IPFILTERLOADED), m_iplist.GetCount()); } return m_iplist.GetCount(); }
CStringA CClientDlg::GetHeaderSummary(IHttpSyncClient* pHttpClient, LPCSTR lpszSep, int iSepCount, BOOL bWithContentLength) { CStringA SEP1; for(int i = 0; i < iSepCount; i++) SEP1 += lpszSep; CStringA SEP2(SEP1); SEP2 += lpszSep; CStringA strResult; strResult.AppendFormat("%s[Status Fields]%s", SEP1, CRLF); strResult.AppendFormat("%s%13s: %u%s", SEP2, "Status Code", pHttpClient->GetStatusCode(), CRLF); DWORD dwHeaderCount = 0; pHttpClient->GetAllHeaders(nullptr, dwHeaderCount); strResult.AppendFormat("%s[Response Headers]%s", SEP1, CRLF); if(dwHeaderCount == 0) strResult.AppendFormat("%s(no header)%s", SEP2, CRLF); else { unique_ptr<THeader[]> headers(new THeader[dwHeaderCount]); VERIFY(pHttpClient->GetAllHeaders(headers.get(), dwHeaderCount)); for(DWORD i = 0; i < dwHeaderCount; i++) strResult.AppendFormat("%s%s: %s%s", SEP2, headers[i].name, headers[i].value, CRLF); } DWORD dwCookieCount = 0; pHttpClient->GetAllCookies(nullptr, dwCookieCount); strResult.AppendFormat("%s[Cookies]%s", SEP1, CRLF); if(dwCookieCount == 0) strResult.AppendFormat("%s(no cookie)%s", SEP2, CRLF); else { unique_ptr<TCookie[]> cookies(new TCookie[dwCookieCount]); VERIFY(pHttpClient->GetAllCookies(cookies.get(), dwCookieCount)); for(DWORD i = 0; i < dwCookieCount; i++) strResult.AppendFormat("%s%s: %s%s", SEP2, cookies[i].name, cookies[i].value, CRLF); } CStringA strVersion; ::HttpVersionToString((EnHttpVersion)pHttpClient->GetVersion(), strVersion); EnHttpUpgradeType enUpgType = pHttpClient->GetUpgradeType(); LPCSTR lpszUpgrade = enUpgType != HUT_NONE ? "true" : "false"; LPCSTR lpszKeepAlive = pHttpClient->IsKeepAlive() ? "true" : "false"; strResult.AppendFormat("%s[Basic Info]%s", SEP1, CRLF); strResult.AppendFormat("%s%13s: %s%s", SEP2, "Version", strVersion, CRLF); strResult.AppendFormat("%s%13s: %u%s", SEP2, "Status Code", pHttpClient->GetStatusCode(), CRLF); strResult.AppendFormat("%s%13s: %s%s", SEP2, "IsUpgrade", lpszUpgrade, CRLF); if(enUpgType != HUT_NONE) strResult.AppendFormat("%s%13s: %d%s", SEP2, "UpgradeType", enUpgType, CRLF); strResult.AppendFormat("%s%13s: %s%s", SEP2, "IsKeepAlive", lpszKeepAlive, CRLF); if(bWithContentLength) strResult.AppendFormat("%s%13s: %lld%s", SEP2, "ContentLength", pHttpClient->GetContentLength(), CRLF); strResult.AppendFormat("%s%13s: %s%s", SEP2, "ContentType", pHttpClient->GetContentType(), CRLF); return strResult; }
// 根据字符串获取键盘码 void CDuiObject::ParseKeyCode(LPCTSTR lpszValue, UINT& nChar, UINT& nFlag) { CStringA strValue; strValue = lpszValue; nChar = 0; nFlag = 0; strValue.Trim(); strValue.MakeUpper(); CStringA strFlag = ""; CStringA strChar = strValue; int nPos = strValue.Find("+"); if(nPos != -1) { strFlag = strValue.Left(nPos); strValue.Delete(0, nPos+1); strChar = strValue; strFlag.Trim(); strChar.Trim(); } if(strChar.IsEmpty()) { return; } if(strFlag == "CTRL") { nFlag |= VK_CONTROL; }else if(strFlag == "ALT") { nFlag |= VK_MENU; }else if(strFlag == "SHIFT") { nFlag |= VK_SHIFT; } if(strChar == "RETURN") { nChar = VK_RETURN; }else if(strChar == "ESC") { nChar = VK_ESCAPE; }else if(strChar == "BACK") { nChar = VK_BACK; }else if(strChar == "TAB") { nChar = VK_TAB; }else if(strChar == "SPACE") { nChar = VK_SPACE; }else if(strChar == "PRIOR") { nChar = VK_PRIOR; }else if(strChar == "NEXT") { nChar = VK_NEXT; }else if(strChar == "END") { nChar = VK_END; }else if(strChar == "HOME") { nChar = VK_HOME; }else if(strChar == "LEFT") { nChar = VK_LEFT; }else if(strChar == "UP") { nChar = VK_UP; }else if(strChar == "RIGHT") { nChar = VK_RIGHT; }else if(strChar == "DOWN") { nChar = VK_DOWN; }else if(strChar == "SELECT") { nChar = VK_SELECT; }else if(strChar == "PRINT") { nChar = VK_PRINT; }else if(strChar == "INSERT") { nChar = VK_INSERT; }else if(strChar == "DELETE") { nChar = VK_DELETE; }else if(strChar == "F1") { nChar = VK_F1; }else if(strChar == "F2") { nChar = VK_F2; }else if(strChar == "F3") { nChar = VK_F3; }else if(strChar == "F4") { nChar = VK_F4; }else if(strChar == "F5") { nChar = VK_F5; }else if(strChar == "F6") { nChar = VK_F6; }else if(strChar == "F7") { nChar = VK_F7; }else if(strChar == "F8") { nChar = VK_F8; }else if(strChar == "F9") { nChar = VK_F9; }else if(strChar == "F10") { nChar = VK_F10; }else if(strChar == "F11") { nChar = VK_F11; }else if(strChar == "F12") { nChar = VK_F12; }else { char ch = strChar[0]; if(((ch >= '0') && (ch < '9')) || ((ch >= 'A') && (ch < 'Z'))) { nChar = ch; } } }
void CRepositoryBrowser::OpenFile(const CString path, eOpenType mode, bool isSubmodule, CGitHash itemHash) { CTGitPath gitPath(path); CString temppath; CString file; GetTempPath(temppath); CGitHash hash; if (g_Git.GetHash(hash, m_sRevision)) { MessageBox(g_Git.GetGitLastErr(_T("Could not get hash of ") + m_sRevision + _T(".")), _T("TortoiseGit"), MB_ICONERROR); return; } file.Format(_T("%s%s_%s%s"), (LPCTSTR)temppath, (LPCTSTR)gitPath.GetBaseFilename(), (LPCTSTR)hash.ToString().Left(g_Git.GetShortHASHLength()), (LPCTSTR)gitPath.GetFileExtension()); if (isSubmodule) { if (mode == OPEN && !GitAdminDir::IsBareRepo(g_Git.m_CurrentDir)) { CTGitPath subPath = CTGitPath(g_Git.m_CurrentDir); subPath.AppendPathString(gitPath.GetWinPathString()); CAutoRepository repo(subPath.GetGitPathString()); CAutoCommit commit; if (!repo || git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)itemHash.m_hash)) { CString out; out.Format(IDS_REPOBROWSEASKSUBMODULEUPDATE, (LPCTSTR)itemHash.ToString(), (LPCTSTR)gitPath.GetGitPathString()); if (MessageBox(out, _T("TortoiseGit"), MB_YESNO | MB_ICONQUESTION) != IDYES) return; CString sCmd; sCmd.Format(_T("/command:subupdate /bkpath:\"%s\" /selectedpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir, (LPCTSTR)gitPath.GetGitPathString()); CAppUtils::RunTortoiseGitProc(sCmd); return; } CString cmd; cmd.Format(_T("/command:repobrowser /path:\"%s\" /rev:%s"), (LPCTSTR)g_Git.CombinePath(path), (LPCTSTR)itemHash.ToString()); CAppUtils::RunTortoiseGitProc(cmd); return; } file += _T(".txt"); CFile submoduleCommit(file, CFile::modeCreate | CFile::modeWrite); CStringA commitInfo = "Subproject commit " + CStringA(itemHash.ToString()); submoduleCommit.Write(commitInfo, commitInfo.GetLength()); } else if (g_Git.GetOneFile(m_sRevision, gitPath, file)) { CString out; out.Format(IDS_STATUSLIST_CHECKOUTFILEFAILED, (LPCTSTR)gitPath.GetGitPathString(), (LPCTSTR)m_sRevision, (LPCTSTR)file); MessageBox(g_Git.GetGitLastErr(out, CGit::GIT_CMD_GETONEFILE), _T("TortoiseGit"), MB_ICONERROR); return; } if (mode == ALTERNATIVEEDITOR) { CAppUtils::LaunchAlternativeEditor(file); return; } else if (mode == OPEN) { CAppUtils::ShellOpen(file); return; } CAppUtils::ShowOpenWithDialog(file); }
VOID CALLBACK HCInternetStatusCallback( __in HINTERNET hInternet, __in_opt DWORD_PTR dwContext, __in DWORD dwInternetStatus, __in_opt LPVOID lpvStatusInformation, __in DWORD dwStatusInformationLength ) { if ( INTERNET_STATUS_REDIRECT == dwInternetStatus ) { LPCSTR pszRedirectUrl = (LPCSTR)lpvStatusInformation; CStringA strRedirectUrl; strRedirectUrl = pszRedirectUrl; CStringA strOrgUrl; UrlRecorder.GetRecordData(hInternet,&strOrgUrl); UrlRecorder.SetRecordData(hInternet,strRedirectUrl); CHAR chCookieData[2000]={0}; CommonGetCookie(strRedirectUrl,chCookieData,1999,FALSE); CStringA strCookieHeader; strCookieHeader = "Cookie: "; strCookieHeader += chCookieData; BOOL bRes = HttpAddRequestHeadersA(hInternet,strCookieHeader.GetBuffer(),strCookieHeader.GetLength(),HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE); int a=0; } if ( INTERNET_STATUS_REQUEST_COMPLETE == dwInternetStatus ) { CStringA strInternetUrl; UrlRecorder.GetRecordData(hInternet,&strInternetUrl); char chRecvCookie[2000]; DWORD dwRecvCookieLen = 2000; DWORD dwCookieIndex = 0; while(HttpQueryInfoA(hInternet,HTTP_QUERY_SET_COOKIE,chRecvCookie,&dwRecvCookieLen,&dwCookieIndex)) { CommonSetCookie(strInternetUrl,chRecvCookie); if ( ERROR_HTTP_HEADER_NOT_FOUND == dwCookieIndex) { break; } dwRecvCookieLen = 2000; } } INTERNET_STATUS_CALLBACK pOrgCallback = NULL; CallbackRecorder.GetRecordData(hInternet,&pOrgCallback); if (pOrgCallback) { pOrgCallback(hInternet, dwContext, dwInternetStatus, lpvStatusInformation, dwStatusInformationLength ); } }
~DeleteTestFileHelper() { if (mTestFile.GetLength()) { Log(L"Deleting %s", CStringW(mTestFile)); DeleteFileA(mTestFile); } }
void CFlashPlayerDlg::LoadConfig() { CAtlStdioFile playercfg; CString inifile = m_program_dir + _T("mplayer.ini"); if(SUCCEEDED(playercfg.OpenFile(inifile.GetBuffer(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING))) { CStringA lineA; CString line; while(playercfg.ReadLineA(lineA)) { line = local2unicode(lineA.GetBuffer()).c_str(); lineA.ReleaseBuffer(); line.TrimLeft(_T(" ")); line.TrimRight(_T(" ")); line.MakeLower(); if(line.Find(_T("#")) == 0) continue; if(line.Find(_T("fs=yes")) == 0) { m_fs_init = true; continue; } if(line.Find(_T("fs=1")) == 0) { m_fs_init = true; continue; } if(line.Find(_T("ontop=2")) == 0) { m_ontop = true; continue; } if(line.Find(_T("ontop=1")) == 0) { m_ontop = true; continue; } } playercfg.Close(); } inifile.ReleaseBuffer(); CAtlStdioFile inputcfg; inifile = m_program_dir + _T("input.ini"); if(SUCCEEDED(inputcfg.OpenFile(inifile.GetBuffer(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING))) { CString line,command,value,key; CStringA lineA; while(inputcfg.ReadLineA(lineA)) { line = local2unicode(lineA.GetBuffer()).c_str(); lineA.ReleaseBuffer(); if(AnalyseLine(line,key,command,value)) m_inputs.Add(key,command,value); } inputcfg.Close(); } else { m_inputs.Add(_T("F"),_T("vo_fullscreen"),_T("")); m_inputs.Add(_T("f"),_T("vo_fullscreen"),_T("")); m_inputs.Add(_T("T"),_T("vo_ontop"),_T("")); m_inputs.Add(_T("t"),_T("vo_ontop"),_T("")); m_inputs.Add(_T("RIGHT"),_T("seek"),_T("30")); m_inputs.Add(_T("LEFT"),_T("seek"),_T("-30")); m_inputs.Add(_T("DOWN"),_T("seek"),_T("10")); m_inputs.Add(_T("UP"),_T("seek"),_T("-10")); m_inputs.Add(_T("SPACE"),_T("pause"),_T("")); m_inputs.Add(_T("ESC"),_T("quit"),_T("")); m_inputs.Add(_T("K"),_T("keep_aspect"),_T("")); m_inputs.Add(_T("k"),_T("keep_aspect"),_T("")); m_inputs.Add(_T(">"),_T("pt_step"),_T("1")); m_inputs.Add(_T("."),_T("pt_step"),_T("1")); m_inputs.Add(_T("<"),_T("pt_step"),_T("-1")); m_inputs.Add(_T(","),_T("pt_step"),_T("-1")); } }
static int Launch() { Log(L"Launching browser..."); DWORD processID; // The interface that allows us to activate the browser CComPtr<IApplicationActivationManager> activateMgr; if (FAILED(CoCreateInstance(CLSID_ApplicationActivationManager, nullptr, CLSCTX_LOCAL_SERVER, IID_IApplicationActivationManager, (void**)&activateMgr))) { Fail(false, L"CoCreateInstance CLSID_ApplicationActivationManager failed."); return FAILURE; } HRESULT hr; WCHAR appModelID[256]; // Activation is based on the browser's registered app model id if (!GetDefaultBrowserAppModelID(appModelID, (sizeof(appModelID)/sizeof(WCHAR)))) { Fail(false, L"GetDefaultBrowserAppModelID failed."); return FAILURE; } Log(L"App model id='%s'", appModelID); // Hand off focus rights if the terminal has focus to the out-of-process // activation server (explorer.exe). Without this the metro interface // won't launch. hr = CoAllowSetForegroundWindow(activateMgr, nullptr); if (FAILED(hr)) { // Log but don't fail. This has happened on vms with certain terminals run by // QA during mozmill testing. Log(L"Windows focus rights hand off failed (HRESULT=0x%X). Ignoring.", hr); } Log(L"Harness process id: %d", GetCurrentProcessId()); // If provided, validate the firefox path passed in. int binLen = wcslen(kFirefoxExe); if (sFirefoxPath.GetLength() && sFirefoxPath.Right(binLen) != kFirefoxExe) { Log(L"firefoxpath is missing a valid bin name! Assuming '%s'.", kFirefoxExe); if (sFirefoxPath.Right(1) != L"\\") { sFirefoxPath += L"\\"; } sFirefoxPath += kFirefoxExe; } // Because we can't pass command line args, we store params in a // tests.ini file in dist/bin which the browser picks up on launch. CStringA testFilePath; if (sFirefoxPath.GetLength()) { // Use the firefoxpath passed to us by the test harness int index = sFirefoxPath.ReverseFind('\\'); if (index == -1) { Fail(false, L"Bad firefoxpath path"); return FAILURE; } testFilePath = sFirefoxPath.Mid(0, index); testFilePath += "\\"; testFilePath += kMetroTestFile; } else { // Use the module path char path[MAX_PATH]; if (!GetModuleFileNameA(nullptr, path, MAX_PATH)) { Fail(false, L"GetModuleFileNameA errorno=%d", GetLastError()); return FAILURE; } char* slash = strrchr(path, '\\'); if (!slash) return FAILURE; *slash = '\0'; // no trailing slash testFilePath = path; testFilePath += "\\"; sFirefoxPath = testFilePath; sFirefoxPath += kFirefoxExe; testFilePath += kMetroTestFile; } // Make sure the firefox bin exists if (GetFileAttributesW(sFirefoxPath) == INVALID_FILE_ATTRIBUTES) { Fail(false, L"Invalid bin path: '%s'", sFirefoxPath); return FAILURE; } Log(L"Using bin path: '%s'", sFirefoxPath); Log(L"Writing out tests.ini to: '%s'", CStringW(testFilePath)); HANDLE hTestFile = CreateFileA(testFilePath, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hTestFile == INVALID_HANDLE_VALUE) { Fail(false, L"CreateFileA errorno=%d", GetLastError()); return FAILURE; } DeleteTestFileHelper dtf(testFilePath); // nsAppRunner expects the first param to be the bin path, just like a // normal startup. So prepend our bin path to our param string we write. CStringA asciiParams = sFirefoxPath; asciiParams += " "; asciiParams += sAppParams; asciiParams.Trim(); Log(L"Browser command line args: '%s'", CString(asciiParams)); if (!WriteFile(hTestFile, asciiParams, asciiParams.GetLength(), nullptr, 0)) { CloseHandle(hTestFile); Fail(false, L"WriteFile errorno=%d", GetLastError()); return FAILURE; } FlushFileBuffers(hTestFile); CloseHandle(hTestFile); // Create a named stdout pipe for the browser if (!SetupTestOutputPipe()) { Fail(false, L"SetupTestOutputPipe failed (errno=%d)", GetLastError()); return FAILURE; } // Launch firefox hr = activateMgr->ActivateApplication(appModelID, L"", AO_NOERRORUI, &processID); if (FAILED(hr)) { Fail(true, L"ActivateApplication result %X", hr); return RETRY; } Log(L"Activation succeeded."); // automation.py picks up on this, don't mess with it. Log(L"METRO_BROWSER_PROCESS=%d", processID); HANDLE child = OpenProcess(SYNCHRONIZE, FALSE, processID); if (!child) { Fail(false, L"Couldn't find child process. (%d)", GetLastError()); return FAILURE; } Log(L"Waiting on child process..."); MSG msg; DWORD waitResult = WAIT_TIMEOUT; HANDLE handles[2] = { child, gTestOutputPipe }; while ((waitResult = MsgWaitForMultipleObjects(2, handles, FALSE, INFINITE, QS_ALLINPUT)) != WAIT_OBJECT_0) { if (waitResult == WAIT_FAILED) { Log(L"Wait failed (errno=%d)", GetLastError()); break; } else if (waitResult == WAIT_OBJECT_0 + 1) { ReadPipe(); } else if (waitResult == WAIT_OBJECT_0 + 2 && PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } } ReadPipe(); CloseHandle(gTestOutputPipe); CloseHandle(child); Log(L"Exiting."); return SUCCESS; }
std::string loadString(UINT resid) { CStringA s; s.LoadString(resid); return s.GetBuffer(); }
////////////////////////////////////////////////////////////////////////// // IDataObject ////////////////////////////////////////////////////////////////////////// STDMETHODIMP GitDataObject::GetData(FORMATETC* pformatetcIn, STGMEDIUM* pmedium) { if (!pformatetcIn) return E_INVALIDARG; if (!pmedium) return E_POINTER; pmedium->hGlobal = nullptr; if ((pformatetcIn->tymed & TYMED_ISTREAM) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_FILECONTENTS)) { // supports the IStream format. // The lindex param is the index of the file to return CString filepath; IStream* pIStream = nullptr; // Note: we don't get called for directories since those are simply created and don't // need to be fetched. // Note2: It would be really nice if we could get a stream from the subversion library // from where we could read the file contents. But the Subversion lib is not implemented // to *read* from a remote stream but so that the library *writes* to a stream we pass. // Since we can't get such a read stream, we have to fetch the file in whole first to // a temp location and then pass the shell an IStream for that temp file. if (m_revision.IsEmpty()) { if ((pformatetcIn->lindex >= 0) && (pformatetcIn->lindex < (LONG)m_allPaths.size())) filepath = g_Git.CombinePath(m_allPaths[pformatetcIn->lindex]); } else { filepath = CTempFiles::Instance().GetTempFilePath(true).GetWinPathString(); if ((pformatetcIn->lindex >= 0) && (pformatetcIn->lindex < (LONG)m_allPaths.size())) { if (g_Git.GetOneFile(m_revision.ToString(), m_allPaths[pformatetcIn->lindex], filepath)) { DeleteFile(filepath); return STG_E_ACCESSDENIED; } } } HRESULT res = SHCreateStreamOnFileEx(filepath, STGM_READ, FILE_ATTRIBUTE_NORMAL, FALSE, nullptr, &pIStream); if (res == S_OK) { // http://blogs.msdn.com/b/oldnewthing/archive/2014/09/18/10558763.aspx LARGE_INTEGER liZero = { 0, 0 }; pIStream->Seek(liZero, STREAM_SEEK_END, nullptr); pmedium->pstm = pIStream; pmedium->tymed = TYMED_ISTREAM; return S_OK; } return res; } else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_FILEDESCRIPTOR)) { for (int i = 0; i < m_gitPaths.GetCount(); ++i) { if (m_gitPaths[i].m_Action & (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED) || m_gitPaths[i].IsDirectory()) continue; m_allPaths.push_back(m_gitPaths[i]); } size_t dataSize = sizeof(FILEGROUPDESCRIPTOR) + ((max(1, m_allPaths.size()) - 1) * sizeof(FILEDESCRIPTOR)); HGLOBAL data = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, dataSize); FILEGROUPDESCRIPTOR* files = (FILEGROUPDESCRIPTOR*)GlobalLock(data); files->cItems = static_cast<UINT>(m_allPaths.size()); int index = 0; for (auto it = m_allPaths.cbegin(); it != m_allPaths.cend(); ++it) { CString temp(m_iStripLength > 0 ? it->GetWinPathString().Mid(m_iStripLength + 1) : (m_iStripLength == 0 ? it->GetWinPathString() : it->GetUIFileOrDirectoryName())); if (temp.GetLength() < MAX_PATH) wcscpy_s(files->fgd[index].cFileName, (LPCTSTR)temp); else { files->cItems--; continue; } files->fgd[index].dwFlags = FD_ATTRIBUTES | FD_PROGRESSUI | FD_FILESIZE | FD_LINKUI; files->fgd[index].dwFileAttributes = FILE_ATTRIBUTE_NORMAL; // Always set the file size to 0 even if we 'know' the file size (infodata.size64). // Because for text files, the file size is too low due to the EOLs getting converted // to CRLF (from LF as stored in the repository). And a too low file size set here // prevents the shell from reading the full file later - it only reads the stream up // to the number of bytes specified here. Which means we would end up with a truncated // text file (binary files are still ok though). files->fgd[index].nFileSizeLow = 0; files->fgd[index].nFileSizeHigh = 0; ++index; } GlobalUnlock(data); pmedium->hGlobal = data; pmedium->tymed = TYMED_HGLOBAL; return S_OK; } // handling CF_PREFERREDDROPEFFECT is necessary to tell the shell that it should *not* ask for the // CF_FILEDESCRIPTOR until the drop actually occurs. If we don't handle CF_PREFERREDDROPEFFECT, the shell // will ask for the file descriptor for every object (file/folder) the mouse pointer hovers over and is // a potential drop target. else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->cfFormat == CF_PREFERREDDROPEFFECT)) { HGLOBAL data = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, sizeof(DWORD)); DWORD* effect = (DWORD*)GlobalLock(data); (*effect) = DROPEFFECT_COPY; GlobalUnlock(data); pmedium->hGlobal = data; pmedium->tymed = TYMED_HGLOBAL; return S_OK; } else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_TEXT)) { // caller wants text // create the string from the path list CString text; if (!m_gitPaths.IsEmpty()) { // create a single string where the URLs are separated by newlines for (int i = 0; i < m_gitPaths.GetCount(); ++i) { text += m_gitPaths[i].GetWinPathString(); text += L"\r\n"; } } CStringA texta = CUnicodeUtils::GetUTF8(text); pmedium->tymed = TYMED_HGLOBAL; pmedium->hGlobal = GlobalAlloc(GHND, (texta.GetLength() + 1) * sizeof(char)); if (pmedium->hGlobal) { char* pMem = (char*)GlobalLock(pmedium->hGlobal); strcpy_s(pMem, texta.GetLength() + 1, (LPCSTR)texta); GlobalUnlock(pmedium->hGlobal); } pmedium->pUnkForRelease = nullptr; return S_OK; } else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && ((pformatetcIn->cfFormat == CF_UNICODETEXT) || (pformatetcIn->cfFormat == CF_INETURL) || (pformatetcIn->cfFormat == CF_SHELLURL))) { // caller wants Unicode text // create the string from the path list CString text; if (!m_gitPaths.IsEmpty()) { // create a single string where the URLs are separated by newlines for (int i = 0; i < m_gitPaths.GetCount(); ++i) { if (pformatetcIn->cfFormat == CF_UNICODETEXT) text += m_gitPaths[i].GetWinPathString(); else text += g_Git.CombinePath(m_gitPaths[i]); text += L"\r\n"; } } pmedium->tymed = TYMED_HGLOBAL; pmedium->hGlobal = GlobalAlloc(GHND, (text.GetLength() + 1) * sizeof(TCHAR)); if (pmedium->hGlobal) { TCHAR* pMem = (TCHAR*)GlobalLock(pmedium->hGlobal); wcscpy_s(pMem, text.GetLength() + 1, (LPCTSTR)text); GlobalUnlock(pmedium->hGlobal); } pmedium->pUnkForRelease = nullptr; return S_OK; } else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_HDROP)) { int nLength = 0; for (int i = 0; i < m_gitPaths.GetCount(); ++i) { if (m_gitPaths[i].m_Action & (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED) || m_gitPaths[i].IsDirectory()) continue; nLength += g_Git.CombinePath(m_gitPaths[i]).GetLength(); nLength += 1; // '\0' separator } int nBufferSize = sizeof(DROPFILES) + (nLength + 1) * sizeof(TCHAR); auto pBuffer = std::make_unique<char[]>(nBufferSize); SecureZeroMemory(pBuffer.get(), nBufferSize); DROPFILES* df = (DROPFILES*)pBuffer.get(); df->pFiles = sizeof(DROPFILES); df->fWide = 1; TCHAR* pFilenames = (TCHAR*)(pBuffer.get() + sizeof(DROPFILES)); TCHAR* pCurrentFilename = pFilenames; for (int i = 0; i < m_gitPaths.GetCount(); ++i) { if (m_gitPaths[i].m_Action & (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED) || m_gitPaths[i].IsDirectory()) continue; CString str = g_Git.CombinePath(m_gitPaths[i]); wcscpy_s(pCurrentFilename, str.GetLength() + 1, (LPCWSTR)str); pCurrentFilename += str.GetLength(); *pCurrentFilename = '\0'; // separator between file names pCurrentFilename++; } *pCurrentFilename = '\0'; // terminate array pmedium->tymed = TYMED_HGLOBAL; pmedium->hGlobal = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE | GMEM_DDESHARE, nBufferSize); if (pmedium->hGlobal) { LPVOID pMem = ::GlobalLock(pmedium->hGlobal); if (pMem) memcpy(pMem, pBuffer.get(), nBufferSize); GlobalUnlock(pmedium->hGlobal); } pmedium->pUnkForRelease = nullptr; return S_OK; } else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_FILE_ATTRIBUTES_ARRAY)) { int nBufferSize = sizeof(FILE_ATTRIBUTES_ARRAY) + m_gitPaths.GetCount() * sizeof(DWORD); auto pBuffer = std::make_unique<char[]>(nBufferSize); SecureZeroMemory(pBuffer.get(), nBufferSize); FILE_ATTRIBUTES_ARRAY* cf = (FILE_ATTRIBUTES_ARRAY*)pBuffer.get(); cf->cItems = m_gitPaths.GetCount(); cf->dwProductFileAttributes = DWORD_MAX; cf->dwSumFileAttributes = 0; for (int i = 0; i < m_gitPaths.GetCount(); ++i) { DWORD fileattribs = FILE_ATTRIBUTE_NORMAL; cf->rgdwFileAttributes[i] = fileattribs; cf->dwProductFileAttributes &= fileattribs; cf->dwSumFileAttributes |= fileattribs; } pmedium->tymed = TYMED_HGLOBAL; pmedium->hGlobal = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE | GMEM_DDESHARE, nBufferSize); if (pmedium->hGlobal) { LPVOID pMem = ::GlobalLock(pmedium->hGlobal); if (pMem) memcpy(pMem, pBuffer.get(), nBufferSize); GlobalUnlock(pmedium->hGlobal); } pmedium->pUnkForRelease = nullptr; return S_OK; } for (size_t i = 0; i < m_vecFormatEtc.size(); ++i) { if ((pformatetcIn->tymed == m_vecFormatEtc[i]->tymed) && (pformatetcIn->dwAspect == m_vecFormatEtc[i]->dwAspect) && (pformatetcIn->cfFormat == m_vecFormatEtc[i]->cfFormat)) { CopyMedium(pmedium, m_vecStgMedium[i], m_vecFormatEtc[i]); return S_OK; } } return DV_E_FORMATETC; }
bool CStrUtil::DecodeBase64(LPCTSTR source,BYTE *buf,int &buflen) { CStringA strA; strA = CT2A(source); return Base64Decode(strA,strA.GetLength(),buf,&buflen) == TRUE; //just for warning C4800. }
int main(int argc, const char* argv[]) { // 分析命令行选项 CmdArgParser cmdParser("", TCtoC_str(CStrFormat(_T("服务版本: %d.%d.%d"), g_majorVer, g_minorVer, g_thirdVer))); CStringA sip; VERIFY(cmdParser.AddStr( sip, "-ip", "", "IP", "服务的TCP监听IP,默认监听本机所有IP" )); int tcpPort = g_serveIPP.port_; VERIFY(cmdParser.AddInt( tcpPort, "-p", 1, GET_INT_MAX_VALUE(WORD), tcpPort, "port", "服务的TCP监听端口" )); if(!cmdParser.RunParse(argc, argv)) return -1; if(!sip.IsEmpty()) { if(!IsValidIP((const char*)sip, &g_serveIPP.ip_)) { NPLogError((_T("非法ip参数: %s"), (LPCTSTR)CtoTC_str((const char*)sip))); return -1; } } g_serveIPP.port_ = tcpPort; //用户定义_S CPCC_Startup pcc; int rt_st = pcc.Startup(); if(rt_st < 0) { return rt_st; } // //用户定义_E // 设置基本系统参数 #if defined(WIN32) SetCurrentDirectory(GetExeDir()); #endif tcps_SetLogPrint(LogPrint__, NULL); // 构造rpc服务对象 // 可在构造PCC_CenterSessionMaker时传递一 void* 参数给会话对象 // 如:PCC_CenterSessionMaker sessionMaker(param); // 在会话对象中可使用this->m_sessionMaker.m_userParameter获得 PCC_CenterSessionMaker sessionMaker; iscm_IRPCServeMan* rpcMan = NULL; TCPSError err = iscm_MakeRPCServeMan(rpcMan, g_serveIPP.port_, g_serveIPP.ip_, &sessionMaker, TCPS_MAX_TOTAL_SESSIONS/2); if(TCPS_OK == err) { // 运行主循环 NPLogInfo(("Running serve...")); struct TCheck { static BOOL RunCheck(void* /*param*/) { return !g_exitFlag; } }; #if defined(WIN32) typedef HWND (WINAPI* FNGetConsoleWindow)(); FNGetConsoleWindow fnGetConsoleWindow = (FNGetConsoleWindow)GetProcAddress(GetModuleHandle(_T("kernel32.dll")), "GetConsoleWindow"); HWND wnd; if(fnGetConsoleWindow && NULL!=(wnd=fnGetConsoleWindow())) { char ch[1024]; int l = GetWindowTextA(wnd, ch, sizeof(ch)-16); char ippStr[32]; GetIPPortTxt(g_serveIPP, ippStr); sprintf(ch+l, " - %s", ippStr); SetWindowTextA(wnd, ch); } #endif RunMainLoop(TCheck::RunCheck, NULL); g_exitFlag = true; NPLogInfo(("Exiting serve...")); } else { NPLogError(("iscm_MakeRPCServeMan(%d) failed, %s(%d)", tcpPort, tcps_GetErrTxt(err), err)); } // 析构rpc服务对象 if(rpcMan) rpcMan->DeleteThis(); //#if defined(_NP_IS_X86) || defined(_NP_IS_X64) // NPCRT_API_SetPerformancePolicy(false, true); //#endif // 销毁tcps/iscm库中所有的全局对象(拥有线程的) tcps_DestroyAllGlobalObjects(); return 0; }