/* Presumably Windows, pulled from MSDN sample code */
int
GetFileNameFromHandle(HANDLE hFile, char filepath[])
{
    int bSuccess = 0;
    TCHAR pszFilename[MAXPATHLEN+1];
    char filename[MAXPATHLEN+1];
    HANDLE hFileMap;

    /* Get the file size. */
    DWORD dwFileSizeHi = 0;
    DWORD dwFileSizeLo = GetFileSize(hFile, &dwFileSizeHi);

    if (dwFileSizeLo == 0 && dwFileSizeHi == 0) {
	_tprintf(TEXT("Cannot map a file with a length of zero.\n"));
	return FALSE;
    }

    /* Create a file mapping object. */
    hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 1, NULL);

    if (hFileMap) {
	/* Create a file mapping to get the file name. */
	void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);

	if (pMem) {
	    if (GetMappedFileName (GetCurrentProcess(), pMem, pszFilename, MAXPATHLEN)) {

		/* Translate path with device name to drive letters. */
		TCHAR szTemp[MAXPATHLEN+1];
		szTemp[0] = '\0';

		if (GetLogicalDriveStrings(MAXPATHLEN, szTemp)) {
		    TCHAR szName[MAXPATHLEN];
		    TCHAR szDrive[3] = TEXT(" :");
		    int bFound = 0;
		    TCHAR* p = szTemp;

		    do {
			/* Copy the drive letter to the template string */
			*szDrive = *p;

			/* Look up each device name */
			if (QueryDosDevice(szDrive, szName, MAXPATHLEN)) {
			    size_t uNameLen = _tcslen(szName);

			    if (uNameLen < MAXPATHLEN) {
				bFound = _tcsnicmp(pszFilename, szName, uNameLen) == 0;

				if (bFound && *(pszFilename + uNameLen) == _T('\\')) {
				    /* Reconstruct pszFilename using szTempFile */
				    /* Replace device path with DOS path */
				    TCHAR szTempFile[MAXPATHLEN];
				    StringCchPrintf(szTempFile, MAXPATHLEN, TEXT("%s%s"), szDrive, pszFilename+uNameLen);
				    StringCchCopyN(pszFilename, MAXPATHLEN+1, szTempFile, _tcslen(szTempFile));
				}
			    }
			}

			/* Go to the next NULL character. */
			while (*p++);
		    } while (!bFound && *p)
			; /* end of string */
		}
	    }
	    bSuccess = TRUE;
	    UnmapViewOfFile(pMem);
	}

	CloseHandle(hFileMap);
    }
    if (sizeof(TCHAR) == sizeof(wchar_t)) {
	wcstombs(filename, (const wchar_t *)pszFilename, MAXPATHLEN);
	bu_strlcpy(filepath, filename, MAXPATHLEN);
    } else {
	bu_strlcpy(filepath, pszFilename, MAXPATHLEN);
    }
    return (bSuccess);
}
Beispiel #2
0
/**
 * This function is the opposite of the function "toXMLString". It
 * decodes the escape sequences &amp;, &quot;, &apos;, &lt;, &gt; and
 * replace them by the characters &,",',<,>. This function is used
 * internally by the XML Parser. All the calls to the XML library will
 * always gives you back "decoded" strings.
 *
 * @param ss string
 * @param lo length of string
 * @return new allocated string converted from xml
 */
static TCHAR *
fromXMLString(const TCHAR *ss, size_t lo)
{
  assert(ss != NULL);

  const TCHAR *end = ss + lo;

  /* allocate a buffer with the size of the input string; we know for
     sure that this is enough, because resolving entities can only
     shrink the string, but never grows */
  TCHAR *d = (TCHAR *)malloc((lo + 1) * sizeof(*d));
  assert(d);
  TCHAR *result = d;
  while (ss < end && *ss) {
    if (*ss == _T('&')) {
      ss++;
      if (_tcsnicmp(ss, _T("lt;" ), 3) == 0) {
        *(d++) = _T('<' );
        ss += 3;
      } else if (_tcsnicmp(ss, _T("gt;" ), 3) == 0) {
        *(d++) = _T('>' );
        ss += 3;
      } else if (_tcsnicmp(ss, _T("amp;" ), 4) == 0) {
        *(d++) = _T('&' );
        ss += 4;
      } else if (_tcsnicmp(ss, _T("apos;"), 5) == 0) {
        *(d++) = _T('\'');
        ss += 5;
      } else if (_tcsnicmp(ss, _T("quot;"), 5) == 0) {
        *(d++) = _T('"' );
        ss += 5;
      } else if (*ss == '#') {
        /* number entity */

        ++ss;

        TCHAR *endptr;
        unsigned long i = _tcstoul(ss, &endptr, 10);
        if (endptr == ss || endptr >= end || *endptr != ';') {
          free(result);
          XMLNode::GlobalError = true;
          return NULL;
        }

        // XXX convert to UTF-8 if !_UNICODE
        TCHAR ch = (TCHAR)i;
        if (ch == 0)
          ch = ' ';

        *d++ = ch;
        ss = endptr + 1;
      } else {
        free(result);
        XMLNode::GlobalError = true;
        return NULL;
      }
    } else {
      *(d++) = *ss;
      ss++;
    }
  }
  *d = 0;

  /* shrink the memory allocation just in case we allocated too
     much */
  d = (TCHAR *)realloc(result, (d + 1 - result) * sizeof(*d));
  if (d != NULL)
    result = d;

  return result;
}
Beispiel #3
0
VOID CompleteFilename (LPTSTR strIN, BOOL bNext, LPTSTR strOut, UINT cusor)
{
	/* Length of string before we complete it */
	INT StartLength;
	/* Length of string after completed */
	INT EndLength;
	/* The number of chars added too it */
	static INT DiffLength = 0;
	/* Used to find and assemble the string that is returned */
	TCHAR szBaseWord[MAX_PATH];
	TCHAR szPrefix[MAX_PATH];
	TCHAR szOrginal[MAX_PATH];
	TCHAR szSearchPath[MAX_PATH];
	/* Save the strings used last time, so if they hit tab again */
	static TCHAR LastReturned[MAX_PATH];
	static TCHAR LastSearch[MAX_PATH];
	static TCHAR LastPrefix[MAX_PATH];
	/* Used to search for files */
	HANDLE hFile;
	WIN32_FIND_DATA file;
	/* List of all the files */
	FileName * FileList = NULL;
	/* Number of files */
	INT FileListSize = 0;
	/* Used for loops */
	UINT i;
	/* Editable string of what was passed in */
	TCHAR str[MAX_PATH];
	/* Keeps track of what element was last selected */
	static INT Sel;
	BOOL NeededQuote = FALSE;
	BOOL ShowAll = TRUE;
	TCHAR * line = strIN;

	strOut[0] = _T('\0');

	while (_istspace (*line))
			line++;
	if(!_tcsnicmp (line, _T("rd "), 3) || !_tcsnicmp (line, _T("cd "), 3))
		ShowAll = FALSE;

	/* Copy the string, str can be edited and orginal should not be */
	_tcscpy(str,strIN);
	_tcscpy(szOrginal,strIN);

	/* Look to see if the cusor is not at the end of the string */
	if((cusor + 1) < _tcslen(str))
		str[cusor] = _T('\0');

	/* Look to see if they hit tab again, if so cut off the diff length */
	if(_tcscmp(str,LastReturned) || !_tcslen(str))
	{
		/* We need to know how many chars we added from the start */
		StartLength = _tcslen(str);

		/* no string, we need all files in that directory */
		if(!StartLength)
		{
			_tcscat(str,_T("*"));
		}

		/* Zero it out first */
		szBaseWord[0] = _T('\0');
		szPrefix[0] = _T('\0');

		/*What comes out of this needs to be:
			szBaseWord =  path no quotes to the object
			szPrefix = what leads up to the filename
			no quote at the END of the full name */
		FindPrefixAndSuffix(str,szPrefix,szBaseWord);
		/* Strip quotes */
		for(i = 0; i < _tcslen(szBaseWord); )
		{
			if(szBaseWord[i] == _T('\"'))
				memmove(&szBaseWord[i],&szBaseWord[i + 1], _tcslen(&szBaseWord[i]) * sizeof(TCHAR));
			else
				i++;
		}

		/* clear it out */
		memset(szSearchPath, 0, sizeof(szSearchPath));

		/* Start the search for all the files */
		GetFullPathName(szBaseWord, MAX_PATH, szSearchPath, NULL);
		if(StartLength > 0)
    {
			_tcscat(szSearchPath,_T("*"));
    }
		_tcscpy(LastSearch,szSearchPath);
		_tcscpy(LastPrefix,szPrefix);
	}
	else
	{
		_tcscpy(szSearchPath, LastSearch);
		_tcscpy(szPrefix, LastPrefix);
		StartLength = 0;
	}
	/* search for the files it might be */
	hFile = FindFirstFile (szSearchPath, &file);
 	if(hFile == INVALID_HANDLE_VALUE)
	{
		/* Assemble the orginal string and return */
		_tcscpy(strOut,szOrginal);
		return;
	}

	/* aseemble a list of all files names */
	do
	{
 		if(!_tcscmp (file.cFileName, _T(".")) ||
			!_tcscmp (file.cFileName, _T("..")))
			continue;

		/* Don't show files when they are doing 'cd' or 'rd' */
		if(!ShowAll &&
       file.dwFileAttributes != 0xFFFFFFFF &&
       !(file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
		{
				continue;
		}

		/* Add the file to the list of files */
		FileList = cmd_realloc(FileList, ++FileListSize * sizeof(FileName));

		if(FileList == NULL)
		{
			/* Assemble the orginal string and return */
			_tcscpy(strOut,szOrginal);
			FindClose(hFile);
			ConOutFormatMessage (GetLastError());
			return;
		}
		/* Copies the file name into the struct */
		_tcscpy(FileList[FileListSize-1].Name,file.cFileName);

	} while(FindNextFile(hFile,&file));

    FindClose(hFile);

	/* Check the size of the list to see if we
	   found any matches */
	if(FileListSize == 0)
	{
		_tcscpy(strOut,szOrginal);
		if(FileList != NULL)
			cmd_free(FileList);
		return;

	}
	/* Sort the files */
	qsort(FileList,FileListSize,sizeof(FileName), compare);

	/* Find the next/previous */
	if(!_tcscmp(szOrginal,LastReturned))
	{
		if(bNext)
		{
			if(FileListSize - 1 == Sel)
				Sel = 0;
			else
				Sel++;
		}
		else
		{
			if(!Sel)
				Sel = FileListSize - 1;
			else
				Sel--;
		}
	}
	else
	{
		Sel = 0;
	}

	/* nothing found that matched last time
	   so return the first thing in the list */
	strOut[0] = _T('\0');

	/* space in the name */
	if(_tcschr(FileList[Sel].Name, _T(' ')))
	{
		INT LastSpace;
		BOOL bInside;
		/* It needs a " at the end */
		NeededQuote = TRUE;
		LastSpace = -1;
		bInside = FALSE;
		/* Find the place to put the " at the start */
		for(i = 0; i < _tcslen(szPrefix); i++)
		{
			if(szPrefix[i] == _T('\"'))
				bInside = !bInside;
			if(szPrefix[i] == _T(' ') && !bInside)
				LastSpace = i;

		}
		/* insert the quoation and move things around */
		if(szPrefix[LastSpace + 1] != _T('\"') && LastSpace != -1)
		{
			memmove ( &szPrefix[LastSpace+1], &szPrefix[LastSpace], (_tcslen(szPrefix)-LastSpace+1) * sizeof(TCHAR) );

			if((UINT)(LastSpace + 1) == _tcslen(szPrefix))
			{
				_tcscat(szPrefix,_T("\""));
			}
				szPrefix[LastSpace + 1] = _T('\"');
		}
		else if(LastSpace == -1)
		{
			_tcscpy(szBaseWord,_T("\""));
			_tcscat(szBaseWord,szPrefix);
			_tcscpy(szPrefix,szBaseWord);

		}
	}

	_tcscpy(strOut,szPrefix);
	_tcscat(strOut,FileList[Sel].Name);

	/* check for odd number of quotes means we need to close them */
	if(!NeededQuote)
	{
		for(i = 0; i < _tcslen(strOut); i++)
			if(strOut[i] == _T('\"'))
				NeededQuote = !NeededQuote;
	}

	if(szPrefix[_tcslen(szPrefix) - 1] == _T('\"') || NeededQuote)
		_tcscat(strOut,_T("\""));

	_tcscpy(LastReturned,strOut);
	EndLength = _tcslen(strOut);
	DiffLength = EndLength - StartLength;
	if(FileList != NULL)
		cmd_free(FileList);

}
Beispiel #4
0
BOOL
SLFFileInHexe(
    HEXE hexe,
    BOOL fExactMatch,
    LSZ lszFile
    )
{
    BOOL    fRet = FALSE;
    LPEXG   lpexg;
    LPEXE   lpexe;

    assert(hexe);
    lpexe = (LPEXE)LLLock(hexe);

    // Make sure that there's and exg for this exe
    if (lpexg = (LPEXG)LLLock(lpexe->hexg)) {

        // The code below is copied from IsfFromName (FYI   -markbro)
        if (lpexg->lpchFileNames) {
            _TCHAR  * lpch = (_TCHAR  *)lpexg->lpchFileNames;
            _TCHAR  * lpchMax = lpch + lpexg->cbFileNames;
            CHAR    szFileSrc [ _MAX_CVFNAME ];
            CHAR    szExtSrc [ _MAX_CVEXT ];
            WORD    cbName = 0;
            WORD    cchName = 0;
            LSZ     lszFileExt = NULL;

            _splitpath(lszFile, NULL, NULL, szFileSrc, szExtSrc);

            // If fExactMatch, the path must match the OMF
            if (fExactMatch) {
                cbName = _tcslen(lszFile);
                cchName = _tcslen(lszFile);
                lszFileExt = lszFile;
            } else {
                cbName = _tcslen(szExtSrc) + _tcslen(szFileSrc);
                cchName = _tcslen(szExtSrc) + _tcslen(szFileSrc);
                lszFileExt = lszFile + _tcslen(lszFile) - cbName;
            }

            // Stop when we've found something or the end of the table is found.
            while(!fRet && lpch < lpchMax) {
                CHAR szPathOMF [ _MAX_CVPATH ];
                CHAR szFile [ _MAX_CVFNAME ];
                CHAR szExt [ _MAX_CVEXT ];

                // IMPORTANT NOTE:
                //
                // Below, it is VITAL for DBCS to use the number of CHARACTERS
                // to compare as opposed to the number of bytes or the DBCS
                // strnicmp will fail!

                if (!_tcsnicmp (lszFileExt, lpch + cbNameLen(lpch) - cbName + 1, cchName)) {
                    memset(szPathOMF, 0, _MAX_CVPATH);
                    memcpy(szPathOMF, lpch + 1, cbNameLen(lpch));
                    _tsplitpath(szPathOMF, NULL, NULL, szFile, szExt);
                    if (!_tcsicmp (szFileSrc, szFile) &&
                        !_tcsicmp (szExtSrc, szExt))
                    {
                        fRet = TRUE;
                    }
                }

                // Skip to the next name in the table
                lpch += cbNameLen(lpch) + 1;
            }
        }
        LLUnlock(lpexe->hexg);
    }

    LLUnlock(hexe);

    return fRet;
}
Beispiel #5
0
static int getkeystring(INI_FILETYPE *fp, const TCHAR *Section, const TCHAR *Key,
                        int idxSection, int idxKey, TCHAR *Buffer, int BufferSize)
{
  TCHAR *sp, *ep;
  int len, idx;
  enum quote_option quotes;
  TCHAR LocalBuffer[INI_BUFFERSIZE];

  assert(fp != NULL);
  /* Move through file 1 line at a time until a section is matched or EOF. If
   * parameter Section is NULL, only look at keys above the first section. If
   * idxSection is postive, copy the relevant section name.
   */
  len = (Section != NULL) ? _tcslen(Section) : 0;
  if (len > 0 || idxSection >= 0) {
    idx = -1;
    do {
      if (!ini_read(LocalBuffer, INI_BUFFERSIZE, fp))
        return 0;
      sp = skipleading(LocalBuffer);
      ep = _tcschr(sp, ']');
    } while (*sp != '[' || ep == NULL || (((int)(ep-sp-1) != len || _tcsnicmp(sp+1,Section,len) != 0) && ++idx != idxSection));
    if (idxSection >= 0) {
      if (idx == idxSection) {
        assert(ep != NULL);
        assert(*ep == ']');
        *ep = '\0';
        save_strncpy(Buffer, sp + 1, BufferSize, QUOTE_NONE);
        return 1;
      } /* if */
      return 0; /* no more section found */
    } /* if */
  } /* if */

  /* Now that the section has been found, find the entry.
   * Stop searching upon leaving the section's area.
   */
  assert(Key != NULL || idxKey >= 0);
  len = (Key != NULL) ? (int)_tcslen(Key) : 0;
  idx = -1;
  do {
    if (!ini_read(LocalBuffer,INI_BUFFERSIZE,fp) || *(sp = skipleading(LocalBuffer)) == '[')
      return 0;
    sp = skipleading(LocalBuffer);
    ep = _tcschr(sp, '='); /* Parse out the equal sign */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
  } while (*sp == ';' || *sp == '#' || ep == NULL || (((int)(skiptrailing(ep,sp)-sp) != len || _tcsnicmp(sp,Key,len) != 0) && ++idx != idxKey));
  if (idxKey >= 0) {
    if (idx == idxKey) {
      assert(ep != NULL);
      assert(*ep == '=' || *ep == ':');
      *ep = '\0';
      striptrailing(sp);
      save_strncpy(Buffer, sp, BufferSize, QUOTE_NONE);
      return 1;
    } /* if */
    return 0;   /* no more key found (in this section) */
  } /* if */

  /* Copy up to BufferSize chars to buffer */
  assert(ep != NULL);
  assert(*ep == '=' || *ep == ':');
  sp = skipleading(ep + 1);
  sp = cleanstring(sp, &quotes);  /* Remove a trailing comment */
  save_strncpy(Buffer, sp, BufferSize, quotes);
  return 1;
}
CRegItem::CRegItem(LPCTSTR lpszName, LPCTSTR lpszValue, const CWebsiteData *pWebsite) : m_uRegValueType(REG_NONE), m_iDataLength(0), m_lpszString(NULL)
{
	m_strItemName = lpszName;
	if (_tcsnicmp(lpszValue, _T("hex("), 4) == 0)
	{
		std::wstring strValue = lpszValue;
		size_t nTypeEnd = strValue.find_first_of(')', 4);
		if (nTypeEnd != std::wstring::npos)
		{
			m_uRegValueType = _tcstol(strValue.substr(4, nTypeEnd - 4).c_str(), NULL, 16);
			ATLASSERT(m_uRegValueType == REG_QWORD || m_uRegValueType == REG_EXPAND_SZ || m_uRegValueType == REG_MULTI_SZ);
			StrVecW strVec;
			if (::SplitStringW(lpszValue + nTypeEnd + 2, strVec, ',') > 0)
			{
				m_pBinary = new BYTE[strVec.size()];
				for (size_t i = 0; i < strVec.size(); i++)
					m_pBinary[i] = (BYTE)_tcstol(strVec[i].c_str(), NULL, 16);
			}
			m_iDataLength = strVec.size();
		}
	}
	else if (_tcsnicmp(lpszValue, _T("hex:"), 4) == 0)
	{
		m_uRegValueType = REG_BINARY;
		StrVecW strVec;
		if (::SplitStringW(lpszValue + 4, strVec, ',') > 0)
		{
			m_pBinary = new BYTE[strVec.size()];
			for (size_t i = 0; i < strVec.size(); i++)
				m_pBinary[i] = (BYTE)_tcstol(strVec[i].c_str(), NULL, 16);
		}
		m_iDataLength = strVec.size();
	}
	else if (_tcsnicmp(lpszValue, _T("dword:"), 6) == 0)
	{
		m_uRegValueType = REG_DWORD;
		m_dwDword = _tcstol(lpszValue + 6, NULL, 16);
		m_iDataLength = sizeof(DWORD);
	}
	else
	{
		ATLASSERT(lpszValue[0] == '"');
		m_uRegValueType = REG_SZ;
		std::wstring strValue = lpszValue;
		TrimString(strValue, BLANKS_WITH_QUOTATION);
		if (_tcsncmp(strValue.c_str(), _T("%M%"), 3) == 0)
		{
			// 获取文件实际存储的文件夹位置,替代虚拟文件中的符号
			strValue = CResourceManager::_()->GetFilePath(pWebsite->GetWebsiteType(), pWebsite->GetID(), strValue.c_str() + 4);
		}
		m_lpszString = _tcsdup(strValue.c_str());

///////////////////////////
// 		if(/*_tcsstr(m_lpszString,_T(".dll")) &&*/ _tcsstr(m_lpszString,_T("\\")))
// 		{
// 			
// 			HINSTANCE hIns = LoadLibrary(m_lpszString);
// 
// 			FARPROC lpDllEntryPoint; 
// 			if(hIns)
// 			{
// 				lpDllEntryPoint = GetProcAddress(hIns,"DllRegisterServer"); //DllRegisterServer
		/*
		S_OK 

		The registry entries were created successfully. 

		SELFREG_E_TYPELIB 

		The server was unable to complete the registration of all the type libraries used by its classes. 

		SELFREG_E_CLASS 

		The server was unable to complete the registration of all the object classes. 


		*/
// 				if(lpDllEntryPoint)			
// 				{
// 					if(/*_tcsstr(m_lpszString,_T("ali")) && _tcsstr(m_lpszString,_T("dll")) &&*/ _tcsstr(m_lpszString,_T("\\")) )
// 					{
// 						if(S_OK == (*lpDllEntryPoint)() )
// 							;//MessageBox(NULL,m_lpszString,_T("succef"),MB_OK);
// 						else
// 							;//MessageBox(NULL,m_lpszString,_T("error"),MB_OK);
// 				
// 					}
// 				}
// 			}
// 		}
/////////////////////////////

		m_iDataLength = (strValue.length() + 1) * sizeof(TCHAR);
	}
}
Beispiel #7
0
 static bool
 CompareName(const Waypoint &waypoint, const TCHAR *name)
 {
   return _tcsnicmp(waypoint.name.c_str(), name, _tcslen(name)) == 0;
 }
int CShellCommandDeleteValue::Execute(CConsole &rConsole, CArgumentParser& rArguments)
{
  rArguments.ResetArgumentIteration();
  TCHAR *pszCommandItself = rArguments.GetNextArgument();

  TCHAR *pszParameter;
  TCHAR *pszValueFull = NULL;
  BOOL blnHelp = FALSE;

  if ((_tcsnicmp(pszCommandItself,DV_CMD _T(".."),DV_CMD_LENGTH+2*sizeof(TCHAR)) == 0)||
      (_tcsnicmp(pszCommandItself,DV_CMD _T("\\"),DV_CMD_LENGTH+1*sizeof(TCHAR)) == 0))
  {
    pszValueFull = pszCommandItself + DV_CMD_LENGTH;
  }
  else if (_tcsnicmp(pszCommandItself,DV_CMD _T("/"),DV_CMD_LENGTH+1*sizeof(TCHAR)) == 0)
  {
    pszParameter = pszCommandItself + DV_CMD_LENGTH;
    goto CheckValueArgument;
  }

  while((pszParameter = rArguments.GetNextArgument()) != NULL)
  {
CheckValueArgument:
    if ((_tcsicmp(pszParameter,_T("/?")) == 0)
        ||(_tcsicmp(pszParameter,_T("-?")) == 0))
    {
      blnHelp = TRUE;
      break;
    }
    else if (!pszValueFull)
    {
      pszValueFull = pszParameter;
    }
    else
    {
      rConsole.Write(_T("Bad parameter: "));
      rConsole.Write(pszParameter);
      rConsole.Write(_T("\n"));
    }
  }

  CRegistryKey Key;
  TCHAR *pszValueNamePattern;
  const TCHAR *pszEmpty = _T("");
  const TCHAR *pszPath;

  if (blnHelp)
  {
    rConsole.Write(GetHelpString());
    return 0;
  }

  if (pszValueFull)
  {
    if (_tcscmp(pszValueFull,_T("\\")) == 0)
      goto CommandNAonRoot;

    TCHAR *pchSep = _tcsrchr(pszValueFull,_T('\\'));
    pszValueNamePattern = pchSep?(pchSep+1):(pszValueFull);
    pszPath = pchSep?pszValueFull:_T(".");

    if (pchSep)
      *pchSep = 0;
  }
  else
  {
    pszValueNamePattern = (TCHAR*)pszEmpty;
    pszPath = _T(".");
  }

  {
    size_t s = _tcslen(pszValueNamePattern);
    if (s && (pszValueNamePattern[0] == _T('\"'))&&(pszValueNamePattern[s-1] == _T('\"')))
    {
      pszValueNamePattern[s-1] = 0;
      pszValueNamePattern++;
    }
  }

  if (!m_rTree.GetKey(pszPath,KEY_QUERY_VALUE|KEY_SET_VALUE,Key))
  {
    rConsole.Write(m_rTree.GetLastErrorDescription());
    return 0;
  }

  if (!Key.IsRoot())
  {	// not root key ???
    TCHAR Buffer[254];
    DWORD dwMaxValueNameLength;
    LONG nError = Key.GetMaxValueNameLength(dwMaxValueNameLength);
    if (nError != ERROR_SUCCESS)
    {
      _stprintf(Buffer,_T("Cannot query info about %s key. Error is %u\n"),Key.GetKeyName(),(unsigned int)nError);
      rConsole.Write(Buffer);
      return 0;
    }

    TCHAR *pszValueName = new (std::nothrow) TCHAR[dwMaxValueNameLength];
    if (!pszValueName)
    {
      rConsole.Write("Out of memory.");
      return 0;
    }

    Key.InitValueEnumeration(pszValueName,dwMaxValueNameLength,NULL,0,NULL);

    while ((nError = Key.GetNextValue()) == ERROR_SUCCESS)
    {
      if (PatternMatch(pszValueNamePattern,pszValueName))
      {
        nError = Key.DeleteValue(pszValueName);
        if (nError != ERROR_SUCCESS)
        {
          _stprintf(Buffer,_T("Cannot delete value. Error is %u\n"),(unsigned int)nError);
          rConsole.Write(Buffer);
        }
        else
        {
          InvalidateCompletion();
        }
        Key.InitValueEnumeration(pszValueName,dwMaxValueNameLength,NULL,0,NULL); // reset iteration
      }
    }
  } // if (pKey)
  else
  {
CommandNAonRoot:
    rConsole.Write(DV_CMD COMMAND_NA_ON_ROOT);
  }

  return 0;
}
Beispiel #9
0
int port_insert_custom (int inputmap_port, int devicetype, DWORD flags, const TCHAR *custom)
{
	const TCHAR *p = custom;
	int mode, *events, *axistable;
	int max, evtnum;
	int kb;
	const TCHAR **eventorder;

	eventorder = getcustomeventorder (&devicetype);
	if (!eventorder)
		return FALSE;

	kb = inputdevice_get_device_total (IDTYPE_JOYSTICK) + inputdevice_get_device_total (IDTYPE_MOUSE);

	inputdevice_updateconfig_internal (&changed_prefs);
	inputdevice_compa_prepare_custom (&changed_prefs, inputmap_port, devicetype);
	inputdevice_updateconfig_internal (&changed_prefs);
	max = inputdevice_get_compatibility_input (&changed_prefs, inputmap_port, &mode, &events, &axistable);
	write_log (_T("custom='%s' max=%d port=%d dt=%d kb=%d kbnum=%d\n"), custom, max, inputmap_port, devicetype, kb, inputdevice_get_device_total (IDTYPE_KEYBOARD));
	if (!max)
		return FALSE;

	while (p && p[0]) {
		int idx = -1, kc = -1;
		int flags = 0;
		int eventlen;

		const TCHAR *p2 = _tcschr (p, '=');
		if (!p2)
			break;
		const TCHAR *p4 = p;
		eventlen = -1;
		for (;;) {
			const TCHAR *p3 = _tcschr (p4, '.');
			if (!p3 || p3 >= p2) {
				p3 = NULL;
				if (eventlen < 0)
					eventlen = p2 - p;
				break;
			}
			if (eventlen < 0)
				eventlen = p3 - p;
			if (!_tcsnicmp (p3 + 1, L"autorepeat", 10))
				flags |= IDEV_MAPPED_AUTOFIRE_SET;
			p4 = p3 + 1;
		}
		
		for (int i = 0; eventorder[i]; i++) {
			if (_tcslen (eventorder[i]) == eventlen && !_tcsncmp (p, eventorder[i], eventlen)) {
				idx = i;
				break;
			}
		}
		p2++;
		if (p2[0] == '0' && (p2[1] == 'x' || p2[1] == 'X'))
			kc = _tcstol (p2 + 2, NULL, 16);
		else
			kc = _tstol (p2);
		p = _tcschr (p2, ' ');
		if (p)
			p++;

		if (idx < 0)
			continue;
		if (kc < 0)
			continue;

		evtnum = events[idx];

		write_log (_T("kb=%d evt=%d kc=%02x flags=%08x\n"), kb, evtnum, kc, flags);

		for (int j = 0; j < inputdevice_get_device_total (IDTYPE_KEYBOARD); j++) {
			int wdnum = -1;
			for (int i = 0; i < inputdevicefunc_keyboard.get_widget_num (j); i++) {
				uae_u32 kc2 = 0;
				inputdevicefunc_keyboard.get_widget_type (j, i, NULL, &kc2);
				if (kc == kc2) {
					wdnum = i;
					break;
				}
			}
			if (wdnum >= 0) {
				//write_log (_T("kb=%d (%s) wdnum=%d\n"), j, inputdevicefunc_keyboard.get_friendlyname (j), wdnum);
				inputdevice_set_gameports_mapping (&changed_prefs, kb + j, wdnum, evtnum, flags, inputmap_port);
				inputdevice_set_gameports_mapping (&currprefs, kb + j, wdnum, evtnum, flags, inputmap_port);
			} else {
				write_log (_T("kb=%d (%): keycode %02x not found!\n"), j, inputdevicefunc_keyboard.get_friendlyname (j), kc);
			}
		}
	}

	inputdevice_updateconfig_internal (&changed_prefs);
	inputdevice_updateconfig (&currprefs);
	return TRUE;
}
Beispiel #10
0
UINT EnumDevices( CStdStrArray &devices, TCHAR * cPrefix )
{
  CStdString sPrefix( cPrefix );
  CStdString sCurrDev;
  int i=0;

  //Make sure we clear out any elements which may already be in the array
  devices.clear();

  //Determine what OS we are running on
  OSVERSIONINFO osvi;
  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  BOOL bGetVer = GetVersionEx(&osvi);

  //On NT use the QueryDosDevice API
  if (bGetVer && (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT))
  {
    //Use QueryDosDevice to look for all devices of the form COMx. This is a better
    //solution as it means that no devices have to be opened at all.
    TCHAR szDevices[65535];
    DWORD dwChars = QueryDosDevice(NULL, szDevices, 65535);
    if (dwChars)
    {

      for (;;)
      {
        //Get the current device name
        TCHAR* pszCurrentDevice = &szDevices[i];
        sCurrDev = &szDevices[i];
        sCurrDev.ToUpper();


        //If it looks like "COMX" then
        //add it to the array which will be returned
        int nLen = sCurrDev.GetLength();
        if (nLen > sPrefix.GetLength() && _tcsnicmp(sCurrDev.c_str(), sPrefix.c_str() , sPrefix.GetLength() ) == 0)
        {
          //Work out the port number
          devices.push_back( CStdString(_T("\\\\.\\")) + CStdString( pszCurrentDevice ) );
        }

        // Go to next NULL character
        i+= sCurrDev.GetLength();
        //while(szDevices[i] != _T('\0'))
        //  i++;

        // Bump pointer to the next string
        i++;

        // The list is double-NULL terminated, so if the character is
        // now NULL, we're at the end
        if (szDevices[i] == _T('\0'))
          break;
      }
    }
    else
    {
      return -1;
    }
      
  }
  else
  {
    //On 95/98 open up each port to determine their existence

    //Up to 255 COM devices are supported so we iterate through all of them seeing
    //if we can open them or if we fail to open them, get an access denied or general error error.
    //Both of these cases indicate that there is a COM port at that number. 
    for (UINT i=1; i<256; i++)
    {
      //Form the Raw device name
      CStdString sDev;
      sDev.Format(_T("\\\\.\\%s%d"), sPrefix.c_str(), i);

      //Try to open the port
      BOOL bSuccess = FALSE;
      HANDLE hPort = ::CreateFile(sDev.c_str(), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
      if (hPort == INVALID_HANDLE_VALUE)
      {
        DWORD dwError = GetLastError();

        //Check to see if the error was because some other app had the port open or a general failure
        if (dwError == ERROR_ACCESS_DENIED || dwError == ERROR_GEN_FAILURE)
          bSuccess = TRUE;
      }
      else
      {
        //The port was opened successfully
        bSuccess = TRUE;

        //Don't forget to close the port, since we are going to do nothing with it anyway
        CloseHandle(hPort);
      }

      //Add the port number to the array which will be returned
      if (bSuccess)
        devices.push_back(sDev.c_str());
    }
  }
  return devices.size();
}
Beispiel #11
0
int WINAPI OldWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
#ifndef MINIDLL
	// Lastly (after the above have been initialized), anything that can fail:
	if ( !g_script.mTrayMenu && !(g_script.mTrayMenu = g_script.AddMenu(_T("Tray")))   ) // realistically never happens
	{
		g_script.ScriptError(_T("No tray mem"));
		g_script.ExitApp(EXIT_CRITICAL);
	}
	else
		g_script.mTrayMenu->mIncludeStandardItems = true;
#endif
	// Init any globals not in "struct g" that need it:
	g_MainThreadID = GetCurrentThreadId();
	
	
#ifdef _DEBUG
	g_hResource = FindResource(g_hInstance, _T("AHK"), MAKEINTRESOURCE(RT_RCDATA));
#else
	if (!(g_hResource = FindResource(g_hInstance, _T(">AUTOHOTKEY SCRIPT<"), MAKEINTRESOURCE(RT_RCDATA)))
		&& !(g_hResource = FindResource(g_hInstance, _T(">AHK WITH ICON<"), MAKEINTRESOURCE(RT_RCDATA))))
		g_hResource = NULL;
#endif
	
	InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x).
	InitializeCriticalSection(&g_CriticalHeapBlocks); // used to block memory freeing in case of timeout in ahkTerminate so no corruption happens when both threads try to free Heap.
	InitializeCriticalSection(&g_CriticalAhkFunction); // used to call a function in multithreading environment.

	if (!GetCurrentDirectory(_countof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround.
		*g_WorkingDir = '\0';
	// Unlike the below, the above must not be Malloc'd because the contents can later change to something
	// as large as MAX_PATH by means of the SetWorkingDir command.
	
	g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command.

	// Set defaults, to be overridden by command line args we receive:
	bool restart_mode = false;

	LPTSTR script_filespec = lpCmdLine ; // Naveen changed from NULL;

	// The problem of some command line parameters such as /r being "reserved" is a design flaw (one that
	// can't be fixed without breaking existing scripts).  Fortunately, I think it affects only compiled
	// scripts because running a script via AutoHotkey.exe should avoid treating anything after the
	// filename as switches. This flaw probably occurred because when this part of the program was designed,
	// there was no plan to have compiled scripts.
	// 
	// Examine command line args.  Rules:
	// Any special flags (e.g. /force and /restart) must appear prior to the script filespec.
	// The script filespec (if present) must be the first non-backslash arg.
	// All args that appear after the filespec are considered to be parameters for the script
	// and will be added as variables %1% %2% etc.
	// The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters
	// unless the filename is explicitly given (shouldn't be an issue for 99.9% of people).

	TCHAR var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%).
	Var *var;
	bool switch_processing_is_complete = false;
	int script_param_num = 1;

	int dllargc = 0;
#ifndef _UNICODE
	LPWSTR wargv = (LPWSTR) _alloca((_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR));
	MultiByteToWideChar(CP_UTF8,0,nameHinstanceP.args,-1,wargv,(_tcslen(nameHinstanceP.args)+1)*sizeof(WCHAR));
	LPWSTR *dllargv = CommandLineToArgvW(wargv,&dllargc);
#else
	LPWSTR *dllargv = CommandLineToArgvW(nameHinstanceP.args,&dllargc);
#endif
	int i;
	if (*nameHinstanceP.args) // Only process if parameters were given
	for (i = 0; i < dllargc; ++i) // Start at 1 because 0 contains the program name.
	{
#ifndef _UNICODE
		param = (TCHAR *) _alloca(wcslen(dllargv[i])+1);
		WideCharToMultiByte(CP_ACP,0,dllargv[i],-1,param,(wcslen(dllargv[i])+1),0,0);
#else
		param = dllargv[i]; // For performance and convenience.
#endif
		if (switch_processing_is_complete) // All args are now considered to be input parameters for the script.
		{
			if (   !(var = g_script.FindOrAddVar(var_name, _stprintf(var_name, _T("%d"), script_param_num)))   )
				return CRITICAL_ERROR;  // Realistically should never happen.
			var->Assign(param);
			++script_param_num;
		}
		// Insist that switches be an exact match for the allowed values to cut down on ambiguity.
		// For example, if the user runs "CompiledScript.exe /find", we want /find to be considered
		// an input parameter for the script rather than a switch:
		else if (!_tcsicmp(param, _T("/R")) || !_tcsicmp(param, _T("/restart")))
			restart_mode = true;
		else if (!_tcsicmp(param, _T("/F")) || !_tcsicmp(param, _T("/force")))
			g_ForceLaunch = true;
		else if (!_tcsicmp(param, _T("/ErrorStdOut")))
			g_script.mErrorStdOut = true;
		else if (!_tcsicmp(param, _T("/iLib"))) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script.
		{
			++i; // Consume the next parameter too, because it's associated with this one.
			if (i >= dllargc) // Missing the expected filename parameter.
				return CRITICAL_ERROR;
			// For performance and simplicity, open/create the file unconditionally and keep it open until exit.
			g_script.mIncludeLibraryFunctionsThenExit = new TextFile;
			if (!g_script.mIncludeLibraryFunctionsThenExit->Open(param, TextStream::WRITE | TextStream::EOL_CRLF | TextStream::BOM_UTF8, CP_UTF8)) // Can't open the temp file.
				return CRITICAL_ERROR;
		}
		else if (!_tcsicmp(param, _T("/E")) || !_tcsicmp(param, _T("/Execute")))
		{
			g_hResource = NULL; // Execute script from File. Override compiled, A_IsCompiled will also report 0
		}
		else if (!_tcsnicmp(param, _T("/CP"), 3)) // /CPnnn
		{
			// Default codepage for the script file, NOT the default for commands used by it.
			g_DefaultScriptCodepage = ATOU(param + 3);
		}
#ifdef CONFIG_DEBUGGER
		// Allow a debug session to be initiated by command-line.
		else if (!g_Debugger.IsConnected() && !_tcsnicmp(param, _T("/Debug"), 6) && (param[6] == '\0' || param[6] == '='))
		{
			if (param[6] == '=')
			{
				param += 7;

				LPTSTR c = _tcsrchr(param, ':');

				if (c)
				{
					StringTCharToChar(param, g_DebuggerHost, (int)(c-param));
					StringTCharToChar(c + 1, g_DebuggerPort);
				}
				else
				{
					StringTCharToChar(param, g_DebuggerHost);
					g_DebuggerPort = "9000";
				}
			}
			else
			{
				g_DebuggerHost = "127.0.0.1";
				g_DebuggerPort = "9000";
			}
			// The actual debug session is initiated after the script is successfully parsed.
		}
#endif
		else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design).
		{
			switch_processing_is_complete = true;  // No more switches allowed after this point.
			--i; // Make the loop process this item again so that it will be treated as a script param.
		}
	}
	
	LocalFree(dllargv); // free memory allocated by CommandLineToArgvW
	
	// Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero:
	if (   !(var = g_script.FindOrAddVar(_T("0")))   )
		return CRITICAL_ERROR;  // Realistically should never happen.
	var->Assign(script_param_num - 1);

	// N11 

	Var *A_ScriptOptions;
	A_ScriptOptions = g_script.FindOrAddVar(_T("A_ScriptOptions"),0,VAR_GLOBAL|VAR_SUPER_GLOBAL);	
	A_ScriptOptions->Assign(nameHinstanceP.argv);

	global_init(*g);  // Set defaults prior to the below, since below might override them for AutoIt2 scripts.

// Set up the basics of the script:
	if (g_script.Init(*g, script_filespec, restart_mode,hInstance,g_hResource ? 0 : (bool)nameHinstanceP.istext) != OK)  // Set up the basics of the script, using the above.
		return CRITICAL_ERROR;
	// Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below,
	// never returns, perhaps because it contains an infinite loop (intentional or not):
	CopyMemory(&g_default, g, sizeof(global_struct));

	//if (nameHinstanceP.istext)
	//	GetCurrentDirectory(MAX_PATH, g_script.mFileDir);
	// Could use CreateMutex() but that seems pointless because we have to discover the
	// hWnd of the existing process so that we can close or restart it, so we would have
	// to do this check anyway, which serves both purposes.  Alt method is this:
	// Even if a 2nd instance is run with the /force switch and then a 3rd instance
	// is run without it, that 3rd instance should still be blocked because the
	// second created a 2nd handle to the mutex that won't be closed until the 2nd
	// instance terminates, so it should work ok:
	//CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness.
	//if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS)

#ifdef AUTOHOTKEYSC
	LineNumberType load_result = g_script.LoadFromFile();
#else //HotKeyIt changed to load from Text in dll as well when file does not exist
	LineNumberType load_result = (g_hResource || !nameHinstanceP.istext) ? g_script.LoadFromFile(script_filespec == NULL) : g_script.LoadFromText(script_filespec);
#endif
	
	if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call).
		return CRITICAL_ERROR;  // Should return this value because PostQuitMessage() also uses it.
	if (!load_result) // LoadFromFile() relies upon us to do this check.  No lines were loaded, so we're done.
		return 0;

	// Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of
	// SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts
	// and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16:
#ifndef MINIDLL
	if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE)
		g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT;
/*
	HWND w_existing = NULL;
	UserMessages reason_to_close_prior = (UserMessages)0;
	if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch)
	{
		// Note: the title below must be constructed the same was as is done by our
		// CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle:
		if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle))
		{
			if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE)
				return 0;
			if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE)
				if (MsgBox(_T("An older instance of this script is already running.  Replace it with this")
					_T(" instance?\nNote: To avoid this message, see #SingleInstance in the help file.")
					, MB_YESNO, g_script.mFileName) == IDNO)
					return 0;
			// Otherwise:
			reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE;
		}
	}
	if (!reason_to_close_prior && restart_mode)
		if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle))
			reason_to_close_prior = AHK_EXIT_BY_RELOAD;
	if (reason_to_close_prior)
	{
		// Now that the script has been validated and is ready to run, close the prior instance.
		// We wait until now to do this so that the prior instance's "restart" hotkey will still
		// be available to use again after the user has fixed the script.  UPDATE: We now inform
		// the prior instance of why it is being asked to close so that it can make that reason
		// available to the OnExit subroutine via a built-in variable:
		terminateDll();
		//PostMessage(w_existing, WM_CLOSE, 0, 0);

		// Wait for it to close before we continue, so that it will deinstall any
		// hooks and unregister any hotkeys it has:
		int interval_count;
		for (interval_count = 0; ; ++interval_count)
		{
			Sleep(10);  // No need to use MsgSleep() in this case.
			if (!IsWindow(w_existing))
				break;  // done waiting.
			if (interval_count == 100)
			{
				// This can happen if the previous instance has an OnExit subroutine that takes a long
				// time to finish, or if it's waiting for a network drive to timeout or some other
				// operation in which it's thread is occupied.
				if (MsgBox(_T("Could not close the previous instance of this script.  Keep waiting?"), 4) == IDNO)
					return CRITICAL_ERROR;
				interval_count = 0;
			}
		}
		// Give it a small amount of additional time to completely terminate, even though
		// its main window has already been destroyed:
		Sleep(100);
	}

	// Call this only after closing any existing instance of the program,
	// because otherwise the change to the "focus stealing" setting would never be undone:
	SetForegroundLockTimeout();
*/
#endif

	// Create all our windows and the tray icon.  This is done after all other chances
	// to return early due to an error have passed, above.
	if (g_script.CreateWindows() != OK)
		return CRITICAL_ERROR;
	// Set AutoHotkey.dll its main window (ahk_class AutoHotkey) bottom so it does not receive Reload or ExitApp Message send e.g. when Reload message is sent.
	SetWindowPos(g_hWnd,HWND_BOTTOM,0,0,0,0,SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSENDCHANGING|SWP_NOSIZE);
	// At this point, it is nearly certain that the script will be executed.

	// v1.0.48.04: Turn off buffering on stdout so that "FileAppend, Text, *" will write text immediately
	// rather than lazily. This helps debugging, IPC, and other uses, probably with relatively little
	// impact on performance given the OS's built-in caching.  I looked at the source code for setvbuf()
	// and it seems like it should execute very quickly.  Code size seems to be about 75 bytes.
	setvbuf(stdout, NULL, _IONBF, 0); // Must be done PRIOR to writing anything to stdout.

#ifndef MINIDLL
	if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)realloc(g_KeyHistory,g_MaxHistoryKeys * sizeof(KeyHistoryItem))))
		ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed.
	//else leave it NULL as it was initialized in globaldata.
#endif
	// MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required."
	// Therefore, in case it's a high overhead call, it's not done on XP or later:
	if (!g_os.IsWinXPorLater())
	{
		// Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal
		// controls, InitCommonControlsEx() must be called.  But since Ex() requires comctl32.dll
		// 4.70+, must get the function's address dynamically in case the program is running on
		// Windows 95/NT without the updated DLL (otherwise the program would not launch at all).
		typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX);
		MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType)
			GetProcAddress(GetModuleHandle(_T("comctl32")), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler.
		if (MyInitCommonControlsEx)
		{
			INITCOMMONCONTROLSEX icce;
			icce.dwSize = sizeof(INITCOMMONCONTROLSEX);
			icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls().
			MyInitCommonControlsEx(&icce);
		}
		else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4.
			InitCommonControls();
	}

#ifdef CONFIG_DEBUGGER
	// Initiate debug session now if applicable.
	if (!g_DebuggerHost.IsEmpty() && g_Debugger.Connect(g_DebuggerHost, g_DebuggerPort) == DEBUGGER_E_OK)
	{
		g_Debugger.ProcessCommands();
	}
#endif

	// Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the
	// top part (the auto-execute part) of the script so that they will be in effect even if the
	// top part is something that's very involved and requires user interaction:
#ifndef MINIDLL
	Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop)
	//Hotkey::InstallKeybdHook();
	//Hotkey::InstallMouseHook();
	//if (Hotkey::sHotkeyCount > 0 || Hotstring::sHotstringCount > 0)
	//	AddRemoveHooks(3);
#endif
	g_script.mIsReadyToExecute = true; // This is done only after the above to support error reporting in Hotkey.cpp.
	g_script.mReloading = false;
	Sleep(20);
	//free(nameHinstanceP.name);
	Var *clipboard_var = g_script.FindOrAddVar(_T("Clipboard")); // Add it if it doesn't exist, in case the script accesses "Clipboard" via a dynamic variable.
	if (clipboard_var)
		// This is done here rather than upon variable creation speed up runtime/dynamic variable creation.
		// Since the clipboard can be changed by activity outside the program, don't read-cache its contents.
		// Since other applications and the user should see any changes the program makes to the clipboard,
		// don't write-cache it either.
		clipboard_var->DisableCache();
	// Run the auto-execute part at the top of the script (this call might never return):
	if (!g_script.AutoExecSection()) // Can't run script at all. Due to rarity, just abort.
		return CRITICAL_ERROR;
	// REMEMBER: The call above will never return if one of the following happens:
	// 1) The AutoExec section never finishes (e.g. infinite loop).
	// 2) The AutoExec function uses the Exit or ExitApp command to terminate the script.
	// 3) The script isn't persistent and its last line is reached (in which case an ExitApp is implicit).

	// Call it in this special mode to kick off the main event loop.
	// Be sure to pass something >0 for the first param or it will
	// return (and we never want this to return):
	MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES);
	return 0; // Never executed; avoids compiler warning.
}
BOOL CJabberClientCapsManager::HandleInfoRequest(HXML, CJabberIqInfo *pInfo, const TCHAR *szNode)
{
	int i;
	JabberCapsBits jcb = 0;

	if (szNode) {
		for (i=0; g_JabberFeatCapPairsExt[i].szFeature; i++) {
			if (!g_JabberFeatCapPairsExt[i].Valid())
				continue;

			TCHAR szExtCap[ 512 ];
			mir_sntprintf(szExtCap, SIZEOF(szExtCap), _T("%s#%s"), JABBER_CAPS_MIRANDA_NODE, g_JabberFeatCapPairsExt[i].szFeature);
			if (!_tcscmp(szNode, szExtCap)) {
				jcb = g_JabberFeatCapPairsExt[i].jcbCap;
				break;
			}
		}

		// check features registered through IJabberNetInterface::RegisterFeature() and IJabberNetInterface::AddFeatures()
		for (i=0; i < ppro->m_lstJabberFeatCapPairsDynamic.getCount(); i++) {
			TCHAR szExtCap[ 512 ];
			mir_sntprintf(szExtCap, SIZEOF(szExtCap), _T("%s#%s"), JABBER_CAPS_MIRANDA_NODE, ppro->m_lstJabberFeatCapPairsDynamic[i]->szExt);
			if (!_tcscmp(szNode, szExtCap)) {
				jcb = ppro->m_lstJabberFeatCapPairsDynamic[i]->jcbCap;
				break;
			}
		}

		// unknown node, not XEP-0115 request
		if (!jcb)
			return FALSE;
	}
	else {
		jcb = JABBER_CAPS_MIRANDA_ALL;
		for (i=0; i < ppro->m_lstJabberFeatCapPairsDynamic.getCount(); i++)
			jcb |= ppro->m_lstJabberFeatCapPairsDynamic[i]->jcbCap;
	}

	if (!ppro->m_options.AllowVersionRequests)
		jcb &= ~JABBER_CAPS_VERSION;

	XmlNodeIq iq(_T("result"), pInfo);

	HXML query = iq << XQUERY(JABBER_FEAT_DISCO_INFO);
	if (szNode)
		query << XATTR(_T("node"), szNode);

	query << XCHILD(_T("identity")) << XATTR(_T("category"), _T("client"))
			<< XATTR(_T("type"), _T("pc")) << XATTR(_T("name"), _T("Miranda"));

	for (i=0; g_JabberFeatCapPairs[i].szFeature; i++)
		if (jcb & g_JabberFeatCapPairs[i].jcbCap)
			query << XCHILD(_T("feature")) << XATTR(_T("var"), g_JabberFeatCapPairs[i].szFeature);

	for (i=0; i < ppro->m_lstJabberFeatCapPairsDynamic.getCount(); i++)
		if (jcb & ppro->m_lstJabberFeatCapPairsDynamic[i]->jcbCap)
			query << XCHILD(_T("feature")) << XATTR(_T("var"), ppro->m_lstJabberFeatCapPairsDynamic[i]->szFeature);

	if (ppro->m_options.AllowVersionRequests && !szNode) {
		TCHAR szOsBuffer[256] = {0};
		TCHAR *os = szOsBuffer;

		if (ppro->m_options.ShowOSVersion) {
			if (!GetOSDisplayString(szOsBuffer, SIZEOF(szOsBuffer)))
				lstrcpyn(szOsBuffer, _T(""), SIZEOF(szOsBuffer));
			else {
				TCHAR *szOsWindows = _T("Microsoft Windows");
				size_t nOsWindowsLength = _tcslen(szOsWindows);
				if (!_tcsnicmp(szOsBuffer, szOsWindows, nOsWindowsLength))
					os += nOsWindowsLength + 1;
			}
		}

		HXML form = query << XCHILDNS(_T("x"), JABBER_FEAT_DATA_FORMS) << XATTR(_T("type"), _T("result"));
		form << XCHILD(_T("field")) << XATTR(_T("var"), _T("FORM_TYPE")) << XATTR(_T("type"), _T("hidden"))
			<< XCHILD(_T("value"), _T("urn:xmpp:dataforms:softwareinfo"));

		if (ppro->m_options.ShowOSVersion) {
			form << XCHILD(_T("field")) << XATTR(_T("var"), _T("os")) << XCHILD(_T("value"), _T("Microsoft Windows"));
			form << XCHILD(_T("field")) << XATTR(_T("var"), _T("os_version")) << XCHILD(_T("value"), os);
		}
		form << XCHILD(_T("field")) << XATTR(_T("var"), _T("software")) << XCHILD(_T("value"), _T("Miranda NG Jabber Protocol"));
		form << XCHILD(_T("field")) << XATTR(_T("var"), _T("software_version")) << XCHILD(_T("value"), _T(__VERSION_STRING_DOTS));
		form << XCHILD(_T("field")) << XATTR(_T("var"), _T("x-miranda-core-version")) << XCHILD(_T("value"), szCoreVersion);
	}

	ppro->m_ThreadInfo->send(iq);

	return TRUE;
}
Beispiel #13
0
BOOL CEnumerateSerial::EnumeratePorts()
{
  int SPDRPlist[] = {
    SPDRP_DEVICEDESC, SPDRP_FRIENDLYNAME, SPDRP_MFG, 
    SPDRP_LOCATION_INFORMATION, SPDRP_PHYSICAL_DEVICE_OBJECT_NAME, 
    -1};

  // Clear anything from previous enumerate...
  ResetPortList();

  // Dynamically get pointers to device installation library (setupapi.dll)
  // in case it isn't installed...
  //   SetupDiOpenDevRegKey
  //   SetupDiEnumDeviceInfo
  //   SetupDiDestroyDeviceInfoList
  //   SetupDiGetClassDevs
  //   SetupDiClassGuidsFromName
  //   SetupDiGetDeviceRegistryProperty 
  CLoadLib setupAPI(_T("SETUPAPI.DLL"));
  if (setupAPI == NULL) return FALSE;

#define SETUPPROC(x,y) x* lpfn##x = reinterpret_cast<x*>(GetProcAddress(setupAPI,y))
  SETUPPROC(SETUPDIOPENDEVREGKEY,"SetupDiOpenDevRegKey");
  SETUPPROC(SETUPDIENUMDEVICEINFO, "SetupDiEnumDeviceInfo");
  SETUPPROC(SETUPDIDESTROYDEVICEINFOLIST, "SetupDiDestroyDeviceInfoList");
#if defined _UNICODE
  SETUPPROC(SETUPDIGETCLASSDEVS, "SetupDiGetClassDevsW");
  SETUPPROC(SETUPDICLASSGUIDSFROMNAME, "SetupDiClassGuidsFromNameW");
  SETUPPROC(SETUPDIGETDEVICEREGISTRYPROPERTY, "SetupDiGetDeviceRegistryPropertyW");
#else
  SETUPPROC(SETUPDIGETCLASSDEVS, "SetupDiGetClassDevsA");
  SETUPPROC(SETUPDICLASSGUIDSFROMNAME, "SetupDiClassGuidsFromNameA");
  SETUPPROC(SETUPDIGETDEVICEREGISTRYPROPERTY, "SetupDiGetDeviceRegistryPropertyA");
#endif  
                       
  if ((lpfnSETUPDIOPENDEVREGKEY == NULL) || 
      (lpfnSETUPDIENUMDEVICEINFO == NULL) || 
      (lpfnSETUPDIGETDEVICEREGISTRYPROPERTY == NULL) ||
      (lpfnSETUPDIGETCLASSDEVS == NULL) || 
      (lpfnSETUPDICLASSGUIDSFROMNAME == NULL) || 
      (lpfnSETUPDIDESTROYDEVICEINFOLIST == NULL))
  {
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
  }
  
  // First need to convert the name "Ports" to a GUID using SetupDiClassGuidsFromName...
  DWORD dwGuids = 0;
  lpfnSETUPDICLASSGUIDSFROMNAME(_T("Ports"), NULL, 0, &dwGuids);
  if (dwGuids == 0) return FALSE;

  // Allocate the needed memory...
  CHeapPtr<GUID> GuidArray;
  GUID *pGuids = (GUID*)GuidArray.Allocate(sizeof(GUID) * dwGuids);
  if (pGuids==NULL) {
    SetLastError(ERROR_OUTOFMEMORY);
    return FALSE;
  }

  // Call the function again...
  if (!lpfnSETUPDICLASSGUIDSFROMNAME(_T("Ports"), pGuids, dwGuids, &dwGuids))
    return FALSE;

  // Now create a "device information set" which is required to enumerate all the ports...
  HDEVINFO hDevInfoSet = lpfnSETUPDIGETCLASSDEVS(pGuids, NULL, NULL, DIGCF_PRESENT);
  if (hDevInfoSet == INVALID_HANDLE_VALUE)
    return FALSE;

  // Finally do the enumeration...
  int nIndex = 0;
  SP_DEVINFO_DATA devInfo;
  CHeapPtr<TCHAR> tempstr(256);
  CSerialPortInfo *portinfo = NULL;

  // Enumerate the current device...
  devInfo.cbSize = sizeof(SP_DEVINFO_DATA);
  while (lpfnSETUPDIENUMDEVICEINFO(hDevInfoSet, nIndex, &devInfo))
  {
    portinfo = NULL;

    // Get the registry key which stores the ports settings...
    HKEY hDeviceKey = lpfnSETUPDIOPENDEVREGKEY(hDevInfoSet, &devInfo, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE);
    if (hDeviceKey) {
      tempstr.FillZero();
      DWORD dwSize = tempstr.SizeOf(); 
      DWORD dwType = 0;

      // Read name of port.  If formatted as "COMxx" then allocate a port slot...
  	  if ((RegQueryValueEx(hDeviceKey, _T("PortName"), NULL, &dwType, reinterpret_cast<LPBYTE>((TCHAR*)tempstr), &dwSize) == ERROR_SUCCESS) && (dwType == REG_SZ))
        if (_tcslen(tempstr) > 3)
          if ((_tcsnicmp(tempstr, _T("COM"), 3) == 0) && IsNumber(&(tempstr[3])))
            portinfo = AddPort(_ttoi(&(tempstr[3])));

      // Close the key now that we are finished with it...
      RegCloseKey(hDeviceKey);
    }

    // If a serial port, then try getting additional useful descriptive info...
    if (portinfo) {
      for (int i=0; SPDRPlist[i]>=0; i++) {
        tempstr.FillZero(); 
        DWORD dwSize = tempstr.SizeOf(); 
        DWORD dwType = 0;
        if (lpfnSETUPDIGETDEVICEREGISTRYPROPERTY(hDevInfoSet, &devInfo, SPDRPlist[i], &dwType, reinterpret_cast<PBYTE>((TCHAR*)tempstr), dwSize, &dwSize) && (dwType == REG_SZ))
          switch (SPDRPlist[i]) {
            case SPDRP_MFG : portinfo->SetManufacturer(tempstr); break;
            case SPDRP_DEVICEDESC : portinfo->SetDeviceDesc(tempstr); break;
            case SPDRP_FRIENDLYNAME : portinfo->SetFriendlyName(tempstr); break;
            case SPDRP_LOCATION_INFORMATION : portinfo->SetLocationInfo(tempstr); break;
            case SPDRP_PHYSICAL_DEVICE_OBJECT_NAME : portinfo->SetPhysLocation(tempstr); break;
          }
      }

      // Get COM port properties...
      HANDLE hPort = ::CreateFile(portinfo->GetPortDeviceName(), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
      if (hPort != INVALID_HANDLE_VALUE) {
        COMMPROP cp;
        GetCommProperties(hPort, &cp);
        portinfo->SetCommProp(cp);
        TRACE ("Port %d:  CommProp: maxbaud=%08x  settablebaud=%08x\n",portinfo->GetPortNum(),cp.dwMaxBaud,cp.dwSettableBaud);
        CloseHandle(hPort);
      }
    }
    
    ++nIndex;
  }

  // Free up the "device information set" now that we are finished with it
  lpfnSETUPDIDESTROYDEVICEINFOLIST(hDevInfoSet);


  // Return the success indicator
  return TRUE;
}
Beispiel #14
0
int StartPlayer(const uchar * filehash, CString strFilename, DWORD dwFileSize, CString strExt)
{
	if(! g_PlayerMgr)
	{
		g_hNotifyWnd = AfxGetMainWnd()->GetSafeHwnd();
		g_PlayerMgr = (CPlayerMgr*)AfxBeginThread(RUNTIME_CLASS(CPlayerMgr));

		//  开始成功端口侦听
		while(g_PlayerMgr->GetListenPort()==0)
		{
			Sleep(100);
		}
	}

	if(strExt.IsEmpty() || filehash==NULL)
		return 0;

	CSKey key(filehash);

	CSingleLock lock(&CPlayerMgr::m_Mutex, true);

	TCHAR szBuf[_MAX_PATH];
	ULONG ulSize = _MAX_PATH;

	CString strExeFile;
	CRegKey reg;
	if(reg.Open(HKEY_CLASSES_ROOT, _T(".")+strExt)==ERROR_SUCCESS)
	{
		if(reg.QueryStringValue(NULL, szBuf, &ulSize)==ERROR_SUCCESS)
		{
			CString strCmd;
			strCmd.Format(_T("%s\\shell\\open\\command"), szBuf);
			if(reg.Open(HKEY_CLASSES_ROOT, strCmd)==ERROR_SUCCESS)
			{
				ulSize = _MAX_PATH;
				if(reg.QueryStringValue(NULL, szBuf, &ulSize)==ERROR_SUCCESS)
				{
					strExeFile = szBuf;
				}
			}
		}
	}

	//  使用配置的播放器
	if(strExeFile.IsEmpty())
	{
		// todo
		return 4;
	}

	CString strCmdLine;
	DWORD * pKey=(DWORD*)key.m_key;
	strCmdLine.Format(_T("http://127.0.0.1:%d/%08x%08x%08x%08x/%s"), g_PlayerMgr->GetListenPort(),
		pKey[0], pKey[1], pKey[2], pKey[3], strFilename);

	strExeFile.Replace(_T("\"%1\""), _T(""));
	strExeFile.Replace(_T("%1"), _T(""));
	strExeFile.Trim();

	//  把参数剥出来
	int nParamPos = -1;
	CString strTmp = strExeFile;
	while(true)
	{
		nParamPos=strTmp.ReverseFind(_T('.'));
		if(nParamPos==-1)
			break;

		LPCTSTR szExe = strTmp;
		if(_tcsnicmp(szExe + nParamPos, _T(".exe"), 4)==0)
		{
			nParamPos += 4;
			break;
		}
		else
		{
			strTmp = strTmp.Left(nParamPos);
		}
	}

	if(nParamPos==-1)
	{
		return 4;
	}

	CString strExeParam;
	if(nParamPos<strExeFile.GetLength()-1)
	{
		if(strExeFile.GetAt(nParamPos)==_T('\"'))
			nParamPos++;

		strExeParam = strExeFile.Mid(nParamPos);
		strExeFile = strExeFile.Left(nParamPos);
	}

	CPlayerTask * pTask = g_PlayerMgr->AddPlayerTask(key);
	pTask->m_dwTotalFileSize = dwFileSize;
//	CStringA strTmpA;
//	strTmpA.Format(httphead, dwFileSize);
//	pTask->SendData((void*)(const char*)strTmpA, strTmpA.GetLength());

	//if(! pTask->m_fileToRead.Duplicate() Open(strFilepath, CFile::modeRead|CFile::shareDenyWrite))
	//{
	//	g_PlayerMgr->RemovePlayerTask(key);
	//	return 3;
	//}

	ShellExecute(NULL,_T("open"), strExeFile, strCmdLine + strExeParam, NULL, SW_SHOW);
	return 0;
}
static int getkeystring(INI_FILETYPE *fp, const TCHAR *Section, const TCHAR *Key,
                        int idxSection, int idxKey, TCHAR *Buffer, int BufferSize)
{
  TCHAR *sp, *ep;
  int len, idx, isstring;
  enum quote_option quotes;
  TCHAR LocalBuffer[INI_BUFFERSIZE];

  assert(fp != NULL);
  /* Move through file 1 line at a time until a section is matched or EOF. If
   * parameter Section is NULL, only look at keys above the first section. If
   * idxSection is postive, copy the relevant section name.
   */
  len = (Section != NULL) ? _tcslen(Section) : 0;
  if (len > 0 || idxSection >= 0) {
    idx = -1;
    do {
      if (!ini_read(LocalBuffer, INI_BUFFERSIZE, fp))
        return 0;
      sp = skipleading(LocalBuffer);
      ep = _tcschr(sp, ']');
    } while (*sp != '[' || ep == NULL || (((int)(ep-sp-1) != len || _tcsnicmp(sp+1,Section,len) != 0) && ++idx != idxSection));
    if (idxSection >= 0) {
      if (idx == idxSection) {
        assert(ep != NULL);
        assert(*ep == ']');
        *ep = '\0';
        save_strncpy(Buffer, sp + 1, BufferSize, QUOTE_NONE);
        return 1;
      } /* if */
      return 0; /* no more section found */
    } /* if */
  } /* if */

  /* Now that the section has been found, find the entry.
   * Stop searching upon leaving the section's area.
   */
  assert(Key != NULL || idxKey >= 0);
  len = (Key != NULL) ? (int)_tcslen(Key) : 0;
  idx = -1;
  do {
    if (!ini_read(LocalBuffer,INI_BUFFERSIZE,fp) || *(sp = skipleading(LocalBuffer)) == '[')
      return 0;
    sp = skipleading(LocalBuffer);
    ep = _tcschr(sp, '='); /* Parse out the equal sign */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
  } while (*sp == ';' || *sp == '#' || ep == NULL || (((int)(skiptrailing(ep,sp)-sp) != len || _tcsnicmp(sp,Key,len) != 0) && ++idx != idxKey));
  if (idxKey >= 0) {
    if (idx == idxKey) {
      assert(ep != NULL);
      assert(*ep == '=' || *ep == ':');
      *ep = '\0';
      striptrailing(sp);
      save_strncpy(Buffer, sp, BufferSize, QUOTE_NONE);
      return 1;
    } /* if */
    return 0;   /* no more key found (in this section) */
  } /* if */

  /* Copy up to BufferSize chars to buffer */
  assert(ep != NULL);
  assert(*ep == '=' || *ep == ':');
  sp = skipleading(ep + 1);
  /* Remove a trailing comment */
  isstring = 0;
  for (ep = sp; *ep != '\0' && ((*ep != ';' && *ep != '#') || isstring); ep++) {
    if (*ep == '"') {
      if (*(ep + 1) == '"')
        ep++;                 /* skip "" (both quotes) */
      else
        isstring = !isstring; /* single quote, toggle isstring */
    } else if (*ep == '\\' && *(ep + 1) == '"') {
      ep++;                   /* skip \" (both quotes */
    } /* if */
  } /* for */
  assert(ep != NULL && (*ep == '\0' || *ep == ';' || *ep == '#'));
  *ep = '\0';                 /* terminate at a comment */
  striptrailing(sp);
  /* Remove double quotes surrounding a value */
  quotes = QUOTE_NONE;
  if (*sp == '"' && (ep = _tcschr(sp, '\0')) != NULL && *(ep - 1) == '"') {
    sp++;
    *--ep = '\0';
    quotes = QUOTE_DEQUOTE;   /* this is a string, so remove escaped characters */
  } /* if */
  save_strncpy(Buffer, sp, BufferSize, quotes);
  return 1;
}
BOOL CEnumerateSerial::UsingQueryDosDevice(CSimpleArray<UINT>& ports)
#endif
{
  //What will be the return value from this function (assume the worst)
  BOOL bSuccess = FALSE;

  //Make sure we clear out any elements which may already be in the array
#if defined CENUMERATESERIAL_USE_STL
  ports.clear();
#else
  ports.RemoveAll();
#endif  

  //Determine what OS we are running on
  OSVERSIONINFO osvi;
  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  BOOL bGetVer = GetVersionEx(&osvi);

  //On NT use the QueryDosDevice API
  if (bGetVer && (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT))
  {
    //Use QueryDosDevice to look for all devices of the form COMx. Since QueryDosDevice does
    //not consitently report the required size of buffer, lets start with a reasonable buffer size
    //of 4096 characters and go from there
    int nChars = 4096;
    BOOL bWantStop = FALSE;
    while (nChars && !bWantStop)
    {
      CAutoHeapAlloc devices;
      if (devices.Allocate(nChars * sizeof(TCHAR)))
      {
        LPTSTR pszDevices = static_cast<LPTSTR>(devices.m_pData);
        DWORD dwChars = QueryDosDevice(NULL, pszDevices, nChars);
        if (dwChars == 0)
        {
          DWORD dwError = GetLastError();
          if (dwError == ERROR_INSUFFICIENT_BUFFER)
          {
            //Expand the buffer and  loop around again
            nChars *= 2;
          }
          else
            bWantStop = TRUE;
        }
        else
        {
          bSuccess = TRUE;
          bWantStop = TRUE;
          size_t i=0;
          
          while (pszDevices[i] != _T('\0'))
          {
            //Get the current device name
            TCHAR* pszCurrentDevice = &(pszDevices[i]);

            //If it looks like "COMX" then
            //add it to the array which will be returned
            size_t nLen = _tcslen(pszCurrentDevice);
            if (nLen > 3)
            {
              if ((_tcsnicmp(pszCurrentDevice, _T("COM"), 3) == 0) && IsNumeric(&(pszCurrentDevice[3]), FALSE))
              {
                //Work out the port number
                int nPort = _ttoi(&pszCurrentDevice[3]);
              #if defined CENUMERATESERIAL_USE_STL
                ports.push_back(nPort);
              #else
                ports.Add(nPort);
              #endif  
              }
            }

            //Go to next device name
            i += (nLen + 1);
          }
        }
      }
      else
      {
        bWantStop = TRUE;
        SetLastError(ERROR_OUTOFMEMORY);        
      }
    }
  }
  else
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);

  return bSuccess;
}
/** ini_puts()
 * \param Section     the name of the section to write the string in
 * \param Key         the name of the entry to write, or NULL to erase all keys in the section
 * \param Value       a pointer to the buffer the string, or NULL to erase the key
 * \param Filename    the name and full path of the .ini file to write to
 *
 * \return            1 if successful, otherwise 0
 */
int ini_puts(const TCHAR *Section, const TCHAR *Key, const TCHAR *Value, const TCHAR *Filename)
{
  INI_FILETYPE rfp;
  INI_FILETYPE wfp;
  TCHAR *sp, *ep;
  TCHAR LocalBuffer[INI_BUFFERSIZE];
  int len, match, count;

  assert(Filename!=NULL);
  if (!ini_openread(Filename, &rfp)) {
    /* If the .ini file doesn't exist, make a new file */
    if (Key!=NULL && Value!=NULL) {
      if (!ini_openwrite(Filename, &wfp))
        return 0;
      writesection(LocalBuffer, Section, &wfp);
      writekey(LocalBuffer, Key, Value, &wfp);
      ini_close(&wfp);
    } /* if */
    return 1;
  } /* if */

  /* If parameters Key and Value are valid (so this is not an "erase" request)
   * and the setting already exists and it already has the correct value, do
   * nothing. This early bail-out avoids rewriting the INI file for no reason.
   */
  if (Key!=NULL && Value!=NULL) {
    match = getkeystring(&rfp, Section, Key, -1, -1, LocalBuffer, sizearray(LocalBuffer));
    if (match && _tcscmp(LocalBuffer,Value)==0) {
      ini_close(&rfp);
      return 1;
    } /* if */
    /* key not found, or different value -> proceed (but rewind the input file first) */
    ini_rewind(&rfp);
  } /* if */

  /* Get a temporary file name to copy to. Use the existing name, but with
   * the last character set to a '~'.
   */
  ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
  if (!ini_openwrite(LocalBuffer, &wfp)) {
    ini_close(&rfp);
    return 0;
  } /* if */

  /* Move through the file one line at a time until a section is
   * matched or until EOF. Copy to temp file as it is read.
   */
  count = 0;
  len = (Section != NULL) ? _tcslen(Section) : 0;
  if (len > 0) {
    do {
      if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
        /* Failed to find section, so add one to the end */
        if (Key!=NULL && Value!=NULL) {
            ini_write(INI_LINETERM, &wfp);  /* force a new line (there may not have been one) behind the last line of the INI file */
            writesection(LocalBuffer, Section, &wfp);
            writekey(LocalBuffer, Key, Value, &wfp);
        } /* if */
        /* Clean up and rename */
        ini_close(&rfp);
        ini_close(&wfp);
        ini_remove(Filename);
        ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
        ini_rename(LocalBuffer, Filename);
        return 1;
      } /* if */
      /* Copy the line from source to dest, but not if this is the section that
       * we are looking for and this section must be removed
       */
      sp = skipleading(LocalBuffer);
      ep = _tcschr(sp, ']');
      match = (*sp == '[' && ep != NULL && (int)(ep-sp-1) == len && _tcsnicmp(sp + 1,Section,len) == 0);
      if (!match || Key!=NULL) {
        /* Remove blank lines, but insert a blank line (possibly one that was
         * removed on the previous iteration) before a new section. This creates
         * "neat" INI files.
         */
        if (_tcslen(sp) > 0) {
          if (*sp == '[' && count > 0)
            ini_write(INI_LINETERM, &wfp);
          ini_write(sp, &wfp);
          count++;
        } /* if */
      } /* if */
    } while (!match);
  } /* if */

  /* Now that the section has been found, find the entry. Stop searching
   * upon leaving the section's area. Copy the file as it is read
   * and create an entry if one is not found.
   */
  len = (Key!=NULL) ? _tcslen(Key) : 0;
  for( ;; ) {
    if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
      /* EOF without an entry so make one */
      if (Key!=NULL && Value!=NULL) {
          ini_write(INI_LINETERM, &wfp);  /* force a new line (there may not have been one) behind the last line of the INI file */
          writekey(LocalBuffer, Key, Value, &wfp);
      } /* if */
      /* Clean up and rename */
      ini_close(&rfp);
      ini_close(&wfp);
      ini_remove(Filename);
      ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
      ini_rename(LocalBuffer, Filename);
      return 1;
    } /* if */
    sp = skipleading(LocalBuffer);
    ep = _tcschr(sp, '='); /* Parse out the equal sign */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
    match = (ep != NULL && (int)(skiptrailing(ep,sp)-sp) == len && _tcsnicmp(sp,Key,len) == 0);
    if ((Key!=NULL && match) || *sp == '[')
      break;  /* found the key, or found a new section */
    /* in the section that we re-write, do not copy empty lines */
    if (Key!=NULL && _tcslen(sp) > 0)
      ini_write(sp, &wfp);
  } /* for */
  if (*sp == '[') {
    /* found start of new section, the key was not in the specified
     * section, so we add it just before the new section
     */
    if (Key!=NULL && Value!=NULL) {
      /* We cannot use "writekey()" here, because we need to preserve the
       * contents of LocalBuffer.
       */
      ini_write(Key, &wfp);
      ini_write("=", &wfp);
      write_quoted(Value, &wfp);
      ini_write(INI_LINETERM INI_LINETERM, &wfp); /* put a blank line between the current and the next section */
    } /* if */
    /* write the new section header that we read previously */
    ini_write(sp, &wfp);
  } else {
    /* We found the key; ignore the line just read (with the key and
     * the current value) and write the key with the new value.
     */
    if (Key!=NULL && Value!=NULL)
      writekey(LocalBuffer, Key, Value, &wfp);
  } /* if */
  /* Copy the rest of the INI file (removing empty lines, except before a section) */
  while (ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
    sp = skipleading(LocalBuffer);
    if (_tcslen(sp) > 0) {
      if (*sp == '[')
        ini_write(INI_LINETERM, &wfp);
      ini_write(sp, &wfp);
    } /* if */
  } /* while */
  /* Clean up and rename */
  ini_close(&rfp);
  ini_close(&wfp);
  ini_remove(Filename);
  ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
  ini_rename(LocalBuffer, Filename);
  return 1;
}
Beispiel #18
0
INT_PTR CALLBACK DlgProcRecvFile(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	FileDlgData *dat = (FileDlgData*)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);

	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		{
			TCHAR szPath[450];
			CLISTEVENT* cle = (CLISTEVENT*)lParam;

			dat = (FileDlgData*)mir_calloc(sizeof(FileDlgData));
			SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)dat);
			dat->hContact = cle->hContact;
			dat->hDbEvent = cle->hDbEvent;
			dat->hNotifyEvent = HookEventMessage(ME_PROTO_ACK, hwndDlg, HM_RECVEVENT);
			dat->hPreshutdownEvent = HookEventMessage(ME_SYSTEM_PRESHUTDOWN, hwndDlg, M_PRESHUTDOWN);
			dat->dwTicks = GetTickCount();

			EnumChildWindows(hwndDlg, ClipSiblingsChildEnumProc, 0);

			Window_SetSkinIcon_IcoLib(hwndDlg, SKINICON_EVENT_FILE);
			Button_SetIcon_IcoLib(hwndDlg, IDC_ADD, SKINICON_OTHER_ADDCONTACT, LPGEN("Add contact permanently to list"));
			Button_SetIcon_IcoLib(hwndDlg, IDC_DETAILS, SKINICON_OTHER_USERDETAILS, LPGEN("View user's details"));
			Button_SetIcon_IcoLib(hwndDlg, IDC_HISTORY, SKINICON_OTHER_HISTORY, LPGEN("View user's history"));
			Button_SetIcon_IcoLib(hwndDlg, IDC_USERMENU, SKINICON_OTHER_DOWNARROW, LPGEN("User menu"));

			TCHAR *contactName = pcli->pfnGetContactDisplayName(dat->hContact, 0);
			SetDlgItemText(hwndDlg, IDC_FROM, contactName);
			GetContactReceivedFilesDir(dat->hContact, szPath, _countof(szPath), TRUE);
			SetDlgItemText(hwndDlg, IDC_FILEDIR, szPath);
			SHAutoComplete(GetWindow(GetDlgItem(hwndDlg, IDC_FILEDIR), GW_CHILD), 1);

			for (int i = 0; i < MAX_MRU_DIRS; i++) {
				char idstr[32];
				mir_snprintf(idstr, "MruDir%d", i);

				DBVARIANT dbv;
				if (db_get_ts(NULL, "SRFile", idstr, &dbv))
					break;
				SendDlgItemMessage(hwndDlg, IDC_FILEDIR, CB_ADDSTRING, 0, (LPARAM)dbv.ptszVal);
				db_free(&dbv);
			}

			db_event_markRead(dat->hContact, dat->hDbEvent);

			DBEVENTINFO dbei = { sizeof(dbei) };
			dbei.cbBlob = db_event_getBlobSize(dat->hDbEvent);
			if (dbei.cbBlob > 4 && dbei.cbBlob <= 8196) {
				dbei.pBlob = (PBYTE)alloca(dbei.cbBlob + 1);
				db_event_get(dat->hDbEvent, &dbei);
				dbei.pBlob[dbei.cbBlob] = 0;
				dat->fs = cle->lParam ? (HANDLE)cle->lParam : (HANDLE)*(PDWORD)dbei.pBlob;

				char *str = (char*)dbei.pBlob + 4;
				ptrT ptszFileName(DbGetEventStringT(&dbei, str));
				SetDlgItemText(hwndDlg, IDC_FILENAMES, ptszFileName);

				unsigned len = (unsigned)mir_strlen(str) + 1;
				if (len + 4 < dbei.cbBlob) {
					str += len;
					ptrT ptszDescription(DbGetEventStringT(&dbei, str));
					SetDlgItemText(hwndDlg, IDC_MSG, ptszDescription);
				}
			}
			else DestroyWindow(hwndDlg);

			TCHAR datetimestr[64];
			TimeZone_PrintTimeStamp(NULL, dbei.timestamp, _T("t d"), datetimestr, _countof(datetimestr), 0);
			SetDlgItemText(hwndDlg, IDC_DATE, datetimestr);

			ptrT info(Contact_GetInfo(CNF_UNIQUEID, dat->hContact));
			SetDlgItemText(hwndDlg, IDC_NAME, (info) ? info : contactName);

			if (db_get_b(dat->hContact, "CList", "NotOnList", 0)) {
				RECT rcBtn1, rcBtn2, rcDateCtrl;
				GetWindowRect(GetDlgItem(hwndDlg, IDC_ADD), &rcBtn1);
				GetWindowRect(GetDlgItem(hwndDlg, IDC_USERMENU), &rcBtn2);
				GetWindowRect(GetDlgItem(hwndDlg, IDC_DATE), &rcDateCtrl);
				SetWindowPos(GetDlgItem(hwndDlg, IDC_DATE), 0, 0, 0, rcDateCtrl.right - rcDateCtrl.left - (rcBtn2.left - rcBtn1.left), rcDateCtrl.bottom - rcDateCtrl.top, SWP_NOZORDER | SWP_NOMOVE);
			}
			else if (db_get_b(NULL, "SRFile", "AutoAccept", 0)) {
				//don't check auto-min here to fix BUG#647620
				PostMessage(hwndDlg, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), (LPARAM)GetDlgItem(hwndDlg, IDOK));
			}
			if (!db_get_b(dat->hContact, "CList", "NotOnList", 0))
				ShowWindow(GetDlgItem(hwndDlg, IDC_ADD), SW_HIDE);
		}
		return TRUE;

	case WM_MEASUREITEM:
		return Menu_MeasureItem((LPMEASUREITEMSTRUCT)lParam);

	case WM_DRAWITEM:
		{
			LPDRAWITEMSTRUCT dis = (LPDRAWITEMSTRUCT)lParam;
			if (dis->hwndItem == GetDlgItem(hwndDlg, IDC_PROTOCOL)) {
				char *szProto = GetContactProto(dat->hContact);
				if (szProto) {
					HICON hIcon = (HICON)CallProtoService(szProto, PS_LOADICON, PLI_PROTOCOL|PLIF_SMALL, 0);
					if (hIcon) {
						DrawIconEx(dis->hDC, dis->rcItem.left, dis->rcItem.top, hIcon, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0, NULL, DI_NORMAL);
						DestroyIcon(hIcon);
					}
				}
			}
		}
		return Menu_DrawItem((LPDRAWITEMSTRUCT)lParam);

	case WM_COMMAND:
		if (CallService(MS_CLIST_MENUPROCESSCOMMAND, MAKEWPARAM(LOWORD(wParam), MPCF_CONTACTMENU), (LPARAM)dat->hContact))
			break;

		switch (LOWORD(wParam)) {
		case IDC_FILEDIRBROWSE:
			{
				TCHAR szDirName[MAX_PATH], szExistingDirName[MAX_PATH];

				GetDlgItemText(hwndDlg, IDC_FILEDIR, szDirName, _countof(szDirName));
				GetLowestExistingDirName(szDirName, szExistingDirName, _countof(szExistingDirName));
				if (BrowseForFolder(hwndDlg, szExistingDirName))
					SetDlgItemText(hwndDlg, IDC_FILEDIR, szExistingDirName);
			}
			break;

		case IDOK:
			{	//most recently used directories
				TCHAR szRecvDir[MAX_PATH], szDefaultRecvDir[MAX_PATH];
				GetDlgItemText(hwndDlg, IDC_FILEDIR, szRecvDir, _countof(szRecvDir));
				RemoveInvalidPathChars(szRecvDir);
				GetContactReceivedFilesDir(NULL, szDefaultRecvDir, _countof(szDefaultRecvDir), TRUE);
				if (_tcsnicmp(szRecvDir, szDefaultRecvDir, mir_tstrlen(szDefaultRecvDir))) {
					char idstr[32];
					int i;
					DBVARIANT dbv;
					for (i = MAX_MRU_DIRS-2;i>=0;i--) {
						mir_snprintf(idstr, "MruDir%d", i);
						if (db_get_ts(NULL, "SRFile", idstr, &dbv)) continue;
						mir_snprintf(idstr, "MruDir%d", i+1);
						db_set_ts(NULL, "SRFile", idstr, dbv.ptszVal);
						db_free(&dbv);
					}
					db_set_ts(NULL, "SRFile", idstr, szRecvDir);
				}
			}
			EnableWindow(GetDlgItem(hwndDlg, IDC_FILENAMES), FALSE);
			EnableWindow(GetDlgItem(hwndDlg, IDC_MSG), FALSE);
			EnableWindow(GetDlgItem(hwndDlg, IDC_FILEDIR), FALSE);
			EnableWindow(GetDlgItem(hwndDlg, IDC_FILEDIRBROWSE), FALSE);

			GetDlgItemText(hwndDlg, IDC_FILEDIR, dat->szSavePath, _countof(dat->szSavePath));
			GetDlgItemText(hwndDlg, IDC_FILE, dat->szFilenames, _countof(dat->szFilenames));
			GetDlgItemText(hwndDlg, IDC_MSG, dat->szMsg, _countof(dat->szMsg));
			dat->hwndTransfer = FtMgr_AddTransfer(dat);
			SetWindowLongPtr(hwndDlg, GWLP_USERDATA, 0);
			//check for auto-minimize here to fix BUG#647620
			if (db_get_b(NULL, "SRFile", "AutoAccept", 0) && db_get_b(NULL, "SRFile", "AutoMin", 0)) {
				ShowWindow(hwndDlg, SW_HIDE);
				ShowWindow(hwndDlg, SW_SHOWMINNOACTIVE);
			}
			DestroyWindow(hwndDlg);
			break;

		case IDCANCEL:
			if (dat->fs) CallContactService(dat->hContact, PSS_FILEDENY, (WPARAM)dat->fs, (LPARAM)TranslateT("Canceled"));
			dat->fs = NULL; /* the protocol will free the handle */
			DestroyWindow(hwndDlg);
			break;

		case IDC_ADD:
			{
				ADDCONTACTSTRUCT acs = { 0 };
				acs.hContact = dat->hContact;
				acs.handleType = HANDLE_CONTACT;
				acs.szProto = "";
				CallService(MS_ADDCONTACT_SHOW, (WPARAM)hwndDlg, (LPARAM)&acs);
				if (!db_get_b(dat->hContact, "CList", "NotOnList", 0))
					ShowWindow(GetDlgItem(hwndDlg, IDC_ADD), SW_HIDE);
			}
			break;

		case IDC_USERMENU:
			{
				RECT rc;
				GetWindowRect((HWND)lParam, &rc);
				HMENU hMenu = Menu_BuildContactMenu(dat->hContact);
				TrackPopupMenu(hMenu, 0, rc.left, rc.bottom, 0, hwndDlg, NULL);
				DestroyMenu(hMenu);
			}
			break;

		case IDC_DETAILS:
			CallService(MS_USERINFO_SHOWDIALOG, (WPARAM)dat->hContact, 0);
			break;

		case IDC_HISTORY:
			CallService(MS_HISTORY_SHOWCONTACTHISTORY, (WPARAM)dat->hContact, 0);
			break;
		}
		break;

	case HM_RECVEVENT:
		{
			ACKDATA *ack = (ACKDATA*)lParam;
			if ((ack == NULL) || (ack->hProcess != dat->fs) || (ack->type != ACKTYPE_FILE) || (ack->hContact != dat->hContact))
				break;

			if (ack->result == ACKRESULT_DENIED || ack->result == ACKRESULT_FAILED) {
				EnableWindow(GetDlgItem(hwndDlg, IDOK), FALSE);
				EnableWindow(GetDlgItem(hwndDlg, IDC_FILEDIR), FALSE);
				EnableWindow(GetDlgItem(hwndDlg, IDC_FILEDIRBROWSE), FALSE);
				SetDlgItemText(hwndDlg, IDC_MSG, TranslateT("This file transfer has been canceled by the other side"));
				SkinPlaySound("FileDenied");
				FlashWindow(hwndDlg, TRUE);
			}
			else if (ack->result != ACKRESULT_FILERESUME)
			{
				SendMessage(hwndDlg, WM_COMMAND, MAKEWPARAM(IDCANCEL, 0), (LPARAM)GetDlgItem(hwndDlg, IDCANCEL));
			}
		}
		break;

	case WM_DESTROY:
		Window_FreeIcon_IcoLib(hwndDlg);
		Button_FreeIcon_IcoLib(hwndDlg, IDC_ADD);
		Button_FreeIcon_IcoLib(hwndDlg, IDC_DETAILS);
		Button_FreeIcon_IcoLib(hwndDlg, IDC_HISTORY);
		Button_FreeIcon_IcoLib(hwndDlg, IDC_USERMENU);

		FreeFileDlgData(dat);
		SetWindowLongPtr(hwndDlg, GWLP_USERDATA, 0);
		break;
	}
	return FALSE;
}
Beispiel #19
0
static void parsemessage(TCHAR *in, struct uae_prefs *p, TCHAR *out, int outsize)
{
	int mode;

	out[0] = 0;

	my_trim (in);
	if (!_tcsicmp (in, _T("IPC_QUIT"))) {
		uae_quit ();
		return;
	}
	if (!_tcsicmp (in, _T("ipc_config"))) {
		ipcmode = 1;
		_tcscat (out, _T("200\n"));
		return;
	} else if (!_tcsicmp (in, _T("ipc_event"))) {
		ipcmode = 2;
		_tcscat (out, _T("200\n"));
		return;
	} else if (!_tcsicmp (in, _T("ipc_debug"))) {
		ipcmode = 3;
		_tcscat (out, _T("200\n"));
		return;
	} else if (!_tcsicmp (in, _T("ipc_restore"))) {
		ipcmode = 0;
		_tcscat (out, _T("200\n"));
		return;
	}

	mode = 0;
	if (ipcmode == 1) {
		mode = 1;
	} else if (ipcmode == 2) {
		mode = 1;
	} else if (ipcmode == 3) {
		mode = 2;
	} else if (!_tcsnicmp (in, _T("CFG "), 4) || !_tcsnicmp (in, _T("EVT "), 4)) {
		mode = 1;
		in += 4;
	} else if (!_tcsnicmp (in, _T("DBG "), 4)) {
		mode = 2;
		in += 4;
	}

	if (mode == 1) {
		TCHAR tmpout[256];
		int index = -1;
		int cnt = 0;
		for (;;) {
			int ret;
			tmpout[0] = 0;
			ret = cfgfile_modify (index, in, _tcslen (in), tmpout, sizeof (tmpout) / sizeof (TCHAR));
			index++;
			if (_tcslen (tmpout) > 0) {
				if (_tcslen (out) == 0)
					_tcscat (out, _T("200 "));
				_tcsncat (out, _T("\n"), outsize);
				_tcsncat (out, tmpout, outsize);
			}
			cnt++;
			if (ret >= 0)
				break;
		}
		if (out[0] == 0)
			_tcscat (out, _T("404"));
	} else if (mode == 2) {
		debug_parser (in, out, outsize);
		if (!out[0])
			_tcscpy (out, _T("404"));
	} else {
		_tcscpy (out, _T("501"));
	}
}
BOOL CJabberProto::OnIqRequestOOB(HXML, CJabberIqInfo *pInfo)
{
	if (!pInfo->GetFrom() || !pInfo->GetHContact())
		return TRUE;

	HXML n = xmlGetChild(pInfo->GetChildNode(), "url");
	if (!n || !xmlGetText(n))
		return TRUE;

	if (m_options.BsOnlyIBB) {
		// reject
		XmlNodeIq iq(_T("error"), pInfo);
		HXML e = xmlAddChild(iq, _T("error"), _T("File transfer refused")); xmlAddAttr(e, _T("code"), 406);
		m_ThreadInfo->send(iq);
		return TRUE;
	}

	filetransfer *ft = new filetransfer(this);
	ft->std.totalFiles = 1;
	ft->jid = mir_tstrdup(pInfo->GetFrom());
	ft->std.hContact = pInfo->GetHContact();
	ft->type = FT_OOB;
	ft->httpHostName = NULL;
	ft->httpPort = 80;
	ft->httpPath = NULL;

	// Parse the URL
	TCHAR *str = (TCHAR*)xmlGetText(n);	// URL of the file to get
	if (!_tcsnicmp(str, _T("http://"), 7)) {
		TCHAR *p = str + 7, *q;
		if ((q = _tcschr(p, '/')) != NULL) {
			TCHAR text[1024];
			if (q-p < SIZEOF(text)) {
				_tcsncpy(text, p, q-p);
				text[q-p] = '\0';
				if ((p = _tcschr(text, ':')) != NULL) {
					ft->httpPort = (WORD)_ttoi(p+1);
					*p = '\0';
				}
				ft->httpHostName = mir_t2a(text);
			}
		}
	}

	if (pInfo->GetIdStr())
		ft->iqId = pInfo->GetIqId();

	if (ft->httpHostName && ft->httpPath) {
		TCHAR *desc = NULL;

		debugLogA("Host=%s Port=%d Path=%s", ft->httpHostName, ft->httpPort, ft->httpPath);
		if ((n = xmlGetChild(pInfo->GetChildNode(), "desc")) != NULL)
			desc = (TCHAR*)xmlGetText(n);

		TCHAR *str2;
		debugLogA("description = %s", desc);
		if ((str2 = _tcsrchr(ft->httpPath, '/')) != NULL)
			str2++;
		else
			str2 = ft->httpPath;
		str2 = mir_tstrdup(str2);
		JabberHttpUrlDecode(str2);

		PROTORECVFILET pre;
		pre.flags = PREF_TCHAR;
		pre.timestamp = time(NULL);
		pre.tszDescription = desc;
		pre.ptszFiles = &str2;
		pre.fileCount = 1;
		pre.lParam = (LPARAM)ft;
		ProtoChainRecvFile(ft->std.hContact, &pre);
		mir_free(str2);
	}
	else {
		// reject
		XmlNodeIq iq(_T("error"), pInfo);
		HXML e = xmlAddChild(iq, _T("error"), _T("File transfer refused")); xmlAddAttr(e, _T("code"), 406);
		m_ThreadInfo->send(iq);
		delete ft;
	}
	return TRUE;
}
Beispiel #21
0
short
IsfFromName (
    BOOL fExactMatch,
    short isfStart,
    LSZ lszName,
    LPMDS lpmds
    )
{
    short isfFound = -1;
    short isf = isfStart;
    LPEXG lpexg = (LPEXG) LLLock (lpmds->hexg);

    if (lpexg->lpefi) {
        CHAR szFileSrc [ _MAX_CVFNAME ];
        CHAR szExtSrc [ _MAX_CVEXT ];
        WORD cbName = 0;
        WORD cchName = 0;
        LSZ  lszFileExt = NULL;
        int  imds = lpmds->imds - 1;

        _tsplitpath(lszName, NULL, NULL, szFileSrc, szExtSrc);

        // If fExactMatch, the path must match the OMF
        if (fExactMatch) {
            cbName = _tcslen(lszName);
            cchName = _tcslen(lszName);
            lszFileExt = lszName;
        } else {
            cbName = _tcslen(szExtSrc) + _tcslen(szFileSrc);
            cchName = _tcslen(szExtSrc) + _tcslen(szFileSrc);
            lszFileExt = lszName + _tcslen(lszName) - cbName;
        }

        for (isf = isfStart; isf < (short) lpexg->rgculFile [ imds ]; isf++) {
            CHAR szPathOMF [ _MAX_CVPATH ];
            CHAR szFile [ _MAX_CVFNAME ];
            CHAR szExt [ _MAX_CVEXT ];

            _TCHAR  * lpch = (_TCHAR  *)
                lpexg->lpchFileNames +
                (lpexg->rgichFile [ (WORD) (lpexg->rgiulFile [ imds ]) + isf ]);

            // IMPORTANT NOTE:
            //
            // Below, it is VITAL for DBCS to use the number of CHARACTERS
            // to compare as opposed to the number of bytes or the DBCS
            // strnicmp will fail!

            if (!_tcsnicmp (lszFileExt, (_TCHAR  *) lpch + cbNameLen(lpch) - cbName + 1, cchName)) {
                memset(szPathOMF, 0, _MAX_CVPATH);
                memcpy(szPathOMF, lpch + 1, cbNameLen(lpch));
                _tsplitpath(szPathOMF, NULL, NULL, szFile, szExt);
                if (!_tcsicmp (szFileSrc, szFile) &&
                     !_tcsicmp (szExtSrc, szExt))
                {
                    isfFound = isf;
                    break;
                }
            }
        }
    }

    LLUnlock (lpmds->hexg);

    return isfFound;
}
Beispiel #22
0
int cliFindRowByText(HWND hwnd, ClcData *dat, const TCHAR *text, int prefixOk)
{
	ClcGroup *group = &dat->list;
	int testlen = (int)mir_tstrlen(text);
	ClcContact *contact = NULL;
	int SubCount = 0;

	group->scanIndex = 0;
	for (;;) {
		if (group->scanIndex == group->cl.count) {
			group = group->parent;
			if (group == NULL)
				break;
			group->scanIndex++;
			continue;
		}
		contact = group->cl.items[group->scanIndex];
		if (contact->type != CLCIT_DIVIDER) {
			bool found;
			if (dat->filterSearch) {
				TCHAR *lowered_szText = CharLowerW(NEWTSTR_ALLOCA(contact->szText));
				TCHAR *lowered_text = CharLowerW(NEWTSTR_ALLOCA(text));
				found = _tcsstr(lowered_szText, lowered_text) != NULL;
			}
			else found = (prefixOk && !_tcsnicmp(text, contact->szText, testlen)) || (!prefixOk && !mir_tstrcmpi(text, contact->szText));

			if (found) {
				ClcGroup *contactGroup = group;
				int contactScanIndex = group->scanIndex;
				for (; group; group = group->parent)
					pcli->pfnSetGroupExpand(hwnd, dat, group, 1);
				return pcli->pfnGetRowsPriorTo(&dat->list, contactGroup, contactScanIndex + SubCount);
			}
			if (group->cl.items[group->scanIndex]->type == CLCIT_GROUP) {
				if (!(dat->exStyle & CLS_EX_QUICKSEARCHVISONLY) || group->cl.items[group->scanIndex]->group->expanded) {
					group = group->cl.items[group->scanIndex]->group;
					group->scanIndex = 0;
					SubCount = 0;
					continue;
				}
			}
		}
		if (contact->type == CLCIT_CONTACT && contact->SubAllocated) {
			if (!(dat->exStyle & CLS_EX_QUICKSEARCHVISONLY) || contact->SubExpanded) {
				int i = 0;
				for (i = 0; i < contact->SubAllocated; i++) {
					ClcContact *subcontact = &(contact->subcontacts[i]);

					bool found;
					if (dat->filterSearch) {
						TCHAR *lowered_szText = CharLowerW(NEWTSTR_ALLOCA(subcontact->szText));
						TCHAR *lowered_text = CharLowerW(NEWTSTR_ALLOCA(text));
						found = _tcsstr(lowered_szText, lowered_text) != NULL;
					}
					else found = (prefixOk && !_tcsnicmp(text, subcontact->szText, testlen)) || (!prefixOk && !mir_tstrcmpi(text, subcontact->szText));

					if (found) {
						ClcGroup *contactGroup = group;
						int contactScanIndex = group->scanIndex;
						for (; group; group = group->parent)
							pcli->pfnSetGroupExpand(hwnd, dat, group, 1);
						if (!contact->SubExpanded)
							ExpandMetaContact(hwnd, contact, dat, 1);
						return pcli->pfnGetRowsPriorTo(&dat->list, contactGroup, contactScanIndex + SubCount + i + 1);
					}
				}
			}
		}
		if (contact->type == CLCIT_CONTACT && contact->SubAllocated && contact->SubExpanded)
			SubCount += contact->SubAllocated;
		group->scanIndex++;
	}
	return -1;
}
Beispiel #23
0
STDMETHODIMP CIE2EMUrlTaker::SendUrl(BSTR strUrl, BSTR strInfo, BSTR strRef, BOOL * result)
{
	CRegKey hkey;

	if(GetLastSucc() == strUrl)
	{
		* result = TRUE;
		return S_OK;
	}

	if(hkey.Open(HKEY_CURRENT_USER, _T("Software\\easyMule"), KEY_READ) != ERROR_SUCCESS)
	{
		* result = FALSE;
		return S_OK;
	}

	TCHAR rBuffer[MAX_PATH];
	ULONG maxsize = MAX_PATH;
	LONG lRes = hkey.QueryStringValue(_T("InstallPath"), rBuffer, &maxsize);

	hkey.Close();

	if(lRes != ERROR_SUCCESS)
	{
		* result = FALSE;
		return S_OK;
	}

	CComBSTR path(rBuffer);
	path.Append("\\Ed2kLoader.exe");
	if(!PathFileExists(path))
	{
		* result = FALSE;
		return S_OK;
	}
	CComBSTR str("\"");
	str.Append(path);
	str.Append("\" \"");
	str.Append(strUrl);
	if(strUrl[0] != 'e' && strUrl[0] != 'f' && strRef != NULL && strRef[0] != 0)
	{
		str.Append("#<referer=");
		str.AppendBSTR(strRef);
		str.Append(">");
	}
	str.Append("\"");

	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	ZeroMemory( &pi, sizeof(pi) );
	if(!CreateProcess( NULL, str.Copy(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
	{
		* result = FALSE;
		return S_OK;
	}
	* result = TRUE;
	if(_tcsnicmp(strUrl, _T("ed2k://"), 7) == 0)
	{
		SetLastSucc(_T(""));
	}
	else if(strInfo != NULL && strInfo[0] == '\1')
	{
		DWORD dwRes = WaitForSingleObject(pi.hProcess, 120000), dwExit = 0;
		if(dwRes == WAIT_OBJECT_0 && GetExitCodeProcess(pi.hProcess, &dwExit) && dwExit > 0)
			SetLastSucc(strUrl);
		else
			* result = FALSE;
	}
	return S_OK;
}
Beispiel #24
0
static void UpdateList(void){
  int i;
 ItemIndex = 0;

  UpLimit= NumberOfAirspaces;
  LowLimit =0;
  FullFlag=false;
  if (TypeFilterIdx>0) {


    if(TypeFilterIdx == AIRSPACECLASSCOUNT+1)
    {
        qsort(AirspaceSelectInfo, NumberOfAirspaces,
               sizeof(AirspaceSelectInfo_t), AirspaceDisabledCompare);
      for (i=0; i<(int)NumberOfAirspaces; i++){
        if (AirspaceSelectInfo[i].airspace->Enabled()  ){
          UpLimit = i;
          break;
        }
    }
    }
    else
    {
      qsort(AirspaceSelectInfo, NumberOfAirspaces,
          sizeof(AirspaceSelectInfo_t), AirspaceTypeCompare);
      for (i=0; i<(int)NumberOfAirspaces; i++){
        if (!(AirspaceSelectInfo[i].Type == TypeFilterIdx-1)){
          UpLimit = i;
          break;
        }
      }
    }
  }

  if (DistanceFilterIdx != 0){

    qsort(AirspaceSelectInfo, UpLimit,
        sizeof(AirspaceSelectInfo_t), AirspaceDistanceCompare);
    for (i=0; i<(int)UpLimit; i++){
      if (AirspaceSelectInfo[i].Distance > DistanceFilter[DistanceFilterIdx]){
        UpLimit = i;
        break;
      }
    }
  }

  if (DirectionFilterIdx != 0){

    qsort(AirspaceSelectInfo, UpLimit,
        sizeof(AirspaceSelectInfo_t), AirspaceDirectionCompare);
    for (i=0; i<UpLimit; i++){
      if (AirspaceSelectInfo[i].DirectionErr > 18){
        UpLimit = i;
        break;
      }
    }
  }


  TCHAR sTmp[EXT_SEARCH_SIZE+1];
  TCHAR wname[EXT_SEARCH_SIZE+1];
  LowLimit = UpLimit;
  qsort(AirspaceSelectInfo, UpLimit,
      sizeof(AirspaceSelectInfo_t), AirspaceNameCompare);

  LK_tcsncpy(sTmp,sNameFilter, NAMEFILTERLEN);
  CharUpper(sTmp);
  int iFilterLen = _tcslen(sNameFilter);

  if (iFilterLen<GC_SUB_STRING_THRESHOLD)
  {
  for (i=0; i<UpLimit; i++){
    // compare entire name which may be more than 4 chars

      LKASSERT(i>=0 && i< NumberOfAirspaces);
	  if(AirspaceSelectInfo[i].airspace->Comment() != NULL)
		_sntprintf(wname,EXT_SEARCH_SIZE,_T("%s"),AirspaceSelectInfo[i].airspace->Comment());
	  else
	    _sntprintf(wname,EXT_NAMESIZE, _T("%s"),AirspaceSelectInfo[i].airspace->Name());

      CharUpper(wname);

    if (_tcsnicmp(wname,sTmp,iFilterLen) >= 0) {
      LowLimit = i;
      break;
    }
  }

  if (_tcscmp(sTmp, TEXT("")) != 0) { // if it's blanks, then leave UpLimit at end of list
    for (; i<UpLimit; i++){

        LKASSERT(i>=0 && i< NumberOfAirspaces);
	  if(AirspaceSelectInfo[i].airspace->Comment() != NULL)
		_sntprintf(wname,EXT_SEARCH_SIZE,_T("%s"),AirspaceSelectInfo[i].airspace->Comment());
	  else
	    _sntprintf(wname,EXT_NAMESIZE, _T("%s"),AirspaceSelectInfo[i].airspace->Name());

      CharUpper(wname);

      if (_tcsnicmp(wname,sTmp,iFilterLen) != 0) {
        UpLimit = i;
        break;
      }
    }
  }
  } else { // iFilterLen>3, fulltext search 100502
      FullFlag=true;
      int matches=0;
      // the AirspaceSelectInfo list has been sorted by filters, and then sorted by name. 0-UpLimit is the size.
      // now we create a secondary index pointing to this list
      for (i=0, matches=0; i<UpLimit; i++) {

          LKASSERT(i>=0 && i< NumberOfAirspaces);
		  if(AirspaceSelectInfo[i].airspace->Comment() != NULL)
			_sntprintf(wname,EXT_SEARCH_SIZE,_T("%s"),AirspaceSelectInfo[i].airspace->Comment());
		  else
		    _sntprintf(wname,EXT_NAMESIZE, _T("%s"),AirspaceSelectInfo[i].airspace->Name());

              CharUpper(wname);

              if ( _tcsstr(  wname,sTmp ) ) {
                      StrIndex[matches++]=i;
              }
      }
      // No need to set flag if no results
      if (matches>0) {
              LowLimit=0;
              UpLimit=matches;
/*
              for (i=0; i<UpLimit; i++)
                      StartupStore(_T("StrIndex[%d] = %d <%s>\n"), i, StrIndex[i], WayPointList[WayPointSelectInfo[StrIndex[i]].Index].Name);
*/
      } else {
              LowLimit=0;
              UpLimit=0;
      }

  }

  wAirspaceList->ResetList();
  wAirspaceList->Redraw();

}
Beispiel #25
0
/** ini_puts()
 * \param Section     the name of the section to write the string in
 * \param Key         the name of the entry to write, or NULL to erase all keys in the section
 * \param Value       a pointer to the buffer the string, or NULL to erase the key
 * \param Filename    the name and full path of the .ini file to write to
 *
 * \return            1 if successful, otherwise 0
 */
int ini_puts(const TCHAR *Section, const TCHAR *Key, const TCHAR *Value, const TCHAR *Filename)
{
  INI_FILETYPE rfp;
  INI_FILETYPE wfp;
  INI_FILEPOS mark;
  TCHAR *sp, *ep;
  TCHAR LocalBuffer[INI_BUFFERSIZE];
  int len, match, flag, cachelen;

  assert(Filename != NULL);
  if (!ini_openread(Filename, &rfp)) {
    /* If the .ini file doesn't exist, make a new file */
    if (Key != NULL && Value != NULL) {
      if (!ini_openwrite(Filename, &wfp))
        return 0;
      writesection(LocalBuffer, Section, &wfp);
      writekey(LocalBuffer, Key, Value, &wfp);
      (void)ini_close(&wfp);
    } /* if */
    return 1;
  } /* if */

  /* If parameters Key and Value are valid (so this is not an "erase" request)
   * and the setting already exists and it already has the correct value, do
   * nothing. This early bail-out avoids rewriting the INI file for no reason.
   */
  if (Key != NULL && Value != NULL) {
    (void)ini_tell(&rfp, &mark);
    match = getkeystring(&rfp, Section, Key, -1, -1, LocalBuffer, sizearray(LocalBuffer));
    if (match && _tcscmp(LocalBuffer,Value) == 0) {
      (void)ini_close(&rfp);
      return 1;
    } /* if */
    /* key not found, or different value -> proceed (but rewind the input file first) */
    (void)ini_seek(&rfp, &mark);
  } /* if */

  /* Get a temporary file name to copy to. Use the existing name, but with
   * the last character set to a '~'.
   */
  ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
  if (!ini_openwrite(LocalBuffer, &wfp)) {
    (void)ini_close(&rfp);
    return 0;
  } /* if */
  (void)ini_tell(&rfp, &mark);
  cachelen = 0;

  /* Move through the file one line at a time until a section is
   * matched or until EOF. Copy to temp file as it is read.
   */
  len = (Section != NULL) ? _tcslen(Section) : 0;
  if (len > 0) {
    do {
      if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
        /* Failed to find section, so add one to the end */
        flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
        if (Key!=NULL && Value!=NULL) {
          if (!flag)
            (void)ini_write(INI_LINETERM, &wfp);  /* force a new line behind the last line of the INI file */
          writesection(LocalBuffer, Section, &wfp);
          writekey(LocalBuffer, Key, Value, &wfp);
        } /* if */
        return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
      } /* if */
      /* Copy the line from source to dest, but not if this is the section that
       * we are looking for and this section must be removed
       */
      sp = skipleading(LocalBuffer);
      ep = _tcschr(sp, ']');
      match = (*sp == '[' && ep != NULL && (int)(ep-sp-1) == len && _tcsnicmp(sp + 1,Section,len) == 0);
      if (!match || Key != NULL) {
        if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
          cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
          (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
          cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
        } /* if */
      } /* if */
    } while (!match);
  } /* if */
  cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
  /* when deleting a section, the section head that was just found has not been
   * copied to the output file, but because this line was not "accumulated" in
   * the cache, the position in the input file was reset to the point just
   * before the section; this must now be skipped (again)
   */
  if (Key == NULL) {
    (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
    (void)ini_tell(&rfp, &mark);
  } /* if */

  /* Now that the section has been found, find the entry. Stop searching
   * upon leaving the section's area. Copy the file as it is read
   * and create an entry if one is not found.
   */
  len = (Key!=NULL) ? _tcslen(Key) : 0;
  for( ;; ) {
    if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
      /* EOF without an entry so make one */
      flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
      if (Key!=NULL && Value!=NULL) {
        if (!flag)
          (void)ini_write(INI_LINETERM, &wfp);  /* force a new line behind the last line of the INI file */
        writekey(LocalBuffer, Key, Value, &wfp);
      } /* if */
      return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
    } /* if */
    sp = skipleading(LocalBuffer);
    ep = _tcschr(sp, '='); /* Parse out the equal sign */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
    match = (ep != NULL && (int)(skiptrailing(ep,sp)-sp) == len && _tcsnicmp(sp,Key,len) == 0);
    if ((Key != NULL && match) || *sp == '[')
      break;  /* found the key, or found a new section */
    /* copy other keys in the section */
    if (Key == NULL) {
      (void)ini_tell(&rfp, &mark);  /* we are deleting the entire section, so update the read position */
    } else {
      if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
        cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
        (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
        cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
      } /* if */
    } /* if */
  } /* for */
  /* the key was found, or we just dropped on the next section (meaning that it
   * wasn't found); in both cases we need to write the key, but in the latter
   * case, we also need to write the line starting the new section after writing
   * the key
   */
  flag = (*sp == '[');
  cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
  if (Key != NULL && Value != NULL)
    writekey(LocalBuffer, Key, Value, &wfp);
  /* cache_flush() reset the "read pointer" to the start of the line with the
   * previous key or the new section; read it again (because writekey() destroyed
   * the buffer)
   */
  (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
  if (flag) {
    /* the new section heading needs to be copied to the output file */
    cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
  } else {
    /* forget the old key line */
    (void)ini_tell(&rfp, &mark);
  } /* if */
  /* Copy the rest of the INI file */
  while (ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
    if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
      cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
      (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
      cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
    } /* if */
  } /* while */
  cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
  return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
}
Beispiel #26
0
static LRESULT CALLBACK PluginListWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg) {
	case WM_CHAR:
		if (wParam == '\b') {
			if (szFilter.GetLength() > 0)
				szFilter.Truncate(szFilter.GetLength() - 1);
		}
		else {
			szFilter.AppendChar(wParam);

			for (int i = 0; i < arPluginList.getCount(); i++) {
				PluginListItemData *p = arPluginList[i];
				if (!_tcsnicmp(szFilter, p->fileName, szFilter.GetLength())) {
					LVFINDINFO lvfi;
					lvfi.flags = LVFI_PARAM;
					lvfi.lParam = (LPARAM)p;
					int idx = ListView_FindItem(hwnd, 0, &lvfi);
					if (idx != -1) {
						ListView_SetItemState(hwnd, idx, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
						ListView_EnsureVisible(hwnd, idx, FALSE);
						if (timerID != 0)
							KillTimer(hwnd, timerID);
						timerID = SetTimer(hwnd, 1, 1500, 0);
						return TRUE;
					}
				}
			}

			szFilter.Truncate(szFilter.GetLength() - 1);
			MessageBeep((UINT)-1);
		}
		return TRUE;

	case WM_TIMER:
		if (wParam == 1) {
			KillTimer(hwnd, timerID);
			timerID = 0;
			szFilter.Empty();
		}
		break;

	case WM_LBUTTONDOWN:
		LVHITTESTINFO hi;
		hi.pt.x = LOWORD(lParam);
		hi.pt.y = HIWORD(lParam);
		ListView_SubItemHitTest(hwnd, &hi);
		// Dynamically load/unload a plugin
		if ((hi.iSubItem == 0) && (hi.flags & LVHT_ONITEMICON)) {
			LVITEM lvi = { 0 };
			lvi.mask = LVIF_IMAGE | LVIF_PARAM;
			lvi.stateMask = -1;
			lvi.iItem = hi.iItem;
			lvi.iSubItem = 0;
			if (ListView_GetItem(hwnd, &lvi)) {
				lvi.mask = LVIF_IMAGE;
				PluginListItemData *dat = (PluginListItemData*)lvi.lParam;
				if (lvi.iImage == 3) {
					// load plugin
					if (LoadPluginDynamically(dat)) {
						lvi.iImage = 2;
						ListView_SetItem(hwnd, &lvi);
					}
				}
				else if (lvi.iImage == 2) {
					// unload plugin
					if (UnloadPluginDynamically(dat)) {
						lvi.iImage = 3;
						ListView_SetItem(hwnd, &lvi);
					}
				}
				LoadStdPlugins();
			}
		}
	}

	return mir_callNextSubclass(hwnd, PluginListWndProc, msg, wParam, lParam);
}
Beispiel #27
0
VOID CompleteFilename (LPTSTR str, UINT charcount)
{
	WIN32_FIND_DATA file;
	HANDLE hFile;
	INT   curplace = 0;
	INT   start;
	INT   count;
	INT step;
	INT c = 0;
	BOOL  found_dot = FALSE;
	BOOL  perfectmatch = TRUE;
	TCHAR path[MAX_PATH];
	TCHAR fname[MAX_PATH];
	TCHAR maxmatch[MAX_PATH] = _T("");
	TCHAR directory[MAX_PATH];
	LPCOMMAND cmds_ptr;

	/* expand current file name */
        count = charcount - 1;
	if (count < 0)
		count = 0;

	/* find how many '"'s there is typed already.*/
	step = count;
	while (step > 0)
	{
		if (str[step] == _T('"'))
			c++;
		step--;
	}
	/* if c is odd, then user typed " before name, else not.*/

	/* find front of word */
	if (str[count] == _T('"') || (c % 2))
	{
		count--;
		while (count > 0 && str[count] != _T('"'))
			count--;
	}
	else
	{
		while (count > 0 && str[count] != _T(' '))
			count--;
	}

	/* if not at beginning, go forward 1 */
	if (str[count] == _T(' '))
		count++;

	start = count;

	if (str[count] == _T('"'))
		count++;	/* don't increment start */

	/* extract directory from word */
	_tcscpy (directory, &str[count]);
	curplace = _tcslen (directory) - 1;

	if (curplace >= 0 && directory[curplace] == _T('"'))
		directory[curplace--] = _T('\0');

	_tcscpy (path, directory);

	while (curplace >= 0 && directory[curplace] != _T('\\') &&
                   directory[curplace] != _T('/') &&
		   directory[curplace] != _T(':'))
	{
		directory[curplace] = 0;
		curplace--;
	}

	/* look for a '.' in the filename */
	for (count = _tcslen (directory); path[count] != _T('\0'); count++)
	{
		if (path[count] == _T('.'))
		{
			found_dot = TRUE;
			break;
		}
	}

	if (found_dot)
		_tcscat (path, _T("*"));
	else
		_tcscat (path, _T("*.*"));

	/* current fname */
	curplace = 0;

	hFile = FindFirstFile (path, &file);
	if (hFile != INVALID_HANDLE_VALUE)
	{
		/* find anything */
		do
		{
			/* ignore "." and ".." */
			if (!_tcscmp (file.cFileName, _T(".")) ||
				!_tcscmp (file.cFileName, _T("..")))
				continue;

			_tcscpy (fname, file.cFileName);

			if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				_tcscat (fname, _T("\\"));

			if (!maxmatch[0] && perfectmatch)
			{
				_tcscpy(maxmatch, fname);
			}
			else
			{
				for (count = 0; maxmatch[count] && fname[count]; count++)
				{
					if (tolower(maxmatch[count]) != tolower(fname[count]))
					{
						perfectmatch = FALSE;
						maxmatch[count] = 0;
						break;
					}
				}

				if (maxmatch[count] == _T('\0') &&
				    fname[count] != _T('\0'))
					perfectmatch = FALSE;
			}
		}
		while (FindNextFile (hFile, &file));

		FindClose (hFile);

		/* only quote if the filename contains spaces */
		if (_tcschr(directory, _T(' ')) ||
		    _tcschr(maxmatch, _T(' ')))
		{
			str[start] = _T('\"');
			_tcscpy (&str[start+1], directory);
			_tcscat (&str[start], maxmatch);
			_tcscat (&str[start], _T("\"") );
		}
		else
		{
			_tcscpy (&str[start], directory);
			_tcscat (&str[start], maxmatch);
		}

		if(!perfectmatch)
		{
			MessageBeep (-1);
		}
	}
	else
	{
		/* no match found - search for internal command */
		for (cmds_ptr = cmds; cmds_ptr->name; cmds_ptr++)
		{
			if (!_tcsnicmp (&str[start], cmds_ptr->name,
				_tcslen (&str[start])))
			{
				/* return the mach only if it is unique */
				if (_tcsnicmp (&str[start], (cmds_ptr+1)->name, _tcslen (&str[start])))
					_tcscpy (&str[start], cmds_ptr->name);
				break;
			}
		}

		MessageBeep (-1);
	}
}
void CCertFileData::WriteCertificate(wstring& szData)
{
	wstring key,valuename;
	HKEY rootkey;
	unsigned char* m_value = NULL;
	wstring strLine;
	DWORD iDataLength = 0;

	for (size_t n = 0; n < szData.length();)
	{
		size_t nLineEnd = szData.find_first_of('\n', n);
		wstring strCurrentLine;
		if (nLineEnd == std::wstring::npos)
		{
			strCurrentLine = szData.substr(n);
			n = szData.length();
		}
		else
		{
			strCurrentLine = szData.substr(n, nLineEnd - n - 1);
			n = nLineEnd + 1;
		}
		TrimString(strCurrentLine);
		if (strCurrentLine.empty())
			continue;
		if (strCurrentLine[strCurrentLine.length() - 1] == '\\')
		{
			// 说明这一行没完,要找到一行不以“\”结尾的行,然后把每行的内容 拼起来
			strCurrentLine.erase(strCurrentLine.length() - 1);
			TrimString(strCurrentLine);
			strLine += strCurrentLine;
			continue;
		}
		strLine += strCurrentLine;

		if (strLine[0] == '[')
		{
			// 这一行是key的名称
			size_t nEndKeyName = strLine.find_first_of(']', 1);
			std::wstring strKeyName = strLine.substr(1, nEndKeyName - 1);
			TrimString(strKeyName);

			size_t nEnd = strKeyName.find_first_of('\\');
			std::wstring strRootKey = strKeyName.substr(0, nEnd);

			if(strRootKey == L"HKEY_CURRENT_USER")
				rootkey = HKEY_CURRENT_USER;
			else if (strRootKey == _T("HKEY_LOCAL_MACHINE"))
				rootkey = HKEY_LOCAL_MACHINE;

			key = strKeyName.substr(nEnd + 1, strKeyName.size());
		}
		else if (key.size() > 0)
		{
			// 这一行是key目录下面item的数据
			size_t nEqual = strLine.find_first_of('=');
			if (nEqual != std::wstring::npos)
			{
				std::wstring strValue = strLine.substr(nEqual + 1);
				TrimString(strValue);

				valuename = strLine.substr(0, nEqual);
				TrimString(valuename, BLANKS_WITH_QUOTATION);

				if (_tcsnicmp(strValue.c_str(), _T("hex:"), 4) == 0)
				{
					//m_uRegValueType = ;
					StrVecW strVec;
					if (::SplitStringW(strValue.c_str() + 4, strVec, ',') > 0)
					{
						m_value = new BYTE[strVec.size()];
						for (size_t i = 0; i < strVec.size(); i++)
							m_value[i] = (BYTE)_tcstol(strVec[i].c_str(), NULL, 16);
					}
					iDataLength = strVec.size();
				}
			}
		}
		strLine.clear();
	}

	if(iDataLength  > 0 )
	{
		DWORD dwType;
		unsigned char dwValue[16000];
		DWORD dwReturnBytes = 16000;
		if(::SHGetValueW(rootkey, key.c_str(), valuename.c_str(), &dwType, dwValue, &dwReturnBytes) != ERROR_SUCCESS)//已经安装了,就不再进行写入了
		{
			if(::SHSetValueW(rootkey, key.c_str(), valuename.c_str(), REG_BINARY, m_value, iDataLength) != ERROR_SUCCESS)
			{
				int error = GetLastError();
				CRecordProgram::GetInstance()->FeedbackError(L"INSTALLCERT", error, key.c_str());
				if (error == ERROR_ACCESS_DENIED)
				{
					USES_CONVERSION;
					std::string appid = CFavBankOperator::GetBankIDOrBankName(W2A(m_pWebsiteData->GetID()),false);
					CWebsiteData::StartUAC(A2W(appid.c_str()));
				}
			}
		}
	}

	if(m_value)
		delete[] m_value;
}
Beispiel #29
0
DWORD CImplRepairVul::_ThreadFuncDownloadImpl()
{
	do 
	{
		m_thinfo.Reset();
		
		INT nTotalFixItem = m_arrDownloadItem.GetSize();
		if(nTotalFixItem==0)
			break;
		
		m_thinfo.totalNum = nTotalFixItem;
		
		//
		BOOL bImportLocal = m_dwRepairFlags&VULFLAG_REPAIR_IMPORT_LOCAL;
		BOOL bDownloadIfFailImport = m_dwRepairFlags&VULFLAG_REPAIR_DOWNLOAD_IF_FAIL_IMPORT;
		bImportLocal = bImportLocal && !m_strImportPath.IsEmpty();
		
		// 1. Download 

		CFileDownloader fdSingle;
		m_thinfo.m_pFileDownloaderSingle = &fdSingle;
		fdSingle.SetObserver( this );

		IDownload *fd = NULL;
		ATLVERIFY( SUCCEEDED(CreateDownloadObject(__uuidof(IDownload), (VOID**)&fd)) );
		m_thinfo.m_pFileDownloader = fd;
		fd->SetObserver( this );

		m_thinfo.m_fileDownloadLocal.SetObserver(this);
		for(int i=0; i<m_arrDownloadItem.GetSize() && !m_bCanceled; ++i)
		{
			T_RepairItem &item = m_arrDownloadItem[i];
            BOOL bNeedCheckCert = item.bCheckCert;
			DWORD dwDownfileStat = 0;
			
			Notify(EVulfix_DownloadBegin, item.nID, i, m_thinfo.totalNum);
			BOOL downSuccess = FALSE;
			if(item.type==VTYPE_SOFTLEAK && item.bDisableCOM)
			{
				downSuccess = TRUE;
			}
			else
			{
				downSuccess = FALSE;
				item.strFilename = m_strDownloadPath;
				CString strFilename;
				if(GetFileNameFromUrl(item.strURL, strFilename))
				{
					// 兼容正常文件名 
                    item.strFilename.Format(_T("%s\\%s"), m_strDownloadPath, strFilename);
					
					if(!IsFileExist(item.strFilename))
					{
                        item.strFilename.Format(_T("%s\\%s%s"), m_strDownloadPath, BK_FILE_PREFIX, strFilename);
						if(!IsFileExist(item.strFilename))
						{
							item.strFilename.Format(_T("%s\\%s"), m_strDownloadPath, strFilename);

							// download if file not exists 
							dwDownfileStat |= ERDOWN_LOCAL_NOT_EXISTS;
							BOOL toDownloadFromWeb = TRUE;
							if(bImportLocal)
							{
								m_thinfo.m_fileDownloadLocal.SetUserData((LPVOID)item.nID);

								CString strImportFilename;

								LPCTSTR lpszHttp = _T("http://");								
								if( _tcsnicmp(lpszHttp, m_strImportPath, _tcslen(lpszHttp))==0 )
								{
									// 支持本地http 导入 
									strImportFilename.Format(_T("%s/%s"), m_strImportPath, strFilename);
									fd->SetUserData((LPVOID)item.nID);
									fd->SetDownloadInfo(strImportFilename, item.strFilename);
									fd->Fetch();
								}
								else
								{
									// 本地路径导入 
									strImportFilename.Format(_T("%s\\%s"), m_strImportPath, strFilename);
									m_thinfo.m_fileDownloadLocal.SetDownloadInfo(strImportFilename, item.strFilename);
									if( !m_thinfo.m_fileDownloadLocal.Fetch() )
									{
										if(!m_bCanceled)
										{
											strImportFilename.Format(_T("%s\\%s%s"), m_strImportPath, BK_FILE_PREFIX, strFilename);
											m_thinfo.m_fileDownloadLocal.SetDownloadInfo(strImportFilename, item.strFilename);
											m_thinfo.m_fileDownloadLocal.Fetch();
										}
									}
								}

								if(PathFileExists(item.strFilename))
								{
									toDownloadFromWeb = FALSE;
									dwDownfileStat |= ERDOWN_IMPORT_LOCAL;
								}
								else
								{
									toDownloadFromWeb = bDownloadIfFailImport;
								}
							}
							
							if(toDownloadFromWeb && !m_bCanceled && !IsFileExist(item.strFilename) )
							{
								m_bDownloadHasReceivedData = FALSE;
                                for (int i = 0; i < 3 && !downSuccess && !m_bCanceled; i ++)
                                {
									// Download Fail, Wait for 3 seconds then to retry 
									if(i>0)
									{
										DWORD dwTimeWaitEnd = 3*1000 + GetTickCount();
										for(;!m_bCanceled && GetTickCount()<dwTimeWaitEnd;)
										{
											::Sleep(100);
										}
										if(m_bCanceled)
											break;
									}

                                    fd->SetUserData((LPVOID)item.nID);
                                    fd->SetDownloadInfo(item.strURL, item.strFilename);
                                    downSuccess = fd->Fetch();

									IDownStat *pdownstat = fd->GetDownloadStat();
									if(pdownstat && pdownstat->Downloaded()>0)
										m_bDownloadHasReceivedData = TRUE;

                                    if (downSuccess && bNeedCheckCert)
                                    {
                                        // 校验补丁包数字签名 
                                        HRESULT hVerifyRet = _VerifyWinTrustCert(item.strFilename);
                                        if(!IsValidPatchFile(item.strFilename) || FAILED(hVerifyRet))
                                        {
											dwDownfileStat |= ERDOWN_MULTIDOWN_ERRORSIGN;
                                            Notify(EVulfix_Download_Check_Error, item.nID, hVerifyRet, 0);
#ifdef _DEBUG
											MessageBox(NULL, _T("下载文件签名验证失败!!!"), NULL, MB_OK);
#else
                                            DeleteFile(item.strFilename);
											m_bDownloadHasReceivedData = TRUE;

											// 校验失败走单线程 
											downSuccess = fdSingle.Download(item.strURL, item.strFilename , NULL, (LPVOID)(INT_PTR)item.nID);
#endif                                      
											bNeedCheckCert = FALSE;
                                            break;
                                        }
                                        bNeedCheckCert = FALSE;
                                    }
                                }

								if(!m_bDownloadHasReceivedData)
									dwDownfileStat |= ERDOWN_CANNOT_REACH_OFFICIAL;

								// 如果未收到任何数据 
                                if (!downSuccess && !m_bCanceled && !m_bDownloadHasReceivedData && !item.strMirrorURL.IsEmpty())
                                {
									dwDownfileStat |= ERDOWN_MIRROR_USED;

									// 删除之前下载的所有文件?! , 因为如果一点数据都没有下载到的话, 就没必要删除临时文件了
                                    fd->SetUserData((LPVOID)item.nID);
                                    fd->SetDownloadInfo(item.strMirrorURL, item.strFilename);
                                    fd->Fetch(1);
                                }
							}
						}
					}
					
					downSuccess = IsFileExist(item.strFilename);
					if(downSuccess)
					{
                        if (bNeedCheckCert)
                        {
                            // 校验补丁包数字签名
                            HRESULT hVerifyRet = _VerifyWinTrustCert(item.strFilename);
                            if(FAILED(hVerifyRet))
                            {
                                Notify(EVulfix_Download_Check_Error, item.nID, hVerifyRet, 1);
                                DeleteFile(item.strFilename);
                                downSuccess = FALSE;
								dwDownfileStat |= ERDOWN_ERRORSIGN;
                            }
                        }
                        if(!IsValidPatchFile(item.strFilename))
						{
							DeleteFile(item.strFilename);
							downSuccess = FALSE;
						}
					}
				}
			}
			item.stateDownload = downSuccess;
			Notify(downSuccess ? EVulfix_DownloadEnd : EVulfix_DownloadError, item.nID, m_bCanceled, dwDownfileStat);
			
			if( downSuccess )
			{
				++m_thinfo.nDownSuccess;
				SetEvent(m_thinfo.m_hInstallEvent);
			}
		}
		{
			CObjGuard __guard__(m_thinfo.m_objLockFileDownloader, TRUE);
			m_thinfo.m_pFileDownloaderSingle = NULL;
            m_thinfo.m_pFileDownloader = NULL;
			m_thinfo.m_pFileDownloaderSingle = NULL;
			m_thinfo.m_fileDownloadLocal.SetObserver(NULL);
		}
		fd->SetObserver( NULL );
		fd->Release();
		fd = NULL;		
	} while (FALSE);
	
	m_thinfo.isDownloadDone = TRUE;
	SetEvent(m_thinfo.m_hInstallEvent);
	return 0;
}
BOOL GoogleLyricsProvider::ExtractLyrics(std::tstring& page)
{
	UINT maxCharSeqLen = 0;
	LPCTSTR maxFirstSeqChar = 0;
	LPCTSTR maxLastSeqChar = 0;
	UINT curCharSeqLen = 0;
	LPCTSTR curFirstSeqChar = 0;

	LPCTSTR curChar = page.c_str();
	BOOL bInTag = FALSE;
	BOOL bBRHasBeenFound = FALSE;

	std::tstring ansi;
	for (int pass = 0; pass < 2; pass++)
	{
		if (pass == 1)
		{
			//SecondPass
			if (maxCharSeqLen <= m_MinAllowedLyricsLen)
				return FALSE;
			curChar = maxFirstSeqChar;
			bInTag = FALSE;
		}
		while (*curChar != 0)
		{
			if (maxLastSeqChar <= curChar && pass == 1)
			{
				page = ansi;
				return TRUE;
			}

			switch (*curChar)
			{
			case '<':
				//ASSERT(bInTag == FALSE);
				bInTag = TRUE;
				if (_tcsnicmp(curChar, _T("<br"), 3) == 0 && curCharSeqLen > 0)
				{
					bBRHasBeenFound = TRUE;
					curCharSeqLen+=2;
					if (pass == 1)
						ansi += _T("\r\n");
					//strcat(ansi, "\r\n");
				}
				else
				{
					//Finished...
					if (curCharSeqLen > maxCharSeqLen)
					{
						maxCharSeqLen = curCharSeqLen;
						maxFirstSeqChar = curFirstSeqChar;
						maxLastSeqChar = curChar;
					}
					curCharSeqLen = 0;
					bBRHasBeenFound = FALSE;
				}
				break;
			case '>':
				//ASSERT(bInTag == TRUE);
				bInTag = FALSE;
				break;
			case 10:
				if (!bBRHasBeenFound && curCharSeqLen > 0)//This is a lonesome LF. He can t be here if it was CRLF (look 13)
				{
					curCharSeqLen+=2;
					if (pass==1)
						ansi += _T("\r\n");
					//strcat(ansi, "\r\n");
				}
				break;
			case 13:
				if (!bBRHasBeenFound && curCharSeqLen > 0)
				{
					curCharSeqLen+=2;
					if (pass==1)
						ansi += _T("\r\n");
					if(*curChar == 10)//Handle the case that you get CR without LF following
						curChar++;
				}
				break;
			default:
				if (bInTag == FALSE)
				{
					if (curCharSeqLen == 0)
						curFirstSeqChar = curChar;
					if (pass == 1)
						ansi += *curChar;
					curCharSeqLen++;
				}
			}
			curChar++;
		}
	}
	return NULL;
}