Beispiel #1
0
static void
ResetArgs(const std::string& strArg)
{
    std::vector<std::string> vecArg;
    boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on);


    vecArg.insert(vecArg.begin(), "testbitcoin");


    std::vector<const char*> vecChar;
    BOOST_FOREACH(std::string& s, vecArg)
        vecChar.push_back(s.c_str());

    ParseParameters(vecChar.size(), &vecChar[0]);
}
Beispiel #2
0
static void ResetArgs(const std::string& strArg)
{
    std::vector<std::string> vecArg;
    if (strArg.size())
      boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on);

    // Insert dummy executable name:
    vecArg.insert(vecArg.begin(), "testemercoin");

    // Convert to char*:
    std::vector<const char*> vecChar;
    BOOST_FOREACH(std::string& s, vecArg)
        vecChar.push_back(s.c_str());

    ParseParameters(vecChar.size(), &vecChar[0]);
}
ECode CHttpAuthHeader::ParseHeader(
    /* [in] */ const String& header)
{
    if (HttpLog::LOGV) {
        HttpLog::V(String("HttpAuthHeader.parseHeader(): header: ") + header);
    }

    if (header != NULL) {
        String parameters;
        ParseScheme(header, &parameters);
        if (parameters != NULL) {
            // if we have a supported scheme
            if (mScheme != UNKNOWN) {
                ParseParameters(parameters);
            }
        }
    }
    return NOERROR;
}
Beispiel #4
0
int main(int argc, char **argv)
{
	CUpdateService		svc;
    struct 	sigaction   handler;
	int					fd;

	Splash();

	if (!ParseParameters(argc, argv))
	{
		return 0;	
	}

	if ((argc - optind) < 2)
	{
		Usage(argv[0]);
		return 0;	
	}


    // Set Interrrupt Signal Handler
	memset(&handler, 0, sizeof(struct sigaction));
    handler.sa_handler = SignalCatcher;
    sigfillset(&handler.sa_mask);
	sigaction(SIGINT, &handler, 0);
    sigaction(SIGTERM, &handler, 0);

	fd = open("lock.monet", O_CREAT, 0644);
	if (flock(fd, LOCK_EX | LOCK_NB) != 0)
	{	
		printf("이미 다른 사람이 사용 중 입니다.\r\n");
		printf("\r\n");
		exit(0);
	}

	svc.Updator(argv[optind+0], argv[optind+1]);

	flock(fd, LOCK_UN);
	close(fd);
	return 0;
}
Beispiel #5
0
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
static bool AppInitRPC(int argc, char* argv[])
{
    //
    // Parameters
    //
    ParseParameters(argc, argv);
    if (!boost::filesystem::is_directory(GetDataDir(false)))
    {
        fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
        return false;
    }
    try {
        ReadConfigFile(mapArgs, mapMultiArgs);
    } catch(std::exception &e) {
        fprintf(stderr,"Error reading configuration file: %s\n", e.what());
        return false;
    }
    // Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause)
    if (!SelectParamsFromCommandLine()) {
        fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
        return false;
    }

    if (argc<2 || mapArgs.count("-?") || mapArgs.count("--help"))
    {
        // First part of help message is specific to RPC client
        std::string strUsage = _("Zmark Core RPC client version") + " " + FormatFullVersion() + "\n\n" +
            _("Usage:") + "\n" +
              "  zmark-cli [options] <command> [params]  " + _("Send command to Zmark Core") + "\n" +
              "  zmark-cli [options] help                " + _("List commands") + "\n" +
              "  zmark-cli [options] help <command>      " + _("Get help for a command") + "\n";

        strUsage += "\n" + HelpMessageCli(true);

        fprintf(stdout, "%s", strUsage.c_str());
        return false;
    }
    return true;
}
int main(int argc, char *argv[])
{

	std::string server("127.0.0.1");
	std::string port("8335");
	std::string password("");
	std::string address("");
	int threadcount=1;

	ParseParameters(argc,argv);

	if(mapArgs.count("-server")>0)
	{
		server=mapArgs["-server"];
	}
	if(mapArgs.count("-port")>0)
	{
		port=mapArgs["-port"];
	}
	if(mapArgs.count("-password")>0)
	{
		password=mapArgs["-password"];
	}
	if(mapArgs.count("-address")>0)
	{
		address=mapArgs["-address"];
		uint160 h160;
		if(AddressToHash160(address.c_str(),h160)==false)
		{
			std::cout << "Address is invalid" << std::endl;
			address="";
		}
	}
	if(mapArgs.count("-threads")>0)
	{
		std::istringstream istr(mapArgs["-threads"]);
		istr >> threadcount;
	}
Beispiel #7
0
bool VistaNewClusterSlave::Init( const std::string& sClusterSection,
								const VistaPropertyList& oConfig )
{
	m_sSlaveSectionName = sClusterSection;
	m_sSlaveName = oConfig.GetValueOrDefault<std::string>( "NAME", sClusterSection );

	vstr::outi() << "[VistaNewClusterSlave]: Initializing" << std::endl;
	vstr::IndentObject oIndent;

	if( oConfig.HasSubList( sClusterSection ) == false )
	{
		vstr::errp() << "Cluster Slave cannot be initialized - section ["
			<< sClusterSection << "] does not exist!" << std::endl;
		return false;
	}
	const VistaPropertyList& oSection = oConfig.GetSubListConstRef( sClusterSection );

	if( ParseParameters( oSection ) == false )
		return false;	

	vstr::outi() << "Slave is told "
			  << (m_bDoOglFinish ? "" : "not ")
			  << "to do glFinish() before swap" << std::endl;

	
	if( WaitForClusterMaster( m_nServerPort ) == false )
	{
		vstr::errp() << "WaitForClusterMaster() failed on IP ["
					<< m_sOwnIP << ":" << m_nServerPort << "]" << std::endl;
		return false;
	}

	PrintClusterSetupInfo();

	vstr::outi() << "[VistaNewClusterSlave]: Initialization finished" << std::endl;
	return true;
}
Beispiel #8
0
int _tmain(int argc, CHAR *argv[]) {
    SECURITY_ATTRIBUTES saAttr;

    InitializeCriticalSection(&g_tear_down_crit);

    if (!SetConsoleCtrlHandler(OnConsoleCtrlEvent, TRUE)) {
        fprintf(stderr, "Parent: Failed to subscribe to console ctrl events\n");
        return -1;
    }

    if (ParseParameters(argc, argv, &g_config) != 0) {
        fprintf(stderr, "Failed to parse arguments\n");
        return -1;
    }

    // Set the bInheritHandle flag so pipe handles are inherited.
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;

    // Create a pipe for the child process's STDIN.
    if (!CreatePipe(&g_child_std_in_rd, &g_child_std_in_wr, &saAttr, 0)) {
        ErrorExit(TEXT("Stdin CreatePipe"));
    }

    // Ensure the write handle to the pipe for STDIN is not inherited.
    if (!SetHandleInformation(g_child_std_in_wr, HANDLE_FLAG_INHERIT, 0)) {
        ErrorExit(TEXT("Stdin SetHandleInformation"));
    }

    // Create the child process.
    if (CreateChildProcess(&g_config)) {
        TrackChildProcess(&g_config);
    }
    return 0;
}
Beispiel #9
0
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;
    boost::thread* detectShutdownThread = NULL;

    bool fRet = false;
    try
    {
        //
        // Parameters
        //
        // If Qt is used, parameters/flex.conf are parsed in qt/bitcoin.cpp's main()
        
        ParseParameters(argc, argv);
        if (!boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
            return false;
        }
        try
        {
            ReadConfigFile(mapArgs, mapMultiArgs);
            
        } catch(std::exception &e) {
            fprintf(stderr,"Error reading configuration file: %s\n", e.what());
            return false;
        }
        
        if (mapArgs.count("-?") || mapArgs.count("--help"))
        {
            // First part of help message is specific to flexd / RPC client
            std::string strUsage = _("Flex Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n\n" +
                _("Usage:") + "\n" +
                  "  flexd [options]                     " + _("Start Flex Core Daemon") + "\n" +
                _("Usage (deprecated, use flex-cli):") + "\n" +
                  "  flexd [options] <command> [params]  " + _("Send command to Flex Core") + "\n" +
                  "  flexd [options] help                " + _("List commands") + "\n" +
                  "  flexd [options] help <command>      " + _("Get help for a command") + "\n";

            strUsage += "\n" + HelpMessage(HMM_BITCOIND);
            strUsage += "\n" + HelpMessageCli(false);

            fprintf(stdout, "%s", strUsage.c_str());
            return false;
        }
        
        // Command-line RPC
        bool fCommandLine = false;
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            int ret = CommandLineRPC(argc, argv);
            exit(ret);
        }
        
#ifndef WIN32
        fDaemon = GetBoolArg("-daemon", false);
        if (fDaemon)
        {
            fprintf(stdout, "Flex server starting\n");

            // Daemonize
            pid_t pid = fork();
            if (pid < 0)
            {
                fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
                return false;
            }
            if (pid > 0) // Parent process, pid is child process id
            {
                CreatePidFile(GetPidFile(), pid);
                return true;
            }
            // Child process falls through to rest of initialization

            pid_t sid = setsid();
            if (sid < 0)
                fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
        }
#endif
        SoftSetBoolArg("-server", true);
        

        detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
        
        fRet = AppInit2(threadGroup);
        
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "AppInit()");
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInit()");
    }

    if (!fRet)
    {
        if (detectShutdownThread)
            detectShutdownThread->interrupt();

        threadGroup.interrupt_all();
        // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
        // the startup-failure cases to make sure they don't result in a hang due to some
        // thread-blocking-waiting-for-another-thread-during-startup case
    }

    if (detectShutdownThread)
    {
        detectShutdownThread->join();
        delete detectShutdownThread;
        detectShutdownThread = NULL;
    }
    Shutdown();

    return fRet;
}
Beispiel #10
0
int main(int argc, char *argv[])
{
    // Do this early as we don't want to bother initializing if we are just calling IPC
    for (int i = 1; i < argc; i++)
    {
        if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0)
        {
            const char *strURL = argv[i];
            try {
                boost::interprocess::message_queue mq(boost::interprocess::open_only, "BitcoinURL");
                if(mq.try_send(strURL, strlen(strURL), 0))
                    exit(0);
                else
                    break;
            }
            catch (boost::interprocess::interprocess_exception &ex) {
                break;
            }
        }
    }

    // Internal string conversion is all UTF-8
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());

    Q_INIT_RESOURCE(bitcoin);
    QApplication app(argc, argv);

    ParseParameters(argc, argv);

    // Get desired locale ("en_US") from command line or system locale
    QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
    // Load language files for configured locale:
    // - First load the translator for the base language, without territory
    // - Then load the more specific locale translator
    QString lang = lang_territory;

    lang.truncate(lang_territory.lastIndexOf('_')); // "en"
    QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;

    qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
    if (!qtTranslatorBase.isEmpty())
        app.installTranslator(&qtTranslatorBase);

    qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
    if (!qtTranslator.isEmpty())
        app.installTranslator(&qtTranslator);

    translatorBase.load(":/translations/"+lang);
    if (!translatorBase.isEmpty())
        app.installTranslator(&translatorBase);

    translator.load(":/translations/"+lang_territory);
    if (!translator.isEmpty())
        app.installTranslator(&translator);

    app.setApplicationName(QApplication::translate("main", "Bitcoin-Qt"));

    QSplashScreen splash(QPixmap(":/images/splash"), 0);
    splash.show();
    splash.setAutoFillBackground(true);
    splashref = &splash;

    app.processEvents();

    app.setQuitOnLastWindowClosed(false);

    try
    {
        if(AppInit2(argc, argv))
        {
            {
                // Put this in a block, so that BitcoinGUI is cleaned up properly before
                // calling Shutdown() in case of exceptions.
                BitcoinGUI window;
                splash.finish(&window);
                OptionsModel optionsModel(pwalletMain);
                ClientModel clientModel(&optionsModel);
                WalletModel walletModel(pwalletMain, &optionsModel);

                guiref = &window;
                window.setClientModel(&clientModel);
                window.setWalletModel(&walletModel);

                // If -min option passed, start window minimized.
                if(GetBoolArg("-min"))
                {
                    window.showMinimized();
                }
                else
                {
                    window.show();
                }

                // Place this here as guiref has to be defined if we dont want to lose URLs
                ipcInit();
                // Check for URL in argv
                for (int i = 1; i < argc; i++)
                {
                    if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0)
                    {
                        const char *strURL = argv[i];
                        try {
                            boost::interprocess::message_queue mq(boost::interprocess::open_only, "BitcoinURL");
                            mq.try_send(strURL, strlen(strURL), 0);
                        }
                        catch (boost::interprocess::interprocess_exception &ex) {
                        }
                    }
                }

                app.exec();

                guiref = 0;
            }
            Shutdown(NULL);
        }
        else
        {
            return 1;
        }
    } catch (std::exception& e) {
        PrintException(&e, "Runaway exception");
    } catch (...) {
        PrintException(NULL, "Runaway exception");
    }
    return 0;
}
bool ShaderVariation::Compile()
{
    const String& sourceCode = owner_->GetSourceCode(type_);
    Vector<String> defines = defines_.Split(' ');

    // Set the entrypoint, profile and flags according to the shader being compiled
    const char* entryPoint = 0;
    const char* profile = 0;
    unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;

    if (type_ == VS)
    {
        entryPoint = "VS";
        defines.Push("COMPILEVS");
        profile = "vs_3_0";
    }
    else
    {
        entryPoint = "PS";
        defines.Push("COMPILEPS");
        profile = "ps_3_0";
        flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
    }

    defines.Push("MAXBONES=" + String(Graphics::GetMaxBones()));

    // Collect defines into macros
    Vector<String> defineValues;
    PODVector<D3D_SHADER_MACRO> macros;

    for (unsigned i = 0; i < defines.Size(); ++i)
    {
        unsigned equalsPos = defines[i].Find('=');
        if (equalsPos != String::NPOS)
        {
            defineValues.Push(defines[i].Substring(equalsPos + 1));
            defines[i].Resize(equalsPos);
        }
        else
            defineValues.Push("1");
    }
    for (unsigned i = 0; i < defines.Size(); ++i)
    {
        D3D_SHADER_MACRO macro;
        macro.Name = defines[i].CString();
        macro.Definition = defineValues[i].CString();
        macros.Push(macro);

        // In debug mode, check that all defines are referenced by the shader code
#ifdef _DEBUG
        if (sourceCode.Find(defines[i]) == String::NPOS)
            ATOMIC_LOGWARNING("Shader " + GetFullName() + " does not use the define " + defines[i]);
#endif
    }

    D3D_SHADER_MACRO endMacro;
    endMacro.Name = 0;
    endMacro.Definition = 0;
    macros.Push(endMacro);

    // Compile using D3DCompile
    ID3DBlob* shaderCode = 0;
    ID3DBlob* errorMsgs = 0;

    HRESULT hr = D3DCompile(sourceCode.CString(), sourceCode.Length(), owner_->GetName().CString(), &macros.Front(), 0,
        entryPoint, profile, flags, 0, &shaderCode, &errorMsgs);
    if (FAILED(hr))
    {
        // Do not include end zero unnecessarily
        compilerOutput_ = String((const char*)errorMsgs->GetBufferPointer(), (unsigned)errorMsgs->GetBufferSize() - 1);
    }
    else
    {
        if (type_ == VS)
            ATOMIC_LOGDEBUG("Compiled vertex shader " + GetFullName());
        else
            ATOMIC_LOGDEBUG("Compiled pixel shader " + GetFullName());

        // Inspect the produced bytecode using MojoShader, then strip and store it
        unsigned char* bufData = (unsigned char*)shaderCode->GetBufferPointer();
        unsigned bufSize = (unsigned)shaderCode->GetBufferSize();
        ParseParameters(bufData, bufSize);
        CopyStrippedCode(byteCode_, bufData, bufSize);
    }

    ATOMIC_SAFE_RELEASE(shaderCode);
    ATOMIC_SAFE_RELEASE(errorMsgs);

    return !byteCode_.Empty();
}
Beispiel #12
0
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;
    CScheduler scheduler;

    bool fRet = false;

    //
    // Parameters
    //
    // If Qt is used, parameters/dash.conf are parsed in qt/dash.cpp's main()
    ParseParameters(argc, argv);

    // Process help and version before taking care about datadir
    if (mapArgs.count("-?") || mapArgs.count("-h") ||  mapArgs.count("-help") || mapArgs.count("-version"))
    {
        std::string strUsage = _("Dash Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n";

        if (mapArgs.count("-version"))
        {
            strUsage += LicenseInfo();
        }
        else
        {
            strUsage += "\n" + _("Usage:") + "\n" +
                  "  dashd [options]                     " + _("Start Dash Core Daemon") + "\n";

            strUsage += "\n" + HelpMessage(HMM_BITCOIND);
        }

        fprintf(stdout, "%s", strUsage.c_str());
        return true;
    }

    try
    {
        bool datadirFromCmdLine = mapArgs.count("-datadir") != 0;
        if (datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
            return false;
        }
        try
        {
            ReadConfigFile(mapArgs, mapMultiArgs);
        } catch (const std::exception& e) {
            fprintf(stderr,"Error reading configuration file: %s\n", e.what());
            return false;
        }
        if (!datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" from config file does not exist.\n", mapArgs["-datadir"].c_str());
            return EXIT_FAILURE;
        }
        // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
        try {
            SelectParams(ChainNameFromCommandLine());
        } catch (const std::exception& e) {
            fprintf(stderr, "Error: %s\n", e.what());
            return false;
        }

        // parse masternode.conf
        std::string strErr;
        if(!masternodeConfig.read(strErr)) {
            fprintf(stderr,"Error reading masternode configuration file: %s\n", strErr.c_str());
            return false;
        }

        // Command-line RPC
        bool fCommandLine = false;
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "dash:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            fprintf(stderr, "Error: There is no RPC client functionality in dashd anymore. Use the dash-cli utility instead.\n");
            exit(EXIT_FAILURE);
        }
#ifndef WIN32
        fDaemon = GetBoolArg("-daemon", false);
        if (fDaemon)
        {
            fprintf(stdout, "Dash Core server starting\n");

            // Daemonize
            pid_t pid = fork();
            if (pid < 0)
            {
                fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
                return false;
            }
            if (pid > 0) // Parent process, pid is child process id
            {
                return true;
            }
            // Child process falls through to rest of initialization

            pid_t sid = setsid();
            if (sid < 0)
                fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
        }
#endif
        SoftSetBoolArg("-server", true);

        // Set this early so that parameter interactions go to console
        InitLogging();
        InitParameterInteraction();
        fRet = AppInit2(threadGroup, scheduler);
    }
    catch (const std::exception& e) {
        PrintExceptionContinue(&e, "AppInit()");
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInit()");
    }

    if (!fRet)
    {
        Interrupt(threadGroup);
        // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
        // the startup-failure cases to make sure they don't result in a hang due to some
        // thread-blocking-waiting-for-another-thread-during-startup case
    } else {
        WaitForShutdown(&threadGroup);
    }
    Shutdown();

    return fRet;
}
Beispiel #13
0
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;
    boost::thread* detectShutdownThread = NULL;

    bool fRet = false;
    try
    {
        //
        // Parameters
        //
        // If Qt is used, parameters/bonus.conf are parsed in qt/bitcoin.cpp's main()
        ParseParameters(argc, argv);
        if (!boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified directory does not exist\n");
            Shutdown();
        }
        ReadConfigFile(mapArgs, mapMultiArgs);

        if (mapArgs.count("-?") || mapArgs.count("--help"))
        {
            // First part of help message is specific to bonusd / RPC client
            std::string strUsage = _("Bonus version") + " " + FormatFullVersion() + "\n\n" +
                _("Usage:") + "\n" +
                  "  bonusd [options]                     " + "\n" +
                  "  bonusd [options] <command> [params]  " + _("Send command to -server or bonusd") + "\n" +
                  "  bonusd [options] help                " + _("List commands") + "\n" +
                  "  bonusd [options] help <command>      " + _("Get help for a command") + "\n";

            strUsage += "\n" + HelpMessage();

            fprintf(stdout, "%s", strUsage.c_str());
            return false;
        }

        // Command-line RPC
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bonus:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            if (!SelectParamsFromCommandLine()) {
                fprintf(stderr, "Error: invalid combination of -regtest and -testnet.\n");
                return false;
            }
            int ret = CommandLineRPC(argc, argv);
            exit(ret);
        }
#if !defined(WIN32)
        fDaemon = GetBoolArg("-daemon", false);
        if (fDaemon)
        {
            // Daemonize
            pid_t pid = fork();
            if (pid < 0)
            {
                fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
                return false;
            }
            if (pid > 0) // Parent process, pid is child process id
            {
                CreatePidFile(GetPidFile(), pid);
                return true;
            }
            // Child process falls through to rest of initialization

            pid_t sid = setsid();
            if (sid < 0)
                fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
        }
#endif

        detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
        fRet = AppInit2(threadGroup);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "AppInit()");
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInit()");
    }
    if (!fRet) {
        if (detectShutdownThread)
            detectShutdownThread->interrupt();
        threadGroup.interrupt_all();
    }

    if (detectShutdownThread)
    {
        detectShutdownThread->join();
        delete detectShutdownThread;
        detectShutdownThread = NULL;
    }
    Shutdown();

    return fRet;
}
Beispiel #14
0
bool AppInit2(int argc, char* argv[])
{
#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
#ifndef __WXMSW__
    umask(077);
#endif

    //
    // Parameters
    //
    ParseParameters(argc, argv);

    if (mapArgs.count("-datadir"))
        strlcpy(pszSetDataDir, mapArgs["-datadir"].c_str(), sizeof(pszSetDataDir));

    ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir

    if (mapArgs.count("-?") || mapArgs.count("--help"))
    {
        string strUsage = string() +
          _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
            "  bitcoin [options]                   \t  " + "\n" +
            "  bitcoin [options] <command> [params]\t  " + _("Send command to -server or bitcoind\n") +
            "  bitcoin [options] <command> -?      \t\t  " + _("Get help for a command\n") +
            "  bitcoin help                        \t\t\t  " + _("List commands\n") +
          _("Options:\n") +
            "  -conf=<file>    \t  " + _("Specify configuration file (default: bitcoin.conf)\n") +
            "  -gen            \t  " + _("Generate coins\n") +
            "  -gen=0          \t  " + _("Don't generate coins\n") +
            "  -min            \t  " + _("Start minimized\n") +
            "  -datadir=<dir>  \t  " + _("Specify data directory\n") +
            "  -proxy=<ip:port>\t  " + _("Connect through socks4 proxy\n") +
            "  -addnode=<ip>   \t  " + _("Add a node to connect to\n") +
            "  -connect=<ip>   \t  " + _("Connect only to the specified node\n") +
            "  -server         \t  " + _("Accept command line and JSON-RPC commands\n") +
            "  -daemon         \t  " + _("Run in the background as a daemon and accept commands\n") +
            "  -?              \t  " + _("This help message\n");

#if defined(__WXMSW__) && defined(GUI)
        // Tabs make the columns line up in the message box
        wxMessageBox(strUsage, "Bitcoin", wxOK);
#else
        // Remove tabs
        strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
        fprintf(stderr, "%s", strUsage.c_str());
#endif
        return false;
    }

    if (mapArgs.count("-debug"))
        fDebug = true;

    if (mapArgs.count("-printtodebugger"))
        fPrintToDebugger = true;

    if (fCommandLine)
    {
        int ret = CommandLineRPC(argc, argv);
        exit(ret);
    }

    if (!fDebug && !pszSetDataDir[0])
        ShrinkDebugFile();
    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    printf("BitcoinTEST version %d.%d.%d%s beta\n", VERSION/10000, (VERSION/100)%100, VERSION%100, pszSubVer);
#ifdef GUI
    printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
    printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
    printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
#endif
    printf("Default data directory %s\n", GetDefaultDataDir().c_str());

    if (mapArgs.count("-loadblockindextest"))
    {
        CTxDB txdb("r");
        txdb.LoadBlockIndex();
        PrintBlockTree();
        return false;
    }

    //
    // Limit to single instance per user
    // Required to protect the database files if we're going to keep deleting log.*
    //
#if defined(__WXMSW__) && defined(GUI)
    // todo: wxSingleInstanceChecker wasn't working on Linux, never deleted its lock file
    //  maybe should go by whether successfully bind port 18333 instead
    wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
    for (int i = 0; i < strMutexName.size(); i++)
        if (!isalnum(strMutexName[i]))
            strMutexName[i] = '.';
    wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
    if (psingleinstancechecker->IsAnotherRunning())
    {
        printf("Existing instance found\n");
        unsigned int nStart = GetTime();
        loop
        {
            // TODO: find out how to do this in Linux, or replace with wxWidgets commands
            // Show the previous instance and exit
            HWND hwndPrev = FindWindowA("wxWindowClassNR", "BitcoinTEST");
            if (hwndPrev)
            {
                if (IsIconic(hwndPrev))
                    ShowWindow(hwndPrev, SW_RESTORE);
                SetForegroundWindow(hwndPrev);
                return false;
            }

            if (GetTime() > nStart + 60)
                return false;

            // Resume this instance if the other exits
            delete psingleinstancechecker;
            Sleep(1000);
            psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
            if (!psingleinstancechecker->IsAnotherRunning())
                break;
        }
    }
Beispiel #15
0
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;
    CScheduler scheduler;

    bool fRet = false;

    //
    // Parameters
    //
    // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
    ParseParameters(argc, argv);

    // Process help and version before taking care about datadir
    if (IsArgSet("-?") || IsArgSet("-h") ||  IsArgSet("-help") || IsArgSet("-version"))
    {
        std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n";

        if (IsArgSet("-version"))
        {
            strUsage += FormatParagraph(LicenseInfo());
        }
        else
        {
            strUsage += "\n" + _("Usage:") + "\n" +
                  "  bitcoind [options]                     " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n";

            strUsage += "\n" + HelpMessage(HMM_BITCOIND);
        }

        fprintf(stdout, "%s", strUsage.c_str());
        return true;
    }

    try
    {
        if (!fs::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
            return false;
        }
        try
        {
            ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
        } catch (const std::exception& e) {
            fprintf(stderr,"Error reading configuration file: %s\n", e.what());
            return false;
        }
        // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
        try {
            SelectParams(ChainNameFromCommandLine());
        } catch (const std::exception& e) {
            fprintf(stderr, "Error: %s\n", e.what());
            return false;
        }

        // Command-line RPC
        bool fCommandLine = false;
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            fprintf(stderr, "Error: There is no RPC client functionality in bitcoind anymore. Use the bitcoin-cli utility instead.\n");
            exit(EXIT_FAILURE);
        }
        // -server defaults to true for bitcoind but not for the GUI so do this here
        SoftSetBoolArg("-server", true);
        // Set this early so that parameter interactions go to console
        InitLogging();
        InitParameterInteraction();
        if (!AppInitBasicSetup())
        {
            // InitError will have been called with detailed error, which ends up on console
            exit(EXIT_FAILURE);
        }
        if (!AppInitParameterInteraction())
        {
            // InitError will have been called with detailed error, which ends up on console
            exit(EXIT_FAILURE);
        }
        if (!AppInitSanityChecks())
        {
            // InitError will have been called with detailed error, which ends up on console
            exit(EXIT_FAILURE);
        }
        if (GetBoolArg("-daemon", false))
        {
#if HAVE_DECL_DAEMON
            fprintf(stdout, "Bitcoin server starting\n");

            // Daemonize
            if (daemon(1, 0)) { // don't chdir (1), do close FDs (0)
                fprintf(stderr, "Error: daemon() failed: %s\n", strerror(errno));
                return false;
            }
#else
            fprintf(stderr, "Error: -daemon is not supported on this operating system\n");
            return false;
#endif // HAVE_DECL_DAEMON
        }

        fRet = AppInitMain(threadGroup, scheduler);
    }
    catch (const std::exception& e) {
        PrintExceptionContinue(&e, "AppInit()");
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInit()");
    }

    if (!fRet)
    {
        Interrupt(threadGroup);
        // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
        // the startup-failure cases to make sure they don't result in a hang due to some
        // thread-blocking-waiting-for-another-thread-during-startup case
    } else {
        WaitForShutdown(&threadGroup);
    }
    Shutdown();

    return fRet;
}
Beispiel #16
0
bool AppInit2(int argc, char* argv[])
{
#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
#ifndef __WXMSW__
    umask(077);
#endif
#ifndef __WXMSW__
    // 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);
    sigaction(SIGHUP, &sa, NULL);
#endif

    //
    // Parameters
    //
    ParseParameters(argc, argv);

    if (mapArgs.count("-datadir"))
    {
        filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
        strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
    }

    ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir

    if (mapArgs.count("-?") || mapArgs.count("--help"))
    {
        string beta = VERSION_IS_BETA ? _(" beta") : "";
        string strUsage = string() +
          _("namecoin version") + " " + FormatFullVersion() + "\n\n" +
          _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
            "  namecoin [options]                   \t  " + "\n" +
            "  namecoin [options] <command> [params]\t  " + _("Send command to -server or namecoind\n") +
            "  namecoin [options] help              \t\t  " + _("List commands\n") +
            "  namecoin [options] help <command>    \t\t  " + _("Get help for a command\n") +
          _("Options:\n") +
            "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)\n") +
            "  -pid=<file>      \t\t  " + _("Specify pid file (default: bitcoind.pid)\n") +
            "  -gen             \t\t  " + _("Generate coins\n") +
            "  -gen=0           \t\t  " + _("Don't generate coins\n") +
            "  -min             \t\t  " + _("Start minimized\n") +
            "  -datadir=<dir>   \t\t  " + _("Specify data directory\n") +
            "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\n") +
            "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +
            "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +
            "  -nolisten        \t  "   + _("Don't accept connections from outside\n") +
#ifdef USE_UPNP
#if USE_UPNP
            "  -noupnp          \t  "   + _("Don't attempt to use UPnP to map the listening port\n") +
#else
            "  -upnp            \t  "   + _("Attempt to use UPnP to map the listening port\n") +
#endif
#endif
            "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send\n") +
#ifdef GUI
            "  -server          \t\t  " + _("Accept command line and JSON-RPC commands\n") +
#endif
#ifndef __WXMSW__
            "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands\n") +
#endif
            "  -testnet         \t\t  " + _("Use the test network\n") +
            "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections\n") +
            "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections\n") +
            "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)\n") +
            "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address\n") +
            "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)\n") +
            "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)\n") +
            "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions\n");

#ifdef USE_SSL
        strUsage += string() +
            _("\nSSL options: (see the namecoin Wiki for SSL setup instructions)\n") +
            "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections\n") +
            "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)\n") +
            "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)\n") +
            "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");
#endif

        strUsage += string() +
            "  -?               \t\t  " + _("This help message\n");

#if defined(__WXMSW__) && defined(GUI)
        // Tabs make the columns line up in the message box
        wxMessageBox(strUsage, "Bitcoin", wxOK);
#else
        // Remove tabs
        strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
        fprintf(stderr, "%s", strUsage.c_str());
#endif
        return false;
    }

    fDebug = GetBoolArg("-debug");

#ifndef __WXMSW__
    fDaemon = GetBoolArg("-daemon");
#else
    fDaemon = false;
#endif

    if (fDaemon)
        fServer = true;
    else
        fServer = GetBoolArg("-server");

    /* force fServer when running without GUI */
#ifndef GUI
    fServer = true;
#endif

    fPrintToConsole = GetBoolArg("-printtoconsole");
    fPrintToDebugger = GetBoolArg("-printtodebugger");

    fTestNet = GetBoolArg("-testnet");
    fNoListen = GetBoolArg("-nolisten");
    fLogTimestamps = GetBoolArg("-logtimestamps");

    for (int i = 1; i < argc; i++)
        if (!IsSwitchChar(argv[i][0]))
            fCommandLine = true;

    if (fCommandLine)
    {
        int ret = CommandLineRPC(argc, argv);
        exit(ret);
    }

#ifndef __WXMSW__
    if (fDaemon)
    {
        // Daemonize
        pid_t pid = fork();
        if (pid < 0)
        {
            fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
            return false;
        }
        if (pid > 0)
        {
            CreatePidFile(GetPidFile(), pid);
            return true;
        }

        pid_t sid = setsid();
        if (sid < 0)
            fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
    }
#endif

    if (!fDebug && !pszSetDataDir[0])
        ShrinkDebugFile();
    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    printf("namecoin version %s\n", FormatFullVersion().c_str());
#ifdef GUI
    printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());
    printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());
    printf("Language file %s (%s)\n", (string("locale/") + (string)g_locale.GetCanonicalName() + "/LC_MESSAGES/bitcoin.mo").c_str(), ((string)g_locale.GetLocale()).c_str());
#endif
    printf("Default data directory %s\n", GetDefaultDataDir().c_str());

    if (GetBoolArg("-loadblockindextest"))
    {
        CTxDB txdb("r");
        txdb.LoadBlockIndex();
        PrintBlockTree();
        return false;
    }

    //
    // Limit to single instance per user
    // Required to protect the database files if we're going to keep deleting log.*
    //
#if defined(__WXMSW__) && defined(GUI)
    // wxSingleInstanceChecker doesn't work on Linux
    wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");
    for (int i = 0; i < strMutexName.size(); i++)
        if (!isalnum(strMutexName[i]))
            strMutexName[i] = '.';
    wxSingleInstanceChecker* psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
    if (psingleinstancechecker->IsAnotherRunning())
    {
        printf("Existing instance found\n");
        unsigned int nStart = GetTime();
        loop
        {
            // Show the previous instance and exit
            HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");
            if (hwndPrev)
            {
                if (IsIconic(hwndPrev))
                    ShowWindow(hwndPrev, SW_RESTORE);
                SetForegroundWindow(hwndPrev);
                return false;
            }

            if (GetTime() > nStart + 60)
                return false;

            // Resume this instance if the other exits
            delete psingleinstancechecker;
            Sleep(1000);
            psingleinstancechecker = new wxSingleInstanceChecker(strMutexName);
            if (!psingleinstancechecker->IsAnotherRunning())
                break;
        }
    }
{
    DWORD Error = ERROR_SUCCESS;
    PWSTR Hostname = NULL;
    PWSTR CertSubjectName = NULL;
    USHORT Port = 0;
    PWSTR StoreName = NULL;
    HTTPAPI_VERSION Version = HTTPAPI_VERSION_2;
    BOOL ApiInitialized = FALSE;

    //
    // Get parameters from input command line.
    //

    Error = ParseParameters(Argc,
                            Argv,
                            &Port,
                            &Hostname,
                            &CertSubjectName,
                            &StoreName);

    if (Error != ERROR_SUCCESS)
    {
        goto exit;
    }

    //
    // Initialize HTTPAPI in config mode.
    //

    Error = HttpInitialize(Version, HTTP_INITIALIZE_CONFIG, NULL);

    if (Error != ERROR_SUCCESS)
Beispiel #18
0
static bool AppInitRawTx(int argc, char* argv[])
{
    //
    // Parameters
    //
    AllowedArgs::BitcoinTx allowedArgs;
    try {
        ParseParameters(argc, argv, allowedArgs);
    } catch (const std::exception& e) {
        fprintf(stderr, "Error parsing program options: %s\n", e.what());
        return false;
    }

    flexTransActive = GetBoolArg("-flextrans", false);

    // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
    try {
        SelectParams(ChainNameFromCommandLine());
    } catch (const std::exception& e) {
        fprintf(stderr, "Error: %s\n", e.what());
        return false;
    }

    fCreateBlank = GetBoolArg("-create", false);

    if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version"))
    {
        // First part of help message is specific to this utility
        std::string strUsage = _("Bitcoin Classic bitcoin-tx utility version") + " " + FormatFullVersion() + "\n";

        fprintf(stdout, "%s", strUsage.c_str());

        if (mapArgs.count("-version"))
            return false;

        strUsage = "\n" + _("Usage:") + "\n" +
              "  bitcoin-tx [options] <hex-tx> [commands]  " + _("Update hex-encoded bitcoin transaction") + "\n" +
              "  bitcoin-tx [options] -create [commands]   " + _("Create hex-encoded bitcoin transaction") + "\n" +
              "\n";

        fprintf(stdout, "%s", strUsage.c_str());

        strUsage = allowedArgs.helpMessage();

        fprintf(stdout, "%s", strUsage.c_str());

        strUsage = AllowedArgs::HelpMessageGroup(_("Commands:"));
        strUsage += AllowedArgs::HelpMessageOpt("delin=N", _("Delete input N from TX"));
        strUsage += AllowedArgs::HelpMessageOpt("delout=N", _("Delete output N from TX"));
        strUsage += AllowedArgs::HelpMessageOpt("in=TXID:VOUT", _("Add input to TX"));
        strUsage += AllowedArgs::HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
        strUsage += AllowedArgs::HelpMessageOpt("nversion=N", _("Set TX version to N"));
        strUsage += AllowedArgs::HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
        strUsage += AllowedArgs::HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
        strUsage += AllowedArgs::HelpMessageOpt("outscript=VALUE:SCRIPT", _("Add raw script output to TX"));
        strUsage += AllowedArgs::HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
            _("This command requires JSON registers:") +
            _("prevtxs=JSON object") + ", " +
            _("privatekeys=JSON object") + ". " +
            _("See signrawtransaction docs for format of sighash flags, JSON objects."));
        fprintf(stdout, "%s", strUsage.c_str());

        strUsage = AllowedArgs::HelpMessageGroup(_("Register Commands:"));
        strUsage += AllowedArgs::HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
        strUsage += AllowedArgs::HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
        fprintf(stdout, "%s", strUsage.c_str());

        return false;
    }
    return true;
}
Beispiel #19
0
HRESULT STDMETHODCALLTYPE CProvider::GetCommitMessage2( 
	/* [in] */ HWND hParentWnd,
	/* [in] */ BSTR parameters,
	/* [in] */ BSTR commonURL,
	/* [in] */ BSTR commonRoot,
	/* [in] */ SAFEARRAY * pathList,
	/* [in] */ BSTR originalMessage,
	/* [retval][out] */ BSTR *newMessage)
{
	USES_CONVERSION;

	if (commonURL)
	{
		// do something with the common root url
		// if necessary
	}

	parameters_t params = ParseParameters(parameters);
	CString commandLine = params[CString("CommandLine")];

	if (commandLine.IsEmpty())
	{
		MessageBox(hParentWnd, _T("CommandLine parameter is empty"), _T("ExampleAtlPlugin"), MB_OK | MB_ICONERROR);
		return S_OK;
	}

	TCHAR szTempPath[MAX_PATH];
	GetTempPath(ARRAYSIZE(szTempPath), szTempPath);

	// Create a temporary file to hold the path list, and write the list to the file.
	TCHAR szPathListTempFile[MAX_PATH];
	GetTempFileName(szTempPath, _T("svn"), 0, szPathListTempFile);

	DWORD bytesWritten;
	HANDLE hPathListFile = CreateFile(szPathListTempFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);

	LONG a, b;
	if (FAILED(SafeArrayGetLBound(pathList, 1, &a)) || (FAILED(SafeArrayGetUBound(pathList, 1, &b))))
		return E_FAIL;

	for (LONG i = a; i <= b; ++i)
	{
		BSTR path = NULL;
		SafeArrayGetElement(pathList, &i, &path);

		CStringA line = OLE2A(path);
		line += "\r\n";

		WriteFile(hPathListFile, line, line.GetLength(), &bytesWritten, NULL);
	}

	CloseHandle(hPathListFile);

	TCHAR szOriginalMessageTempFile[MAX_PATH];
	GetTempFileName(szTempPath, _T("svn"), 0, szOriginalMessageTempFile);

	HANDLE hOriginalMessageFile = CreateFile(szOriginalMessageTempFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);

	CStringA temp = OLE2A(originalMessage);
	WriteFile(hOriginalMessageFile, temp, temp.GetLength(), &bytesWritten, NULL);

	CloseHandle(hOriginalMessageFile);

	commandLine.AppendFormat(_T(" \"%s\" \"%ls\" \"%s\""), szPathListTempFile, commonRoot, szOriginalMessageTempFile);

	CString message = originalMessage;
	CWaitDialog dlg(commandLine);
	if (dlg.DoModal() == IDOK)
	{
		HANDLE hOrig = CreateFile(szOriginalMessageTempFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
		DWORD cb = GetFileSize(hOrig, NULL);
		BYTE *buffer = (BYTE *)malloc(cb + 1);
		memset(buffer, 0, cb + 1);
		DWORD bytesRead;
		ReadFile(hOrig, buffer, cb, &bytesRead, NULL);
		CloseHandle(hOrig);

		message = A2T((const char *)buffer);
	}

	DeleteFile(szPathListTempFile);
	DeleteFile(szOriginalMessageTempFile);

	*newMessage = message.AllocSysString();
	return S_OK;
}
Beispiel #20
0
HRESULT ScalingEffect::LoadEffect(const TCHAR *filename)
{
    KillThis();

    LPD3DXBUFFER		lpBufferEffect = 0;
    LPD3DXBUFFER		lpErrors = 0;
    LPD3DXEFFECTCOMPILER	lpEffectCompiler = 0;

    m_strErrors += filename;
    m_strErrors += ":\n";

    // First create an effect compiler
    HRESULT hr = D3DXCreateEffectCompilerFromFile(filename, NULL, NULL,NULL,
						&lpEffectCompiler, &lpErrors);
	
    // Errors...
    if(FAILED(hr)) {
	if(lpErrors) {
	    m_strErrors += (char*) lpErrors->GetBufferPointer();
	    SAFE_RELEASE(lpErrors);
	}

	m_strErrors += "Unable to create effect compiler from ";
	m_strErrors += filename;
    }

    if(SUCCEEDED(hr)) {
#ifdef C_D3DSHADERS_COMPILE_WITH_DEBUG
	hr = lpEffectCompiler->CompileEffect(D3DXSHADER_DEBUG, &lpBufferEffect, &lpErrors);
#else
	hr = lpEffectCompiler->CompileEffect(0, &lpBufferEffect, &lpErrors);
#endif
	
	// Errors...
	if(FAILED(hr)) {
	    if(lpErrors) {
		m_strErrors += (char*) lpErrors->GetBufferPointer();
		SAFE_RELEASE(lpErrors);
	    }

	    m_strErrors += "Unable to compile effect from ";
	    m_strErrors += filename;
	}
    }

    if(SUCCEEDED(hr)) {
	hr = D3DXCreateEffect(m_pd3dDevice,
			    lpBufferEffect->GetBufferPointer(),
			    lpBufferEffect->GetBufferSize(),
			    NULL, NULL,
			    0,
			    NULL, &m_pEffect, &lpErrors);

	// Errors...
	if(FAILED(hr)) {
	    if(lpErrors) {
		m_strErrors += (char*) lpErrors->GetBufferPointer();
		SAFE_RELEASE(lpErrors);
	    }

	    m_strErrors += "Unable to create effect from compiled ";
	    m_strErrors += filename;
	}
    }

    if(SUCCEEDED(hr)) {
        m_pEffect->GetDesc(&m_EffectDesc);
	hr = ParseParameters(lpEffectCompiler);
    }

    SAFE_RELEASE(lpErrors);
    SAFE_RELEASE(lpBufferEffect);
    SAFE_RELEASE(lpEffectCompiler);
    return hr;
}
Beispiel #21
0
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;
    boost::thread* detectShutdownThread = NULL;

    bool fRet = false;

    //
    // Parameters
    //
    // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
    ParseParameters(argc, argv);

    // Process help and version before taking care about datadir
    if (mapArgs.count("-?") || mapArgs.count("-h") ||  mapArgs.count("-help") || mapArgs.count("-version"))
    {
        std::string strUsage = _("Florincoin Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n";

        if (mapArgs.count("-version"))
        {
            strUsage += LicenseInfo();
        }
        else
        {
            strUsage += "\n" + _("Usage:") + "\n" +
                  "  florincoind [options]                     " + _("Start Florincoin Core Daemon") + "\n";

            strUsage += "\n" + HelpMessage(HMM_BITCOIND);
        }

        fprintf(stdout, "%s", strUsage.c_str());
        return false;
    }

    try
    {
        if (!boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
            return false;
        }
        try
        {
            ReadConfigFile(mapArgs, mapMultiArgs);
        } catch(std::exception &e) {
            fprintf(stderr,"Error reading configuration file: %s\n", e.what());
            return false;
        }
        // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
        if (!SelectParamsFromCommandLine()) {
            fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
            return false;
        }

        // Command-line RPC
        bool fCommandLine = false;
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "florincoin:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            fprintf(stderr, "Error: There is no RPC client functionality in florincoind anymore. Use the florincoin-cli utility instead.\n");
            exit(1);
        }
#ifndef WIN32
        fDaemon = GetBoolArg("-daemon", false);
        if (fDaemon)
        {
            fprintf(stdout, "Florincoin server starting\n");

            // Daemonize
            pid_t pid = fork();
            if (pid < 0)
            {
                fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
                return false;
            }
            if (pid > 0) // Parent process, pid is child process id
            {
                return true;
            }
            // Child process falls through to rest of initialization

            pid_t sid = setsid();
            if (sid < 0)
                fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
        }
#endif
        SoftSetBoolArg("-server", true);

        detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
        fRet = AppInit2(threadGroup);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "AppInit()");
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInit()");
    }

    if (!fRet)
    {
        if (detectShutdownThread)
            detectShutdownThread->interrupt();

        threadGroup.interrupt_all();
        // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
        // the startup-failure cases to make sure they don't result in a hang due to some
        // thread-blocking-waiting-for-another-thread-during-startup case
    }

    if (detectShutdownThread)
    {
        detectShutdownThread->join();
        delete detectShutdownThread;
        detectShutdownThread = NULL;
    }
    Shutdown();

    return fRet;
}
Beispiel #22
0
// Main program
int main(int argc, char** argv) {

    // Overall program timer
    auto overallstart = std::chrono::steady_clock::now();

    // Print program header
    std::cout<<std::endl;
    std::cout<<"PGURE-SVT Denoising"<<std::endl;
    std::cout<<"Author: Tom Furnival"<<std::endl;
    std::cout<<"Email:  [email protected]"<<std::endl<<std::endl;
    std::cout<<"Version 0.3.0 - April 2016"<<std::endl<<std::endl;

    /////////////////////////////
    //                           //
    //    PARAMETER IMPORT     //
    //                           //
    /////////////////////////////

    // Read in the parameter file name
    if( argc != 2) {
        std::cout<<"  Usage: ./PGURE-SVT paramfile"<<std::endl;
        return -1;
    }
    std::map<std::string, std::string> programOptions;
    std::ifstream paramFile(argv[1], std::ios::in);

    // Parse the parameter file
    ParseParameters(paramFile, programOptions);

    // Check all required parameters are specified
    if(programOptions.count("filename") == 0 || programOptions.count("start_image") == 0 || programOptions.count("end_image") == 0) {
        std::cout<<"**WARNING** Required parameters not specified"<<std::endl;
        std::cout<<"            You must specify filename, start and end frame"<<std::endl;
        return -1;
    }

    // Extract parameters
    // File path
    std::string filename = programOptions.at("filename");
    int lastindex = filename.find_last_of(".");
    std::string filestem = filename.substr(0, lastindex);

    // Frames to process
    int startimg = std::stoi(programOptions.at("start_image"));
    int endimg = std::stoi(programOptions.at("end_image"));
    int num_images = endimg - startimg + 1;

    // Move onto optional parameters
    // Patch size and trajectory length
    // Check sizes to ensure SVD is done right way round
    int Bs = (programOptions.count("patch_size") == 1) ? std::stoi(programOptions.at("patch_size")) : 4;
    //int Overlap = (programOptions.count("patch_overlap") == 1) ? std::stoi(programOptions.at("patch_overlap")) : 1;
    int T = (programOptions.count("trajectory_length") == 1) ? std::stoi(programOptions.at("trajectory_length")) : 15;
    T = (Bs*Bs<T) ? (Bs*Bs)-1 : T;
    std::string casoratisize = std::to_string(Bs*Bs) + "x" + std::to_string(T);

    // Noise parameters initialized at -1 unless user-defined
    double alpha = (programOptions.count("alpha") == 1) ? std::stod(programOptions.at("alpha")) : -1.;
    double mu = (programOptions.count("mu") == 1) ? std::stod(programOptions.at("mu")) : -1.;
    double sigma = (programOptions.count("sigma") == 1) ? std::stod(programOptions.at("sigma")) : -1.;

    // SVT thresholds and noise parameters initialized at -1 unless user-defined
    bool pgureOpt = (programOptions.count("pgure") == 1) ? strToBool(programOptions.at("pgure")) : true;
    double lambda;
    if(!pgureOpt) {
        if(programOptions.count("lambda") == 1) {
            lambda = std::stod(programOptions.at("lambda"));
        }
        else {
            std::cout<<"**WARNING** PGURE optimization is turned OFF but no lambda specified in parameter file"<<std::endl;
            return -1;
        }
    }

    // Move onto advanced parameters
    // Motion neigbourhood size
    int MotionP = (programOptions.count("motion_neighbourhood") == 1) ? std::stoi(programOptions.at("motion_neighbourhood")) : 7;

    // Size of median filter
    int MedianSize = (programOptions.count("median_filter") == 1) ? std::stoi(programOptions.at("median_filter")) : 5;

    // PGURE tolerance
    double tol = 1E-7;
    if(programOptions.count("tolerance") == 1) {
        std::istringstream osTol(programOptions.at("tolerance"));
        double tol;
        osTol >> tol;
    }
Beispiel #23
0
/*********************************
* main - this is where it begins
*********************************/
int main(int argc, char **argv)
{
  std::cout << "********************************************" << std::endl;
  std::cout << "*** Xolominer - Primecoin Pool Miner v" << VERSION_MAJOR << "." << VERSION_MINOR << " " << VERSION_EXT << std::endl;
  std::cout << "*** by xolokram/TB - www.beeeeer.org - glhf" << std::endl;
  std::cout << "***" << std::endl;
  std::cout << "*** thx to Sunny King & mikaelh" << std::endl;
  std::cout << "*** press CTRL+C to exit" << std::endl;
  std::cout << "********************************************" << std::endl;

  t_start = boost::posix_time::second_clock::universal_time();
  running = true;

#if defined(__MINGW32__) || defined(__MINGW64__)
  SetConsoleCtrlHandler(ctrl_handler, TRUE);
#elif defined(__GNUG__)
  set_signal_handler(SIGINT, ctrl_handler);
#endif //TODO: __APPLE__

  if (argc < 2)
  {
    std::cerr << "usage: " << argv[0] <<
    " -poolfee=<fee-in-%> -poolip=<ip> -poolport=<port> -pooluser=<user> -poolpassword=<password>" <<
    std::endl;
    return EXIT_FAILURE;
  }

  const int atexit_res = std::atexit(exit_handler);
  if (atexit_res != 0)
    std::cerr << "atexit registration failed, shutdown will be dirty!" << std::endl;

  // init everything:
  ParseParameters(argc, argv);

  socket_to_server = NULL;
  pool_share_minimum = (unsigned int)GetArg("-poolshare", 7);
  thread_num_max = GetArg("-genproclimit", 1); // what about boost's hardware_concurrency() ?
  fee_to_pay = GetArg("-poolfee", 3);
  miner_id = GetArg("-minerid", 0);

  if (thread_num_max == 0 || thread_num_max > MAX_THREADS)
  {
    std::cerr << "usage: " << "current maximum supported number of threads = " << MAX_THREADS << std::endl;
    return EXIT_FAILURE;
  }

  if (fee_to_pay == 0 || fee_to_pay > 100)
  {
    std::cerr << "usage: " << "please use a pool fee between [1 , 100]" << std::endl;
    return EXIT_FAILURE;
  }

  if (miner_id > 65535)
  {
    std::cerr << "usage: " << "please use a miner id between [0 , 65535]" << std::endl;
    return EXIT_FAILURE;
  }

  fPrintToConsole = true; // always on
  fDebug          = GetBoolArg("-debug");

  pindexBest = new CBlockIndex();

  GeneratePrimeTable();

  // ok, start mining:
  CBlockProviderGW* bprovider = new CBlockProviderGW();
  CMasterThread *mt = new CMasterThread(bprovider);
  mt->run();

  // end:
  return EXIT_SUCCESS;
}
Beispiel #24
0
int main(int argc, char *argv[])
{
    // Do this early as we don't want to bother initializing if we are just calling IPC
    for (int i = 1; i < argc; i++)
    {
        if (strlen(argv[i]) > 8 && strncasecmp(argv[i], "bitshekel:", 9) == 0)
        {
            const char *strURL = argv[i];
            try {
                boost::interprocess::message_queue mq(boost::interprocess::open_only, "BitcoinURL");
                if(mq.try_send(strURL, strlen(strURL), 0))
                    exit(0);
                else
                    break;
            }
            catch (boost::interprocess::interprocess_exception &ex) {
                break;
            }
        }
    }

    // Internal string conversion is all UTF-8
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());

    Q_INIT_RESOURCE(bitcoin);
    QApplication app(argc, argv);

    // Command-line options take precedence:
    ParseParameters(argc, argv);

    // ... then bitcoin.conf:
    if (!ReadConfigFile(mapArgs, mapMultiArgs))
    {
        fprintf(stderr, "Error: Specified directory does not exist\n");
        return 1;
    }

    // Application identification (must be set before OptionsModel is initialized,
    // as it is used to locate QSettings)
    app.setOrganizationName("Bitcoin");
    app.setOrganizationDomain("bitcoin.org");
    if(GetBoolArg("-testnet")) // Separate UI settings for testnet
        app.setApplicationName("Bitshekel-Qt-testnet");
    else
        app.setApplicationName("Bitshekel-Qt");

    // ... then GUI settings:
    OptionsModel optionsModel;

    // Get desired locale ("en_US") from command line or system locale
    QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
    // Load language files for configured locale:
    // - First load the translator for the base language, without territory
    // - Then load the more specific locale translator
    QString lang = lang_territory;

    lang.truncate(lang_territory.lastIndexOf('_')); // "en"
    QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;

    qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
    if (!qtTranslatorBase.isEmpty())
        app.installTranslator(&qtTranslatorBase);

    qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
    if (!qtTranslator.isEmpty())
        app.installTranslator(&qtTranslator);

    translatorBase.load(":/translations/"+lang);
    if (!translatorBase.isEmpty())
        app.installTranslator(&translatorBase);

    translator.load(":/translations/"+lang_territory);
    if (!translator.isEmpty())
        app.installTranslator(&translator);

    QSplashScreen splash(QPixmap(":/images/splash"), 0);
    if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
    {
        splash.show();
        splash.setAutoFillBackground(true);
        splashref = &splash;
    }

    app.processEvents();

    app.setQuitOnLastWindowClosed(false);

    try
    {
        if(AppInit2(argc, argv))
        {
            {
                // Put this in a block, so that BitcoinGUI is cleaned up properly before
                // calling Shutdown() in case of exceptions.

                optionsModel.Upgrade(); // Must be done after AppInit2

                BitcoinGUI window;
                if (splashref)
                    splash.finish(&window);

                ClientModel clientModel(&optionsModel);
                WalletModel walletModel(pwalletMain, &optionsModel);

                guiref = &window;
                window.setClientModel(&clientModel);
                window.setWalletModel(&walletModel);

                // If -min option passed, start window minimized.
                if(GetBoolArg("-min"))
                {
                    window.showMinimized();
                }
                else
                {
                    window.show();
                }

                // Place this here as guiref has to be defined if we dont want to lose URLs
                ipcInit();
                // Check for URL in argv
                for (int i = 1; i < argc; i++)
                {
                    if (strlen(argv[i]) > 8 && strncasecmp(argv[i], "bitshekel:", 9) == 0)
                    {
                        const char *strURL = argv[i];
                        try {
                            boost::interprocess::message_queue mq(boost::interprocess::open_only, "BitcoinURL");
                            mq.try_send(strURL, strlen(strURL), 0);
                        }
                        catch (boost::interprocess::interprocess_exception &ex) {
                        }
                    }
                }

                app.exec();

                guiref = 0;
            }
            Shutdown(NULL);
        }
        else
        {
            return 1;
        }
    } catch (std::exception& e) {
        handleRunawayException(&e);
    } catch (...) {
        handleRunawayException(NULL);
    }
    return 0;
}
Beispiel #25
0
//
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
//
static int AppInitRawTx(int argc, char* argv[])
{
    //
    // Parameters
    //
    ParseParameters(argc, argv);

    // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
    try {
        SelectParams(ChainNameFromCommandLine());
    } catch (const std::exception& e) {
        fprintf(stderr, "Error: %s\n", e.what());
        return EXIT_FAILURE;
    }

    fCreateBlank = GetBoolArg("-create", false);

    if (argc<2 || mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help"))
    {
        // First part of help message is specific to this utility
        std::string strUsage = strprintf(_("%s bitcoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +
            _("Usage:") + "\n" +
              "  bitcoin-tx [options] <hex-tx> [commands]  " + _("Update hex-encoded bitcoin transaction") + "\n" +
              "  bitcoin-tx [options] -create [commands]   " + _("Create hex-encoded bitcoin transaction") + "\n" +
              "\n";

        fprintf(stdout, "%s", strUsage.c_str());

        strUsage = HelpMessageGroup(_("Options:"));
        strUsage += HelpMessageOpt("-?", _("This help message"));
        strUsage += HelpMessageOpt("-create", _("Create new, empty TX."));
        strUsage += HelpMessageOpt("-json", _("Select JSON output"));
        strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
        AppendParamsHelpMessages(strUsage);

        fprintf(stdout, "%s", strUsage.c_str());

        strUsage = HelpMessageGroup(_("Commands:"));
        strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX"));
        strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX"));
        strUsage += HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX"));
        strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
        strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N"));
        strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
        strUsage += HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
        strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT", _("Add raw script output to TX"));
        strUsage += HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
            _("This command requires JSON registers:") +
            _("prevtxs=JSON object") + ", " +
            _("privatekeys=JSON object") + ". " +
            _("See signrawtransaction docs for format of sighash flags, JSON objects."));
        fprintf(stdout, "%s", strUsage.c_str());

        strUsage = HelpMessageGroup(_("Register Commands:"));
        strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
        strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
        fprintf(stdout, "%s", strUsage.c_str());

        if (argc < 2) {
            fprintf(stderr, "Error: too few parameters\n");
            return EXIT_FAILURE;
        }
        return EXIT_SUCCESS;
    }
    return CONTINUE_EXECUTION;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;

    bool fRet = false;
    try
    {
        //
        // Parameters
        //
        // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
        ParseParameters(argc, argv);
        if (!boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified directory does not exist\n");
            Shutdown();
        }
        ReadConfigFile(mapArgs, mapMultiArgs);

        if (mapArgs.count("-?") || mapArgs.count("--help"))
        {
            // First part of help message is specific to bitcoind / RPC client
            std::string strUsage = _("FlappyCoin version") + " " + FormatFullVersion() + "\n\n" +
                _("Usage:") + "\n" +
                  "  FlappyCoind [options]                     " + "\n" +
                  "  FlappyCoind [options] <command> [params]  " + _("Send command to -server or FlappyCoind") + "\n" +
                  "  FlappyCoind [options] help                " + _("List commands") + "\n" +
                  "  FlappyCoind [options] help <command>      " + _("Get help for a command") + "\n";

            strUsage += "\n" + HelpMessage();

            fprintf(stdout, "%s", strUsage.c_str());
            return false;
        }

        // Command-line RPC
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "FlappyCoin:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            if (!SelectParamsFromCommandLine()) {
                fprintf(stderr, "Error: invalid combination of -regtest and -testnet.\n");
                return false;
            }
            int ret = CommandLineRPC(argc, argv);
            exit(ret);
        }
#if !defined(WIN32)
        fDaemon = GetBoolArg("-daemon", false);
        if (fDaemon)
        {
            // Daemonize
            pid_t pid = fork();
            if (pid < 0)
            {
                fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
                return false;
            }
            if (pid > 0) // Parent process, pid is child process id
            {
                CreatePidFile(GetPidFile(), pid);
                return true;
            }
            // Child process falls through to rest of initialization

            pid_t sid = setsid();
            if (sid < 0)
                fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
        }
#endif

        fRet = AppInit2(threadGroup);
    }
    catch (std::exception& e) {
        PrintException(&e, "AppInit()");
    } catch (...) {
        PrintException(NULL, "AppInit()");
    }

    if (!fRet)
    {
        threadGroup.interrupt_all();
        // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
        // the startup-failure cases to make sure they don't result in a hang due to some
        // thread-blocking-waiting-for-another-thread-during-startup case
    } else {
        WaitForShutdown(&threadGroup);
    }
    Shutdown();

    return fRet;
}
Beispiel #27
0
int main (int argc, char **argv)
{
    setlocale (LC_ALL, "");

    if (!ParseParameters(argc, argv))
        return -1;

    // load database
    lfDatabase *ldb = new lfDatabase ();

    if (ldb->Load () != LF_NO_ERROR) {
        ldb->Destroy();
        g_print ("\rERROR: Database could not be loaded\n");
        return -1;
    }

    // try to find camera in the database
    const lfCamera *cam = NULL;
    if (opts.Camera) {
        const lfCamera ** cameras = ldb->FindCamerasExt(NULL, opts.Camera);
        if (cameras)
            cam = cameras[0];
        else
            g_print ("Cannot find a camera matching `%s' in database\n", opts.Camera);
        lf_free (cameras);
     }

    // try to find a matching lens in the database
    const lfLens *lens = NULL;
    if (opts.Lens) {
        const lfLens **lenses = ldb->FindLenses (cam, NULL, opts.Lens);
        if (lenses)
            lens = lenses [0];
        else
            g_print ("Cannot find a lens matching `%s' in database\n", opts.Lens);
        lf_free (lenses);
    }

    // print camera and lens information if in verbose mode or if no input file is specified
    if (opts.Verbose || !opts.Input) {
        if (cam && lens) {
            g_print("Matching lens and camera combination found in the database:\n");
            PrintCamera(cam, ldb);
            PrintLens(lens, ldb);
        } else if (!cam && lens) {
            g_print("Matching lens found in the database:\n");
            PrintLens(lens, ldb);
        } else if (!lens && cam) {
            g_print("Matching camera found in the database:\n");
            PrintCamera(cam, ldb);
        }
    } else {
        if (cam && lens) {
            g_print("= Selecting %s / %s\n", cam->Model, lens->Model);
        } else if (!cam && lens) {
            g_print("= Selecting %s\n", lens->Model);
        }
    }

    // nothing to process, so lets quit here
    if (!opts.Input) {
        ldb->Destroy();
        return 0;
    }

    // assume standard values if parameters are not specified
    if (cam)
        opts.Crop = cam->CropFactor;
    else if (!opts.Crop)
        opts.Crop = lens->CropFactor;    
    if (!opts.Focal)
        opts.Focal = lens->MinFocal;
    if (!opts.Aperture)
        opts.Aperture = lens->MinAperture;

    if (opts.Verbose) {
        g_print("\nProcessing parameters:\n"
                "    |- Image crop factor: %g\n"
                "    |- Focal length: %gmm\n"
                "    |- Aperture: f/%g\n"
                "    |- Distance: %gm\n\n",
                opts.Crop, opts.Focal, opts.Aperture, opts.Distance);
    } else {
        g_print("= Processing parameters: Crop %g, Focal %gmm, Aperture f/%g, Distance: %gm\n",
                opts.Crop, opts.Focal, opts.Aperture, opts.Distance);
    }

    Image *img = new Image ();
    g_print ("~ Loading `%s' ... ", opts.Input);
    if (!img->Open (opts.Input)) {
        g_print ("\rERROR: failed to open file `%s'\n", opts.Input);
        delete img;
        ldb->Destroy();
        return -1;
    }
    if (!img->LoadPNG ()) {
        g_print ("\rERROR: failed to parse PNG data from file `%s'\n", opts.Input);
        delete img;
        ldb->Destroy();
        return -1;
    }
    g_print ("done.\n~ Image size [%ux%u].\n", img->width, img->height);

    lfModifier *mod = lfModifier::Create (lens, opts.Crop, img->width, img->height);
    if (!mod) {
        g_print ("\rWarning: failed to create modifier\n");
        delete img;
        ldb->Destroy();
        return -1;
    }
    int modflags = mod->Initialize (
        lens, LF_PF_U8, opts.Focal,
        opts.Aperture, opts.Distance, opts.Scale, opts.TargetGeom,
        opts.ModifyFlags, opts.Inverse);

    g_print("~ Selected modifications: ");
    if (modflags & LF_MODIFY_TCA)
        g_print ("[tca]");
    if (modflags & LF_MODIFY_VIGNETTING)
        g_print ("[vign]");
    if (modflags & LF_MODIFY_DISTORTION)
        g_print ("[dist]");
    if (modflags & LF_MODIFY_GEOMETRY)
        g_print ("[geom]");
    if (opts.Scale != 1.0)
        g_print ("[scale]");
    if (modflags==0)
        g_print ("[NOTHING]");
    g_print ("\n");

    g_print("~ Run processing chain... ");

    clock_t st;
    clock_t xt = clock ();
    while (xt == (st = clock ()))
        ;

    img = ApplyModifier (modflags, opts.Inverse, img, mod);

    clock_t et = clock ();
    g_print ("done (%.3g secs)\n", double (et - st) / CLOCKS_PER_SEC);

    mod->Destroy ();

    g_print ("~ Save output as `%s'...", opts.Output);
    bool ok = img->SavePNG (opts.Output);

    delete img;
    ldb->Destroy ();

    if (ok) {
        g_print (" done\n");
        return 0;
    } else {
        g_print (" FAILED\n");
        return -1;
    }

}