示例#1
1
/**
 * Removes a string from a registry string list (STRING_SZ).
 * Only operates in HKLM for now, needs to be extended later for
 * using other hives. Only processes lists with a "," separator
 * at the moment.
 *
 * @return  Exit code (EXIT_OK, EXIT_FAIL)
 * @param   pszSubKey           Sub key containing the list.
 * @param   pszKeyValue         The actual key name of the list.
 * @param   pszValueToRemove    The value to remove from the list.
 */
int RegistryRemoveStringFromList(const TCHAR *pszSubKey, const TCHAR *pszKeyValue, const TCHAR *pszValueToRemove)
{
    HKEY hKey = NULL;
    DWORD disp, dwType;
    LONG lRet = RegCreateKeyEx(HKEY_LOCAL_MACHINE, pszSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, &hKey, &disp);
    if (lRet != ERROR_SUCCESS)
        _tprintf(_T("RegistryRemoveStringFromList: RegCreateKeyEx %ts failed with error %ld!\n"), pszSubKey, lRet);

    TCHAR szKeyValue[512] = { 0 };
    TCHAR szNewKeyValue[512] = { 0 };
    DWORD cbKeyValue = sizeof(szKeyValue);

    lRet = RegQueryValueEx(hKey, pszKeyValue, NULL, &dwType, (LPBYTE)szKeyValue, &cbKeyValue);
    if (   lRet != ERROR_SUCCESS
        || dwType != REG_SZ)
    {
        _tprintf(_T("RegistryRemoveStringFromList: RegQueryValueEx failed with %d, key type = 0x%x!\n"), lRet, dwType);
    }

    if (lRet == ERROR_SUCCESS)
    {
    #ifdef DEBUG
        _tprintf(_T("RegistryRemoveStringFromList: Key value: %ws\n"), szKeyValue);
    #endif

        /* Create entire new list. */
        int iPos = 0;

        TCHAR *pszToken = wcstok(szKeyValue, _T(","));
        TCHAR *pszNewToken = NULL;
        while (pszToken != NULL)
        {
            pszNewToken = wcstok(NULL, _T(","));

            /* Append all list values as long as it's not the
             * value we want to remove. */
            if (wcsicmp(pszToken, pszValueToRemove))
            {
                wcscat(szNewKeyValue, pszToken);
                wcscat(szNewKeyValue, _T(","));
                iPos++;
            }

    #ifdef DEBUG
            _tprintf (_T("RegistryRemoveStringFromList: Temp new key value: %ws\n"), szNewKeyValue);
    #endif
            pszToken = pszNewToken;
        }

        /* Last char a delimiter? Cut off ... */
        if (szNewKeyValue[wcslen(szNewKeyValue) - 1] == ',')
            szNewKeyValue[wcslen(szNewKeyValue) - 1] = '\0';

        size_t iNewLen = (wcslen(szNewKeyValue) * sizeof(WCHAR)) + sizeof(WCHAR);

    #ifdef DEBUG
        _tprintf(_T("RegistryRemoveStringFromList: New provider list: %ws (%u bytes)\n"), szNewKeyValue, iNewLen);
    #endif

        lRet = RegSetValueExW(hKey, pszKeyValue, 0, REG_SZ, (LPBYTE)szNewKeyValue, (DWORD)iNewLen);
        if (lRet != ERROR_SUCCESS)
            _tprintf(_T("RegistryRemoveStringFromList: RegSetValueEx failed with %ld!\n"), lRet);
    }

    RegCloseKey(hKey);
    return (lRet == ERROR_SUCCESS) ? EXIT_OK : EXIT_FAIL;
}
示例#2
0
文件: regproc.c 项目: Moteesh/reactos
/******************************************************************************
 * This funtion is the main entry point to the deletetValue type of action.  It
 * receives the currently read line and dispatch the work depending on the
 * context.
 */
void doDeleteValue(LPTSTR line) {
  _tprintf(_T("deleteValue not yet implemented\n"));
}
示例#3
0
文件: regproc.c 项目: Moteesh/reactos
/******************************************************************************
 * This funtion is the main entry point to the createKey type of action.  It
 * receives the currently read line and dispatch the work depending on the
 * context.
 */
void doCreateKey(LPTSTR line)   {
  _tprintf(_T("createKey not yet implemented\n"));
}
int _tmain(int argc, _TCHAR* argv[])
{	
	bool enableEnum = false;
	bool enableName = false;

	argv++;
	argc--;
	
	bool okArgs = false;

	if (argc == 1)
		okArgs = true;
	else if (argc == 2)
	{
		if (argv[1][0] == '-'
			&& (argv[1][1] == 'e' || argv[1][1] == 'E' || argv[2][1] == 's' || argv[2][1] == 'S')
			)
		okArgs = true;
	}
	else if (argc == 3)
	{
		if (argv[1][0] == '-' && argv[2][0] == '-'
			&& (argv[1][1] == 'e' || argv[1][1] == 'E' || argv[1][1] == 's' || argv[1][1] == 'S')
			&& (argv[2][1] == 'e' || argv[2][1] == 'E' || argv[2][1] == 's' || argv[2][1] == 'S') 
			)
		okArgs = true;
	}

	if (okArgs)
	{
		if (argc >= 2)
		{	
			if (argv[1][1] == 'e' || argv[1][1] == 'E')
				enableEnum = true;
			if (argv[1][1] == 's' || argv[1][1] == 'S')
				enableName = true;

		}

		if (argc >= 3)
		{	
			if (argv[2][1] == 'e' || argv[2][1] == 'E')
				enableEnum = true;
			if (argv[2][1] == 's' || argv[2][1] == 'S')
				enableName = true;

		}

		if (!enableEnum && !enableName)
			enableEnum = true;

		TCHAR* inputFilename = argv[0];
		//TCHAR* inputFilename = _T("D:\\Projects\\Tools\\EditableEditor2\\exml\\EditorSave.exbn");
		//int _len = _tcslen(argv[0]);

		char package[256] = {0};

		if (argc == 3)
		{
			char* _package = package;

			wcharToChar(argv[2] , &_package , 256 );
		}

		//if (argc < 3)
		{	
			_tprintf(_T("input file\n"));
			DBG_TRACE(inputFilename);

			ByteArray ba(inputFilename);
			ba.endian = Endian::BIG;

			for (int i = _tcslen(inputFilename) ; i >=0 ; i-- )
			{
				if (inputFilename[i] == '\\' || inputFilename[i] == '/')
				{
					TCHAR back = inputFilename[i];
					inputFilename[i] = '\0';

					char path[256] = {0};
					char* _path = path;
					wcharToChar(inputFilename , &_path , 256 );

					_chdir(path);

					inputFilename[i] = back;
					break;
				}
			}


			if (readFileHead(ba))
			{
				_tprintf(_T("file head ok!!\n"));

				//////////////////////////////////////////////////////////////////////////
				int strPoolLength= 	ba.readUnsignedByteOrShort();
				DBG_TRACE(_T("strPoolLength %d") , strPoolLength);
				ASSERT(strPoolLength < countof(s_stringPool) , _T("too much strPoolLength"));

				for (int i = 0 ; i < strPoolLength; i++ )
				{
					int strLeng = ba.readUnsignedByteOrShort(); 
					char* _name = new char[strLeng+1];
					ba.readBytes((unsigned char* )(_name) ,strLeng+1 , 0 , strLeng );
					_name[strLeng] = '\0';


					printf("Get string[%d]: %s\n" , s_stringPool_index , _name );

					s_stringPool[s_stringPool_index++] = _name;

					
				}
				//////////////////////////////////////////////////////////////////////////

				//int classPoolDataLength = ba.readUnsignedShortOrInt();
				//int destEnd = ba.getPosition() + classPoolDataLength;

				int classPoolLength  =  ba.readUnsignedByteOrShort();
				DBG_TRACE(_T("classPoolLength %d") , classPoolLength);
				ASSERT(classPoolLength < countof(s_classPool) , _T("too much classPoolLength"));

				for (int i  = 0 ; i < classPoolLength; i++ )
				{
					ClassBinStruct& _cbs = s_classPool[s_classPool_index++];
					_cbs.needExport = false;

					_cbs.classNameId = ba.readUnsignedByteOrShort();
					ASSERT(_cbs.classNameId  < s_stringPool_index , _T("error string"));
					_cbs.className = s_stringPool[_cbs.classNameId];
					_cbs.variableNum = ba.readUnsignedByteOrShort();

					ASSERT(_cbs.variableNum < countof(_cbs.variableArray) , _T("too much variableNum"));

					printf("find class %s _cbs.className %d\n" , _cbs.className , _cbs.variableNum);

					for (int vi = 0 ; vi <  _cbs.variableNum; vi++ )
					{
						VariableBinStruct& vbs = _cbs.variableArray[vi];
						vbs.variableNameId = ba.readUnsignedByteOrShort();
						ASSERT(vbs.variableNameId  < s_stringPool_index , _T("error string"));
						vbs.variableName = s_stringPool[vbs.variableNameId];

						vbs.type = (VariableBinStruct::eVType)ba.readByte();
						vbs.inlineClassId = -1;

						if (vbs.type == VariableBinStruct::TYPE_INSTANCE_UID_INLINE || vbs.type == VariableBinStruct::TYPE_INSTANCE_UID)
							vbs.inlineClassId = ba.readUnsignedByteOrShort();
						else
							vbs.inlineClassId = -1;

						if (vbs.type == VariableBinStruct::TYPE_INSTANCE_UID_INLINE)
						{	
							printf(("    var %d %s type %d inline class %s\n") ,  vi , vbs.variableName , vbs.type , s_classPool[vbs.inlineClassId].className);
						}
						else if (vbs.type == VariableBinStruct::TYPE_INSTANCE_UID)
						{	
							printf(("    var %d %s type %d class %s\n") ,  vi , vbs.variableName , vbs.type , s_classPool[vbs.inlineClassId].className);
						}
						else
						{	
							printf(("    var %d %s type %d\n") ,  vi , vbs.variableName , vbs.type);
						}
					} 

				}
				//ASSERT(destEnd == ba.getPosition() , _T("error"));

				//////////////////////////////////////////////////////////////////////////

				//find root class
				int classInstanceLength  =  ba.readUnsignedByteOrShort();
				
				//int instancPose = ba.getPosition();

				printf("classInstanceLength %d\n" , classInstanceLength);

				for (int i  = 0 ; i < classInstanceLength; i++ )
				{
					int classDataLength = ba.readUnsignedByteOrShort();
					int pos = ba.getPosition();
					int endPos = pos + classDataLength;
					int clsId =  ba.readUnsignedByteOrShort();

					ASSERT(clsId < s_classPool_index , _T("error string"));

					ClassBinStruct& _cbs = s_classPool[clsId];
					_cbs.needExport = true;

					ba.setPosition(endPos);

				}


				for (int classi = 0; classi < s_classPool_index ; classi++)
				{
					ClassBinStruct& _cbs = s_classPool[classi];
					if (_cbs.needExport)
					{	
						printf("export class %s\n" , _cbs.className);
						
						bool hasInstance = false;

						ByteArray output;
						output.writeMultiByte("#ifndef __EXBN_");
						output.writeMultiByte(_cbs.className);
						output.writeMultiByte("_H__\n");
						output.writeMultiByte("#define __EXBN_");
						output.writeMultiByte(_cbs.className);
						output.writeMultiByte("_H__\n");

						//output.writeMultiByte("\timport ExbnDecoder.*;\n");
						//output.writeMultiByte("\timport flash.utils.ByteArray;\n");

						output.writeMultiByte("\nclass ");
						output.writeMultiByte(_cbs.className);
						output.writeMultiByte(" : public ExbnClassBase {\n");

						output.writeMultiByte("\npublic : \n");
						output.writeMultiByte("\n\t");
						output.writeMultiByte("static ExbnClassBase* createInstace(unsigned int a_instanceUID) {return NEW ");
						output.writeMultiByte(_cbs.className);
						output.writeMultiByte("(a_instanceUID);}");

						output.writeMultiByte("\n\t");
						output.writeMultiByte(_cbs.className);
						output.writeMultiByte("(unsigned int a_instanceUID) : ExbnClassBase(a_instanceUID) {");
							
						if (enableEnum)
						{
							output.writeMultiByte("\n\t\t");
							output.writeMultiByte("EXBN_CLS_ENUM = EXBN_ENUM_");
							output.writeMultiByte(_cbs.className);
							output.writeMultiByte(";");
						}
						if (enableName)
						{
							output.writeMultiByte("\n\t\t");
							output.writeMultiByte("EXBN_CLS_NAME = _T(\"");
							output.writeMultiByte(_cbs.className);
							output.writeMultiByte("\");");
						}

						output.writeMultiByte("\n\t}\n");

						for (int vi = 0 ; vi <  _cbs.variableNum; vi++ )
						{

							VariableBinStruct& vbs = _cbs.variableArray[vi];

							if (getInlineTypeNeedDispose(vbs))
								hasInstance = true;

							output.writeMultiByte("\t");
							output.writeMultiByte(getInlineTypeType(vbs));
							output.writeMultiByte(" ");
							output.writeMultiByte(vbs.variableName);

							output.writeMultiByte(";\n");

						}

						output.writeMultiByte("\n\n");
						{

							
							output.writeMultiByte("\tvoid virtual decode(ByteArray& ba , ExbnEnv& a_env ) {\n");
							
							for (int vi = 0 ; vi <  _cbs.variableNum; vi++ )
							{

								VariableBinStruct& vbs = _cbs.variableArray[vi];

								output.writeMultiByte("\t\t");
								output.writeMultiByte(vbs.variableName);
								output.writeMultiByte(" = ");
								output.writeMultiByte(getInlineTypeRead(vbs));


								output.writeMultiByte("\n");

							}
							

							output.writeMultiByte("\n\t}\n\n");
						}
						
					
						


						/*
						if (hasInstance)
						{
							output.writeMultiByte("\n\n");
							output.writeMultiByte("\t\tpublic override function dispose() : void {\n");
							
							for (int vi = 0 ; vi <  _cbs.variableNum; vi++ )
							{

								VariableBinStruct& vbs = _cbs.variableArray[vi];

								if (getInlineTypeNeedDispose(vbs))
								{
									
									if (vbs.inlineClassId != -1 && (vbs.type == VariableBinStruct::TYPE_INSTANCE_UID))
									{
										output.writeMultiByte("\t\t\tif (");
										output.writeMultiByte(vbs.variableName);
										output.writeMultiByte(") ");

										output.writeMultiByte(vbs.variableName);
										output.writeMultiByte(".dispose();\n");

									}
									output.writeMultiByte("\t\t\t");
									output.writeMultiByte(vbs.variableName);
									output.writeMultiByte(" = null;\n");


									
								}	

							}

							output.writeMultiByte("\n\t\t\t");
							output.writeMultiByte("super.dispose();");
							output.writeMultiByte("\n");

							output.writeMultiByte("\n\t\t}\n\n");
						}

						output.writeMultiByte("\t}\n");*/

						output.writeMultiByte("};\n#endif\n\0");
						
						char outputfilename[256];
						sprintf_s(outputfilename, 256, "%s.hpp" , _cbs.className);


						output.save(outputfilename);

					}
				}
				//////////////////////////////////////////////////////////////////////////
				//system("pause");

			}

		}

	}
	else
	{
		_tprintf(_T("\a"));//di
		_tprintf( _T("plz use as ExbnExporter inputFilename (-enum -string) \ne.g. ExbnExporter c:\\a.exbn -enum -string\n"));
		
		
		for (int i = 0 ; i< argc; i++)
		{	
			_tprintf(_T("\n %d:") , i );
			_tprintf(argv[i]);

		}
		_tprintf(_T("\n"));
		system("pause");
	}
	




	return 0;
}
static int
CmdRemoveServices ()
{
  SC_HANDLE service;
  SC_HANDLE svc_ctl_mgr;
  SERVICE_STATUS status;
  int i, ret = _service_max;

  svc_ctl_mgr = OpenSCManager (NULL, NULL, SC_MANAGER_CONNECT);
  if (svc_ctl_mgr == NULL)
    {
      _tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText ());
      return 1;
    }

  for (i = 0; i < _service_max; i++)
    {
      openvpn_service_t *ovpn_svc = &openvpn_service[i];
      service = OpenService (svc_ctl_mgr, ovpn_svc->name,
                             DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
      if (service == NULL)
        {
          _tprintf (TEXT("OpenService failed - %s\n"), GetLastErrorText ());
          goto out;
        }

      /* try to stop the service */
      if (ControlService (service, SERVICE_CONTROL_STOP, &status))
        {
          _tprintf (TEXT("Stopping %s."), ovpn_svc->display_name);
          Sleep (1000);

          while (QueryServiceStatus (service, &status))
            {
              if (status.dwCurrentState == SERVICE_STOP_PENDING)
                {
                  _tprintf (TEXT("."));
                  Sleep (1000);
                }
              else
                break;
            }

          if (status.dwCurrentState == SERVICE_STOPPED)
            _tprintf (TEXT("\n%s stopped.\n"), ovpn_svc->display_name);
          else
            _tprintf (TEXT("\n%s failed to stop.\n"), ovpn_svc->display_name);
        }

      /* now remove the service */
      if (DeleteService (service))
        {
          _tprintf (TEXT("%s removed.\n"), ovpn_svc->display_name);
          --ret;
        }
      else
        _tprintf (TEXT("DeleteService failed - %s\n"), GetLastErrorText ());

      CloseServiceHandle (service);
    }

out:
  CloseServiceHandle (svc_ctl_mgr);
  return ret;
}
示例#6
0
 void ReportError(LPTSTR szMsg)
 {
     _tprintf(szErrorFormat, GetLastError(), szMsg);
 }
示例#7
0
static int handleCommands(FILE *fd)
{
    char buf[BUFLEN + 1], commandLine[BUFLEN + 1];
    int rv = EXIT_SUCCESS, i;
    char *token;
    OptionStr optionStr;

    while (fgets (buf, BUFLEN, fd) != NULL) {

	// copy command line for printing it out later
	strncpy (commandLine, buf, BUFLEN);

	token = strtokCheckComment(buf);
	while (token != NULL) {
	    if (token[0] == '#' || strncmp (token, "//", 2) == 0)
		break;

	    // print command line
	    printf ("%s", commandLine);

	    if (strcmp(token, "establish_context") == 0) {
		// Establish context
		rv = establish_context(&cardContext);
		if (rv != OPGP_ERROR_SUCCESS) {
		    printf ("establish_context failed with error 0x%08X\n", rv);
			rv = EXIT_FAILURE;
			goto end;
		}
		break;
	    } else if (strcmp(token, "release_context") == 0) {
		// Release context
		rv = release_context(cardContext);
		if (rv != OPGP_ERROR_SUCCESS) {
		    printf ("release_context failed with error 0x%08X\n", rv);
			rv = EXIT_FAILURE;
			goto end;
		}

		break;
	    } else if (strcmp(token, "card_connect") == 0) {
		TCHAR buf[BUFLEN + 1];
		DWORD readerStrLen = BUFLEN;
		// open reader
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (_tcslen(optionStr.reader) == 0) {
			int j=0;
			int k=0;

			// get all readers
		    rv = list_readers (cardContext, buf, &readerStrLen);

			for (j=0; j<(int)readerStrLen;) {
				/* Check for end of readers */
				if (buf[j] == _T('\0'))
					break;
				_tcsncpy(optionStr.reader, buf+j, READERNAMELEN+1);
				if (k == optionStr.readerNumber)
					break;
				k++;
				j+=(int)_tcslen(buf+j)+1;
			}
			optionStr.reader[READERNAMELEN] = _T('\0');

#ifdef DEBUG
		    _tprintf ( _T("* reader name %s\n"), optionStr.reader);
#endif
		}

		rv = card_connect (cardContext, optionStr.reader,
				   &cardInfo, optionStr.protocol);

		if (rv != 0) {
		    _tprintf (_T("card_connect() returns 0x%08X (%s)\n"), rv,
			      stringify_error(rv));
		}

		break;
	    } if (strcmp(token, "open_sc") == 0) {
		// open secure channel
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
			if (gemXpressoPro) {
				rv = GemXpressoPro_create_daughter_keys(cardInfo, optionStr.key,  
								 optionStr.enc_key, optionStr.mac_key, optionStr.kek_key);
				if (rv != 0) {
					_tprintf (_T("GemXpressoPro_create_daughter_keys() returns 0x%08X (%s)\n"),
						rv, stringify_error(rv));
					rv = EXIT_FAILURE;
					goto end;
				}
			}
		    rv = OP201_mutual_authentication(cardInfo,
						     optionStr.enc_key,
						     optionStr.mac_key,
							 optionStr.kek_key,
						     optionStr.keySetVersion,
						     optionStr.keyIndex,
						     optionStr.securityLevel,
						     &securityInfo201);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
			if (optionStr.scp == 0 || optionStr.scpImpl == 0) {
				rv = GP211_get_secure_channel_protocol_details(cardInfo,
					&optionStr.scp,
					&optionStr.scpImpl);
				if (rv != 0) {
					_tprintf (_T("GP211_get_secure_channel_protocol_details() returns 0x%08X (%s)\n"),
						rv, stringify_error(rv));
					rv = EXIT_FAILURE;
					goto end;
				}
			}

		    rv = GP211_mutual_authentication(cardInfo,
						     optionStr.key,
						     optionStr.enc_key,
						     optionStr.mac_key,
						     optionStr.kek_key,
						     optionStr.keySetVersion,
						     optionStr.keyIndex,
						     optionStr.scp,
						     optionStr.scpImpl,
						     optionStr.securityLevel,
						     &securityInfo211);

		}

		if (rv != 0) {
		    _tprintf (_T("mutual_authentication() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}

		break;
	    } else if (strcmp(token, "select") == 0) {
		// select instance
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		rv = select_application (cardInfo,
                                         (PBYTE)optionStr.AID, optionStr.AIDLen);
		if (rv != 0) {
		    _tprintf (_T("select_application() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}
		break;
	    } else if (strcmp(token, "getdata") == 0) {
		// Get Data
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		// TODO: get data
		break;
	    } else if (strcmp(token, "load") == 0) {
		// Load Applet
		DWORD receiptDataLen = 0;
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
		    rv = OP201_load(cardInfo, &securityInfo201,
				    NULL, 0,
				    optionStr.file,
				    NULL, &receiptDataLen);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
		    rv = GP211_load(cardInfo, &securityInfo211,
				    NULL, 0,
				    optionStr.file,
				    NULL, &receiptDataLen);
		}

		if (rv != 0) {
		    _tprintf (_T("load_applet() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}

		break;
	    }  else if (strcmp(token, "delete") == 0) {
		// Delete Applet
		OPGP_AID AIDs[1];

		DWORD receiptLen = 10;

		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		memcpy (AIDs[0].AID, optionStr.AID, optionStr.AIDLen);
		AIDs[0].AIDLength = optionStr.AIDLen;

		if (platform_mode == PLATFORM_MODE_OP_201) {
		    OP201_RECEIPT_DATA receipt[10];
		    rv = OP201_delete_application(cardInfo, &securityInfo201,
					      AIDs, 1,
					      (OP201_RECEIPT_DATA *)receipt,
					      &receiptLen);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
		    GP211_RECEIPT_DATA receipt[10];
		    rv = GP211_delete_application(cardInfo, &securityInfo211,
						  AIDs, 1,
						  (GP211_RECEIPT_DATA *)receipt,
						  &receiptLen);

		}

		if (rv != 0) {
		    _tprintf (_T("delete_applet() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
		}
		break;
	    }

	    else if (strcmp(token, "install") == 0) {
			// One step install
			OPGP_LOAD_FILE_PARAMETERS loadFileParams;
			DWORD receiptDataAvailable = 0;
			DWORD receiptDataLen = 0;
			char installParam[1];
			installParam[0] = 0;

			rv = handleOptions(&optionStr);
			if (rv != EXIT_SUCCESS) {
				goto end;
			}
			rv = read_executable_load_file_parameters(optionStr.file, &loadFileParams);
			if (rv != EXIT_SUCCESS) {
				_tprintf (_T("read_executable_load_file_parameters() returns 0x%08X (%s)\n"),
					rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
			}
			if (optionStr.pkgAIDLen == 0) {
				optionStr.pkgAIDLen = loadFileParams.loadFileAID.AIDLength;
				memcpy(optionStr.pkgAID, loadFileParams.loadFileAID.AID, optionStr.pkgAIDLen);
			}
			if (optionStr.AIDLen == 0) {
				optionStr.AIDLen = loadFileParams.appletAIDs[0].AIDLength;
				memcpy(optionStr.AID, loadFileParams.appletAIDs[0].AID, optionStr.AIDLen);
			}
			if (optionStr.instAIDLen == 0) {
				optionStr.instAIDLen = loadFileParams.appletAIDs[0].AIDLength;
				memcpy(optionStr.instAID, loadFileParams.appletAIDs[0].AID, optionStr.instAIDLen);
			}
			if (optionStr.nvCodeLimit == 0) {
				optionStr.nvCodeLimit = loadFileParams.loadFileSize;
			}
			if (platform_mode == PLATFORM_MODE_OP_201) {
				if (optionStr.sdAIDLen == 0) {
					optionStr.sdAIDLen = sizeof(OP201_CARD_MANAGER_AID);
					memcpy(optionStr.sdAID, OP201_CARD_MANAGER_AID, optionStr.sdAIDLen);
				}
				rv = OP201_install_for_load(cardInfo, &securityInfo201,
							(PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
							(PBYTE)optionStr.sdAID, optionStr.sdAIDLen,
						NULL, NULL,
						optionStr.nvCodeLimit,
						0,
						0);
			} else if (platform_mode == PLATFORM_MODE_GP_211) {
				if (optionStr.sdAIDLen == 0) {
					optionStr.sdAIDLen = sizeof(GP211_CARD_MANAGER_AID);
					memcpy(optionStr.sdAID, GP211_CARD_MANAGER_AID, optionStr.sdAIDLen);
				}
				rv = GP211_install_for_load(cardInfo, &securityInfo211,
							(PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
							(PBYTE)optionStr.sdAID, optionStr.sdAIDLen,
							NULL, NULL,
							optionStr.nvCodeLimit,
							optionStr.nvDataLimit,
							optionStr.vDataLimit);
			}

			if (rv != 0) {
				_tprintf (_T("install_for_load() returns 0x%08X (%s)\n"),
					rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
			}
			if (platform_mode == PLATFORM_MODE_OP_201) {
				rv = OP201_load(cardInfo, &securityInfo201,
						NULL, 0,
						optionStr.file,
						NULL, &receiptDataLen);
			} else if (platform_mode == PLATFORM_MODE_GP_211) {
				rv = GP211_load(cardInfo, &securityInfo211,
						NULL, 0,
						optionStr.file,
						NULL, &receiptDataLen);
			}

			if (rv != 0) {
				_tprintf (_T("load_applet() returns 0x%08X (%s)\n"),
					rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
			}

			if (platform_mode == PLATFORM_MODE_OP_201) {
				OP201_RECEIPT_DATA receipt;
				rv = OP201_install_for_install_and_make_selectable(
							cardInfo, &securityInfo201,
						(PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
						(PBYTE)optionStr.AID, optionStr.AIDLen,
						(PBYTE)optionStr.instAID, optionStr.instAIDLen,
						optionStr.privilege,
						optionStr.vDataLimit,
						optionStr.nvDataLimit,
											(PBYTE)optionStr.instParam,
						optionStr.instParamLen,
						NULL, // No install token
						&receipt,
						&receiptDataAvailable);
			} else if (platform_mode == PLATFORM_MODE_GP_211) {
				GP211_RECEIPT_DATA receipt;

				rv = GP211_install_for_install_and_make_selectable(
						cardInfo, &securityInfo211,
						(PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
						(PBYTE)optionStr.AID, optionStr.AIDLen,
						(PBYTE)optionStr.instAID, optionStr.instAIDLen,
						optionStr.privilege,
						optionStr.vDataLimit,
						optionStr.nvDataLimit,
											(PBYTE)optionStr.instParam,
						optionStr.instParamLen,
						NULL, // No install token
						&receipt,
						&receiptDataAvailable);
			}

			if (rv != 0) {
				_tprintf (_T("install_for_install_and_make_selectable() returns 0x%08X (%s)\n"),
					rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
			}
			break;
		}
	    else if (strcmp(token, "install_for_load") == 0) {
		// Install for Load
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
			if (optionStr.sdAIDLen == 0) {
				optionStr.sdAIDLen = sizeof(OP201_CARD_MANAGER_AID);
				memcpy(optionStr.sdAID, OP201_CARD_MANAGER_AID, optionStr.sdAIDLen);
			}
			rv = OP201_install_for_load(cardInfo, &securityInfo201,
                        (PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
                        (PBYTE)optionStr.sdAID, optionStr.sdAIDLen,
				      NULL, NULL,
				      optionStr.nvCodeLimit,
				      optionStr.nvDataLimit,
				      optionStr.vDataLimit);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
			if (optionStr.sdAIDLen == 0) {
				optionStr.sdAIDLen = sizeof(GP211_CARD_MANAGER_AID);
				memcpy(optionStr.sdAID, GP211_CARD_MANAGER_AID, optionStr.sdAIDLen);
			}
			rv = GP211_install_for_load(cardInfo, &securityInfo211,
                        (PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
                        (PBYTE)optionStr.sdAID, optionStr.sdAIDLen,
					    NULL, NULL,
					    optionStr.nvCodeLimit,
					    optionStr.nvDataLimit,
					    optionStr.vDataLimit);
		}

		if (rv != 0) {
		    _tprintf (_T("install_for_load() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}
		break;
	    } else if (strcmp(token, "install_for_install") == 0) {


		DWORD receiptDataAvailable = 0;
		char installParam[1];
		installParam[0] = 0;

		// Install for Install
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
		    OP201_RECEIPT_DATA receipt;
		    rv = OP201_install_for_install_and_make_selectable(
				         cardInfo, &securityInfo201,
                    (PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
                    (PBYTE)optionStr.AID, optionStr.AIDLen,
                    (PBYTE)optionStr.instAID, optionStr.instAIDLen,
					 optionStr.privilege,
					 optionStr.vDataLimit,
					 optionStr.nvDataLimit,
                                         (PBYTE)optionStr.instParam,
					 optionStr.instParamLen,
					 NULL, // No install token
					 &receipt,
					 &receiptDataAvailable);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
		    GP211_RECEIPT_DATA receipt;

		    rv = GP211_install_for_install_and_make_selectable(
					cardInfo, &securityInfo211,
                    (PBYTE)optionStr.pkgAID, optionStr.pkgAIDLen,
                    (PBYTE)optionStr.AID, optionStr.AIDLen,
                    (PBYTE)optionStr.instAID, optionStr.instAIDLen,
					optionStr.privilege,
					optionStr.vDataLimit,
					optionStr.nvDataLimit,
                                        (PBYTE)optionStr.instParam,
					optionStr.instParamLen,
					NULL, // No install token
					&receipt,
					&receiptDataAvailable);
		}

		if (rv != 0) {
		    _tprintf (_T("install_for_install_and_make_selectable() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}

		break;
	    } else if (strcmp(token, "card_disconnect") == 0) {
		// disconnect card
		card_disconnect(cardInfo);

		break;
	    } else if (strcmp(token, "put_sc_key") == 0) {
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
		    rv = OP201_put_secure_channel_keys(cardInfo, &securityInfo201,
						       optionStr.keySetVersion,
						       optionStr.newKeySetVersion,
						       optionStr.enc_key,
						       optionStr.mac_key,
						       optionStr.kek_key,
						       optionStr.current_kek);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
		    rv = GP211_put_secure_channel_keys(cardInfo,
						       &securityInfo211,
						       optionStr.keySetVersion,
						       optionStr.newKeySetVersion,
						       NULL,
						       optionStr.enc_key,
						       optionStr.mac_key,
						       optionStr.kek_key);
		}

		if (rv != 0) {
		    _tprintf (_T("put_secure_channel_keys() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}
		break;
	    } else if (strcmp(token, "get_status") == 0) {
#define NUM_APPLICATIONS 64
		DWORD numData = NUM_APPLICATIONS;

		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		if (platform_mode == PLATFORM_MODE_OP_201) {
		    OP201_APPLICATION_DATA data[NUM_APPLICATIONS];
		    rv = OP201_get_status(cardInfo, &securityInfo201,
				      optionStr.element,
				      data,
				      &numData);

		    if (rv != 0) {
			_tprintf (_T("OP201_get_status() returns 0x%08X (%s)\n"),
				  rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
		    }
#ifdef DEBUG
		    printf ("OP201_get_status() returned %d items\n", numData);
#endif
		    printf ("\nList of applets (AID state privileges)\n");
		    for (i=0; i<(int)numData; i++) {
			int j;

			for (j=0; j<data[i].AIDLength; j++) {
			    printf ("%02x", data[i].AID[j]);
			}

			printf ("\t%x", data[i].lifeCycleState);
			printf ("\t%x\n", data[i].privileges);
		    }
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
                  GP211_APPLICATION_DATA appData[NUM_APPLICATIONS];
                  GP211_EXECUTABLE_MODULES_DATA execData[NUM_APPLICATIONS];
		    rv = GP211_get_status(cardInfo, &securityInfo211,
                                          optionStr.element,
					  appData,
					  execData,
					  &numData);

		    if (rv != 0) {
				_tprintf (_T("GP211_get_status() returns 0x%08X (%s)\n"),
				  rv, stringify_error(rv));
				rv = EXIT_FAILURE;
				goto end;
		    }
#ifdef DEBUG
		    printf ("GP211_get_status() returned %d items\n", numData);
#endif
		    printf ("\nList of applets (AID state privileges)\n");
		    for (i=0; i<(int)numData; i++) {
			int j;

			for (j=0; j<appData[i].AIDLength; j++) {
			    printf ("%02x", appData[i].AID[j]);
			}

			printf ("\t%x", appData[i].lifeCycleState);
			printf ("\t%x\n", appData[i].privileges);
		    }
		}
		if (rv != 0) {
		    _tprintf (_T("get_status() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}


		break;
	    } else if (strcmp(token, "send_apdu") == 0) {
		unsigned char recvAPDU[257];
                DWORD recvAPDULen = 257;
                int i;
		// Install for Load
		rv = handleOptions(&optionStr);
		if (rv != EXIT_SUCCESS) {
			goto end;
		}
		printf ("Send APDU: ");
		for (i=0; i<optionStr.APDULen; i++)
		    printf ("%02X ", optionStr.APDU[i] & 0xFF);
		printf ("\n");

		if (platform_mode == PLATFORM_MODE_OP_201) {
		    rv = OP201_send_APDU(cardInfo,
				     (optionStr.secureChannel == 0 ? NULL : &securityInfo201),
				     (PBYTE)(optionStr.APDU), optionStr.APDULen,
				     recvAPDU, &recvAPDULen);
		} else if (platform_mode == PLATFORM_MODE_GP_211) {
		    rv = GP211_send_APDU(cardInfo,
				     (optionStr.secureChannel == 0 ? NULL : &securityInfo211),
					 (PBYTE)(optionStr.APDU), optionStr.APDULen,
				     recvAPDU, &recvAPDULen);
		}
		if (rv != 0) {
		    _tprintf (_T("send_APDU() returns 0x%08X (%s)\n"),
			      rv, stringify_error(rv));
			rv = EXIT_FAILURE;
			goto end;
		}

		printf ("Recv APDU: ");
		for (i=0; i<(int)recvAPDULen; i++)
		    printf ("%02x ", recvAPDU[i]);
		printf ("\n");

		break;
	    } else if (strcmp(token, "mode_201") == 0) {
			platform_mode = PLATFORM_MODE_OP_201;
	    } else if (strcmp(token, "mode_211") == 0) {
			platform_mode = PLATFORM_MODE_GP_211;
	    } else if (strcmp(token, "enable_trace") == 0) {
			enableTraceMode(OPGP_TRACE_MODE_ENABLE, NULL);
	    } else if (strcmp(token, "gemXpressoPro") == 0) {
			gemXpressoPro = 1;
	    }

	    else {
			printf ("Unknown command %s\n", token);
			rv = EXIT_FAILURE;
			goto end;
	    }

	    token = strtokCheckComment(NULL);
	}
    }
end:
    return rv;
}
示例#8
0
BOOL CPublisherHelp::GetProgAndPublisherInfo(PCMSG_SIGNER_INFO pSignerInfo,
							 PSPROG_PUBLISHERINFO Info)
{
	BOOL fReturn = FALSE;
	PSPC_SP_OPUS_INFO OpusInfo = NULL;
	DWORD dwData;
	BOOL fResult;
	__try
	{
		// Loop through authenticated attributes and find
		// SPC_SP_OPUS_INFO_OBJID OID.
		for (DWORD n = 0; n < pSignerInfo->AuthAttrs.cAttr; n++)
		{
			if (lstrcmpA(SPC_SP_OPUS_INFO_OBJID,
				pSignerInfo->AuthAttrs.rgAttr[n].pszObjId) == 0)
			{
				// Get Size of SPC_SP_OPUS_INFO structure.
				fResult = CryptDecodeObject(ENCODING,
					SPC_SP_OPUS_INFO_OBJID,
					pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].pbData,
					pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].cbData,
					0,
					NULL,
					&dwData);
				if (!fResult)
				{
					_tprintf(_T("CryptDecodeObject failed with %x\n"),
						GetLastError());
					__leave;
				}
				// Allocate memory for SPC_SP_OPUS_INFO structure.
				OpusInfo = (PSPC_SP_OPUS_INFO)LocalAlloc(LPTR, dwData);
				if (!OpusInfo)
				{
					_tprintf(_T("Unable to allocate memory for Publisher Info.\n"));
					__leave;
				}
				// Decode and get SPC_SP_OPUS_INFO structure.
				fResult = CryptDecodeObject(ENCODING,
					SPC_SP_OPUS_INFO_OBJID,
					pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].pbData,
					pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].cbData,
					0,
					OpusInfo,
					&dwData);
				if (!fResult)
				{
					_tprintf(_T("CryptDecodeObject failed with %x\n"),
						GetLastError());
					__leave;
				}
				// Fill in Program Name if present.
				if (OpusInfo->pwszProgramName)
				{
					Info->lpszProgramName =
						AllocateAndCopyWideString(OpusInfo->pwszProgramName);
				}
				else
					Info->lpszProgramName = NULL;
				// Fill in Publisher Information if present.
				if (OpusInfo->pPublisherInfo)
				{
					switch (OpusInfo->pPublisherInfo->dwLinkChoice)
					{
					case SPC_URL_LINK_CHOICE:
						Info->lpszPublisherLink =
							AllocateAndCopyWideString(OpusInfo->pPublisherInfo->pwszUrl);
						break;
					case SPC_FILE_LINK_CHOICE:
						Info->lpszPublisherLink =
							AllocateAndCopyWideString(OpusInfo->pPublisherInfo->pwszFile);
						break;
					default:
						Info->lpszPublisherLink = NULL;
						break;
					}
				}
				else
				{
					Info->lpszPublisherLink = NULL;
				}
				// Fill in More Info if present.
				if (OpusInfo->pMoreInfo)
				{
					switch (OpusInfo->pMoreInfo->dwLinkChoice)
					{
					case SPC_URL_LINK_CHOICE:
						Info->lpszMoreInfoLink =
							AllocateAndCopyWideString(OpusInfo->pMoreInfo->pwszUrl);
						break;
					case SPC_FILE_LINK_CHOICE:
						Info->lpszMoreInfoLink =
							AllocateAndCopyWideString(OpusInfo->pMoreInfo->pwszFile);
						break;
					default:
						Info->lpszMoreInfoLink = NULL;
						break;
					}
				}
				else
				{
					Info->lpszMoreInfoLink = NULL;
				}
				fReturn = TRUE;
				break; // Break from for loop.
			} // lstrcmp SPC_SP_OPUS_INFO_OBJID
		} // for
	}
	__finally
	{
		if (OpusInfo != NULL) LocalFree(OpusInfo);
	}
	return fReturn;
}
示例#9
0
BOOL CPublisherHelp::GetTimeStampSignerInfo(PCMSG_SIGNER_INFO pSignerInfo, PCMSG_SIGNER_INFO *pCounterSignerInfo)
{
	PCCERT_CONTEXT pCertContext = NULL;
	BOOL fReturn = FALSE;
	BOOL fResult;
	DWORD dwSize;
	__try
	{
		*pCounterSignerInfo = NULL;
		// Loop through unathenticated attributes for
		// szOID_RSA_counterSign OID.
		for (DWORD n = 0; n < pSignerInfo->UnauthAttrs.cAttr; n++)
		{
			if (lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[n].pszObjId,
				szOID_RSA_counterSign) == 0)
			{
				// Get size of CMSG_SIGNER_INFO structure.
				fResult = CryptDecodeObject(ENCODING,
					PKCS7_SIGNER_INFO,
					pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData,
					pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].cbData,
					0,
					NULL,
					&dwSize);
				if (!fResult)
				{
					_tprintf(_T("CryptDecodeObject failed with %x\n"),
						GetLastError());
					__leave;
				}
				// Allocate memory for CMSG_SIGNER_INFO.
				*pCounterSignerInfo = (PCMSG_SIGNER_INFO)LocalAlloc(LPTR, dwSize);
				if (!*pCounterSignerInfo)
				{
					_tprintf(_T("Unable to allocate memory for timestamp info.\n"));
					__leave;
				}
				// Decode and get CMSG_SIGNER_INFO structure
				// for timestamp certificate.
				fResult = CryptDecodeObject(ENCODING,
					PKCS7_SIGNER_INFO,
					pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData,
					pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].cbData,
					0,
					(PVOID)*pCounterSignerInfo,
					&dwSize);
				if (!fResult)
				{
					_tprintf(_T("CryptDecodeObject failed with %x\n"),
						GetLastError());
					__leave;
				}
				fReturn = TRUE;
				break; // Break from for loop.
			}
		}
	}
	__finally
	{
		// Clean up.
		if (pCertContext != NULL) CertFreeCertificateContext(pCertContext);
	}
	return fReturn;
}
示例#10
0
VOID CALLBACK Fiber1Proc(PVOID param)
{
  _tprintf(TEXT("Fiber1Proc\n"));
}
示例#11
0
BOOL CPublisherHelp::PrintCertificateInfo(PCCERT_CONTEXT pCertContext)
{
	BOOL fReturn = FALSE;
	LPTSTR szName = NULL;
	DWORD dwData;
	__try
	{
		// Print Serial Number.
		_tprintf(_T("Serial Number: "));
		dwData = pCertContext->pCertInfo->SerialNumber.cbData;
		for (DWORD n = 0; n < dwData; n++)
		{
			_tprintf(_T("%02x "),
				pCertContext->pCertInfo->SerialNumber.pbData[dwData - (n + 1)]);
		}
		_tprintf(_T("\n"));
		// Get Issuer name size.
		if (!(dwData = CertGetNameString(pCertContext,
			CERT_NAME_SIMPLE_DISPLAY_TYPE,
			CERT_NAME_ISSUER_FLAG,
			NULL,
			NULL,
			0)))
		{
			_tprintf(_T("CertGetNameString failed.\n"));
			__leave;
		}
		// Allocate memory for Issuer name.
		szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(TCHAR));
		if (!szName)
		{
			_tprintf(_T("Unable to allocate memory for issuer name.\n"));
			__leave;
		}
		// Get Issuer name.
		if (!(CertGetNameString(pCertContext,
			CERT_NAME_SIMPLE_DISPLAY_TYPE,
			CERT_NAME_ISSUER_FLAG,
			NULL,
			szName,
			dwData)))
		{
			_tprintf(_T("CertGetNameString failed.\n"));
			__leave;
		}
		// print Issuer name.
		_tprintf(_T("Issuer Name: %s\n"), szName);
		LocalFree(szName);
		szName = NULL;
		// Get Subject name size.
		if (!(dwData = CertGetNameString(pCertContext,
			CERT_NAME_SIMPLE_DISPLAY_TYPE,
			0,
			NULL,
			NULL,
			0)))
		{
			_tprintf(_T("CertGetNameString failed.\n"));
			__leave;
		}
		// Allocate memory for subject name.
		szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(TCHAR));
		if (!szName)
		{
			_tprintf(_T("Unable to allocate memory for subject name.\n"));
			__leave;
		}
		// Get subject name.
		if (!(CertGetNameString(pCertContext,
			CERT_NAME_SIMPLE_DISPLAY_TYPE,
			0,
			NULL,
			szName,
			dwData)))
		{
			_tprintf(_T("CertGetNameString failed.\n"));
			__leave;
		}
		// Print Subject Name.
		_tprintf(_T("Subject Name: %s\n"), szName);
		fReturn = TRUE;
	}
	__finally
	{
		if (szName != NULL) LocalFree(szName);
	}
	return fReturn;
}
示例#12
0
void usage()
{
	_tprintf(TEXT("xixfscmd [version | shutdown]\n"));
	_tprintf(TEXT("  - shutdown : shutdown the xixfs to unload.\n"));
}
示例#13
0
VARIANT Functions::InvokeMember2(mscorlib::_AppDomainPtr pDefaultDomain, BSTR dll, BSTR Typename, BSTR Method, int Numargs, ...)
{
	VARIANT returnValue;

	try
	{
		va_list vl;
		va_start(vl,Numargs);
		SAFEARRAY* psa = SafeArrayCreateVector(VT_VARIANT, 0, Numargs / 2);

		for (int i = 0; i < Numargs; i+=2)
		{
			int typeName = va_arg(vl, int);
			switch(typeName)
			{
			case 0:
				{
					BSTR wstr = SysAllocString(va_arg(vl, wchar_t*));
					VARIANT val;
					val.vt = VT_BSTR;
					val.bstrVal = wstr;
					LONG index[1] = { i / 2 };

					SafeArrayPutElement(psa, index, &val);

					SysFreeString(wstr);
					break;
				}
			case 1:
				{
					int intval = va_arg(vl, int);
					VARIANT val;
					val.vt = VT_INT;
					val.intVal = intval;
					LONG index[1] = { i / 2 };

					SafeArrayPutElement(psa, index, &val);
					break;
				}
			}
		}

		mscorlib::_ObjectPtr pObject; 
		mscorlib::_ObjectHandlePtr pObjectHandle; 

		pObjectHandle = pDefaultDomain->CreateInstanceFrom(dll, Typename);
		variant_t vtobj = pObjectHandle->Unwrap();
		vtobj.pdispVal->QueryInterface(__uuidof(mscorlib::_Object),(void**)&pObject); 

		mscorlib::_TypePtr pType = pObject->GetType();

		returnValue = pType->InvokeMember_3(Method,
			mscorlib::BindingFlags_InvokeMethod,
			NULL,
			vtobj,
			psa);

		SafeArrayDestroy(psa);
		vtobj.Clear();
		pType->Release();
		pObject->Release();
	}
	catch(_com_error& error) {
		_tprintf(TEXT("ERROR: %s\n"),(_TCHAR*)error.Description());
	}

	return returnValue;
}
示例#14
0
int CreateService(const TCHAR *pszStartStopName,
                  const TCHAR *pszDisplayName,
                  int iServiceType,
                  int iStartType,
                  const TCHAR *pszBinPath,
                  const TCHAR *pszLoadOrderGroup,
                  const TCHAR *pszDependencies,
                  const TCHAR *pszLogonUser,
                  const TCHAR *pszLogonPassword)
{
    int rc = ERROR_SUCCESS;

    _tprintf(_T("Installing service %ws (%ws) ...\n"), pszDisplayName, pszStartStopName);

    SC_HANDLE hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (hSCManager == NULL)
    {
        _tprintf(_T("Could not get handle to SCM! Error: %ld\n"), GetLastError());
        return EXIT_FAIL;
    }

    /* Fixup end of multistring. */
    TCHAR szDepend[ _MAX_PATH ] = { 0 }; /* @todo Use dynamically allocated string here! */
    if (pszDependencies != NULL)
    {
        _tcsnccpy (szDepend, pszDependencies, wcslen(pszDependencies));
        DWORD len = (DWORD)wcslen (szDepend);
        szDepend [len + 1] = 0;

        /* Replace comma separator on null separator. */
        for (DWORD i = 0; i < len; i++)
        {
            if (',' == szDepend [i])
                szDepend [i] = 0;
        }
    }

    DWORD dwTag = 0xDEADBEAF;
    SC_HANDLE hService = CreateService (hSCManager,           /* SCManager database handle. */
                                        pszStartStopName,     /* Name of service. */
                                        pszDisplayName,       /* Name to display. */
                                        SERVICE_ALL_ACCESS,   /* Desired access. */
                                        iServiceType,         /* Service type. */
                                        iStartType,           /* Start type. */
                                        SERVICE_ERROR_NORMAL, /* Error control type. */
                                        pszBinPath,           /* Service's binary. */
                                        pszLoadOrderGroup,    /* Ordering group. */
                                        (pszLoadOrderGroup != NULL) ? &dwTag : NULL,           /* Tag identifier. */
                                        (pszDependencies != NULL) ? szDepend : NULL,           /* Dependencies. */
                                        (pszLogonUser != NULL) ? pszLogonUser: NULL,           /* Account. */
                                        (pszLogonPassword != NULL) ? pszLogonPassword : NULL); /* Password. */
    if (NULL == hService)
    {
        DWORD dwErr = GetLastError();
        switch (dwErr)
        {

        case ERROR_SERVICE_EXISTS:
        {
            _tprintf(_T("Service already exists. No installation required. Updating the service config.\n"));

            hService = OpenService (hSCManager,          /* SCManager database handle. */
                                    pszStartStopName,    /* Name of service. */
                                    SERVICE_ALL_ACCESS); /* Desired access. */
            if (NULL == hService)
            {
                dwErr = GetLastError();
                _tprintf(_T("Could not open service! Error: %ld\n"), dwErr);
            }
            else
            {
                BOOL fResult = ChangeServiceConfig (hService,            /* Service handle. */
                                                   iServiceType,         /* Service type. */
                                                   iStartType,           /* Start type. */
                                                   SERVICE_ERROR_NORMAL, /* Error control type. */
                                                   pszBinPath,           /* Service's binary. */
                                                   pszLoadOrderGroup,    /* Ordering group. */
                                                   (pszLoadOrderGroup != NULL) ? &dwTag : NULL,          /* Tag identifier. */
                                                   (pszDependencies != NULL) ? szDepend : NULL,          /* Dependencies. */
                                                   (pszLogonUser != NULL) ? pszLogonUser: NULL,          /* Account. */
                                                   (pszLogonPassword != NULL) ? pszLogonPassword : NULL, /* Password. */
                                                   pszDisplayName);      /* Name to display. */
                if (fResult)
                    _tprintf(_T("The service config has been successfully updated.\n"));
                else
                {
                    dwErr = GetLastError();
                    _tprintf(_T("Could not change service config! Error: %ld\n"), dwErr);
                }
                CloseServiceHandle(hService);
            }

            /*
             * This entire branch do not return an error to avoid installations failures,
             * if updating service parameters. Better to have a running system with old
             * parameters and the failure information in the installation log.
             */
            break;
        }

        case ERROR_INVALID_PARAMETER:

            _tprintf(_T("Invalid parameter specified!\n"));
            rc = EXIT_FAIL;
            break;

        default:

            _tprintf(_T("Could not create service! Error: %ld\n"), dwErr);
            rc = EXIT_FAIL;
            break;
        }

        if (rc == EXIT_FAIL)
            goto cleanup;
    }
    else
    {
        CloseServiceHandle (hService);
        _tprintf(_T("Installation of service successful!\n"));
    }

cleanup:

    if (hSCManager != NULL)
        CloseServiceHandle (hSCManager);

    return rc;
}
示例#15
0
int _tmain(int argc, _TCHAR* argv[])
{
	HRESULT hr;
	IXenGuestServices *piXgs = NULL;
	IXenVmInfo *piXvi = NULL;
	USHORT usd;
	BSTR uuid;
	ULONG c;
	SAFEARRAY *psa;

	::CoInitializeEx(NULL, COINIT_MULTITHREADED);
	hr = ::CoCreateInstance(CLSID_XenGuestServices,
							NULL,
							CLSCTX_LOCAL_SERVER,
							IID_IXenGuestServices,
							(LPVOID*)&piXgs);

	
	if (FAILED(hr))
	{
		_tprintf(_T("Borked...\n"));
		return -1;
	}

	piXgs->GetDomId(&usd);
	_tprintf(_T("My DOMID: %d\n"), usd);

	piXgs->GetUuid(&uuid);
	wprintf(L"My UUID: %s\n", uuid);
	::SysFreeString(uuid);

	piXgs->QueryVms(&c);
	wprintf(L"Domains: %d\n", c);

	if (c == 0)
		goto done;

	piXgs->GetVmObject(0, &piXvi);

	if (piXvi == NULL)
	{
		wprintf(L"Hosed...\n");
		goto done;
	}

	piXvi->GetUuid(&uuid);
	wprintf(L"VM UUID: %s\n", uuid);
	::SysFreeString(uuid);

	piXvi->GetImage(&psa);
	if (psa != NULL)
	{
		wprintf(L"Elements: %d\n", psa->cbElements);
		::SafeArrayDestroy(psa);
	}

	piXvi->Release();
	
done:
	piXgs->Release();
	::CoUninitialize();
	return 0;
}
示例#16
0
static void testShortProd() {
  DigitPool pool(-5);
  Random rnd;

  for(int i = 0; i < 500000;) {
    if((i++)%10000 == 9999) _tprintf(_T("i:%d\r"), i);
    int lengthX = randInt(4,500);
    int lengthY = randInt(4,500);
    int expoX   = randInt(-500,500);
    int expoY   = randInt(-500,500);
    const FullFormatBigReal x(e(randBigReal(lengthX, &rnd, &pool), expoX));
    const FullFormatBigReal y(e(randBigReal(lengthY, &rnd, &pool), expoY));

    FullFormatBigReal p1(&pool), p2(&pool);

//    printf(_T("x:%50s\n y:%50s\n"), x.toString().cstr(), y.toString().cstr());
//  for(int p = 0; p >= -100; p--) {
//    BigReal f(e(1, -70));
#define F BIGREAL_0

    BigReal::setUseShortProdRefenceVersion(true);
    p1 = BigReal::shortProd(x, y, F, &pool);

    try {
      p1.assertIsValidBigReal();
    } catch(Exception e) {
      printf(_T("p1 failed:%s\n"), e.what());
      continue;
    }

    BigReal::setUseShortProdRefenceVersion(false);
    p2 = BigReal::shortProd(x, y, F, &pool);

    try {
      p2.assertIsValidBigReal();
    } catch(Exception e) {
      printf(_T("p2 failed:%s\n"), e.what());
      continue;
    }

    if(p1 != p2) {
      _tprintf(_T("x:%s\ny:%s\npref:%s\np2:%s\n")
              ,x.toString().cstr()
              ,y.toString().cstr()
              ,p1.toString().cstr()
              ,p2.toString().cstr()
            );
      pause();
    }
//    printf(_T("p:%4d. prod:%s\n"), p, p1.toString().cstr());
  }
/*
//    useNewShortProduct = true;
//    p2 = BigReal::shortProd(x, y, BIGREAL_0, &pool);
//    useNewShortProduct = false;

    printf(_T("x*y (1) = %s\n"), p1.toString().cstr());
    printf(_T("x*y (2) = %s\n"), p2.toString().cstr());

    try {
      p1.assertIsValidBigReal();
    } catch(Exception e) {
      printf(_T("p1 failed:%s\n"), e.what());
    }
    try {
      p2.assertIsValidBigReal();
    } catch(Exception e) {
      printf(_T("p2 failed:%s\n"), e.what());
    }
  }
*/
}
示例#17
0
DWORD queue_func(BYTE* pParam, DWORD param_size)
{
	int res = -1;
	queue_param_t * param = (queue_param_t*)pParam;
	TCHAR tempfilename[MAX_PATH];

	if (!GetTempFileName(param->state->out_dir, _T("out"), 0, tempfilename)) {
		_tprintf(_T("GetTempFileName failed\n"));
		return -1;
	}
	HANDLE hfile = CreateFile(tempfilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 
		FILE_ATTRIBUTE_NORMAL, 0);
	if (hfile == INVALID_HANDLE_VALUE) {
		_tprintf(_T("CreateFile failed: %s\n"), tempfilename);
		return -1;
	}

	SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sock == INVALID_SOCKET) {
		_tprintf(_T("create socket failed\n"));
		goto cleanup;
	}
	if (connect(sock, param->state->addrinfo->ai_addr, param->state->addrinfo->ai_addrlen) != 0) {
		_tprintf(_T("connect() failed\n"));
		goto cleanup2;
	}

	int i = rand() % NUM_OF_REQUESTS;
	int remaining = param->state->requests[i].length;
	const char * buf = (const char*)param->state->requests[i].buffer;
	while (remaining > 0) {
		int count = send(sock, buf, remaining, 0);
		if (count == SOCKET_ERROR) {
			_tprintf(_T("send() failed\n"));
			goto cleanup2;
		}
		remaining -= count;
		buf += count;
	}
	shutdown(sock, SD_SEND);
	char recvbuf[4096];
	while (true) {
		int count = recv(sock, recvbuf, sizeof(recvbuf), 0);
		if (count == 0) {
			break; // EOF
		}
		else if (count == SOCKET_ERROR) {
			_tprintf(_T("recv() failed\n"));
			goto cleanup2;
		}
		DWORD writecount;
		if (!WriteFile(hfile, recvbuf, count, &writecount, NULL)) {
			_tprintf(_T("WriteFile() failed\n"));
			goto cleanup2;
		}
	}
	shutdown(sock, SD_RECEIVE);

	res = 0;
cleanup2:
	closesocket(sock);
cleanup:
	CloseHandle(hfile);
	return res;
}
示例#18
0
int _tmain(int argc, TCHAR **argv)
{
	SQLHENV		lpEnv = NULL;
	SQLHDBC		lpDbc = NULL;
	SQLHSTMT	lpStmt = NULL;
	TCHAR		*pszConnStr;
	TCHAR		szInput[SQL_QUERY_SIZE];

	// Allocate an environment

	if (SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&lpEnv) == SQL_ERROR)
	{
		fprintf(stderr,"Unable to allocate an environment handle\n");
		exit(-1);
	}

	// Register this as an application that expects 2.x behavior,
	// you must register something if you use AllocHandle

	TRYODBC(lpEnv,
			SQL_HANDLE_ENV,
			SQLSetEnvAttr(lpEnv,
						  SQL_ATTR_ODBC_VERSION,
						  (SQLPOINTER)SQL_OV_ODBC2,
						  0));

	// Allocate a connection

	TRYODBC(lpEnv,
			SQL_HANDLE_ENV,
			SQLAllocHandle(SQL_HANDLE_DBC,lpEnv,&lpDbc));

	

	if (argc > 1)
	{
		pszConnStr = *++argv;
	} else
	{
		pszConnStr = NULL;
	}

	// Connect to the driver.  Use the connection string if supplied
	// on the input, otherwise let the driver manager prompt for input.

	TRYODBC(lpDbc,
			SQL_HANDLE_DBC,
			SQLDriverConnect(lpDbc,
							 GetDesktopWindow(),
							 pszConnStr,
							 SQL_NTS,
							 NULL,
							 0,
							 NULL,
							 SQL_DRIVER_COMPLETE));

	fprintf(stderr,"Connected!\n");

	TRYODBC(lpDbc,
			SQL_HANDLE_DBC,
			SQLAllocHandle(SQL_HANDLE_STMT,lpDbc,&lpStmt));


	printf("Enter SQL commands, type (control)Z to exit\nSQL COMMAND>");

	// Loop to get input and execute queries

	while(_fgetts(szInput, SQL_QUERY_SIZE-1, stdin))
	{
		RETCODE		RetCode;
		SQLSMALLINT	sNumResults;

		// Execute the query

		if (!(*szInput))
		{
			printf("SQL COMMAND>");
			continue;
		}
		RetCode = SQLExecDirect(lpStmt,szInput,SQL_NTS);

		switch(RetCode)
		{
			case	SQL_SUCCESS_WITH_INFO:
			{
				HandleError(lpStmt,SQL_HANDLE_STMT,RetCode);
				// fall through
			}
			case	SQL_SUCCESS:
			{
				// If this is a row-returning query, display
				// results
				TRYODBC(lpStmt,
						SQL_HANDLE_STMT,
						SQLNumResultCols(lpStmt,&sNumResults));

				if (sNumResults > 0)
				{
					DisplayResults(lpStmt,sNumResults);
				} else
				{
					SQLLEN		siRowCount;

					TRYODBC(lpStmt,
							SQL_HANDLE_STMT,
							SQLRowCount(lpStmt,&siRowCount));

					if (siRowCount >= 0)
					{
						_tprintf(TEXT("%d %s affected\n"),
								siRowCount,
								siRowCount == 1 ? TEXT("row") : TEXT("rows"));
					}
				}
				break;
			}

			case	SQL_ERROR:
			{
				HandleError(lpStmt,SQL_HANDLE_STMT,RetCode);
				break;
			}

			default:
					fprintf(stderr,"Unexpected return code %d!\n",RetCode);

		}
		TRYODBC(lpStmt,
				SQL_HANDLE_STMT,
				SQLFreeStmt(lpStmt,SQL_CLOSE));

		printf("SQL COMMAND>");
	}

Exit:

	// Free ODBC handles and exit

	if (lpDbc)
	{
		SQLDisconnect(lpDbc);
		SQLFreeConnect(lpDbc);
	}
	if (lpEnv)
		SQLFreeEnv(lpEnv);

	printf("\nDisconnected.");

	return 0;

}
示例#19
0
static int handleOptions(OptionStr *pOptionStr)
{
	int rv = EXIT_SUCCESS;
    char *token;
	char dummy[BUFLEN+1];

    pOptionStr->keyIndex = 0;
    pOptionStr->keySetVersion = 0;
    pOptionStr->newKeySetVersion = 0;
    pOptionStr->securityLevel = 0;
    pOptionStr->AID[0] = '\0';
	pOptionStr->AIDLen = 0;
    pOptionStr->sdAID[0] = '\0';
	pOptionStr->sdAIDLen = 0;
    pOptionStr->pkgAID[0] = '\0';
	pOptionStr->pkgAIDLen = 0;
    pOptionStr->instAID[0] = '\0';
	pOptionStr->instAIDLen = 0;
    pOptionStr->APDU[0] = '\0';
	pOptionStr->APDULen = 0;
    pOptionStr->secureChannel = 0;
    pOptionStr->reader[0] = _T('\0');
	pOptionStr->readerNumber = 0;
    pOptionStr->file[0] = _T('\0');
	pOptionStr->protocol = OPGP_CARD_PROTOCOL_T0 | OPGP_CARD_PROTOCOL_T1;
    pOptionStr->nvCodeLimit = 0;
    pOptionStr->nvDataLimit = 0;
    pOptionStr->vDataLimit = 0;
    pOptionStr->instParam[0] = '\0';
	pOptionStr->instParamLen = 0;
    pOptionStr->element = 0;
    pOptionStr->privilege = 0;
    pOptionStr->scp = 0;
    pOptionStr->scpImpl = 0;

    token = strtokCheckComment(NULL);

    while (token != NULL) {
	if (strcmp(token, "-keyind") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -keyind not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		pOptionStr->keyIndex = atoi(token);
	    }
	} else if (strcmp(token, "-keyver") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -keyver not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
		} else {
		pOptionStr->keySetVersion = atoi(token);
	    }
	} else if (strcmp(token, "-newkeyver") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -newkeyver not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		pOptionStr->newKeySetVersion = atoi(token);
	    }
	} else if (strcmp(token, "-sc") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -sc not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		if (atoi(token) == 0)
		    pOptionStr->secureChannel = 0;
		else if (atoi(token) == 1)
		    pOptionStr->secureChannel = 1;
		else {
		    printf ("Error: option -sc not followed 0 (secure channel off) or 1 (secure channel on)\n");
			rv = EXIT_FAILURE;
			goto end;
		}
	    }
	} else if (strcmp(token, "-security") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -security not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
			pOptionStr->securityLevel = atoi(token);
	    }
	} else if (strcmp(token, "-readerNumber") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -readerNumber not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
			pOptionStr->readerNumber = atoi(token)-1;
	    }
	} else if (strcmp(token, "-reader") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -reader not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
			strncpy(dummy, token, READERNAMELEN+1);
			dummy[READERNAMELEN] = '\0';
			ConvertCToT (pOptionStr->reader, dummy);
#ifdef DEBUG
		_tprintf ( _T("reader name %s\n"), pOptionStr->reader);
#endif
	    }
	} else if (strcmp(token, "-file") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -file not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
			strncpy(dummy, token, FILENAMELEN+1);
			dummy[FILENAMELEN] = '\0';
			ConvertCToT (pOptionStr->file, dummy);
#ifdef DEBUG
		_tprintf ( _T("file name %s\n"), pOptionStr->file);
#endif
	    }
	} else if (strcmp(token, "-key") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -key not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		int i;

		for (i=0; i<DDES_KEY_LEN; i++) {
		    sscanf (token, "%02x", &(pOptionStr->key[i]));
		    token += 2;
		}
	    }
	} else if (strcmp(token, "-mac_key") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -key not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		int i;

		for (i=0; i<DDES_KEY_LEN; i++) {
		    sscanf (token, "%02x", &(pOptionStr->mac_key[i]));
		    token += 2;
		}
	    }
	} else if (strcmp(token, "-enc_key") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -enc_key not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		int i;

		for (i=0; i<DDES_KEY_LEN; i++) {
		    sscanf (token, "%02x", &(pOptionStr->enc_key[i]));
		    token += 2;
		}
	    }
	} else if (strcmp(token, "-kek_key") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -kek_key not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		int i;

		for (i=0; i<DDES_KEY_LEN; i++) {
		    sscanf (token, "%02x", &(pOptionStr->kek_key[i]));
		    token += 2;
		}
	    }
	} else if (strcmp(token, "-current_kek") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -current_kek not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		int i;

		for (i=0; i<DDES_KEY_LEN; i++) {
		    sscanf (token, "%02x", &(pOptionStr->current_kek[i]));
		    token += 2;
		}
	    }
	} else if (strcmp(token, "-AID") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -AID not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {

			int i = 0;

			strncpy(dummy, token, AIDLEN*2+1);
			dummy[AIDLEN*2] = '\0';

			while (sscanf (&(dummy[i*2]), "%02x", &(pOptionStr->AID[i])) > 0) {
				i++;
			}
			pOptionStr->AIDLen = i;
	    }
	} else if (strcmp(token, "-sdAID") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -sdAID not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
			int i = 0;
			strncpy(dummy, token, AIDLEN*2+1);
			dummy[AIDLEN*2] = '\0';

			while (sscanf (&(dummy[i*2]), "%02x", &(pOptionStr->sdAID[i])) > 0) {
				i++;
			}
			pOptionStr->sdAIDLen = i;
	    }
	} else if (strcmp(token, "-pkgAID") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -pkgAID not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
			int i = 0;
			strncpy(dummy, token, AIDLEN*2+1);
			dummy[AIDLEN*2] = '\0';
			while (sscanf (&(dummy[i*2]), "%02x", &(pOptionStr->pkgAID[i])) > 0) {
				i++;
			}
			pOptionStr->pkgAIDLen = i;
	    }
	} else if (strcmp(token, "-instAID") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
		printf ("Error: option -instAID not followed by data\n");
		exit (EXIT_FAILURE);
	    } else {
			int i = 0;
			strncpy(dummy, token, AIDLEN*2+1);
			dummy[AIDLEN*2] = '\0';

			while (sscanf (&(dummy[i*2]), "%02x", &(pOptionStr->instAID[i])) > 0) {
				i++;
			}
			pOptionStr->instAIDLen = i;
	    }
	} else if (strcmp(token, "-APDU") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -APDU not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
			int i = 0;

			strncpy(dummy, token, APDULEN*2+1);
			dummy[APDULEN*2] = '\0';

			while (sscanf (&(dummy[i*2]), "%02x", &(pOptionStr->APDU[i])) > 0) {
				i++;
			}
			pOptionStr->APDULen = i;
	    }
	} else if (strcmp(token, "-protocol") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -protocol not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		if (atoi(token) == 0) {
		    pOptionStr->protocol = OPGP_CARD_PROTOCOL_T0;
		} else if (atoi(token) == 1) {
		    pOptionStr->protocol = OPGP_CARD_PROTOCOL_T1;
		} else {
		    printf ("Unknown protocol type %s\n", token);
			rv = EXIT_FAILURE;
			goto end;
		}
	    }
	} else if (strcmp(token, "-nvCodeLimit") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -nvCodeLimit not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		pOptionStr->nvCodeLimit = atoi(token);
	    }
	} else if (strcmp(token, "-nvDataLimit") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -nvDataLimit not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		pOptionStr->nvDataLimit = atoi(token);
	    }
	} else if (strcmp(token, "-vDataLimit") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -vDataLimit not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		pOptionStr->vDataLimit = atoi(token);
	    }
	} else if (strcmp(token, "-instParam") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -instParam not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
			unsigned int i = 0;
			strncpy(dummy, token, INSTPARAMLEN*2+1);
			dummy[INSTPARAMLEN*2] = '\0';
			while (sscanf (&(dummy[i*2]), "%02x", &(pOptionStr->instParam[i])) > 0) {
				i++;
			}
			pOptionStr->instParamLen = i;
	    }
	} else if (strcmp(token, "-element") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -element not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    }

	    if (sscanf (token, "%02x", &(pOptionStr->element)) <= 0) {
			printf ("Error: option -element followed by an illegal string %s\n",
			token);
			rv = EXIT_FAILURE;
			goto end;
	    }
	} else if (strcmp(token, "-priv") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -priv not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		pOptionStr->privilege = atoi(token);
	    }
	} else if (strcmp(token, "-scp") == 0) {
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -scp not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
		pOptionStr->scp = atoi(token);
	    }
	} else if (strcmp(token, "-scpimpl") == 0) {
          char **dummy = NULL;
	    token = strtokCheckComment(NULL);
	    if (token == NULL) {
			printf ("Error: option -scpimpl not followed by data\n");
			rv = EXIT_FAILURE;
			goto end;
	    } else {
              pOptionStr->scpImpl = (int)strtol(token, dummy, 0);
	    }
	} else {
	    // unknown option
	    printf ("Error: unknown option %s\n", token);
		rv = EXIT_FAILURE;
		goto end;
	}

	token = strtokCheckComment(NULL);
    }
end:
    return rv;
}
示例#20
0
void DisplayResults(HSTMT		lpStmt,
			   		SQLSMALLINT	cCols)
{
	BINDING			*pFirstBinding, *pThisBinding;			
	SQLSMALLINT		siDisplaySize;
	RETCODE			RetCode;
	int				iCount = 0;

	// Allocate memory for each column 

	AllocateBindings(lpStmt,cCols,&pFirstBinding, &siDisplaySize);

	// Set the display mode and write the titles

	DisplayTitles(lpStmt,siDisplaySize+1, pFirstBinding);


	// Fetch and display the data

	do {
		// Fetch a row

		if (iCount++ >= gHeight - 2)
		{
			int 	nInputChar;

			while(1)
			{	
				printf("              ");
				SetConsole(siDisplaySize+2,TRUE);
				printf("   Press ENTER to continue, Q to quit (height:%d)", gHeight);
				SetConsole(siDisplaySize+2,FALSE);

				nInputChar = _getch();
				printf("\n");
				if ((nInputChar == 'Q') || (nInputChar == 'q'))
				{
					goto Exit;
				}
				else if ('\r' == nInputChar)
				{
					break;
				}
				// else loop back to display prompt again
			}

			iCount = 1;
			DisplayTitles(lpStmt,siDisplaySize+1, pFirstBinding);
		}

		TRYODBC(lpStmt,SQL_HANDLE_STMT, RetCode = SQLFetch(lpStmt));

		if (RetCode == SQL_NO_DATA_FOUND)
			break;
			

		// Display the data.   Ignore truncations

		for (pThisBinding = pFirstBinding;
			 pThisBinding;
			 pThisBinding = pThisBinding->sNext)
		{
			if (pThisBinding->indPtr != SQL_NULL_DATA)
			{
				_tprintf(pThisBinding->fChar ? TEXT(DISPLAY_FORMAT_C):
											   TEXT(DISPLAY_FORMAT),
						PIPE,
						pThisBinding->siDisplaySize,
						pThisBinding->siDisplaySize,
						pThisBinding->szBuffer);
			} else
			{
				_tprintf(TEXT(DISPLAY_FORMAT_C),
						PIPE,
						pThisBinding->siDisplaySize,
						pThisBinding->siDisplaySize,
						"<NULL>");
			}
		}
		_tprintf(TEXT(" %c\n"),PIPE);


	} while ( 1);

	SetConsole(siDisplaySize+2,TRUE);
	printf("%*.*s",siDisplaySize+2,siDisplaySize+2," ");
	SetConsole(siDisplaySize+2,FALSE);
	printf("\n");

Exit:
	// Clean up the allocated buffers

	while (pFirstBinding)
	{
		pThisBinding=pFirstBinding->sNext;
		free(pFirstBinding->szBuffer);
		free(pFirstBinding);
		pFirstBinding=pThisBinding;
	}

}
示例#21
0
//Use ProcessID to control the specific process 
void GetProcessBaseAddr(DWORD processId)
{
	TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
	//require information type, ?, processid
	HANDLE hProcess = OpenProcess (PROCESS_ALL_ACCESS, FALSE, processId);
	DWORD baseAddr=0;
	
	HMODULE lphModule[BUF_SIZE];
	
	MODULEINFO miModInfo = { 0 };
	MEMORY_BASIC_INFORMATION sMemoryInfo = { 0 };

	unsigned int i =0;
	LPVOID lpBuffer[700]; //max mine is 668
	DWORD cReturned =0;
	
	if(NULL!=hProcess)
	{
		//HMODULE hMod;
		DWORD cbReturned;
		cReturned = 0;	
		
		if(EnumProcessModules(hProcess, lphModule, sizeof(lphModule), &cbReturned))
		{
			//for(i=0; i<cbReturned/4; i++)
			for(i=0; i<1; i++)
			{
				GetModuleBaseName(hProcess, lphModule[i], szProcessName, sizeof(szProcessName)/sizeof(TCHAR));
				GetModuleInformation(hProcess, lphModule[i], &miModInfo, sizeof(miModInfo));
				//_tprintf( TEXT("%s  (PID: %u) EntryPoint: 0x%8X\n"), szProcessName, processId, miModInfo.EntryPoint);
				_tprintf( TEXT("baseAddr1: 0x%8X\n"),(DWORD)miModInfo.lpBaseOfDll);
				{
						DWORD base = (DWORD)miModInfo.lpBaseOfDll+0x868B4;
						bool isMine[30][30];
						//_tprintf( TEXT("baseAddr: 0x%8X\n"),base);					
						//first pointer
						ReadProcessMemory(hProcess,(LPCVOID)(base), lpBuffer, 4, &cReturned);
						base = (DWORD)lpBuffer[0]; 
						//_tprintf( TEXT("ESI+OFFSET: %8X \n"), base);
						//second pointer 
						ReadProcessMemory(hProcess,(LPCVOID)((DWORD)(base+0x10)), lpBuffer, 4, &cReturned);
						base = (DWORD)lpBuffer[0]; //HERE IS ESI 
						//_tprintf( TEXT("%8X \n"), base);
						//NUMBER OF mines rows cols
						ReadProcessMemory(hProcess,(LPCVOID)((DWORD)(base+0x4)), lpBuffer, 12, &cReturned);
						int mines = (DWORD)lpBuffer[0], rows = (DWORD)lpBuffer[1], cols = (DWORD)lpBuffer[2]; 
						_tprintf( TEXT("Number of mines  :%2d \n"), mines);
						_tprintf( TEXT("Number of rows   :%2d \n"), rows);
						_tprintf( TEXT("Number of columns:%2d \n"), cols);

						DWORD mineBase;
						//mov ebx,dword ptr ds:[esi+44]
						ReadProcessMemory(hProcess,(LPCVOID)((DWORD)(base+0x44)), lpBuffer, 4, &cReturned);
						mineBase = (DWORD)lpBuffer[0];//ebx
						//mov ebx,dword ptr ds:[ebx+C] 
						ReadProcessMemory(hProcess,(LPCVOID)((DWORD)(mineBase+0x0C)), lpBuffer, 4, &cReturned);
						mineBase = (DWORD)lpBuffer[0];//ebx
						_tprintf(TEXT("%8X\n"), (DWORD)(lpBuffer[0]));
						//mov edx,dword ptr ds:[ebx+edx*4]

						int ptr = 0, c = 0, edx = 0;
						for(edx=0 ; edx < cols ; edx++)
						{
							//each colum
							ReadProcessMemory ( hProcess ,(LPCVOID)(mineBase+4*edx) , lpBuffer ,4 ,NULL);							
							ReadProcessMemory ( hProcess ,(LPCVOID)((DWORD)lpBuffer[0]+0xC) , lpBuffer ,4 ,NULL);	
							for ( c=0 ;c<cols ;c++ )
								ReadProcessMemory ( hProcess ,(LPCVOID)((DWORD)lpBuffer[0]+c) ,(LPVOID)&isMine[edx][c] ,1 ,&cReturned);
						}
						int r = 0;
						_tprintf(TEXT("  "));
						for ( r = 0 ; r < cols ; r++ )
						{
							_tprintf( TEXT("%2d"), r + 1);
						}
						_tprintf(TEXT("\n"));
						for ( r=0 ; r< rows ;r++ )
						{
							_tprintf(TEXT("%2d"), r + 1);
							for ( c=0 ;c< cols ;c++ )
							{
								if(isMine[c][r]) _tprintf(TEXT(" *"));
								else _tprintf(TEXT(" -"));
							}
							_tprintf(TEXT("\n"));
						}
				}
			}
 		}
	}
	else 
	{
		cout << "Failed to open the Process" << endl;
	}
	CloseHandle(hProcess);
}
示例#22
0
int __cdecl _tmain(int argc, LPTSTR* argv)
{
	BOOL	fSuccess(FALSE);
	ULONG	SlotNo;
	BOOL	bret;

	if(argc < 2) {
		usage();
		return 1;
	}

	if (lstrcmpi(argv[1],TEXT("version")) == 0) {
		WORD VersionMajor;
		WORD VersionMinor;
		WORD VersionBuild;
		WORD VersionPrivate;

		bret = NdasBusCtlGetVersion(
					&VersionMajor,
					&VersionMinor,
					&VersionBuild,
					&VersionPrivate
				);
		if(bret == FALSE) {
			_tprintf(TEXT("LanscsiBus control failed. LastError:%lu\n"), GetLastError());
		} else {
			_tprintf(TEXT("- LanscsiBus version\n"));
			_tprintf(	TEXT("Major   : %u\n")
						TEXT("Minor   : %u\n")
						TEXT("Build   : %u\n")
						TEXT("Private : %u\n"),
						VersionMajor, VersionMinor, VersionBuild, VersionPrivate);
		}
#if 0
	} else if(lstrcmpi(argv[1],TEXT("mpversion")) == 0) {
		WORD VersionMajor;
		WORD VersionMinor;
		WORD VersionBuild;
		WORD VersionPrivate;

		if(argc < 3) {
			usage();
			return 1;
		}

		SlotNo = _tstoi(argv[2]);
		bret = NdasBusCtlGetMiniportVersion(
					SlotNo,
					&VersionMajor,
					&VersionMinor,
					&VersionBuild,
					&VersionPrivate
			);
		if(bret == FALSE) {
			_tprintf(TEXT("NDASSCSI control failed. LastError:%lu\n"), GetLastError());
		} else {
			_tprintf(TEXT("- NDASSCSI version\n"));
			_tprintf(	TEXT("Major   : %u\n")
				TEXT("Minor   : %u\n")
				TEXT("Build   : %u\n")
				TEXT("Private : %u\n"),
				VersionMajor, VersionMinor, VersionBuild, VersionPrivate);
		}
#endif
	} else if(lstrcmpi(argv[1],TEXT("slotlist")) == 0) {
		PNDASBUS_INFORMATION	busInfo;

		bret = NdasBusCtlQueryPdoSlotList(&busInfo);
		if(bret == FALSE) {
			_tprintf(TEXT("Querying slot list failed. LastError:%lu\n"), GetLastError());
		} else {
			ULONG idx_slot;
			_tprintf(TEXT("Slot list:"));
			for(idx_slot = 0; idx_slot < busInfo->PdoSlotList.SlotNoCnt; idx_slot++ ) {
				_tprintf(TEXT(" %lu"), busInfo->PdoSlotList.SlotNo[idx_slot]);
			}
			_tprintf(TEXT("\n"));
			HeapFree(GetProcessHeap(), 0, busInfo);
		}
	} else if(lstrcmpi(argv[1],TEXT("pdoinfo")) == 0) {
		NDASBUS_QUERY_INFORMATION BusEnumQuery = {0};
		NDASBUS_INFORMATION BusEnumInformation = {0};

		if(argc < 3) {
			usage();
			return 1;
		}

		SlotNo = _tstoi(argv[2]);

		//
		// Get default priamry/secondary information from the NDAS bus drver.
		//

		BusEnumQuery.InfoClass = INFORMATION_PDO;
		BusEnumQuery.Size = sizeof(NDASBUS_QUERY_INFORMATION);
		BusEnumQuery.SlotNo = SlotNo;
		BusEnumQuery.Flags = 0;
		bret = NdasBusCtlQueryInformation(
			&BusEnumQuery,
			sizeof(NDASBUS_QUERY_INFORMATION),
			&BusEnumInformation,
			sizeof(NDASBUS_INFORMATION));
		if(bret == FALSE) {
			_tprintf(TEXT("NdasBusCtlQueryInformation failed. LASTERR=%x\n"), GetLastError());
			return 1;
		}

		_tprintf(TEXT("Ndas logical address: %d\n"), SlotNo);
		_tprintf(TEXT("Adapter status    : %08lx\n"), BusEnumInformation.PdoInfo.AdapterStatus);
		_tprintf(TEXT("Device mode       : %08lx\n"), BusEnumInformation.PdoInfo.DeviceMode);
		_tprintf(TEXT("Supported features: %08lx\n"), BusEnumInformation.PdoInfo.SupportedFeatures);
		_tprintf(TEXT("Enabled features  : %08lx\n"), BusEnumInformation.PdoInfo.EnabledFeatures);

	} else if(lstrcmpi(argv[1],TEXT("pdoevent")) == 0) {
		ULONG ulStatus;
		if(argc < 3) {
			usage();
			return 1;
		}

		SlotNo = _tstoi(argv[2]);
		bret = NdasBusCtlQueryEvent(SlotNo, &ulStatus);

		if(bret == FALSE) {
			DWORD lastError = GetLastError();

			if(lastError == ERROR_NO_MORE_ITEMS) {
				_tprintf(TEXT("No more event exists.\n"));
			} else if(lastError == ERROR_FILE_NOT_FOUND) {
				_tprintf(TEXT("No PDO exists.\n"));
			} else {
				_tprintf(TEXT("Querying PDO event failed. LastError:%lu\n"), GetLastError());
			}
		} else {
			PrintStatus(ulStatus);
		}
	} else if(lstrcmpi(argv[1],TEXT("pdoeventptr")) == 0) {
		HANDLE	alarm;
		HANDLE	discon;

		if(argc < 3) {
			usage();
			return 1;
		}

		SlotNo = _tstoi(argv[2]);
		bret = NdasBusCtlQueryPdoEvent(SlotNo, &alarm, &discon);
		if(bret == FALSE) {
			_tprintf(TEXT("Querying pdo events failed. LastError:%lu\n"), GetLastError());
		} else {
			_tprintf(	TEXT("Alarm event        : %p\n")
						TEXT("Disconnection event: %p\n"),
						alarm, discon
				);
			bret = CloseHandle(alarm);
			if(bret == FALSE) {
				_tprintf(TEXT("Closing alarm event failed. LastError:%lu\n"), GetLastError());
			}
			bret = CloseHandle(discon);
			if(bret == FALSE) {
				_tprintf(TEXT("Closing disconnection event failed. LastError:%lu\n"), GetLastError());
			}
		}

	} else if(lstrcmpi(argv[1],TEXT("status")) == 0) {
	  ULONG ulStatus;
		if(argc < 3) {
			usage();
			return 1;
		}

		SlotNo = _tstoi(argv[2]);
		bret = NdasBusCtlQueryStatus(SlotNo, &ulStatus);

		if(bret == FALSE) {
			_tprintf(TEXT("Querying PDO status failed. LastError:%lu\n"), GetLastError());
		} else {
			PrintStatus(ulStatus);
		}

	} else if(lstrcmpi(argv[1],TEXT("fdoinfo")) == 0) {
		PNDSCIOCTL_LURINFO	lurFullInfo;

		if(argc < 3) {
			usage();
			return 1;
		}

		SlotNo = _tstoi(argv[2]);
		bret = NdasBusCtlQueryMiniportFullInformation(SlotNo, &lurFullInfo);
		if(bret == FALSE) {
			_tprintf(TEXT("Querying LUR full information  failed. LastError:%lu\n"), GetLastError());
		} else {
			ULONG				idx_ud;
			PNDSC_LURN_FULL		unitDisk;

			_tprintf(TEXT("Structure length                     :%u\n"), lurFullInfo->Length);
			_tprintf(TEXT("Lur.Length                           :%u\n"), lurFullInfo->Lur.Length);
			_tprintf(TEXT("Lur.TargetId                         :%u\n"), lurFullInfo->Lur.TargetId);
			_tprintf(TEXT("Lur.Lun                              :%u\n"), lurFullInfo->Lur.Lun);
			_tprintf(TEXT("Lur.DeviceMode                       :%08lx\n"), lurFullInfo->Lur.DeviceMode);
			_tprintf(TEXT("Lur.SupportedFeatures                :%08lx\n"), lurFullInfo->Lur.SupportedFeatures);
			_tprintf(TEXT("Lur.EnabledFeatures                  :%08lx\n"), lurFullInfo->Lur.EnabledFeatures);
			_tprintf(TEXT("Lur.LurnCnt                          :%u\n"), lurFullInfo->Lur.LurnCnt);
			_tprintf(TEXT("EnableTime                           :%I64u\n"), lurFullInfo->EnabledTime.QuadPart);
			_tprintf(TEXT("UnitDiskCnt                          :%u\n"), lurFullInfo->LurnCnt);
			for(idx_ud = 0; idx_ud < lurFullInfo->LurnCnt; idx_ud++) {
				unitDisk = lurFullInfo->Lurns + idx_ud;
				_tprintf(TEXT("- LURN #%u   :\n"), idx_ud);
				_tprintf(TEXT("Length       :%u\n"), unitDisk->Length);
				_tprintf(TEXT("LurnId       :%u\n"), unitDisk->LurnId);
				_tprintf(TEXT("LurnType     :%u\n"), unitDisk->LurnType);

				_tprintf(TEXT("NetDiskAddress.TAAddressCount            :%u\n"), unitDisk->NetDiskAddress.TAAddressCount);
				_tprintf(TEXT("NetDiskAddress.Address[0].AddressType    :%x\n"), unitDisk->NetDiskAddress.Address[0].AddressType);
				_tprintf(TEXT("NetDiskAddress.Address[0].AddressLength  :%x\n"), unitDisk->NetDiskAddress.Address[0].AddressLength);
				_tprintf(TEXT("NetDiskAddress.Address[0].Address        :%02X %02X | %02X %02X %02X %02X %02X %02X\n"),
													(int)unitDisk->NetDiskAddress.Address[0].Address.Address[0],
													(int)unitDisk->NetDiskAddress.Address[0].Address.Address[1],
													(int)unitDisk->NetDiskAddress.Address[0].Address.Address[2],
													(int)unitDisk->NetDiskAddress.Address[0].Address.Address[3],
													(int)unitDisk->NetDiskAddress.Address[0].Address.Address[4],
													(int)unitDisk->NetDiskAddress.Address[0].Address.Address[5],
													(int)unitDisk->NetDiskAddress.Address[0].Address.Address[6],
													(int)unitDisk->NetDiskAddress.Address[0].Address.Address[7]
													);

				_tprintf(TEXT("BindingAddress.TAAddressCount            :%u\n"), unitDisk->BindingAddress.TAAddressCount);
				_tprintf(TEXT("BindingAddress.Address[0].AddressType    :%x\n"), unitDisk->BindingAddress.Address[0].AddressType);
				_tprintf(TEXT("BindingAddress.Address[0].AddressLength  :%x\n"), unitDisk->BindingAddress.Address[0].AddressLength);
				_tprintf(TEXT("BindingAddress.Address[0].Address        :%02X %02X | %02X %02X %02X %02X %02X %02X\n"),
													(int)unitDisk->BindingAddress.Address[0].Address.Address[0],
													(int)unitDisk->BindingAddress.Address[0].Address.Address[1],
													(int)unitDisk->BindingAddress.Address[0].Address.Address[2],
													(int)unitDisk->BindingAddress.Address[0].Address.Address[3],
													(int)unitDisk->BindingAddress.Address[0].Address.Address[4],
													(int)unitDisk->BindingAddress.Address[0].Address.Address[5],
													(int)unitDisk->BindingAddress.Address[0].Address.Address[6],
													(int)unitDisk->BindingAddress.Address[0].Address.Address[7]
													);
				_tprintf(TEXT("UnitDiskId   :%u\n"), (int)unitDisk->UnitDiskId);
				_tprintf(TEXT("UserID       :%02x %02x %02x %02x\n"),
															(int)unitDisk->UserID[0],
															(int)unitDisk->UserID[1],
															(int)unitDisk->UserID[2],
															(int)unitDisk->UserID[3]
															);
				_tprintf(TEXT("Password     :%02x %02x %02x %02x %02x %02x\n"),
															(int)unitDisk->Password[0],
															(int)unitDisk->Password[1],
															(int)unitDisk->Password[2],
															(int)unitDisk->Password[3],
															(int)unitDisk->Password[4],
															(int)unitDisk->Password[5]
															);
				_tprintf(TEXT("AccessRight  :%08lx\n"), unitDisk->AccessRight);
				_tprintf(TEXT("UnitBlocks   :%u\n"), unitDisk->UnitBlocks);
				_tprintf(TEXT("StatusFlags  :%u\n"), unitDisk->StatusFlags);
			}
			_tprintf(TEXT("\n"));
			HeapFree(GetProcessHeap(), 0, lurFullInfo);
		}

	}  else if(lstrcmpi(argv[1],TEXT("pdofile")) == 0) {
		HANDLE	pdoFileHandle;

		SlotNo = _tstoi(argv[2]);
		bret = NdasBusCtlQueryPdoFileHandle(SlotNo, &pdoFileHandle);
		if(bret == FALSE) {
			_tprintf(TEXT("Querying PDO file handle  failed. LastError:%lu\n"), GetLastError());
		} else {
			_tprintf(TEXT("PDO file handle  :%p\n"), pdoFileHandle);
			CloseHandle(pdoFileHandle);
		}
	} else {
		usage();
	}


	return fSuccess ? 0 : 1;
}
示例#23
0
int _tmain(int argc, _TCHAR* argv[])
{
	_tsetlocale(LC_ALL, _T("")); // fixes VS11DP quirk

	// open csv file

	RCSVFileRO file;

	if (argc == 2)
	{
		if (!file.Open(CorrectPath(argv[1])))
			{_putts(_T("Unable to open file: ") + CorrectPath(argv[1])); PAUSERETURN(-1);}
	}
	else if (argc == 1)
	{
		if (!file.Open(CorrectPath(_T("strings.csv"))))
			{_putts(_T("Please supply the name of CSV-file.")); PAUSERETURN(-2);}
	}
	else
		{_putts(_T("Invalid argument count.")); PAUSERETURN(-3);}

	if (file.GetLineCount() == 0)
		{_putts(_T("Empty file.")); PAUSERETURN(1);}

	if (file.GetLineCount() < 2)
		{_putts(_T("File must contain at least two lines.")); PAUSERETURN(-4);}

	if (file.GetFieldCount() < 2)
		{_putts(_T("File must contain at least two columns.")); PAUSERETURN(-5);}

	// generate header file contents

	RString str;
	str += _T("// strings.h : Defines the strings to be used throughout the application.\r\n");
	str += _T("//\r\n");
	str += _T("\r\n");

	int n = 1000;
	
	int i, j;
	for (i = 1; i < file.GetLineCount(); i++)
		if (_tcscmp(file.GetField(i, 0), _T("")) != 0)
			str += RString(_T("#define ")) + file.GetField(i, 0) + _T(" ") + NumberToString(n++) + _T("\r\n");

	str += _T("\r\n");
	str += _T("inline void LoadStrings()\r\n");
	str += _T("{\r\n");
	str += _T("\tINT_PTR nLanguage;\r\n");

	for (i = 1; i < file.GetFieldCount(); i++)
	{
		str += _T("\r\n");
		str += (RString)_T("\tnLanguage = GetLangMgr()->GetLanguage(_T(\"") + file.GetField(0, i) + _T("\"));\r\n");
		str += (RString)_T("\tif (nLanguage == -1)\r\n");
		str += (RString)_T("\t\tnLanguage = GetLangMgr()->AddLanguage(_T(\"") + file.GetField(0, i) + _T("\"), _T(\"") + file.GetField(1, i)
				+ _T("\"), _T(\"\"));\r\n\r\n");

		for (j = 1; j < file.GetLineCount(); j++)
		{
			if (_tcscmp(file.GetField(j, 0), _T("")) == 0)
				continue; // skip empty ids

			str += (RString)_T("\tGetLangMgr()->SetString(nLanguage, ") + NumberToString(j-1) + _T(", _T(\"") +
					file.GetField(j, i) + _T("\"), false);\r\n");
		}
	}

	str += _T("}\r\n");

	// write to file

	RString strFilePath = CorrectPath(argc == 2 ? argv[1] : _T("strings.csv"));
	strFilePath = strFilePath.Left(strFilePath.ReverseFind(_T('\\'))+1) + _T("strings.h");

	RArray<BYTE> data = StringToData(str, CHARSET_ANSI);
	if (!DataToFile(data, strFilePath))
		{_tprintf(_T("Failed to open %s for writing.\n"), (LPCTSTR)strFilePath); PAUSERETURN(-6);}

	_tprintf(_T("Created %s succesfully.\n"), (LPCTSTR)strFilePath);

	PAUSERETURN(0);
}
示例#24
0
void usage()
{
	_tprintf(TEXT("ndasbuscmd [version | slotlist | fdoinfo | status | pdoinfo | pdoevent | pdoeventptr | pdofile] slotno\n"));
}
示例#25
0
文件: regproc.c 项目: Moteesh/reactos
/******************************************************************************
 * Writes contents of the registry key to the specified file stream.
 *
 * Parameters:
 * file_name - name of a file to export registry branch to.
 * reg_key_name - registry branch to export. The whole registry is exported if
 *      reg_key_name is NULL or contains an empty string.
 */
BOOL export_registry_key(TCHAR* file_name, TCHAR* reg_key_name)
{
    HKEY reg_key_class;

    TCHAR *reg_key_name_buf;
    TCHAR *val_name_buf;
    BYTE *val_buf;
    DWORD reg_key_name_len = KEY_MAX_LEN;
    DWORD val_name_len = KEY_MAX_LEN;
    DWORD val_size = REG_VAL_BUF_SIZE;
    FILE *file = NULL;

    //_tprintf(_T("export_registry_key(%s, %s)\n"), reg_key_name, file_name);

    reg_key_name_buf = HeapAlloc(GetProcessHeap(), 0, reg_key_name_len * sizeof(*reg_key_name_buf));
    val_name_buf = HeapAlloc(GetProcessHeap(), 0, val_name_len * sizeof(*val_name_buf));
    val_buf = HeapAlloc(GetProcessHeap(), 0, val_size);
    CHECK_ENOUGH_MEMORY(reg_key_name_buf && val_name_buf && val_buf);

    if (reg_key_name && reg_key_name[0]) {
        TCHAR *branch_name;
        HKEY key;

        REGPROC_resize_char_buffer(&reg_key_name_buf, &reg_key_name_len,
                                   _tcslen(reg_key_name));
        _tcscpy(reg_key_name_buf, reg_key_name);

        /* open the specified key */
        reg_key_class = getRegClass(reg_key_name);
        if (reg_key_class == (HKEY)ERROR_INVALID_PARAMETER) {
            _tprintf(_T("Incorrect registry class specification in '%s\n"), reg_key_name);
            //exit(1);
            return FALSE;
        }
        branch_name = getRegKeyName(reg_key_name);
        CHECK_ENOUGH_MEMORY(branch_name);
        if (!branch_name[0]) {
            /* no branch - registry class is specified */
            file = REGPROC_open_export_file(file_name);
            export_hkey(file, reg_key_class,
                        &reg_key_name_buf, &reg_key_name_len,
                        &val_name_buf, &val_name_len,
                        &val_buf, &val_size);
        } else if (RegOpenKey(reg_key_class, branch_name, &key) == ERROR_SUCCESS) {
            file = REGPROC_open_export_file(file_name);
            export_hkey(file, key,
                        &reg_key_name_buf, &reg_key_name_len,
                        &val_name_buf, &val_name_len,
                        &val_buf, &val_size);
            RegCloseKey(key);
        } else {
            _tprintf(_T("Can't export. Registry key '%s does not exist!\n"), reg_key_name);
            REGPROC_print_error();
        }
        HeapFree(GetProcessHeap(), 0, branch_name);
    } else {
        int i;

        /* export all registry classes */
        file = REGPROC_open_export_file(file_name);
        for (i = 0; i < REG_CLASS_NUMBER; i++) {
            /* do not export HKEY_CLASSES_ROOT */
            if (reg_class_keys[i] != HKEY_CLASSES_ROOT &&
                reg_class_keys[i] != HKEY_CURRENT_USER &&
                reg_class_keys[i] != HKEY_CURRENT_CONFIG) {
                _tcscpy(reg_key_name_buf, reg_class_names[i]);
                export_hkey(file, reg_class_keys[i],
                            &reg_key_name_buf, &reg_key_name_len,
                            &val_name_buf, &val_name_len,
                            &val_buf, &val_size);
            }
        }
    }
    if (file) {
        fclose(file);
    }
//    HeapFree(GetProcessHeap(), 0, reg_key_name);
    HeapFree(GetProcessHeap(), 0, val_buf);
    HeapFree(GetProcessHeap(), 0, val_name_buf);
    HeapFree(GetProcessHeap(), 0, reg_key_name_buf);
    return TRUE;
}
示例#26
0
文件: app.c 项目: stoni/luarest
static luarest_status parse_apps(application** apps, char* directory_path)
{
#ifdef WIN32
	WIN32_FIND_DATA ffd;
	WIN32_FIND_DATA fap;
	size_t length_of_arg;
	TCHAR szDir[MAX_PATH];
	TCHAR appFile[MAX_PATH];
	HANDLE hFind = INVALID_HANDLE_VALUE;
	HANDLE hApp = INVALID_HANDLE_VALUE;
	luarest_status ret;
	// Check that the input path plus 2 is not longer than MAX_PATH.
	StringCchLength(directory_path, MAX_PATH, &length_of_arg);
	if (length_of_arg > (MAX_PATH - 2)) {
		_tprintf(TEXT("\nDirectory path is too long.\n"));
		return(LUAREST_ERROR);
	}
	// Prepare string for use with FindFile functions.  First, copy the
	// string to a buffer, then append '\*' to the directory name.
	StringCchCopy(szDir, MAX_PATH, directory_path);
	StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
	// Find the first file in the directory.
	hFind = FindFirstFile(szDir, &ffd);
	if (INVALID_HANDLE_VALUE == hFind) {
      return(LUAREST_ERROR);
	}
	// List all the files in the directory with some info about them.
	do {
		if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
			StringCchCopy(appFile, MAX_PATH, directory_path);
			StringCchCat(appFile, MAX_PATH, TEXT("\\"));
			StringCchCat(appFile, MAX_PATH, ffd.cFileName);
			StringCchCat(appFile, MAX_PATH, TEXT("\\"));
			StringCchCat(appFile, MAX_PATH, APP_ENTRY_POINT);
			hApp = FindFirstFile(appFile, &fap);
			if (hApp != INVALID_HANDLE_VALUE) {
				UT_string* app;
				utstring_new(app);
				utstring_printf(app, appFile);
				/* verify application */
				ret = verify_application(apps, ffd.cFileName, app);
				utstring_free(app);
				if (ret != LUAREST_SUCCESS) {
					printf("Application %s couldn't be load due to errors!\n", ffd.cFileName);
				}
			}
			FindClose(hApp);
		}
	}
	while (FindNextFile(hFind, &ffd) != 0);
	FindClose(hFind);
#else
    DIR *dpdf;
    struct dirent *epdf;
    struct stat st;
    int is_dir = 0;
    dpdf = opendir("./");
    if (dpdf != NULL){
        while ( (epdf = readdir(dpdf)) != NULL) {
            if (stat(epdf->d_name, &st) == -1) {
                continue;
            }
            is_dir = (st.st_mode & S_IFDIR) != 0;
            if (is_dir) {
                continue;
            }
            /* re-do for unix */
        }
    }
    closedir(dpdf);
#endif
	return(LUAREST_SUCCESS);
}
示例#27
0
文件: regproc.c 项目: Moteesh/reactos
/******************************************************************************
 * This funtion is the main entry point to the deleteKey type of action.  It
 * receives the currently read line and dispatch the work depending on the
 * context.
 */
void doDeleteKey(LPTSTR line)   {
  _tprintf(_T("deleteKey not yet implemented\n"));
}
示例#28
0
void LoadCommonMPQFiles(uint32 build)
{
    TCHAR filename[512];
    _stprintf(filename, _T("%sworld.MPQ"), input_path);
    _tprintf(_T("Loading common MPQ files\n"));
    if (!SFileOpenArchive(filename, 0, MPQ_OPEN_READ_ONLY, &WorldMpq))
    {
        if (GetLastError() != ERROR_PATH_NOT_FOUND)
            _tprintf(_T("Cannot open archive %s\n"), filename);
        return;
    }

    int count = sizeof(CONF_mpq_list) / sizeof(char*);
    for (int i = 1; i < count; ++i)
    {
        if (build < 15211 && !strcmp("world2.MPQ", CONF_mpq_list[i]))   // 4.3.2 and higher MPQ
            continue;

        _stprintf(filename, _T("%s%s"), input_path, CONF_mpq_list[i]);
        if (!SFileOpenPatchArchive(WorldMpq, filename, "", 0))
        {
            if (GetLastError() != ERROR_PATH_NOT_FOUND)
                _tprintf(_T("Cannot open archive %s\n"), filename);
            else
                _tprintf(_T("Not found %s\n"), filename);
        }
        else
            _tprintf(_T("Loaded %s\n"), filename);
    }

    char const* prefix = NULL;
    for (int i = 0; Builds[i] && Builds[i] <= CONF_TargetBuild; ++i)
    {
        // Do not attempt to read older MPQ patch archives past this build, they were merged with base
        // and trying to read them together with new base will not end well
        if (CONF_TargetBuild >= NEW_BASE_SET_BUILD && Builds[i] < NEW_BASE_SET_BUILD)
            continue;

        memset(filename, 0, sizeof(filename));
        if (Builds[i] > LAST_DBC_IN_DATA_BUILD)
        {
            prefix = "";
            _stprintf(filename, _T("%swow-update-base-%u.MPQ"), input_path, Builds[i]);
        }
        else
        {
            prefix = "base";
            _stprintf(filename, _T("%swow-update-%u.MPQ"), input_path, Builds[i]);
        }

        if (!SFileOpenPatchArchive(WorldMpq, filename, prefix, 0))
        {
            if (GetLastError() != ERROR_PATH_NOT_FOUND)
                _tprintf(_T("Cannot open patch archive %s\n"), filename);
            else
                _tprintf(_T("Not found %s\n"), filename);
            continue;
        }
        else
            _tprintf(_T("Loaded %s\n"), filename);
    }

    printf("\n");
}
示例#29
0
文件: regproc.c 项目: Moteesh/reactos
/******************************************************************************
 * This function is a wrapper for the queryValue function.  It prepares the
 * land and clean the area once completed.
 */
void processQueryValue(LPTSTR cmdline)
{
  _tprintf(_T("ERROR!!! - temporary disabled"));
  //exit(1);
  return;
#if 0
  LPSTR   argv[QUERY_VALUE_MAX_ARGS];/* args storage    */
  LPSTR   token      = NULL;         /* current token analized */
  ULONG   argCounter = 0;            /* counter of args */
  INT     counter;
  HRESULT hRes       = 0;
  LPSTR   keyValue   = NULL;
  LPSTR   lpsRes     = NULL;

  /*
   * Init storage and parse the line
   */
  for (counter = 0; counter < QUERY_VALUE_MAX_ARGS; counter++)
    argv[counter] = NULL;

  while ((token = getToken(&cmdline, queryValueDelim[argCounter])) != NULL) {
    argv[argCounter++] = getArg(token);
    if (argCounter == QUERY_VALUE_MAX_ARGS)
      break;  /* Stop processing args no matter what */
  }

  /* The value we look for is the first token on the line */
  if (argv[0] == NULL)
    return; /* SHOULD NOT HAPPEN */
  else
    keyValue = argv[0];

  if ((keyValue[0] == '@') && (_tcslen(keyValue) == 1)) {
    LONG lLen = KEY_MAX_LEN;
    TCHAR* lpsData = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,KEY_MAX_LEN);
    /*
     * We need to query the key default value
     */
    hRes = RegQueryValue(currentKeyHandle, currentKeyName, (LPBYTE)lpsData, &lLen);
    if (hRes == ERROR_MORE_DATA) {
        lpsData = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpsData, lLen);
        hRes = RegQueryValue(currentKeyHandle, currentKeyName, (LPBYTE)lpsData, &lLen);
    }
    if (hRes == ERROR_SUCCESS) {
      lpsRes = HeapAlloc(GetProcessHeap(), 0, lLen);
      strncpy(lpsRes, lpsData, lLen);
      lpsRes[lLen-1]='\0';
    }
  } else {
    DWORD dwLen = KEY_MAX_LEN;
    BYTE* lpbData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, KEY_MAX_LEN);
    DWORD dwType;
    /*
     * We need to query a specific value for the key
     */
    hRes = RegQueryValueEx(
             currentKeyHandle,
             keyValue,
             0,
             &dwType,
             (LPBYTE)lpbData,
             &dwLen);

    if (hRes == ERROR_MORE_DATA) {
        lpbData = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, lpbData, dwLen * sizeof(TCHAR));
        hRes = RegQueryValueEx(currentKeyHandle, keyValue, NULL, &dwType, (LPBYTE)lpbData, &dwLen);
    }

    if (hRes == ERROR_SUCCESS) {
      /*
       * Convert the returned data to a displayable format
       */
      switch (dwType) {
        case REG_SZ:
        case REG_EXPAND_SZ:
          lpsRes = HeapAlloc(GetProcessHeap(), 0, dwLen * sizeof(TCHAR));
          strncpy(lpsRes, lpbData, dwLen);
          lpsRes[dwLen-1] = '\0';
          break;
        case REG_DWORD:
          lpsRes = convertHexToDWORDStr(lpbData, dwLen);
          break;
        default:
          lpsRes = convertHexToHexCSV(lpbData, dwLen);
          break;
      }
    }

    HeapFree(GetProcessHeap(), 0, lpbData);
  }
  if (hRes == ERROR_SUCCESS) {
    _tprintf(_T("Value \"%s\" = \"%s\" in key [%s]\n"), keyValue, lpsRes, currentKeyName);

  } else {
    _tprintf(_T("ERROR Value \"%s\" not found. for key \"%s\"\n"), keyValue, currentKeyName);
  }

  /*
   * Do some cleanup
   */
  for (counter=0; counter<argCounter; counter++)
    if (argv[counter] != NULL)
      HeapFree(GetProcessHeap(), 0, argv[counter]);

  if (lpsRes != NULL)
    HeapFree(GetProcessHeap(), 0, lpsRes);
#endif
}
示例#30
0
/**
 * Adds a string to a registry string list (STRING_SZ).
 * Only operates in HKLM for now, needs to be extended later for
 * using other hives. Only processes lists with a "," separator
 * at the moment.
 *
 * @return  Exit code (EXIT_OK, EXIT_FAIL)
 * @param   pszSubKey           Sub key containing the list.
 * @param   pszKeyValue         The actual key name of the list.
 * @param   pszValueToAdd       The value to add to the list.
 * @param   uiOrder             Position (zero-based) of where to add the value to the list.
 * @param   dwFlags             Flags.
 */
int RegistryAddStringToList(const TCHAR *pszSubKey, const TCHAR *pszKeyValue, const TCHAR *pszValueToAdd,
                            unsigned int uiOrder, DWORD dwFlags)
{
    HKEY hKey = NULL;
    DWORD disp, dwType;
    LONG lRet = RegCreateKeyEx(HKEY_LOCAL_MACHINE, pszSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, &hKey, &disp);
    if (lRet != ERROR_SUCCESS)
        _tprintf(_T("RegistryAddStringToList: RegCreateKeyEx %ts failed with error %ld!\n"), pszSubKey, lRet);

    TCHAR szKeyValue[512] = { 0 };
    TCHAR szNewKeyValue[512] = { 0 };
    DWORD cbKeyValue = sizeof(szKeyValue);

    lRet = RegQueryValueEx(hKey, pszKeyValue, NULL, &dwType, (LPBYTE)szKeyValue, &cbKeyValue);
    if (   lRet != ERROR_SUCCESS
        || dwType != REG_SZ)
    {
        _tprintf(_T("RegistryAddStringToList: RegQueryValueEx failed with %d, key type = 0x%x!\n"), lRet, dwType);
    }

    if (lRet == ERROR_SUCCESS)
    {
    #ifdef DEBUG
        _tprintf(_T("RegistryAddStringToList: Key value: %ws\n"), szKeyValue);
    #endif

        /* Create entire new list. */
        unsigned int iPos = 0;
        TCHAR *pszToken = wcstok(szKeyValue, _T(","));
        TCHAR *pszNewToken = NULL;
        while (pszToken != NULL)
        {
            pszNewToken = wcstok(NULL, _T(","));

            /* Append new provider name (at beginning if iOrder=0). */
            if (iPos == uiOrder)
            {
                wcscat(szNewKeyValue, pszValueToAdd);
                wcscat(szNewKeyValue, _T(","));
                iPos++;
            }

            BOOL fAddToList = FALSE;
            if (   !wcsicmp(pszToken, pszValueToAdd)
                && (dwFlags & VBOX_REG_STRINGLIST_ALLOW_DUPLICATES))
                fAddToList = TRUE;
            else if (wcsicmp(pszToken, pszValueToAdd))
                fAddToList = TRUE;

            if (fAddToList)
            {
                wcscat(szNewKeyValue, pszToken);
                wcscat(szNewKeyValue, _T(","));
                iPos++;
            }

    #ifdef DEBUG
            _tprintf (_T("RegistryAddStringToList: Temp new key value: %ws\n"), szNewKeyValue);
    #endif
            pszToken = pszNewToken;
        }

        /* Append as last item if needed. */
        if (uiOrder >= iPos)
            wcscat(szNewKeyValue, pszValueToAdd);

        /* Last char a delimiter? Cut off ... */
        if (szNewKeyValue[wcslen(szNewKeyValue) - 1] == ',')
            szNewKeyValue[wcslen(szNewKeyValue) - 1] = '\0';

        size_t iNewLen = (wcslen(szNewKeyValue) * sizeof(WCHAR)) + sizeof(WCHAR);

    #ifdef DEBUG
        _tprintf(_T("RegistryAddStringToList: New provider list: %ws (%u bytes)\n"), szNewKeyValue, iNewLen);
    #endif

        lRet = RegSetValueExW(hKey, pszKeyValue, 0, REG_SZ, (LPBYTE)szNewKeyValue, (DWORD)iNewLen);
        if (lRet != ERROR_SUCCESS)
            _tprintf(_T("RegistryAddStringToList: RegSetValueEx failed with %ld!\n"), lRet);
    }

    RegCloseKey(hKey);
    return (lRet == ERROR_SUCCESS) ? EXIT_OK : EXIT_FAIL;
}