Beispiel #1
0
	FDWEpollBackend::FDWEpollBackend(int nfds_)
		:FDWBackend(nfds_), sr(0)
	{
		if ((epfd = epoll_create(nfds)) < 0)
			throw InitError("failed to open epoll device");
		epevents.reset(new struct epoll_event[nfds]);

		std::memset(epevents.get(), 0, sizeof(struct epoll_event) * nfds);

		INFO1("fdwatch epoll() based layer initialized (max %d sockets)", nfds);
	}
/** Sanity checks
 *  Ensure that Bitcoin is running in a usable environment with all
 *  necessary library support.
 */
bool InitSanityCheck(void)
{
    if (!ECC_InitSanityCheck())
    {
        InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more "
                  "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries");
        return false;
    };

    // TODO: remaining sanity checks, see #4081

    return true;
}
Beispiel #3
0
QtSpeech::QtSpeech(VoiceName n, QObject * parent)
    :QObject(parent), d(new Private)
{
    if (n.id.isEmpty()) {
        VoiceName def = {Private::VoiceId.arg("english"), "English"};
        n = def;
    }

    if (n.id.isEmpty())
        throw InitError(Where+"No default voice in system");

    d->name = n;
}
Beispiel #4
0
Subscriber::Subscriber (int argc, ACE_TCHAR *argv[]) throw (Subscriber::InitError)
  : topic_count_ (1), participant_count_ (1), reader_count_(1)
  , control_file_ ("barrier_file"), publisher_count_ (1)
{
  try
    {
      dpf_ = TheParticipantFactoryWithArgs (argc, argv);

      if (!this->parse_args (argc, argv)) {
        throw InitError ("Subscriber::ctor> Failed to parse args.");
      }

      sync_client_.reset (new SyncClientExt_i (sync_server_, CORBA::ORB::_nil()
                                            , SyncClient_i::Sub));
    }
    catch (SyncClient_i::InitError& er)
    {
      std::cerr << "Exception in SyncClient_i initialization."
                << std::endl;
      throw InitError (er);
    }
  catch (CORBA::Exception& ex)
    {
       cerr << "PUB: Exception caught in Publisher cstr:" << endl
            << ex << endl;
       throw InitError (ex._info().c_str());
    }

  size_t max_subs
    = ((participant_count_ > topic_count_) ? topic_count_ : participant_count_);
  max_subs = ((max_subs > reader_count_) ? reader_count_ : max_subs);
  reader_count_ = max_subs;

  participant_.resize (participant_count_);
  topic_.resize (topic_count_);
  subs_.resize (reader_count_);
  dr_.resize (reader_count_);
}
 TImpl(const Stroka& style, const Stroka& base = "") {
     InitError();
     TxmlDocHolder sheetDoc(xmlParseMemory(~style, +style));
     if (!!base) {
         xmlNodeSetBase(sheetDoc->children, (xmlChar*)base.c_str());
     }
     if (!sheetDoc)
         ythrow yexception() << "cannot parse xml of xslt: " << ErrorMessage;
     Stylesheet.Reset(xsltParseStylesheetDoc(sheetDoc.Get()));
     if (!Stylesheet)
         ythrow yexception() << "cannot parse xslt: " << ErrorMessage;
     // sheetDoc - ownership transferred to Stylesheet
     sheetDoc.Release();
 }
bool static Bind(const CService &addr, bool fError = true)
{
    if (IsLimited(addr))
        return false;

    std::string strError;
    if (!BindListenPort(addr, strError))
    {
        if (fError)
            return InitError(strError);
        return false;
    };

    return true;
}
Beispiel #7
0
SyncServer::SyncServer (int argc, ACE_TCHAR* argv[])
  throw (SyncServer::InitError)
  : pub_count_ (1), sub_count_ (1)
{
  try
    {
      CORBA::ORB_var orb = CORBA::ORB_init (argc, argv, "SyncServer");
      if (!this->parse_args (argc, argv)) {
        throw InitError ("SyncServer encountered failure while parsing arguments.\n");
      }

      sync_server_.reset (new SyncExt_i (pub_count_, sub_count_
                                         , orb.in()));
      // Bump up the ref count (TAO proprietary) so object can exist
      //  beyond ORB destruction.
      sync_server_->_add_ref();
    }
  catch (SyncServer_i::InitError& e) {
    throw InitError (e);
  }
  catch (CORBA::Exception& ex) {
    throw InitError (ex._info().c_str());
  }
}
Beispiel #8
0
FDWKqueueBackend::FDWKqueueBackend(int nfds_)
:FDWBackend(nfds_), sr(0), nochanges(0)
{
	if ((kq = kqueue()) == -1)
		throw InitError("error from kqueue()");

	kqevents.reset(new struct kevent[nfds]);
	kqchanges.reset(new struct kevent[nfds * 2]);
	rridx.reset(new int[nfds]);
	wridx.reset(new int[nfds]);

	std::memset(kqchanges.get(), 0, sizeof(struct kevent) * nfds);
	for (int i = 0; i < nfds; i++)
	{
		rridx[i] = -1;
		wridx[i] = -1;
	}

	INFO1("fdwatch kqueue() based layer initialized (max %d sockets)", nfds);
}
QtSpeech::QtSpeech(VoiceName n, QObject * parent)
    :QObject(parent), d(new Private)
{
    ULONG count = 0;
    CComPtr<IEnumSpObjectTokens> voices;

    CoInitialize(NULL);
    SysCall( d->voice.CoCreateInstance( CLSID_SpVoice ), InitError);

    if (n.id.isEmpty()) {
        WCHAR * w_id = 0L;
        WCHAR * w_name = 0L;
        CComPtr<ISpObjectToken> voice;
        SysCall( d->voice->GetVoice(&voice), InitError);
        SysCall( SpGetDescription(voice, &w_name), InitError);
        SysCall( voice->GetId(&w_id), InitError);
        n.name = QString::fromWCharArray(w_name);
        n.id = QString::fromWCharArray(w_id);
        voice.Release();
    }
    else {
        SysCall( SpEnumTokens(SPCAT_VOICES, NULL, NULL, &voices), InitError);
        SysCall( voices->GetCount(&count), InitError);
        for (int i =0; i< count; i++) {
            WCHAR * w_id = 0L;
            CComPtr<ISpObjectToken> voice;
            SysCall( voices->Next( 1, &voice, NULL ), InitError);
            SysCall( voice->GetId(&w_id), InitError);
            QString id = QString::fromWCharArray(w_id);
            if (id == n.id) d->voice->SetVoice(voice);
            voice.Release();
        }
    }

    if (n.id.isEmpty())
        throw InitError(Where+"No default voice in system");

    d->name = n;
    d->ptrs << this;
}
/// <summary>Creates an open gl shader by loading in GLSL source code from an external
/// file</summary>
/// <param name="fileLocation">The path to a file to load the GLSL source code from</param>
/// <param name="type">The open gl constant (often found in the form GL_(shader type)_SHADER) representing the type of shader to create</param>
/// <returns>The GLuint handle for the compiled shader</returns>
/// <exception cref="InitError">Throws InitError if fileLocation is invalid</exception>
/// <exception cref="GLError">Throws GLError if the source code fails to compile </exception>
GLuint ShaderHelper::makeGLShader(string fileLocation, GLint type)
{
	ifstream file;
	file.exceptions(ifstream::badbit);
	
	string shaderSource;

	try
	{
		file.open(fileLocation);

		stringstream fileInput;
		fileInput << file.rdbuf();
		file.close();

		shaderSource = fileInput.str();
	}
	catch (ifstream::failure)
	{
		throw InitError("Failed to open/read shader source code at path \"" + fileLocation + "\"");
	}

	const GLchar* cStyleSource = shaderSource.c_str();

	
	GLuint shader;
	shader = glCreateShader(type);
	glShaderSource(shader, 1, &cStyleSource, NULL);
	glCompileShader(shader);

	GLint success;
	glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
	if (!success)
	{
		throw GLError(GLErrorType::SHADER, shader, ("GL Shader at \"" + fileLocation + "\" failed to compile."));
	}

	return shader;
}
Beispiel #11
0
GLuint GeneralGL::MakeShader(GLenum type, std::string path)
{
	std::ifstream file;
	file.exceptions(std::ifstream::badbit);

	std::string shaderSource;

	try
	{
		file.open(path);

		std::stringstream fileInput;
		fileInput << file.rdbuf();
		file.close();

		shaderSource = fileInput.str();
	}
	catch (std::ifstream::failure)
	{
		throw InitError("Failed to open/read shader source code at path \"" + path + "\"");
	}

	const GLchar* cStyleSource = shaderSource.c_str();


	GLuint shader;
	shader = glCreateShader(type);
	glShaderSource(shader, 1, &cStyleSource, NULL);
	glCompileShader(shader);

	GLint success;
	glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
	if (!success)
	{
		throw GeneralGL::GLError(GLErrorType::SHADER, shader, ("GL Shader at \"" + path + "\" failed to compile."));
	}

	return shader;
}
// implementation
QtSpeech::QtSpeech(QObject * parent)
    :QObject(parent), d(new Private)
{
    CoInitialize(NULL);
    SysCall( d->voice.CoCreateInstance( CLSID_SpVoice ), InitError);

    VoiceName n;
    WCHAR * w_id = 0L;
    WCHAR * w_name = 0L;
    CComPtr<ISpObjectToken> voice;
    SysCall( d->voice->GetVoice(&voice), InitError);
    SysCall( SpGetDescription(voice, &w_name), InitError);
    SysCall( voice->GetId(&w_id), InitError);
    n.name = QString::fromWCharArray(w_name);
    n.id = QString::fromWCharArray(w_id);
    voice.Release();

    if (n.id.isEmpty())
        throw InitError(Where+"No default voice in system");

    d->name = n;
    d->ptrs << this;
}
Beispiel #13
0
void
Lorica::Proxy::configure(Config & config, 
			 const std::string &def_ior_file )
	throw (InitError)
{
	try {
		// This should be OK even if multiple copies of Proxy
		// get created as they all create the same ORB instance
		// and therefore the single ORB instance will get shutdown.
		Lorica::Proxy::this_ = this;

		std::auto_ptr<ACE_ARGV> arguments(config.get_orb_options());

		// Create proxy ORB.
		int argc = arguments->argc();
		if (Lorica_debug_level > 2) {
			ACE_DEBUG((LM_DEBUG,
				   ACE_TEXT("(%T) %N:%l - passing %d args to ORB_init:\n"), 
				   argc));

			for (int i = 0; i < argc; i++)
				ACE_DEBUG((LM_DEBUG, ACE_TEXT("%N:%l - %s\n"), arguments->argv()[i]));
		}
		orb_ = CORBA::ORB_init(argc, arguments->argv());

		// test if we have any security functionality
		ACE_Service_Repository * repo = 
			orb_->orb_core()->configuration()->
			current_service_repository();
		config.secure_available(repo->find("SSLIOP_Factory") == 0);

		int attempts = 3;
		CORBA::Object_var obj = CORBA::Object::_nil();
		resolve_again:
		try {
			obj = orb_->resolve_initial_references("RootPOA");
		}
		catch (CORBA::Exception & ex) {
			if (attempts--) {
				ACE_DEBUG((LM_INFO, ACE_TEXT("(%T) %N:%l - Exception trying to resolve initial references\n")));
				ACE_OS::sleep(10);
				goto resolve_again;
			}
			ACE_DEBUG((LM_ERROR, ACE_TEXT("(%T) %N:%l - %s\n"), ex._info().c_str()));
			throw InitError();
		}

		root_poa_ = PortableServer::POA::_narrow(obj.in());
		if (CORBA::is_nil(root_poa_.in())) {
			ACE_ERROR((LM_ERROR,
				   "(%T) %N:%l - could not get root POA\n"));
			throw InitError();
		}

		pmf_ = root_poa_->the_POAManagerFactory();
		if (CORBA::is_nil(pmf_.in())) {
			ACE_ERROR((LM_ERROR,
				   "(%T) %N:%l - could not get PMF\n"));
			throw InitError();
		}

		obj = orb_->resolve_initial_references("IORTable");
		iorTable_ = IORTable::Table::_narrow(obj.in());
		if (CORBA::is_nil(iorTable_.in())) {
			ACE_ERROR((LM_ERROR,
				   "(%T) %N:%l - could not get IORTable\n"));
			throw InitError();
		}

		CORBA::PolicyList policies;
		EndpointPolicy::EndpointList list;
		CORBA::Any policy_value;

		// Create external POA manager
		Config::Endpoints ex_points = config.get_endpoints(true);
		policies.length(1);
		list.length(ex_points.size());
		if (Lorica_debug_level > 2) {
			ACE_DEBUG((LM_DEBUG,
				   ACE_TEXT("(%T) %N:%l - setting up External POA manager with %d endpoints\n"),
				   ex_points.size()));
		}
		for (size_t count = 0; count < ex_points.size(); count++) {
			std::string inter = ex_points[count].hostname_;
			if (!ex_points[count].alias_.empty())
				inter = ex_points[count].alias_;

			list[count] = new IIOPEndpointValue_i(inter.c_str(),
							      ex_points[count].port_);
		}
		policy_value <<= list;
		policies[0] = orb_->create_policy(EndpointPolicy::ENDPOINT_POLICY_TYPE,
						  policy_value);
		outside_pm_ = pmf_->create_POAManager("OutsidePOAManager",
						      policies);

		// Create internal POA manager.
		Config::Endpoints in_points = config.get_endpoints(false);
		policies.length(1);
		list.length(in_points.size());
		if (Lorica_debug_level > 2) {
			ACE_DEBUG((LM_DEBUG,
				   ACE_TEXT("(%T) %N:%l - setting up Internal POA manager with %d endpoints\n"),
				   in_points.size()));
		}
		for (size_t count = 0; count < in_points.size(); count++) {
			std::string inter = in_points[count].hostname_;
			if (!in_points[count].alias_.empty())
				inter = in_points[count].alias_;

			list[count] = new IIOPEndpointValue_i(inter.c_str(),
							      in_points[count].port_);
		}
		policy_value <<= list;
		policies[0] = orb_->create_policy(EndpointPolicy::ENDPOINT_POLICY_TYPE,
						  policy_value);
		inside_pm_ = pmf_->create_POAManager("InsidePOAManager",
						     policies);

		if (Lorica_debug_level > 2) {
			ACE_DEBUG((LM_DEBUG,
				   ACE_TEXT("(%T) %N:%l - creating admin POA with internal POA manager\n")));
		}
		policies.length(0);
		admin_poa_ = root_poa_->create_POA("adminPOA",
						   inside_pm_.in(),
						   policies);

		try {
			ReferenceMapper_i *refMapper = new ReferenceMapper_i(orb_.in(),
									     iorTable_.in(),
									     config.secure_available());
			PortableServer::ServantBase_var refMapperServant = refMapper;

			PortableServer::ObjectId_var oid = admin_poa_->activate_object(refMapperServant.in());
			obj = admin_poa_->id_to_reference(oid.in());

			// refMapper->allow_insecure_access (obj.in());
		}
		catch (CORBA::Exception & ex) {
			ACE_DEBUG((LM_ERROR, ACE_TEXT("(%T) %N:%l - %s\n"), ex._info().c_str()));
			throw InitError();
		}

		ReferenceMapper_var refMapper_obj = ReferenceMapper::_narrow(obj.in());

		CORBA::String_var ior = 
			orb_->object_to_string(refMapper_obj.in());
		iorTable_->bind(Lorica::ReferenceMapper::IOR_TABLE_KEY,
				ior.in());

		this->ior_file_ = config.get_value("IOR_FILE", def_ior_file);

		FILE *output_file =
			ACE_OS::fopen (ACE_TEXT_CHAR_TO_TCHAR (this->ior_file_.c_str()), ACE_TEXT("w"));
		if (!output_file) {
			ACE_ERROR((LM_ERROR,
				   "(%T) %N:%l - cannot open output file for writing IOR: %s\n",
				   this->ior_file_.c_str()));
			throw InitError();
		}
		ACE_OS::fprintf(output_file, "%s", ior.in());
		ACE_OS::fclose(output_file);

		if (!setup_shutdown_handler()) {
			ACE_ERROR ((LM_ERROR,
				    "(%T) %N:%l - could not set up shutdown handler\n"));
			throw InitError();
		}

		// Initialize the mapper registry
		Lorica_MapperRegistry *mreg = 
			ACE_Dynamic_Service<Lorica_MapperRegistry>::instance
			(this->orb_->orb_core()->configuration(),"MapperRegistry");

		std::string ne_ids = config.null_eval_type_ids();
		if (!ne_ids.empty()) {
			if (Lorica_debug_level > 2) {
				ACE_DEBUG((LM_DEBUG,
					   ACE_TEXT("(%T) %N:%l - adding type ids for null ")
					   ACE_TEXT("evaluator: %s\n"),
					   ne_ids.c_str()));
			}

			size_t space = ne_ids.find(' ');
			size_t start = 0;
			while (space != std::string::npos) {
				mreg->add_null_mapper_type(ne_ids.substr(start,space - start));
				start = space+1;
				space = ne_ids.find(' ',start);
			}
			mreg->add_null_mapper_type(ne_ids.substr(start));
		} else if (config.null_eval_any()) {
			if (Lorica_debug_level > 2)
				ACE_DEBUG((LM_DEBUG,
					   ACE_TEXT("(%T) %N:%l - creating default null mapper\n")));
			mreg->create_default_null_mapper();
		}
		if (config.generic_evaluator()) {
			if (Lorica_debug_level > 0) {
				ACE_DEBUG((LM_DEBUG,
					   ACE_TEXT("(%T) %N:%l - loading generic evaluator\n")));
			}
#ifdef ACE_WIN32
			this->orb_->orb_core()->configuration()->process_directive
				(ACE_TEXT_ALWAYS_CHAR
				 (ACE_DYNAMIC_SERVICE_DIRECTIVE("Lorica_GenericLoader",
								"lorica_GenericEvaluator",
								"_make_Lorica_GenericLoader",
								"")
					 )
					);
#else
			Lorica::GenericMapper *gen_eval =
				new Lorica::GenericMapper(debug_, *mreg);
			mreg->add_proxy_mapper(gen_eval);
#endif
		}

		// add generic or other mappers...
		mreg->init_mappers(this->outside_pm_,
				   this->inside_pm_,
				   this->orb_,
				   config.secure_available());



		// last thing to do, put both POAs in the active state.
		outside_pm_->activate();
		inside_pm_->activate();

	}
	catch (CORBA::Exception & ex) {
		ACE_DEBUG((LM_ERROR, ACE_TEXT("(%T) %N:%l - %s\n"), ex._info().c_str()));
		throw InitError();
	}
	catch (...) {
		ACE_ERROR((LM_ERROR, "%N:%l - Caught an otherwise unknown exception\n"));
		throw InitError();
	}
}
Beispiel #14
0
int main( int argc, char **argv )
{
    char        **nargv;
    char        **sargv;
    FILE        *fin;
    int         fout;
    char        *helpstr[2];
    bool        f_swtch;

    f_swtch = FALSE;
    helpstr[0] = NULL;
    helpstr[1] = NULL;
    for( argc=1, sargv=nargv=argv+1; *sargv; ++sargv ) {
        if( ! _IsCmdSwitch( *sargv ) ) {
            *nargv++ = *sargv;
            argc++;
        } else {
            switch( (*sargv)[1] ) {
            case 'n':
                GenIndex = FALSE;
                if( f_swtch ) {
                    PrintError( "More than one format switch found in command line\n" );
                    Usage();
                }
                f_swtch = TRUE;
                break;
            case 'v':
                Verbose = TRUE;
            break;
            case 'c':
                if( (*sargv)[2] != '\0' ) {
                    MaxCol = atoi( &(*sargv)[2] );
                } else {
                    if( *++sargv == NULL )
                        Usage();
                    MaxCol = atoi( *sargv );
                }
                break;
            case 'r':
                if( (*sargv)[2] != '\0' ) {
                    MaxRow = atoi( &(*sargv)[2] );
                } else {
                    if( *++sargv == NULL )
                        Usage();
                    MaxRow = atoi( *sargv );
                }
                break;
            case 'h':
                if( (*sargv)[2] != '\0' ) {
                    Height = atoi( &(*sargv)[2] );
                } else {
                    if( *++sargv == NULL )
                        Usage();
                    Height = atoi( *sargv );
                }
                break;
            case 'w':
                if( (*sargv)[2] != '\0' ) {
                    Width = atoi( &(*sargv)[2] );
                } else {
                    if( *++sargv == NULL )
                        Usage();
                    Width = atoi( *sargv );
                }
                break;
            case 'f':
                if( f_swtch ) {
                    PrintError( "More than one format switch found in command line\n" );
                    Usage();
                }
                f_swtch = TRUE;
                if( (*sargv)[2] == '0' ) {
                    GenIndex = FALSE;
                } else if( (*sargv)[2] == '1' ) {
                    GenStrings = FALSE;
                } else if( (*sargv)[2] == '2' ) {
                    GenStrings = TRUE;
                } else {
                    Usage();
                }
                break;
            default:
                Usage();
            break;
            }
        }
    }

    if( argc > 1  &&  strcmp( argv[1], "?" ) == 0 ) {
        Usage();
    }

    if( argc != 3 ) {
        Usage();
    }

    InitError( argv[1] );
    fin = fopen( argv[1], "rt" );
    if( fin == NULL ) {
        PrintError( "Unable to open '%s' for input\n", argv[1] );
        return( -1 );
    }

    fout = open( argv[2], O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, PMODE_RW );
    if( fout == -1 ) {
        PrintError( "Unable to open '%s' for output\n", argv[2] );
        return( -1 );
    }

    pass1( fin, helpstr );
    pass2( fin, fout, helpstr );

    fclose( fin );
    close( fout );
    if( GenIndex ) {
        fout = open( argv[2], O_WRONLY | O_BINARY );
        WriteIndex( fout, helpstr, GenStrings );
        close( fout );
    }
    FiniError();
    HelpMemFree( helpstr[0] );
    HelpMemFree( helpstr[1] );
    return( 0 );
}
 void Transform(const TDataRegion& src, TBuffer& dest, const TXslParams& params) {
     InitError();
     TxmlDocHolder srcDoc(xmlParseMemory(~src, +src));
     Transform(srcDoc, dest, params);
 }
Beispiel #16
0
bool WalletInit::Verify() const
{
    if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
        return true;
    }

    if (gArgs.IsArgSet("-walletdir")) {
        fs::path wallet_dir = gArgs.GetArg("-walletdir", "");
        if (!fs::exists(wallet_dir)) {
            return InitError(strprintf(_("Specified -walletdir \"%s\" does not exist"), wallet_dir.string()));
        } else if (!fs::is_directory(wallet_dir)) {
            return InitError(strprintf(_("Specified -walletdir \"%s\" is not a directory"), wallet_dir.string()));
        } else if (!wallet_dir.is_absolute()) {
            return InitError(strprintf(_("Specified -walletdir \"%s\" is a relative path"), wallet_dir.string()));
        }
    }

    LogPrintf("Using wallet directory %s\n", GetWalletDir().string());

    uiInterface.InitMessage(_("Verifying wallet(s)..."));

    // Keep track of each wallet absolute path to detect duplicates.
    std::set<fs::path> wallet_paths;

    for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
        // Do some checking on wallet path. It should be either a:
        //
        // 1. Path where a directory can be created.
        // 2. Path to an existing directory.
        // 3. Path to a symlink to a directory.
        // 4. For backwards compatibility, the name of a data file in -walletdir.
        fs::path wallet_path = fs::absolute(walletFile, GetWalletDir());
        fs::file_type path_type = fs::symlink_status(wallet_path).type();
        if (!(path_type == fs::file_not_found || path_type == fs::directory_file ||
              (path_type == fs::symlink_file && fs::is_directory(wallet_path)) ||
              (path_type == fs::regular_file && fs::path(walletFile).filename() == walletFile))) {
            return InitError(strprintf(
                _("Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
                  "database/log.?????????? files can be stored, a location where such a directory could be created, "
                  "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)"),
                walletFile, GetWalletDir()));
        }

        if (!wallet_paths.insert(wallet_path).second) {
            return InitError(strprintf(_("Error loading wallet %s. Duplicate -wallet filename specified."), walletFile));
        }

        std::string strError;
        if (!WalletBatch::VerifyEnvironment(wallet_path, strError)) {
            return InitError(strError);
        }

        if (gArgs.GetBoolArg("-salvagewallet", false)) {
            // Recover readable keypairs:
            CWallet dummyWallet("dummy", WalletDatabase::CreateDummy());
            std::string backup_filename;
            if (!WalletBatch::Recover(wallet_path, (void *)&dummyWallet, WalletBatch::RecoverKeysOnlyFilter, backup_filename)) {
                return false;
            }
        }

        std::string strWarning;
        bool dbV = WalletBatch::VerifyDatabaseFile(wallet_path, strWarning, strError);
        if (!strWarning.empty()) {
            InitWarning(strWarning);
        }
        if (!dbV) {
            InitError(strError);
            return false;
        }
    }

    return true;
}
Beispiel #17
0
bool WalletInit::ParameterInteraction() const
{
    if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
        for (const std::string& wallet : gArgs.GetArgs("-wallet")) {
            LogPrintf("%s: parameter interaction: -disablewallet -> ignoring -wallet=%s\n", __func__, wallet);
        }

        return true;
    }

    gArgs.SoftSetArg("-wallet", "");
    const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;

    if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) {
        LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
    }

    if (gArgs.GetBoolArg("-salvagewallet", false)) {
        if (is_multiwallet) {
            return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
        }
        // Rewrite just private keys: rescan to find transactions
        if (gArgs.SoftSetBoolArg("-rescan", true)) {
            LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
        }
    }

    int zapwallettxes = gArgs.GetArg("-zapwallettxes", 0);
    // -zapwallettxes implies dropping the mempool on startup
    if (zapwallettxes != 0 && gArgs.SoftSetBoolArg("-persistmempool", false)) {
        LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -persistmempool=0\n", __func__, zapwallettxes);
    }

    // -zapwallettxes implies a rescan
    if (zapwallettxes != 0) {
        if (is_multiwallet) {
            return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
        }
        if (gArgs.SoftSetBoolArg("-rescan", true)) {
            LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -rescan=1\n", __func__, zapwallettxes);
        }
    }

    if (is_multiwallet) {
        if (gArgs.GetBoolArg("-upgradewallet", false)) {
            return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
        }
    }

    if (gArgs.GetBoolArg("-sysperms", false))
        return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
    if (gArgs.GetArg("-prune", 0) && gArgs.GetBoolArg("-rescan", false))
        return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));

    if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
        InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
                    _("The wallet will avoid paying less than the minimum relay fee."));

    if (gArgs.IsArgSet("-mintxfee"))
    {
        CAmount n = 0;
        if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n)
            return InitError(AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", "")));
        if (n > HIGH_TX_FEE_PER_KB)
            InitWarning(AmountHighWarn("-mintxfee") + " " +
                        _("This is the minimum transaction fee you pay on every transaction."));
        CWallet::minTxFee = CFeeRate(n);
    }

    g_wallet_allow_fallback_fee = Params().IsFallbackFeeEnabled();
    if (gArgs.IsArgSet("-fallbackfee"))
    {
        CAmount nFeePerK = 0;
        if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK))
            return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", "")));
        if (nFeePerK > HIGH_TX_FEE_PER_KB)
            InitWarning(AmountHighWarn("-fallbackfee") + " " +
                        _("This is the transaction fee you may pay when fee estimates are not available."));
        CWallet::fallbackFee = CFeeRate(nFeePerK);
        g_wallet_allow_fallback_fee = nFeePerK != 0; //disable fallback fee in case value was set to 0, enable if non-null value
    }
    if (gArgs.IsArgSet("-discardfee"))
    {
        CAmount nFeePerK = 0;
        if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK))
            return InitError(strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", "")));
        if (nFeePerK > HIGH_TX_FEE_PER_KB)
            InitWarning(AmountHighWarn("-discardfee") + " " +
                        _("This is the transaction fee you may discard if change is smaller than dust at this level"));
        CWallet::m_discard_rate = CFeeRate(nFeePerK);
    }
    if (gArgs.IsArgSet("-paytxfee"))
    {
        CAmount nFeePerK = 0;
        if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK))
            return InitError(AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", "")));
        if (nFeePerK > HIGH_TX_FEE_PER_KB)
            InitWarning(AmountHighWarn("-paytxfee") + " " +
                        _("This is the transaction fee you will pay if you send a transaction."));

        payTxFee = CFeeRate(nFeePerK, 1000);
        if (payTxFee < ::minRelayTxFee)
        {
            return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
                                       gArgs.GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
        }
    }
    if (gArgs.IsArgSet("-maxtxfee"))
    {
        CAmount nMaxFee = 0;
        if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee))
            return InitError(AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", "")));
        if (nMaxFee > HIGH_MAX_TX_FEE)
            InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
        maxTxFee = nMaxFee;
        if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
        {
            return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
                                       gArgs.GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
        }
    }
    nTxConfirmTarget = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
    bSpendZeroConfChange = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
    fWalletRbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);

    return true;
}
Beispiel #18
0
    void init()
    {
        LOG_AS("GLInfo");

        if (inited) return;

        if (!initializeOpenGLFunctions())
        {
            throw InitError("GLInfo::init", "Failed to initialize OpenGL");
        }

        // Extensions.
        ext.ARB_draw_instanced             = query("GL_ARB_draw_instanced");
        ext.ARB_instanced_arrays           = query("GL_ARB_instanced_arrays");
        ext.ARB_texture_env_combine        = query("GL_ARB_texture_env_combine") || query("GL_EXT_texture_env_combine");
        ext.ARB_texture_non_power_of_two   = query("GL_ARB_texture_non_power_of_two");

        ext.EXT_blend_subtract             = query("GL_EXT_blend_subtract");
        ext.EXT_framebuffer_blit           = query("GL_EXT_framebuffer_blit");
        ext.EXT_framebuffer_multisample    = query("GL_EXT_framebuffer_multisample");
        ext.EXT_framebuffer_object         = query("GL_EXT_framebuffer_object");
        ext.EXT_packed_depth_stencil       = query("GL_EXT_packed_depth_stencil");
        ext.EXT_texture_compression_s3tc   = query("GL_EXT_texture_compression_s3tc");
        ext.EXT_texture_filter_anisotropic = query("GL_EXT_texture_filter_anisotropic");
        ext.EXT_timer_query                = query("GL_EXT_timer_query");

        ext.ATI_texture_env_combine3       = query("GL_ATI_texture_env_combine3");
        ext.NV_framebuffer_multisample_coverage
                                           = query("GL_NV_framebuffer_multisample_coverage");
        ext.NV_texture_env_combine4        = query("GL_NV_texture_env_combine4");
        ext.SGIS_generate_mipmap           = query("GL_SGIS_generate_mipmap");

#ifdef WIN32
        ext.Windows_ARB_multisample        = query("WGL_ARB_multisample");
        ext.Windows_EXT_swap_control       = query("WGL_EXT_swap_control");

        if (ext.Windows_EXT_swap_control)
        {
            wglSwapIntervalEXT = de::function_cast<decltype(wglSwapIntervalEXT)>
                (QOpenGLContext::currentContext()->getProcAddress("wglSwapIntervalEXT"));
        }
#endif

#ifdef DENG_X11
        ext.X11_EXT_swap_control           = query("GLX_EXT_swap_control");
        ext.X11_SGI_swap_control           = query("GLX_SGI_swap_control");
        ext.X11_MESA_swap_control          = query("GLX_MESA_swap_control");

        if (ext.X11_EXT_swap_control)
        {
            glXSwapIntervalEXT = de::function_cast<decltype(glXSwapIntervalEXT)>
                    (glXGetProcAddress(reinterpret_cast<GLubyte const *>("glXSwapIntervalEXT")));
        }
        if (ext.X11_SGI_swap_control)
        {
            glXSwapIntervalSGI = de::function_cast<decltype(glXSwapIntervalSGI)>
                    (glXGetProcAddress(reinterpret_cast<GLubyte const *>("glXSwapIntervalSGI")));
        }
        if (ext.X11_MESA_swap_control)
        {
            glXSwapIntervalMESA = de::function_cast<decltype(glXSwapIntervalMESA)>
                    (glXGetProcAddress(reinterpret_cast<GLubyte const *>("glXSwapIntervalMESA")));
        }
#endif

        if (ext.ARB_draw_instanced)
        {
            ARB_draw_instanced.reset(new QOpenGLExtension_ARB_draw_instanced);
            ARB_draw_instanced->initializeOpenGLFunctions();
        }
        if (ext.ARB_instanced_arrays)
        {
            ARB_instanced_arrays.reset(new QOpenGLExtension_ARB_instanced_arrays);
            ARB_instanced_arrays->initializeOpenGLFunctions();
        }
        if (ext.EXT_framebuffer_blit)
        {
            EXT_framebuffer_blit.reset(new QOpenGLExtension_EXT_framebuffer_blit);
            EXT_framebuffer_blit->initializeOpenGLFunctions();
        }
        if (ext.EXT_framebuffer_multisample)
        {
            EXT_framebuffer_multisample.reset(new QOpenGLExtension_EXT_framebuffer_multisample);
            EXT_framebuffer_multisample->initializeOpenGLFunctions();
        }
        if (ext.EXT_framebuffer_object)
        {
            EXT_framebuffer_object.reset(new QOpenGLExtension_EXT_framebuffer_object);
            EXT_framebuffer_object->initializeOpenGLFunctions();
        }
        if (ext.NV_framebuffer_multisample_coverage)
        {
            NV_framebuffer_multisample_coverage.reset(new QOpenGLExtension_NV_framebuffer_multisample_coverage);
            NV_framebuffer_multisample_coverage->initializeOpenGLFunctions();
        }

        // Limits.
        glGetIntegerv(GL_MAX_TEXTURE_SIZE,  (GLint *) &lim.maxTexSize);
        glGetIntegerv(GL_MAX_TEXTURE_UNITS, (GLint *) &lim.maxTexUnits);

        if (ext.EXT_texture_filter_anisotropic)
        {
            glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, (GLint *) &lim.maxTexFilterAniso);
        }

        // Set a custom maximum size?
        if (CommandLine_CheckWith("-maxtex", 1))
        {
            lim.maxTexSize = min(ceilPow2(String(CommandLine_Next()).toInt()),
                                 lim.maxTexSize);

            LOG_GL_NOTE("Using requested maximum texture size of %i x %i") << lim.maxTexSize << lim.maxTexSize;
        }

        // Check default OpenGL format attributes.
        QOpenGLContext const *ctx = QOpenGLContext::currentContext();
        QSurfaceFormat form = ctx->format();

        LOGDEV_GL_MSG("Initial OpenGL format:");
        LOGDEV_GL_MSG(" - version: %i.%i") << form.majorVersion() << form.minorVersion();
        LOGDEV_GL_MSG(" - profile: %s") << (form.profile() == QSurfaceFormat::CompatibilityProfile? "Compatibility" : "Core");
        LOGDEV_GL_MSG(" - color: R%i G%i B%i A%i bits") << form.redBufferSize() << form.greenBufferSize() << form.blueBufferSize() << form.alphaBufferSize();
        LOGDEV_GL_MSG(" - depth: %i bits") << form.depthBufferSize();
        LOGDEV_GL_MSG(" - stencil: %i bits") << form.stencilBufferSize();
        LOGDEV_GL_MSG(" - samples: %i") << form.samples();
        LOGDEV_GL_MSG(" - swap behavior: %i") << form.swapBehavior();

        inited = true;
    }
Beispiel #19
0
bool WalletInit::ParameterInteraction() const
{
    if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
        for (const std::string& wallet : gArgs.GetArgs("-wallet")) {
            LogPrintf("%s: parameter interaction: -disablewallet -> ignoring -wallet=%s\n", __func__, wallet);
        }

        return true;
    }

    gArgs.SoftSetArg("-wallet", "");
    const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;

    if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) {
        LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
    }

    if (gArgs.GetBoolArg("-salvagewallet", false)) {
        if (is_multiwallet) {
            return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
        }
        // Rewrite just private keys: rescan to find transactions
        if (gArgs.SoftSetBoolArg("-rescan", true)) {
            LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
        }
    }

    bool zapwallettxes = gArgs.GetBoolArg("-zapwallettxes", false);
    // -zapwallettxes implies dropping the mempool on startup
    if (zapwallettxes && gArgs.SoftSetBoolArg("-persistmempool", false)) {
        LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -persistmempool=0\n", __func__);
    }

    // -zapwallettxes implies a rescan
    if (zapwallettxes) {
        if (is_multiwallet) {
            return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
        }
        if (gArgs.SoftSetBoolArg("-rescan", true)) {
            LogPrintf("%s: parameter interaction: -zapwallettxes enabled -> setting -rescan=1\n", __func__);
        }
    }

    if (is_multiwallet) {
        if (gArgs.GetBoolArg("-upgradewallet", false)) {
            return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
        }
    }

    if (gArgs.GetBoolArg("-sysperms", false))
        return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
    if (gArgs.GetArg("-prune", 0) && gArgs.GetBoolArg("-rescan", false))
        return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));

    if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
        InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
                    _("The wallet will avoid paying less than the minimum relay fee."));

    if (gArgs.IsArgSet("-maxtxfee"))
    {
        CAmount nMaxFee = 0;
        if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee))
            return InitError(AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", "")));
        if (nMaxFee > HIGH_MAX_TX_FEE)
            InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
        maxTxFee = nMaxFee;
        if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
        {
            return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
                                       gArgs.GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
        }
    }

    return true;
}
/** Initialize bitcoin.
 *  @pre Parameters should be parsed and config file should be read.
 */
bool AppInit2(boost::thread_group& threadGroup)
{
    // ********************************************************* Step 1: setup
#ifdef _MSC_VER
    // Turn off Microsoft heap dump noise
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
    // Disable confusing "helpful" text message on abort, Ctrl-C
    _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
    // Enable Data Execution Prevention (DEP)
    // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
    // A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
    typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
    PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
    if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
#endif
#ifndef WIN32
    umask(077);

    // Clean shutdown on SIGTERM
    struct sigaction sa;
    sa.sa_handler = HandleSIGTERM;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGINT, &sa, NULL);

    // Reopen debug.log on SIGHUP
    struct sigaction sa_hup;
    sa_hup.sa_handler = HandleSIGHUP;
    sigemptyset(&sa_hup.sa_mask);
    sa_hup.sa_flags = 0;
    sigaction(SIGHUP, &sa_hup, NULL);
#endif

    if (!CheckDiskSpace())
        return false;

    // ********************************************************* Step 2: parameter interactions

    nNodeLifespan = GetArg("-addrlifespan", 7);

    nMinStakeInterval = GetArg("-minstakeinterval", 0);
    nMinerSleep = GetArg("-minersleep", 500);

    // Largest block you're willing to create.
    // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
    nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
    nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));

    // How much of the block should be dedicated to high-priority transactions,
    // included regardless of the fees they pay
    nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
    nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);

    // Minimum block size you want to create; block will be filled with free transactions
    // until there are no more or the block reaches this size:
    nBlockMinSize = GetArg("-blockminsize", 0);
    nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);

    // Fee-per-kilobyte amount considered the same as "free"
    // Be careful setting this: if you set it to zero then
    // a transaction spammer can cheaply fill blocks using
    // 1-satoshi-fee transactions. It should be set above the real
    // cost to you of processing a transaction.
    if (mapArgs.count("-mintxfee"))
        ParseMoney(mapArgs["-mintxfee"], nMinTxFee);

    if (fDebug)
        LogPrintf("nMinerSleep %u\n", nMinerSleep);

    CheckpointsMode = Checkpoints::STRICT;
    std::string strCpMode = GetArg("-cppolicy", "strict");

    if (strCpMode == "strict")
        CheckpointsMode = Checkpoints::STRICT;

    if (strCpMode == "advisory")
        CheckpointsMode = Checkpoints::ADVISORY;

    if (strCpMode == "permissive")
        CheckpointsMode = Checkpoints::PERMISSIVE;

    nDerivationMethodIndex = 0;

    fTestNet = GetBoolArg("-testnet");
    
    if (!SelectParamsFromCommandLine())
        return InitError("Invalid combination of -testnet and -regtest.");
    
    if (GetBoolArg("-thinmode"))
        nNodeMode = NT_THIN;
    
    if (fTestNet)
    {
        SoftSetBoolArg("-irc", true);
    }

    if (mapArgs.count("-bind"))
    {
        // when specifying an explicit binding address, you want to listen on it
        // even when -connect or -proxy is specified
        SoftSetBoolArg("-listen", true);
    }

    if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
    {
        // when only connecting to trusted nodes, do not seed via DNS, or listen by default
        SoftSetBoolArg("-dnsseed", false);
        SoftSetBoolArg("-listen", false);
    }

    if (mapArgs.count("-proxy"))
    {
        // to protect privacy, do not listen by default if a proxy server is specified
        SoftSetBoolArg("-listen", false);
    }

    if (!GetBoolArg("-listen", true))
    {
        // do not map ports or try to retrieve public IP when not listening (pointless)
        SoftSetBoolArg("-upnp", false);
        SoftSetBoolArg("-discover", false);
    }

    if (mapArgs.count("-externalip"))
    {
        // if an explicit public IP is specified, do not try to find others
        SoftSetBoolArg("-discover", false);
    }

    if (GetBoolArg("-salvagewallet"))
    {
        // Rewrite just private keys: rescan to find transactions
        SoftSetBoolArg("-rescan", true);
    }

    if (fTestNet)
    {
        nStakeMinAge = 1 * 60 * 60; // test net min age is 1 hour
        nCoinbaseMaturity = 10; // test maturity is 10 blocks
    };

    // ********************************************************* Step 3: parameter-to-internal-flags
    
    fDebug = !mapMultiArgs["-debug"].empty();
    // Special-case: if -debug=0/-nodebug is set, turn off debugging messages
    const std::vector<std::string>& categories = mapMultiArgs["-debug"];
    if (GetBoolArg("-nodebug", false) || std::find(categories.begin(), categories.end(), std::string("0")) != categories.end())
        fDebug = false;
    
    // -debug implies fDebug*, unless otherwise specified
    if (fDebug)
    {
        SoftSetBoolArg("-debugnet", true);
        SoftSetBoolArg("-debugsmsg", true);
        SoftSetBoolArg("-debugchain", true);
        SoftSetBoolArg("-debugringsig", true);
    };

    fDebugNet = GetBoolArg("-debugnet");
    fDebugSmsg = GetBoolArg("-debugsmsg");
    fDebugChain = GetBoolArg("-debugchain");
    fDebugRingSig = GetBoolArg("-debugringsig");
    fDebugPoS = GetBoolArg("-debugpos");

    fNoSmsg = GetBoolArg("-nosmsg");
    
    // Check for -socks - as this is a privacy risk to continue, exit here
    if (mapArgs.count("-socks"))
        return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));

    bitdb.SetDetach(GetBoolArg("-detachdb", false));
    if (fDaemon)
        fServer = true;
    else
        fServer = GetBoolArg("-server", false);

    /* force fServer when running without GUI */
    if (!fHaveGUI)
        fServer = true;

    fPrintToConsole = GetBoolArg("-printtoconsole");
    fPrintToDebugLog = SoftSetBoolArg("-printtodebuglog", true);
    fLogTimestamps = GetBoolArg("-logtimestamps");

    if (mapArgs.count("-timeout"))
    {
        int nNewTimeout = GetArg("-timeout", 5000);
        if (nNewTimeout > 0 && nNewTimeout < 600000)
            nConnectTimeout = nNewTimeout;
    };

    if (mapArgs.count("-paytxfee"))
    {
        if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
            return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
        if (nTransactionFee > 0.25 * COIN)
            InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
    };

    fConfChange = GetBoolArg("-confchange", false);
    fEnforceCanonical = GetBoolArg("-enforcecanonical", true);

    if (mapArgs.count("-mininput"))
    {
        if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
            return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
    };


    // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
    // Sanity check
    if (!InitSanityCheck())
        return InitError(_("Initialization sanity check failed. PerfectCoin is shutting down."));

    
    std::string strDataDir = GetDataDir().string();
    std::string strWalletFileName = GetArg("-wallet", "wallet.dat");

    // strWalletFileName must be a plain filename without a directory
    if (strWalletFileName != fs::basename(strWalletFileName) + fs::extension(strWalletFileName))
        return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str()));

    // Make sure only a single Bitcoin process is using the data directory.
    fs::path pathLockFile = GetDataDir() / ".lock";
    FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
    if (file)
        fclose(file);

    static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
    if (!lock.try_lock())
        return InitError(strprintf(_("Cannot obtain a lock on data directory %s.  PerfectCoin is probably already running."), strDataDir.c_str()));
    
    if (GetBoolArg("-shrinkdebugfile", !fDebug))
        ShrinkDebugFile();

    LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    LogPrintf("PerfectCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
    LogPrintf("Operating in %s mode.\n", GetNodeModeName(nNodeMode));
    LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));

    if (!fLogTimestamps)
        LogPrintf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());

    LogPrintf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
    LogPrintf("Used data directory %s\n", strDataDir.c_str());

    std::ostringstream strErrors;

    if (fDaemon)
    {
        fprintf(stdout, "PerfectCoin server starting\n");
        fflush(stdout);
    };
    
    int64_t nStart;



    /* *********************************************************
        Step 4.5: adjust parameters for nNodeMode
    ********************************************************* */

    switch (nNodeMode)
    {
        case NT_FULL:
            if (GetBoolArg("-nothinssupport"))
            {
                LogPrintf("Thin support disabled.\n");
                nLocalServices &= ~(THIN_SUPPORT);
            };

            if (GetBoolArg("-nothinstealth"))
            {
                LogPrintf("Thin stealth support disabled.\n");
                nLocalServices &= ~(THIN_STEALTH);
            };
            break;
        case NT_THIN:
            SetBoolArg("-staking", false);

            // -- clear services
            nLocalServices &= ~(NODE_NETWORK);
            nLocalServices &= ~(THIN_SUPPORT);
            nLocalServices &= ~(THIN_STAKE);
            nLocalServices &= ~(THIN_STEALTH);

            nLocalRequirements |= (THIN_SUPPORT);

            if (GetBoolArg("-thinfullindex"))
            {
                LogPrintf("Thin full index enabled.\n");
                fThinFullIndex = true;
            } else
            {
                nThinIndexWindow = GetArg("-thinindexmax", 4096);

                if (nThinIndexWindow < 4096)
                {
                    LogPrintf("Thin index window minimum size is %d.\n", 4096);
                    nThinIndexWindow = 4096;
                };

                LogPrintf("Thin index window size %d.\n", nThinIndexWindow);
            };

            if (GetBoolArg("-nothinstealth"))
            {
                LogPrintf("Thin stealth disabled.\n");
            } else
            {
                nLocalRequirements |= (THIN_STEALTH);
            };

            break;
        default:
            break;
    };

    // -- thin and full
    if (fNoSmsg)
        nLocalServices &= ~(SMSG_RELAY);

    if (initialiseRingSigs() != 0)
        return InitError("initialiseRingSigs() failed.");

    // ********************************************************* Step 5: verify database integrity

    uiInterface.InitMessage(_("Verifying database integrity..."));

    if (!bitdb.Open(GetDataDir()))
    {
        std::string msg = strprintf(_("Error initializing database environment %s!"
            " To recover, BACKUP THAT DIRECTORY, then remove"
            " everything from it except for wallet.dat."), strDataDir.c_str());
        return InitError(msg);
    };

    if (GetBoolArg("-salvagewallet"))
    {
        // Recover readable keypairs:
        if (!CWalletDB::Recover(bitdb, strWalletFileName, true))
            return false;
    };

    if (fs::exists(GetDataDir() / strWalletFileName))
    {
        CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover);
        if (r == CDBEnv::RECOVER_OK)
        {
            std::string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
                " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
                " your balance or transactions are incorrect you should"
                " restore from a backup."), strDataDir.c_str());
            uiInterface.ThreadSafeMessageBox(msg, _("PerfectCoin"), CClientUIInterface::BTN_OK | CClientUIInterface::ICON_WARNING | CClientUIInterface::MODAL);
        };

        if (r == CDBEnv::RECOVER_FAIL)
            return InitError(_("wallet.dat corrupt, salvage failed"));
    };

    // ********************************************************* Step 6: network initialization

    nMaxThinPeers = GetArg("-maxthinpeers", 8);

    nBloomFilterElements = GetArg("-bloomfilterelements", 1536);

    if (mapArgs.count("-onlynet"))
    {
        std::set<enum Network> nets;
        BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"])
        {
            enum Network net = ParseNetwork(snet);
            if (net == NET_UNROUTABLE)
                return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
            nets.insert(net);
        };
        for (int n = 0; n < NET_MAX; n++)
        {
            enum Network net = (enum Network)n;
            if (!nets.count(net))
                SetLimited(net);
        };
    };
Beispiel #21
0
bool VerifyWallets()
{
    if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
        return true;
    }

    if (gArgs.IsArgSet("-walletdir")) {
        fs::path wallet_dir = gArgs.GetArg("-walletdir", "");
        if (!fs::exists(wallet_dir)) {
            return InitError(strprintf(_("Specified -walletdir \"%s\" does not exist"), wallet_dir.string()));
        } else if (!fs::is_directory(wallet_dir)) {
            return InitError(strprintf(_("Specified -walletdir \"%s\" is not a directory"), wallet_dir.string()));
        } else if (!wallet_dir.is_absolute()) {
            return InitError(strprintf(_("Specified -walletdir \"%s\" is a relative path"), wallet_dir.string()));
        }
    }

    LogPrintf("Using wallet directory %s\n", GetWalletDir().string());

    uiInterface.InitMessage(_("Verifying wallet(s)..."));

    // Keep track of each wallet absolute path to detect duplicates.
    std::set<fs::path> wallet_paths;

    for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
        if (boost::filesystem::path(walletFile).filename() != walletFile) {
            return InitError(strprintf(_("Error loading wallet %s. -wallet parameter must only specify a filename (not a path)."), walletFile));
        }

        if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
            return InitError(strprintf(_("Error loading wallet %s. Invalid characters in -wallet filename."), walletFile));
        }

        fs::path wallet_path = fs::absolute(walletFile, GetWalletDir());

        if (fs::exists(wallet_path) && (!fs::is_regular_file(wallet_path) || fs::is_symlink(wallet_path))) {
            return InitError(strprintf(_("Error loading wallet %s. -wallet filename must be a regular file."), walletFile));
        }

        if (!wallet_paths.insert(wallet_path).second) {
            return InitError(strprintf(_("Error loading wallet %s. Duplicate -wallet filename specified."), walletFile));
        }

        std::string strError;
        if (!CWalletDB::VerifyEnvironment(walletFile, GetWalletDir().string(), strError)) {
            return InitError(strError);
        }

        if (gArgs.GetBoolArg("-salvagewallet", false)) {
            // Recover readable keypairs:
            CWallet dummyWallet;
            std::string backup_filename;
            if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter, backup_filename)) {
                return false;
            }
        }

        std::string strWarning;
        bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetWalletDir().string(), strWarning, strError);
        if (!strWarning.empty()) {
            InitWarning(strWarning);
        }
        if (!dbV) {
            InitError(strError);
            return false;
        }
    }

    return true;
}
Beispiel #22
0
////////////////////////////////////////////////////////////////////////////////
//	O p e n U S B D e v i c e
////////////////////////////////////////////////////////////////////////////////
HANDLE OpenUSBDevice( LPCSTR lpMfg, LPCSTR lpPdt, USB_ERROR_INFO *lpUsbErrorInfo )
{	
	int									ii;
	DWORD								dwBytes;
	BOOL								bFoundMfg;
	BOOL								bFoundPdt;
	LPTSTR								lpToken, lpWorkToken;
	int									nDeviceIndex;
	HDEVINFO							hDevInfo;
	HANDLE								hUsbPrinter;
	char								szUsb1284[1024];
	GUID								guidUSBDeviceSupport;
	SP_DEVICE_INTERFACE_DATA			deviceInterfaceData;
	PSP_DEVICE_INTERFACE_DETAIL_DATA	deviceInterfaceDetailData;
	HINSTANCE							pSetupAPI					= NULL;

	FAR HDEVINFO ( FAR WINAPI *SetupDiGetClassDevs )(CONST GUID *, PCTSTR, HWND, DWORD);
	FAR BOOL ( FAR WINAPI *SetupDiEnumDeviceInterfaces )(HDEVINFO, PSP_DEVINFO_DATA, CONST GUID *,DWORD, PSP_DEVICE_INTERFACE_DATA);
	FAR BOOL ( FAR WINAPI *SetupDiGetDeviceInterfaceDetail )(HDEVINFO, PSP_DEVICE_INTERFACE_DATA, PSP_DEVICE_INTERFACE_DETAIL_DATA, DWORD, PDWORD, PSP_DEVINFO_DATA);
	FAR BOOL ( FAR WINAPI *SetupDiDestroyDeviceInfoList )(HDEVINFO);



	//
	// The functions SetupDiGetClassDevs, SetupDiEnumDeviceInterfaces , 
	// SetupDiGetDeviceInterfaceDetail, SetupDiDestroyDeviceInfoList
	// are supported only on Windows 2000 and above and Windows 98 and above.
	// So link them dynamically to avoid windows errors.
	//
	pSetupAPI = LoadLibrary( "Setupapi" );

	if ( pSetupAPI != NULL )
	{

		SetupDiGetClassDevs = ( HDEVINFO ( WINAPI * )(CONST GUID *, PCTSTR, HWND, DWORD)) GetProcAddress( pSetupAPI, "SetupDiGetClassDevsA" );

		if ( SetupDiGetClassDevs == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiGetClassDevs");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiEnumDeviceInterfaces = ( BOOL ( WINAPI * )(HDEVINFO, PSP_DEVINFO_DATA, CONST GUID *,DWORD, PSP_DEVICE_INTERFACE_DATA)) GetProcAddress( pSetupAPI, "SetupDiEnumDeviceInterfaces" );

		if ( SetupDiEnumDeviceInterfaces == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiEnumDeviceInterfaces");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiGetDeviceInterfaceDetail = ( BOOL ( WINAPI * )(HDEVINFO, PSP_DEVICE_INTERFACE_DATA, PSP_DEVICE_INTERFACE_DETAIL_DATA, DWORD, PDWORD, PSP_DEVINFO_DATA)) GetProcAddress( pSetupAPI, "SetupDiGetDeviceInterfaceDetailA" );

		if ( SetupDiGetDeviceInterfaceDetail == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiGetDeviceInterfaceDetailA");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiDestroyDeviceInfoList = ( BOOL ( WINAPI * )(HDEVINFO)) GetProcAddress( pSetupAPI, "SetupDiDestroyDeviceInfoList" );

		if ( SetupDiDestroyDeviceInfoList == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiDestroyDeviceInfoList");
		    FreeLibrary( pSetupAPI );
			return 0;
		}
	}
	else
	{
		lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_HANDLE;
		strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to load Setupapi!");
		return 0;
	}


	//
	// get a handle to the set of device information returned by the Win32 API
	// functions.  This handle points to an object that is then operated on 
	// by the SetupDiEnumDeviceInterfaces function.
	//
	InitError( lpUsbErrorInfo );
	guidUSBDeviceSupport = GUID_CLASS_USB_DEVICE;
	hDevInfo = SetupDiGetClassDevs(	&guidUSBDeviceSupport,
									NULL,
									NULL,
									0x12 );	// TODO : Determine the constant
	if ( INVALID_HANDLE_VALUE == hDevInfo )
	{
		if ( NULL != lpUsbErrorInfo )
		{
			// get the last error from system
			lpUsbErrorInfo->dwSysLastError = GetLastError();

			// get the system defined message
			FormatMessage(	FORMAT_MESSAGE_FROM_SYSTEM			|
								FORMAT_MESSAGE_IGNORE_INSERTS,
							NULL,
							lpUsbErrorInfo->dwSysLastError,
							MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
							lpUsbErrorInfo->szSysErrorMsg,
							sizeof(lpUsbErrorInfo->szSysErrorMsg) / sizeof(lpUsbErrorInfo->szSysErrorMsg[0]),
							NULL );
		}
	}


	//
	//
	//	
	nDeviceIndex = 0;
	bFoundMfg = bFoundPdt = FALSE;
	hUsbPrinter = INVALID_HANDLE_VALUE;
	deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
	for ( nDeviceIndex = 0; SetupDiEnumDeviceInterfaces(	hDevInfo,
											NULL,
											&guidUSBDeviceSupport,
											nDeviceIndex,
											&deviceInterfaceData ); 
		nDeviceIndex++ ) 
	{




		//
		// determine the amout of memory we need to allocate for the next
		// call to this function
		//
		dwBytes= 0;
		ii = SetupDiGetDeviceInterfaceDetail(	hDevInfo,
												&deviceInterfaceData,
												NULL,
												0,
												&dwBytes,
												NULL );
		if ( 0 == dwBytes )
		{
			//
			// Reinitialize the data for next pass
			// through this loop.
			//
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}


		
		deviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(dwBytes);
		deviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);


		//
		// get the device path for the current device we are enumerating over.
		//
		ii = SetupDiGetDeviceInterfaceDetail(	hDevInfo,
												&deviceInterfaceData,
												deviceInterfaceDetailData,
												dwBytes,
												&dwBytes,
												NULL );
		if ( 0 == ii )
		{
			//
			// Free DetailData struct and reinitialize the data for next pass
			//through this loop.
			//
			free(deviceInterfaceDetailData);
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}


		//
		// get handle to the device so that we can 
		//
		hUsbPrinter = CreateFile(	deviceInterfaceDetailData->DevicePath,
									GENERIC_READ		| 
										GENERIC_WRITE,
									FILE_SHARE_WRITE	|
										FILE_SHARE_READ,
									NULL,
									OPEN_EXISTING,
									0,
									NULL );


		//
		//
		//
		if ( INVALID_HANDLE_VALUE == hUsbPrinter )
		{
			//
			// Free DetailData struct and reinitialize the data for next pass
			// through this loop.
			//
			free(deviceInterfaceDetailData);
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}



		//
		//
		//
		dwBytes = 0;
		memset( szUsb1284, 0, sizeof(szUsb1284) );
		ii = DeviceIoControl(	hUsbPrinter,
								IOCTL_USBPRINT_GET_1284_ID,
								NULL,
								0,
								szUsb1284,
								sizeof(szUsb1284),
								&dwBytes,
								NULL );

		//
		// parse the PNP string returned from the device.
		//		
		lpToken = strtok( szUsb1284, PNP_DELIMITOR );
		while ( NULL != lpToken )
		{
			// have the manfacturer.
			lpWorkToken = strstr(lpToken,MFG_TOKEN);
			if ( lpWorkToken != NULL )
			{
				RTrim(lpWorkToken);
				if ( strcmp( lpMfg, lpWorkToken + MFG_TOKEN_LEN ) == 0 )
					bFoundMfg = TRUE;
			}

			//	model of the printer
			lpWorkToken = strstr(lpToken,MDL_TOKEN);
			if ( lpWorkToken != NULL )
			{
				RTrim(lpWorkToken);
				if ( strcmp( lpPdt, lpWorkToken + MDL_TOKEN_LEN ) == 0 )
					bFoundPdt = TRUE;
			}

			// next token
			lpToken = strtok( NULL, PNP_DELIMITOR );
		}


	
		//
		//
		//
		if ( bFoundMfg && bFoundPdt )
		{
	        free(deviceInterfaceDetailData);
			break;
		}
	

		//
		//
		//
		CloseHandle( hUsbPrinter );
		hUsbPrinter = INVALID_HANDLE_VALUE;


		
		//
		// Free DetailData struct and reinitialize the data for next pass
		// through this loop.
		//
		free(deviceInterfaceDetailData);
		deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);

	}

	//
	//Destroy device information set and free all associated memory. 
	//
	SetupDiDestroyDeviceInfoList(hDevInfo);

	//
	//Free setupapi library
	//
    FreeLibrary( pSetupAPI );

	//
	//
	//
	return hUsbPrinter;
}
Beispiel #23
0
////////////////////////////////////////////////////////////////////////////////
//	G e t U S B D e v i c e s
////////////////////////////////////////////////////////////////////////////////
INT GetUSBDevices( INT nMaxDevices, USB_DEVICE_NAME *lpUsbDevices, USB_ERROR_INFO *lpUsbErrorInfo )
{
	int									ii;
	DWORD								dwBytes;
	INT									nDeviceFound;
	HDEVINFO							hDevInfo;
	LPTSTR								lpToken, lpWorkToken;
	GUID								guidUSBDeviceSupport;
	HANDLE								hUsbPrinter;
	SP_DEVICE_INTERFACE_DATA			deviceInterfaceData;
	PSP_DEVICE_INTERFACE_DETAIL_DATA	deviceInterfaceDetailData;
	char								szUsb1284[1024];
	int									nDeviceIndex;
	HINSTANCE							pSetupAPI					= NULL;

	FAR HDEVINFO ( FAR WINAPI *SetupDiGetClassDevs )(CONST GUID *, PCTSTR, HWND, DWORD);
	FAR BOOL ( FAR WINAPI *SetupDiEnumDeviceInterfaces )(HDEVINFO, PSP_DEVINFO_DATA, CONST GUID *,DWORD, PSP_DEVICE_INTERFACE_DATA);
	FAR BOOL ( FAR WINAPI *SetupDiGetDeviceInterfaceDetail )(HDEVINFO, PSP_DEVICE_INTERFACE_DATA, PSP_DEVICE_INTERFACE_DETAIL_DATA, DWORD, PDWORD, PSP_DEVINFO_DATA);
	FAR BOOL ( FAR WINAPI *SetupDiDestroyDeviceInfoList )(HDEVINFO);



	//
	// The functions SetupDiGetClassDevs, SetupDiEnumDeviceInterfaces , 
	// SetupDiGetDeviceInterfaceDetail, SetupDiDestroyDeviceInfoList
	// are supported only on Windows 2000 and above and Windows 98 and above.
	// So link them dynamically to avoid windows errors.
	//
	pSetupAPI = LoadLibrary( "Setupapi" );

	if ( pSetupAPI != NULL )
	{

		SetupDiGetClassDevs = ( HDEVINFO ( WINAPI * )(CONST GUID *, PCTSTR, HWND, DWORD)) GetProcAddress( pSetupAPI, "SetupDiGetClassDevsA" );

		if ( SetupDiGetClassDevs == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiGetClassDevs");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiEnumDeviceInterfaces = ( BOOL ( WINAPI * )(HDEVINFO, PSP_DEVINFO_DATA, CONST GUID *,DWORD, PSP_DEVICE_INTERFACE_DATA)) GetProcAddress( pSetupAPI, "SetupDiEnumDeviceInterfaces" );

		if ( SetupDiEnumDeviceInterfaces == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiEnumDeviceInterfaces");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiGetDeviceInterfaceDetail = ( BOOL ( WINAPI * )(HDEVINFO, PSP_DEVICE_INTERFACE_DATA, PSP_DEVICE_INTERFACE_DETAIL_DATA, DWORD, PDWORD, PSP_DEVINFO_DATA)) GetProcAddress( pSetupAPI, "SetupDiGetDeviceInterfaceDetailA" );

		if ( SetupDiGetDeviceInterfaceDetail == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiGetDeviceInterfaceDetailA");
		    FreeLibrary( pSetupAPI );
			return 0;
		}

		SetupDiDestroyDeviceInfoList = ( BOOL ( WINAPI * )(HDEVINFO)) GetProcAddress( pSetupAPI, "SetupDiDestroyDeviceInfoList" );

		if ( SetupDiDestroyDeviceInfoList == NULL )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_FUNCTION;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to get a pointer to SetupDiDestroyDeviceInfoList");
		    FreeLibrary( pSetupAPI );
			return 0;
		}
	}
	else
	{
		lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_HANDLE;
		strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : Unable to load Setupapi!");
		return 0;
	}



	//
	// initialize local variables and initialize error
	// struct if a non NULL pointer was passed.
	// 
	nDeviceFound = 0;
	if ( NULL != lpUsbErrorInfo )
		InitError( lpUsbErrorInfo );


	//
	// validate that the user passed in the number of
	// available USE_DEVICE_NAMES to fill with inofrmation.
	//
	if ( 0 == nMaxDevices )
	{	
		if ( NULL != lpUsbErrorInfo )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_DATA;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : nMaxDevices has a value of zero!");
		}
		return 0;
	};

	
	
	//
	// check that we can pass information back to the calling application!
	//
	if ( NULL == lpUsbDevices )
	{
		if ( NULL != lpUsbErrorInfo )
		{
			lpUsbErrorInfo->dwSysLastError = ERROR_INVALID_DATA;
			strcpy( lpUsbErrorInfo->szSysErrorMsg, "ERROR : lpUsbDevices is NULL!" );
		}
		return 0;
	}



	//
	// get a handle to the set of device information returned by the Win32 API
	// functions.  This handle points to an object that is then operated on 
	// by the SetupDiEnumDeviceInterfaces function.
	//
	guidUSBDeviceSupport = GUID_CLASS_USB_DEVICE;
	hDevInfo = SetupDiGetClassDevs(	&guidUSBDeviceSupport,
									0,
									0,
									0x12);	// TODO : Determine the constant
	if ( INVALID_HANDLE_VALUE == hDevInfo )
	{
		if ( NULL != lpUsbErrorInfo )
		{
			// get the last error from system
			lpUsbErrorInfo->dwSysLastError = GetLastError();

			// get the system defined message
			FormatMessage(	FORMAT_MESSAGE_FROM_SYSTEM			|
							FORMAT_MESSAGE_IGNORE_INSERTS,
							NULL,
							lpUsbErrorInfo->dwSysLastError,
							MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
							lpUsbErrorInfo->szSysErrorMsg,
							sizeof(lpUsbErrorInfo->szSysErrorMsg) / sizeof(lpUsbErrorInfo->szSysErrorMsg[0]),
							NULL );
		}
	}


	//
	//
	//
	nDeviceFound = nDeviceIndex = 0;	
	deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
	for (nDeviceIndex = 0; SetupDiEnumDeviceInterfaces( hDevInfo,
									  NULL,
									  &guidUSBDeviceSupport,
									  nDeviceIndex,
									  &deviceInterfaceData );
		nDeviceIndex++) 
	{



		//
		// determine the amout of memory we need to allocate for the next
		// call to this function
		//
		dwBytes= 0;
		ii = SetupDiGetDeviceInterfaceDetail(	hDevInfo,
												&deviceInterfaceData,
												NULL,
												0,
												&dwBytes,
												NULL );
		if ( 0 == dwBytes )
		{
			//
			// Reinitialize the data for next pass
			// through this loop.
			//
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}


		
		//Set cbSize in the detailData structure.
		deviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc (dwBytes);
		deviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

			
		//
		// get the device path for the current device we are enumerating over.
		//
		ii = SetupDiGetDeviceInterfaceDetail(	hDevInfo,
												&deviceInterfaceData,
												deviceInterfaceDetailData,
												dwBytes, 
												&dwBytes,
												NULL );
		if ( 0 == ii )
		{
			//
			// Free DetailData struct and reinitialize the data for next pass
			//	through this loop.
			//
			free(deviceInterfaceDetailData);
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}


		//
		// get handle to the device so that we can 
		//
		hUsbPrinter = CreateFile(	deviceInterfaceDetailData->DevicePath,
									GENERIC_READ		| 
										GENERIC_WRITE,
									FILE_SHARE_WRITE	|
										FILE_SHARE_READ,
									NULL,
									OPEN_EXISTING,
									0,
									NULL );


		//
		//
		//
		if ( INVALID_HANDLE_VALUE == hUsbPrinter )
		{
			//
			// Free DetailData struct and reinitialize the data for next pass
			// through this loop.
			//
			free(deviceInterfaceDetailData);
			deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);
			continue;
		}



		//
		//
		//
		dwBytes = 0;
		memset( szUsb1284, 0, sizeof(szUsb1284) );
		ii = DeviceIoControl(	hUsbPrinter,
								IOCTL_USBPRINT_GET_1284_ID,
								NULL,
								0,
								szUsb1284,
								sizeof(szUsb1284),
								&dwBytes,
								NULL );

		//
		//
		//
		CloseHandle( hUsbPrinter );



		//
		// parse the PNP string returned from the device.
		//		
		lpToken = strtok( szUsb1284, PNP_DELIMITOR );
		while ( NULL != lpToken )
		{
			// have the manfacturer.
			lpWorkToken = strstr(lpToken, MFG_TOKEN);
			if (lpWorkToken != NULL)
			{
				strcpy(	lpUsbDevices[nDeviceFound].szDeviceMfg, lpWorkToken + MFG_TOKEN_LEN);
				RTrim( lpUsbDevices[nDeviceFound].szDeviceMfg );
			}

			//	model of the printer
			lpWorkToken = strstr(lpToken, MDL_TOKEN);
			if (lpWorkToken != NULL)
			{
				strcpy(	lpUsbDevices[nDeviceFound].szDevicePdt, lpWorkToken + MDL_TOKEN_LEN );
				RTrim( lpUsbDevices[nDeviceFound].szDevicePdt );
			}


			// next token
			lpToken = strtok( NULL, PNP_DELIMITOR );
		}



		//
		//  if the we don't manage to get BOTH the manufacturer and the product
		// of the USB printer then don't return information back the calling code.
		//
		if (	strlen(lpUsbDevices[nDeviceFound].szDeviceMfg) + 
				strlen(lpUsbDevices[nDeviceFound].szDevicePdt) > 1 )
		{
			nDeviceFound++;
			
			//break after getting the number of devices requested.
			if (nMaxDevices == nDeviceFound)
			{
		        free(deviceInterfaceDetailData);
				break;

			}

		}
		else
		{
			lpUsbDevices[nDeviceFound].szDeviceMfg[0] = 
			lpUsbDevices[nDeviceFound].szDevicePdt[0] = 0;
		}



		//
		// Free DetailData struct and reinitialize the data for next pass
		// through this loop.
		//
        free(deviceInterfaceDetailData);
		deviceInterfaceData.cbSize = sizeof(deviceInterfaceData);

	}

	//
	//Destroy device information set and free all associated memory. 
	//
	SetupDiDestroyDeviceInfoList(hDevInfo);

	//
	//Free setupapi library
	//
    FreeLibrary( pSetupAPI );

	return nDeviceFound;

}
Beispiel #24
0
//================================================================================================
//--------------------------------------------------+++--> The Main Application "Window" Procedure:
LRESULT CALLBACK WndProc(HWND hwnd,	UINT message, WPARAM wParam, LPARAM lParam)   //--------+++-->
{
	switch(message) {
	case WM_CREATE:
		InitAlarm();  // initialize alarms
		SetTimer(hwnd, IDTIMER_MAIN, 1000, NULL);
		InjectClockHook(hwnd);
		return 0;
		
	case WM_TIMER:
		if(wParam == IDTIMER_MAIN) OnTimerMain(hwnd);
		else if(wParam == IDTIMER_MOUSE) OnTimerMouse(hwnd);
		return 0;
		
	case WM_ENDSESSION:
		if(!wParam)
			break;
		/* fall through */
	case WM_DESTROY:
		KillTimer(hwnd, IDTIMER_MAIN);
		if(g_hwndSheet && IsWindow(g_hwndSheet))
			SendMessage(g_hwndSheet, WM_CLOSE, 0, 0);
		if(g_hDlgTimer && IsWindow(g_hDlgTimer))
			SendMessage(g_hDlgTimer, WM_CLOSE, 0, 0);
		if(g_hDlgStopWatch && IsWindow(g_hDlgStopWatch))
			SendMessage(g_hDlgStopWatch, WM_CLOSE, 0, 0);
		g_hwndSheet = g_hDlgTimer = g_hDlgStopWatch = NULL;
		EndAlarm();
		EndAllTimers();
		api.Exit(); // exit clock, remove injection
		if(message!=WM_ENDSESSION)
			PostQuitMessage(0);
		return 0;
	case WM_PAINT: {
//			HDC hdc;
//			PAINTSTRUCT ps;
//			hdc = BeginPaint(hwnd, &ps);
//			EndPaint(hwnd, &ps);
			return 0;}
	case WM_HOTKEY: // Feature Requested From eweoma at DonationCoder.com
		switch(wParam) { // And a Damn Fine Request it Was... :-)
		case HOT_WATCH:
			PostMessage(hwnd, WM_COMMAND, IDM_TIMEWATCH, 0);
			return 0;
			
		case HOT_TIMER:
			PostMessage(hwnd, WM_COMMAND, IDM_TIMER, 0);
			return 0;
			
		case HOT_STOPW:
			PostMessage(hwnd, WM_COMMAND, IDM_STOPWATCH, 0);
			return 0;
			
		case HOT_PROPR:
			PostMessage(hwnd, WM_COMMAND, IDM_SHOWPROP, 0);
			return 0;
			
		case HOT_CALEN:
			PostMessage(hwnd, WM_COMMAND, IDM_SHOWCALENDER, 0);
			return 0;
			
		case HOT_TSYNC:
			SyncTimeNow();
			return 0;
			
		} return 0;
		
		//==================================================
	case MAINM_CLOCKINIT: // Messages sent/posted from TCDLL.dll
		g_hwndClock = (HWND)lParam;
		api.InjectFinalize(); // injected, now remove hook
		return 0;
		
	case MAINM_ERROR:    // error
		InitError((int)lParam);
		SendMessage(hwnd, WM_CLOSE, 0, 0);
		return 0;
		
	case MAINM_EXIT:    // exit
		SendMessage(hwnd, WM_CLOSE, 0, 0);
		return 0;
		
	case MAINM_BLINKOFF:    // clock no longer blinks
		if(!g_bPlayingNonstop) StopFile();
		return 0;
		
	case MM_MCINOTIFY: // stop playing or repeat mci file (all but .wav, .pcb)
		OnMCINotify(hwnd);
		return 0;
	case MM_WOM_DONE: // stop playing wave
	case MAINM_STOPSOUND:
		StopFile();
		return 0;
		
	case WM_WININICHANGE:
		RefreshUs();
		return 0;
	// inform clock about DWM color change
	case WM_DWMCOLORIZATIONCOLORCHANGED:
		api.On_DWMCOLORIZATIONCOLORCHANGED((unsigned)wParam, (BOOL)lParam);
		PostMessage(g_hwndClock, WM_DWMCOLORIZATIONCOLORCHANGED, wParam, lParam);
		return 0;
		
	// context menu
	case WM_COMMAND:
		OnTClockCommand(hwnd, LOWORD(wParam)); // menu.c
		return 0;
		
	case WM_LBUTTONDOWN:
	case WM_RBUTTONDOWN:
	case WM_MBUTTONDOWN:
	case WM_XBUTTONDOWN:
		if(!g_bPlayingNonstop) PostMessage(hwnd, MAINM_STOPSOUND, 0, 0);
		/* fall through */
	case WM_LBUTTONUP:
	case WM_RBUTTONUP:
	case WM_MBUTTONUP:
	case WM_XBUTTONUP:
		OnMouseMsg(hwnd, message, wParam, lParam); // mouse.c
		return 0;
		
	case WM_WTSSESSION_CHANGE:
		switch(wParam) {
		case WTS_SESSION_LOCK:
			Sleep(500); // Eliminate user's interaction for 500 ms
			SendMessage(HWND_BROADCAST_nowarn, WM_SYSCOMMAND,SC_MONITORPOWER, 2);
			return 0;
		}
		break;
	default:
		if(message == g_WM_TaskbarCreated){
			InjectClockHook(hwnd);
		}
	}
	return DefWindowProc(hwnd, message, wParam, lParam);
}
void
InfoRepo::init()
{
  ACE_Argv_Type_Converter cvt(this->federatorConfig_.argc(),
                              this->federatorConfig_.argv());
  this->orb_ = CORBA::ORB_init(cvt.get_argc(), cvt.get_ASCII_argv(), "");

  this->info_servant_ =
    new TAO_DDS_DCPSInfo_i(this->orb_, this->resurrect_, this,
                           this->federatorConfig_.federationId());

  // Install the DCPSInfo_i into the Federator::Manager.
  this->federator_.info() = this->info_servant_.in();

  CORBA::Object_var obj =
    this->orb_->resolve_initial_references("RootPOA");
  PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj);

  PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();

  // Use persistent and user id POA policies so the Info Repo's
  // object references are consistent.
  CORBA::PolicyList policies(2);
  policies.length(2);
  policies[0] = root_poa->create_id_assignment_policy(PortableServer::USER_ID);
  policies[1] = root_poa->create_lifespan_policy(PortableServer::PERSISTENT);
  PortableServer::POA_var info_poa = root_poa->create_POA("InfoRepo",
                                                          poa_manager,
                                                          policies);

  // Creation of the new POAs over, so destroy the Policy_ptr's.
  for (CORBA::ULong i = 0; i < policies.length(); ++i) {
    policies[i]->destroy();
  }

  PortableServer::ObjectId_var oid =
    PortableServer::string_to_ObjectId("InfoRepo");
  info_poa->activate_object_with_id(oid, this->info_servant_.in());
  obj = info_poa->id_to_reference(oid);
  // the object is created locally, so it is safe to do an
  // _unchecked_narrow, this was needed to prevent an exception
  // when dealing with ImR-ified objects
  OpenDDS::DCPS::DCPSInfo_var info_repo =
    OpenDDS::DCPS::DCPSInfo::_unchecked_narrow(obj);

  CORBA::String_var objref_str =
    orb_->object_to_string(info_repo);

  // Initialize the DomainParticipantFactory
  DDS::DomainParticipantFactory_var dpf =
    TheParticipantFactoryWithArgs(cvt.get_argc(),
                                  cvt.get_TCHAR_argv());

  // We need parse the command line options for DCPSInfoRepo after parsing DCPS specific
  // command line options.

  // Check the non-ORB arguments.
  this->parse_args(cvt.get_argc(), cvt.get_TCHAR_argv());

  // Activate the POA manager before initialize built-in-topics
  // so invocations can be processed.
  poa_manager->activate();

  if (this->use_bits_) {
    if (this->info_servant_->init_transport(this->listen_address_given_,
        this->listen_address_str_.c_str())
        != 0 /* init_transport returns 0 for success */) {
      ACE_ERROR((LM_ERROR, ACE_TEXT("(%P|%t) ERROR: DCPSInfoRepo::init: ")
                 ACE_TEXT("Unable to initialize transport.\n")));
      throw InitError("Unable to initialize transport.");
    }

  } else {
    TheServiceParticipant->set_BIT(false);
  }

  // This needs to be done after initialization since we create the reference
  // to ourselves in the service here.
  OpenDDS::DCPS::Service_Participant* serv_part = TheServiceParticipant;
  serv_part->set_repo_ior(objref_str, OpenDDS::DCPS::Discovery::DEFAULT_REPO);

  OpenDDS::DCPS::Discovery_rch disc = serv_part->get_discovery(0 /*domainId*/);
  OpenDDS::DCPS::InfoRepoDiscovery_rch ird =
    OpenDDS::DCPS::static_rchandle_cast<OpenDDS::DCPS::InfoRepoDiscovery>(disc);
  if (!ird->set_ORB(orb_)) {
    ACE_ERROR((LM_ERROR, ACE_TEXT("(%P|%t) ERROR: DCPSInfoRepo::init: ")
               ACE_TEXT("Unable to set the ORB in InfoRepoDiscovery.\n")));
    throw InitError("Unable to set the ORB in InfoRepoDiscovery.");
  }

  // Initialize persistence _after_ initializing the participant factory
  // and intializing the transport.
  if (!this->info_servant_->init_persistence()) {
    ACE_ERROR((LM_ERROR, ACE_TEXT("(%P|%t) ERROR: DCPSInfoRepo::init: ")
               ACE_TEXT("Unable to initialize persistence.\n")));
    throw InitError("Unable to initialize persistence.");
  }

  // Initialize reassociation.
  if (this->reassociate_delay_ != ACE_Time_Value::zero &&
     !this->info_servant_->init_reassociation(this->reassociate_delay_)) {
    ACE_ERROR((LM_ERROR, ACE_TEXT("(%P|%t) ERROR: DCPSInfoRepo::init: ")
               ACE_TEXT("Unable to initialize reassociation.\n")));
    throw InitError("Unable to initialize reassociation.");
  }

  // Initialize dispatch checking
  if (this->dispatch_cleanup_delay_ != ACE_Time_Value::zero &&
     !this->info_servant_->init_dispatchChecking(this->dispatch_cleanup_delay_)) {
    ACE_ERROR((LM_ERROR, ACE_TEXT("(%P|%t) ERROR: DCPSInfoRepo::init: ")
               ACE_TEXT("Unable to initialize Dispatch checking.\n")));
    throw InitError("Unable to initialize dispatch checking.");
  }

  // Fire up the federator.
  OpenDDS::Federator::Manager_var federator;
  CORBA::String_var               federator_ior;

  if (federator_.id().overridden()) {
    oid = PortableServer::string_to_ObjectId("Federator");
    info_poa->activate_object_with_id(oid, &federator_);
    obj = info_poa->id_to_reference(oid);
    federator = OpenDDS::Federator::Manager::_narrow(obj);

    federator_ior = orb_->object_to_string(federator);

    // Add a local repository reference that can be returned via a
    // remote call to a peer.
    this->federator_.localRepo(info_repo);

    // It should be safe to initialize the federation mechanism at this
    // point.  What we really needed to wait for is the initialization of
    // the service components - like the DomainParticipantFactory and the
    // repository bindings.
    // N.B. This is done *before* being added to the IOR table to avoid any
    //      races with an eager client.
    this->federator_.orb(this->orb_);

    //
    // Add the federator to the info_servant update manager as an
    // additional updater interface to be called.
    // N.B. This needs to be done *after* the call to load_domains()
    //      since that is where the update manager is initialized in the
    //      info startup sequencing.
    this->info_servant_->add(&this->federator_);
  }

  // Grab the IOR table.
  CORBA::Object_var table_object =
    this->orb_->resolve_initial_references("IORTable");

  IORTable::Table_var adapter = IORTable::Table::_narrow(table_object);

  if (CORBA::is_nil(adapter)) {
    ACE_ERROR((LM_ERROR, ACE_TEXT("Nil IORTable\n")));

  } else {
    adapter->bind(OpenDDS::Federator::REPOSITORY_IORTABLE_KEY, objref_str);

    if (this->federator_.id().overridden()) {
      // Bind to '/Federator'
      adapter->bind(OpenDDS::Federator::FEDERATOR_IORTABLE_KEY, federator_ior);

      // Bind to '/Federator/1382379631'
      std::stringstream buffer(OpenDDS::Federator::FEDERATOR_IORTABLE_KEY);
      buffer << "/" << std::dec << this->federatorConfig_.federationDomain();
      adapter->bind(buffer.str().c_str(), federator_ior);
    }
  }

  FILE* output_file = ACE_OS::fopen(this->ior_file_.c_str(), ACE_TEXT("w"));

  if (output_file == 0) {
    ACE_ERROR((LM_ERROR, ACE_TEXT("ERROR: Unable to open IOR file: %s\n"),
               ior_file_.c_str()));
    throw InitError("Unable to open IOR file.");
  }

  ACE_OS::fprintf(output_file, "%s", objref_str.in());
  ACE_OS::fclose(output_file);

  // Initial federation join if specified on command line.
  if (this->federator_.id().overridden()
       && !this->federatorConfig_.federateIor().empty()) {
    if (OpenDDS::DCPS::DCPS_debug_level > 0) {
      ACE_DEBUG((LM_DEBUG,
                 ACE_TEXT("(%P|%t) INFO: DCPSInfoRepo::init() - ")
                 ACE_TEXT("joining federation with repository %s\n"),
                 this->federatorConfig_.federateIor().c_str()));
    }

    obj = this->orb_->string_to_object(
          this->federatorConfig_.federateIor().c_str());

    if (CORBA::is_nil(obj)) {
      ACE_ERROR((LM_ERROR,
                 ACE_TEXT("(%P|%t) ERROR: could not resolve %s for initial federation.\n"),
                 this->federatorConfig_.federateIor().c_str()));
      throw InitError("Unable to resolve IOR for initial federation.");
    }

    OpenDDS::Federator::Manager_var peer =
      OpenDDS::Federator::Manager::_narrow(obj);

    if (CORBA::is_nil(peer)) {
      ACE_ERROR((LM_ERROR,
                 ACE_TEXT("(%P|%t) ERROR: could not narrow %s.\n"),
                 this->federatorConfig_.federateIor().c_str()));
      throw InitError("Unable to narrow peer for initial federation.");
    }

    // Actually join.
    peer->join_federation(federator,
                          this->federatorConfig_.federationDomain());
  }
}
void
InfoRepo::parse_args(int argc, ACE_TCHAR *argv[])
{
  ACE_Arg_Shifter arg_shifter(argc, argv);

  const ACE_TCHAR* current_arg = 0;

  while (arg_shifter.is_anything_left()) {
    if ((current_arg = arg_shifter.get_the_parameter(ACE_TEXT("-a"))) != 0) {
      this->listen_address_str_ = ACE_TEXT_ALWAYS_CHAR(current_arg);
      this->listen_address_given_ = 1;
      arg_shifter.consume_arg();
    // Must check for -ReassociateDelay before -r
    } else if ((current_arg = arg_shifter.get_the_parameter(ACE_TEXT("-ReassociateDelay"))) != 0) {
      long msec = ACE_OS::atoi(current_arg);
      this->reassociate_delay_.msec(msec);

      arg_shifter.consume_arg();
    } else if ((current_arg = arg_shifter.get_the_parameter
                              (ACE_TEXT("-r"))) != 0) {
      int p = ACE_OS::atoi(current_arg);
      this->resurrect_ = true;

      if (p == 0) {
        this->resurrect_ = false;
      }

      arg_shifter.consume_arg();

    } else if ((current_arg = arg_shifter.get_the_parameter(ACE_TEXT("-o"))) != 0) {
      this->ior_file_ = current_arg;
      arg_shifter.consume_arg();

    } else if (arg_shifter.cur_arg_strncasecmp(ACE_TEXT("-NOBITS")) == 0) {
      this->use_bits_ = false;
      arg_shifter.consume_arg();

    } else if (arg_shifter.cur_arg_strncasecmp(ACE_TEXT("-z")) == 0) {
      TURN_ON_VERBOSE_DEBUG;
      arg_shifter.consume_arg();

    } else if ((current_arg = arg_shifter.get_the_parameter(ACE_TEXT("-DispatchingCheckDelay"))) != 0) {
      long sec = ACE_OS::atoi(current_arg);
      this->dispatch_cleanup_delay_.sec(sec);
      arg_shifter.consume_arg();

    }

    // The '-?' option
    else if (arg_shifter.cur_arg_strncasecmp(ACE_TEXT("-?")) == 0) {
      this->usage(argv[0]);
      throw InitError("Usage");
    }

    // Anything else we just skip

    else {
      arg_shifter.ignore_arg();
    }
  }
}
Beispiel #27
0
FileStream::FileStream(const std::string& ,const int)
  throw (NameError,InitError,FileError) : Stream() {
  throw InitError("No support for streaming from files compiled in.");
}
Beispiel #28
0
Stream::Stream() throw (NameError) : SoundData() {
  throw InitError("No streaming support compiled in.");
}