void OscapScannerLocal::evaluate()
{
    if (mDryRun)
    {
        signalCompletion(mCancelRequested);
        return;
    }

    emit infoMessage(QObject::tr("Querying capabilities..."));

    {
        SyncProcess proc(this);
        proc.setCommand(SCAP_WORKBENCH_LOCAL_OSCAP_PATH);
        proc.setArguments(QStringList("--v"));
        proc.run();

        if (proc.getExitCode() != 0)
        {
            emit errorMessage(
                QObject::tr("Failed to query capabilities of oscap on local machine.\n"
                    "Diagnostic info:\n%1").arg(proc.getDiagnosticInfo())
            );

            mCancelRequested = true;
            signalCompletion(mCancelRequested);
            return;
        }

        mCapabilities.parse(proc.getStdOutContents());
    }

    if (!checkPrerequisites())
    {
        mCancelRequested = true;
        signalCompletion(mCancelRequested);
        return;
    }

    // TODO: Error handling!
    emit infoMessage(QObject::tr("Creating temporary files..."));

    QTemporaryFile resultFile;
    resultFile.setAutoRemove(true);
    // the following forces Qt to give us the filename
    resultFile.open(); resultFile.close();

    QTemporaryFile reportFile;
    reportFile.setAutoRemove(true);
    reportFile.open(); reportFile.close();

    QTemporaryFile arfFile;
    arfFile.setAutoRemove(true);
    arfFile.open(); arfFile.close();

    // This is mainly for check-engine-results and oval-results, to ensure
    // we get a full report, including info from these files. openscap's XSLT
    // uses info in the check engine results if it can find them.
    TemporaryDir workingDir;

    emit infoMessage(QObject::tr("Starting the oscap process..."));
    QProcess process(this);
    process.setWorkingDirectory(workingDir.getPath());

    QStringList args;

    QTemporaryFile inputARFFile;
    inputARFFile.setAutoRemove(true);

    if (mScannerMode == SM_OFFLINE_REMEDIATION)
    {
        inputARFFile.open();
        inputARFFile.write(getARFForRemediation());
        inputARFFile.close();

        args = buildOfflineRemediationArgs(inputARFFile.fileName(),
                resultFile.fileName(),
                reportFile.fileName(),
                arfFile.fileName());
    }
    else
    {
        args = buildEvaluationArgs(mSession->getOpenedFilePath(),
                mSession->hasTailoring() ? mSession->getTailoringFilePath() : QString(),
                resultFile.fileName(),
                reportFile.fileName(),
                arfFile.fileName(),
                mScannerMode == SM_SCAN_ONLINE_REMEDIATION);
    }

    QString program = "";
#ifdef SCAP_WORKBENCH_LOCAL_NICE_FOUND
    args.prepend(getPkexecOscapPath());
    args.prepend(QString::number(SCAP_WORKBENCH_LOCAL_OSCAP_NICENESS));
    args.prepend("-n");

    program = SCAP_WORKBENCH_LOCAL_NICE_PATH;
#else
    program = getPkexecOscapPath();
#endif

    process.start(program, args);
    process.waitForStarted();

    if (process.state() != QProcess::Running)
    {
        emit errorMessage(QObject::tr("Failed to start local scanning process '%1'. Perhaps the executable was not found?").arg(program));
        mCancelRequested = true;
    }

    const unsigned int pollInterval = 100;

    emit infoMessage(QObject::tr("Processing..."));
    while (!process.waitForFinished(pollInterval))
    {
        // read everything new
        readStdOut(process);
        watchStdErr(process);

        // pump the event queue, mainly because the user might want to cancel
        QAbstractEventDispatcher::instance(mScanThread)->processEvents(QEventLoop::AllEvents);

        if (mCancelRequested)
        {
            emit infoMessage(QObject::tr("Cancellation was requested! Terminating scanning..."));
            process.kill();
            process.waitForFinished(1000);
            break;
        }
    }

    if (!mCancelRequested)
    {
        if (process.exitCode() == 1) // error happened
        {
            watchStdErr(process);
            // TODO: pass the diagnostics over
            emit errorMessage(QObject::tr("There was an error during evaluation! Exit code of the 'oscap' process was 1."));
            // mark this run as canceled
            mCancelRequested = true;
        }
        else
        {
            // read everything left over
            readStdOut(process);
            watchStdErr(process);

            emit infoMessage(QObject::tr("The oscap tool has finished. Reading results..."));

            resultFile.open();
            mResults = resultFile.readAll();
            resultFile.close();

            reportFile.open();
            mReport = reportFile.readAll();
            reportFile.close();

            arfFile.open();
            mARF = arfFile.readAll();
            arfFile.close();

            emit infoMessage(QObject::tr("Processing has been finished!"));
        }
    }

    signalCompletion(mCancelRequested);
}
void OscapScannerRemoteSsh::evaluate()
{
    if (mDryRun)
    {
        signalCompletion(mCancelRequested);
        return;
    }

    ensureConnected();

    if (mCancelRequested)
    {
        signalCompletion(true);
        return;
    }

    {
        SshSyncProcess proc(mSshConnection, this);
        emit infoMessage(QObject::tr("Checking if oscap is available on remote machine..."));

        proc.setCommand(QString("command"));
        proc.setArguments(QStringList() << "-v" << SCAP_WORKBENCH_REMOTE_OSCAP_PATH);
        proc.setCancelRequestSource(&mCancelRequested);
        proc.run();

        if (proc.getExitCode() != 0)
        {
            emit errorMessage(
                QObject::tr("Failed to locate oscap on remote machine. "
                        "Please, check that openscap-scanner is installed on the remote machine.")
            );

            mCancelRequested = true;
            signalCompletion(mCancelRequested);
            return;
        }

        emit infoMessage(QObject::tr("Querying capabilities on remote machine..."));
        proc.setCommand(SCAP_WORKBENCH_REMOTE_OSCAP_PATH);
        proc.setArguments(QStringList("-V"));
        proc.setCancelRequestSource(&mCancelRequested);
        proc.run();

        if (proc.getExitCode() != 0)
        {
            emit errorMessage(
                QObject::tr("Failed to query capabilities of oscap on remote machine.\n"
                        "Diagnostic info:\n%1").arg(proc.getDiagnosticInfo())
            );

            mCancelRequested = true;
            signalCompletion(mCancelRequested);
            return;
        }

        mCapabilities.parse(proc.getStdOutContents());
    }

    if (!checkPrerequisites())
    {
        mCancelRequested = true;
        signalCompletion(mCancelRequested);
        return;
    }

    QStringList baseArgs;
    baseArgs.append("-o"); baseArgs.append(QString("ControlPath=%1").arg(mSshConnection._getMasterSocket()));
    baseArgs.append(mTarget);

    QString diagnosticInfo;

    emit infoMessage(QObject::tr("Copying input data to remote target..."));

    const QString inputFile = copyInputFileOver();
    const QString tailoringFile = mSession->hasTailoring() ?
        copyFileOver(mSession->getTailoringFilePath()) : QString();

    if (mCancelRequested)
    {
        signalCompletion(true);
        return;
    }

    const QString reportFile = createRemoteTemporaryFile();
    const QString resultFile = createRemoteTemporaryFile();
    const QString arfFile = createRemoteTemporaryFile();
    const QString workingDir = createRemoteTemporaryDirectory();

    // TODO: We could be leaking any of the temporary files at this point!
    if (mCancelRequested)
    {
        signalCompletion(true);
        return;
    }

    QStringList args;

    if (mScannerMode == SM_OFFLINE_REMEDIATION)
    {
        args = buildOfflineRemediationArgs(inputFile,
                resultFile,
                reportFile,
                arfFile);
    }
    else
    {
        args = buildEvaluationArgs(inputFile,
                tailoringFile,
                resultFile,
                reportFile,
                arfFile,
                mScannerMode == SM_SCAN_ONLINE_REMEDIATION);
    }

    const QString sshCmd = args.join(" ");

    emit infoMessage(QObject::tr("Starting the remote process..."));

    QProcess process(this);

    process.start(SCAP_WORKBENCH_LOCAL_SSH_PATH, baseArgs + QStringList(QString("cd '%1'; " SCAP_WORKBENCH_REMOTE_OSCAP_PATH " %2").arg(workingDir).arg(sshCmd)));
    process.waitForStarted();

    if (process.state() != QProcess::Running)
    {
        emit errorMessage(QObject::tr("Failed to start ssh. Perhaps the executable was not found?"));
        mCancelRequested = true;
    }

    const unsigned int pollInterval = 100;

    emit infoMessage(QObject::tr("Processing on the remote machine..."));
    while (!process.waitForFinished(pollInterval))
    {
        // read everything new
        readStdOut(process);
        watchStdErr(process);

        // pump the event queue, mainly because the user might want to cancel
        QAbstractEventDispatcher::instance(mScanThread)->processEvents(QEventLoop::AllEvents);

        if (mCancelRequested)
        {
            emit infoMessage(QObject::tr("Cancellation was requested! Terminating..."));
            // TODO: On Windows we have to kill immediately, terminate() posts WM_CLOSE
            //       but oscap doesn't have any event loop running.
            process.terminate();
            break;
        }
    }

    if (mCancelRequested)
    {
        unsigned int waited = 0;
        while (!process.waitForFinished(pollInterval))
        {
            waited += pollInterval;
            if (waited > 10000) // 10 seconds should be enough for the process to terminate
            {
                emit warningMessage(QObject::tr("The oscap process didn't terminate in time, it will be killed instead."));
                // if it didn't terminate, we have to kill it at this point
                process.kill();
                break;
            }
        }
    }
    else
    {
        // read everything left over
        readStdOut(process);
        watchStdErr(process);

        mResults = readRemoteFile(resultFile, QObject::tr("XCCDF results")).toUtf8();
        mReport = readRemoteFile(reportFile, QObject::tr("XCCDF report (HTML)")).toUtf8();
        mARF = readRemoteFile(arfFile, QObject::tr("Result DataStream (ARF)")).toUtf8();
    }

    emit infoMessage(QObject::tr("Cleaning up..."));

    // Remove all the temporary remote files
    removeRemoteFile(inputFile, QObject::tr("input file"));
    if (!tailoringFile.isEmpty())
        removeRemoteFile(tailoringFile, QObject::tr("tailoring file"));
    removeRemoteFile(resultFile, QObject::tr("XCCDF result file"));
    removeRemoteFile(reportFile, QObject::tr("XCCDF report file"));
    removeRemoteFile(arfFile, QObject::tr("Result DataStream file"));
    removeRemoteDirectory(workingDir, QObject::tr("Temporary Working Directory"));

    emit infoMessage(QObject::tr("Processing has been finished!"));
    signalCompletion(mCancelRequested);
}
Esempio n. 3
0
void Sheeve::addReadLine(Sheeve::intrusive_ptr &result)
{

    DeclaredProcedure::shared_ptr proc(new DeclaredProcedure_Readln());
    result->addPrcedure(proc);
}
Esempio n. 4
0
 const TCHAR *GetValue() const
 {
     clib::recursive_mutex::scoped_lock proc(m_mutex);
     return m_value;
 }
Esempio n. 5
0
 const TCHAR *GetFileName() const
 {
     clib::recursive_mutex::scoped_lock proc(m_mutex);
     return m_fileName;
 }
Esempio n. 6
0
void
get_heap_info(
  size_t &		heap_size,
  size_t &		largest_free)
{
  heap_size = 0;
  largest_free = 0;

#if defined(SIERRA_HEAP_INFO)

# if defined(SIERRA_PTMALLOC3_ALLOCATOR) || defined(SIERRA_PTMALLOC2_ALLOCATOR)
  heap_size = malloc_used();
  
# elif 0 // if defined(REDS) // Redstorm now links in gnu's malloc
  static size_t reds_fragments;
  static unsigned long reds_total_free;
  static unsigned long reds_heap_size;
  static unsigned long reds_largest_free;

  ::heap_info(&reds_fragments, &reds_total_free, &reds_largest_free, &reds_heap_size);

  heap_size = reds_heap_size;
  largest_free = reds_largest_free;

  slibout.m(Slib::LOG_MEMORY) <<"reds_fragments " << reds_fragments
			      << ", reds_total_free " << reds_total_free
			      << ", reds_largest_free " << reds_largest_free
			      << ", reds_heap_size " << reds_heap_size << Diag::dendl;

# elif ( defined(__linux__) || defined(REDS) ) && ! defined(__IBMCPP__)
  static struct mallinfo minfo;
  minfo = mallinfo();
  heap_size = (unsigned int) minfo.uordblks + (unsigned int) minfo.hblkhd;
  largest_free = (unsigned int) minfo.fordblks;

  slibout.m(Slib::LOG_MEMORY) << "size_t size " << sizeof(size_t)*8 << " bits"
                              << ", heap size " << heap_size
                              << ", arena " << (unsigned int) minfo.arena
			      << ", ordblks " << minfo.ordblks
			      << ", smblks " << minfo.smblks
			      << ", hblks " << minfo.hblks
			      << ", hblkhd " << (unsigned int) minfo.hblkhd
			      << ", usmblks " << minfo.usmblks
			      << ", fsmblks " << minfo.fsmblks
			      << ", uordblks " << (unsigned int) minfo.uordblks
			      << ", fordblks " << (unsigned int) minfo.fordblks
			      << ", keepcost " << minfo.keepcost << Diag::dendl;


# elif defined(__sun)
  pstatus_t proc_status;

  std::ifstream proc("/proc/self/status", std::ios_base::in|std::ios_base::binary);
  if (proc) {
    proc.read((char *)&proc_status, sizeof(proc_status));
    heap_size = proc_status.pr_brksize;
    slibout.m(Slib::LOG_MEMORY) <<"pr_brksize " << proc_status.pr_brksize
				<< ", pr_stksize " << proc_status.pr_stksize << Diag::dendl;
  }
# endif
#endif // defined(SIERRA_HEAP_INFO)
}
Esempio n. 7
0
 const TCHAR * GetCacheID() const
 {
     clib::recursive_mutex::scoped_lock proc(m_mutex);
     return m_id;
 }
Esempio n. 8
0
void packages::sLoad()
{
  QProcess proc(this);
#ifdef Q_WS_MACX
  QString proc_path = QDir::cleanPath(qApp->applicationDirPath() +
                      "/../../../updater.app/Contents/MacOS/updater");
  QString proc_path2= QDir::cleanPath(qApp->applicationDirPath() +
                      "/../../../../Updater/updater.app/Contents/MacOS/updater");
#elif defined Q_WS_WIN
  QString proc_path = QDir::cleanPath(qApp->applicationDirPath() + "/updater.exe");
  QString proc_path2= QDir::cleanPath(qApp->applicationDirPath() + "/../Updater/updater.exe");
#else
  QString proc_path = QDir::cleanPath(qApp->applicationDirPath() + "/updater");
  QString proc_path2= QDir::cleanPath(qApp->applicationDirPath() + "/../Updater/updater");
#endif
  if (! QFile::exists(proc_path))
    proc_path = proc_path2;
  if (! QFile::exists(proc_path))
  {
#ifdef Q_WS_MACX
    if (QMessageBox::question(this, tr("Could Not Find Updater"),
                              tr("<p>xTuple ERP could not find the Updater "
                                 "application. Would you like to look for it?"),
                              QMessageBox::Yes | QMessageBox::Default,
                              QMessageBox::No) == QMessageBox::No)
      return;
#endif
    proc_path = QFileDialog::getOpenFileName(this,
                                             tr("Find Updater Application"));
    if (proc_path.isEmpty())
      return;
#ifdef Q_WS_MACX
    proc_path += "/Contents/MacOS/updater";
#endif
  }

  QStringList proc_args;
  QSqlDatabase db = QSqlDatabase::database();
  QString dbURL;
  buildDatabaseURL(dbURL, "QPSQL", db.hostName(), db.databaseName(),
                   QString::number(db.port()));
  proc_args << "-databaseURL=" + dbURL;
  if (! db.userName().isEmpty())
    proc_args << "-username="******"-passwd=" + db.password();

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  proc.start(proc_path, proc_args);
  if (proc.waitForStarted() &&
      proc.waitForFinished(-1) &&
      proc.exitStatus() == QProcess::NormalExit &&
      proc.exitCode() == 0)
  {
    QApplication::restoreOverrideCursor();
    sFillList();
  }
  else
  {
    if (! db.password().isEmpty())
    {
      proc_args.removeLast();
      proc_args << "-passwd=XXXXX";
    }
    QApplication::restoreOverrideCursor();
    systemError(this,
                tr("<p>There was an error running the Updater program: "
                   "<br>%1 %2<br><br><pre>%3</pre>")
		  .arg(proc_path)
                  .arg(proc_args.join(" "))
		  .arg(QString(proc.readAllStandardError())));
    return;
  }

  sFillList();
}
Esempio n. 9
0
void mapped_module::parseFileLineInfo() {
	static std::set< image * > haveParsedFileMap;
	
   image * fileOnDisk = obj()->parse_img();
	assert( fileOnDisk != NULL );
	if( haveParsedFileMap.count( fileOnDisk ) != 0 ) { return; }
	// /* DEBUG */ fprintf( stderr, "%s[%d]: Considering image at 0x%lx\n", __FILE__, __LINE__, fileOnDisk );

	/* FIXME: hack.  Should be argument to parseLineInformation(), which should in turn be merged
	   back into here so it can tell how far to extend the range of the last line information point. */
	Address baseAddress = obj()->codeBase();

	trueBaseAddress = baseAddress;

	const Object & xcoffObject = fileOnDisk->getObject();

	/* We haven't parsed this file already, so iterate over its stab entries. */
	char * stabstr = NULL;
	int nstabs = 0;
	SYMENT * syms = 0;
	char * stringpool = NULL;
	xcoffObject.get_stab_info( stabstr, nstabs, syms, stringpool );

	int nlines = 0;
	char * lines = NULL;
	unsigned long linesfdptr;
	xcoffObject.get_line_info( nlines, lines, linesfdptr );

	/* I'm not sure why the original code thought it should copy (short) names (through here). */
	char temporaryName[256];
	char * funcName = NULL;
	char * currentSourceFile = NULL;
   char *moduleName = NULL;

	/* Iterate over STAB entries. */
	for( int i = 0; i < nstabs; i++ ) {
		/* sizeof( SYMENT ) is 20, not 18, as it should be. */
		SYMENT * sym = (SYMENT *)( (unsigned)syms + (i * SYMESZ) );

      /* Get the name (period) */
      if (!sym->n_zeroes) {
         moduleName = &stringpool[sym->n_offset];
      } else {
         memset(temporaryName, 0, 9);
         strncpy(temporaryName, sym->n_name, 8);
         moduleName = temporaryName;
      }

	
		/* Extract the current source file from the C_FILE entries. */
		if( sym->n_sclass == C_FILE ) {
         if (!strcmp(moduleName, ".file")) {
            // The actual name is in an aux record.

            int j;
            /* has aux record with additional information. */
            for (j=1; j <= sym->n_numaux; j++) {
               union auxent *aux = (union auxent *) ((char *) sym + j * SYMESZ);
               if (aux->x_file._x.x_ftype == XFT_FN) {
                  // this aux record contains the file name.
                  if (!aux->x_file._x.x_zeroes) {
                     moduleName = &stringpool[aux->x_file._x.x_offset];
                  } else {
                     // x_fname is 14 bytes
                     memset(temporaryName, 0, 15);
                     strncpy(temporaryName, aux->x_file.x_fname, 14);
                     moduleName = temporaryName;
                  }
               }
            }
         }
			
         currentSourceFile = strrchr( moduleName, '/' );
         if( currentSourceFile == NULL ) { currentSourceFile = moduleName; }
         else { ++currentSourceFile; }
                    
         /* We're done with this entry. */
         continue;
      } /* end if C_FILE */
	
		/* This apparently compensates for a bug in the naming of certain entries. */
		char * nmPtr = NULL;
		if( 	! sym->n_zeroes && (
                                ( sym->n_sclass & DBXMASK ) ||
                                ( sym->n_sclass == C_BINCL ) ||
                                ( sym->n_sclass == C_EINCL )
                                ) ) {
			if( sym->n_offset < 3 ) {
				if( sym->n_offset == 2 && stabstr[ 0 ] ) {
					nmPtr = & stabstr[ 0 ];
            } else {
					nmPtr = & stabstr[ sym->n_offset ];
            }
         } else if( ! stabstr[ sym->n_offset - 3 ] ) {
				nmPtr = & stabstr[ sym->n_offset ];
         } else {
				/* has off by two error */
				nmPtr = & stabstr[ sym->n_offset - 2 ];
         } 
      } else {
			// names 8 or less chars on inline, not in stabstr
			memset( temporaryName, 0, 9 );
			strncpy( temporaryName, sym->n_name, 8 );
			nmPtr = temporaryName;
      } /* end bug compensation */

		/* Now that we've compensated for buggy naming, actually
		   parse the line information. */
		if(	( sym->n_sclass == C_BINCL ) 
            || ( sym->n_sclass == C_EINCL )
            || ( sym->n_sclass == C_FUN ) ) {
			if( funcName ) {
				free( funcName );
				funcName = NULL;
         }
			funcName = strdup( nmPtr );

			pdstring pdCSF( currentSourceFile );
			parseLineInformation( proc(), & pdCSF, funcName, (SYMENT *)sym, linesfdptr, lines, nlines );
      } /* end if we're actually parsing line information */
   } /* end iteration over STAB entries. */

	if( funcName != NULL ) { 
		free( funcName );
   }		
	haveParsedFileMap.insert( fileOnDisk );
} /* end parseFileLineInfo() */
Esempio n. 10
0
int
snmp_parse_args(int argc,
                char *const *argv,
                netsnmp_session * session, const char *localOpts,
                void (*proc) (int, char *const *, int))
{
    int             arg;
    char           *cp;
    char           *Apsz = NULL;
    char           *Xpsz = NULL;
    char           *Cpsz = NULL;
    char            Opts[BUF_SIZE];

    /*
     * initialize session to default values 
     */
    snmp_sess_init(session);
    strcpy(Opts, "Y:VhHm:M:O:I:P:D:dv:r:t:c:Z:e:E:n:u:l:x:X:a:A:p:T:-:3:");
    if (localOpts)
        strcat(Opts, localOpts);

    /*
     * get the options 
     */
    DEBUGMSGTL(("snmp_parse_args", "starting: %d/%d\n", optind, argc));
    for (arg = 0; arg < argc; arg++) {
        DEBUGMSGTL(("snmp_parse_args", " arg %d = %s\n", arg, argv[arg]));
    }

    optind = 1;
    while ((arg = getopt(argc, argv, Opts)) != EOF) {
        DEBUGMSGTL(("snmp_parse_args", "handling (#%d): %c\n", optind,
                    arg));
        switch (arg) {
        case '-':
            if (strcasecmp(optarg, "help") == 0) {
                return (-1);
            }
            if (strcasecmp(optarg, "version") == 0) {
                fprintf(stderr, "NET-SNMP version: %s\n",
                        netsnmp_get_version());
                return (-2);
            }

            handle_long_opt(optarg);
            break;

        case 'V':
            fprintf(stderr, "NET-SNMP version: %s\n",
                    netsnmp_get_version());
            return (-2);

        case 'h':
            return (-1);
            break;

        case 'H':
            init_snmp("snmpapp");
            fprintf(stderr, "Configuration directives understood:\n");
            read_config_print_usage("  ");
            return (-2);

        case 'Y':
            netsnmp_config_remember(optarg);
            break;

        case 'm':
            setenv("MIBS", optarg, 1);
            break;

        case 'M':
            setenv("MIBDIRS", optarg, 1);
            break;

        case 'O':
            cp = snmp_out_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr,
                        "Unknown output option passed to -O: %c.\n", *cp);
                return (-1);
            }
            break;

        case 'I':
            cp = snmp_in_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr, "Unknown input option passed to -I: %c.\n",
                        *cp);
                return (-1);
            }
            break;

        case 'P':
            cp = snmp_mib_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr,
                        "Unknown parsing option passed to -P: %c.\n", *cp);
                return (-1);
            }
            break;

        case 'D':
            debug_register_tokens(optarg);
            snmp_set_do_debugging(1);
            break;

        case 'd':
            ds_set_boolean(DS_LIBRARY_ID, DS_LIB_DUMP_PACKET, 1);
            break;

        case 'v':
            if (!strcmp(optarg, "1")) {
                session->version = SNMP_VERSION_1;
            } else if (!strcasecmp(optarg, "2c")) {
                session->version = SNMP_VERSION_2c;
            } else if (!strcasecmp(optarg, "3")) {
                session->version = SNMP_VERSION_3;
            } else {
                fprintf(stderr,
                        "Invalid version specified after -v flag: %s\n",
                        optarg);
                return (-1);
            }
            break;

        case 'p':
            fprintf(stderr, "Warning: -p option is no longer used - ");
            fprintf(stderr, "specify the remote host as HOST:PORT\n");
            return (-1);
            break;

        case 'T':
            fprintf(stderr, "Warning: -T option is no longer used - ");
            fprintf(stderr, "specify the remote host as TRANSPORT:HOST\n");
            return (-1);
            break;

        case 't':
            session->timeout = atoi(optarg) * 1000000L;
            if (session->timeout < 0 || !isdigit(optarg[0])) {
                fprintf(stderr,
                        "Invalid timeout in seconds after -t flag.\n");
                return (-1);
            }
            break;

        case 'r':
            session->retries = atoi(optarg);
            if (session->retries < 0 || !isdigit(optarg[0])) {
                fprintf(stderr,
                        "Invalid number of retries after -r flag.\n");
                return (-1);
            }
            break;

        case 'c':
            Cpsz = optarg;
            break;

        case '3':
            if (snmpv3_options(optarg, session, &Apsz, &Xpsz, argc, argv) <
                0) {
                return (-1);
            }
            break;

#define SNMPV3_CMD_OPTIONS
#ifdef  SNMPV3_CMD_OPTIONS
        case 'Z':
            session->engineBoots = strtoul(optarg, NULL, 10);
            if (session->engineBoots == 0 || !isdigit(optarg[0])) {
                fprintf(stderr,
                        "Need engine boots value after -Z flag.\n");
                return (-1);
            }
            cp = strchr(optarg, ',');
            if (cp && *(++cp) && isdigit(*cp))
                session->engineTime = strtoul(cp, NULL, 10);
            /*
             * Handle previous '-Z boot time' syntax 
             */
            else if ((optind < argc) && isdigit(argv[optind][0]))
                session->engineTime = strtoul(argv[optind], NULL, 10);
            else {
                fprintf(stderr, "Need engine time value after -Z flag.\n");
                return (-1);
            }
            break;

        case 'e':{
                size_t          ebuf_len = 32, eout_len = 0;
                u_char         *ebuf = (u_char *) malloc(ebuf_len);

                if (ebuf == NULL) {
                    fprintf(stderr,
                            "malloc failure processing -e flag.\n");
                    return (-1);
                }
                if (!snmp_hex_to_binary
                    (&ebuf, &ebuf_len, &eout_len, 1, optarg)) {
                    fprintf(stderr,
                            "Bad engine ID value after -e flag.\n");
                    free(ebuf);
                    return (-1);
                }
                session->securityEngineID = ebuf;
                session->securityEngineIDLen = eout_len;
                break;
            }

        case 'E':{
                size_t          ebuf_len = 32, eout_len = 0;
                u_char         *ebuf = (u_char *) malloc(ebuf_len);

                if (ebuf == NULL) {
                    fprintf(stderr,
                            "malloc failure processing -E flag.\n");
                    return (-1);
                }
                if (!snmp_hex_to_binary
                    (&ebuf, &ebuf_len, &eout_len, 1, optarg)) {
                    fprintf(stderr,
                            "Bad engine ID value after -E flag.\n");
                    free(ebuf);
                    return (-1);
                }
                session->contextEngineID = ebuf;
                session->contextEngineIDLen = eout_len;
                break;
            }

        case 'n':
            session->contextName = optarg;
            session->contextNameLen = strlen(optarg);
            break;

        case 'u':
            session->securityName = optarg;
            session->securityNameLen = strlen(optarg);
            break;

        case 'l':
            if (!strcasecmp(optarg, "noAuthNoPriv") || !strcmp(optarg, "1")
                || !strcasecmp(optarg, "nanp")) {
                session->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
            } else if (!strcasecmp(optarg, "authNoPriv")
                       || !strcmp(optarg, "2")
                       || !strcasecmp(optarg, "anp")) {
                session->securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
            } else if (!strcasecmp(optarg, "authPriv")
                       || !strcmp(optarg, "3")
                       || !strcasecmp(optarg, "ap")) {
                session->securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
            } else {
                fprintf(stderr,
                        "Invalid security level specified after -l flag: %s\n",
                        optarg);
                return (-1);
            }

            break;

        case 'a':
            if (!strcasecmp(optarg, "MD5")) {
                session->securityAuthProto = usmHMACMD5AuthProtocol;
                session->securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
            } else if (!strcasecmp(optarg, "SHA")) {
                session->securityAuthProto = usmHMACSHA1AuthProtocol;
                session->securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
            } else {
                fprintf(stderr,
                        "Invalid authentication protocol specified after -a flag: %s\n",
                        optarg);
                return (-1);
            }
            break;

        case 'x':
            if (!strcasecmp(optarg, "DES")) {
                session->securityPrivProto = usmDESPrivProtocol;
                session->securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
            } else {
                fprintf(stderr,
                        "Invalid privacy protocol specified after -x flag: %s\n",
                        optarg);
                return (-1);
            }
            break;

        case 'A':
            Apsz = optarg;
            break;

        case 'X':
            Xpsz = optarg;
            break;
#endif                          /* SNMPV3_CMD_OPTIONS */

        case '?':
            return (-1);
            break;

        default:
            proc(argc, argv, arg);
            break;
        }
    }
    DEBUGMSGTL(("snmp_parse_args", "finished: %d/%d\n", optind, argc));

    /*
     * read in MIB database and initialize the snmp library
     */
    init_snmp("snmpapp");

    /*
     * session default version 
     */
    if (session->version == SNMP_DEFAULT_VERSION) {
        /*
         * run time default version 
         */
        session->version = ds_get_int(DS_LIBRARY_ID, DS_LIB_SNMPVERSION);

        /*
         * compile time default version 
         */
        if (!session->version) {
            switch (SNMP_DEFAULT_VERSION) {
            case 1:
                session->version = SNMP_VERSION_1;
                break;

            case 2:
                session->version = SNMP_VERSION_2c;
                break;

            case 3:
                session->version = SNMP_VERSION_3;
                break;
            }
        } else {
            if (session->version == DS_SNMP_VERSION_1)  /* bogus value.  version 1 actually = 0 */
                session->version = SNMP_VERSION_1;
        }
    }

    /*
     * make master key from pass phrases 
     */
    if (Apsz) {
        session->securityAuthKeyLen = USM_AUTH_KU_LEN;
        if (session->securityAuthProto == NULL) {
            /*
             * get .conf set default 
             */
            const oid      *def =
                get_default_authtype(&session->securityAuthProtoLen);
            session->securityAuthProto =
                snmp_duplicate_objid(def, session->securityAuthProtoLen);
        }
        if (session->securityAuthProto == NULL) {
            /*
             * assume MD5 
             */
            session->securityAuthProto =
                snmp_duplicate_objid(usmHMACMD5AuthProtocol,
                                     USM_AUTH_PROTO_MD5_LEN);
            session->securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
        }
        if (generate_Ku(session->securityAuthProto,
                        session->securityAuthProtoLen,
                        (u_char *) Apsz, strlen(Apsz),
                        session->securityAuthKey,
                        &session->securityAuthKeyLen) != SNMPERR_SUCCESS) {
            snmp_perror(argv[0]);
            fprintf(stderr,
                    "Error generating a key (Ku) from the supplied authentication pass phrase. \n");
            return (-2);
        }
    }
    if (Xpsz) {
        session->securityPrivKeyLen = USM_PRIV_KU_LEN;
        if (session->securityPrivProto == NULL) {
            /*
             * get .conf set default 
             */
            const oid      *def =
                get_default_privtype(&session->securityPrivProtoLen);
            session->securityPrivProto =
                snmp_duplicate_objid(def, session->securityPrivProtoLen);
        }
        if (session->securityPrivProto == NULL) {
            /*
             * assume DES 
             */
            session->securityPrivProto =
                snmp_duplicate_objid(usmDESPrivProtocol,
                                     USM_PRIV_PROTO_DES_LEN);
            session->securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
        }
        if (generate_Ku(session->securityAuthProto,
                        session->securityAuthProtoLen,
                        (u_char *) Xpsz, strlen(Xpsz),
                        session->securityPrivKey,
                        &session->securityPrivKeyLen) != SNMPERR_SUCCESS) {
            snmp_perror(argv[0]);
            fprintf(stderr,
                    "Error generating a key (Ku) from the supplied privacy pass phrase. \n");
            return (-2);
        }
    }
    /*
     * get the hostname 
     */
    if (optind == argc) {
        fprintf(stderr, "No hostname specified.\n");
        return (-1);
    }
    session->peername = argv[optind++]; /* hostname */

    /*
     * If v1 or v2c, check community has been set, either by a -c option above,
     * or via a default token somewhere.  
     */

    if (session->version == SNMP_VERSION_1 ||
        session->version == SNMP_VERSION_2c) {
        if (Cpsz == NULL) {
            Cpsz = ds_get_string(DS_LIBRARY_ID, DS_LIB_COMMUNITY);
        }
        if (Cpsz == NULL) {
            fprintf(stderr, "No community name specified.\n");
            return (-1);
        }
        session->community = (unsigned char *) Cpsz;
        session->community_len = strlen(Cpsz);
    }
    return optind;
}
Esempio n. 11
0
 int LuaIOLib::io_close(lua_State *lua)
 {
     auto process = proc(lua);
     process->write_std_out("Close!");
     return 0;
 }
Esempio n. 12
0
File: 2458.cpp Progetto: kyg516/ps
int main()
{
	proc();
	return 0;
}
Esempio n. 13
0
/*
 * This method does the real work for snmp_parse_args.  It takes an
 * extra argument, proxy, and uses this to decide how to handle the lack of
 * of a community string.
 */
int
snmp_parse_args(int argc,
                char **argv,
                netsnmp_session * session, const char *localOpts,
                void (*proc) (int, char *const *, int))
{
    static char	   *sensitive[4] = { NULL, NULL, NULL, NULL };
    int             arg, sp = 0, zero_sensitive = 1, testcase = 0;
    char           *cp;
    char           *Apsz = NULL;
    char           *Xpsz = NULL;
    char           *Cpsz = NULL;
    char            Opts[BUF_SIZE];
    int             logopt = 0;

    /*
     * initialize session to default values
     */
    snmp_sess_init(session);
    strcpy(Opts, "Y:VhHm:M:O:I:P:D:dv:r:t:c:Z:e:E:n:u:l:x:X:a:A:p:T:-:3:s:S:L:");
    if (localOpts)
        strcat(Opts, localOpts);

    if (strcmp(argv[0], "snmpd-trapsess") == 0 ||
            strcmp(argv[0], "snmpd-proxy")    == 0) {
        /*  Don't worry about zeroing sensitive parameters as they are not
            on the command line anyway (called from internal config-line
            handler).  */
        zero_sensitive = 0;
    }

    /*
     * get the options
     */
    DEBUGMSGTL(("snmp_parse_args", "starting: %d/%d\n", optind, argc));
    for (arg = 0; arg < argc; arg++) {
        DEBUGMSGTL(("snmp_parse_args", " arg %d = %s\n", arg, argv[arg]));
    }

    optind = 1;
    while ((arg = getopt(argc, argv, Opts)) != EOF) {
        DEBUGMSGTL(("snmp_parse_args", "handling (#%d): %c\n", optind, arg));
        switch (arg) {
        case '-':
            if (strcasecmp(optarg, "help") == 0) {
                return (-1);
            }
            if (strcasecmp(optarg, "version") == 0) {
                fprintf(stderr,"NET-SNMP version: %s\n",netsnmp_get_version());
                return (-2);
            }

            handle_long_opt(optarg);
            break;

        case 'V':
            fprintf(stderr, "NET-SNMP version: %s\n", netsnmp_get_version());
            return (-2);

        case 'h':
            return (-1);
            break;

        case 'H':
            init_snmp("snmpapp");
            fprintf(stderr, "Configuration directives understood:\n");
            read_config_print_usage("  ");
            return (-2);

        case 'Y':
            netsnmp_config_remember(optarg);
            break;

#ifndef NETSNMP_DISABLE_MIB_LOADING
        case 'm':
            setenv("MIBS", optarg, 1);
            break;

        case 'M':
            netsnmp_get_mib_directory(); /* prepare the default directories */
            netsnmp_set_mib_directory(optarg);
            break;
#endif /* NETSNMP_DISABLE_MIB_LOADING */

        case 'O':
            cp = snmp_out_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr, "Unknown output option passed to -O: %c.\n",
                        *cp);
                return (-1);
            }
            break;

        case 'I':
            cp = snmp_in_options(optarg, argc, argv);
            if (cp != NULL) {
                fprintf(stderr, "Unknown input option passed to -I: %c.\n",
                        *cp);
                return (-1);
            }
            break;

#ifndef NETSNMP_DISABLE_MIB_LOADING
        case 'P':
            cp = snmp_mib_toggle_options(optarg);
            if (cp != NULL) {
                fprintf(stderr,
                        "Unknown parsing option passed to -P: %c.\n", *cp);
                return (-1);
            }
            break;
#endif /* NETSNMP_DISABLE_MIB_LOADING */

        case 'D':
            debug_register_tokens(optarg);
            snmp_set_do_debugging(1);
            break;

        case 'd':
            netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
                                   NETSNMP_DS_LIB_DUMP_PACKET, 1);
            break;

        case 'v':
            session->version = -1;
#ifndef NETSNMP_DISABLE_SNMPV1
            if (!strcmp(optarg, "1")) {
                session->version = SNMP_VERSION_1;
            }
#endif
#ifndef NETSNMP_DISABLE_SNMPV2C
            if (!strcasecmp(optarg, "2c")) {
                session->version = SNMP_VERSION_2c;
            }
#endif
            if (!strcasecmp(optarg, "3")) {
                session->version = SNMP_VERSION_3;
            }
            if (session->version == -1) {
                fprintf(stderr,
                        "Invalid version specified after -v flag: %s\n",
                        optarg);
                return (-1);
            }
            break;

        case 'p':
            fprintf(stderr, "Warning: -p option is no longer used - ");
            fprintf(stderr, "specify the remote host as HOST:PORT\n");
            return (-1);
            break;

        case 'T':
            fprintf(stderr, "Warning: -T option is no longer used - ");
            fprintf(stderr, "specify the remote host as TRANSPORT:HOST\n");
            return (-1);
            break;

        case 't':
            session->timeout = (long)(atof(optarg) * 1000000L);
            if (session->timeout <= 0) {
                fprintf(stderr, "Invalid timeout in seconds after -t flag.\n");
                return (-1);
            }
            break;

        case 'r':
            session->retries = atoi(optarg);
            if (session->retries < 0 || !isdigit(optarg[0])) {
                fprintf(stderr, "Invalid number of retries after -r flag.\n");
                return (-1);
            }
            break;

        case 'c':
            if (zero_sensitive) {
                if ((sensitive[sp] = strdup(optarg)) != NULL) {
                    Cpsz = sensitive[sp];
                    memset(optarg, '\0', strlen(optarg));
                    sp++;
                } else {
                    fprintf(stderr, "malloc failure processing -c flag.\n");
                    return -1;
                }
            } else {
                Cpsz = optarg;
            }
            break;

#ifndef NO_SNMPV3
        case '3':
            /*  TODO: This needs to zero things too.  */
            if (snmpv3_options(optarg, session, &Apsz, &Xpsz, argc, argv) < 0) {
                return (-1);
            }
            break;

        case 'L':
            if (snmp_log_options(optarg, argc, argv) < 0) {
                return (-1);
            }
            logopt = 1;
            break;
#endif

#ifndef NO_SNMPV3
#define SNMPV3_CMD_OPTIONS
#endif
#ifdef  SNMPV3_CMD_OPTIONS
        case 'Z':
            errno = 0;
            session->engineBoots = strtoul(optarg, &cp, 10);
            if (errno || cp == optarg) {
                fprintf(stderr, "Need engine boots value after -Z flag.\n");
                return (-1);
            }
            if (*cp == ',') {
                char *endptr;
                cp++;
                session->engineTime = strtoul(cp, &endptr, 10);
                if (errno || cp == endptr) {
                    fprintf(stderr, "Need engine time after \"-Z engineBoot,\".\n");
                    return (-1);
                }
            }
            /*
             * Handle previous '-Z boot time' syntax
             */
            else if (optind < argc) {
                session->engineTime = strtoul(argv[optind], &cp, 10);
                if (errno || cp == argv[optind]) {
                    fprintf(stderr, "Need engine time after \"-Z engineBoot\".\n");
                    return (-1);
                }
            } else {
                fprintf(stderr, "Need engine time after \"-Z engineBoot\".\n");
                return (-1);
            }
            break;

        case 'e': {
            size_t ebuf_len = 32, eout_len = 0;
            u_char *ebuf = (u_char *)malloc(ebuf_len);

            if (ebuf == NULL) {
                fprintf(stderr, "malloc failure processing -e flag.\n");
                return (-1);
            }
            if (!snmp_hex_to_binary
                    (&ebuf, &ebuf_len, &eout_len, 1, optarg)) {
                fprintf(stderr, "Bad engine ID value after -e flag.\n");
                free(ebuf);
                return (-1);
            }
            if ((eout_len < 5) || (eout_len > 32)) {
                fprintf(stderr, "Invalid engine ID value after -e flag.\n");
                free(ebuf);
                return (-1);
            }
            session->securityEngineID = ebuf;
            session->securityEngineIDLen = eout_len;
            break;
        }

        case 'E': {
            size_t ebuf_len = 32, eout_len = 0;
            u_char *ebuf = (u_char *)malloc(ebuf_len);

            if (ebuf == NULL) {
                fprintf(stderr, "malloc failure processing -E flag.\n");
                return (-1);
            }
            if (!snmp_hex_to_binary(&ebuf, &ebuf_len,
                                    &eout_len, 1, optarg)) {
                fprintf(stderr, "Bad engine ID value after -E flag.\n");
                free(ebuf);
                return (-1);
            }
            if ((eout_len < 5) || (eout_len > 32)) {
                fprintf(stderr, "Invalid engine ID value after -E flag.\n");
                free(ebuf);
                return (-1);
            }
            session->contextEngineID = ebuf;
            session->contextEngineIDLen = eout_len;
            break;
        }

        case 'n':
            session->contextName = optarg;
            session->contextNameLen = strlen(optarg);
            break;

        case 'u':
            if (zero_sensitive) {
                if ((sensitive[sp] = strdup(optarg)) != NULL) {
                    session->securityName = sensitive[sp];
                    session->securityNameLen = strlen(sensitive[sp]);
                    memset(optarg, '\0', strlen(optarg));
                    sp++;
                } else {
                    fprintf(stderr, "malloc failure processing -u flag.\n");
                    return -1;
                }
            } else {
                session->securityName = optarg;
                session->securityNameLen = strlen(optarg);
            }
            break;

        case 'l':
            if (!strcasecmp(optarg, "noAuthNoPriv") || !strcmp(optarg, "1")
                    || !strcasecmp(optarg, "noauth")
                    || !strcasecmp(optarg, "nanp")) {
                session->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
            } else if (!strcasecmp(optarg, "authNoPriv")
                       || !strcmp(optarg, "2")
                       || !strcasecmp(optarg, "auth")
                       || !strcasecmp(optarg, "anp")) {
                session->securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
            } else if (!strcasecmp(optarg, "authPriv")
                       || !strcmp(optarg, "3")
                       || !strcasecmp(optarg, "priv")
                       || !strcasecmp(optarg, "ap")) {
                session->securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
            } else {
                fprintf(stderr,
                        "Invalid security level specified after -l flag: %s\n",
                        optarg);
                return (-1);
            }

            break;

        case 'a':
#ifndef NETSNMP_DISABLE_MD5
            if (!strcasecmp(optarg, "MD5")) {
                session->securityAuthProto = usmHMACMD5AuthProtocol;
                session->securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
            } else
#endif
                if (!strcasecmp(optarg, "SHA")) {
                    session->securityAuthProto = usmHMACSHA1AuthProtocol;
                    session->securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
                } else {
                    fprintf(stderr,
                            "Invalid authentication protocol specified after -a flag: %s\n",
                            optarg);
                    return (-1);
                }
            break;

        case 'x':
            testcase = 0;
#ifndef NETSNMP_DISABLE_DES
            if (!strcasecmp(optarg, "DES")) {
                testcase = 1;
                session->securityPrivProto = usmDESPrivProtocol;
                session->securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
            }
#endif
#ifdef HAVE_AES
            if (!strcasecmp(optarg, "AES128") ||
                    !strcasecmp(optarg, "AES")) {
                testcase = 1;
                session->securityPrivProto = usmAESPrivProtocol;
                session->securityPrivProtoLen = USM_PRIV_PROTO_AES_LEN;
            }
#endif
            if (testcase == 0) {
                fprintf(stderr,
                        "Invalid privacy protocol specified after -x flag: %s\n",
                        optarg);
                return (-1);
            }
            break;

        case 'A':
            if (zero_sensitive) {
                if ((sensitive[sp] = strdup(optarg)) != NULL) {
                    Apsz = sensitive[sp];
                    memset(optarg, '\0', strlen(optarg));
                    sp++;
                } else {
                    fprintf(stderr, "malloc failure processing -A flag.\n");
                    return -1;
                }
            } else {
                Apsz = optarg;
            }
            break;

        case 'X':
            if (zero_sensitive) {
                if ((sensitive[sp] = strdup(optarg)) != NULL) {
                    Xpsz = sensitive[sp];
                    memset(optarg, '\0', strlen(optarg));
                    sp++;
                } else {
                    fprintf(stderr, "malloc failure processing -X flag.\n");
                    return -1;
                }
            } else {
                Xpsz = optarg;
            }
            break;
#endif                          /* SNMPV3_CMD_OPTIONS */

        case '?':
            return (-1);
            break;

        default:
            proc(argc, argv, arg);
            break;
        }
    }
    DEBUGMSGTL(("snmp_parse_args", "finished: %d/%d\n", optind, argc));

    if (!logopt)
        snmp_enable_stderrlog();

    /*
     * read in MIB database and initialize the snmp library
     */
    init_snmp("snmpapp");

    /*
     * session default version
     */
    if (session->version == SNMP_DEFAULT_VERSION) {
        /*
         * run time default version
         */
        session->version = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID,
                                              NETSNMP_DS_LIB_SNMPVERSION);

        /*
         * compile time default version
         */
        if (!session->version) {
            switch (NETSNMP_DEFAULT_SNMP_VERSION) {
#ifndef NETSNMP_DISABLE_SNMPV1
            case 1:
                session->version = SNMP_VERSION_1;
                break;
#endif

#ifndef NETSNMP_DISABLE_SNMPV2C
            case 2:
                session->version = SNMP_VERSION_2c;
                break;
#endif

#ifndef NO_SNMPV3
            case 3:
                session->version = SNMP_VERSION_3;
                break;
#endif

            default:
                snmp_log(LOG_ERR, "Can't determine a valid SNMP version for the session\n");
                return(-2);
            }
        } else {
#ifndef NETSNMP_DISABLE_SNMPV1
            if (session->version == NETSNMP_DS_SNMP_VERSION_1)  /* bogus value.  version 1 actually = 0 */
                session->version = SNMP_VERSION_1;
#endif
        }
    }

#ifndef NO_SNMPV3
    /*
     * make master key from pass phrases
     */
    if (Apsz) {
        session->securityAuthKeyLen = USM_AUTH_KU_LEN;
        if (session->securityAuthProto == NULL) {
            /*
             * get .conf set default
             */
            const oid      *def =
                get_default_authtype(&session->securityAuthProtoLen);
            session->securityAuthProto =
                snmp_duplicate_objid(def, session->securityAuthProtoLen);
        }
        if (session->securityAuthProto == NULL) {
#ifndef NETSNMP_DISABLE_MD5
            /*
             * assume MD5
             */
            session->securityAuthProto =
                snmp_duplicate_objid(usmHMACMD5AuthProtocol,
                                     USM_AUTH_PROTO_MD5_LEN);
            session->securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
#else
            session->securityAuthProto =
                snmp_duplicate_objid(usmHMACSHA1AuthProtocol,
                                     USM_AUTH_PROTO_SHA_LEN);
            session->securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
#endif
        }
        if (generate_Ku(session->securityAuthProto,
                        session->securityAuthProtoLen,
                        (u_char *) Apsz, strlen(Apsz),
                        session->securityAuthKey,
                        &session->securityAuthKeyLen) != SNMPERR_SUCCESS) {
            snmp_perror(argv[0]);
            fprintf(stderr,
                    "Error generating a key (Ku) from the supplied authentication pass phrase. \n");
            return (-2);
        }
    }
    if (Xpsz) {
        session->securityPrivKeyLen = USM_PRIV_KU_LEN;
        if (session->securityPrivProto == NULL) {
            /*
             * get .conf set default
             */
            const oid      *def =
                get_default_privtype(&session->securityPrivProtoLen);
            session->securityPrivProto =
                snmp_duplicate_objid(def, session->securityPrivProtoLen);
        }
        if (session->securityPrivProto == NULL) {
            /*
             * assume DES
             */
#ifndef NETSNMP_DISABLE_DES
            session->securityPrivProto =
                snmp_duplicate_objid(usmDESPrivProtocol,
                                     USM_PRIV_PROTO_DES_LEN);
            session->securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
#else
            session->securityPrivProto =
                snmp_duplicate_objid(usmAESPrivProtocol,
                                     USM_PRIV_PROTO_AES_LEN);
            session->securityPrivProtoLen = USM_PRIV_PROTO_AES_LEN;
#endif

        }
        if (generate_Ku(session->securityAuthProto,
                        session->securityAuthProtoLen,
                        (u_char *) Xpsz, strlen(Xpsz),
                        session->securityPrivKey,
                        &session->securityPrivKeyLen) != SNMPERR_SUCCESS) {
            snmp_perror(argv[0]);
            fprintf(stderr,
                    "Error generating a key (Ku) from the supplied privacy pass phrase. \n");
            return (-2);
        }
    }
#endif

    /*
     * get the hostname
     */
    if (optind == argc) {
        fprintf(stderr, "No hostname specified.\n");
        return (-1);
    }
    session->peername = argv[optind++]; /* hostname */

#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
    /*
     * If v1 or v2c, check community has been set, either by a -c option above,
     * or via a default token somewhere.
     * If neither, it will be taken from the incoming request PDU.
     */

#if defined(NETSNMP_DISABLE_SNMPV1)
    if (session->version == SNMP_VERSION_2c)
#else
#if defined(NETSNMP_DISABLE_SNMPV2C)
    if (session->version == SNMP_VERSION_1)
#else
    if (session->version == SNMP_VERSION_1 ||
            session->version == SNMP_VERSION_2c)
#endif
#endif
    {
        if (Cpsz == NULL) {
            Cpsz = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID,
                                         NETSNMP_DS_LIB_COMMUNITY);
            if (Cpsz == NULL) {
                if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID,
                                           NETSNMP_DS_LIB_IGNORE_NO_COMMUNITY)) {
                    DEBUGMSGTL(("snmp_parse_args",
                                "ignoring that the community string is not present\n"));
                    session->community = NULL;
                    session->community_len = 0;
                } else {
                    fprintf(stderr, "No community name specified.\n");
                    return (-1);
                }
            }
        } else {
            session->community = (unsigned char *)Cpsz;
            session->community_len = strlen(Cpsz);
        }
    }
#endif /* support for community based SNMP */

    return optind;
}
void collect_func_decls(ast_manager & m, expr * n, func_decl_set & r, bool ng_only) {
    collect_dependencies_proc proc(m, r, ng_only);
    for_each_expr(proc, n);
}
Esempio n. 15
0
bool instrCodeNode::loadInstrIntoApp() 
{
    if (instrLoaded()) {
        return true;
    }

    // These need to be consistent; if not, move them into
    // this class.
    assert(V.instrCatchuped_ == false);
    
    // Loop thru "instRequests", an array of instReqNode:
    // (Here we insert code instrumentation, tramps, etc. via addInstFunc())
    unsigned int inst_size = V.instRequests.size();

    //cerr << "instrCodeNode id: " << getID() << " attempted insert of " 
    //     << inst_size << " instRequests\n";

    for (unsigned u1=0; u1<inst_size; u1++) {
        // code executed later (prepareCatchupInstr) may also manually trigger 
        // the instrumentation via inferiorRPC.
        instReqNode *instReq = V.instRequests[u1];
        
        bool success = instReq->loadInstrIntoApp(proc());
        if (!success) {
          fprintf(stderr, "%s[%d]:  failed to loadInstrIntoApp\n", FILE__, __LINE__);
          return false;
        }

#if 0  //  DISABLED
        // Commented out deferred instru 'cause we don't
        // relocate right now.
        unmarkAsDeferred();
        switch(res) {
        case deferred_res:
            markAsDeferred();
            //           cerr << "marking " << (void*)this << " " << u1+1 << " / "
            //     << inst_size << " as deferred\n";
            return inst_insert_deferred;
            break;
        case failure_res:
            //cerr << "instRequest.insertInstr - wasn't successful\n";
            return inst_insert_failure;
            break;
        case success_res:
            //cerr << "instrRequest # " << u1+1 << " / " << inst_size
            //     << "inserted\n";
            // Interesting... it's possible that this minitramp writes to more
            // than one variable (data, constraint, "temp" vector)
            {
                pdvector<instrDataNode *> affectedNodes;
                getDataNodes(&affectedNodes);
                for (unsigned i = 0; i < affectedNodes.size(); i++)
                    affectedNodes[i]->incRefCount();
                V.registerCallback(instReq);
                break;
            }
        }
#endif
        
    }
    V.instrLoaded_ = true;
    return inst_insert_success;
}
Esempio n. 16
0
void PCA_BuildSave(char *image_dir, int blocks)
{
	char path[40];
	int fcount = 30, descsize;
	double *desc;
	cv::Mat cinput, coutput;

	sprintf(path, "%s/image1", image_dir);
	cinput = cv::imread(path);
	
	format_image(cinput, coutput);
	
	Gist_Processor proc(coutput, blocks);

	cv::Mat PCAm(fcount, proc.base_descsize, CV_64FC1);

	for (int i=0; i < fcount; i++) {

		sprintf(path, "%s/image%d", image_dir, i);
		printf("Image %d\n", i);
		cinput = cv::imread(path);
	
		format_image(cinput, coutput);
		proc.Process(coutput);

		descsize = proc.Get_Descriptor(&desc,blocks);
		
		
		for (int d=0; d < descsize; d++) {
			//((double *)Row.data)[d] = desc[d];
			PCAm.at<double>(i,d) = desc[d];
			
		}

		free(desc);
		
	}
	
	cv::PCA pca_obj(PCAm, cv::Mat(), CV_PCA_DATA_AS_ROW, PCA_DIM);
	
	printf("type %d %d %d\n", pca_obj.eigenvectors.type(), CV_64FC1, CV_64FC1);
	
	sprintf(path, "./PCAeigenvectors%d.mat", blocks);

	FILE *fd = fopen(path, "w+");
	
	if (!fd) {
			printf("%s\n", path);
            perror("Error opening file for loading %s\n");
            return;
    }

	fprintf(fd, "%d\n%d\n", pca_obj.eigenvectors.rows, pca_obj.eigenvectors.cols);

	for (int j=0; j < pca_obj.eigenvectors.rows; j++) {
		for (int i=0; i < pca_obj.eigenvectors.cols; i++) {
			fprintf(fd, "%f\n", pca_obj.eigenvectors.at<double>(j,i));
		}
	}
	fclose(fd);


	sprintf(path, "./PCAmean%d.mat", blocks);
	fd = fopen(path, "w+");
	if (!fd) {
            perror("Error opening file for loading\n");
            return;
    }	
	fprintf(fd, "%d\n%d\n", pca_obj.mean.rows, pca_obj.mean.cols);	

	for (int j=0; j < pca_obj.mean.rows; j++) {
		for (int i=0; i < pca_obj.mean.cols; i++) {
			fprintf(fd, "%f\n", pca_obj.mean.at<double>(j,i));
		}
	}
	fclose(fd);
	
}
Esempio n. 17
0
int netscan_done(struct netscan_t *scan, void *arg, int (*proc)(unsigned int addr, unsigned short port, void *arg))
{
	unsigned int addr, i = 0, j = 0;
	unsigned short port = 0;
	int scan_flag = 0, no_port = 0;
	
	if(!scan)
		return -1;
	if(!netscan_check(scan)){
		return -1;
	}
	
	if(test_bit(SCAN_FLAG_ASCEND, &scan->flags))
		scan_flag = SCAN_FLAG_ASCEND;
	else if(test_bit(SCAN_FLAG_DESCEND, &scan->flags))
		scan_flag = SCAN_FLAG_DESCEND;
	else
		scan_flag = SCAN_FLAG_RANDOM;

	if(test_bit(SCAN_FLAG_NO_PORT, &scan->flags))
		no_port = 1;

	if(test_bit(SCAN_FLAG_ADDR_CONTINUE, &scan->flags)){
		for(addr=scan->saddr; addr<=scan->eaddr; addr++){
			if(no_port){
				proc(addr, 0, arg);
				continue;
			}
			
			if(scan_flag == SCAN_FLAG_ASCEND){
				for(port=scan->sport; port<=scan->eport; port++){
					proc(addr, port, arg);
				}
			}
			else if(scan_flag == SCAN_FLAG_DESCEND){
				for(port=scan->eport; port<=scan->sport; port++){
					proc(addr, port, arg);
				}
			}
			else{
				for(i=0; i<scan->port_num; i++){
					port = scan->port[i];
					proc(addr, port, arg);
				}
			}
		}
	}
	else{
		for(j=0; j<scan->addr_num; j++){
			addr = scan->addr[j];

			if(no_port){
				proc(addr, 0, arg);
				continue;
			}
			
			if(scan_flag == SCAN_FLAG_ASCEND){
				for(port=scan->sport; port<=scan->eport; port++){
					proc(addr, port, arg);
				}
			}
			else if(scan_flag == SCAN_FLAG_DESCEND){
				for(port=scan->eport; port<=scan->sport; port++){
					proc(addr, port, arg);
				}
			}
			else{
				for(i=0; i<scan->port_num; i++){
					port = scan->port[i];
					proc(addr, port, arg);
				}
			}
		}
	}
	
	return 0;
}
Esempio n. 18
0
/******************************************************************************
 * frameworks/base/media/mediaserver/main_mediaserver.cpp
 *
 * Library:
 * LOCAL_MODULE:= mediaserver
 *
 * system/core/rootdir/init.rc
 *
 * service media /system/bin/mediaserver
    user media
    group system audio camera graphics inet net_bt net_bt_admin
 *
 */
int main(int argc, char** argv)
{
    // Get IServiceManager
    sp<ProcessState> proc(ProcessState::self());
    sp<IServiceManager> sm = defaultServiceManager();

    AudioFlinger::instantiate();
    // void AudioFlinger::instantiate()
    {
        // AudioFlinger <-- BnAudioFlinger <-- BnInterface<IAudioFlinger> <--
        // BBinder <-- IBinder <-- RefBase
        defaultServiceManager()->addService(String16("media.audio_flinger"), new AudioFlinger());
        // status_t BpServiceManager::addService(const String16& name, const
        // sp<IBinder>& service)
        //
        // The service is IAudioFlinger as BBinder and IBinder interface.
        {
            Parcel data, reply;
            // write to IServiceManager
            data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
            // write name "android.media.IAudioFlinger"
            data.writeString16(name);
            data.writeStrongBinder(service);
            // status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
            {
                flatten_binder(ProcessState::self(), val, this);
                // status_t flatten_binder(const sp<ProcessState>& proc, const
                // sp<IBinder>& binder, Parcel* out)
                {
                    flat_binder_object obj;

                    IBinder *local = binder->localBinder();
                    // BBinder* BBinder::localBinder()
                    //
                    // AudioFlinger is derived from BBinder, so it shall call
                    // BBinder::localBinder() to return itself
                    //
                    // TODO: check if the pointer will be switched to handle in
                    // binder driver
                    {
                        return this;
                    }

                    obj.type = BINDER_TYPE_BINDER;
                    obj.binder = local->getWeakRefs();
                    obj.cookie = local;

                    finish_flatten_binder(binder, obj, out);
                    // inline static status_t finish_flatten_binder(const
                    // sp<IBinder>& binder, const flat_binder_object& flat,
                    // Parcel* out)
                    {
                        out->writeObject(flat, false);
                    }

                    // After the packet for addService RPC call is made,
                    // BpServiceManager::addService will call BpBinder’s
                    // transact.
                    //

                }
            } // writeStrongBinder()
        }
    }

    MediaPlayerService::instantiate();
    // void MediaPlayerService::instantiate()
    // frameworks/base/media/libmediaplayerservice/MediaPlayerService.cpp
    // TODO: how to connect the pointer to the handle??
    {
        defaultServiceManager()->addService(
            String16("media.player"), new MediaPlayerService());
    }


}
Esempio n. 19
0
void glAddSwapHintRectWINWrapperNonstatic(GLint x, GLint y, GLsizei width, GLsizei height)
{
  RESOLVE(PFNGLADDSWAPHINTRECTWIN, "glAddSwapHintRectWIN");
  proc(x, y, width, height);
}
Esempio n. 20
0
 boost::signals::connection on_refresh_connect(const localfile_slot_type& s)
 {
     clib::recursive_mutex::scoped_lock proc(m_mutex);
     return on_refresh.connect(s); 
 }
Esempio n. 21
0
 int GetSequence() const
 {
     clib::recursive_mutex::scoped_lock proc(m_mutex);
     return m_sequence;
 }
Esempio n. 22
0
 int GetType() const
 {
     clib::recursive_mutex::scoped_lock proc(m_mutex);
     return m_type;
 }
Esempio n. 23
0
 const TCHAR *GetLink() const
 {
     clib::recursive_mutex::scoped_lock proc(m_mutex);
     return m_link;
 }
Esempio n. 24
0
 const TCHAR *GetSource() const
 {
     clib::recursive_mutex::scoped_lock proc(m_mutex);
     return m_source;
 }
Esempio n. 25
0
 __int64 GetTotal() const
 {
     clib::recursive_mutex::scoped_lock proc(m_mutex);
     return m_total;
 }
Esempio n. 26
0
 const TCHAR *GetDestination() const
 {
     clib::recursive_mutex::scoped_lock proc(m_mutex);
     return m_destination;
 }
Esempio n. 27
0
void Sheeve::addWriteln(Sheeve::intrusive_ptr &result)
{

    DeclaredProcedure::shared_ptr proc(new DeclaredProcedure_Writeln());
    result->addPrcedure(proc);
}
Esempio n. 28
0
Spectrum PhotonIntegrator::Li(const Scene *scene, const Renderer *renderer,
        const RayDifferential &ray, const Intersection &isect,
        const Sample *sample, MemoryArena &arena) const {
    Spectrum L(0.);
    Vector wo = -ray.d;
    // Compute emitted light if ray hit an area light source
    L += isect.Le(wo);

    // Evaluate BSDF at hit point
    BSDF *bsdf = isect.GetBSDF(ray, arena);
    const Point &p = bsdf->dgShading.p;
    const Normal &n = bsdf->dgShading.nn;
    L += UniformSampleAllLights(scene, renderer, arena, p, n,
        wo, isect.rayEpsilon, bsdf, sample,
        lightSampleOffsets, bsdfSampleOffsets);
    // Compute caustic lighting for photon map integrator
    L += LPhoton(causticMap, nCausticPaths, nLookup, arena, bsdf,
                 *sample->rng, isect, wo, maxDistSquared);

    // Compute indirect lighting for photon map integrator
    if (finalGather) {
    #if 1
        // Do one-bounce final gather for photon map
        BxDFType nonSpecular = BxDFType(BSDF_REFLECTION |
            BSDF_TRANSMISSION | BSDF_DIFFUSE | BSDF_GLOSSY);
        if (bsdf->NumComponents(nonSpecular) > 0) {
            // Find indirect photons around point for importance sampling
            const u_int nIndirSamplePhotons = 50;
            PhotonProcess proc(nIndirSamplePhotons,
                               arena.Alloc<ClosePhoton>(nIndirSamplePhotons));
            float searchDist2 = maxDistSquared;
            while (proc.nFound < nIndirSamplePhotons) {
                float md2 = searchDist2;
                proc.nFound = 0;
                indirectMap->Lookup(p, proc, md2);
                searchDist2 *= 2.f;
            }

            // Copy photon directions to local array
            Vector *photonDirs = arena.Alloc<Vector>(nIndirSamplePhotons);
            for (u_int i = 0; i < nIndirSamplePhotons; ++i)
                photonDirs[i] = proc.photons[i].photon->wi;

            // Use BSDF to do final gathering
            Spectrum Li = 0.;
            for (int i = 0; i < gatherSamples; ++i) {
                // Sample random direction from BSDF for final gather ray
                Vector wi;
                float pdf;
                BSDFSample bsdfSample(sample, bsdfGatherSampleOffsets, i);
                Spectrum fr = bsdf->Sample_f(wo, &wi, bsdfSample,
                                             &pdf, BxDFType(BSDF_ALL & ~BSDF_SPECULAR));
                if (fr.IsBlack() || pdf == 0.f) continue;
                Assert(pdf >= 0.f);

                // Trace BSDF final gather ray and accumulate radiance
                RayDifferential bounceRay(p, wi, ray, isect.rayEpsilon);
                Intersection gatherIsect;
                if (scene->Intersect(bounceRay, &gatherIsect)) {
                    // Compute exitant radiance _Lindir_ using radiance photons
                    Spectrum Lindir = 0.f;
                    Normal nGather = gatherIsect.dg.nn;
                    nGather = Faceforward(nGather, -bounceRay.d);
                    RadiancePhotonProcess proc(nGather);
                    float md2 = INFINITY;
                    radianceMap->Lookup(gatherIsect.dg.p, proc, md2);
                    if (proc.photon != NULL)
                        Lindir = proc.photon->Lo;
                    Lindir *= renderer->Transmittance(scene, bounceRay, NULL, arena,
                                                      sample->rng);

                    // Compute MIS weight for BSDF-sampled gather ray

                    // Compute PDF for photon-sampling of direction _wi_
                    float photonPdf = 0.f;
                    float conePdf = UniformConePdf(cosGatherAngle);
                    for (u_int j = 0; j < nIndirSamplePhotons; ++j)
                        if (Dot(photonDirs[j], wi) > .999f * cosGatherAngle)
                            photonPdf += conePdf;
                    photonPdf /= nIndirSamplePhotons;
                    float wt = PowerHeuristic(gatherSamples, pdf, gatherSamples, photonPdf);
                    Li += fr * Lindir * AbsDot(wi, n) * wt / pdf;
                }
            }
            L += Li / gatherSamples;

            // Use nearby photons to do final gathering
            Li = 0.;
            for (int i = 0; i < gatherSamples; ++i) {
                // Sample random direction using photons for final gather ray
                BSDFSample gatherSample(sample, indirGatherSampleOffsets, i);
                int photonNum = min((int)nIndirSamplePhotons - 1,
                    Floor2Int(gatherSample.uComponent * nIndirSamplePhotons));

                // Sample gather ray direction from _photonNum_
                Vector vx, vy;
                CoordinateSystem(photonDirs[photonNum], &vx, &vy);
                Vector wi = UniformSampleCone(gatherSample.uDir[0], gatherSample.uDir[1],
                                              cosGatherAngle, vx, vy, photonDirs[photonNum]);

                // Trace photon-sampled final gather ray and accumulate radiance
                Spectrum fr = bsdf->f(wo, wi);
                if (fr.IsBlack()) continue;
                RayDifferential bounceRay(p, wi, ray, isect.rayEpsilon);
                Intersection gatherIsect;
                PBRT_PHOTON_MAP_STARTED_GATHER_RAY(&bounceRay);
                if (scene->Intersect(bounceRay, &gatherIsect)) {
                    // Compute exitant radiance _Lindir_ using radiance photons
                    Spectrum Lindir = 0.f;
                    Normal nGather = gatherIsect.dg.nn;
                    nGather = Faceforward(nGather, -bounceRay.d);
                    RadiancePhotonProcess proc(nGather);
                    float md2 = INFINITY;
                    radianceMap->Lookup(gatherIsect.dg.p, proc, md2);
                    if (proc.photon != NULL)
                        Lindir = proc.photon->Lo;
                    Lindir *= renderer->Transmittance(scene, bounceRay, NULL, arena,
                                                      sample->rng);

                    // Compute PDF for photon-sampling of direction _wi_
                    float photonPdf = 0.f;
                    float conePdf = UniformConePdf(cosGatherAngle);
                    for (u_int j = 0; j < nIndirSamplePhotons; ++j)
                        if (Dot(photonDirs[j], wi) > .999f * cosGatherAngle)
                            photonPdf += conePdf;
                    photonPdf /= nIndirSamplePhotons;

                    // Compute MIS weight for photon-sampled gather ray
                    float bsdfPdf = bsdf->Pdf(wo, wi);
                    float wt = PowerHeuristic(gatherSamples, photonPdf, gatherSamples, bsdfPdf);
                    Li += fr * Lindir * AbsDot(wi, n) * wt / photonPdf;
                }
                PBRT_PHOTON_MAP_FINISHED_GATHER_RAY(&bounceRay);
            }
            L += Li / gatherSamples;
        }
    #else
        // for debugging / examples: use the photon map directly
        Normal nn = Faceforward(n, -ray.d);
        RadiancePhotonProcess proc(nn);
        float md2 = INFINITY;
        radianceMap->Lookup(p, proc, md2);
        if (proc.photon)
            L += proc.photon->Lo;
    #endif
    }
    else
        L += LPhoton(indirectMap, nIndirectPaths, nLookup, arena,
                     bsdf, *sample->rng, isect, wo, maxDistSquared);
    if (ray.depth+1 < maxSpecularDepth) {
        Vector wi;
        // Trace rays for specular reflection and refraction
        L += SpecularReflect(ray, bsdf, *sample->rng, isect, renderer,
                             scene, sample, arena);
        L += SpecularTransmit(ray, bsdf, *sample->rng, isect, renderer,
                              scene, sample, arena);
    }
    return L;
}
Esempio n. 29
0
int main(int argc, char* argv[]) {
    int opt;
    auto pss_sort = [](const Vma& a, const Vma& b) {
        uint64_t pss_a = a.usage.pss;
        uint64_t pss_b = b.usage.pss;
        return pss_a > pss_b;
    };

    auto uss_sort = [](const Vma& a, const Vma& b) {
        uint64_t uss_a = a.usage.uss;
        uint64_t uss_b = b.usage.uss;
        return uss_a > uss_b;
    };

    std::function<bool(const Vma& a, const Vma& b)> sort_func = nullptr;
    while ((opt = getopt(argc, argv, "himpuWw")) != -1) {
        switch (opt) {
            case 'h':
                hide_zeroes = true;
                break;
            case 'i':
                // TODO: libmeminfo doesn't support the flag to chose
                // between idle page tracking vs clear_refs. So for now,
                // this flag is unused and the library defaults to using
                // /proc/<pid>/clear_refs for finding the working set.
                use_pageidle = true;
                break;
            case 'm':
                // this is the default
                break;
            case 'p':
                sort_func = pss_sort;
                break;
            case 'u':
                sort_func = uss_sort;
                break;
            case 'W':
                reset_wss = true;
                break;
            case 'w':
                show_wss = true;
                break;
            case '?':
                usage(EXIT_SUCCESS);
            default:
                usage(EXIT_FAILURE);
        }
    }

    if (optind != (argc - 1)) {
        fprintf(stderr, "Need exactly one pid at the end\n");
        usage(EXIT_FAILURE);
    }

    pid_t pid = atoi(argv[optind]);
    if (pid == 0) {
        std::cerr << "Invalid process id" << std::endl;
        exit(EXIT_FAILURE);
    }

    if (reset_wss) {
        if (!ProcMemInfo::ResetWorkingSet(pid)) {
            std::cerr << "Failed to reset working set of pid : " << pid << std::endl;
            exit(EXIT_FAILURE);
        }
        return 0;
    }

    ProcMemInfo proc(pid, show_wss);
    const MemUsage& proc_stats = proc.Usage();
    std::vector<Vma> maps(proc.Maps());
    if (sort_func != nullptr) {
        std::sort(maps.begin(), maps.end(), sort_func);
    }

    return show(proc_stats, maps);
}
Esempio n. 30
0
void Drive::Mount(HWND hwnd)
{
  // check drive empty or require a new drive
  while (GetDriveType(mnt) != DRIVE_NO_ROOT_DIR) {
    char drive = SelectFreeDrive(hwnd);
    if (!drive)
      return;
    _stprintf(mnt, _T("%c:\\"), drive);
    Save();
  }

  // check directory existence
  if (!encfs::isDirectory(wchar_to_utf8_cstr(dir.c_str()).c_str())) {
    if (YesNo(hwnd, _T("Directory does not exists. Remove from list?")))
      Drives::Delete(shared_from_this());
    return;
  }

  // TODO check configuration still exists ?? ... no can cause recursion problem

  // search if executable is present
  TCHAR executable[MAX_PATH];
  if (!SearchPath(NULL, _T("encfs.exe"), NULL, LENGTH(executable), executable, NULL))
    throw truntime_error(_T("Unable to find encfs.exe file"));

  // ask a password to mount
  TCHAR pass[128 + 2];
  if (!GetPassword(hwnd, pass, LENGTH(pass) - 2))
    return;
  _tcscat(pass, _T("\r\n"));

  // mount using a sort of popen
  TCHAR cmd[2048];
  _sntprintf(cmd, LENGTH(cmd), _T("\"%s\" -S -f \"%s\" %c:"), executable, dir.c_str(), mnt[0]);
  std::shared_ptr<SubProcessInformations> proc(new SubProcessInformations);
  proc->creationFlags = CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW;
  if (!CreateSubProcess(cmd, proc.get())) {
    DWORD err = GetLastError();
    memset(pass, 0, sizeof(pass));
    _sntprintf(cmd, LENGTH(cmd), _T("Error: %s (%u)"), proc->errorPart, (unsigned)err);
    throw truntime_error(cmd);
  }
  subProcess = proc;

  // send the password
  std::string pwd = wchar_to_utf8_cstr(pass);
  DWORD written;
  WriteFile(proc->hIn, pwd.c_str(), pwd.length(), &written, NULL);
  CloseHandle(proc->hIn);	// close input so sub process does not any more
  proc->hIn = NULL;
  memset(pass, 0, sizeof(pass));
  memset((char*)pwd.c_str(), 0, pwd.length());

  mounted = false;

  // wait for mount, read error and give feedback
  for (unsigned n = 0; n < 5 * 10; ++n) {
    // drive appeared
    if (GetDriveType(mnt) != DRIVE_NO_ROOT_DIR) {
      if (Drives::autoShow)
        Show(hwnd);
      break;
    }

    // process terminated
    DWORD readed;
    char output[2048];
    switch (WaitForSingleObject(subProcess->hProcess, 200)) {
    case WAIT_OBJECT_0:
    case WAIT_ABANDONED:
      if (ReadFile(proc->hOut, output, sizeof(output) - 1, &readed, NULL)) {
        output[readed] = 0;
        utf8_to_wchar_buf(output, cmd, LENGTH(cmd));
      }
      else {
        _stprintf(cmd, _T("Unknown error mounting drive %c:"), mnt[0]);
      }
      subProcess.reset();
      throw truntime_error(cmd);
    }
  }
  if (subProcess)
    mounted = true;
  Save(); // save for resume
}