Exemplo n.º 1
0
void COption::parse(int argc, char *argv[]) {
	int opt = 0;
	while ((opt = getopt_long(argc, argv, option_str, opts, NULL)) != -1) {
		switch (opt) {
			case 'h':
				displayUsage(argv[0]);
				exit(0);
				break;
			case 's':
				m_stop = true;
				break;
			case 'f':
				m_configFile = optarg;
				break;
			case 'd':
				m_daemon = true;
				break;
			case '?':
				//cout << "unknown" << endl;
				break;
			default:
				displayUsage(argv[0]);
				exit(0);
		}
	}
}
Exemplo n.º 2
0
void performUsage ( int argc, char **argv ) {

	// Argument parsing

	int opt = 0;
	int longIndex = 0;
	
	// Initialize globalArgs before we get to work
	globalArgs.fit = 0;
	globalArgs.tabulate = 0;
	globalArgs.parameters = parametersFile;
	globalArgs.output = outputFile;
	globalArgs.ffdata = dataFile1;
	globalArgs.csdata = dataFile2;

	// Process the arguments with getopt_long()
	
	opt = getopt_long( argc, argv, optString, longOpts, &longIndex );

	while( opt != -1 ) {

		switch( opt ) {
			case 'p':
				globalArgs.parameters = optarg;
				break;
				
			case 'o':
				globalArgs.output = optarg;
				break;
				
			case 'd':
				globalArgs.ffdata = optarg;
				break;

			case 'c':
				globalArgs.csdata = optarg;
				break;
				
			case 'h':
				displayUsage();
				break;
				
			case '?':
				displayUsage();
				break;

			default:
				//displayUsage();
				break;
		}
		
		opt = getopt_long( argc, argv, optString, longOpts, &longIndex );
	}
	if ( val==1 ) { globalArgs.fit = 1; }
	if ( tab==1 ) { globalArgs.tabulate = 1; }
	if ( deb==1 ) { globalArgs.verbose = 1; }
	
}
Exemplo n.º 3
0
void
Builder::displayHelp()
{
    if ( genericHelpRequested() )
    {
        if ( m_parent == NULL )
        {
            displayUsage( m_progname );
        }

        displayGenericHelp();

        for ( std::list< Builder * >::iterator i = m_children.begin();
              i != m_children.end();
              ++i )
        {
            (*i)->displayGenericHelp();
        }

        if ( detailedHelpRequested() )
        {
            displayDetailedHelp();
        }

        for ( std::list< Builder * >::iterator i = m_children.begin();
              i != m_children.end();
              ++i )
        {
            if ( (*i)->detailedHelpRequested() )
            {
                (*i)->displayDetailedHelp();
            }
        }
    }
}
Exemplo n.º 4
0
/* =============================================================================
 * parseArgs
 * =============================================================================
 */
static void
parseArgs (long argc, char* const argv[])
{
    long i;
    long opt;

    opterr = 0;

    while ((opt = getopt(argc, argv, "a:i:t:")) != -1) {
        switch (opt) {
            case 'a':
                global_angleConstraint = atof(optarg);
                break;
            case 'i':
                global_inputPrefix = optarg;
                break;
            case 't':
                global_numThread = atol(optarg);
                break;
            case '?':
            default:
                opterr++;
                break;
        }
    }

    for (i = optind; i < argc; i++) {
        fprintf(stderr, "Non-option argument: %s\n", argv[i]);
        opterr++;
    }

    if (opterr) {
        displayUsage(argv[0]);
    }
}
Exemplo n.º 5
0
/* =============================================================================
 * parseArgs
 * =============================================================================
 */
static void
parseArgs (long argc, char* const argv[])
{
    long i;
    long opt;

    opterr = 0;

    setDefaultParams();

    while ((opt = getopt(argc, argv, "g:n:s:t:")) != -1) {
        switch (opt) {
            case 'g':
            case 'n':
            case 's':
            case 't':
                global_params[(unsigned char)opt] = atol(optarg);
                break;
            case '?':
            default:
                opterr++;
                break;
        }
    }

    for (i = optind; i < argc; i++) {
        fprintf(stderr, "Non-option argument: %s\n", argv[i]);
        opterr++;
    }

    if (opterr) {
        displayUsage(argv[0]);
    }
}
Exemplo n.º 6
0
/* For the most basic example of Fudge-C use, see the "simple.c" file that
   should be in the same directory as this one.

   This is a basic "pretty printer" for Fudge-C encoded message files. It
   takes the filename of the message to display and dumps the contents, in
   human readable form, to the standard output.

   Rather than assume a Unicode compatible console, all strings are
   converted in to 7bit ASCII before being output.
*/
int main ( int argc, char * argv [ ] )
{
    FudgeStatus status;
    FudgeMsgEnvelope envelope;
    const char * filename;
    fudge_byte * bytes;
    fudge_i32 numbytes;

    /* Get the filename from the command-line arguments */
    if ( argc != 2 )
        displayUsage ( );
    filename = argv [ 1 ];

    /* Initialise the Fudge library */
    if ( ( status = Fudge_init ( ) ) )
        fatalFudgeError ( status, "Failed to initialise Fudge library" );

    /* Load in the file and attempt to decode it */
    loadFile ( &bytes, &numbytes, filename );
    if ( ( status = FudgeCodec_decodeMsg ( &envelope, bytes, numbytes ) ) )
        fatalFudgeError ( status, "Failed to decode file" );
    free ( bytes );

    /* Output the file contents */
    outputEnvelope ( envelope );
    FudgeMsgEnvelope_release ( envelope );
    return 0;
}
Exemplo n.º 7
0
void QtWindow::decodeCommandLine()
{
    bool hasMidiFile = false;
    QStringList argList = QCoreApplication::arguments();
    QString arg;
    for (int i = 0; i < argList.size(); ++i)
    {
        arg = argList[i];
        if (arg.startsWith("-"))
        {
            if (arg.startsWith("-d"))
                Cfg::logLevel++;
            else if (arg.startsWith("-q"))
                Cfg::quickStart = true;
            else if (arg.startsWith("-X1"))
                Cfg::experimentalTempo = true;
            else if (arg.startsWith("-Xswap"))
                Cfg::experimentalSwapInterval = decodeIntegerParam(arg, 100);

            else if (arg.startsWith("-h") || arg.startsWith("-?") ||arg.startsWith("--help"))
            {
                displayUsage();
                exit(0);
            }
            else if (arg.startsWith("-v"))
            {
                fprintf(stderr, "pianobooster Version " PB_VERSION"\n");
                exit(0);
            }
            else
            {
                fprintf(stderr, "ERROR: Unknown arguments \n");
                displayUsage();
                exit(0);
            }
        }
        else {
            if ( hasMidiFile == false && i > 0)
            {
                hasMidiFile = true;
                decodeMidiFileArg(arg);
            }
        }
    }
}
Exemplo n.º 8
0
int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        displayUsage();
        return 1;
    }

    unsigned short port =
        static_cast<unsigned short>(strtoul(argv[2], NULL, 10));

    s_shutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (s_shutdownEvent == NULL)
    {
        return 1;
    }

    if (!SetConsoleCtrlHandler(&consoleCtrlHandler, TRUE))
    {
        return 1;
    }

    // Startup the communication library
    int err = CLStartup();
    if (err != CL_ERR_OK)
    {
        std::cout << "\r\nCLStartup() failed, err=" << err << "\r\n" <<
            std::flush;
        return 1;
    }

    // Create the listening socket
    CLSrvSocket srvSkt = 0;
    err = CLCreateSrvSocket(argv[1], port, conPending, srvSocketClosed, 200,
        NULL, &srvSkt);
    if (err == CL_ERR_OK)
    {
        static const DWORD DISPLAY_INTERVAL = 5 * 60 * 1000; // 5 mins
        while (WaitForSingleObject(s_shutdownEvent, DISPLAY_INTERVAL) !=
            WAIT_OBJECT_0)
        {
            s_metrics.displayMetrics();
        }
    }
    else
    {
        std::cout << "\r\nCLCreateSrvSocket() failed, err=" << err << "\r\n" <<
            std::flush;
    }

    // Cleanup the communication library
    CLCleanup();

    s_metrics.displayMetrics();
    return 0;
}
Exemplo n.º 9
0
/* =============================================================================
 * parseArgs
 * =============================================================================
 */
static void
parseArgs (long argc, char* const argv[])
{
    long i;
    long opt;

    opterr = 0;

    setDefaultParams();

    while ((opt = getopt(argc, argv, "c:n:q:r:t:u:ALTX:Z:")) != -1) {
        switch (opt) {
            case 'c':
            case 'n':
            case 'q':
            case 'r':
            case 't':
            case 'u':
                global_params[(unsigned char)opt] = atol(optarg);
                break;
	    case 'A':
		setAdaptMode(0);
		break;
	    case 'L':
		setAdaptMode(-1);
		break;
	    case 'T':
		setAdaptMode(1);
		break;
	    case 'X':
		setTranxOvhd(atof(optarg));
		break;
	    case 'Z':
		setTranxInstr(atoi(optarg),atoi(optarg)*2);
		break;
	    case '?':
            default:
                opterr++;
                break;
        }
    }

    for (i = optind; i < argc; i++) {
        fprintf(stderr, "Non-option argument: %s\n", argv[i]);
        opterr++;
    }

    if (opterr) {
        displayUsage(argv[0]);
    }

}
Exemplo n.º 10
0
void decrypt7(const std::vector<std::string *> arguments)
{
	if (arguments.size() != 5)
	{
		displayUsage();
		return;
	}

	std::string &databaseFilename = *arguments[2];
	std::string &keyFilename = *arguments[3];
	std::string &outputFilename = *arguments[4];
	decryptWhatsappDatabase7(databaseFilename, outputFilename, keyFilename);
}
Exemplo n.º 11
0
int main(int argc, char *argv[]) {
    int day = 0;
    int month = 0;
    int year = 0;

    if (argc == 2) {
        if (strcmp(argv[1], "-t") == EQUAL) {
            runTests();
        } else {
            displayUsage();
        }
    } else if (argc == 3) {
        if (strcmp(argv[1], "-l") == EQUAL) {
            year = atoi(argv[2]);
            printf("%d is ", year);
            if (!isLeapYear(year))
                printf("not ");
            printf("a leap year.\n");
        } else if (strcmp(argv[1], "-d") == EQUAL) {
            year = atoi(argv[2]);
            printf("The doomsday for %d is %s.\n", year, getDayName(getDoomsday(year)));
        } else {
            displayUsage();
        }
    } else if (argc == 4) {
        day = atoi(argv[1]);
        month = atoi(argv[2]);
        year = atoi(argv[3]);

        printf("%d %d %d\n", day, month, year);
        printf("%s\n", getDayName(getDayOfWeek(day, month, year)));
    } else {
        displayUsage();
    }

    return EXIT_SUCCESS;
}
Exemplo n.º 12
0
int main(int argc, char** argv)
{
	m::system::Log::registerDefaultLogImpl();
	m::system::Log log("", m::LOG_INFO);
	log() << " Haize v" << HAIZE_VERSION << ", a C++ Script Language " << m::endl;
	log() << " Copyright (C) 2015-2016 Louis Schnellbach" << m::endl
		<< m::endl;

	if (parseArguments(argc, argv))
	{
		executeProgram();
	}
	else
	{
		displayUsage();
	}

	leave(0);
}
Exemplo n.º 13
0
/* =============================================================================
 * parseArgs
 * =============================================================================
 */
static void
parseArgs (long argc, char* const argv[])
{
    long i;
    long opt;

    opterr = 0;

    setDefaultParams();

    while ((opt = getopt(argc, argv, "b:i:pt:x:y:z:")) != -1) {
        switch (opt) {
            case 'b':
            case 't':
            case 'x':
            case 'y':
            case 'z':
                global_params[(unsigned char)opt] = atol(optarg);
                break;
            case 'i':
                global_inputFile = optarg;
                break;
            case 'p':
                global_doPrint = TRUE;
                break;
            case '?':
            default:
                opterr++;
                break;
        }
    }

    for (i = optind; i < argc; i++) {
        fprintf(stderr, "Non-option argument: %s\n", argv[i]);
        opterr++;
    }

    if (opterr) {
        displayUsage(argv[0]);
    }
}
Exemplo n.º 14
0
int ServiceDaemon::pre_initialize()
{
  //
  // Parse command line options
  //
  parseOptions();

  if (hasOption("daemonize"))
  {
    if (!hasOption("pid-file"))
    {
      std::cerr << "You need to specify a PID file when running as daemon!" << std::endl;
      displayUsage(std::cerr);
      return -1;
    }

    getOption("pid-file", _pidFile);
    OSS::app_set_pid_file(_pidFile);
    daemonize();
  }


  return 0;
}
Exemplo n.º 15
0
// Main
int main(int argc, char *argv[])
{
    // We must save it here because QApplication constructor may change it
    bool isOneArg = (argc == 2);

#ifdef Q_OS_MAC
    // On macOS 10.12 Sierra, Apple changed the behaviour of CFPreferencesSetValue() https://bugreports.qt.io/browse/QTBUG-56344
    // Due to this, we have to move from native plist to IniFormat
    macMigratePlists();
#endif

#ifndef DISABLE_GUI
    migrateRSS();
#endif

    // Create Application
    QString appId = QLatin1String("qBittorrent-") + Utils::Misc::getUserIDString();
    QScopedPointer<Application> app(new Application(appId, argc, argv));

    const QBtCommandLineParameters params = parseCommandLine();

    if (!params.unknownParameter.isEmpty()) {
        displayBadArgMessage(QObject::tr("%1 is an unknown command line parameter.", "--random-parameter is an unknown command line parameter.")
                             .arg(params.unknownParameter));
        return EXIT_FAILURE;
    }

#ifndef Q_OS_WIN
    if (params.showVersion) {
        if (isOneArg) {
            displayVersion();
            return EXIT_SUCCESS;
        }
        else {
            displayBadArgMessage(QObject::tr("%1 must be the single command line parameter.")
                                 .arg(QLatin1String("-v (or --version)")));
            return EXIT_FAILURE;
        }
    }
#endif

    if (params.showHelp) {
        if (isOneArg) {
            displayUsage(argv[0]);
            return EXIT_SUCCESS;
        }
        else {
            displayBadArgMessage(QObject::tr("%1 must be the single command line parameter.")
                                 .arg(QLatin1String("-h (or --help)")));
            return EXIT_FAILURE;
        }
    }

    if ((params.webUiPort > 0) && (params.webUiPort <= 65535)) {
        Preferences::instance()->setWebUiPort(params.webUiPort);
    }
    else {
        displayBadArgMessage(QObject::tr("%1 must specify the correct port (1 to 65535).")
                             .arg(QLatin1String("--webui-port")));
        return EXIT_FAILURE;
    }

    // Set environment variable
    if (!qputenv("QBITTORRENT", QBT_VERSION))
        std::cerr << "Couldn't set environment variable...\n";

#ifndef DISABLE_GUI
    if (!userAgreesWithLegalNotice())
        return EXIT_SUCCESS;
#else
    if (!params.shouldDaemonize
        && isatty(fileno(stdin))
        && isatty(fileno(stdout))
        && !userAgreesWithLegalNotice())
        return EXIT_SUCCESS;
#endif

    // Check if qBittorrent is already running for this user
    if (app->isRunning()) {
#ifdef DISABLE_GUI
        if (params.shouldDaemonize) {
            displayBadArgMessage(QObject::tr("You cannot use %1: qBittorrent is already running for this user.")
                                 .arg(QLatin1String("-d (or --daemon)")));
            return EXIT_FAILURE;
        }
        else
#endif
        qDebug("qBittorrent is already running for this user.");

        Utils::Misc::msleep(300);
        app->sendParams(params.torrents);

        return EXIT_SUCCESS;
    }

#if defined(Q_OS_WIN)
    // This affects only Windows apparently and Qt5.
    // When QNetworkAccessManager is instantiated it regularly starts polling
    // the network interfaces to see what's available and their status.
    // This polling creates jitter and high ping with wifi interfaces.
    // So here we disable it for lack of better measure.
    // It will also spew this message in the console: QObject::startTimer: Timers cannot have negative intervals
    // For more info see:
    // 1. https://github.com/qbittorrent/qBittorrent/issues/4209
    // 2. https://bugreports.qt.io/browse/QTBUG-40332
    // 3. https://bugreports.qt.io/browse/QTBUG-46015

    qputenv("QT_BEARER_POLL_TIMEOUT", QByteArray::number(-1));
#endif

#if defined(Q_OS_MAC)
{
    // Since Apple made difficult for users to set PATH, we set here for convenience.
    // Users are supposed to install Homebrew Python for search function.
    // For more info see issue #5571.
    QByteArray path = "/usr/local/bin:";
    path += qgetenv("PATH");
    qputenv("PATH", path.constData());
}
#endif

#ifndef DISABLE_GUI
    if (!upgrade()) return EXIT_FAILURE;
#else
    if (!upgrade(!params.shouldDaemonize
                 && isatty(fileno(stdin))
                 && isatty(fileno(stdout)))) return EXIT_FAILURE;
#endif

#ifdef DISABLE_GUI
    if (params.shouldDaemonize) {
        app.reset(); // Destroy current application
        if ((daemon(1, 0) == 0)) {
            app.reset(new Application(appId, argc, argv));
            if (app->isRunning()) {
                // Another instance had time to start.
                return EXIT_FAILURE;
            }
        }
        else {
            qCritical("Something went wrong while daemonizing, exiting...");
            return EXIT_FAILURE;
        }
    }
#else
    if (!params.noSplash)
        showSplashScreen();
#endif

#if defined(Q_OS_UNIX) || defined(STACKTRACE_WIN)
    signal(SIGINT, sigNormalHandler);
    signal(SIGTERM, sigNormalHandler);
    signal(SIGABRT, sigAbnormalHandler);
    signal(SIGSEGV, sigAbnormalHandler);
#endif

    return app->exec(params.torrents);
}
Exemplo n.º 16
0
int main(int argc, char *argv[])
{
    ConnectN game;            // game to play

    std::string nString = "";
    std::string rString = "";
    std::string cString = "";

    std::stringstream nConvert;
    std::stringstream rConvert;
    std::stringstream cConvert;

    bool strategySet = false;
    bool difficultySet = false;

    int nValue = 4;
    int rValue = 6;
    int cValue = 7;

    // if no command line args (besides program name), play with defaults
    if (argc == 1) {
        game.playGame();
        return 0;
    }

    // check arg count
    if (argc > 9) {
        std::cout << "Error, invalid command line arguments." << std::endl;
        displayUsage(argv);
        return -1;
    }

    // parse command line
    for (int i = 1; i < argc; i++) {
        if (std::string(argv[i]) == "-help") {
            displayUsage(argv);
            return 0;
        }
        else if (std::string(argv[i]) == "-e") {
            if (!difficultySet) {
                difficultySet = true;
                game.setComputerDifficultyEasy();
            }
            else {
                std::cout << "Error, only one difficulty setting allowed." << std::endl;
                displayUsage(argv);
                return -1;
            }
        }
        else if (std::string(argv[i]) == "-m") {
            if (!difficultySet) {
                difficultySet = true;
                game.setComputerDifficultyMedium();
            }
            else {
                std::cout << "Error, only one difficulty setting allowed." << std::endl;
                displayUsage(argv);
                return -1;
            }
        }
        else if (std::string(argv[i]) == "-h") {
            if (!difficultySet) {
                difficultySet = true;
                game.setComputerDifficultyHard();
            }
            else {
                std::cout << "Error, only one difficulty setting allowed." << std::endl;
                displayUsage(argv);
                return -1;
            }
        }
        else if (std::string(argv[i]) == "-o") {
            if (!strategySet) {
                strategySet = true;
                game.setComputerStrategyOffensive();
            }
            else {
                std::cout << "Error, only one strategy setting allowed." << std::endl;
                displayUsage(argv);
                return -1;
            }
        }
        else if (std::string(argv[i]) == "-d") {
            if (!strategySet) {
                strategySet = true;
                game.setComputerStrategyDefensive();
            }
            else {
                std::cout << "Error, only one strategy setting allowed." << std::endl;
                displayUsage(argv);
                return -1;
            }
        }
        else if (std::string(argv[i]) == "-b") {
            if (!strategySet) {
                strategySet = true;
                game.setComputerStrategyBalanced();
            }
            else {
                std::cout << "Error, only one strategy setting allowed." << std::endl;
                displayUsage(argv);
                return -1;
            }
        }
        else if (std::string(argv[i]) == "-n") {
            if (i != argc - 1) {
                i++;
                nString = argv[i];
            }
            else {
                std::cout << "Error, invalid command line arguments." << std::endl;
                displayUsage(argv);
                return -1;
            }
        }
        else if (std::string(argv[i]) == "-r") {
            if (i != argc - 1) {
                i++;
                rString = argv[i];
            }
            else {
                std::cout << "Error, invalid command line arguments." << std::endl;
                displayUsage(argv);
                return -1;
            }
        }
        else if (std::string(argv[i]) == "-c") {
            if (i != argc - 1) {
                i++;
                cString = argv[i];
            }
            else {
                std::cout << "Error, invalid command line arguments." << std::endl;
                displayUsage(argv);
                return -1;
            }
        }
        else {
            std::cout << "Error, invalid command line arguments." << std::endl;
            return -1;
        }
    }

    // check for valid r, c, and n values, if any were entered
    if (nString != "") {
        nConvert << nString;
        nConvert >> nValue;
        if (nConvert.fail()) {
            std::cout << "Error, N value must be integer." << std::endl;
            return -1;
        }
    }
Exemplo n.º 17
0
    void ConsoleUI::handleUsageHelp(const char * cpszUsage, const char * cpszHelp, const char * cpszHelpFlags) {
      std::vector<const char *>     opts;        // Vector of possible option (start points)
      unsigned int                  i;
      apr_status_t                  rv;
      unsigned int                  nHelpFlags;

      if (cpszHelpFlags == NULL)
        cpszHelpFlags = "[--help | -?]\t\n";
      iv_cpszUsage[0] = cpszHelpFlags;
      iv_cpszUsage[1] = cpszUsage;
      iv_cpszHelp     = cpszHelp;

      // Step thru the usage msg to and create a vector addressing the start of each option
      // Options can be switches or take a value, and be marked as optional (most options are
      // are optional [!] but taftest_app requires one and only one of --config & --configs)

      //      --opt      --opt <val>      --opt=<val>
      //     [--opt]    [--opt <val>]    [--opt=<val>]  [-c] [-f foo] [-x | -y]

      // Assume a long option starts with -- preceeded by [ or whitespace
      // Assume a short option starts with - preceeded by [ or space and is followed by ] or space

      // First process help flags then the remainder of the usage message.
      for ( i = 0; i < 2; ++i ) {
        const char * str = iv_cpszUsage[i];
        if ( *str == '-' && *++str == '-' )           // Check for initial -- where str[-1] would be bad!
          opts.push_back(str);
        while ((str = strchr(str+1, '-')) != NULL) {
          if ( ( str[1]=='-' && (str[-1]=='[' || isspace(str[-1])) ) ||
               ( str[1]!='-' && isgraph(str[1]) && (str[-1]=='[' || str[-1]==' ') && (str[2]==']' || str[2]==' ') ) )
            opts.push_back(++str);
        }
        if (i == 0)
          nHelpFlags = opts.size();
      }

      iv_pOpts = (apr_getopt_option_t *)apr_palloc( consPool, (opts.size()+1) * sizeof(apr_getopt_option_t) );

      // Process short and long options in two passes as must use a wierd value for optch to
      // locate long options, so can have no more than 47 long options (1 - '0')

      int j = 0;
      const char * opt, * str;
      int k = 0;
      char helpChars[20];

      for ( i = 0; i < opts.size(); ++i ) {
        opt = opts[i];
        if ( *opt == '-' ) {                        // Long option
          str = strpbrk( ++opt, "]= \n" );
          if (str == NULL)                          // Must be last option!
            str = opt + strlen(opt);
          iv_pOpts[j].name = apr_pstrndup(consPool, opt, str - opt);
          iv_pOpts[j].has_arg = (*str == '=' || (*str == ' ' && *(str+1) == '<'));
          iv_pOpts[j].optch = j+1;                  // Use 1-based index as "short" option
          if (i < nHelpFlags)
            helpChars[k++] = j+1;
          ++j;
        }
      }
      iv_maxOptIndex = j;                           // Largest wierd value marking a long option
      // NOTE: should check that this is < any alphanumeric char, i.e. < 48 ('0')

      for ( i = 0; i < opts.size(); ++i ) {
        opt = opts[i];
        if ( *opt != '-' ) {                        // Short option
          iv_pOpts[j].optch = *opt;                 // Use real character
          iv_pOpts[j].name = NULL;
          iv_pOpts[j++].has_arg = (opt[1] == ' ' && opt[2] != '|' );
          if (i < nHelpFlags)
            helpChars[k++] = *opt;
        }
      }
      iv_pOpts[j].optch = 0;                        // Mark end of list
      helpChars[k] = '\0';

#ifndef NDEBUG
      // Dump all legal options when called with just 1 arg of "--"
      if ( iv_argc == 2 && strcmp(iv_argv[1],"--")==0 )
        debugDisplayOptions(j);
#endif

      // Set up processing of interleaved options and arguments
      apr_getopt_init(&iv_hGetopt, consPool, iv_argc, iv_argv);
      iv_hGetopt->interleave = 1;

      // Can't have more options than args!
      iv_pFoundOpts = (found_opt_t *)apr_palloc(consPool, iv_argc * sizeof(found_opt_t));
      iv_nFoundOpts = 0;

      // Check that provided options are valid and save them.
      int          index;
      const char * optarg;
      bool         needHelp = false;

      while ((rv = apr_getopt_long(iv_hGetopt, iv_pOpts, &index, &optarg)) == APR_SUCCESS) {
        iv_pFoundOpts[iv_nFoundOpts].index = index;
        iv_pFoundOpts[iv_nFoundOpts++].value = optarg;
        if (strchr(helpChars,index) != NULL)
          needHelp = true;
      }

      // Two errors are:  Invalid option & missing argument
      // getopt prints these on error streamwith fprintf(stderr but can override
      // via iv_hGetopt->errfn        typedef void( apr_getopt_err_fn_t)(void *arg, const char *err,...)

      if ( rv != APR_EOF )
        displayUsage();

      // Args are valid ... now check for the help flags
      else
        if (needHelp)
          displayHelp();
    }
Exemplo n.º 18
0
///////////////////////////////////
// and here the fun begins...
int
main (int argc, char *argv[])
{
  // option processing variables
  int  opt;
  int  option_index = 0;

  // should the action be forced
  bool forceAction = false;

  // should help be displayed
  bool displayHelp = false;

  // should version info be displayed
  bool displayVer = false;

  // the action the user has chosen to perform
  int  action = 0;

  // the argument to the action
  const char* action_arg = NULL;

  // should existing records be updated (default: No)
  bool updateRecords = false;

  // selected itemNr, 0 = no specific item selected
  uint16_t itemNr = 0;

  // enabled DBTypes (default to all)
  int dbTypes = (EQItemDB::LORE_DB | EQItemDB::NAME_DB | 
		 EQItemDB::DATA_DB | EQItemDB::RAW_DATA_DB);

  // search string
  QString search;

  // note program name for later use.
  progname = argv[0];

  // Get an instance of the EQItemDB
  EQItemDB* itemDB = new EQItemDB;
  
  // begin processing options
  while ((opt = getopt_long( argc,
			     argv,
			     OPTION_LIST,
			     option_list,
			     &option_index)) != -1)
    {
      switch(opt)
	{
	case 'd': // display an item
	case 'l': // list items
	case 'f': // import from a flat file db
	case 'r': // import from a itemrawdata.dbm file
	case 'o': // import from an old GDBM file
	case 'e': // export a raw data record
	case 'x': // export database as a CSV file
	case 'D': // delete a record
	case 'R': // reorganize database
	case 'u': // upgrade ItemDB to current format
	  // these actions are mutually exclusive, if two chosen, display help
	  if (action != 0)
	    displayHelp = true;
	  else
	  {
	    // save action and it's argument
	    action = opt;
	    action_arg = optarg;
	  }
	  break;
	case 'i':
	  itemNr = (uint16_t)atoi(optarg);
	  break;
	case 'U':
	  updateRecords = true;
	  break;
	case 'v':
	case 'V':
	  displayVer = true;
	  break;
	case ITEMDB_LORE_FILENAME_OPTION:
	  itemDB->SetDBFile(EQItemDB::LORE_DB, optarg);
	  break;
	case ITEMDB_NAME_FILENAME_OPTION:
	  itemDB->SetDBFile(EQItemDB::NAME_DB, optarg);
	  break;
	case ITEMDB_DATA_FILENAME_OPTION:
	  itemDB->SetDBFile(EQItemDB::DATA_DB, optarg);
	  break;
	case ITEMDB_RAW_FILENAME_OPTION:
	  itemDB->SetDBFile(EQItemDB::RAW_DATA_DB, optarg);
	  break;
	case ITEMDB_DATABASES_ENABLED:
	  dbTypes = atoi(optarg);
	  break;
	case FORCE_ACTION:
	  forceAction = true;
	  break;
	case 'h': // display usage info
	default:
	  displayHelp = true;
	  break;
	}
    }

  // if no action selected, display help
  if ((action == 0) && !displayHelp && !displayVer)
  {
    fprintf(stderr, "No action specified\n");
    displayHelp = true;
  }

  // are there extra arguments
  if (optind < argc)
  {
    //yes, there are

    // is the action list with no search argument
    if ((action == 'l') && (action_arg == 0))
    {
      // yes, so use them for the search argument
      while (optind < argc)
	{
	  if (!search.isEmpty())
	    search += " ";
	  
	  // append extra arguments to search string
	  search += argv[optind++];
	}
    }
    else // otherwise display help
    {
      fprintf(stderr, "Extra arguments!\n");
      displayHelp = true;
    }
  }

  // if either the display or delete actions were specified and no 
  // item was specified display help.
  if (((action == 'd') || (action == 'D')) && 
      (itemNr == 0))
    displayHelp = true;

  // result to return from the program (the exit code).
  int result = 0;

  // display the help/usage information if required and exit
  if (displayHelp)
  {
    // display the usage information
    displayUsage(); 

    // return non-zero result
    result = 1;
  }
  else
  {
    // enable the set of dbtypes
    itemDB->SetEnabledDBTypes(dbTypes);
    
    // display the version information
    if (displayVer)
      displayVersion(itemDB);

    // perform the requested action
    switch(action)
    {
    case 'd': // display an item
      result = displayRecord(itemDB, itemNr);
      break;
    case 'l': // list items
    {
      if (action_arg)
	search = action_arg;
      result = listRecords(itemDB, itemNr, search);
      break;
    }
    case 'f': // import from a flat file db
      result = importFlatFile(itemDB, action_arg, itemNr, 
			      forceAction, updateRecords);
      break;
    case 'r': // import from a itemrawdata.dbm file
    case 'o': // import from an old GDBM file
      // the above two options are really the same
      result = importGDBM(itemDB, action_arg, itemNr, 
			  forceAction, updateRecords);
      break;
    case 'e': // export a raw data record
      result = exportRawRecord(itemDB, action_arg, itemNr);
      break;
    case 'x': // export database as a CSV file
      result = exportRecordCSV(itemDB, action_arg, itemNr);
      break;
    case 'D': // delete a record
      result = deleteRecord(itemDB, itemNr, forceAction);
      break;
    case 'R': // reorganize database
      result = reorganize(itemDB);
      break;
    case 'u': // upgrade ItemDB to current format
      result = upgradeItemDB(itemDB);

    }
  }

  // shutdown the ItemDB
  itemDB->Shutdown();

  // delete this instance of ItemDB
  delete itemDB;

  return result;
}
Exemplo n.º 19
0
Arquivo: alock.c Projeto: mgumz/alock
int main(int argc, char **argv) {


    struct aXInfo xinfo;
    struct aOpts opts;

#if HAVE_XF86MISC
    int xf86misc_major = -1;
    int xf86misc_minor = -1;
#endif

    int arg = 0;
    const char* cursor_args = NULL;
    const char* background_args = NULL;

    opts.auth = NULL;
    opts.cursor = alock_cursors[0];
    opts.background = alock_backgrounds[0];

    /*  parse options */
    if (argc != 1) {
        for(arg = 1; arg <= argc; arg++) {
            if (!strcmp(argv[arg - 1], "-bg")) {
                if (arg < argc) {

                    char* char_tmp;
                    struct aBackground* bg_tmp = NULL;
                    struct aBackground** i;
                    if (strcmp(argv[arg], "list") == 0) {
                        for(i = alock_backgrounds; *i; ++i) {
                            printf("%s\n", (*i)->name);
                        }
                        exit(EXIT_SUCCESS);
                    }

                    for(i = alock_backgrounds; *i; ++i) {
                        char_tmp = strstr(argv[arg], (*i)->name);
                        if(char_tmp && char_tmp == argv[arg]) {
                            background_args = char_tmp;
                            bg_tmp = *i;
                            opts.background = bg_tmp;
                            ++arg;
                            break;
                        }
                    }

                    if (bg_tmp == NULL) {
                        printf("%s", "alock: error, couldnt find the bg-module you specified.\n");
                        exit(EXIT_FAILURE);
                    }

                } else {
                    printf("%s", "alock, error, missing argument\n");
                    displayUsage();
                    exit(EXIT_FAILURE);
                }
            } else if (!strcmp(argv[arg - 1], "-auth")) {
                if (arg < argc) {

                    char* char_tmp;
                    struct aAuth* auth_tmp = NULL;
                    struct aAuth** i;
                    if (!strcmp(argv[arg], "list")) {
                        for(i = alock_authmodules; *i; ++i) {
                            printf("%s\n", (*i)->name);
                        }
                        exit(EXIT_SUCCESS);
                    }

                    for(i = alock_authmodules; *i; ++i) {
                        char_tmp = strstr(argv[arg], (*i)->name);
                        if(char_tmp && char_tmp == argv[arg]) {
                            auth_tmp = (*i);
                            if (auth_tmp->init(argv[arg]) == 0) {
                                printf("alock: error, failed init of [%s].\n", auth_tmp->name);
                                exit(EXIT_FAILURE);
                            }
                            opts.auth = auth_tmp;
                            ++arg;
                            break;
                        }
                    }

                    if (auth_tmp == NULL) {
                        printf("%s", "alock: error, couldnt find the auth-module you specified.\n");
                        exit(EXIT_FAILURE);
                    }

                } else {
                    printf("%s", "alock, error, missing argument\n");
                    displayUsage();
                    exit(EXIT_FAILURE);
                }
            } else if (strcmp(argv[arg - 1], "-cursor") == 0) {
                if (arg < argc) {

                    char* char_tmp;
                    struct aCursor* cursor_tmp = NULL;
                    struct aCursor** i;
                    if (strcmp(argv[arg], "list") == 0) {
                        for(i = alock_cursors; *i; ++i) {
                            printf("%s\n", (*i)->name);
                        }
                        exit(EXIT_SUCCESS);
                    }

                    for(i = alock_cursors; *i; ++i) {
                        char_tmp = strstr(argv[arg], (*i)->name);
                        if(char_tmp && char_tmp == argv[arg]) {
                            cursor_args = char_tmp;
                            cursor_tmp = *i;
                            opts.cursor= cursor_tmp;
                            ++arg;
                            break;
                        }
                    }

                    if (!cursor_tmp) {
                        printf("%s", "alock: error, couldnt find the cursor-module you specified.\n");
                        exit(EXIT_FAILURE);
                    }

                } else {
                    printf("%s", "alock, error, missing argument\n");
                    displayUsage();
                    exit(EXIT_FAILURE);
                }
            } else if (strcmp(argv[arg - 1], "-h") == 0) {
                displayUsage();
                exit(EXIT_SUCCESS);
            } else if (strcmp(argv[arg - 1], "-v") == 0) {
                printf("alock-%s by m.gumz 2005 - 2006\n", VERSION);
                exit(EXIT_SUCCESS);
            }
        }
    }


    initStartTime();
    initXInfo(&xinfo);
    if (detectOtherInstance(&xinfo)) {
        printf("%s", "alock: error, another instance seems to be running\n");
        exit(EXIT_FAILURE);
    }

    if (!opts.auth) {
        printf("%s", "alock: error, no auth-method specified.\n");
        displayUsage();
        exit(EXIT_FAILURE);
    }

    if (opts.background->init(background_args, &xinfo) == 0) {
        printf("alock: error, couldnt init [%s] with [%s].\n",
               opts.background->name,
               background_args);
        exit(EXIT_FAILURE);
    }

    if (opts.cursor->init(cursor_args, &xinfo) == 0) {
        printf("alock: error, couldnt init [%s] with [%s].\n",
               opts.cursor->name,
               cursor_args);
        exit(EXIT_FAILURE);
    }

    {
        int scr;
        for (scr = 0; scr < xinfo.nr_screens; scr++) {

            XSelectInput(xinfo.display, xinfo.window[scr], KeyPressMask|KeyReleaseMask);
            XMapWindow(xinfo.display, xinfo.window[scr]);
            XRaiseWindow(xinfo.display, xinfo.window[scr]);

        }
    }

    /* try to grab 2 times, another process (windowmanager) may have grabbed
     * the keyboard already */
    if ((XGrabKeyboard(xinfo.display, xinfo.window[0], True, GrabModeAsync, GrabModeAsync,
                          CurrentTime)) != GrabSuccess) {
        sleep(1);
        if ((XGrabKeyboard(xinfo.display, xinfo.window[0], True, GrabModeAsync, GrabModeAsync,
                        CurrentTime)) != GrabSuccess) {
            printf("%s", "alock: couldnt grab the keyboard.\n");
            exit(EXIT_FAILURE);
        }
    }

#if HAVE_XF86MISC
    {
        if (XF86MiscQueryVersion(xinfo.display, &xf86misc_major, &xf86misc_minor) == True) {

            if (xf86misc_major >= 0 &&
                xf86misc_minor >= 5 &&
                XF86MiscSetGrabKeysState(xinfo.display, False) == MiscExtGrabStateLocked) {

                printf("%s", "alock: cant disable xserver hotkeys to remove grabs.\n");
                exit(EXIT_FAILURE);
            }

            printf("%s", "disabled AllowDeactivateGrabs and AllowClosedownGrabs\n.");
        }
    }
#endif

    /* TODO: think about it: do we really need NR_SCREEN cursors ? we grab the
     * pointer on :*.0 anyway ... */
    if (XGrabPointer(xinfo.display, xinfo.window[0], False, None,
                     GrabModeAsync, GrabModeAsync, None, xinfo.cursor[0], CurrentTime) != GrabSuccess) {
        XUngrabKeyboard(xinfo.display, CurrentTime);
        printf("%s", "alock: couldnt grab the pointer.\n");
        exit(EXIT_FAILURE);
    }

    registerInstance(&xinfo);
    eventLoop(&opts, &xinfo);
    unregisterInstance(&xinfo);

    opts.auth->deinit();
    opts.cursor->deinit(&xinfo);
    opts.background->deinit(&xinfo);

#if HAVE_XF86MISC
    if (xf86misc_major >= 0 && xf86misc_minor >= 5) {
        XF86MiscSetGrabKeysState(xinfo.display, True);
        XFlush(xinfo.display);
    }
#endif

    XCloseDisplay(xinfo.display);

    return EXIT_SUCCESS;
}
Exemplo n.º 20
0
int parse_args(int argc, char **argv) {
	int i;
	argc--;
	argv++;
	if (!argc) {
		printf("Invalid usage.\n\n");
		displayUsage();
		return -1;
	}
	for (i = 0; i < argc; i++) {
		if (match_option("-c", "--config")) {
			i++;
			packager.configName = argv[i];
		} else if (match_option("-e", "--extract")) {
			packager.pack = 0;
		} else if (match_option("-s", "--stub")) {
			packager.stub = 1;
		} else if (match_option("-h", "--help")) {
			displayUsage();
			return 1;
		} else if (match_option("-i", "--info")) {
			packager.pack = 0;
			packager.printMeta = 1;
		} else if (match_option("-k", "--sum")) {
			i++;
			if (strcmp(argv[i], "crc16") == 0) {
				packager.sumType = SUM_CRC16;
			} else if (strcmp(argv[i], "sha1") == 0) {
				packager.sumType = SUM_SHA1;
			} else if (strcmp(argv[i], "md5") == 0) {
				packager.sumType = SUM_MD5;
			} else if (strcmp(argv[i], "none") == 0) {
				packager.sumType = SUM_NONE;
			} else {
				printf("Invalid checksum type. See kpack --help.\n");
				return -1;
			}
		} else if (match_option("-x", "--compressor")) {
			i++;
			if (strcmp(argv[i], "pucrunch") == 0) {
				packager.compressionType = COMPRESSION_PUCRUNCH;
			} else if (strcmp(argv[i], "rle") == 0) {
				packager.compressionType = COMPRESSION_RLE;
			} else if (strcmp(argv[i], "none") == 0) {
				packager.compressionType = COMPRESSION_NONE;
			} else {
				printf("Invalid compression type. See kpack --help.\n");
				return -1;
			}
		} else if(match_option("-v", "--version")) {
			printf("kpack (KnightOS) %s\n", GIT_SHORT_VERSION);
			printf(COPYRIGHT);
			printf(LICENSE);
			return 1;
		} else if (*argv[i] == '-') {
			printf("Unknown option %s. See kpack --help for usage.\n", argv[i]);
			return -1;
		} else {
			if (!packager.filename) {
				packager.filename = argv[i];
			} else if (!packager.rootName) {
				packager.rootName = argv[i];
				if (packager.rootName[strlen(packager.rootName) - 1] == '/') {
					/* Remove trailing slash */
					packager.rootName[strlen(packager.rootName) - 1] = 0;
				}
			} else {
				printf("Error: unrecognized argument %s.\n", argv[i]);
				return -1;
			}
		}
	}
	
	if (!packager.filename) {
		printf("Invalid usage - no package specified. See kpack --help.\n");
		return -1;
	}
	if (!packager.rootName && !packager.printMeta) {
		/* if we are going to unpack then we need a target dir */
		if(!packager.pack) {
			printf("Invalid usage - no target directory specified for unpacking. See kpack --help.\n");
			return -1;
		}
		printf("Invalid usage - no model specified. See kpack --help.\n");
	}
	
	if(!packager.printMeta && packager.pack) {
		if (!packager.configName) {
			packager.configName = "package.config";
		}
			
		packager.config = fopen(packager.configName, "r");
		
		if (!packager.config) {
			printf("Config file '%s' not found.\n", packager.configName);
			return -1;
		}
	}
	
	return 0;
}
Exemplo n.º 21
0
int main(int argc, char **argv)
{

	struct aXInfo xinfo;

	struct aOpts opts;

	int arg = 0;
	const char* cursor_args = NULL;
	const char* background_args = NULL;
	int precheck = 0;

	opts.auth = NULL;
	opts.cursor = tlock_cursors[0];
	opts.background = tlock_backgrounds[0];
	opts.flash = 0;
	opts.gids = 0;

	/*  parse options */
	if (argc != 1)
	{
		for (arg = 1; arg <= argc; arg++)
		{
			/**
			 * Background options.
			 */
			if (!strcmp(argv[arg - 1], "-bg"))
			{
				if (arg < argc)
				{

					char* char_tmp;
					struct aBackground* bg_tmp = NULL;
					struct aBackground** i;
					/*
					 * List all the available backgrounds.
					 */
					if (strcmp(argv[arg], "list") == 0)
					{
						for (i = tlock_backgrounds; *i; ++i)
						{
							printf("%s\n", (*i)->name);
						}
						exit(EXIT_SUCCESS);
					}

					/*
					 * Assigning the backgrounds to the option array.
					 */
					for (i = tlock_backgrounds; *i; ++i)
					{
						char_tmp = strstr(argv[arg], (*i)->name);
						if (char_tmp && char_tmp == argv[arg])
						{
							background_args = char_tmp;
							bg_tmp = *i;
							opts.background = bg_tmp;
							++arg;
							break;
						}
					}

					/**
					 * Abort when background is not found.
					 */
					if (bg_tmp == NULL)
					{
						printf("%s", "tlock: error, couldn't find the bg-module you specified.\n");
						exit(EXIT_FAILURE);
					}

				} else
				{
					printf("%s", "tlock, error, missing argument\n");
					displayUsage();
					exit(EXIT_FAILURE);
				}
			} else
				if (!strcmp(argv[arg - 1], "-auth"))
				{
					if (arg < argc)
					{

						char* char_tmp;
						struct aAuth* auth_tmp = NULL;
						struct aAuth** i;

						if (!strcmp(argv[arg], "list"))
						{
							for (i = tlock_authmodules; *i; ++i)
							{
								printf("%s\n", (*i)->name);
							}
							exit(EXIT_SUCCESS);
						}

						for (i = tlock_authmodules; *i; ++i)
						{
							char_tmp = strstr(argv[arg], (*i)->name);
							if (char_tmp && char_tmp == argv[arg])
							{
								auth_tmp = (*i);
								if (auth_tmp->init(argv[arg]) == 0)
								{
									printf("%s.%s: error, failed init of [%s] with arguments [%s].\n",
									__FILE__, __FUNCTION__, auth_tmp->name, argv[arg]);
									exit(EXIT_FAILURE);
								} else
								{
									printf("%s.%s: initialized [%s] with arguments [%s].\n",
									__FILE__, __FUNCTION__, auth_tmp->name, argv[arg]);
								}
								opts.auth = auth_tmp;
								++arg;
								break;
							}
						}

						if (auth_tmp == NULL)
						{
							printf("%s", "tlock: error, couldnt find the auth-module you specified.\n");
							exit(EXIT_FAILURE);
						}

					} else
					{
						printf("%s", "tlock, error, missing argument\n");
						displayUsage();
						exit(EXIT_FAILURE);
					}
				} else
					if (strcmp(argv[arg - 1], "-cursor") == 0)
					{
						if (arg < argc)
						{

							char* char_tmp;
							struct aCursor* cursor_tmp = NULL;
							struct aCursor** i;
							if (strcmp(argv[arg], "list") == 0)
							{
								for (i = tlock_cursors; *i; ++i)
								{
									printf("%s\n", (*i)->name);
								}
								exit(EXIT_SUCCESS);
							}

							for (i = tlock_cursors; *i; ++i)
							{
								char_tmp = strstr(argv[arg], (*i)->name);
								if (char_tmp && char_tmp == argv[arg])
								{
									cursor_args = char_tmp;
									cursor_tmp = *i;
									opts.cursor = cursor_tmp;
									++arg;
									break;
								}
							}

							if (!cursor_tmp)
							{
								printf("%s", "tlock: error, couldn't find the cursor-module you specified.\n");
								exit(EXIT_FAILURE);
							}

						} else
						{
							printf("%s", "tlock, error, missing argument\n");
							displayUsage();
							exit(EXIT_FAILURE);
						}
					} else
					{
						if (strcmp(argv[arg - 1], "-h") == 0)
						{
							displayUsage();
							exit(EXIT_SUCCESS);
						} else
							if (strcmp(argv[arg - 1], "-v") == 0)
							{
								printf("tlock-%s by André 'Bananaman' Kaan\n",
								VERSION);
								exit(EXIT_SUCCESS);
							} else
								if (strcmp(argv[arg - 1], "-pre") == 0)
								{
									precheck = 1;
								}
								else
						if (strcmp(argv[arg - 1], "-flash") == 0)
						{
							opts.flash = 1;
						}
						else
				if (strcmp(argv[arg - 1], "-gids") == 0)
				{
					opts.gids = 1;
				}
					}
		}
	}

	/**
	 *
	 */
	initStartTime();
	/*
	 *
	 */
	initXInfo(&xinfo);
	if (detectOtherInstance(&xinfo))
	{
		printf("%s", "tlock: error, another instance seems to be running\n");
		exit(EXIT_FAILURE);
	}

	/*
	 * List the usage of the authentication.
	 */
	if (!opts.auth)
	{
		printf("%s", "tlock: error, no auth-method specified.\n");
		displayUsage();
		exit(EXIT_FAILURE);
	}

	/*
	 *
	 */
	if (opts.background->init(background_args, &xinfo) == 0)
	{
		printf("tlock: error, couldn't init [%s] with [%s].\n", opts.background->name, background_args);
		exit(EXIT_FAILURE);
	}

	if (opts.cursor->init(cursor_args, &xinfo) == 0)
	{
		printf("tlock: error, couldn't init [%s] with [%s].\n", opts.cursor->name, cursor_args);
		exit(EXIT_FAILURE);
	}

	LOG("initializing screens");
	{
		int scr;
		for (scr = 0; scr < xinfo.nr_screens; scr++)
		{

			XSelectInput(xinfo.display, xinfo.window[scr],
			ButtonReleaseMask | ButtonPressMask);
			XMapWindow(xinfo.display, xinfo.window[scr]);
			XRaiseWindow(xinfo.display, xinfo.window[scr]);

		}
	}

	LOG("initializing keyboard control");
	/* try to grab 2 times, another process (windowmanager) may have grabbed
	 * the keyboard already */
	if ((XGrabKeyboard(xinfo.display, xinfo.window[0], True, GrabModeAsync,
	GrabModeAsync,
	CurrentTime)) != GrabSuccess)
	{
		sleep(1);
		if ((XGrabKeyboard(xinfo.display, xinfo.window[0], True, GrabModeAsync,
		GrabModeAsync,
		CurrentTime)) != GrabSuccess)
		{
			printf("%s", "tlock: couldn't grab the keyboard.\n");
			exit(EXIT_FAILURE);
		}
	}

	/* TODO: think about it: do we really need NR_SCREEN cursors ? we grab the
	 * pointer on :*.0 anyway ... */
	LOG("initializing mouse control");
	if (XGrabPointer(xinfo.display, xinfo.window[0],
	False,
	ButtonPressMask | ButtonReleaseMask,
	// needed for the propagation of the pointer events on window[0]
	      GrabModeAsync,
	      GrabModeAsync,
	      None,
	      xinfo.cursor[0],
	      CurrentTime) != GrabSuccess)
	{
		XUngrabKeyboard(xinfo.display, CurrentTime);
		printf("%s", "tlock: couldn't grab the pointer.\n");
		exit(EXIT_FAILURE);
	}

	openlog("tlock", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
	syslog(LOG_NOTICE, "program started by user %d(%s), accepting groups as '%s' only.",
			getuid(), getenv("USER"), opts.gids ? "id" : "names"	);
	// pre authorization check
	if (precheck == 1)
	{
		if (opts.auth != NULL)
		{
			int ret = opts.auth->auth(NULL, NULL, 0);
			syslog(
			LOG_NOTICE, "%s: %s[exit=%d]\n",
			__FILE__, __FUNCTION__, ret);

			if (ret != 1)
			{

				registerInstance(&xinfo);
				eventLoop(&opts, &xinfo);
				LOG("exiting eventloop, and unregister");
				unregisterInstance(&xinfo);

			}

		}
	} else
	{

		registerInstance(&xinfo);
		eventLoop(&opts, &xinfo);
		LOG("exiting eventloop, and unregister");
		unregisterInstance(&xinfo);

	}

	closelog();

	opts.auth->deinit();
	opts.cursor->deinit(&xinfo);
	opts.background->deinit(&xinfo);

	XCloseDisplay(xinfo.display);

	return EXIT_SUCCESS;
}
Exemplo n.º 22
0
// Main
int main(int argc, char *argv[])
{
    // We must save it here because QApplication constructor may change it
    bool isOneArg = (argc == 2);

    // Create Application
    QString appId = QLatin1String("qBittorrent-") + Utils::Misc::getUserIDString();
    QScopedPointer<Application> app(new Application(appId, argc, argv));

    const QBtCommandLineParameters params = parseCommandLine();

    if (!params.unknownParameter.isEmpty()) {
        displayBadArgMessage(QObject::tr("%1 is an unknown command line parameter.", "--random-parameter is an unknown command line parameter.")
                             .arg(params.unknownParameter));
        return EXIT_FAILURE;
    }

#ifndef Q_OS_WIN
    if (params.showVersion) {
        if (isOneArg) {
            displayVersion();
            return EXIT_SUCCESS;
        }
        else {
            displayBadArgMessage(QObject::tr("%1 must be the single command line parameter.")
                                 .arg(QLatin1String("-v (or --version)")));
            return EXIT_FAILURE;
        }
    }
#endif

    if (params.showHelp) {
        if (isOneArg) {
            displayUsage(argv[0]);
            return EXIT_SUCCESS;
        }
        else {
            displayBadArgMessage(QObject::tr("%1 must be the single command line parameter.")
                                 .arg(QLatin1String("-h (or --help)")));
            return EXIT_FAILURE;
        }
    }

    if ((params.webUiPort > 0) && (params.webUiPort <= 65535)) {
        Preferences::instance()->setWebUiPort(params.webUiPort);
    }
    else {
        displayBadArgMessage(QObject::tr("%1 must specify the correct port (1 to 65535).")
                             .arg(QLatin1String("--webui-port")));
        return EXIT_FAILURE;
    }

    // Set environment variable
    if (!qputenv("QBITTORRENT", QByteArray(VERSION)))
        std::cerr << "Couldn't set environment variable...\n";

#ifndef DISABLE_GUI
    if (!userAgreesWithLegalNotice())
        return EXIT_SUCCESS;
#else
    if (!params.shouldDaemonize
        && isatty(fileno(stdin))
        && isatty(fileno(stdout))
        && !userAgreesWithLegalNotice())
        return EXIT_SUCCESS;
#endif

    // Check if qBittorrent is already running for this user
    if (app->isRunning()) {
#ifdef DISABLE_GUI
        if (params.shouldDaemonize) {
            displayBadArgMessage(QObject::tr("You cannot use %1: qBittorrent is already running for this user.")
                                 .arg(QLatin1String("-d (or --daemon)")));
            return EXIT_FAILURE;
        }
        else
#endif
        qDebug("qBittorrent is already running for this user.");

        Utils::Misc::msleep(300);
        app->sendParams(params.torrents);

        return EXIT_SUCCESS;
    }

#ifndef DISABLE_GUI
    if (!upgrade()) return EXIT_FAILURE;
#else
    if (!upgrade(!params.shouldDaemonize
                 && isatty(fileno(stdin))
                 && isatty(fileno(stdout)))) return EXIT_FAILURE;
#endif

    srand(time(0));
#ifdef DISABLE_GUI
    if (params.shouldDaemonize) {
        app.reset(); // Destroy current application
        if ((daemon(1, 0) == 0)) {
            app.reset(new Application(appId, argc, argv));
            if (app->isRunning()) {
                // Another instance had time to start.
                return EXIT_FAILURE;
            }
        }
        else {
            qCritical("Something went wrong while daemonizing, exiting...");
            return EXIT_FAILURE;
        }
    }
#else
    if (!params.noSplash)
        showSplashScreen();
#endif

#if defined(Q_OS_UNIX) || defined(STACKTRACE_WIN)
    signal(SIGABRT, sigabrtHandler);
    signal(SIGTERM, sigtermHandler);
    signal(SIGINT, sigintHandler);
    signal(SIGSEGV, sigsegvHandler);
#endif

    return app->exec(params.torrents);
}
Exemplo n.º 23
0
void rtParseArgsForExtMode(int_T        argc, 
                           const char_T *argv[])
{

#ifdef  EXTMODE_DISABLE_ARGS_PROCESSING
    /* Some targets do not support command line args, so bypass the args 
     * processing and directly call into ExtParseArgsAndInitUD.
     */

    /* initialize external mode */
    ExtParseArgsAndInitUD(0, NULL);

#else    
    /* parse command line args */

    int_T  oldStyle_argc;
    const char_T *oldStyle_argv[5];

    if ((argc > 1) && (argv[1][0] != '-')) {
        /* old style */
        if ( argc > 3 ) {
            displayUsage();
            exit(EXIT_FAILURE);
        }

        oldStyle_argc    = 1;
        oldStyle_argv[0] = argv[0];
    
        if (argc >= 2) {
            oldStyle_argc = 3;

            oldStyle_argv[1] = "-tf";
            oldStyle_argv[2] = argv[1];
        }

        if (argc == 3) {
            oldStyle_argc = 5;

            oldStyle_argv[3] = "-port";
            oldStyle_argv[4] = argv[2];

        }

        argc = oldStyle_argc;
        argv = oldStyle_argv;

    }

    {
        /* new style: */
        double    tmpDouble;
        char_T tmpStr2[200];
        int_T  count      = 1;
        int_T  parseError = FALSE;

        /*
         * Parse the standard RTW parameters.  Let all unrecognized parameters
         * pass through to external mode for parsing.  NULL out all args handled
         * so that the external mode parsing can ignore them.
         */
        while(count < argc) {
            const char_T *option = argv[count++];
            
            /* final time */
            if ((strcmp(option, "-tf") == 0) && (count != argc)) {
                const char_T *tfStr = argv[count++];
                
                sscanf(tfStr, "%200s", tmpStr2);
                if (strcmp(tmpStr2, "inf") == 0) {
                    tmpDouble = RUN_FOREVER;
                } else {
                    char_T tmpstr[2];

#if INTEGER_CODE == 0
                    if ( (sscanf(tmpStr2,"%lf%1s", &tmpDouble, tmpstr) != 1) ||
                         (tmpDouble < (real_T)0) ) {
    #ifndef EXTMODE_DISABLEPRINTF
                        (void)printf("finaltime must be a positive, real value or inf\n");
    #endif
                        parseError = TRUE;
                        break;
                    }
#else
                    if ( (sscanf(tmpStr2,"%d%1s", &tmpDouble, tmpstr) != 1) ||
                         (tmpDouble < (real_T)0) ) {
    #ifndef EXTMODE_DISABLEPRINTF
                        (void)printf("tmpDouble = %d\n", tmpDouble);
                        (void)printf("finaltime must be a positive, integer value or inf\n");
    #endif
                        parseError = TRUE;
                        break;
                    }
#endif
                }
                finaltime = (real_T) tmpDouble;

                argv[count-2] = NULL;
                argv[count-1] = NULL;
            }
        }

        if (parseError) {
    #ifndef EXTMODE_DISABLEPRINTF        
            (void)printf("\nUsage: model_name -option1 val1 -option2 val2 -option3 "
                         "...\n\n");
            (void)printf("\t-tf 20 - sets final time to 20 seconds\n");
    #endif        

            exit(EXIT_FAILURE);
        }

        /*
         * Parse the external mode arguments.
         */
        {
            const char_T *extParseErrorPkt = ExtParseArgsAndInitUD(argc, argv);
            if (extParseErrorPkt != NULL) {
    #ifndef EXTMODE_DISABLEPRINTF           
                printf(
                    "\nError processing External Mode command line arguments:\n");
                printf("\t%s",extParseErrorPkt);
    #endif
                exit(EXIT_FAILURE);
            }
        }

        /*
         * Check for unprocessed ("unhandled") args.
         */
        {
            int i;
            for (i=1; i<argc; i++) {
                if (argv[i] != NULL) {
    #ifndef EXTMODE_DISABLEPRINTF                
                    printf("Unexpected command line argument: %s\n",argv[i]);
    #endif
                    exit(EXIT_FAILURE);
                }
            }
        }
    }

    if (finaltime == RUN_FOREVER) {
        #ifndef EXTMODE_DISABLEPRINTF
                printf ("\n**warning: the simulation will run with no stop time due "
                "to external mode with '-tf inf' argument.\n");
        #endif
    }

#endif /* EXTMODE_DISABLE_ARGS_PROCESSING */
}
Exemplo n.º 24
0
bool parseCommandline(const std::vector<Common::UString> &argv, Common::UString &target, int &code) {
	target.clear();

	Common::UString key;

	bool stopMark = false;
	for (size_t i = 1; i < argv.size(); i++) {

		if (!key.empty()) {
		// Still got one parameter missing from last time
			if (!setOption(key, argv[i])) {
				code = 1;
				return false;
			}

			continue;
		}

		if (!stopMark && argv[i].beginsWith("-")) {
			if (argv[i] == "--") {
				stopMark = true;
				continue;
			}

			if (argv[i] == "--help") {
				code = 0;
				displayUsage(argv[0]);
				return false;
			}

			if (argv[i] == "--version") {
				code = 0;
				displayVersion();
				return false;
			}

			if (!parseOption(argv[i], key)) {
				code = 1;
				return false;
			}

			if (key == "listdebug") {
				setOption(key, "true");
				key.clear();
			}

			if (key == "listlangs") {
				setOption(key, "true");
				key.clear();
			}

			continue;
		}

		if (!target.empty()) {
			warning("Found multiple target (\"%s\" and \"%s\")", target.c_str(), argv[i].c_str());
			code = 1;
			return false;
		}

		target = argv[i];
	}

	if (target.empty() && !ConfigMan.hasKey("path") && !ConfigMan.getBool("listdebug", false)) {
		displayUsage(argv[0]);
		code = 1;
		return false;
	}

	return true;
}
Exemplo n.º 25
0
/* Function: main =============================================================
 *
 * Abstract:
 *      Execute model on a generic target such as a workstation.
 */
int_T main(int_T argc, const char_T *argv[])
{
    RT_MODEL  *S;
    const char *status;
    real_T     finaltime = -2.0;

    int_T  oldStyle_argc;
    const char_T *oldStyle_argv[5];

    /******************************
     * MathError Handling for BC++ *
     ******************************/
#ifdef BORLAND
    signal(SIGFPE, (fptr)divideByZero);
#endif

    /*******************
     * Parse arguments *
     *******************/
    if ((argc > 1) && (argv[1][0] != '-')) {
        /* old style */
        if ( argc > 3 ) {
            displayUsage();
            exit(EXIT_FAILURE);
        }

        oldStyle_argc    = 1;
        oldStyle_argv[0] = argv[0];
    
        if (argc >= 2) {
            oldStyle_argc = 3;

            oldStyle_argv[1] = "-tf";
            oldStyle_argv[2] = argv[1];
        }

        if (argc == 3) {
            oldStyle_argc = 5;

            oldStyle_argv[3] = "-port";
            oldStyle_argv[4] = argv[2];

        }

        argc = oldStyle_argc;
        argv = oldStyle_argv;

    }

    {
        /* new style: */
        double    tmpDouble;
        char_T tmpStr2[200];
        int_T  count      = 1;
        int_T  parseError = FALSE;

        /*
         * Parse the standard RTW parameters.  Let all unrecognized parameters
         * pass through to external mode for parsing.  NULL out all args handled
         * so that the external mode parsing can ignore them.
         */
        while(count < argc) {
            const char_T *option = argv[count++];
            
            /* final time */
            if ((strcmp(option, "-tf") == 0) && (count != argc)) {
                const char_T *tfStr = argv[count++];
                
                sscanf(tfStr, "%200s", tmpStr2);
                if (strcmp(tmpStr2, "inf") == 0) {
                    tmpDouble = RUN_FOREVER;
                } else {
                    char_T tmpstr[2];

                    if ( (sscanf(tmpStr2,"%lf%1s", &tmpDouble, tmpstr) != 1) ||
                         (tmpDouble < 0.0) ) {
                        (void)printf("finaltime must be a positive, real value or inf\n");
                        parseError = TRUE;
                        break;
                    }
                }
                finaltime = (real_T) tmpDouble;

                argv[count-2] = NULL;
                argv[count-1] = NULL;
            }
        }

        if (parseError) {
            (void)printf("\nUsage: %s -option1 val1 -option2 val2 -option3 "
                         "...\n\n", QUOTE(MODEL));
            (void)printf("\t-tf 20 - sets final time to 20 seconds\n");

            exit(EXIT_FAILURE);
        }

        rtExtModeParseArgs(argc, argv, NULL);

        /*
         * Check for unprocessed ("unhandled") args.
         */
        {
            int i;
            for (i=1; i<argc; i++) {
                if (argv[i] != NULL) {
                    printf("Unexpected command line argument: %s\n",argv[i]);
                    exit(EXIT_FAILURE);
                }
            }
        }
    }

    /****************************
     * Initialize global memory *
     ****************************/
    (void)memset(&GBLbuf, 0, sizeof(GBLbuf));

    /************************
     * Initialize the model *
     ************************/
    rt_InitInfAndNaN(sizeof(real_T));

    S = MODEL();
    if (rtmGetErrorStatus(S) != NULL) {
        (void)fprintf(stderr,"Error during model registration: %s\n",
                      rtmGetErrorStatus(S));
        exit(EXIT_FAILURE);
    }
    if (finaltime >= 0.0 || finaltime == RUN_FOREVER) rtmSetTFinal(S,finaltime);

    MdlInitializeSizes();
    MdlInitializeSampleTimes();
    
    status = rt_SimInitTimingEngine(rtmGetNumSampleTimes(S),
                                    rtmGetStepSize(S),
                                    rtmGetSampleTimePtr(S),
                                    rtmGetOffsetTimePtr(S),
                                    rtmGetSampleHitPtr(S),
                                    rtmGetSampleTimeTaskIDPtr(S),
                                    rtmGetTStart(S),
                                    &rtmGetSimTimeStep(S),
                                    &rtmGetTimingData(S));

    if (status != NULL) {
        (void)fprintf(stderr,
                "Failed to initialize sample time engine: %s\n", status);
        exit(EXIT_FAILURE);
    }
    rt_CreateIntegrationData(S);
/*
#ifdef UseMMIDataLogging
    rt_FillStateSigInfoFromMMI(rtmGetRTWLogInfo(S),&rtmGetErrorStatus(S));
    rt_FillSigLogInfoFromMMI(rtmGetRTWLogInfo(S),&rtmGetErrorStatus(S));
#endif*/
 /*   GBLbuf.errmsg = rt_StartDataLogging(rtmGetRTWLogInfo(S),
                                        rtmGetTFinal(S),
                                        rtmGetStepSize(S),
                                        &rtmGetErrorStatus(S));
    if (GBLbuf.errmsg != NULL) {
        (void)fprintf(stderr,"Error starting data logging: %s\n",GBLbuf.errmsg);
        return(EXIT_FAILURE);
    }*//*removed datalogging*/

    rtExtModeCheckInit(rtmGetNumSampleTimes(S));
    rtExtModeWaitForStartPkt(rtmGetRTWExtModeInfo(S),
                             rtmGetNumSampleTimes(S),
                             (boolean_T *)&rtmGetStopRequested(S));

    (void)printf("\n** starting the model **\n");

    MdlStart();
    if (rtmGetErrorStatus(S) != NULL) {
      GBLbuf.stopExecutionFlag = 1;
    }

    /*************************************************************************
     * Execute the model.  You may attach rtOneStep to an ISR, if so replace *
     * the call to rtOneStep (below) with a call to a background task        *
     * application.                                                          *
     *************************************************************************/
    if (rtmGetTFinal(S) == RUN_FOREVER) {
        printf ("\n**May run forever. Model stop time set to infinity.**\n");
    }



    stepTime=(FPS*CLOCKS_PER_SEC)/1000;
    nextStart = clock();
    nextStart+=stepTime;

    while (!GBLbuf.stopExecutionFlag &&
           (rtmGetTFinal(S) == RUN_FOREVER ||
            rtmGetTFinal(S)-rtmGetT(S) > rtmGetT(S)*DBL_EPSILON)) {

        rtExtModePauseIfNeeded(rtmGetRTWExtModeInfo(S),
                               rtmGetNumSampleTimes(S),
                               (boolean_T *)&rtmGetStopRequested(S));
 
    if( clock() >= nextStart)
     {
    if( stepTime > 0)
{
    	printf("***Execution slower than requested rate: Actual speed =%d ms***\n",(1000*(stepTime+clock()-nextStart))/CLOCKS_PER_SEC);
nextStart=clock();
}
	
	}
    while (clock() < nextStart) {}
    nextStart+=stepTime;

        if (rtmGetStopRequested(S)) break;
        rt_OneStep(S);
    }

    if (!GBLbuf.stopExecutionFlag && !rtmGetStopRequested(S)) {
        /* Execute model last time step */
        rt_OneStep(S);
    }

    /********************
     * Cleanup and exit *
     ********************/
	/*
#ifdef UseMMIDataLogging
    rt_CleanUpForStateLogWithMMI(rtmGetRTWLogInfo(S));
    rt_CleanUpForSigLogWithMMI(rtmGetRTWLogInfo(S));
#endif
    rt_StopDataLogging(MATFILE,rtmGetRTWLogInfo(S));*/

    rtExtModeShutdown(rtmGetNumSampleTimes(S));

    if (GBLbuf.errmsg) {
        (void)fprintf(stderr,"%s\n",GBLbuf.errmsg);
        exit(EXIT_FAILURE);
    }

    if (rtmGetErrorStatus(S) != NULL) {
        (void)fprintf(stderr,"ErrorStatus set: \"%s\"\n", rtmGetErrorStatus(S));
        exit(EXIT_FAILURE);
    }

    if (GBLbuf.isrOverrun) {
        (void)fprintf(stderr,
                      "%s: ISR overrun - base sampling rate is too fast\n",
                      QUOTE(MODEL));
        exit(EXIT_FAILURE);
    }

#ifdef MULTITASKING
    else {
        int_T i;
        for (i=1; i<NUMST; i++) {
            if (GBLbuf.overrunFlags[i]) {
                (void)fprintf(stderr,
                        "%s ISR overrun - sampling rate is too fast for "
                        "sample time index %d\n", QUOTE(MODEL), i);
                exit(EXIT_FAILURE);
            }
        }
    }
#endif

    MdlTerminate();
    return(EXIT_SUCCESS);

} /* end main */