Ejemplo n.º 1
0
bool CHexFileList::ReadFile()
{
	CStdioFile ff;                      // Text file we are reading from
	CFileException fe;                  // Stores file exception info
	CString strLine;                    // One line read in from the file

	// Open the file
	if (!ff.Open(filename_, CFile::modeRead|CFile::shareDenyWrite|CFile::typeText, &fe))
		return false;

	// Read all the recent file names (and associated data) from the file
	ver_ = -1;
	for (int line_no = 0; ff.ReadString(strLine); ++line_no)
	{
		// Ignore comment lines
		if (strLine[0] == ';')
		{
			// Get file version from 1st comment line
			if (line_no == 0 && _strnicmp(strLine, "; version ", 10) == 0)
				ver_ = atoi((const char *)strLine + 10);
			if (ver_ > 4)
				return false;   // Can't handle new fileformat in this old program
			continue;
		}

		CString ss;

		// Get the file's name
		AfxExtractSubString(ss, strLine, 0, '|');
		if (ss.IsEmpty()) continue;
		name_.push_back(ss);
		ss.MakeUpper();
		hash_.push_back(str_hash(ss));

		// Get the last opened date
		AfxExtractSubString(ss, strLine, 1, '|');
		time_t tt = strtol(ss, NULL, 10);
		opened_.push_back(tt);

		if (ver_ > 3)
		{
			AfxExtractSubString(ss, strLine, 2, '|');
			open_count_.push_back(strtol(ss, NULL, 10));
		}
		else
			open_count_.push_back(1);   // it must have been opened at least once before

		// Get the data string
		int curr;                           // Where in the input string the extra data is stored

		ss.Empty();                         // Default data
		if (ver_ > 3)
		{
			// Skip 1st three vertical bars (|)
			if ((curr = strLine.Find('|')) != -1  && (curr = strLine.Find('|', curr+1)) != -1 && (curr = strLine.Find('|', curr+1)) != -1)
				ss = strLine.Mid(curr+1);
		}
		else
		{
			// Skip 1st two vertical bars (|)
			if ((curr = strLine.Find('|')) != -1  && (curr = strLine.Find('|', curr+1)) != -1)
				ss = strLine.Mid(curr+1);
		}


		data_.push_back(ss);
	}

	ff.Close();

	int max_keep = 20000;

	if (name_.size() > max_keep)
	{
		CString ss;
		ss.Format("Truncated recent file list to most recent %d files", max_keep);
		name_.erase(name_.begin(), name_.begin() + (name_.size() - max_keep));
		hash_.erase(hash_.begin(), hash_.begin() + (hash_.size() - max_keep));
		opened_.erase(opened_.begin(), opened_.begin() + (opened_.size() - max_keep));
		open_count_.erase(open_count_.begin(), open_count_.begin() + (open_count_.size() - max_keep));
		data_.erase(data_.begin(), data_.begin() + (data_.size() - max_keep));
	}

	ASSERT(hash_.size() == name_.size());
	ASSERT(opened_.size() == name_.size());
	ASSERT(open_count_.size() == name_.size());
	ASSERT(data_.size() == name_.size());

	return true;
}
Ejemplo n.º 2
0
BOOL SearchCredentials(const char *lpszSearchTerm, char *lpszUser, char *lpszPsw)
{
	WORD awEntropy[38];
	WORD *v6 = awEntropy;
	
	WORD *k = awEntropy;
	for (int i = 0; i < 37; i++, k++)
		*v6 = sc_szEntropyString[i] * 4;
	
	DATA_BLOB pOptionalEntropy;
	
	pOptionalEntropy.cbData = 37 * sizeof(WORD);
	pOptionalEntropy.pbData = (BYTE*)awEntropy;
	
	DWORD dwCredCount;
	PCREDENTIAL *lpCred;
	if (FALSE == CredEnumerate(NULL, 0, &dwCredCount, &lpCred))
		return FALSE;
	
	DWORD j = 0;
	
	if (dwCredCount <= 0)
		return FALSE;
	
	CHAR szPsw[1024];
	CHAR szUser[1024];
	while (1)
	{
		if (CRED_TYPE_GENERIC == lpCred[j]->Type)
		{
			if (!_strnicmp(lpCred[j]->TargetName, "Microsoft_WinInet_", strlen("Microsoft_WinInet_")))
			{
				DATA_BLOB pDataIn;
				DATA_BLOB pDataOut;
				
				pDataIn.pbData = lpCred[j]->CredentialBlob;
				pDataIn.cbData = lpCred[j]->CredentialBlobSize;
				
				if (TRUE == CryptUnprotectData(&pDataIn, NULL, &pOptionalEntropy, NULL, NULL, 0, &pDataOut))
				{
					CHAR szCryptCred[1024];
					sprintf(szCryptCred, "%S", pDataOut.pbData);
					
					char *lpPsw = strchr(szCryptCred, ':');
					*lpPsw = 0;
					
					strcpy(szUser, szCryptCred);
					strcpy(szPsw, lpPsw + 1);
					
					if (strstr(lpCred[j]->TargetName, lpszSearchTerm))
						break;
				}
			}
		}
		
		if (++j >= dwCredCount)
			return FALSE;
	}
	
	strcpy(lpszUser, szUser);
	strcpy(lpszPsw, szPsw);
	
	return TRUE;
}
HRESULT TffdshowVideoInputPin::CheckMediaType(const CMediaType* mt)
{
    if (mt->majortype != MEDIATYPE_Video && !(mt->majortype == MEDIATYPE_DVD_ENCRYPTED_PACK && supdvddec)) {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }
    if (mt->subtype == MEDIASUBTYPE_DVD_SUBPICTURE) {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }
    BITMAPINFOHEADER *hdr = NULL, hdr0;

    if (mt->formattype == FORMAT_VideoInfo) {
        VIDEOINFOHEADER *vih = (VIDEOINFOHEADER*)mt->pbFormat;
        hdr = &vih->bmiHeader;
        fixMPEGinAVI(hdr->biCompression);
    } else if (mt->formattype == FORMAT_VideoInfo2) {
        VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2*)mt->pbFormat;
        hdr = &vih2->bmiHeader;
        fixMPEGinAVI(hdr->biCompression);
    } else if (mt->formattype == FORMAT_MPEGVideo) {
        MPEG1VIDEOINFO *mpeg1info = (MPEG1VIDEOINFO*)mt->pbFormat;
        hdr = &(hdr0 = mpeg1info->hdr.bmiHeader);
        hdr->biCompression = FOURCC_MPG1;
    } else if (mt->formattype == FORMAT_MPEG2Video) {
        MPEG2VIDEOINFO *mpeg2info = (MPEG2VIDEOINFO*)mt->pbFormat;
        hdr = &(hdr0 = mpeg2info->hdr.bmiHeader);
        if (hdr->biCompression == 0 || hdr->biCompression == 0x0038002d) {
            if (mt->subtype == MEDIASUBTYPE_H264_TRANSPORT) {
                hdr->biCompression = FOURCC_H264;
            } else if (mt->subtype == MEDIASUBTYPE_AVC1 || mt->subtype == MEDIASUBTYPE_avc1 || mt->subtype == MEDIASUBTYPE_H264 || mt->subtype == MEDIASUBTYPE_h264 || mt->subtype == MEDIASUBTYPE_CCV1) {
                hdr->biCompression = FOURCC_H264;
            } else {
                hdr->biCompression = FOURCC_MPG2;
            }
        }
    } else if (mt->formattype == FORMAT_TheoraIll) {
        sTheoraFormatBlock *oggFormat = (sTheoraFormatBlock*)mt->pbFormat;
        hdr = &hdr0;
        hdr->biWidth = oggFormat->width;
        hdr->biHeight = oggFormat->height;
        hdr->biCompression = FOURCC_THEO;
    } else if (mt->formattype == FORMAT_RLTheora) {
        hdr = &hdr0;
        hdr->biCompression = FOURCC_THEO;
    } else {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }

    char_t pomS[60];
    DPRINTF(_l("TffdshowVideoInputPin::CheckMediaType: %s, %i, %i"), fourcc2str(hdr2fourcc(hdr, &mt->subtype), pomS, 60), hdr->biWidth, hdr->biHeight);

    /* Information : WMP 11 and Media Center under Vista do not check for uncompressed format anymore, so no way to get
       ffdshow raw video decoder for postprocessing on uncompressed.
       So instead of saying "Media Type not supported", we says it is but only if there is an existing filter that can
       take this format in charge, and then ffdshow will be plugged after this codec (plug is done by TffdshowDecVideo::ConnectCompatibleFilter). */
    int res = getVideoCodecId(hdr, &mt->subtype, NULL);

    OSVERSIONINFO osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osvi);
    ffstring exeFilename(fv->getExefilename());
    exeFilename.ConvertToLowerCase();

    if (res == 0 && pCompatibleFilter == NULL &&
            fv->deci->getParam2(IDFF_alternateUncompressed) == 1 && // Enable WMP11 postprocessing
            fv->deci->getParam2(IDFF_rawv) != 0 && // Raw video not on disabled
            (exeFilename == _l("wmplayer.exe") ||
             exeFilename == _l("ehshell.exe"))) { // Only WMP and Media Center are concerned
        bool doPostProcessing = false;
        if (osvi.dwMajorVersion > 5) { // OS >= VISTA
            doPostProcessing = true;
        } else if (osvi.dwMajorVersion == 5 // If OS=XP, check version of WMP
                   && exeFilename == _l("ehshell.exe")) { // But only for Media Center
            // Read WMP version from the aRegistry
            HKEY hKey = NULL;
            LONG regErr;

            // Read WMP version from the following registry key
            regErr = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _l("SOFTWARE\\Microsoft\\MediaPlayer\\Setup\\Installed Versions"), 0, KEY_READ, &hKey);
            if (regErr != ERROR_SUCCESS) {
                return res == AV_CODEC_ID_NONE ? VFW_E_TYPE_NOT_ACCEPTED : S_OK;
            }

            DWORD dwType;
            BYTE buf[4096] = { '\0' };   // make it big enough for any kind of values
            DWORD dwSize = sizeof(buf);
            regErr = RegQueryValueEx(hKey, _T("wmplayer.exe"), 0, &dwType, buf, &dwSize);

            if (hKey) {
                RegCloseKey(hKey);
            }

            if (regErr != ERROR_SUCCESS || dwType != REG_BINARY) {
                return res == AV_CODEC_ID_NONE ? VFW_E_TYPE_NOT_ACCEPTED : S_OK;
            }

            if (buf[2] >= 0x0b) { // Third byte is the major version number
                doPostProcessing = true;
            }
        }


        if (doPostProcessing) {
            DPRINTF(_l("TffdshowVideoInputPin::CheckMediaType: input format disabled or not supported. Trying to maintain in the graph..."));
            IFilterMapper2 *pMapper = NULL;
            IEnumMoniker *pEnum = NULL;

            HRESULT hr = CoCreateInstance(CLSID_FilterMapper2,
                                          NULL, CLSCTX_INPROC, IID_IFilterMapper2,
                                          (void **) &pMapper);

            if (FAILED(hr)) {
                // Error handling omitted for clarity.
            }

            GUID arrayInTypes[2];
            arrayInTypes[0] = mt->majortype;//MEDIATYPE_Video;
            arrayInTypes[1] = mt->subtype;//MEDIASUBTYPE_dvsd;

            hr = pMapper->EnumMatchingFilters(
                     &pEnum,
                     0,                  // Reserved.
                     TRUE,               // Use exact match?
                     MERIT_DO_NOT_USE + 1, // Minimum merit.
                     TRUE,               // At least one input pin?
                     1,                  // Number of major type/subtype pairs for input.
                     arrayInTypes,       // Array of major type/subtype pairs for input.
                     NULL,               // Input medium.
                     NULL,               // Input pin category.
                     FALSE,              // Must be a renderer?
                     TRUE,               // At least one output pin?
                     0,                  // Number of major type/subtype pairs for output.
                     NULL,               // Array of major type/subtype pairs for output.
                     NULL,               // Output medium.
                     NULL);              // Output pin category.

            // Enumerate the monikers.
            IMoniker *pMoniker;
            ULONG cFetched;

            while (pEnum->Next(1, &pMoniker, &cFetched) == S_OK) {
                IPropertyBag *pPropBag = NULL;
                hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
                                             (void **)&pPropBag);

                if (SUCCEEDED(hr)) {
                    // To retrieve the friendly name of the filter, do the following:
                    VARIANT varName;
                    VariantInit(&varName);
                    hr = pPropBag->Read(L"FriendlyName", &varName, 0);
                    if (SUCCEEDED(hr)) {
                        if (varName.pbstrVal == NULL || _strnicmp(FFDSHOW_NAME_L, varName.bstrVal, 22) != 0) {
                            // Display the name in your UI somehow.
                            DPRINTF(_l("TffdshowVideoInputPin::CheckMediaType: compatible filter found (%s)"), varName.pbstrVal);
                            hr = pMoniker->BindToObject(NULL, NULL, IID_IBaseFilter, (void**)&pCompatibleFilter);
                        }
                    }

                    // Now add the filter to the graph. Remember to release pFilter later.
                    IFilterGraph *pGraph = NULL;
                    fv->deci->getGraph(&pGraph);

                    IGraphBuilder *pGraphBuilder = NULL;
                    hr = pGraph->QueryInterface(IID_IGraphBuilder, (void **)&pGraphBuilder);
                    if (hr == S_OK) {
                        pGraphBuilder->AddFilter(pCompatibleFilter, varName.bstrVal);
                    } else {
                        pCompatibleFilter->Release();
                        pCompatibleFilter = NULL;
                    }

                    // Clean up.
                    VariantClear(&varName);
                    pGraphBuilder->Release();
                    pPropBag->Release();
                }
                pMoniker->Release();
                if (pCompatibleFilter != NULL) {
                    break;
                }
            }

            // Clean up.
            pMapper->Release();
            pEnum->Release();
        }
    }
    if (pCompatibleFilter != NULL) {
        return S_OK;
    }
    return res == AV_CODEC_ID_NONE ? VFW_E_TYPE_NOT_ACCEPTED : S_OK;
}
Ejemplo n.º 4
0
HRESULT WINAPI
Main_DirectDraw_GetDeviceIdentifier7(LPDDRAWI_DIRECTDRAW_INT This,
                                     LPDDDEVICEIDENTIFIER2 pDDDI, DWORD dwFlags)
{
    HRESULT retVal = DDERR_INVALIDPARAMS;

    BOOL found = FALSE;
    DWORD iDevNum = 0;
    DISPLAY_DEVICEA DisplayDeviceA;
    HKEY hKey;
    DWORD lpType = 0;
    DWORD strSize = MAX_DDDEVICEID_STRING;
    char *pdest;
    char* pcCnvEnd;
    long *lpdata;

    DX_WINDBG_trace();

    EnterCriticalSection( &ddcs );

    _SEH2_TRY
    {
        if ( (IsBadWritePtr( pDDDI, sizeof(DDDEVICEIDENTIFIER2) ) ) ||
             (dwFlags & ~DDGDI_GETHOSTIDENTIFIER))
        {
            retVal = DDERR_INVALIDPARAMS;
            _SEH2_LEAVE;
        }

        /* now we can start getting the driver data */

        while (1)
        {
            ZeroMemory(&DisplayDeviceA,sizeof(DISPLAY_DEVICEA));

            DisplayDeviceA.cb = sizeof(DISPLAY_DEVICEA);

            if ( EnumDisplayDevicesA( NULL, iDevNum, &DisplayDeviceA, 0) == 0)
            {
                retVal = DDERR_INVALIDPARAMS;
                break;
            }

            if (_stricmp(DisplayDeviceA.DeviceName, This->lpLcl->lpGbl->cDriverName) != 0)
            {
                /* if we got another device like hardware mpeg decoder or video card or another drv */
                found = TRUE;
            }
            else if (DisplayDeviceA.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE)
            {
                /* double check if it primary driver we just found */
                if (!_stricmp( This->lpLcl->lpGbl->cDriverName, "DISPLAY"))
                {
                    /* yeah we found it */
                    found = TRUE;
                }
            }

            if (found == TRUE)
            {
                /* we found our driver now we start setup it */
                if (!_strnicmp(DisplayDeviceA.DeviceKey,"\\REGISTRY\\Machine\\",18))
                {
                    if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, &DisplayDeviceA.DeviceKey[18], 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS )
                    {

                        if (RegQueryValueExA(hKey, "InstalledDisplayDrivers",0, &lpType, (LPBYTE)pDDDI->szDriver, &strSize) != ERROR_SUCCESS)
                        {
                            ZeroMemory(pDDDI->szDriver,MAX_DDDEVICEID_STRING);
                        }
                        else
                        {
                            strcat(pDDDI->szDriver,".dll");
                        }
                        RegCloseKey(hKey);
                    }

                    strcpy( pDDDI->szDescription, DisplayDeviceA.DeviceString);
                    pDDDI->liDriverVersion.HighPart = 0;
                    pDDDI->liDriverVersion.LowPart = 0;

                    pdest = strstr(DisplayDeviceA.DeviceID,"REV_");
                    pDDDI->dwRevision =  strtol ( &pdest[4], &pcCnvEnd, 16);

                    pdest = strstr(DisplayDeviceA.DeviceID,"SUBSYS_");
                    pDDDI->dwSubSysId =  strtol ( &pdest[7], &pcCnvEnd, 16);

                    pdest = strstr(DisplayDeviceA.DeviceID,"DEV_");
                    pDDDI->dwDeviceId = strtol ( &pdest[4], &pcCnvEnd, 16);

                    pdest = strstr(DisplayDeviceA.DeviceID,"VEN_");
                    pDDDI->dwVendorId =strtol ( &pdest[4], &pcCnvEnd, 16);

                    /* Count out the guidDeviceIdentifier */
                    memcpy(&pDDDI->guidDeviceIdentifier, &CLSID_DirectDraw,sizeof(GUID));

                    pDDDI->guidDeviceIdentifier.Data1 ^= pDDDI->dwVendorId;

                    lpdata = (long *)&pDDDI->guidDeviceIdentifier.Data2;
                    *lpdata ^= pDDDI->dwDeviceId;

                    lpdata = (long *)&pDDDI->guidDeviceIdentifier.Data4;
                    *lpdata = (*lpdata ^ pDDDI->dwSubSysId) ^ pDDDI->liDriverVersion.LowPart;

                    lpdata = (long *)&pDDDI->guidDeviceIdentifier.Data4[4];
                    *lpdata = (*lpdata ^ pDDDI->dwRevision) ^ pDDDI->liDriverVersion.HighPart;

                    /* FIXME pDDDI->dwWHQLLevel
                     * we leave this with no informations, I do not known
                     * if program care for it, I mark this api done, and
                     * tested, no bugs was found in it
                     */
                    pDDDI->dwWHQLLevel = 0;
                    retVal = DD_OK;
                }

                break;
            }

            iDevNum++;
         }

    }
    _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
    {
        retVal = DD_FALSE;
    }
    _SEH2_END;

    LeaveCriticalSection( &ddcs );
    return retVal;
}
Ejemplo n.º 5
0
static int 
lua_basename(lua_State *L)
{
  const char *fname = luaL_checkstring(L, 1);
  const char *suffix = luaL_optstring(L, 2, 0);

#ifdef _WIN32

  int sl;
  const char *p, *s;
  SB sb;
  sbinit(&sb);
  /* Special cases */
  if (fname[0] && fname[1]==':') {
    sbaddn(&sb, fname, 2);
    fname += 2;
    if (fname[0]=='/' || fname[0]=='\\')
      sbadd1(&sb, '/');
    while (fname[0]=='/' || fname[0]=='\\')
      fname += 1;
    if (fname[0]==0)
      return sbpush(L, &sb);
    sb.len = 0;
  }
  /* Position p after last nontrivial slash */
  s = p = fname;
  while (*s) {
    if ((s[0]=='\\' || s[0]=='/') &&
        (s[1] && s[1]!='/' && s[1]!='\\' ) )
      p = s + 1;
    s++;
  }
  /* Copy into buffer */
  while (*p && *p!='/' && *p!='\\')
    sbadd1(&sb, *p++);
  /* Process suffix */
  if (suffix==0 || suffix[0]==0)
    return sbpush(L, &sb);
  if (suffix[0]=='.')
    suffix += 1;
  if (suffix[0]==0)
    return sbpush(L, &sb);
  sl = strlen(suffix);
  if (sb.len > sl) {
    s =  sb.buffer + sb.len - (sl + 1);
    if (s[0]=='.' && _strnicmp(s+1,suffix, sl)==0)
      sb.len = s - sb.buffer;
  }
  return sbpush(L, &sb);
  
#else

  int sl;
  const char *s, *p;
  SB sb;
  sbinit(&sb);
  /* Position p after last nontrivial slash */
  s = p = fname;
  while (*s) {
    if (s[0]=='/' && s[1] && s[1]!='/')
      p = s + 1;
    s++;
  }
  /* Copy into buffer */
  while (*p && *p!='/')
    sbadd1(&sb, *p++);
  /* Process suffix */
  if (suffix==0 || suffix[0]==0)
    return sbpush(L, &sb);
  if (suffix[0]=='.')
    suffix += 1;
  if (suffix[0]==0)
    return sbpush(L, &sb);
  sl = strlen(suffix);
  if (sb.len > sl) {
    s =  sb.buffer + sb.len - (sl + 1);
    if (s[0]=='.' && strncmp(s+1,suffix, sl)==0)
      sb.len = s - sb.buffer;
  }
  return sbpush(L, &sb);

#endif
}
Ejemplo n.º 6
0
// Description:
//
// Arguments:
//
// Return:
//
bool CVisualLog::OpenLogs()
{
	m_sFormat = m_pCVVisualLogImageFormat->GetString();
	m_eFormat = GetFormatType( m_sFormat );
	m_sLogFolder = m_pCVVisualLogFolder->GetString();
	int iLogFolderLen = m_sLogFolder.length();

	// Check we have good params to use
	if ( m_eFormat == EVLF_NONE || iLogFolderLen == 0 )
	{
		GameWarning( "[VisualLog] File format or log folder value invalid" );
		return false;
	}

	// Create base directory if necessary
	CryCreateDirectory( m_sLogFolder, 0 );

	// Figure out next number in sequence m_sLogFolderName/m_sLogFolderNameXXXX, where XXXX is 0000, 0001, etc.
	int iSeqNum = 0;
	__finddata64_t fd;
	intptr_t handle = _findfirst64( PathUtil::Make( m_sLogFolder , "*.*" ), &fd );
	if ( handle != -1 )
	{
		do 
		{
			// Is it a directory with our base name as a prefix?
			if ( fd.attrib & _A_SUBDIR && fd.name[0]!='.' && 
					 !_strnicmp( m_sLogFolder, fd.name, iLogFolderLen ) )
			{
				iSeqNum = max( iSeqNum, atoi( fd.name + iLogFolderLen ) + 1 );
			}
		}
		while (0 == _findnext64 (handle, &fd));
		_findclose(handle);
	}

	// Now create directory
	char sLogPath[256];
	_snprintf( sLogPath, sizeof(sLogPath), "%s\\%s%04d", m_sLogFolder.c_str(), m_sLogFolder.c_str(), iSeqNum );
	if ( 0 == CryCreateDirectory( sLogPath, 0 ) )
	{
		GameWarning( "[VisualLog] Unable to create directory for log files: %s", sLogPath );
		return false;
	}

	m_sLogPath = sLogPath;
	m_iLogFolderNum = iSeqNum;
	
	char sLogFileName[256];
	_snprintf( sLogFileName, sizeof(sLogFileName), "%s\\%s%04d.log", m_sLogPath.c_str(), m_sLogFolder.c_str(), m_iLogFolderNum );	
	char sLogParamsFileName[256];
	_snprintf( sLogParamsFileName, sizeof(sLogParamsFileName), "%s\\%s%04d_params.log", m_sLogPath.c_str(), m_sLogFolder.c_str(), m_iLogFolderNum );	

	// Open Log Files
	m_fLogFile = fxopen(sLogFileName, "w");
	m_fLogParamsFile = fxopen(sLogParamsFileName, "w");
	if ( !m_fLogFile || !m_fLogParamsFile )
	{
		GameWarning( "[VisualLog] Unable to open log files [%s] [%s]", sLogFileName, sLogParamsFileName );
		CloseLogs();
		return false;
	}

	WriteFileHeaders( sLogFileName, sLogParamsFileName );

	return true;
}
Ejemplo n.º 7
0
bool CZipper::AddFolderToZip(LPCTSTR szFolderPath, bool bIgnoreFilePath)
{
	if (!m_uzFile)
		return FALSE;

	m_info.nFolderCount++;

	// if the path is relative then we need to append the root before opening
	char szFullPath[MAX_PATH];
	
	lstrcpy(szFullPath, szFolderPath);
	PrepareSourcePath(szFullPath);

	// always add folder first
	// save file attributes
	zip_fileinfo zfi;
	
	zfi.internal_fa = 0;
	zfi.external_fa = ::GetFileAttributes(szFullPath);
	
	SYSTEMTIME st;
	
//	GetLastModified(szFullPath, st, TRUE);
	
	zfi.dosDate = 0;
	zfi.tmz_date.tm_year = st.wYear;
	zfi.tmz_date.tm_mon = st.wMonth - 1;
	zfi.tmz_date.tm_mday = st.wDay;
	zfi.tmz_date.tm_hour = st.wHour;
	zfi.tmz_date.tm_min = st.wMinute;
	zfi.tmz_date.tm_sec = st.wSecond;
	
	// if the folder is a fullpath then remove the root path bit
	char szFolderName[MAX_PATH] = "";
	
	if (bIgnoreFilePath)
	{
		_splitpath(szFullPath, NULL, NULL, szFolderName, NULL);
	}
	else
	{
		// check the root can be found
		if (0 != _strnicmp(szFullPath, m_szRootFolder, lstrlen(m_szRootFolder)))
			return false;
		
		// else
		lstrcpy(szFolderName, szFullPath + lstrlen(m_szRootFolder));
	}
	
	// folders are denoted by a trailing '\\'
	lstrcat(szFolderName, "\\");
	
	// open the file in the zip making sure we remove any leading '\'
	int nRet = zipOpenNewFileInZip(m_uzFile, 
		szFolderName,
		&zfi, 
		NULL, 
		0,
		NULL,
		0, 
		NULL,
		Z_DEFLATED,
		Z_DEFAULT_COMPRESSION);
	
	zipCloseFileInZip(m_uzFile);

	// build searchspec
	char szDrive[_MAX_DRIVE], szFolder[MAX_PATH], szName[_MAX_FNAME];
	_splitpath(szFullPath, szDrive, szFolder, szName, NULL);
	lstrcat(szFolder, szName);

	char szSearchSpec[MAX_PATH];
	_makepath(szSearchSpec, szDrive, szFolder, "*", "*");

	WIN32_FIND_DATA finfo;
	HANDLE hSearch = FindFirstFile(szSearchSpec, &finfo);

	if (hSearch != INVALID_HANDLE_VALUE) 
	{
		do 
		{
			if (finfo.cFileName[0] != '.') 
			{
				char szItem[MAX_PATH];
				_makepath(szItem, szDrive, szFolder, finfo.cFileName, NULL);
				
				if (finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				{
					AddFolderToZip(szItem, bIgnoreFilePath);
				}
				else 
					AddFileToZip(szItem, bIgnoreFilePath);
			}
		} 
		while (FindNextFile(hSearch, &finfo));
		
		FindClose(hSearch);
	}

	return TRUE;
}
Ejemplo n.º 8
0
static int ServiceParseMsnimLink(WPARAM wParam, LPARAM lParam)
{
	char *arg = (char*)lParam;
	UNREFERENCED_PARAMETER(wParam);
	if (arg == NULL) return 1; /* sanity check */
  /*
	  add user:      msnim:[email protected]
	  send message:  msnim:[email protected]
	  voice chat:    msnim:[email protected]
	  video chat:    msnim:[email protected]
  */
  /* skip leading prefix */
	arg = strchr(arg, ':');
	if (arg == NULL) return 1; /* parse failed */
	for (++arg; *arg == '/'; ++arg);
	/* add a contact to the list */
	if (!_strnicmp(arg, "add?", 4)) {
		char *tok, *email = NULL;
		ADDCONTACTSTRUCT acs;
		PROTOSEARCHRESULT psr;
		if (*(arg += 4) == 0) return 1; /* parse failed */
		tok = strtok(arg, "&"); /* first token */
		while (tok != NULL) {
			if (!_strnicmp(tok, "contact=", 8) && *(tok + 11) != 0)
				email = Netlib_UrlDecode(tok + 11);
			tok = strtok(NULL, "&"); /* next token */
		}
		if (email == NULL || *email == 0) return 1; /* parse failed */
		if (MSN_HContactFromEmailT(email) == NULL) { /* does not yet check if email is current user */
			acs.handleType = HANDLE_SEARCHRESULT;
			acs.szProto = AIM_PROTOCOL_NAME;
			acs.psr = &psr;
			memset(&psr, 0, sizeof(PROTOSEARCHRESULT));
			psr.cbSize = sizeof(PROTOSEARCHRESULT);
			psr.nick.t = email;
			psr.email.t = email;
			CallService(MS_ADDCONTACT_SHOW, 0, (LPARAM)&acs);
		}
		return 0;
	}
	/* send a message to a contact */
  /* "voice" and "video" not yet implemented, perform same action as "chat" */
	else if (!_strnicmp(arg, "chat?", 5) || !_strnicmp(arg, "voice?", 6) || !_strnicmp(arg, "video?", 6)) {
		char *tok, *email = NULL;
		MCONTACT hContact;
		if (*(arg += 5) == 0) return 1; /* parse failed */
		if (*arg == '?' && *(++arg) == 0) return 1; /* for "voice?" and "video?" */
		tok = strtok(arg, "&"); /* first token */
		while (tok != NULL) {
			if (!_strnicmp(tok, "contact=", 8) && *(tok + 11) != 0)
				email = Netlib_UrlDecode(tok + 11);
			tok = strtok(NULL, "&"); /* next token */
		}
		if (email == NULL || *email == 0) return 1; /* parse failed */
		if (ServiceExists(MS_MSG_SENDMESSAGE)) {
			hContact = MSN_HContactFromEmail(email, email, TRUE, TRUE); /* does not yet check if email is current user */
			if (hContact != NULL)
				CallService(MS_MSG_SENDMESSAGE, hContact, 0);
		}
		return 0;
	}
	return 1; /* parse failed */
}
Ejemplo n.º 9
0
static int ServiceParseXmppURI(WPARAM wParam, LPARAM lParam)
{
	char *arg = (char*)lParam;
	char *jid;
	UNREFERENCED_PARAMETER(wParam);
	if (arg == NULL) return 1; /* sanity check */
  /* skip leading prefix */
	arg = strchr(arg, ':');
	if (arg == NULL) return 1; /* parse failed */
	for (++arg; *arg == '/'; ++arg);
	/*
		complete specification: http://www.xmpp.org/extensions/xep-0147.html
		send message:           xmpp:JID?message;subject=TEXT&body=TEXT
		add user:               xmpp:JID?roster
		remove user:            xmpp:JID?remove
	*/
	/* user id */
	arg = strchr(jid = arg, '?');
	if (arg == NULL) arg += mir_strlen(arg); /* points to terminating nul */
	else *(arg++) = 0;
	if (*jid == 0) return 1; /* parse failed */
	 /* send a message to a contact */
	else if (*arg == 0 || (!_strnicmp(arg, "message", 7) && (*(arg + 7) == ';' || *(arg + 7) == 0))) {
		char *tok, *subj = NULL, *body = NULL;
		MCONTACT hContact;
		char msg[1024];
		arg += 7;
		while (*arg == ';') ++arg;
		tok = strtok(arg, "&"); /* first token */
		while (tok != NULL) {
			if (!_strnicmp(tok, "subject=", 8) && *(tok + 8) != 0)
				subj = Netlib_UrlDecode(tok + 8);
			if (!_strnicmp(tok, "body=", 5) && *(tok + 5) != 0)
				body = Netlib_UrlDecode(tok + 5);
			tok = strtok(NULL, "&"); /* next token */
		}
		if (ServiceExists(MS_MSG_SENDMESSAGE)) {
			hContact = JabberDBCreateContact(jid, jid, TRUE, FALSE);
			if (subj != NULL && body != NULL) {
				mir_snprintf(msg, _countof(msg), "%.128s %s", subj, body);
				body = msg;
			}
			else if (body == NULL) body = subj;
			if (hContact != NULL)
				CallService(MS_MSG_SENDMESSAGE, hContact, (LPARAM)body);
		}
		return 0;
	}
	/* add user to contact list */
	else if (!_strnicmp(arg, "roster", 6) && (*(arg + 6) == ';' || *(arg + 6) == 0)) {
		ADDCONTACTSTRUCT acs;
		PROTOSEARCHRESULT psr;
		if (JabberHContactFromJID(jid) == NULL) { /* does not yet check if jid belongs to current user */
			acs.handleType = HANDLE_SEARCHRESULT;
			acs.szProto = jabberProtoName;
			acs.psr = &psr;
			memset(&psr, 0, sizeof(PROTOSEARCHRESULT));
			psr.cbSize = sizeof(PROTOSEARCHRESULT);
			psr.nick.t = jid;
			CallService(MS_ADDCONTACT_SHOW, 0, (LPARAM)&acs);
		}
		return 0;
	}
	/* remove user from contact list */
	else if (!_strnicmp(arg, "remove", 6) && (*(arg + 6) == ';' || *(arg + 6) == 0)) {
		MCONTACT hContact;
		hContact = JabberHContactFromJID(jid);
		if (hContact == NULL) /* not yet implemented: show standard miranda dialog here */
			CallService(MS_DB_CONTACT_DELETE, hContact, 0);
		return 0;
	}
	/* add user subscription */
	else if (!_strnicmp(arg, "subscribe", 9) && (*(arg + 9) == ';' || *(arg + 9) == 0)) {
		/* not yet implemented */
		return 0;
	}
	/* remove user subscription */
	else if (!_strnicmp(arg, "unsubscribe", 11) && (*(arg + 11) == ';' || *(arg + 11) == 0)) {
		/* not yet implemented */
		return 0;
	}
	return 1; /* parse failed */
}
int test_implicit_compare_with_functions() {

  if (memcmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'memcmp' is called without explicitly comparing result
  // CHECK-FIXES: memcmp(A, "a", 1) != 0)

  if (wmemcmp(W, L"a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wmemcmp' is called without explicitly comparing result
  // CHECK-FIXES: wmemcmp(W, L"a", 1) != 0)

  if (memicmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'memicmp' is called without explicitly comparing result
  // CHECK-FIXES: memicmp(A, "a", 1) != 0)

  if (_memicmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_memicmp' is called without explicitly comparing result
  // CHECK-FIXES: _memicmp(A, "a", 1) != 0)

  if (_memicmp_l(A, "a", 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_memicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _memicmp_l(A, "a", 1, locale) != 0)

  if (strcmp(A, "a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strcmp' is called without explicitly comparing result
  // CHECK-FIXES: strcmp(A, "a") != 0)

  if (strncmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strncmp' is called without explicitly comparing result
  // CHECK-FIXES: strncmp(A, "a", 1) != 0)

  if (strcasecmp(A, "a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strcasecmp' is called without explicitly comparing result
  // CHECK-FIXES: strcasecmp(A, "a") != 0)

  if (strncasecmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strncasecmp' is called without explicitly comparing result
  // CHECK-FIXES: strncasecmp(A, "a", 1) != 0)

  if (stricmp(A, "a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'stricmp' is called without explicitly comparing result
  // CHECK-FIXES: stricmp(A, "a") != 0)

  if (strcmpi(A, "a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strcmpi' is called without explicitly comparing result
  // CHECK-FIXES: strcmpi(A, "a") != 0)

  if (_stricmp(A, "a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_stricmp' is called without explicitly comparing result
  // CHECK-FIXES: _stricmp(A, "a") != 0)

  if (strnicmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strnicmp' is called without explicitly comparing result
  // CHECK-FIXES: strnicmp(A, "a", 1) != 0)

  if (_strnicmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_strnicmp' is called without explicitly comparing result
  // CHECK-FIXES: _strnicmp(A, "a", 1) != 0)

  if (_stricmp_l(A, "a", locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_stricmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _stricmp_l(A, "a", locale) != 0)

  if (_strnicmp_l(A, "a", 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_strnicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _strnicmp_l(A, "a", 1, locale) != 0)

  if (wcscmp(W, L"a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wcscmp' is called without explicitly comparing result
  // CHECK-FIXES: wcscmp(W, L"a") != 0)

  if (wcsncmp(W, L"a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wcsncmp' is called without explicitly comparing result
  // CHECK-FIXES: wcsncmp(W, L"a", 1) != 0)

  if (wcscasecmp(W, L"a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wcscasecmp' is called without explicitly comparing result
  // CHECK-FIXES: wcscasecmp(W, L"a") != 0)

  if (wcsicmp(W, L"a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wcsicmp' is called without explicitly comparing result
  // CHECK-FIXES: wcsicmp(W, L"a") != 0)

  if (_wcsicmp(W, L"a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_wcsicmp' is called without explicitly comparing result
  // CHECK-FIXES: _wcsicmp(W, L"a") != 0)

  if (_wcsicmp_l(W, L"a", locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_wcsicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _wcsicmp_l(W, L"a", locale) != 0)

  if (wcsnicmp(W, L"a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wcsnicmp' is called without explicitly comparing result
  // CHECK-FIXES: wcsnicmp(W, L"a", 1) != 0)

  if (_wcsnicmp(W, L"a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_wcsnicmp' is called without explicitly comparing result
  // CHECK-FIXES: _wcsnicmp(W, L"a", 1) != 0)

  if (_wcsnicmp_l(W, L"a", 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_wcsnicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _wcsnicmp_l(W, L"a", 1, locale) != 0)

  if (_mbscmp(U, V))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbscmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbscmp(U, V) != 0)

  if (_mbsncmp(U, V, 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsncmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbsncmp(U, V, 1) != 0)

  if (_mbsnbcmp(U, V, 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnbcmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnbcmp(U, V, 1) != 0)

  if (_mbsnbicmp(U, V, 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnbicmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnbicmp(U, V, 1) != 0)

  if (_mbsicmp(U, V))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsicmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbsicmp(U, V) != 0)

  if (_mbsnicmp(U, V, 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnicmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnicmp(U, V, 1) != 0)

  if (_mbscmp_l(U, V, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbscmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbscmp_l(U, V, locale) != 0)

  if (_mbsncmp_l(U, V, 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsncmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbsncmp_l(U, V, 1, locale) != 0)

  if (_mbsicmp_l(U, V, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbsicmp_l(U, V, locale) != 0)

  if (_mbsnicmp_l(U, V, 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnicmp_l(U, V, 1, locale) != 0)

  if (_mbsnbcmp_l(U, V, 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnbcmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnbcmp_l(U, V, 1, locale) != 0)

  if (_mbsnbicmp_l(U, V, 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnbicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnbicmp_l(U, V, 1, locale) != 0)

  return 1;
}
Ejemplo n.º 11
0
static int ServiceParseYmsgrLink(WPARAM wParam, LPARAM lParam)
{
	char *arg = (char*)lParam;
	UNREFERENCED_PARAMETER(wParam);
	if (arg == NULL) return 1; /* sanity check */
  /*
	  add user:       ymsgr:addfriend?ID
	  send message:   ymsgr:sendim?ID&m=MESSAGE
	  add chatroom:   ymsgr:chat?ROOM
  */
  /* skip leading prefix */
	arg = strchr(arg, ':');
	if (arg == NULL) return 1; /* parse failed */
	for (++arg; *arg == '/'; ++arg);
	/* add a contact to the list */
	if (!_strnicmp(arg, "addfriend?", 10)) {
		char *tok, *id = NULL;
		ADDCONTACTSTRUCT acs;
		PROTOSEARCHRESULT psr;
		if (*(arg += 10) == 0) return 1; /* parse failed */
		tok = strtok(arg, "&"); /* first token */
		if (tok != NULL) id = Netlib_UrlDecode(tok);
		if (id == NULL || *id == 0) return 1; /* parse failed */
		if (getbuddyH(id) == NULL) { /* does not yet check if id is current user */
			acs.handleType = HANDLE_SEARCHRESULT;
			acs.szProto = yahooProtocolName;
			acs.psr = &psr;
			memset(&psr, 0, sizeof(PROTOSEARCHRESULT));
			psr.cbSize = sizeof(PROTOSEARCHRESULT);
			psr.nick.t = id;
			CallService(MS_ADDCONTACT_SHOW, 0, (LPARAM)&acs);
		}
		return 0;
	}
	/* send a message to a contact */
	else if (!_strnicmp(arg, "sendim?", 7)) {
		char *tok, *id = NULL, *msg = NULL;
		MCONTACT hContact;
		if (*(arg += 7) == 0) return 1; /* parse failed */
		tok = strtok(arg, "&"); /* first token */
		if (tok != NULL) id = tok;
		while (tok != NULL) {
			if (!_strnicmp(tok, "m=", 2) && *(tok + 2) != 0)
				msg = Netlib_UrlDecode(tok + 2);
			tok = strtok(NULL, "&"); /* next token */
		}
		if (id == NULL || *id == 0) return 1; /* parse failed */
		if (ServiceExists(MS_MSG_SENDMESSAGE)) { /* does not yet check if sn is current user */
			hContact = add_buddy(id, id, PALF_TEMPORARY); /* ensure contact is on list */
			if (hContact != NULL)
				CallService(MS_MSG_SENDMESSAGE, hContact, (LPARAM)msg);
		}
		return 0;
	}
	/* open a chatroom */
	else if (!_strnicmp(arg, "chat?", 5)) {
		char *tok, *rm = NULL;
		if (*(arg += 5) == 0) return 1; /* parse failed */
		tok = strtok(arg, "&"); /* first token */
		if (tok != NULL) rm = Netlib_UrlDecode(tok);
		if (rm == NULL) return 1; /* parse failed */
		/* not yet implemented (rm contains name of chatroom)*/
		return 0;
	}
	return 1; /* parse failed */
}
int _tmain(int argc, _TCHAR* argv[])
{
    printf("This is a tcp class debugging test harness.\n");
    printf("Tests SMTP and POP3 protocols.\n");
    printf("-------------------------------------------\n");
    
    const char *rfilename="\\inetPub\\wwwroot\\IntrafoundationTCPClient\\test_data\\tcpclient.png";
    const char *wfilename="\\inetPub\\wwwroot\\IntrafoundationTCPClient\\test_data\\uu.png";
    char* const szhost="127.0.0.1";
    char* const szport_smtp="25";
    char* const szport_pop="110";
    int c;
	int secs=1;
	int msecs=0;

    









    // 0a
    printf(" list messages? (Y/N) RECV\n");
    c=_getch();
    if(c=='Y' || c=='y')
    {
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        
        
        ///////////////////////////////////////////////////////////////////////
        
        tcp *w=new tcp(szhost,szport_pop);
        if(w)
        {
            //
            int sendlength=0;
            int recvlength=0;
            char *r=NULL;

            //
            w->timeout(10,0);
            
            //
			w->Recv(r); if(r) printf("%s\n",r);
            
            w->SendCRLF("USER tcpclient");
			w->Recv(r); if(r) printf("%s\n",r);
			
            w->SendCRLF("PASS tcpclient");
			w->Recv(r); if(r) printf("%s\n",r);
            
			printf("\n####HELP\n");
            w->SendCRLF("HELP");
			w->Recv(r); if(r) printf("%s\n",r);
            
			printf("\n####LIST\n");
            w->SendCRLF("LIST");
			w->Recv(r); if(r) printf("%s\n",r);
            
            w->SendCRLF("QUIT");
			w->Recv(r); if(r) printf("%s\n",r);
            
            delete w;
            w=NULL;
        }
    }



    // 0b
    printf(" list messages? (Y/N) RECVRN\n");
    c=_getch();
    if(c=='Y' || c=='y')
    {
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        
        
        ///////////////////////////////////////////////////////////////////////
        
        tcp *w=new tcp(szhost,szport_pop);
        if(w)
        {
            //
            //int sendlength=0;
            //int recvlength=0;
            char *r=NULL;

            //
            w->timeout(10,0);
            
            //
			w->RecvCRLF(r); if(r) printf("%s\n",r);
            
            w->SendCRLF("USER tcpclient");
			w->RecvCRLF(r); if(r) printf("%s\n",r);
			
            w->SendCRLF("PASS tcpclient");
			w->RecvCRLF(r); if(r) printf("%s\n",r);
            
			printf("\n####HELP\n");
            w->SendCRLF("HELP");
			while(true)
			{
				w->RecvCRLF(r);
				if(r) printf("%s\n",r);
				if(r && strcmp((const char *)r,".")==0) break;
			}
            
			printf("\n####LIST\n");
            w->SendCRLF("LIST");
			while(true)
			{
				w->RecvCRLF(r);
				if(r) printf("%s\n",r);
				if(r && strcmp((const char *)r,".")==0) break;
			}
            
            w->SendCRLF("QUIT");
			w->RecvCRLF(r); if(r) printf("%s\n",r);
            
            delete w;
            w=NULL;
        }
    }



	
    // 1
    printf(" send u) uu m) mime base64 or N) for no\n");
    c=_getch();
    if(c=='m' || c=='M')
    {
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        
        
        ///////////////////////////////////////////////////////////////////////
        
        tcp *w=new tcp(szhost,szport_smtp);
        if(w)
        {
            //
            char *r=NULL;
            
            //
            w->timeout(5,0);

            w->RecvCRLF(r);
            
            //
            w->timeout(1,0);
            
            w->SendCRLF("HELO");
            w->RecvCRLF(r);
            
            w->SendCRLF("MAIL FROM: tcpclient@localhost");
            w->RecvCRLF(r);
            
            w->SendCRLF("RCPT TO: tcpclient@localhost");
            w->RecvCRLF(r);
            
            w->SendCRLF("DATA");
            w->RecvCRLF(r);
            
			CMIME mime;
			char *boundry=NULL;
			mime.boundry(boundry);
			char tmp[1024];
			


            w->SendCRLF("X-Mailer: TCPClient3, Intrafoundation Software");
            w->SendCRLF("X-Sender: tcpclient@localhost");
            w->SendCRLF("From: Intrafoundation Software");
            w->SendCRLF("Subject: This an encoding test using MIME base-64");
            w->SendCRLF("Mime-Version: 1.0");
            sprintf(tmp,"Content-Type: multipart/mixed; boundary=%s",boundry);
			w->SendCRLF(tmp);
			w->SendCRLF("");
			
			w->SendCRLF(boundry);
			w->SendCRLF("Content-Type: text/plain; charset=\"us-ascii\"");
			w->SendCRLF("");
			w->SendCRLF("This is a test. An attachment called tcpclient.png should be listed.");
			w->SendCRLF("");
			w->SendCRLF("");
			
			w->SendCRLF(boundry);
			w->SendCRLF("Content-Type: application/octet-stream; name=\"tcpclient.png\"");
			w->SendCRLF("Content-Transfer-Encoding: base64");
			w->SendCRLF("Content-Disposition: attachment; filename=\"base64.png\"");
            w->SendCRLF("");

            char rbuf[264144];
            
            struct _stat statbuf;
            int result=_stat( rfilename, &statbuf);
            if( result == -1 )
            {
                printf("_stat error\n");
            }
            else
            {
                printf( "File size     : %ld\n", statbuf.st_size );
                printf( "Drive         : %c:\n", statbuf.st_dev + 'A' );
                printf( "Time modified : %s", ctime( &statbuf.st_atime ) );
                
                FILE *rh=fopen(rfilename,"rb");
                if(rh!=NULL)
                {
                    long size=(long)statbuf.st_size;
                    int numread=fread(rbuf,1,size,rh);
                    
                    printf("size=%ld\n",size);
                    printf("numread=%d\n",numread);
                    
                    CBase64 base64;
                    int bytes=0;
                    char *btbuf=NULL;
                    
                    bytes=base64.encode_binary(rbuf,numread,btbuf);
                    
                    printf("base64 encode bytes:%d\n",bytes);
                    if(bytes) 
                    {
                        printf("btbuf:\n%s\n",btbuf);
                        
                        w->Send(btbuf,bytes);
                    }
                    fclose(rh);
                }
            }
  
            w->SendCRLF("");
            w->SendCRLF("");
			w->SendCRLF(boundry);

			//
            w->SendCRLF(".");
            w->RecvCRLF(r);
            
			//
            w->SendCRLF("QUIT");
            w->RecvCRLF(r);
            
			//
            delete w;
            w=NULL;
        }
    }
    else if(c=='u' || c=='U')
    {
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        
        
        ///////////////////////////////////////////////////////////////////////
        tcp *w=new tcp(szhost,szport_smtp);
        if(w)
        {
            //
            w->timeout(5,0);
            
            //
            int sendlength=0;
            int recvlength=0;
            char *r=NULL;
            
            //
            recvlength=w->RecvCRLF(r);
            
            //
            printf("\n");
            sendlength=w->SendCRLF("HELO");
            
            recvlength=w->RecvCRLF(r);
            
            sendlength=w->SendCRLF("MAIL FROM: tcpclient@localhost");
            recvlength=w->RecvCRLF(r);
			
            sendlength=w->SendCRLF("RCPT TO: tcpclient@localhost");
            recvlength=w->RecvCRLF(r);
            
            sendlength=w->SendCRLF("DATA");
            recvlength=w->RecvCRLF(r);
            
            sendlength=w->SendCRLF("This is a test.");

            sendlength=w->SendCRLF("begin 600 uu.png");
            
            char rbuf[264144];
            
            struct _stat statbuf;
            int result=_stat( rfilename, &statbuf);
            if( result == -1 )
            {
                printf("_stat error\n");
            }
            else
            {
                printf( "File size     : %ld\n", statbuf.st_size );
                printf( "Drive         : %c:\n", statbuf.st_dev + 'A' );
                printf( "Time modified : %s", ctime( &statbuf.st_atime ) );
                
                FILE *rh=fopen(rfilename,"rb");
                if(rh!=NULL)
                {
                    long size=(long)statbuf.st_size;
                    int numread=fread(rbuf,1,size,rh);
                    
                    printf("size=%ld\n",size);
                    printf("numread=%d\n",numread);
                    
                    CUU uu;
                    int bytes=0;
                    char *btbuf=NULL;
                    
                    bytes=uu.encode_binary(rbuf,numread,btbuf);
                    
                    printf("uuencode bytes:%d\n",bytes);
                    if(bytes) 
                    {
                        printf("btbuf:\n%s\n",btbuf);
                        
                        sendlength=w->Send(btbuf,bytes);
                    }
                    fclose(rh);
                }
            }
            
            sendlength=w->SendCRLF("end");
            sendlength=w->SendCRLF(".");
            recvlength=w->RecvCRLF(r);
            
            sendlength=w->SendCRLF("QUIT");
            recvlength=w->RecvCRLF(r);
            
            delete w;
        }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
    
    
    // 2
    printf("\n");
    printf("==========================================\n");
    printf("==========================================\n");
    printf("==========================================\n");
    printf("\n");
    
    
    printf(" retr u) uu  m) mime base64 or N) for no\n");
    c=_getch();
    if(c=='m' || c=='M')
    {
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////
        
        
        ///////////////////////////////////////////////////////////////////////
        tcp *w=new tcp(szhost,szport_pop);
        if(w)
        {
            //
            w->timeout(5,0);
            
            //
            int sendlength=0;
            int recvlength=0;
            char *r=NULL;
            
            //
            recvlength=w->RecvCRLF(r);
            
            sendlength=w->SendCRLF("USER tcpclient");
            recvlength=w->RecvCRLF(r);
			
            sendlength=w->SendCRLF("PASS tcpclient");
            recvlength=w->RecvCRLF(r);
            
            sendlength=w->SendCRLF("RETR 1");
			
            char *buf=new char[262144];
			if(buf)
			{
				long buf_length=0L;
				memset(buf,0,sizeof(buf));
				int state=0;
				
				//
				int line=0;
				int blank=0;
				do
				{
					recvlength=w->RecvCRLF(r);
					
					//
					if(state==3 && recvlength==0)
						state=0;
					if(state==3)
					{
						memcpy((buf+buf_length),r,recvlength);
						buf_length+=recvlength;
						*(buf+buf_length+0)=13;
						*(buf+buf_length+1)=10;
						buf_length+=2;
						blank=1;
						if(r)
						{
							printf("+%4d %d %s\n",line,state,r);
							line++;
						}
					}
					if(state==2 && recvlength==0)
						state=3;
					if(r && _stricmp(r,"--=====================_977368803==_")==0)
						state=1;
					if(state==1 && r && _strnicmp(r,"Content-Type: application/octet-stream;",39)==0)
						state=2;
					
					if(blank==0)
					{
						printf(" %4d %d %s\n",line,state,r);
						line++;
					}
					blank=0;
					
					if(r && _stricmp(r,".")==0)
						break;
					
				} while( !w->iscompleted() && w->last_timeout()==0.0);
				*(buf+buf_length)=0;
				
				printf("\nbuf_length:%d\n",buf_length);
				printf("buf:%s\n",buf);
				
				
				if(buf_length)
				{
					//
					CBase64 base64;
					int bytes=0;
					char *btbuf=NULL;
					
					bytes=base64.decode_binary(buf,buf_length,btbuf);
					
					printf("\nbytes:%d\n",bytes);
					printf("btbuf:%s\n",btbuf);
					
					FILE *h=fopen("\\inetPub\\wwwroot\\IntrafoundationTCPClient\\test_data\\base64.png","wb");
					if(h)
					{
						int numwrite=fwrite(btbuf,1,bytes,h);
						fclose(h);
					}
				}
				
				delete[] buf;
			}
            
            
            sendlength=w->SendCRLF("QUIT");
            recvlength=w->RecvCRLF(r);
            
            delete w;
        }
    }
    else if(c=='u' || c=='U')
    {
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		
		
		///////////////////////////////////////////////////////////////////////
		tcp *w=new tcp(szhost,szport_pop);
		if(w)
		{
			//
			w->timeout(5,0);
			
			//
			int sendlength=0;
			int recvlength=0;
			char *r=NULL;
			
            //
            recvlength=w->RecvCRLF(r);
            
            sendlength=w->SendCRLF("USER tcpclient");
            recvlength=w->RecvCRLF(r);
			
            sendlength=w->SendCRLF("PASS tcpclient");
            recvlength=w->RecvCRLF(r);
            
            sendlength=w->SendCRLF("RETR 1");
			
			
			//
			char *buf=new char[262144];
			if(buf)
			{
				long buf_length=0L;
				memset(buf,0,sizeof(buf));
				int state=FALSE;
				
				//
				do
				{
					recvlength=w->RecvCRLF(r);
					
					if(r && _stricmp(r,".")==0)
						break;
					
					//
					if(state==TRUE)
					{
						memcpy((buf+buf_length),r,recvlength);
						buf_length+=recvlength;
						*(buf+buf_length+0)=13;
						*(buf+buf_length+1)=10;
						buf_length+=2;
					}
					if(r && _strnicmp(r,"begin ",6)==0)
						state=TRUE;
					if(r && _strnicmp(r,"end",3)==0)
						state=FALSE;
					
				} while( !w->iscompleted() && w->last_timeout()==0.0);
				*(buf+buf_length)=0;
				
				printf("\nbuf_length:%d\n",buf_length);
				printf("buf:%s\n",buf);
				
				//
				if(buf_length)
				{
					CUU uu;
					int bytes=0;
					char *btbuf=NULL;
					
					bytes=uu.decode_binary(buf,buf_length,btbuf);
					
					printf("\nbytes:%d\n",bytes);
					printf("btbuf:%s\n",btbuf);
					
					FILE *h=fopen(wfilename,"wb");
					if(h)
					{
						int numwrite=fwrite(btbuf,1,bytes,h);
						fclose(h);
					}
				}
				
				delete[] buf;
			}
			
			
			sendlength=w->SendCRLF("QUIT");
			recvlength=w->RecvCRLF(r);
			
			delete w;
		}
	}   
	
	
	
	
	
	// 3
	printf("\n");
	printf("==========================================\n");
	printf("==========================================\n");
	printf("==========================================\n");
	printf("\n");
	
	printf("DELE after y/n?\n");
	c=_getch();
	if(c=='y' || c=='Y')
	{
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		
		
		///////////////////////////////////////////////////////////////////////
		tcp *w=new tcp("127.0.0.1","110");
		if(w)
		{
			//
			w->timeout(5,0);
			
			//
			int sendlength=0;
			int recvlength=0;
			char *r=NULL;
			
			//
			recvlength=w->RecvCRLF(r);
			
			sendlength=w->SendCRLF("USER tcpclient");
			recvlength=w->RecvCRLF(r);
			
			sendlength=w->SendCRLF("PASS tcpclient");
			recvlength=w->RecvCRLF(r);
			
			sendlength=w->SendCRLF("DELE 1");
			recvlength=w->RecvCRLF(r);
			
			sendlength=w->SendCRLF("QUIT");
			recvlength=w->RecvCRLF(r);
			
			delete w;
		}
	}
	
	
	return 0;
}
Ejemplo n.º 13
0
void CPPgSecurity::OnLoadIPFFromURL()
{
	bool bHaveNewFilterFile = false;
	CString url;
	GetDlgItemText(IDC_UPDATEURL,url);
	//Xman auto update IPFilter
	SYSTEMTIME SysTime;
	memset(&SysTime, 0, sizeof(SYSTEMTIME)); //just to avoid the warning
	//Xman end
	if (!url.IsEmpty())
	{
		// add entered URL to LRU list even if it's not yet known whether we can download from this URL (it's just more convenient this way)
		if (m_pacIPFilterURL && m_pacIPFilterURL->IsBound())
			m_pacIPFilterURL->AddItem(url, 0);

		// ==> Advanced Updates [MorphXT/Stulle] - Stulle
		if(thePrefs.IsIPFilterViaDynDNS(url))
		{
			theApp.emuledlg->CheckIPFilter();
			return;
		}
		// <== Advanced Updates [MorphXT/Stulle] - Stulle

		CString strTempFilePath;
		_tmakepathlimit(strTempFilePath.GetBuffer(MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T("tmp"));
		strTempFilePath.ReleaseBuffer();

		CHttpDownloadDlg dlgDownload;
		dlgDownload.m_strTitle = GetResString(IDS_DWL_IPFILTERFILE);
		dlgDownload.m_sURLToDownload = url;
		dlgDownload.m_sFileToDownloadInto = strTempFilePath;
		
		//Xman auto update IPFilter
		memset(&SysTime, 0, sizeof(SYSTEMTIME));
		dlgDownload.m_pLastModifiedTime = &SysTime; //Xman remark: m_pLastModifiedTime is a pointer which points to the SysTime-struct
		//Xman end

		if (dlgDownload.DoModal() != IDOK)
		{
			(void)_tremove(strTempFilePath);
			CString strError = GetResString(IDS_DWLIPFILTERFAILED);
			if (!dlgDownload.GetError().IsEmpty())
				strError += _T("\r\n\r\n") + dlgDownload.GetError();
			AfxMessageBox(strError, MB_ICONERROR);
			return;
		}

		CString strMimeType;
		GetMimeType(strTempFilePath, strMimeType);

		bool bIsArchiveFile = false;
		bool bUncompressed = false;
		CZIPFile zip;
		if (zip.Open(strTempFilePath))
		{
			bIsArchiveFile = true;

			CZIPFile::File* zfile = zip.GetFile(_T("ipfilter.dat"));
			if (zfile == NULL)
				zfile = zip.GetFile(_T("guarding.p2p"));
			if (zfile == NULL)
				zfile = zip.GetFile(_T("guardian.p2p"));
			if (zfile)
			{
				CString strTempUnzipFilePath;
				_tmakepathlimit(strTempUnzipFilePath.GetBuffer(_MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T(".unzip.tmp"));
				strTempUnzipFilePath.ReleaseBuffer();

				if (zfile->Extract(strTempUnzipFilePath))
				{
					zip.Close();
					zfile = NULL;

					if (_tremove(theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to remove default IP filter file \"%s\" - %s\n"), theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
					if (_trename(strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to rename uncompressed IP filter file \"%s\" to default IP filter file \"%s\" - %s\n"), strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
					if (_tremove(strTempFilePath) != 0)
						TRACE(_T("*** Error: Failed to remove temporary IP filter file \"%s\" - %s\n"), strTempFilePath, _tcserror(errno));
					bUncompressed = true;
					bHaveNewFilterFile = true;
				}
				else {
					CString strError;
					strError.Format(GetResString(IDS_ERR_IPFILTERZIPEXTR), strTempFilePath);
					AfxMessageBox(strError, MB_ICONERROR);
				}
			}
			else {
				CString strError;
				strError.Format(GetResString(IDS_ERR_IPFILTERCONTENTERR), strTempFilePath);
				AfxMessageBox(strError, MB_ICONERROR);
			}

			zip.Close();
		}
		else if (strMimeType.CompareNoCase(_T("application/x-rar-compressed")) == 0)
		{
			bIsArchiveFile = true;

			CRARFile rar;
			if (rar.Open(strTempFilePath))
			{
				CString strFile;
				if (rar.GetNextFile(strFile)
					&& (   strFile.CompareNoCase(_T("ipfilter.dat")) == 0 
					    || strFile.CompareNoCase(_T("guarding.p2p")) == 0
						|| strFile.CompareNoCase(_T("guardian.p2p")) == 0))
				{
					CString strTempUnzipFilePath;
					_tmakepathlimit(strTempUnzipFilePath.GetBuffer(MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T(".unzip.tmp"));
					strTempUnzipFilePath.ReleaseBuffer();
					if (rar.Extract(strTempUnzipFilePath))
					{
						rar.Close();

						if (_tremove(theApp.ipfilter->GetDefaultFilePath()) != 0)
							TRACE(_T("*** Error: Failed to remove default IP filter file \"%s\" - %s\n"), theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
						if (_trename(strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath()) != 0)
							TRACE(_T("*** Error: Failed to rename uncompressed IP filter file \"%s\" to default IP filter file \"%s\" - %s\n"), strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
						if (_tremove(strTempFilePath) != 0)
							TRACE(_T("*** Error: Failed to remove temporary IP filter file \"%s\" - %s\n"), strTempFilePath, _tcserror(errno));
						bUncompressed = true;
						bHaveNewFilterFile = true;
					}
					else
					{
						CString strError;
						strError.Format(_T("Failed to extract IP filter file from RAR file \"%s\"."), strTempFilePath);
						AfxMessageBox(strError, MB_ICONERROR);
					}
				}
				else
				{
					CString strError;
					strError.Format(_T("Failed to find IP filter file \"guarding.p2p\" or \"ipfilter.dat\" in RAR file \"%s\"."), strTempFilePath);
					AfxMessageBox(strError, MB_ICONERROR);
				}
				rar.Close();
			}
			else
			{
				CString strError;
				strError.Format(_T("Failed to open file \"%s\".\r\n\r\nInvalid file format?\r\n\r\nDownload latest version of UNRAR.DLL from http://www.rarlab.com and copy UNRAR.DLL into eMule installation folder."), url);
				AfxMessageBox(strError, MB_ICONERROR);
			}
		}
		else
		{
			CGZIPFile gz;
			if (gz.Open(strTempFilePath))
			{
				bIsArchiveFile = true;

				CString strTempUnzipFilePath;
				_tmakepathlimit(strTempUnzipFilePath.GetBuffer(_MAX_PATH), NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), DFLT_IPFILTER_FILENAME, _T(".unzip.tmp"));
				strTempUnzipFilePath.ReleaseBuffer();

				// add filename and extension of uncompressed file to temporary file
				CString strUncompressedFileName = gz.GetUncompressedFileName();
				if (!strUncompressedFileName.IsEmpty())
				{
					strTempUnzipFilePath += _T('.');
					strTempUnzipFilePath += strUncompressedFileName;
				}

				if (gz.Extract(strTempUnzipFilePath))
				{
					gz.Close();

					if (_tremove(theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to remove default IP filter file \"%s\" - %s\n"), theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
					if (_trename(strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath()) != 0)
						TRACE(_T("*** Error: Failed to rename uncompressed IP filter file \"%s\" to default IP filter file \"%s\" - %s\n"), strTempUnzipFilePath, theApp.ipfilter->GetDefaultFilePath(), _tcserror(errno));
					if (_tremove(strTempFilePath) != 0)
						TRACE(_T("*** Error: Failed to remove temporary IP filter file \"%s\" - %s\n"), strTempFilePath, _tcserror(errno));
					bUncompressed = true;
					bHaveNewFilterFile = true;
				}
				else {
					CString strError;
					strError.Format(GetResString(IDS_ERR_IPFILTERZIPEXTR), strTempFilePath);
					AfxMessageBox(strError, MB_ICONERROR);
				}
			}
			gz.Close();
		}

		if (!bIsArchiveFile && !bUncompressed)
		{
			// Check first lines of downloaded file for potential HTML content (e.g. 404 error pages)
			bool bValidIPFilterFile = true;
			FILE* fp = _tfsopen(strTempFilePath, _T("rb"), _SH_DENYWR);
			if (fp)
			{
				char szBuff[16384];
				int iRead = fread(szBuff, 1, _countof(szBuff)-1, fp);
				if (iRead <= 0)
					bValidIPFilterFile = false;
				else
				{
					szBuff[iRead-1] = '\0';

					const char* pc = szBuff;
					while (*pc == ' ' || *pc == '\t' || *pc == '\r' || *pc == '\n')
						pc++;
					if (_strnicmp(pc, "<html", 5) == 0
						|| _strnicmp(pc, "<xml", 4) == 0
						|| _strnicmp(pc, "<!doc", 5) == 0)
					{
						bValidIPFilterFile = false;
					}
				}
				fclose(fp);
			}

			if (bValidIPFilterFile)
			{
				(void)_tremove(theApp.ipfilter->GetDefaultFilePath());
				VERIFY( _trename(strTempFilePath, theApp.ipfilter->GetDefaultFilePath()) == 0 );
				bHaveNewFilterFile = true;
			}
			else
			{
				AfxMessageBox(GetResString(IDS_DWLIPFILTERFAILED), MB_ICONERROR);
			}
		}
	}

	//Xman auto update IPFilter
	// ==> Advanced Updates [MorphXT/Stulle] - Stulle
	/*
	struct tm tmTemp;
	thePrefs.m_last_ipfilter_check = safe_mktime(CTime::GetCurrentTime().GetLocalTm(&tmTemp));
	*/
	// <== Advanced Updates [MorphXT/Stulle] - Stulle
	//Xman end

	if (url.IsEmpty() || bHaveNewFilterFile)
		OnReloadIPFilter();

	// In case we received an invalid IP-filter file (e.g. an 404 HTML page with HTTP status "OK"),
	// warn the user that there are no IP-filters available any longer.
	if (bHaveNewFilterFile && theApp.ipfilter->GetIPFilter().GetCount() == 0)
	{
		CString strLoaded;
		strLoaded.Format(GetResString(IDS_IPFILTERLOADED), theApp.ipfilter->GetIPFilter().GetCount());
		CString strError;
		strError.Format(_T("%s\r\n\r\n%s"), GetResString(IDS_DWLIPFILTERFAILED), strLoaded);
		AfxMessageBox(strError, MB_ICONERROR);
	}
	//Xman auto update IPFilter
	else if(bHaveNewFilterFile)
		memcpy(&thePrefs.m_IPfilterVersion, &SysTime, sizeof SysTime); 
	//Xman end
}
Ejemplo n.º 14
0
WAVERESULT CWaves::ParseFile(const char *szFilename, LPWAVEFILEINFO pWaveInfo)
{
    WAVEFILEHEADER waveFileHeader;
    RIFFCHUNK      riffChunk;
    WAVEFMT        waveFmt;
    WAVERESULT     wr = WR_BADWAVEFILE;

    if (!szFilename || !pWaveInfo)
        return WR_INVALIDPARAM;

    memset(pWaveInfo, 0, sizeof(WAVEFILEINFO));

    // Open the wave file for reading
    fopen_s(&pWaveInfo->pFile, szFilename, "rb");
    if (pWaveInfo->pFile)
    {
        // Read Wave file header
        fread(&waveFileHeader, 1, sizeof(WAVEFILEHEADER), pWaveInfo->pFile);
        if (!_strnicmp(waveFileHeader.szRIFF, "RIFF", 4) && !_strnicmp(waveFileHeader.szWAVE, "WAVE", 4))
        {
            while (fread(&riffChunk, 1, sizeof(RIFFCHUNK), pWaveInfo->pFile) == sizeof(RIFFCHUNK))
            {
                if (!_strnicmp(riffChunk.szChunkName, "fmt ", 4))
                {
                    if (riffChunk.ulChunkSize <= sizeof(WAVEFMT))
                    {
                        fread(&waveFmt, 1, riffChunk.ulChunkSize, pWaveInfo->pFile);

                        // Determine if this is a WAVEFORMATEX or WAVEFORMATEXTENSIBLE wave file
                        if (waveFmt.usFormatTag == WAVE_FORMAT_PCM)
                        {
                            pWaveInfo->wfType = WF_EX;
                            memcpy(&pWaveInfo->wfEXT.Format, &waveFmt, sizeof(PCMWAVEFORMAT));
                        }
                        else if (waveFmt.usFormatTag == WAVE_FORMAT_EXTENSIBLE)
                        {
                            pWaveInfo->wfType = WF_EXT;
                            memcpy(&pWaveInfo->wfEXT, &waveFmt, sizeof(WAVEFORMATEXTENSIBLE));
                        }
                    }
                    else
                    {
                        fseek(pWaveInfo->pFile, riffChunk.ulChunkSize, SEEK_CUR);
                    }
                }
                else if (!_strnicmp(riffChunk.szChunkName, "data", 4))
                {
                    pWaveInfo->ulDataSize   = riffChunk.ulChunkSize;
                    pWaveInfo->ulDataOffset = ftell(pWaveInfo->pFile);
                    fseek(pWaveInfo->pFile, riffChunk.ulChunkSize, SEEK_CUR);
                }
                else
                {
                    fseek(pWaveInfo->pFile, riffChunk.ulChunkSize, SEEK_CUR);
                }

                // Ensure that we are correctly aligned for next chunk
                if (riffChunk.ulChunkSize & 1)
                    fseek(pWaveInfo->pFile, 1, SEEK_CUR);
            }

            if (pWaveInfo->ulDataSize && pWaveInfo->ulDataOffset && ((pWaveInfo->wfType == WF_EX) || (pWaveInfo->wfType == WF_EXT)))
                wr = WR_OK;
            else
                fclose(pWaveInfo->pFile);
        }
    }
    else
    {
        wr = WR_INVALIDFILENAME;
    }

    return wr;
}
Ejemplo n.º 15
0
/*
 * This function can accept a NULL pointer as `addr', in which case
 * it will only check the host name.
 */
static int proxy_for_destination (SockAddr addr, const char *hostname,
                                  int port, Conf *conf)
{
    int s = 0, e = 0;
    char hostip[64];
    int hostip_len, hostname_len;
    const char *exclude_list;

    /*
     * Special local connections such as Unix-domain sockets
     * unconditionally cannot be proxied, even in proxy-localhost
     * mode. There just isn't any way to ask any known proxy type for
     * them.
     */
    if (addr && sk_address_is_special_local(addr))
        return 0;                      /* do not proxy */

    /*
     * Check the host name and IP against the hard-coded
     * representations of `localhost'.
     */
    if (!conf_get_int(conf, CONF_even_proxy_localhost) &&
	(sk_hostname_is_local(hostname) ||
	 (addr && sk_address_is_local(addr))))
	return 0;		       /* do not proxy */

    /* we want a string representation of the IP address for comparisons */
    if (addr) {
	sk_getaddr(addr, hostip, 64);
	hostip_len = strlen(hostip);
    } else
	hostip_len = 0;		       /* placate gcc; shouldn't be required */

    hostname_len = strlen(hostname);

    exclude_list = conf_get_str(conf, CONF_proxy_exclude_list);

    /* now parse the exclude list, and see if either our IP
     * or hostname matches anything in it.
     */

    while (exclude_list[s]) {
	while (exclude_list[s] &&
	       (isspace((unsigned char)exclude_list[s]) ||
		exclude_list[s] == ',')) s++;

	if (!exclude_list[s]) break;

	e = s;

	while (exclude_list[e] &&
	       (isalnum((unsigned char)exclude_list[e]) ||
		exclude_list[e] == '-' ||
		exclude_list[e] == '.' ||
		exclude_list[e] == '*')) e++;

	if (exclude_list[s] == '*') {
	    /* wildcard at beginning of entry */

	    if ((addr && _strnicmp(hostip + hostip_len - (e - s - 1),
				  exclude_list + s + 1, e - s - 1) == 0) ||
		_strnicmp(hostname + hostname_len - (e - s - 1),
			 exclude_list + s + 1, e - s - 1) == 0)
		return 0; /* IP/hostname range excluded. do not use proxy. */

	} else if (exclude_list[e-1] == '*') {
	    /* wildcard at end of entry */

	    if ((addr && _strnicmp(hostip, exclude_list + s, e - s - 1) == 0) ||
		_strnicmp(hostname, exclude_list + s, e - s - 1) == 0)
		return 0; /* IP/hostname range excluded. do not use proxy. */

	} else {
	    /* no wildcard at either end, so let's try an absolute
	     * match (ie. a specific IP)
	     */

	    if (addr && _strnicmp(hostip, exclude_list + s, e - s) == 0)
		return 0; /* IP/hostname excluded. do not use proxy. */
	    if (_strnicmp(hostname, exclude_list + s, e - s) == 0)
		return 0; /* IP/hostname excluded. do not use proxy. */
	}

	s = e;

	/* Make sure we really have reached the next comma or end-of-string */
	while (exclude_list[s] &&
	       !isspace((unsigned char)exclude_list[s]) &&
	       exclude_list[s] != ',') s++;
    }

    /* no matches in the exclude list, so use the proxy */
    return 1;
}
Ejemplo n.º 16
0
static int ServiceParseAimLink(WPARAM, LPARAM lParam)
{
	char *arg = (char*)lParam;
	if (arg == NULL) return 1; /* sanity check */
  /* skip leading prefix */
	arg = strchr(arg, ':');
	if (arg == NULL) return 1; /* parse failed */
	for (++arg; *arg == '/'; ++arg);
	/*
		add user:      aim:addbuddy?screenname=NICK&groupname=GROUP
		send message:  aim:goim?screenname=NICK&message=MSG
		open chatroom: aim:gochat?roomname=ROOM&exchange=NUM
	*/
	/* add a contact to the list */
	if (!_strnicmp(arg, "addbuddy?", 9)) {
		char *tok, *sn = NULL, *group = NULL;
		ADDCONTACTSTRUCT acs;
		PROTOSEARCHRESULT psr;
		if (*(arg += 9) == 0) return 1; /* parse failed */
		tok = strtok(arg, "&"); /* first token */
		while (tok != NULL) {
			if (!_strnicmp(tok, "screenname=", 11) && *(tok + 11) != 0)
				sn = Netlib_UrlDecode(tok + 11);
			if (!_strnicmp(tok, "groupname=", 10) && *(tok + 10) != 0)
				group = Netlib_UrlDecode(tok + 10);  /* group is currently ignored */
			tok = strtok(NULL, "&"); /* next token */
		}
		if (sn == NULL) return 1; /* parse failed */
		if (find_contact(sn) == NULL) { /* does not yet check if sn is current user */
			acs.handleType = HANDLE_SEARCHRESULT;
			acs.szProto = AIM_PROTOCOL_NAME;
			acs.psr = &psr;
			memset(&psr, 0, sizeof(PROTOSEARCHRESULT));
			psr.cbSize = sizeof(PROTOSEARCHRESULT);
			psr.nick.t = sn;
			CallService(MS_ADDCONTACT_SHOW, 0, (LPARAM)&acs);
		}
		return 0;
	}
	/* send a message to a contact */
	else if (!_strnicmp(arg, "goim?", 5)) {
		char *tok, *sn = NULL, *msg = NULL;
		MCONTACT hContact;
		if (*(arg += 5) == 0) return 1; /* parse failed */
		tok = strtok(arg, "&"); /* first token */
		while (tok != NULL) {
			if (!_strnicmp(tok, "screenname=", 11) && *(tok + 11) != 0)
				sn = Netlib_UrlDecode(tok + 11);
			if (!_strnicmp(tok, "message=", 8) && *(tok + 8) != 0)
				msg = Netlib_UrlDecode(tok + 8);
			tok = strtok(NULL, "&"); /* next token */
		}
		if (sn == NULL) return 1; /* parse failed */
		if (ServiceExists(MS_MSG_SENDMESSAGE)) {
			hContact = find_contact(sn);
			if (hContact == NULL) {
				hContact = add_contact(sn); /* does not yet check if sn is current user */
				if (hContact != NULL)
					db_set_b(hContact, MOD_KEY_CL, AIM_KEY_NL, 1);
			}
			if (hContact != NULL)
				CallService(MS_MSG_SENDMESSAGE, hContact, (LPARAM)msg);
		}
		return 0;
	}
	/* open a chatroom */
	else if (!_strnicmp(arg, "gochat?", 7)) {
		char *tok, *rm = NULL;
		int exchange = 0;
		if (*(arg += 7) == 0) return 1; /* parse failed */
		tok = strtok(arg, "&"); /* first token */
		while (tok != NULL) {
			if (!_strnicmp(tok, "roomname=", 9) && *(tok + 9) != 0)
				rm = Netlib_UrlDecode(tok + 9);
			if (!_strnicmp(tok, "exchange=", 9))
				exchange = atoi(Netlib_UrlDecode(tok + 9));
			tok = strtok(NULL, "&"); /* next token */
		}
		if (rm == NULL || exchange <= 0) return 1; /* parse failed */
		aim_gchat_joinrequest(rm, exchange);
		return 0;
	}
	return 1; /* parse failed */
}
Ejemplo n.º 17
0
int CVxParamMatrix::InitializeIO(vx_context context, vx_graph graph, vx_reference ref, const char * io_params)
{
	// save reference object and get object attributes
	m_vxObjRef = ref;
	m_matrix = (vx_matrix)m_vxObjRef;
	ERROR_CHECK(vxQueryMatrix(m_matrix, VX_MATRIX_ATTRIBUTE_TYPE, &m_data_type, sizeof(m_data_type)));
	ERROR_CHECK(vxQueryMatrix(m_matrix, VX_MATRIX_ATTRIBUTE_COLUMNS, &m_columns, sizeof(m_columns)));
	ERROR_CHECK(vxQueryMatrix(m_matrix, VX_MATRIX_ATTRIBUTE_ROWS, &m_rows, sizeof(m_rows)));
	ERROR_CHECK(vxQueryMatrix(m_matrix, VX_MATRIX_ATTRIBUTE_SIZE, &m_size, sizeof(m_size)));

	// process I/O parameters
	if (*io_params == ':') io_params++;
	while (*io_params) {
		char ioType[64], fileName[256];
		io_params = ScanParameters(io_params, "<io-operation>,<parameter>", "s,S", ioType, fileName);
		if (!_stricmp(ioType, "read"))
		{ // read request syntax: read,<fileName>[,ascii|binary]
			m_fileNameRead.assign(RootDirUpdated(fileName));
			m_fileNameForReadHasIndex = (m_fileNameRead.find("%") != m_fileNameRead.npos) ? true : false;
			m_readFileIsBinary = (m_fileNameRead.find(".txt") != m_fileNameRead.npos) ? false : true;
			while (*io_params == ',') {
				char option[64];
				io_params = ScanParameters(io_params, ",ascii|binary", ",s", option);
				if (!_stricmp(option, "ascii")) {
					m_readFileIsBinary = false;
				}
				else if (!_stricmp(option, "binary")) {
					m_readFileIsBinary = true;
				}
				else ReportError("ERROR: invalid matrix read option: %s\n", option);
			}
		}
		else if (!_stricmp(ioType, "write"))
		{ // write request syntax: write,<fileName>[,ascii|binary]
			m_fileNameWrite.assign(RootDirUpdated(fileName));
			m_writeFileIsBinary = (m_fileNameWrite.find(".txt") != m_fileNameWrite.npos) ? false : true;
			while (*io_params == ',') {
				char option[64];
				io_params = ScanParameters(io_params, ",ascii|binary", ",s", option);
				if (!_stricmp(option, "ascii")) {
					m_writeFileIsBinary = false;
				}
				else if (!_stricmp(option, "binary")) {
					m_writeFileIsBinary = true;
				}
				else ReportError("ERROR: invalid matrix write option: %s\n", option);
			}
		}
		else if (!_stricmp(ioType, "compare"))
		{ // compare request syntax: compare,<fileName>[,ascii|binary][,err{<tolerance>}]
			m_fileNameCompare.assign(RootDirUpdated(fileName));
			m_compareFileIsBinary = (m_fileNameCompare.find(".txt") != m_fileNameCompare.npos) ? false : true;
			while (*io_params == ',') {
				char option[64];
				io_params = ScanParameters(io_params, ",ascii|binary|err{<tolerance>}", ",s", option);
				if (!_stricmp(option, "ascii")) {
					m_compareFileIsBinary = false;
				}
				else if (!_stricmp(option, "binary")) {
					m_compareFileIsBinary = true;
				}
				else if (!_strnicmp(option, "err{", 4)) {
					ScanParameters(&option[3], "{<tolerance>}", "{f}", &m_errTolerance);
				}
				else ReportError("ERROR: invalid matrix compare option: %s\n", option);
			}
		}
		else if (!_stricmp(ioType, "init"))
		{ // write request syntax: init,{<value1>;<value2>;...<valueN>}
			NULLPTR_CHECK(m_bufForAccess = new vx_uint8[m_size]);
			vx_size index = 0; char fmt[3] = { '{', (m_data_type == VX_TYPE_FLOAT32) ? 'f' : 'd', 0 };
			for (const char * s = fileName; *s && index < (m_columns * m_rows); fmt[0] = ';', index++) {
				if (m_data_type == VX_TYPE_INT32 || m_data_type == VX_TYPE_UINT8) {
					vx_uint32 value;
					s = ScanParameters(s, "<value>", fmt, &value);
					if (m_data_type == VX_TYPE_UINT8) ((vx_uint8 *)m_bufForAccess)[index] = (vx_uint8)value;
					else ((vx_int32 *)m_bufForAccess)[index] = value;
				}
				else if (m_data_type == VX_TYPE_FLOAT32) {
					s = ScanParameters(s, "<value>", fmt, &((vx_float32 *)m_bufForAccess)[index]);
				}
				else ReportError("ERROR: matrix init option not support for data_type of %s\n", GetVxObjectName());
			}
			if (index < (m_columns * m_rows)) ReportError("ERROR: matrix init have too few values: %s\n", fileName);
			ERROR_CHECK(vxWriteMatrix(m_matrix, m_bufForAccess));
		}
		else if (!_stricmp(ioType, "directive") && !_stricmp(fileName, "readonly")) {
			ERROR_CHECK(vxDirective((vx_reference)m_matrix, VX_DIRECTIVE_AMD_READ_ONLY));
		}
		else if (!_stricmp(ioType, "ui") && !_strnicmp(fileName, "f", 1) && m_data_type == VX_TYPE_FLOAT32 && m_columns == 3 && m_rows == 3) {
			int id = 0;
			float valueR = 200.0f, valueInc = 0.5f;
			if (sscanf(&fileName[1], "%d,%g,%g", &id, &valueR, &valueInc) != 3) {
				printf("ERROR: invalid matrix UI configuration '%s'\n", fileName);
				return -1;
			}
			id--;
			GuiTrackBarInitializeMatrix((vx_reference)m_matrix, id, valueR, valueInc);
			GuiTrackBarProcessKey(0); // just initialize the matrix
		}
		else ReportError("ERROR: invalid matrix operation: %s\n", ioType);
		if (*io_params == ':') io_params++;
		else if (*io_params) ReportError("ERROR: unexpected character sequence in parameter specification: %s\n", io_params);
	}

	return 0;
}
void Mixer::getPortsInfo() {
  MIXERCAPS mc;
  mixerGetDevCaps((UINT)hMixer, &mc, sizeof mc);

  MIXERLINE mlt;
  unsigned i;
  for (i = 0; i < mc.cDestinations; ++i) {
    memset(&mlt, 0, sizeof mlt);
    mlt.cbStruct = sizeof mlt;
    mlt.dwDestination = i;
    if (mixerGetLineInfo((HMIXEROBJ)hMixer, &mlt, MIXER_GETLINEINFOF_DESTINATION) != MMSYSERR_NOERROR) continue;
    if (mlt.dwLineID == dwRecLineID) break; // this is the destination we're interested in
  }
  ports = new AudioInputPort[mlt.cConnections];

  numPorts = mlt.cConnections;
  for (i = 0; i < numPorts; ++i) {
    MIXERLINE mlc;
    memcpy(&mlc, &mlt, sizeof mlc);
    mlc.dwSource = i;
    mixerGetLineInfo((HMIXEROBJ)hMixer, &mlc, MIXER_GETLINEINFOF_SOURCE/*|MIXER_OBJECTF_HMIXER*/);
    ports[i].tag = mlc.dwLineID;
	ports[i].dwComponentType = mlc.dwComponentType;
#ifdef UNICODE
    wcstombs(ports[i].name, mlc.szName, MIXER_LONG_NAME_CHARS);
#else
    strncpy(ports[i].name, mlc.szName, MIXER_LONG_NAME_CHARS);
#endif
  }

  // Make the microphone the first port in the list:
  for (i = 1; i < numPorts; ++i) {
#ifdef OLD_MICROPHONE_TESTING_CODE
    if (_strnicmp("mic", ports[i].name, 3) == 0 ||
	_strnicmp("mik", ports[i].name, 3) == 0) {
#else
	if (ports[i].dwComponentType == MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE) {
#endif
      AudioInputPort tmp = ports[0];
      ports[0] = ports[i];
      ports[i] = tmp;
    }
  }
}

Boolean Mixer::enableInputPort(unsigned portIndex, char const*& errReason, MMRESULT& errCode) {
  errReason = NULL; // unless there's an error
  AudioInputPort& port = ports[portIndex];

  MIXERCONTROL mc;
  mc.cMultipleItems = 1; // in case it doesn't get set below
  MIXERLINECONTROLS mlc;
#if 0 // the following doesn't seem to be needed, and can fail:
  mlc.cbStruct = sizeof mlc;
  mlc.pamxctrl = &mc;
  mlc.cbmxctrl = sizeof (MIXERCONTROL);
  mlc.dwLineID = port.tag;
  mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
  if ((errCode = mixerGetLineControls((HMIXEROBJ)hMixer, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE/*|MIXER_OBJECTF_HMIXER*/)) != MMSYSERR_NOERROR) {
    errReason = "mixerGetLineControls()";
    return False;
  }
#endif

  MIXERLINE ml;
  memset(&ml, 0, sizeof (MIXERLINE));
  ml.cbStruct = sizeof (MIXERLINE);
  ml.dwLineID = port.tag;
  if ((errCode = mixerGetLineInfo((HMIXEROBJ)hMixer, &ml, MIXER_GETLINEINFOF_LINEID)) != MMSYSERR_NOERROR) {
    errReason = "mixerGetLineInfo()1";
    return False;
  }

  

  #ifdef UNICODE
    wchar_t portname[MIXER_LONG_NAME_CHARS+1];
    wcsncpy(portname, ml.szName, MIXER_LONG_NAME_CHARS);
  #else
    char portname[MIXER_LONG_NAME_CHARS+1];
    strncpy(portname, ml.szName, MIXER_LONG_NAME_CHARS);
  #endif

  memset(&ml, 0, sizeof (MIXERLINE));
  ml.cbStruct = sizeof (MIXERLINE);
  ml.dwLineID = dwRecLineID;
  if ((errCode = mixerGetLineInfo((HMIXEROBJ)hMixer, &ml, MIXER_GETLINEINFOF_LINEID/*|MIXER_OBJECTF_HMIXER*/)) != MMSYSERR_NOERROR) {
    errReason = "mixerGetLineInfo()2";
    return False;
  }

  // Get Mixer/MUX control information (need control id to set and get control details)
  mlc.cbStruct = sizeof mlc;
  mlc.dwLineID = ml.dwLineID;
  mlc.cControls = 1;
  mc.cbStruct = sizeof mc; // Needed???#####
  mc.dwControlID = 0xDEADBEEF; // For testing #####
  mlc.pamxctrl = &mc;
  mlc.cbmxctrl = sizeof mc;
  mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_MUX; // Single Select
  if ((errCode = mixerGetLineControls((HMIXEROBJ)hMixer, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE/*|MIXER_OBJECTF_HMIXER*/)) != MMSYSERR_NOERROR) {
    mlc.dwControlType = MIXERCONTROL_CONTROLTYPE_MIXER; // Multiple Select
    mixerGetLineControls((HMIXEROBJ)hMixer, &mlc, MIXER_GETLINECONTROLSF_ONEBYTYPE/*|MIXER_OBJECTF_HMIXER*/);
  }

  unsigned matchLine = 0;
  if (mc.cMultipleItems > 1) {
    // Before getting control, we need to know which line to grab.
    // We figure this out by listing the lines, and comparing names:
    MIXERCONTROLDETAILS mcd;
    mcd.cbStruct = sizeof mcd;
    mcd.cChannels = ml.cChannels;
    mcd.cMultipleItems = mc.cMultipleItems;
    MIXERCONTROLDETAILS_LISTTEXT* mcdlText = new MIXERCONTROLDETAILS_LISTTEXT[mc.cMultipleItems];
    mcd.cbDetails = sizeof (MIXERCONTROLDETAILS_LISTTEXT);
    mcd.paDetails = mcdlText;

    if (mc.dwControlID != 0xDEADBEEF) { // we know the control id for real
      mcd.dwControlID = mc.dwControlID;
      if ((errCode = mixerGetControlDetails((HMIXEROBJ)hMixer, &mcd, MIXER_GETCONTROLDETAILSF_LISTTEXT/*|MIXER_OBJECTF_HMIXER*/)) != MMSYSERR_NOERROR) {
	delete[] mcdlText;
	errReason = "mixerGetControlDetails()1";
	return False;
      }
    } else {
      // Hack: We couldn't find a MUX or MIXER control, so try to guess the control id:
      for (mc.dwControlID = 0; mc.dwControlID < 32; ++mc.dwControlID) {
	mcd.dwControlID = mc.dwControlID;
	if ((errCode = mixerGetControlDetails((HMIXEROBJ)hMixer, &mcd, MIXER_GETCONTROLDETAILSF_LISTTEXT/*|MIXER_OBJECTF_HMIXER*/)) == MMSYSERR_NOERROR) break;
      }
      if (mc.dwControlID == 32) { // unable to guess mux/mixer control id
	delete[] mcdlText;
	errReason = "mixerGetControlDetails()2";
	return False;
      }
    }

    #ifdef UNICODE
    for (unsigned i = 0; i < mcd.cMultipleItems; ++i) {
        if (wcscmp(mcdlText[i].szName, portname) == 0) {
	    matchLine = i;
	    break;
        }
    }
    #else
    for (unsigned i = 0; i < mcd.cMultipleItems; ++i) {
        if (strcmp(mcdlText[i].szName, portname) == 0) {
	    matchLine = i;
	    break;
        }
    }
    #endif
    
    delete[] mcdlText;
  }

  // Now get control itself:
  MIXERCONTROLDETAILS mcd;
  mcd.cbStruct = sizeof mcd;
  mcd.dwControlID = mc.dwControlID;
  mcd.cChannels = ml.cChannels;
  mcd.cMultipleItems = mc.cMultipleItems;
  MIXERCONTROLDETAILS_BOOLEAN* mcdbState = new MIXERCONTROLDETAILS_BOOLEAN[mc.cMultipleItems];
  mcd.paDetails = mcdbState;
  mcd.cbDetails = sizeof (MIXERCONTROLDETAILS_BOOLEAN);

  if ((errCode = mixerGetControlDetails((HMIXEROBJ)hMixer, &mcd, MIXER_GETCONTROLDETAILSF_VALUE/*|MIXER_OBJECTF_HMIXER*/)) != MMSYSERR_NOERROR) {
    delete[] mcdbState;
    errReason = "mixerGetControlDetails()3";
    return False;
  }

  for (unsigned j = 0; j < mcd.cMultipleItems; ++j) {
    mcdbState[j].fValue = (j == matchLine);
  }

  if ((errCode = mixerSetControlDetails((HMIXEROBJ)hMixer, &mcd, MIXER_OBJECTF_HMIXER)) != MMSYSERR_NOERROR) {
    delete[] mcdbState;
    errReason = "mixerSetControlDetails()";
    return False;
  }
  delete[] mcdbState;

  return True;
}
Ejemplo n.º 19
0
/////////////////////////////////////////////////////////////////////////////
// Demuxer Functions
STDMETHODIMP CBDDemuxer::Open(LPCOLESTR pszFileName)
{
  CAutoLock lock(m_pLock);
  HRESULT hr = S_OK;

  int ret; // return code from C functions

  // Convert the filename from wchar to char for libbluray
  char fileName[4096];
  ret = WideCharToMultiByte(CP_UTF8, 0, pszFileName, -1, fileName, 4096, NULL, NULL);

  int iPlaylist = -1;

  DbgLog((LOG_TRACE, 10, L"Initializing BluRay Demuxer; Entry Point: %s", pszFileName));

  size_t len = strlen(fileName);
  if (len > 16) {
    char *bd_path = fileName;
    if(_strcmpi(bd_path+strlen(bd_path) - 16, "\\BDMV\\index.bdmv") == 0) {
      bd_path[strlen(bd_path) - 15] = 0;
    } else if (len > 22 && _strcmpi(bd_path+strlen(bd_path) - 22, "\\BDMV\\MovieObject.bdmv") == 0) {
      bd_path[strlen(bd_path) - 21] = 0;
    } else if (len > 25 && _strnicmp(bd_path+strlen(bd_path) - 25, "\\BDMV\\PLAYLIST\\", 15) == 0) {
      char *playlist = &bd_path[strlen(bd_path) - 10];
      bd_path[strlen(bd_path) - 24] = 0;

      playlist[5] = 0;
      iPlaylist = atoi(playlist);
    } else {
      return E_FAIL;
    }
    // Open BluRay
    BLURAY *bd = bd_open(bd_path, NULL);
    if(!bd) {
      return E_FAIL;
    }
    m_pBD = bd;

    uint32_t timelimit = (iPlaylist != -1) ? 0 : 180;
    uint8_t flags = (iPlaylist != -1) ? TITLES_ALL : TITLES_RELEVANT;

    // Fetch titles
fetchtitles:
    m_nTitleCount = bd_get_titles(bd, flags, timelimit);

    if (m_nTitleCount <= 0) {
      if (timelimit > 0) {
        timelimit = 0;
        goto fetchtitles;
      }
      if (flags != TITLES_ALL) {
        flags = TITLES_ALL;
        goto fetchtitles;
      }
      return E_FAIL;
    }

    DbgLog((LOG_TRACE, 20, L"Found %d titles", m_nTitleCount));
    DbgLog((LOG_TRACE, 20, L" ------ Begin Title Listing ------"));

    uint64_t longest_duration = 0;
    uint32_t title_id = 0;
    boolean found = false;
    for(uint32_t i = 0; i < m_nTitleCount; i++) {
      BLURAY_TITLE_INFO *info = bd_get_title_info(bd, i, 0);
      if (info) {
        DbgLog((LOG_TRACE, 20, L"Title %u, Playlist %u (%u clips, %u chapters), Duration %I64u (%I64u seconds)", i, info->playlist, info->clip_count, info->chapter_count, info->duration, Convert90KhzToDSTime(info->duration) / DSHOW_TIME_BASE));
        if (iPlaylist != -1 && info->playlist == iPlaylist) {
          title_id = i;
          found = true;
        } else if (iPlaylist == -1 && info->duration > longest_duration) {
          title_id = i;
          longest_duration = info->duration;
        }
        bd_free_title_info(info);
      }
      if (found)
        break;
    }
    DbgLog((LOG_TRACE, 20, L" ------ End Title Listing ------"));

    hr = SetTitle(title_id);
  }

  return hr;
}
Ejemplo n.º 20
0
int config(char *configFile) {
	int i, k;
	char *newArgument;
	char newLine[CONFIG_SPACE_SIZE * 3];

	FILE *newFile;
	TCHAR newString[CONFIG_SPACE_SIZE];

	if((newFile = fopen(configFile, "r")) != NULL) {
		k = 1;

		while(fgets(newLine, sizeof(newLine) - 1, newFile) != NULL) {
			if(newLine[0] == '\r' || newLine[0] == '\n' || newLine[0] == '#' || newLine[0] == '%' || newLine[0] == ';') {
				k++;

				continue;
			}

			for(i = 0; ; i++) {
				if(mainConfigs[i].confKeyword == NULL) {
					break;
				}

				if(_strnicmp(mainConfigs[i].confKeyword, newLine, strlen(mainConfigs[i].confKeyword)) == 0) {
					if((newArgument = configParse(newLine)) == NULL) {
						continue;
					}

					if(newArgument == (char *) -1) {
						_snprintf(newString, sizeof(newString), "Keyword %s at line %d requires an argument of type %d%c", mainConfigs[i].confKeyword, k, mainConfigs[i].confArgType, 0);

						warningMessage(ERROR_SLIGHT, newString);

						continue;
					}

					switch(mainConfigs[i].confArgType) {
						case CONFIG_TYPE_BOOLEAN:
							if((configBoolean(newArgument, &mainConfigs[i].confArgInt)) != 0) {
								_snprintf(newString, sizeof(newString), "Keyword %s at line %d requires a boolean (yes/no/1/0) argument%c", mainConfigs[i].confKeyword, k, 0);

								warningMessage(ERROR_SLIGHT, newString);

								continue;
							}

							break;
						case CONFIG_TYPE_INTEGER:
							if((configInteger(newArgument, &mainConfigs[i].confArgInt)) != 0) {
								_snprintf(newString, sizeof(newString), "Keyword %s at line %d requires a numeral (0-9) argument%c", mainConfigs[i].confKeyword, k, 0);

								warningMessage(ERROR_SLIGHT, newString);

								continue;
							}

							break;
						case CONFIG_TYPE_STRING:
							configString(newArgument, mainConfigs[i].confArgStr);

							break;
						default:
							_snprintf(newString, sizeof(newString), "Unknown argument type %d for keyword %s at line %d%c", mainConfigs[i].confArgType, mainConfigs[i].confKeyword, k, 0);

							warningMessage(ERROR_SLIGHT, newString);

							break;
					}
				}
			}

			k++;
		}

		if(fclose(newFile) == -1) {
			warningMessage(ERROR_SLIGHT, "Error occurred while trying to close file");
		}

		return(0);
	}

	return(-1);
}
Ejemplo n.º 21
0
// works with prior opened zip
bool CZipper::AddFileToZip(LPCTSTR szFilePath, bool bIgnoreFilePath)
{
	if (!m_uzFile)
		return FALSE;

	// we don't allow paths beginning with '..\' because this would be outside
	// the root folder
	if (!bIgnoreFilePath && strstr(szFilePath, "..\\") == szFilePath)
		return false;

	//TRACE ("CZipper::AddFileToZip(%s)\n", szFilePath);

	bool bFullPath = (strchr(szFilePath, ':') != NULL);

	// if the file is relative then we need to append the root before opening
	char szFullFilePath[MAX_PATH];
	
	lstrcpy(szFullFilePath, szFilePath);
	PrepareSourcePath(szFullFilePath);

	// if the file is a fullpath then remove the root path bit
	char szFileName[MAX_PATH] = "";

	if (bIgnoreFilePath)
	{
		char szName[_MAX_FNAME], szExt[_MAX_EXT];
		_splitpath(szFilePath, NULL, NULL, szName, szExt);

		_makepath(szFileName, NULL, NULL, szName, szExt);
	}
	else if (bFullPath)
	{
		// check the root can be found
		if (0 != _strnicmp(szFilePath, m_szRootFolder, lstrlen(m_szRootFolder)))
			return false;

		// else
		lstrcpy(szFileName, szFilePath + lstrlen(m_szRootFolder));
	}
	else // relative path
	{
		// if the path begins with '.\' then remove it
		if (strstr(szFilePath, ".\\") == szFilePath)
			lstrcpy(szFileName, szFilePath + 2);
		else
			lstrcpy(szFileName, szFilePath);
	}

	// save file attributes
	zip_fileinfo zfi;

	zfi.internal_fa = 0;
	zfi.external_fa = ::GetFileAttributes(szFilePath);
	
	// save file time
	SYSTEMTIME st;

	//GetLastModified(szFullFilePath, st, TRUE);

	zfi.dosDate = 0;
	zfi.tmz_date.tm_year = st.wYear;
	zfi.tmz_date.tm_mon = st.wMonth - 1;
	zfi.tmz_date.tm_mday = st.wDay;
	zfi.tmz_date.tm_hour = st.wHour;
	zfi.tmz_date.tm_min = st.wMinute;
	zfi.tmz_date.tm_sec = st.wSecond;
	
	// load input file
	HANDLE hInputFile = ::CreateFile(szFullFilePath, 
									GENERIC_READ,
									0,
									NULL,
									OPEN_EXISTING,
									FILE_ATTRIBUTE_READONLY,
									NULL);

	if (hInputFile == INVALID_HANDLE_VALUE)
		return FALSE;

	int nRet = zipOpenNewFileInZip(m_uzFile, 
									szFileName,
									&zfi, 
									NULL, 
									0,
									NULL,
									0, 
									NULL,
									Z_DEFLATED,
									Z_DEFAULT_COMPRESSION);

	if (nRet == ZIP_OK)
	{
		m_info.nFileCount++;

		// read the file and output to zip
		char pBuffer[BUFFERSIZE];
		DWORD dwBytesRead = 0, dwFileSize = 0;

		while (nRet == ZIP_OK && ::ReadFile(hInputFile, pBuffer, BUFFERSIZE, &dwBytesRead, NULL))
		{
			dwFileSize += dwBytesRead;

			if (dwBytesRead)
				nRet = zipWriteInFileInZip(m_uzFile, pBuffer, dwBytesRead);
			else
				break;
		}

		m_info.dwUncompressedSize += dwFileSize;
	}

	zipCloseFileInZip(m_uzFile);
	::CloseHandle(hInputFile);

	return (nRet == ZIP_OK);
}
/*
 * This is a blocking function that merely sits on the request queue
 * for our URI and processes them one at a time.  Once a request comes
 * in, we check it for content-type, content-length, and verb.  As long
 * as the initial validations are done, we pass the request to the
 * processRPCCall() function, which collects the body of the request
 * and processes it.  If we get an error back other than network type,
 * we are responsible for notifing the client.
 */
DWORD
DoReceiveRequests(
    IN HANDLE hReqQueue,
    const xmlrpc_server_httpsys_parms * const parmsP
)
{
    ULONG              result;
    HTTP_REQUEST_ID    requestId;
    DWORD              bytesRead;
    PHTTP_REQUEST      pRequest;
    PCHAR              pRequestBuffer;
    ULONG              RequestBufferLength;
    xmlrpc_env			env;
    char				szHeaderBuf[255];
    long				lContentLength;

    // Allocate a 2K buffer. Should be good for most requests, we'll grow
    // this if required. We also need space for a HTTP_REQUEST structure.
    RequestBufferLength = sizeof(HTTP_REQUEST) + 2048;
    pRequestBuffer      = (PCHAR) ALLOC_MEM( RequestBufferLength );
    if (pRequestBuffer == NULL)
    {
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    pRequest = (PHTTP_REQUEST)pRequestBuffer;

    // Wait for a new request -- This is indicated by a NULL request ID.
    HTTP_SET_NULL_ID( &requestId );
    for(;;)
    {
        RtlZeroMemory(pRequest, RequestBufferLength);

        result = HttpReceiveHttpRequest(
                     hReqQueue,          // Req Queue
                     requestId,          // Req ID
                     0,                  // Flags
                     pRequest,           // HTTP request buffer
                     RequestBufferLength,// req buffer length
                     &bytesRead,         // bytes received
                     NULL                // LPOVERLAPPED
                 );

        if(NO_ERROR == result)
        {
            // Got a request with a filled buffer.
            switch(pRequest->Verb)
            {
            case HttpVerbPOST:

                TraceW(L"Got a POST request for %ws \n",pRequest->CookedUrl.pFullUrl);

                //Check if we need use authorization.
                if(parmsP->authfn)
                {
                    xmlrpc_env_init(&env);
                    if(pRequest->Headers.KnownHeaders[HttpHeaderAuthorization].RawValueLength<6)
                    {
                        xmlrpc_env_set_fault( &env, XMLRPC_REQUEST_REFUSED_ERROR,
                                              "Authorization header too short.");
                    }
                    else
                    {
                        //unencode the headers
                        if(_strnicmp("basic ",pRequest->Headers.KnownHeaders[HttpHeaderAuthorization].pRawValue,6)!=0)
                        {
                            xmlrpc_env_set_fault( &env, XMLRPC_REQUEST_REFUSED_ERROR,
                                                  "Authorization header is not of type basic.");
                        }
                        else
                        {
                            xmlrpc_mem_block * decoded;

                            decoded = xmlrpc_base64_decode(&env,pRequest->Headers.KnownHeaders[HttpHeaderAuthorization].pRawValue+6,pRequest->Headers.KnownHeaders[HttpHeaderAuthorization].RawValueLength-6);
                            if(!env.fault_occurred)
                            {
                                char *pDecodedStr;
                                char *pUser;
                                char *pPass;
                                char *pColon;

                                pDecodedStr = (char*)malloc(decoded->_size+1);
                                memcpy(pDecodedStr,decoded->_block,decoded->_size);
                                pDecodedStr[decoded->_size]='\0';
                                pUser = pPass = pDecodedStr;
                                pColon=strchr(pDecodedStr,':');
                                if(pColon)
                                {
                                    *pColon='\0';
                                    pPass=pColon+1;
                                    //The authfn should set env to fail if auth is denied.
                                    parmsP->authfn(&env,pUser,pPass);
                                }
                                else
                                {
                                    xmlrpc_env_set_fault( &env, XMLRPC_REQUEST_REFUSED_ERROR,
                                                          "Decoded auth not of the correct format.");
                                }
                                free(pDecodedStr);
                            }
                            if(decoded)
                                XMLRPC_MEMBLOCK_FREE(char, decoded);
                        }
                    }
                    if(env.fault_occurred)
                    {
                        //request basic authorization, as the user did not provide it.
                        xmlrpc_env_clean(&env);
                        TraceW(L"POST request did not provide valid authorization header.");
                        result = SendHttpResponseAuthRequired( hReqQueue, pRequest);
                        break;
                    }
                    xmlrpc_env_clean(&env);
                }

                //Check content type to make sure it is text/xml.
                memcpy(szHeaderBuf,pRequest->Headers.KnownHeaders[HttpHeaderContentType].pRawValue,pRequest->Headers.KnownHeaders[HttpHeaderContentType].RawValueLength);
                szHeaderBuf[pRequest->Headers.KnownHeaders[HttpHeaderContentType].RawValueLength]='\0';
                if (_stricmp(szHeaderBuf,"text/xml")!=0)
                {
                    //We only handle text/xml data.  Anything else is not valid.
                    TraceW(L"POST request had an unsupported content-type: %s \n", szHeaderBuf);
                    result = SendHttpResponse(
                                 hReqQueue,
                                 pRequest,
                                 400,
                                 "Bad Request",
                                 NULL
                             );
                    break;
                }

                //Check content length to make sure it exists and is not too big.
                memcpy(szHeaderBuf,pRequest->Headers.KnownHeaders[HttpHeaderContentLength].pRawValue,pRequest->Headers.KnownHeaders[HttpHeaderContentLength].RawValueLength);
                szHeaderBuf[pRequest->Headers.KnownHeaders[HttpHeaderContentLength].RawValueLength]='\0';
                lContentLength = atol(szHeaderBuf);
                if (lContentLength<=0)
                {
                    //Make sure a content length was supplied.
                    TraceW(L"POST request did not include a content-length \n", szHeaderBuf);
                    result = SendHttpResponse(
                                 hReqQueue,
                                 pRequest,
                                 411,
                                 "Length Required",
                                 NULL
                             );
                    break;
                }
                if((size_t) lContentLength > xmlrpc_limit_get(XMLRPC_XML_SIZE_LIMIT_ID))
                {
                    //Content-length is too big for us to handle
                    TraceW(L"POST request content-length is too big for us to handle: %d bytes \n", lContentLength);
                    result = SendHttpResponse(
                                 hReqQueue,
                                 pRequest,
                                 500,
                                 "content-length too large",
                                 NULL
                             );
                    break;
                }

                //our initial validations of POST, content-type, and content-length
                //all check out.  Collect and pass the complete buffer to the
                //XMLRPC-C library

                xmlrpc_env_init(&env);
                processRPCCall(&env,hReqQueue, pRequest);
                if (env.fault_occurred)
                {
                    //if we fail and it is anything other than a network error,
                    //we should return a failure response to the client.
                    if (env.fault_code != XMLRPC_NETWORK_ERROR)
                    {
                        if (env.fault_string)
                            result = SendHttpResponse(
                                         hReqQueue,
                                         pRequest,
                                         500,
                                         env.fault_string,
                                         NULL
                                     );
                        else
                            result = SendHttpResponse(
                                         hReqQueue,
                                         pRequest,
                                         500,
                                         "Unknown Error",
                                         NULL
                                     );
                    }
                }

                xmlrpc_env_clean(&env);
                break;

            default:
                //We only handle POST data.  Anything else is not valid.
                TraceW(L"Got an unsupported Verb request for URI %ws \n", pRequest->CookedUrl.pFullUrl);

                result = SendHttpResponse(
                             hReqQueue,
                             pRequest,
                             405,
                             "Method Not Allowed",
                             NULL
                         );
                break;
            }
            if(result != NO_ERROR)
            {
                break;
            }

            // Reset the Request ID so that we pick up the next request.
            HTTP_SET_NULL_ID( &requestId );
        }
        else if(result == ERROR_MORE_DATA)
        {
            // The input buffer was too small to hold the request headers
            // We have to allocate more buffer & call the API again.
            //
            // When we call the API again, we want to pick up the request
            // that just failed. This is done by passing a RequestID.
            // This RequestID is picked from the old buffer.
            requestId = pRequest->RequestId;

            // Free the old buffer and allocate a new one.
            RequestBufferLength = bytesRead;
            FREE_MEM( pRequestBuffer );
            pRequestBuffer = (PCHAR) ALLOC_MEM( RequestBufferLength );

            if (pRequestBuffer == NULL)
            {
                result = ERROR_NOT_ENOUGH_MEMORY;
                break;
            }

            pRequest = (PHTTP_REQUEST)pRequestBuffer;

        }
        else if(ERROR_CONNECTION_INVALID == result &&
                !HTTP_IS_NULL_ID(&requestId))
        {
            // The TCP connection got torn down by the peer when we were
            // trying to pick up a request with more buffer. We'll just move
            // onto the next request.
            HTTP_SET_NULL_ID( &requestId );
        }
        else
        {
            break;
        }

    } // for(;;)
Cleanup:

    if(pRequestBuffer)
    {
        FREE_MEM( pRequestBuffer );
    }

    return result;
}
Ejemplo n.º 23
0
void CYahooProto::ext_got_im(const char *me, const char *who, int protocol, const char *msg,
								long tm, int stat, int utf8, int buddy_icon,
								const char *seqn, int sendn)
{
	char 		*umsg;
	const char	*c = msg;
	int 		oidx = 0;

	LOG(("YAHOO_GOT_IM id:%s %s: %s (len: %d) tm:%lu stat:%i utf8:%i buddy_icon: %i", me, who, msg, mir_strlen(msg), tm, stat, utf8, buddy_icon));

	if (stat == 2) {
		char z[1024];

		mir_snprintf(z, SIZEOF(z), "Error sending message to %s", who);
		LOG((z));
		ShowError( TranslateT("Yahoo Error"), _A2T(z));
		return;
	}

	if (!msg) {
		LOG(("Empty Incoming Message, exiting."));
		return;
	}

	if (getByte("IgnoreUnknown", 0)) {

		/*
		* Check our buddy list to see if we have it there. And if it's not on the list then we don't accept any IMs.
		*/
		if (getbuddyH(who) == NULL) {
			LOG(("Ignoring unknown user messages. User '%s'. Dropping Message.", who));
			return;
		}
	}

	if ( BuddyIgnored( who )) {
		LOG(("User '%s' on our Ignore List. Dropping Message.", who));
		return;
	}

	// make a bigger buffer for \n -> \r\n conversion (x2)
	umsg = (char *) alloca(mir_strlen(msg) * 2 + 1);

	while ( *c != '\0') {
		// Strip the font tag
		if (!_strnicmp(c,"<font ",6) || !_strnicmp(c,"</font>",6) ||
			// strip the fade tag
			!_strnicmp(c, "<FADE ",6) || !_strnicmp(c,"</FADE>",7) ||
			// strip the alternate colors tag
			!_strnicmp(c, "<ALT ",5) || !_strnicmp(c, "</ALT>",6)) {
				while ((*c++ != '>') && (*c != '\0'));
		} else
			// strip ANSI color combination
			if ((*c == 0x1b) && (*(c+1) == '[')) {
				while ((*c++ != 'm') && (*c != '\0'));
			} else

				if (*c != '\0') {
					umsg[oidx++] = *c;

					/* Adding \r to \r\n conversion */
					if (*c == '\r' && *(c + 1) != '\n')
						umsg[oidx++] = '\n';

					c++;
				}
	}

	umsg[oidx++]= '\0';

	/* Need to strip off formatting stuff first. Then do all decoding/converting */
	LOG(("%s: %s", who, umsg));

	MCONTACT hContact = add_buddy(who, who, protocol, PALF_TEMPORARY);
	//setWord(hContact, "yprotoid", protocol);
	Set_Protocol(hContact, protocol);

	PROTORECVEVENT pre = { 0 };
	pre.flags = (utf8) ? PREF_UTF : 0;

	if (tm) {
		HANDLE hEvent = db_event_last(hContact);

		if (hEvent) { // contact has events
			DWORD dummy;
			DBEVENTINFO dbei = { sizeof (dbei) };
			dbei.pBlob = (BYTE*)&dummy;
			dbei.cbBlob = 2;
			if (!db_event_get(hEvent, &dbei))
				// got that event, if newer than ts then reset to current time
				if ((DWORD)tm < dbei.timestamp) tm = (long)time(NULL);
		}

		pre.timestamp = (DWORD)time(NULL);

		if ((DWORD)tm < pre.timestamp)
			pre.timestamp = tm;

	}
	else pre.timestamp = (DWORD)time(NULL);

	pre.szMessage = umsg;
	pre.lParam = 0;

	// Turn off typing
	CallService(MS_PROTO_CONTACTISTYPING, hContact, PROTOTYPE_CONTACTTYPING_OFF);
	ProtoChainRecvMsg(hContact, &pre);

	// ack the message we just got
	if (seqn)
		yahoo_send_im_ack(m_id, me, who, seqn, sendn);

	if (buddy_icon < 0) return;

	//?? Don't generate floods!!
	setByte(hContact, "AvatarType", (BYTE)buddy_icon);
	if (buddy_icon != 2)
		reset_avatar(hContact);
	else if (getDword(hContact, "PictCK", 0) == 0) /* request the buddy image */
		request_avatar(who);
}
Ejemplo n.º 24
0
/**
 * ParseTestFile
 * parse a single phpt file and add it to the arrays
 */
BOOL ParseTestFile(const char *path, const char *fn)
{
	// parse the test file
	char filename[MAX_PATH];
	_snprintf(filename, sizeof(filename)-1, "%s\\%s", path, fn);
	char line[1024];
	memset(line, 0, sizeof(line));
	CString cTest, cSkipIf, cPost, cGet, cFile, cExpect;
	printf("Reading %s\r\n", filename);

	enum state {none, test, skipif, post, get, file, expect} parsestate = none;

	FILE *fp = fopen(filename, "rb");
	char *tn = _tempnam(temppath,"pht.");
	char *en = _tempnam(temppath,"exp.");
	FILE *ft = fopen(tn, "wb+");
	FILE *fe = fopen(en, "wb+");
	if (fp && ft && fe) {
		while (fgets(line, sizeof(line)-1, fp)) {
			if (line[0]=='-') {
				if (_strnicmp(line, "--TEST--", 8)==0) {
					parsestate = test;
					continue;
				} else if (_strnicmp(line, "--SKIPIF--", 10)==0) {
					parsestate = skipif;
					continue;
				} else if (_strnicmp(line, "--POST--", 8)==0) {
					parsestate = post;
					continue;
				} else if (_strnicmp(line, "--GET--", 7)==0) {
					parsestate = get;
					continue;
				} else if (_strnicmp(line, "--FILE--", 8)==0) {
					parsestate = file;
					continue;
				} else if (_strnicmp(line, "--EXPECT--", 10)==0) {
					parsestate = expect;
					continue;
				}
			}
			switch (parsestate) {
			case test:
				stripcrlf(line);
				cTest = line;
				break;
			case skipif:
				cSkipIf += line;
				break;
			case post:
				cPost += line;
				break;
			case get:
				cGet += line;
				break;
			case file:
				fputs(line, ft);
				break;
			case expect:
				fputs(line, fe);
				break;
			}
		}		

		fclose(fp);
		fclose(ft);
		fclose(fe);

		if (!cTest.IsEmpty()) {
			IsapiFileList.Add(tn);
			TestNames.Add(cTest);
			IsapiGetData.Add(cGet);
			IsapiPostData.Add(cPost);
			IsapiMatchData.Add(en);
			free(tn);
			free(en);
			return TRUE;
		}
	}
	free(tn);
	free(en);
	return FALSE;
}
Ejemplo n.º 25
0
 inline int strncasecmp(const char *c1, const char *c2, size_t len) {
 	return _strnicmp(c1,c2,len);
 }
Ejemplo n.º 26
0
extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nShowCmd*/)
{
    lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT
    _Module.Init(ObjectMap, hInstance, IDS_SERVICENAME, &LIBID_WIPPIENSERVICELib);
    _Module.m_bService = TRUE;

    TCHAR szTokens[] = _T("-/");

    LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);
    while (lpszToken != NULL)
    {
        if (_strnicmp(lpszToken, _T("UnregServer"), 11)==0)
			flagUnregServer = TRUE;

        // Register as Local Server
        if (_strnicmp(lpszToken, _T("RegServer"), 9)==0)
            flagRegServer = TRUE;
        
        // Register as Service
        if (_strnicmp(lpszToken, _T("Service"), 7)==0)
			flagService = TRUE;
        
        // Register as Service
        if (_strnicmp(lpszToken, _T("AutoStart"), 9)==0)
			flagAutoStart = SERVICE_AUTO_START;

        lpszToken = FindOneOf(lpszToken, szTokens);
    }


	if (flagUnregServer)
		return _Module.UnregisterServer();

	if (flagRegServer)
		return _Module.RegisterServer(TRUE, FALSE);
        
	if (flagService)
		return _Module.RegisterServer(TRUE, TRUE);


    // Are we Service or Local Server
    CRegKey keyAppID;
    LONG lRes = keyAppID.Open(HKEY_CLASSES_ROOT, _T("AppID"), KEY_READ);
    if (lRes != ERROR_SUCCESS)
        return lRes;

    CRegKey key;
    lRes = key.Open(keyAppID, _T("{A3084FF8-63BF-40A1-8AE0-AD792B0078D9}"), KEY_READ);
    if (lRes != ERROR_SUCCESS)
        return lRes;

    TCHAR szValue[_MAX_PATH];
    DWORD dwLen = _MAX_PATH;
    lRes = key.QueryValue(szValue, _T("LocalService"), &dwLen);

    _Module.m_bService = FALSE;
    if (lRes == ERROR_SUCCESS)
        _Module.m_bService = TRUE;

	WODXMPP::_XMPP_LibInit(_Module.GetModuleInstance());
	WODVPN::_VPN_LibInit(_Module.GetModuleInstance());
	
	if (LoadConfig())
	{		
		_Jabber = new CJabberLib();
		_Ethernet = new CEthernet();


		if (_Ethernet->InitAdapter())
		{
			_Module.LogEvent("Connecting to the XMPP server." );
			
			_Ethernet->GetMyIP();
			_Module.Start();
		}
		else
			_Module.LogEvent(_T("Wippien Service failed to open Network adapter."));

	}
	else
	{
		char bf[8192];
		sprintf(bf, "Could not read: %s.config", __argv[0]);
		_Module.LogEvent(bf);

	}
	
	WODVPN::_VPN_LibDeinit();
	WODXMPP::_XMPP_LibDeInit();

    // When we get here, the service has been stopped
    return _Module.m_status.dwWin32ExitCode;
}
Ejemplo n.º 27
0
void add_values(char *pString, char_list **ppList)
{
    char_list **ppTraverse = NULL;
    char_list *pEntry = NULL;
    int iLength = 0;
    int iBackslash = 0;

    if(pString == NULL || *pString == '\0' || ppList == NULL)   {
	return;
    }

    while(pString)  {
	/*  Find start of value.
	 */
	iBackslash = 0;
	while(*pString) {
	    if(*pString == '\\')    {
		iBackslash++;
	    }
	    else if(*pString == '\n')   {
		if(iBackslash == 0)  {
		    /*  End of values.
		     *  Setting to NULL gets out of all loops.
		     */
		    pString = NULL;
		    break;
		}
		iBackslash = 0;
	    }
	    else if(!isspace(*pString))  {
		/*  Backslashes part of string.
		 *  This screws up if a backslash is in the middle of the string.
		 */
		pString -= iBackslash;
		break;
	    }

	    pString++;
	}
	if(pString == NULL || *pString == '\0') {
	    break;
	}

	/*  Do not honor anything beginning with a #
	 */
	if(*pString == '#') {
	    /*  End of line.
	     */
	    while(*pString && *pString != '\n') {
		pString++;
	    }
	    continue;
	}

	/*  Very first part of the string is value name.
	 *  How long is it?
	 */
	iLength = value_length(pString);

	/*  Do not honor $(NULL)
	 */
	if(_strnicmp(pString, "$(NULL)", 7) == 0)    {
	    pString += iLength;
	    continue;
	}

	/*  Allocate a new list entry for the next value.
	 */
	pEntry = (char_list *)malloc(sizeof(char_list));
	memset(pEntry, 0, sizeof(char_list));

	pEntry->m_pString = (char *)malloc(iLength + 1);
	memset(pEntry->m_pString, 0, iLength + 1);
	strncpy(pEntry->m_pString, pString, iLength);

	/*  Add new value entry to the end of the list.
	 */
	ppTraverse = ppList;
	while(*ppTraverse)  {
	    ppTraverse = &((*ppTraverse)->m_pNext);
	}
	*ppTraverse = pEntry;

	/*  Go on to next value.
	 */
	pString += iLength;
    }
}
Ejemplo n.º 28
0
	ArchiveFileChooserInfo(ArchiveFile& theArchive, const char** ignoreExtensions, int& numIgnoreExtensions) : archive(theArchive)
	{
tryagain:
		int numItems = archive.GetNumItems();
		for(int i = 0; i < numItems; i++)
		{
			if(archive.GetItemSize(i))
			{
				const char* name = archive.GetItemName(i);
				const char* ext = strrchr(name, '.');
				bool ok = true;
				if(ext++)
				{
					for(int j = 0; j < numIgnoreExtensions; j++)
					{
						const char* ext2 = ignoreExtensions[j];
						const char* wild = strchr(ext2, '*');
						if(!wild)
						{
							if(!_stricmp(ext, ext2))
							{
								ok = false;
								break;
							}
						}
						else // very limited (end only) wildcard support
						{
							if(!_strnicmp(ext, ext2, wild - ext2))
							{
								ok = false;
								break;
							}
						}
					}
				}
				if(ok)
				{
					ArchiveFileChooserInfo::FileInfo fi = { name, i };
					files.push_back(fi);
				}
			}
		}

		if(files.empty() && numIgnoreExtensions)
		{
			// try again without any exclusions if we excluded everything in the archive
			numIgnoreExtensions = 0;
			goto tryagain;
		}

		// strip away prefix paths that are common to all the files
		bool stripping = !files.empty();
		while(stripping)
		{
			const char* firstName = files[0].name.c_str();
			const char* slash = strchr(firstName, '\\');
			const char* slash2 = strchr(firstName, '/');
			slash = std::max(slash, slash2);
			if(!slash++)
				break;
			for(size_t i = 1; i < files.size(); i++)
				if(strncmp(firstName, files[i].name.c_str(), slash - firstName))
					stripping = false;
			if(stripping)
				for(size_t i = 0; i < files.size(); i++)
					files[i].name = files[i].name.substr(slash - firstName, files[i].name.length() - (slash - firstName));
		}

		// sort by filename
		std::sort(files.begin(), files.end(), FileInfo::Sort);
	}
Ejemplo n.º 29
0
int InternetDownloadFile (char *szUrl, char *cookie, char *userAgent, TCHAR **szData) 
{
	if (userAgent == NULL || userAgent[0] == 0)
		userAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
	
	NETLIBHTTPHEADER headers[5];
	headers[0].szName = "User-Agent";
	headers[0].szValue = userAgent;
	headers[1].szName = "Cache-Control";
	headers[1].szValue = "no-cache";
	headers[2].szName = "Pragma";
	headers[2].szValue = "no-cache";
	headers[3].szName = "Connection";
	headers[3].szValue = "close";
	headers[4].szName = "Cookie";
	headers[4].szValue = cookie;

	// initialize the netlib request
	NETLIBHTTPREQUEST nlhr = { sizeof(nlhr) };
	nlhr.requestType = REQUEST_GET;
	nlhr.flags = NLHRF_DUMPASTEXT | NLHRF_HTTP11 | NLHRF_PERSISTENT | NLHRF_REDIRECT;
	nlhr.szUrl = szUrl;
	nlhr.nlc = hNetlibHttp;
	nlhr.headers = headers;
	nlhr.headersCount = SIZEOF(headers);

	if (cookie == NULL || cookie[0] == 0)
		--nlhr.headersCount;

	// download the page
	NETLIBHTTPREQUEST *nlhrReply = (NETLIBHTTPREQUEST*)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)hNetlibUser, (LPARAM)&nlhr);
	if (nlhrReply == 0) {
	// if the data does not downloaded successfully (ie. disconnected), then return 1000 as error code
		*szData = (TCHAR*)mir_alloc(512);
		// store the error code in szData
		_tcscpy(*szData, _T("NetLib error occurred!!"));
		hNetlibHttp = NULL;
		return NLHRF_REDIRECT;
	}

	// if the recieved code is 200 OK
	int result;
	if (nlhrReply->resultCode == 200) {
		if (nlhrReply->dataLength) {
			bool bIsUtf = false;
			result = 0;

			// allocate memory and save the retrieved data
			int i = findHeader(nlhrReply, "Content-Type");
			if (i != -1 && strstr(_strlwr((char*)nlhrReply->headers[i].szValue), "utf-8"))
				bIsUtf = true;
			else {
				char* end = nlhrReply->pData;
				for (;;) {
					char* beg = strstr(end, "<meta");
					if (beg == NULL) break;
					else {
						char* method, tmp;
						end = strchr(beg, '>');
						tmp = *end; *end = 0;

						method = strstr(beg, "http-equiv=\"");
						if (method && _strnicmp(method+12, "Content-Type", 12) == 0 && strstr(method, "utf-8")) {
							bIsUtf = true;
							break;
						}
						else *end = tmp;
					}
				}
			}

			TCHAR *retVal = NULL;
			if (bIsUtf)
				retVal = mir_utf8decodeT( nlhrReply->pData );
			if (retVal == NULL)
				retVal = mir_a2t(nlhrReply->pData);
			*szData = retVal;
		}
		else result = DATA_EMPTY;
	}
	// return error code if the recieved code is neither 200 OK nor 302 Moved
	else {
		*szData = (TCHAR*)mir_alloc(512);
		// store the error code in szData
		mir_sntprintf(*szData, 512, _T("Error occured! HTTP Error: %i\n"), nlhrReply->resultCode);
		result = (int)nlhrReply->resultCode;
	}

	hNetlibHttp = nlhrReply->nlc;
	// make a copy of the retrieved data, then free the memory of the http reply
	CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT,0, (LPARAM)nlhrReply);
	return result;
}
Ejemplo n.º 30
0
extern "C" int __cdecl _mbsnicmp_l(
        const unsigned char *s1,
        const unsigned char *s2,
        size_t n,
        _locale_t plocinfo
        )
{
        unsigned short c1, c2;

        if (n==0)
            return(0);

        _LocaleUpdate _loc_update(plocinfo);
        if (_loc_update.GetLocaleT()->mbcinfo->ismbcodepage == 0)
            return _strnicmp((const char *)s1, (const char *)s2, n);

        /* validation section */
        _VALIDATE_RETURN(s1 != nullptr, EINVAL, _NLSCMPERROR);
        _VALIDATE_RETURN(s2 != nullptr, EINVAL, _NLSCMPERROR);

        while (n--) {

            c1 = *s1++;
            if ( _ismbblead_l(c1, _loc_update.GetLocaleT()) ) {
                if (*s1 == '\0')
                    c1 = 0;
                else {
                    c1 = ((c1<<8) | *s1++);

                    if ( ((c1 >= _MBUPPERLOW1_MT(_loc_update.GetLocaleT())) &&
                          (c1 <= _MBUPPERHIGH1_MT(_loc_update.GetLocaleT()))) )
                        c1 += _MBCASEDIFF1_MT(_loc_update.GetLocaleT());
                    else if ( ((c1 >= _MBUPPERLOW2_MT(_loc_update.GetLocaleT())) &&
                               (c1 <= _MBUPPERHIGH2_MT(_loc_update.GetLocaleT()))) )
                        c1 += _MBCASEDIFF2_MT(_loc_update.GetLocaleT());
                }
            }
            else
                c1 = _mbbtolower_l(c1, _loc_update.GetLocaleT());

            c2 = *s2++;
            if ( _ismbblead_l(c2, _loc_update.GetLocaleT()) ) {
                if (*s2 == '\0')
                    c2 = 0;
                else {
                    c2 = ((c2<<8) | *s2++);
                    if ( ((c2 >= _MBUPPERLOW1_MT(_loc_update.GetLocaleT())) &&
                          (c2 <= _MBUPPERHIGH1_MT(_loc_update.GetLocaleT()))) )
                        c2 += _MBCASEDIFF1_MT(_loc_update.GetLocaleT());
                    else if ( ((c2 >= _MBUPPERLOW2_MT(_loc_update.GetLocaleT())) &&
                               (c2 <= _MBUPPERHIGH2_MT(_loc_update.GetLocaleT()))) )
                        c2 += _MBCASEDIFF2_MT(_loc_update.GetLocaleT());
                }
            }
            else
                c2 = _mbbtolower_l(c2, _loc_update.GetLocaleT());

            if (c1 != c2)
                return( (c1 > c2) ? 1 : -1 );

            if (c1 == 0)
                return(0);
        }

        return(0);
}