Example #1
0
// Initialize library.
// To be called once during the lifetime of the app.
// $package: The folder where the package data resides.
// $webroot: The document root folder for the web server.
void bibledit_initialize_library (const char * package, const char * webroot)
{
  // Must initialize libcurl before any threads are started.
#ifdef HAVE_CLIENT
#else
  curl_global_init (CURL_GLOBAL_ALL);
#endif
  
  // Thread locking.
  thread_setup ();
  
  // Initialize SQLite: Full thread safety: https://www.sqlite.org/c3ref/threadsafe.html.
  // This is supported to prevent "database locked" errors.
  if (!sqlite3_threadsafe ()) {
    cerr << "SQLite is not threadsafe" << endl;
  }
  sqlite3_config (SQLITE_CONFIG_SERIALIZED);

  // Binary file mode on Windows.
#ifdef HAVE_WINDOWS
  _set_fmode (_O_BINARY);
#endif

  // Set the web root folder.
  config_globals_document_root = webroot;
  
  // Initialize SSL/TLS (after webroot has been set).
  filter_url_ssl_tls_initialize ();
  
#ifndef HAVE_CLIENT
  // Cloud initializes OpenLDAP server access settings (after webroot has been set).
  ldap_logic_initialize ();
#endif

#ifdef HAVE_CLIENT
  // Set local timezone offset in the library.
#ifdef HAVE_WINDOWS
  TIME_ZONE_INFORMATION tzi;
  DWORD dwRet = GetTimeZoneInformation (&tzi);
  (void)dwRet;
  int offset = 0 - (tzi.Bias / 60);
  bibledit_set_timezone_hours_offset_utc (offset);
#else
  time_t t = time (NULL);
  struct tm lt = {};
  localtime_r (&t, &lt);
  int offset = round (lt.tm_gmtoff / 3600);
  bibledit_set_timezone_hours_offset_utc (offset);
#endif
  
#endif

  // Initialize data in a thread.
  thread setup_thread = thread (setup_conditionally, package);
  setup_thread.detach ();
  
  // Multiple start/stop guard.
  bibledit_started = false;
}
Example #2
0
/* this is called from main() in s_entry.c */
int sys_main(int argc, char **argv)
{
    int i, noprefs;
    sys_externalschedlib = 0;
    sys_extraflags = 0;
#ifdef PD_DEBUG
    fprintf(stderr, "Pd: COMPILED FOR DEBUGGING\n");
#endif
    /* use Win32 "binary" mode by default since we don't want the
     * translation that Win32 does by default */
#ifdef _WIN32
# ifdef _MSC_VER /* MS Visual Studio */
    _set_fmode( _O_BINARY );
# else  /* MinGW */
    {
        extern int _fmode;
        _fmode = _O_BINARY;
    }
# endif /* _MSC_VER */
#endif  /* WIN32 */
    pd_init();                                  /* start the message system */
    sys_findprogdir(argv[0]);                   /* set sys_progname, guipath */
    for (i = noprefs = 0; i < argc; i++)        /* prescan args for noprefs */
        if (!strcmp(argv[i], "-noprefs"))
            noprefs = 1;
    if (!noprefs)
        sys_loadpreferences();                  /* load default settings */
#ifndef _WIN32
    if (!noprefs)
        sys_rcfile();                           /* parse the startup file */
#endif
    if (sys_argparse(argc-1, argv+1))           /* parse cmd line */
        return (1);
    sys_afterargparse();                    /* post-argparse settings */
    if (sys_verbose || sys_version) fprintf(stderr, "%s compiled %s %s\n",
        pd_version, pd_compiletime, pd_compiledate);
    if (sys_version)    /* if we were just asked our version, exit here. */
        return (0);
    sys_setsignalhandlers();
    if (sys_startgui(sys_libdir->s_name))       /* start the gui */
        return (1);
    if (sys_externalschedlib)
        return (sys_run_scheduler(sys_externalschedlibname,
            sys_extraflagsstring));
    else if (sys_batch)
        return (m_batchmain());
    else
    {
            /* open audio and MIDI */
        sys_reopen_midi();
        if (audio_shouldkeepopen())
            sys_reopen_audio();
            /* run scheduler until it quits */
        return (m_mainloop());
    }
}
Example #3
0
int
main(int argc, char **argv)
{
    struct CmdLine cmdline;
    struct cmd_syndesc *ts;
    int err = 0;

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a
     * crash (i.e. core is generated) we can include the user's data section
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGABRT, &nsa, NULL);
    sigaction(SIGSEGV, &nsa, NULL);
#endif

    /* Initialize directory paths */
    if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
#ifdef AFS_NT40_ENV
	ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
#endif
	fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
		argv[0]);
	exit(2);
    }
#ifdef AFS_NT40_ENV
    /* Default to binary mode for fopen() */
    _set_fmode(_O_BINARY);

    main_thread = pthread_self();
    if (spawnDatap && spawnDataLen) {
	/* This is a child per partition salvager. Don't setup log or
	 * try to lock the salvager lock.
	 */
	if (nt_SetupPartitionSalvage(spawnDatap, spawnDataLen) < 0)
	    exit(3);
    } else {
#endif

#ifndef AFS_NT40_ENV
	if (geteuid() != 0) {
	    printf("Salvager must be run as root.\n");
	    fflush(stdout);
	    Exit(0);
	}
#endif

	/* Get and hold a lock for the duration of the salvage to make sure
	 * that no other salvage runs at the same time.  The routine
	 * VInitVolumePackage2 (called below) makes sure that a file server or
	 * other volume utilities don't interfere with the salvage.
	 */
	get_salvage_lock = 1;
#ifdef AFS_NT40_ENV
    }
#endif

    cmdline.argc = argc;
    cmdline.argv = argv;
    ts = cmd_CreateSyntax("initcmd", handleit, &cmdline, 0, "initialize the program");
    cmd_AddParm(ts, "-partition", CMD_SINGLE, CMD_OPTIONAL,
		"Name of partition to salvage");
    cmd_AddParm(ts, "-volumeid", CMD_SINGLE, CMD_OPTIONAL,
		"Volume Id to salvage");
    cmd_AddParm(ts, "-debug", CMD_FLAG, CMD_OPTIONAL,
		"Run in Debugging mode");
    cmd_AddParm(ts, "-nowrite", CMD_FLAG, CMD_OPTIONAL,
		"Run readonly/test mode");
    cmd_AddParm(ts, "-inodes", CMD_FLAG, CMD_OPTIONAL,
		"Just list affected afs inodes - debugging flag");
    cmd_AddParm(ts, "-force", CMD_FLAG, CMD_OPTIONAL, "Force full salvaging");
    cmd_AddParm(ts, "-oktozap", CMD_FLAG, CMD_OPTIONAL,
		"Give permission to destroy bogus inodes/volumes - debugging flag");
    cmd_AddParm(ts, "-rootinodes", CMD_FLAG, CMD_OPTIONAL,
		"Show inodes owned by root - debugging flag");
    cmd_AddParm(ts, "-salvagedirs", CMD_FLAG, CMD_OPTIONAL,
		"Force rebuild/salvage of all directories");
    cmd_AddParm(ts, "-blockreads", CMD_FLAG, CMD_OPTIONAL,
		"Read smaller blocks to handle IO/bad blocks");
    cmd_AddParm(ts, "-parallel", CMD_SINGLE, CMD_OPTIONAL,
		"# of max parallel partition salvaging");
    cmd_AddParm(ts, "-tmpdir", CMD_SINGLE, CMD_OPTIONAL,
		"Name of dir to place tmp files ");
    cmd_AddParm(ts, "-showlog", CMD_FLAG, CMD_OPTIONAL,
		"Show log file upon completion");
    cmd_AddParm(ts, "-showsuid", CMD_FLAG, CMD_OPTIONAL,
		"Report on suid/sgid files");
    cmd_AddParm(ts, "-showmounts", CMD_FLAG, CMD_OPTIONAL,
		"Report on mountpoints");
    cmd_AddParm(ts, "-orphans", CMD_SINGLE, CMD_OPTIONAL,
		"ignore | remove | attach");

    /* note - syslog isn't avail on NT, but if we make it conditional, have
     * to deal with screwy offsets for cmd params */
    cmd_AddParm(ts, "-syslog", CMD_FLAG, CMD_OPTIONAL,
		"Write salvage log to syslogs");
    cmd_AddParm(ts, "-syslogfacility", CMD_SINGLE, CMD_OPTIONAL,
		"Syslog facility number to use");
    cmd_AddParm(ts, "-datelogs", CMD_FLAG, CMD_OPTIONAL,
		"Include timestamp in logfile filename");
#ifdef FAST_RESTART
    cmd_AddParm(ts, "-DontSalvage", CMD_FLAG, CMD_OPTIONAL,
		"Don't salvage. This my be set in BosConfig to let the fileserver restart immediately after a crash. Bad volumes will be taken offline");
#elif defined(AFS_DEMAND_ATTACH_FS)
    cmd_Seek(ts, 20); /* skip DontSalvage */
    cmd_AddParm(ts, "-forceDAFS", CMD_FLAG, CMD_OPTIONAL,
		"For Demand Attach Fileserver, permit a manual volume salvage outside of the salvageserver");
#endif /* FAST_RESTART */
    cmd_Seek(ts, 21); /* skip DontSalvage and forceDAFS if needed */
    cmd_AddParm(ts, "-f", CMD_FLAG, CMD_OPTIONAL, "Alias for -force");
    err = cmd_Dispatch(argc, argv);
    Exit(err);
    return 0; /* not reached */
}
Example #4
0
// On Android, there there is a libqgis.so instead of a qgis executable.
// The main method symbol of this library needs to be exported so it can be called by java
// On Windows this main is included in qgis_app and called from mainwin.cpp
APP_EXPORT
#endif
int main( int argc, char *argv[] )
{
#ifdef Q_OS_MACX
  // Increase file resource limits (i.e., number of allowed open files)
  // (from code provided by Larry Biehl, Purdue University, USA, from 'MultiSpec' project)
  // This is generally 256 for the soft limit on Mac
  // NOTE: setrlimit() must come *before* initialization of stdio strings,
  //       e.g. before any debug messages, or setrlimit() gets ignored
  // see: http://stackoverflow.com/a/17726104/2865523
  struct rlimit rescLimit;
  if ( getrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 )
  {
    rlim_t oldSoft( rescLimit.rlim_cur );
    rlim_t oldHard( rescLimit.rlim_max );
#ifdef OPEN_MAX
    rlim_t newSoft( OPEN_MAX );
    rlim_t newHard( std::min( oldHard, newSoft ) );
#else
    rlim_t newSoft( 4096 );
    rlim_t newHard( std::min( ( rlim_t )8192, oldHard ) );
#endif
    if ( rescLimit.rlim_cur < newSoft )
    {
      rescLimit.rlim_cur = newSoft;
      rescLimit.rlim_max = newHard;

      if ( setrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 )
      {
        QgsDebugMsg( QString( "Mac RLIMIT_NOFILE Soft/Hard NEW: %1 / %2" )
                     .arg( rescLimit.rlim_cur ).arg( rescLimit.rlim_max ) );
      }
    }
    Q_UNUSED( oldSoft ); //avoid warnings
    QgsDebugMsg( QString( "Mac RLIMIT_NOFILE Soft/Hard ORIG: %1 / %2" )
                 .arg( oldSoft ).arg( oldHard ) );
  }
#endif

  QgsDebugMsg( QString( "Starting qgis main" ) );
#ifdef WIN32  // Windows
#ifdef _MSC_VER
  _set_fmode( _O_BINARY );
#else //MinGW
  _fmode = _O_BINARY;
#endif  // _MSC_VER
#endif  // WIN32

  // Set up the custom qWarning/qDebug custom handler
#ifndef ANDROID
  qInstallMsgHandler( myMessageOutput );
#endif

#if (defined(linux) && !defined(ANDROID)) || defined(__FreeBSD__)
  signal( SIGQUIT, qgisCrash );
  signal( SIGILL, qgisCrash );
  signal( SIGFPE, qgisCrash );
  signal( SIGSEGV, qgisCrash );
  signal( SIGBUS, qgisCrash );
  signal( SIGSYS, qgisCrash );
  signal( SIGTRAP, qgisCrash );
  signal( SIGXCPU, qgisCrash );
  signal( SIGXFSZ, qgisCrash );
#endif

#ifdef Q_OS_WIN
  SetUnhandledExceptionFilter( QgsCrashHandler::handle );
#endif

  // initialize random number seed
  qsrand( time( nullptr ) );

  /////////////////////////////////////////////////////////////////
  // Command line options 'behavior' flag setup
  ////////////////////////////////////////////////////////////////

  //
  // Parse the command line arguments, looking to see if the user has asked for any
  // special behaviors. Any remaining non command arguments will be kept aside to
  // be passed as a list of layers and / or a project that should be loaded.
  //

  // This behavior is used to load the app, snapshot the map,
  // save the image to disk and then exit
  QString mySnapshotFileName;
  QString configLocalStorageLocation;
  QString profileName;
  int mySnapshotWidth = 800;
  int mySnapshotHeight = 600;

  bool myHideSplash = false;
  bool mySettingsMigrationForce = false;
  bool mySkipVersionCheck = false;
#if defined(ANDROID)
  QgsDebugMsg( QString( "Android: Splash hidden" ) );
  myHideSplash = true;
#endif

  bool myRestoreDefaultWindowState = false;
  bool myRestorePlugins = true;
  bool myCustomization = true;

  QString dxfOutputFile;
  QgsDxfExport::SymbologyExport dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology;
  double dxfScale = 50000.0;
  QString dxfEncoding = QStringLiteral( "CP1252" );
  QString dxfPreset;
  QgsRectangle dxfExtent;

  // This behavior will set initial extent of map canvas, but only if
  // there are no command line arguments. This gives a usable map
  // extent when qgis starts with no layers loaded. When layers are
  // loaded, we let the layers define the initial extent.
  QString myInitialExtent;
  if ( argc == 1 )
    myInitialExtent = QStringLiteral( "-1,-1,1,1" );

  // This behavior will allow you to force the use of a translation file
  // which is useful for testing
  QString myTranslationCode;

  // The user can specify a path which will override the default path of custom
  // user settings (~/.qgis) and it will be used for QgsSettings INI file
  QString configpath;
  QString authdbdirectory;

  QString pythonfile;

  QString customizationfile;
  QString globalsettingsfile;

// TODO Fix android
#if defined(ANDROID)
  QgsDebugMsg( QString( "Android: All params stripped" ) );// Param %1" ).arg( argv[0] ) );
  //put all QGIS settings in the same place
  configpath = QgsApplication::qgisSettingsDirPath();
  QgsDebugMsg( QString( "Android: configpath set to %1" ).arg( configpath ) );
#endif

  QStringList args;

  if ( !bundleclicked( argc, argv ) )
  {
    // Build a local QCoreApplication from arguments. This way, arguments are correctly parsed from their native locale
    // It will use QString::fromLocal8Bit( argv ) under Unix and GetCommandLine() under Windows.
    QCoreApplication coreApp( argc, argv );
    args = QCoreApplication::arguments();

    for ( int i = 1; i < args.size(); ++i )
    {
      const QString &arg = args[i];

      if ( arg == QLatin1String( "--help" ) || arg == QLatin1String( "-?" ) )
      {
        usage( args[0] );
        return 2;
      }
      else if ( arg == QLatin1String( "--nologo" ) || arg == QLatin1String( "-n" ) )
      {
        myHideSplash = true;
      }
      else if ( arg == QLatin1String( "--version-migration" ) )
      {
        mySettingsMigrationForce = true;
      }
      else if ( arg == QLatin1String( "--noversioncheck" ) || arg == QLatin1String( "-V" ) )
      {
        mySkipVersionCheck = true;
      }
      else if ( arg == QLatin1String( "--noplugins" ) || arg == QLatin1String( "-P" ) )
      {
        myRestorePlugins = false;
      }
      else if ( arg == QLatin1String( "--nocustomization" ) || arg == QLatin1String( "-C" ) )
      {
        myCustomization = false;
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--profile" ) ) )
      {
        profileName = args[++i];
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--profiles-path" ) || arg == QLatin1String( "-s" ) ) )
      {
        configLocalStorageLocation = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--snapshot" ) || arg == QLatin1String( "-s" ) ) )
      {
        mySnapshotFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--width" ) || arg == QLatin1String( "-w" ) ) )
      {
        mySnapshotWidth = QString( args[++i] ).toInt();
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--height" ) || arg == QLatin1String( "-h" ) ) )
      {
        mySnapshotHeight = QString( args[++i] ).toInt();
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--lang" ) || arg == QLatin1String( "-l" ) ) )
      {
        myTranslationCode = args[++i];
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--project" ) || arg == QLatin1String( "-p" ) ) )
      {
        sProjectFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--extent" ) || arg == QLatin1String( "-e" ) ) )
      {
        myInitialExtent = args[++i];
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--authdbdirectory" ) || arg == QLatin1String( "-a" ) ) )
      {
        authdbdirectory = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() );
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--code" ) || arg == QLatin1String( "-f" ) ) )
      {
        pythonfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--customizationfile" ) || arg == QLatin1String( "-z" ) ) )
      {
        customizationfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == QLatin1String( "--globalsettingsfile" ) || arg == QLatin1String( "-g" ) ) )
      {
        globalsettingsfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( arg == QLatin1String( "--defaultui" ) || arg == QLatin1String( "-d" ) )
      {
        myRestoreDefaultWindowState = true;
      }
      else if ( arg == QLatin1String( "--dxf-export" ) )
      {
        dxfOutputFile = args[++i];
      }
      else if ( arg == QLatin1String( "--dxf-extent" ) )
      {
        QgsLocaleNumC l;
        QString ext( args[++i] );
        QStringList coords( ext.split( ',' ) );

        if ( coords.size() != 4 )
        {
          std::cerr << "invalid dxf extent " << ext.toStdString() << std::endl;
          return 2;
        }

        for ( int i = 0; i < 4; i++ )
        {
          bool ok;
          double d;

          d = coords[i].toDouble( &ok );
          if ( !ok )
          {
            std::cerr << "invalid dxf coordinate " << coords[i].toStdString() << " in extent " << ext.toStdString() << std::endl;
            return 2;
          }

          switch ( i )
          {
            case 0:
              dxfExtent.setXMinimum( d );
              break;
            case 1:
              dxfExtent.setYMinimum( d );
              break;
            case 2:
              dxfExtent.setXMaximum( d );
              break;
            case 3:
              dxfExtent.setYMaximum( d );
              break;
          }
        }
      }
      else if ( arg == QLatin1String( "--dxf-symbology-mode" ) )
      {
        QString mode( args[++i] );
        if ( mode == QLatin1String( "none" ) )
        {
          dxfSymbologyMode = QgsDxfExport::NoSymbology;
        }
        else if ( mode == QLatin1String( "symbollayer" ) )
        {
          dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology;
        }
        else if ( mode == QLatin1String( "feature" ) )
        {
          dxfSymbologyMode = QgsDxfExport::FeatureSymbology;
        }
        else
        {
          std::cerr << "invalid dxf symbology mode " << mode.toStdString() << std::endl;
          return 2;
        }
      }
      else if ( arg == QLatin1String( "--dxf-scale-denom" ) )
      {
        bool ok;
        QString scale( args[++i] );
        dxfScale = scale.toDouble( &ok );
        if ( !ok )
        {
          std::cerr << "invalid dxf scale " << scale.toStdString() << std::endl;
          return 2;
        }
      }
      else if ( arg == QLatin1String( "--dxf-encoding" ) )
      {
        dxfEncoding = args[++i];
      }
      else if ( arg == QLatin1String( "--dxf-preset" ) )
      {
        dxfPreset = args[++i];
      }
      else if ( arg == QLatin1String( "--" ) )
      {
        for ( i++; i < args.size(); ++i )
          sFileList.append( QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ) );
      }
      else
      {
        sFileList.append( QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ) );
      }
    }
  }

  /////////////////////////////////////////////////////////////////////
  // If no --project was specified, parse the args to look for a     //
  // .qgs file and set myProjectFileName to it. This allows loading  //
  // of a project file by clicking on it in various desktop managers //
  // where an appropriate mime-type has been set up.                 //
  /////////////////////////////////////////////////////////////////////
  if ( sProjectFileName.isEmpty() )
  {
    // check for a .qgs
    for ( int i = 0; i < args.size(); i++ )
    {
      QString arg = QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() );
      if ( arg.endsWith( QLatin1String( ".qgs" ), Qt::CaseInsensitive ) )
      {
        sProjectFileName = arg;
        break;
      }
    }
  }


  /////////////////////////////////////////////////////////////////////
  // Now we have the handlers for the different behaviors...
  ////////////////////////////////////////////////////////////////////

  /////////////////////////////////////////////////////////////////////
  // Initialize the application and the translation stuff
  /////////////////////////////////////////////////////////////////////

#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) && !defined(ANDROID)
  bool myUseGuiFlag = nullptr != getenv( "DISPLAY" );
#else
  bool myUseGuiFlag = true;
#endif
  if ( !myUseGuiFlag )
  {
    std::cerr << QObject::tr(
                "QGIS starting in non-interactive mode not supported.\n"
                "You are seeing this message most likely because you "
                "have no DISPLAY environment variable set.\n"
              ).toUtf8().constData();
    exit( 1 ); //exit for now until a version of qgis is capabable of running non interactive
  }

  // GUI customization is enabled according to settings (loaded when instance is created)
  // we force disabled here if --nocustomization argument is used
  if ( !myCustomization )
  {
    QgsCustomization::instance()->setEnabled( false );
  }

  QCoreApplication::setOrganizationName( QgsApplication::QGIS_ORGANIZATION_NAME );
  QCoreApplication::setOrganizationDomain( QgsApplication::QGIS_ORGANIZATION_DOMAIN );
  QCoreApplication::setApplicationName( QgsApplication::QGIS_APPLICATION_NAME );
  QCoreApplication::setAttribute( Qt::AA_DontShowIconsInMenus, false );

  QgsSettings settings;
  if ( configLocalStorageLocation.isEmpty() )
  {
    if ( getenv( "QGIS_CUSTOM_CONFIG_PATH" ) )
    {
      configLocalStorageLocation = getenv( "QGIS_CUSTOM_CONFIG_PATH" );
    }
    else if ( settings.contains( QStringLiteral( "profilesPath" ), QgsSettings::Core ) )
    {
      configLocalStorageLocation = settings.value( QStringLiteral( "profilesPath" ), "", QgsSettings::Core ).toString();
      QgsDebugMsg( QString( "Loading profiles path from global config at %1" ).arg( configLocalStorageLocation ) );
    }

    // If it is still empty at this point we get it from the standard location.
    if ( configLocalStorageLocation.isEmpty() )
    {
      configLocalStorageLocation = QStandardPaths::standardLocations( QStandardPaths::AppDataLocation ).value( 0 );
    }
  }

  QString rootProfileFolder = QgsUserProfileManager::resolveProfilesFolder( configLocalStorageLocation );
  QgsUserProfileManager manager( rootProfileFolder );
  QgsUserProfile *profile = manager.getProfile( profileName, true );
  QString profileFolder = profile->folder();
  profileName = profile->name();
  delete profile;

  QgsDebugMsg( "User profile details:" );
  QgsDebugMsg( QString( "\t - %1" ).arg( profileName ) );
  QgsDebugMsg( QString( "\t - %1" ).arg( profileFolder ) );
  QgsDebugMsg( QString( "\t - %1" ).arg( rootProfileFolder ) );

  QgsApplication myApp( argc, argv, myUseGuiFlag, profileFolder );

  // SetUp the QgsSettings Global Settings:
  // - use the path specified with --globalsettingsfile path,
  // - use the environment if not found
  // - use a default location as a fallback
  if ( globalsettingsfile.isEmpty() )
  {
    globalsettingsfile = getenv( "QGIS_GLOBAL_SETTINGS_FILE" );
  }
  if ( globalsettingsfile.isEmpty() )
  {
    QString default_globalsettingsfile = QgsApplication::pkgDataPath() + "/qgis_global_settings.ini";
    if ( QFile::exists( default_globalsettingsfile ) )
    {
      globalsettingsfile = default_globalsettingsfile;
    }
  }
  if ( !globalsettingsfile.isEmpty() )
  {
    if ( ! QgsSettings::setGlobalSettingsPath( globalsettingsfile ) )
    {
      QgsMessageLog::logMessage( QStringLiteral( "Invalid globalsettingsfile path: %1" ).arg( globalsettingsfile ), QStringLiteral( "QGIS" ) );
    }
    else
    {
      QgsMessageLog::logMessage( QStringLiteral( "Successfully loaded globalsettingsfile path: %1" ).arg( globalsettingsfile ), QStringLiteral( "QGIS" ) );
    }
  }

  // Settings migration is only supported on the default profile for now.
  if ( profileName == "default" )
  {
    std::unique_ptr< QgsVersionMigration > migration( QgsVersionMigration::canMigrate( 20000, Qgis::QGIS_VERSION_INT ) );
    if ( migration && ( mySettingsMigrationForce || migration->requiresMigration() ) )
    {
      QgsDebugMsg( "RUNNING MIGRATION" );
      migration->runMigration();
    }
  }

  // Redefine QgsApplication::libraryPaths as necessary.
  // IMPORTANT: Do *after* QgsApplication myApp(...), but *before* Qt uses any plugins,
  //            e.g. loading splash screen, setting window icon, etc.
  //            Always honor QT_PLUGIN_PATH env var or qt.conf, which will
  //            be part of libraryPaths just after QgsApplication creation.
#ifdef Q_OS_WIN
  // For non static builds on win (static builds are not supported)
  // we need to be sure we can find the qt image plugins.
  QCoreApplication::addLibraryPath( QApplication::applicationDirPath()
                                    + QDir::separator() + "qtplugins" );
#endif
#ifdef Q_OS_MAC
  // Resulting libraryPaths has critical QGIS plugin paths first, then any Qt plugin paths, then
  // any dev-defined paths (in app's qt.conf) and/or user-defined paths (QT_PLUGIN_PATH env var).
  //
  // NOTE: Minimizes, though does not fully protect against, crashes due to dev/user-defined libs
  //       built against a different Qt/QGIS, while still allowing custom C++ plugins to load.
  QStringList libPaths( QCoreApplication::libraryPaths() );

  QgsDebugMsgLevel( QStringLiteral( "Initial macOS QCoreApplication::libraryPaths: %1" )
                    .arg( libPaths.join( " " ) ), 4 );

  // Strip all critical paths that should always be prepended
  if ( libPaths.removeAll( QDir::cleanPath( QgsApplication::pluginPath() ) ) )
  {
    QgsDebugMsgLevel( QStringLiteral( "QgsApplication::pluginPath removed from initial libraryPaths" ), 4 );
  }
  if ( libPaths.removeAll( QCoreApplication::applicationDirPath() ) )
  {
    QgsDebugMsgLevel( QStringLiteral( "QCoreApplication::applicationDirPath removed from initial libraryPaths" ), 4 );
  }
  // Prepend path, so a standard Qt bundle directory is parsed
  QgsDebugMsgLevel( QStringLiteral( "Prepending QCoreApplication::applicationDirPath to libraryPaths" ), 4 );
  libPaths.prepend( QCoreApplication::applicationDirPath() );

  // Check if we are running in a 'release' app bundle, i.e. contains copied-in
  // standard Qt-specific plugin subdirectories (ones never created by QGIS, e.g. 'sqldrivers' is).
  // Note: bundleclicked(...) is inadequate to determine which *type* of bundle was opened, e.g. release or build dir.
  // An app bundled with QGIS_MACAPP_BUNDLE > 0 is considered a release bundle.
  QString  relLibPath( QDir::cleanPath( QCoreApplication::applicationDirPath().append( "/../PlugIns" ) ) );
  // Note: relLibPath becomes the defacto QT_PLUGINS_DIR of a release app bundle
  if ( QFile::exists( relLibPath + QStringLiteral( "/imageformats" ) )
       && QFile::exists( relLibPath + QStringLiteral( "/codecs" ) ) )
  {
    // We are in a release app bundle.
    // Strip QT_PLUGINS_DIR because it will crash a launched release app bundle, since
    // the appropriate Qt frameworks and plugins have been copied into the bundle.
    if ( libPaths.removeAll( QT_PLUGINS_DIR ) )
    {
      QgsDebugMsgLevel( QStringLiteral( "QT_PLUGINS_DIR removed from initial libraryPaths" ), 4 );
    }
    // Prepend the Plugins path, so copied-in Qt plugin bundle directories are parsed.
    QgsDebugMsgLevel( QStringLiteral( "Prepending <bundle>/Plugins to libraryPaths" ), 4 );
    libPaths.prepend( relLibPath );

    // TODO: see if this or another method can be used to avoid QCA's install prefix plugins
    //       from being parsed and loaded (causes multi-Qt-loaded errors when bundled Qt should
    //       be the only one loaded). QCA core (> v2.1.3) needs an update first.
    //setenv( "QCA_PLUGIN_PATH", relLibPath.toUtf8().constData(), 1 );
  }
  else
  {
    // We are either running from build dir bundle, or launching Mach-O binary directly.
    // Add system Qt plugins, since they are not bundled, and not always referenced by default.
    // An app bundled with QGIS_MACAPP_BUNDLE = 0 will still have Plugins/qgis in it.
    // Note: Don't always prepend.
    //       User may have already defined it in QT_PLUGIN_PATH in a specific order.
    if ( !libPaths.contains( QT_PLUGINS_DIR ) )
    {
      QgsDebugMsgLevel( QStringLiteral( "Prepending QT_PLUGINS_DIR to libraryPaths" ), 4 );
      libPaths.prepend( QT_PLUGINS_DIR );
    }
  }

  QgsDebugMsgLevel( QStringLiteral( "Prepending QgsApplication::pluginPath to libraryPaths" ), 4 );
  libPaths.prepend( QDir::cleanPath( QgsApplication::pluginPath() ) );

  // Redefine library search paths.
  QCoreApplication::setLibraryPaths( libPaths );

  QgsDebugMsgLevel( QStringLiteral( "Rewritten macOS QCoreApplication::libraryPaths: %1" )
                    .arg( QCoreApplication::libraryPaths().join( " " ) ), 4 );
#endif

#ifdef Q_OS_MAC
  // Set hidpi icons; use SVG icons, as PNGs will be relatively too small
  QCoreApplication::setAttribute( Qt::AA_UseHighDpiPixmaps );

  // Set 1024x1024 icon for dock, app switcher, etc., rendering
  myApp.setWindowIcon( QIcon( QgsApplication::iconsPath() + QStringLiteral( "qgis-icon-macos.png" ) ) );
#else
  myApp.setWindowIcon( QIcon( QgsApplication::appIconPath() ) );
#endif

  // TODO: use QgsSettings
  QSettings *customizationsettings = nullptr;

  // Using the customizationfile option always overrides the option and config path options.
  if ( !customizationfile.isEmpty() )
  {
    customizationsettings = new QSettings( customizationfile, QSettings::IniFormat );
    QgsCustomization::instance()->setEnabled( true );
  }
  else
  {
    customizationsettings = new QSettings( QStringLiteral( "QGIS" ), QStringLiteral( "QGISCUSTOMIZATION2" ) );
  }

  // Load and set possible default customization, must be done after QgsApplication init and QgsSettings ( QCoreApplication ) init
  QgsCustomization::instance()->setSettings( customizationsettings );
  QgsCustomization::instance()->loadDefault();

#ifdef Q_OS_MACX
  // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH
  // is not already defined, use the GDAL plugins in the application bundle.
  QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) );
  if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) )
  {
    setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 );
  }

  // Point GDAL_DATA at any GDAL share directory embedded in the app bundle
  if ( !getenv( "GDAL_DATA" ) )
  {
    QStringList gdalShares;
    QString appResources( QDir::cleanPath( QgsApplication::pkgDataPath() ) );
    gdalShares << QCoreApplication::applicationDirPath().append( "/share/gdal" )
               << appResources.append( "/share/gdal" )
               << appResources.append( "/gdal" );
    Q_FOREACH ( const QString &gdalShare, gdalShares )
    {
      if ( QFile::exists( gdalShare ) )
      {
        setenv( "GDAL_DATA", gdalShare.toUtf8().constData(), 1 );
        break;
      }
    }
  }
Example #5
0
int
main(int argc, char **argv)
{
    struct cmd_syndesc *ts;
    int err = 0;
    struct cmdline_rock arock;

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a
     * crash (i.e. core is generated) we can include the user's data section
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGABRT, &nsa, NULL);
    sigaction(SIGSEGV, &nsa, NULL);
#endif

    /* Initialize directory paths */
    if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
#ifdef AFS_NT40_ENV
	ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
#endif
	fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
		argv[0]);
	exit(2);
    }
#ifdef AFS_NT40_ENV
    /* Default to binary mode for fopen() */
    _set_fmode(_O_BINARY);

    main_thread = pthread_self();
    if (spawnDatap && spawnDataLen) {
	/* This is a child per partition salvager. Don't setup log or
	 * try to lock the salvager lock.
	 */
	if (nt_SetupPartitionSalvage(spawnDatap, spawnDataLen) < 0)
	    exit(3);
    } else {
#endif

#ifndef AFS_NT40_ENV
	if (geteuid() != 0) {
	    printf("Salvager must be run as root.\n");
	    fflush(stdout);
	    Exit(0);
	}
#endif

	/* bad for normal help flag processing, but can do nada */

#ifdef AFS_NT40_ENV
    }
#endif

    arock.argc = argc;
    arock.argv = argv;

    ts = cmd_CreateSyntax("initcmd", handleit, &arock, "initialize the program");
    cmd_AddParm(ts, "-partition", CMD_SINGLE, CMD_OPTIONAL,
		"Name of partition to salvage");
    cmd_AddParm(ts, "-volumeid", CMD_SINGLE, CMD_OPTIONAL,
		"Volume Id to salvage");
    cmd_AddParm(ts, "-debug", CMD_FLAG, CMD_OPTIONAL,
		"Run in Debugging mode");
    cmd_AddParm(ts, "-nowrite", CMD_FLAG, CMD_OPTIONAL,
		"Run readonly/test mode");
    cmd_AddParm(ts, "-inodes", CMD_FLAG, CMD_OPTIONAL,
		"Just list affected afs inodes - debugging flag");
    cmd_AddParm(ts, "-oktozap", CMD_FLAG, CMD_OPTIONAL,
		"Give permission to destroy bogus inodes/volumes - debugging flag");
    cmd_AddParm(ts, "-rootinodes", CMD_FLAG, CMD_OPTIONAL,
		"Show inodes owned by root - debugging flag");
    cmd_AddParm(ts, "-salvagedirs", CMD_FLAG, CMD_OPTIONAL,
		"Force rebuild/salvage of all directories");
    cmd_AddParm(ts, "-blockreads", CMD_FLAG, CMD_OPTIONAL,
		"Read smaller blocks to handle IO/bad blocks");
    cmd_AddParm(ts, "-parallel", CMD_SINGLE, CMD_OPTIONAL,
		"# of max parallel partition salvaging");
    cmd_AddParm(ts, "-tmpdir", CMD_SINGLE, CMD_OPTIONAL,
		"Name of dir to place tmp files ");
    cmd_AddParm(ts, "-showlog", CMD_FLAG, CMD_OPTIONAL,
		"Show log file upon completion");
    cmd_AddParm(ts, "-orphans", CMD_SINGLE, CMD_OPTIONAL,
		"ignore | remove | attach");

    /* note - syslog isn't avail on NT, but if we make it conditional, have
     * to deal with screwy offsets for cmd params */
    cmd_AddParm(ts, "-syslog", CMD_FLAG, CMD_OPTIONAL,
		"Write salvage log to syslogs");
    cmd_AddParm(ts, "-syslogfacility", CMD_SINGLE, CMD_OPTIONAL,
		"Syslog facility number to use");
    cmd_AddParm(ts, "-datelogs", CMD_FLAG, CMD_OPTIONAL,
		"Include timestamp in logfile filename");

    cmd_AddParm(ts, "-client", CMD_FLAG, CMD_OPTIONAL,
		"Use SALVSYNC to ask salvageserver to salvage a volume");

    err = cmd_Dispatch(argc, argv);
    Exit(err);
    return 0; /* not reached */
}
Example #6
0
int main(int argc, char **argv)
{
	int ds, dms, ret;
	double mb;
	struct timeval t1, t2;
#ifndef C_WINDOWS
	struct timezone tz;
	sigset_t sigset;
#endif
	struct optstruct *opt;
	const char *pt;

#if defined(C_WINDOWS) && defined(CL_THREAD_SAFE)
    if(!pthread_win32_process_attach_np()) {
	mprintf("!Can't start the win32 pthreads layer\n");
	return 72;
    }
#endif

#if !defined(C_WINDOWS) && !defined(C_BEOS)
    sigemptyset(&sigset);
    sigaddset(&sigset, SIGXFSZ);
    sigprocmask(SIG_SETMASK, &sigset, NULL);
#endif

    opt = opt_parse(argc, argv, clamscan_shortopt, clamscan_longopt, NULL, clamscan_deprecated);
    if(!opt) {
	mprintf("!Can't parse the command line\n");
	return 40;
    }

    if(opt_check(opt, "verbose")) {
	mprintf_verbose = 1;
	logg_verbose = 1;
    }

    if(opt_check(opt, "quiet"))
	mprintf_quiet = 1;

    if(opt_check(opt, "stdout"))
	mprintf_stdout = 1;


    if(opt_check(opt, "debug")) {
#if defined(C_LINUX)
	    /* [email protected]: create a dump if needed */
	    struct rlimit rlim;

	rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
	if(setrlimit(RLIMIT_CORE, &rlim) < 0)
	    perror("setrlimit");
#endif
	cl_debug(); /* enable debug messages */
    }

    if(opt_check(opt, "version")) {
	print_version(opt_arg(opt, "database"));
	opt_free(opt);
	return 0;
    }

    if(opt_check(opt, "help")) {
	opt_free(opt);
    	help();
	return 0;
    }

    if(opt_check(opt, "recursive"))
	recursion = 1;

    if(opt_check(opt, "infected"))
	printinfected = 1;

    if(opt_check(opt, "bell"))
	bell = 1;

    if(opt_check(opt, "tempdir"))
	cl_settempdir(opt_arg(opt, "tempdir"), 0);

    if(opt_check(opt, "leave-temps"))
	cl_settempdir(NULL, 1);

    /* initialize logger */
    if(opt_check(opt, "log")) {
	logg_file = opt_arg(opt, "log");
	if(logg("#\n-------------------------------------------------------------------------------\n\n")) {
	    mprintf("!Problem with internal logger.\n");
	    opt_free(opt);
	    return 62;
	}
    } else 
	logg_file = NULL;


    /* validate some numerical options */

    if(opt_check(opt, "max-scansize")) {
	pt = opt_arg(opt, "max-scansize");
	if(!strchr(pt, 'M') && !strchr(pt, 'm')) {
	    if(!cli_isnumber(pt)) {
		logg("!--max-scansize requires a natural number\n");
		opt_free(opt);
		return 40;
	    }
	}
    }

    if(opt_check(opt, "max-filesize")) {
	pt = opt_arg(opt, "max-filesize");
	if(!strchr(pt, 'M') && !strchr(pt, 'm')) {
	    if(!cli_isnumber(pt)) {
		logg("!--max-filesize requires a natural number\n");
		opt_free(opt);
		return 40;
	    }
	}
    }

    if(opt_check(opt, "max-files")) {
	if(!cli_isnumber(opt_arg(opt, "max-files"))) {
	    logg("!--max-files requires a natural number\n");
	    opt_free(opt);
	    return 40;
	}
    }

    if(opt_check(opt, "max-recursion")) {
	if(!cli_isnumber(opt_arg(opt, "max-recursion"))) {
	    logg("!--max-recursion requires a natural number\n");
	    opt_free(opt);
	    return 40;
	}
    }

    if(opt_check(opt, "max-mail-recursion")) {
	if(!cli_isnumber(opt_arg(opt, "max-mail-recursion"))) {
	    logg("!--max-mail-recursion requires a natural number\n");
	    opt_free(opt);
	    return 40;
	}
    }

    if(opt_check(opt, "max-dir-recursion")) {
	if(!cli_isnumber(opt_arg(opt, "max-dir-recursion"))) {
	    logg("!--max-dir-recursion requires a natural number\n");
	    opt_free(opt);
	    return 40;
	}
    }

    if(opt_check(opt, "max-ratio")) {
	if(!cli_isnumber(opt_arg(opt, "max-ratio"))) {
	    logg("!--max-ratio requires a natural number\n");
	    opt_free(opt);
	    return 40;
	}
    }

    memset(&info, 0, sizeof(struct s_info));

#ifdef _WIN32
    SetConsoleCtrlHandler((PHANDLER_ROUTINE) clamscan_ctrl_handler, TRUE);
#endif

#ifdef C_WINDOWS
    _set_fmode(_O_BINARY);
#ifdef CL_DEBUG
    {
	_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
    }
#endif	
    gettimeofday(&t1, NULL);
#else
    gettimeofday(&t1, &tz);
#endif

    ret = scanmanager(opt);

    if(!opt_check(opt, "disable-summary") && !opt_check(opt, "no-summary")) {
#ifdef C_WINDOWS
	gettimeofday(&t2, NULL);
#else
	gettimeofday(&t2, &tz);
#endif
	ds = t2.tv_sec - t1.tv_sec;
	dms = t2.tv_usec - t1.tv_usec;
	ds -= (dms < 0) ? (1):(0);
	dms += (dms < 0) ? (1000000):(0);
	logg("\n----------- SCAN SUMMARY -----------\n");
	logg("Known viruses: %u\n", info.sigs);
	logg("Engine version: %s\n", get_version());
	logg("Scanned directories: %u\n", info.dirs);
	logg("Scanned files: %u\n", info.files);
	logg("Infected files: %u\n", info.ifiles);
	if(info.notremoved) {
	    logg("Not removed: %u\n", info.notremoved);
	}
	if(info.notmoved) {
	    logg("Not %s: %u\n", opt_check(opt, "copy") ? "moved" : "copied", info.notmoved);
	}
	mb = info.blocks * (CL_COUNT_PRECISION / 1024) / 1024.0;
	logg("Data scanned: %2.2lf MB\n", mb);
	logg("Time: %u.%3.3u sec (%u m %u s)\n", ds, dms/1000, ds/60, ds%60);
    }

    opt_free(opt);

#if defined(C_WINDOWS) && defined(CL_THREAD_SAFE)
    if(!pthread_win32_process_detach_np()) {
	logg("!Can't stop the win32 pthreads layer\n");
	return 72;
    }
#endif

    return ret;
}
Example #7
0
int main(int argc, char** argv) {
	CString sConfig;
	CString sDataDir = "";

	seedPRNG();
	// Win32 doesn't support shell escape codes, so we do this.
	CUtils::SetStdoutIsTTY(false);

	CString sConsoleTitle = "ZNC " + CZNC::GetVersion();
	SetConsoleTitle(sConsoleTitle.c_str());

	// register Ctrl handler
	if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleCtrlHandler, TRUE) == NULL)
	{
		CUtils::PrintMessage("Couldn't register console Ctrl handler function!");
	}

	// this prevents open()/read() and friends from stripping \r
	// from files... simply adding _O_BINARY to the modes doesn't seem
	// to be enough for some reason...
	// if we don't do this, Template.cpp will break
	// because it uses string.size() for file pos
	// calculations.
	_set_fmode(_O_BINARY);

#ifdef HAVE_LIBSSL
	CRYPTO_malloc_init();
#endif

	// make sure the stuff in ZNC.dll matches this exe's version... bad crashes otherwise.
	if(CZNC::GetCoreVersion() != MODVERSION)
	{
		CUtils::PrintError("The version number in ZNC.dll doesn't match. Aborting.");
		return 1;
	}

	// process command line arguments

	int iArg, iOptIndex = -1;
	bool bMakeConf = false;
	bool bMakePass = false;
	bool bAllowRoot = false;

#ifdef HAVE_LIBSSL
	bool bMakePem = false;

	while ((iArg = getopt_long(argc, argv, "hvcspd:D", g_LongOpts, &iOptIndex)) != -1) {
#else
	while ((iArg = getopt_long(argc, argv, "hvcsd:D", g_LongOpts, &iOptIndex)) != -1) {
#endif /* HAVE_LIBSSL */
		switch (iArg) {
		case 'h':
			GenerateHelp(argv[0]);
			return 0;
		case 'v':
			cout << CZNC::GetTag() << endl;
			return 0;
		case 'c':
			bMakeConf = true;
			break;
		case 's':
			bMakePass = true;
			break;
#ifdef HAVE_LIBSSL
		case 'p':
			bMakePem = true;
			break;
#endif /* HAVE_LIBSSL */
		case 'd':
			sDataDir = CString(optarg);
			break;
		case 'D':
			CUtils::SetDebug(true);
			break;
		case '?':
		default:
			GenerateHelp(argv[0]);
			return 1;
		}
	}

	if (optind < argc) {
		sConfig = argv[optind];
	}

	if (!InitCsocket()) {
		CUtils::PrintError("Failed to initialize Csocket!");
		exit(-1);
	}

	CZNC* pZNC = &CZNC::Get();
	pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir);

#ifdef HAVE_LIBSSL
	if (bMakePem) {
		pZNC->WritePemFile();

		delete pZNC;
		return 0;
	}
#endif /* HAVE_LIBSSL */

	if (bMakePass) {
		CString sSalt;
		CString sHash = CUtils::GetSaltedHashPass(sSalt);
		CUtils::PrintMessage("Use this in the <User> section of your config:");
		CUtils::PrintMessage("Pass = "******"#" + sHash + "#" + sSalt + "#");

		delete pZNC;
		return 0;
	}

#ifndef RUN_FROM_SOURCE
	if (CFile::Exists(pZNC->GetCurPath() + "/znc-uninstalled.pc")) {
		CUtils::PrintError("It looks like you are running znc without installing it first.");
		CUtils::PrintError("Recompile with --enable-run-from-source if you intend to do that.");
	}
#endif

	if (bMakeConf) {
		if (!pZNC->WriteNewConfig(sConfig)) {
			delete pZNC;
			return 0;
		}
		/* Fall through to normal bootup */
	}

	if (!pZNC->ParseConfig(sConfig)) {
		if(argc < 2)
		{
			CUtils::PrintMessage("\n");
			CUtils::PrintMessage("Press any key to continue...");
			_getch();
		}
		else
		{
			CUtils::PrintError("Unrecoverable config error.");
		}
		delete pZNC;
		return 1;
	}

	if (!pZNC->OnBoot()) {
		CUtils::PrintError("Exiting due to module boot errors.");
		delete pZNC;
		return 1;
	}

	// removed: checks for isRoot, bForeground, forking and signal handlers

	int iRet = 0;

	CUtils::PrintMessage("\n\n***************************************************");
	CUtils::PrintMessage("** ZNC is now running. Do not close this window. **");
	CUtils::PrintMessage("***************************************************\n\n");

	try {
		pZNC->Loop(&g_bMainLoop);
		CUtils::PrintMessage("Terminating ...");	
	} catch (CException e) {
		switch (e.GetType()) {
			case CException::EX_Shutdown:
				iRet = 0;
				CUtils::PrintMessage("************** Shutting down ZNC... **************");
				break;
			case CException::EX_Restart: {
				// strdup() because GCC is stupid
				char *args[] = {
					strdup(argv[0]),
					strdup("--datadir"),
					strdup(pZNC->GetZNCPath().c_str()),
					NULL,
					NULL,
					NULL,
					NULL,
					NULL
				};
				int pos = 3;
				if (CUtils::Debug())
					args[pos++] = strdup("--debug");
#if 0
				else if (bForeground)
					args[pos++] = strdup("--foreground");
				if (!CUtils::StdoutIsTTY())
					args[pos++] = strdup("--no-color");
				if (bAllowRoot)
					args[pos++] = strdup("--allow-root");
#endif
				args[pos++] = strdup(pZNC->GetConfigFile().c_str());
				// The above code adds 4 entries to args tops
				// which means the array should be big enough

				CUtils::PrintMessage("************** Restarting ZNC... **************");
				delete pZNC; /* stuff screws up real bad if we don't close all sockets etc. */
				pZNC = NULL;

				execvp(args[0], args);
				CUtils::PrintError("Unable to restart znc [" + CString(strerror(errno)) + "]");
			} /* Fall through */
			default:
				iRet = 1;
		}
	}

	delete pZNC;

#ifdef _DEBUG
	::_getch();
#endif

	return iRet;
}
Example #8
0
int main( int argc, char *argv[] )
{
#ifdef WIN32  // Windows
#ifdef _MSC_VER
  _set_fmode( _O_BINARY );
#else //MinGW
  _fmode = _O_BINARY;
#endif  // _MSC_VER
#endif  // WIN32

  /////////////////////////////////////////////////////////////////
  // Command line options 'behaviour' flag setup
  ////////////////////////////////////////////////////////////////

  //
  // Parse the command line arguments, looking to see if the user has asked for any
  // special behaviours. Any remaining non command arguments will be kept aside to
  // be passed as a list of layers and / or a project that should be loaded.
  //

  int myIterations = 1;
  QString mySnapshotFileName = "";
  QString myLogFileName = "";
  QString myPrefixPath = "";
  int mySnapshotWidth = 800;
  int mySnapshotHeight = 600;
  QString myQuality = "";

  // This behaviour will set initial extent of map canvas, but only if
  // there are no command line arguments. This gives a usable map
  // extent when qgis starts with no layers loaded. When layers are
  // loaded, we let the layers define the initial extent.
  QString myInitialExtent = "";
  if ( argc == 1 )
    myInitialExtent = "-1,-1,1,1";

  // The user can specify a path which will override the default path of custom
  // user settings (~/.qgis) and it will be used for QSettings INI file
  QString configpath;

#ifndef WIN32
  ////////////////////////////////////////////////////////////////
  // USe the GNU Getopts utility to parse cli arguments
  // Invokes ctor `GetOpt (int argc, char **argv,  char *optstring);'
  ///////////////////////////////////////////////////////////////
  int optionChar;
  while ( 1 )
  {
    static struct option long_options[] =
    {
      /* These options set a flag. */
      {"help", no_argument, 0, '?'},
      /* These options don't set a flag.
       *  We distinguish them by their indices. */
      {"iterations",    required_argument, 0, 'i'},
      {"snapshot", required_argument, 0, 's'},
      {"log", required_argument, 0, 'l'},
      {"width",    required_argument, 0, 'w'},
      {"height",   required_argument, 0, 'h'},
      {"project",  required_argument, 0, 'p'},
      {"extent",   required_argument, 0, 'e'},
      {"optionspath", required_argument, 0, 'o'},
      {"configpath", required_argument, 0, 'c'},
      {"prefix", required_argument, 0, 'r'},
      {"quality", required_argument, 0, 'q'},
      {0, 0, 0, 0}
    };

    /* getopt_long stores the option index here. */
    int option_index = 0;

    optionChar = getopt_long( argc, argv, "islwhpeocrq",
                              long_options, &option_index );

    /* Detect the end of the options. */
    if ( optionChar == -1 )
      break;

    switch ( optionChar )
    {
      case 0:
        /* If this option set a flag, do nothing else now. */
        if ( long_options[option_index].flag != 0 )
          break;
        printf( "option %s", long_options[option_index].name );
        if ( optarg )
          printf( " with arg %s", optarg );
        printf( "\n" );
        break;

      case 'i':
        myIterations = QString( optarg ).toInt();
        break;

      case 's':
        mySnapshotFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() );
        break;

      case 'l':
        myLogFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() );
        break;

      case 'w':
        mySnapshotWidth = QString( optarg ).toInt();
        break;

      case 'h':
        mySnapshotHeight = QString( optarg ).toInt();
        break;

      case 'p':
        myProjectFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() );
        break;

      case 'e':
        myInitialExtent = optarg;
        break;

      case 'o':
        QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optarg );
        break;

      case 'c':
        configpath = optarg;
        break;

      case 'r':
        myPrefixPath = optarg;
        break;

      case 'q':
        myQuality = optarg;
        break;

      case '?':
        usage( argv[0] );
        return 2;   // XXX need standard exit codes
        break;

      default:
        QgsDebugMsg( QString( "%1: getopt returned character code %2" ).arg( argv[0] ).arg( optionChar ) );
        return 1;   // XXX need standard exit codes
    }
  }

  // Add any remaining args to the file list - we will attempt to load them
  // as layers in the map view further down....
  QgsDebugMsg( QString( "Files specified on command line: %1" ).arg( optind ) );
  if ( optind < argc )
  {
    while ( optind < argc )
    {
#ifdef QGISDEBUG
      int idx = optind;
      QgsDebugMsg( QString( "%1: %2" ).arg( idx ).arg( argv[idx] ) );
#endif
      myFileList.append( QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[optind++] ) ).absoluteFilePath() ) );
    }
  }
#else
  for ( int i = 1; i < argc; i++ )
  {
    QString arg = argv[i];

    if ( arg == "--help" || arg == "-?" )
    {
      usage( argv[0] );
      return 2;
    }
    else if ( i + 1 < argc && ( arg == "--iterations" || arg == "-i" ) )
    {
      myIterations = QString( argv[++i] ).toInt();
    }
    else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) )
    {
      mySnapshotFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() );
    }
    else if ( i + 1 < argc && ( arg == "--log" || arg == "-l" ) )
    {
      myLogFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() );
    }
    else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) )
    {
      mySnapshotWidth = QString( argv[++i] ).toInt();
    }
    else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) )
    {
      mySnapshotHeight = QString( argv[++i] ).toInt();
    }
    else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) )
    {
      myProjectFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() );
    }
    else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) )
    {
      myInitialExtent = argv[++i];
    }
    else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) )
    {
      QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, argv[++i] );
    }
    else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) )
    {
      configpath = argv[++i];
      QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, configpath );
    }
    else if ( i + 1 < argc && ( arg == "--prefix" ) )
    {
      myPrefixPath = argv[++i];
    }
    else if ( i + 1 < argc && ( arg == "--quality" || arg == "-q" ) )
    {
      myQuality = argv[++i];
    }
    else
    {
      myFileList.append( QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[i] ) ).absoluteFilePath() ) );
    }
  }
#endif //WIN32

  /////////////////////////////////////////////////////////////////////
  // Now we have the handlers for the different behaviours...
  ////////////////////////////////////////////////////////////////////

  /////////////////////////////////////////////////////////////////////
  // Initialise the application and the translation stuff
  /////////////////////////////////////////////////////////////////////

  if ( !configpath.isEmpty() )
  {
    // tell QSettings to use INI format and save the file in custom config path
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, configpath );
  }

  // TODO: Qt: there should be exactly one QCoreApplication object for console app.
  // but QgsApplication inherits from QApplication (GUI)
  // it is working, but maybe we should make QgsCoreApplication, which
  // could also be used by mapserver
  // Note (mkuhn,20.4.2013): Labeling does not work with QCoreApplication, because
  // fontconfig needs some X11 dependencies which are initialized in QApplication (GUI)
  // using it with QCoreApplication only crashes at the moment.
  // Only use QgsApplication( int, char **, bool GUIenabled, QString) for newer versions
  // so that this program may be run with old libraries
  //QgsApplication myApp( argc, argv, false, configpath );

  QCoreApplication *myApp;

#if VERSION_INT >= 10900
  myApp = new QgsApplication( argc, argv, false );
#else
  myApp = new QCoreApplication( argc, argv );
#endif

  if ( myPrefixPath.isEmpty() )
  {
    QDir dir( QCoreApplication::applicationDirPath() );
    dir.cdUp();
    myPrefixPath = dir.absolutePath();
  }
  QgsApplication::setPrefixPath( myPrefixPath, true );

  // Set up the QSettings environment must be done after qapp is created
  QgsApplication::setOrganizationName( "QuantumGIS" );
  QgsApplication::setOrganizationDomain( "qgis.org" );
  QgsApplication::setApplicationName( "QGIS2" );

  QgsProviderRegistry::instance( QgsApplication::pluginPath() );

#ifdef Q_OS_MACX
  // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH
  // is not already defined, use the GDAL plugins in the application bundle.
  QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) );
  if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) )
  {
    setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 );
  }
#endif

  QSettings mySettings;

  // For non static builds on mac and win (static builds are not supported)
  // we need to be sure we can find the qt image
  // plugins. In mac be sure to look in the
  // application bundle...
#ifdef Q_WS_WIN
  QCoreApplication::addLibraryPath( QApplication::applicationDirPath()
                                    + QDir::separator() + "qtplugins" );
#endif
#ifdef Q_OS_MACX
  //qDebug("Adding qt image plugins to plugin search path...");
  CFURLRef myBundleRef = CFBundleCopyBundleURL( CFBundleGetMainBundle() );
  CFStringRef myMacPath = CFURLCopyFileSystemPath( myBundleRef, kCFURLPOSIXPathStyle );
  const char *mypPathPtr = CFStringGetCStringPtr( myMacPath, CFStringGetSystemEncoding() );
  CFRelease( myBundleRef );
  CFRelease( myMacPath );
  QString myPath( mypPathPtr );
  // if we are not in a bundle assume that the app is built
  // as a non bundle app and that image plugins will be
  // in system Qt frameworks. If the app is a bundle
  // lets try to set the qt plugin search path...
  QFileInfo myInfo( myPath );
  if ( myInfo.isBundle() )
  {
    // First clear the plugin search paths so we can be sure
    // only plugins from the bundle are being used
    QStringList myPathList;
    QCoreApplication::setLibraryPaths( myPathList );
    // Now set the paths inside the bundle
    myPath += "/Contents/plugins";
    QCoreApplication::addLibraryPath( myPath );
  }
#endif

  QgsBench *qbench = new QgsBench( mySnapshotWidth, mySnapshotHeight, myIterations );

  /////////////////////////////////////////////////////////////////////
  // If no --project was specified, parse the args to look for a     //
  // .qgs file and set myProjectFileName to it. This allows loading  //
  // of a project file by clicking on it in various desktop managers //
  // where an appropriate mime-type has been set up.                 //
  /////////////////////////////////////////////////////////////////////
  if ( myProjectFileName.isEmpty() )
  {
    // check for a .qgs
    for ( int i = 0; i < argc; i++ )
    {
      QString arg = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[i] ) ).absoluteFilePath() );
      if ( arg.contains( ".qgs" ) )
      {
        myProjectFileName = arg;
        break;
      }
    }
  }

  /////////////////////////////////////////////////////////////////////
  // Load a project file if one was specified
  /////////////////////////////////////////////////////////////////////
  if ( ! myProjectFileName.isEmpty() )
  {
    if ( ! qbench->openProject( myProjectFileName ) )
    {
      fprintf( stderr, "Cannot load project\n" );
      return 1;
    }
  }

  if ( ! myQuality.isEmpty() )
  {
    QPainter::RenderHints hints;
    QStringList list = myQuality.split( ',' );
    foreach ( QString q, list )
    {
      if ( q == "Antialiasing" ) hints |= QPainter::Antialiasing;
      else if ( q == "TextAntialiasing" ) hints |= QPainter::TextAntialiasing;
      else if ( q == "SmoothPixmapTransform" ) hints |= QPainter::SmoothPixmapTransform;
      else if ( q == "NonCosmeticDefaultPen" ) hints |= QPainter::NonCosmeticDefaultPen;
      else
      {
        fprintf( stderr, "Unknown quality option\n" );
        return 1;
      }
    }
    QgsDebugMsg( QString( "hints: %1" ).arg( hints ) );
    qbench->setRenderHints( hints );
  }
Example #9
0
int
main(int argc, char **argv)
{
	struct bsdtar		*bsdtar;
	int			 opt;
	char			 possible_help_request;
	char			 buff[16];
	char			 cachedir[PATH_MAX + 1];
	struct passwd		*pws;
	char			*conffile;
	const char		*missingkey;
	time_t			 now;
	size_t 			 i;

	WARNP_INIT;

	/* Use a pointer for consistency. */
	bsdtar = bsdtar_init();

#if defined(_WIN32) && !defined(__CYGWIN__)
	/* Make sure open() function will be used with a binary mode. */
	/* on cygwin, we need something similar, but instead link against */
	/* a special startup object, binmode.o */
	_set_fmode(_O_BINARY);
#endif

	/* Need bsdtar->progname before calling bsdtar_warnc. */
	if (*argv == NULL)
		bsdtar->progname = "tarsnap";
	else {
#if defined(_WIN32) && !defined(__CYGWIN__)
		bsdtar->progname = strrchr(*argv, '\\');
#else
		bsdtar->progname = strrchr(*argv, '/');
#endif
		if (bsdtar->progname != NULL)
			bsdtar->progname++;
		else
			bsdtar->progname = *argv;
	}

	/* We don't have a machine # yet. */
	bsdtar->machinenum = (uint64_t)(-1);

	/* Allocate space for archive names; at most argc of them. */
	if ((bsdtar->tapenames = malloc(argc * sizeof(const char *))) == NULL)
		bsdtar_errc(bsdtar, 1, ENOMEM, "Cannot allocate memory");
	bsdtar->ntapes = 0;

	/* Allocate space for config file names; at most argc of them. */
	if ((bsdtar->configfiles = malloc(argc * sizeof(const char *))) == NULL)
		bsdtar_errc(bsdtar, 1, ENOMEM, "Cannot allocate memory");
	bsdtar->nconfigfiles = 0;

	time(&now);
	bsdtar->creationtime = now;

	if (setlocale(LC_ALL, "") == NULL)
		bsdtar_warnc(bsdtar, 0, "Failed to set default locale");
#if defined(HAVE_NL_LANGINFO) && defined(HAVE_D_MD_ORDER)
	bsdtar->day_first = (*nl_langinfo(D_MD_ORDER) == 'd');
#endif
	possible_help_request = 0;

	/* Initialize key cache.  We don't have any keys yet. */
	if (crypto_keys_init())
		exit(1);

	/*
	 * Make stdout line-buffered (if possible) so that operations such as
	 * "tarsnap --list-archives | more" will run more smoothly.  The only
	 * downside to this is a slight performance cost; but we don't write
	 * enough data to stdout for that to matter.
	 */
	setvbuf(stdout, NULL, _IONBF, 0);

	/*
	 * Unless specified otherwise, we consider ourselves to be
	 * constructing a snapshot of the disk as it is right now.
	 */
	/*
	 * POSIX doesn't provide any mechanism for distinguishing between
	 * an error and the time (time_t)(-1).  Since we only use this to
	 * avoid race conditions in the chunkification cache (i.e., so
	 * that we can determine if a file has been modified since it was
	 * last backed up), and hopefully nobody will have any files with
	 * negative last-modified dates, an error return of (-1) can be
	 * handled the same was as a legitimate return of (-1): Nothing
	 * gets cached.
	 */
	bsdtar->snaptime = time(NULL);

	/* Store original argument vector. */
	bsdtar->argc_orig = argc;
	bsdtar->argv_orig = argv;

	/* Look up the current user and his home directory. */
	if ((pws = getpwuid(geteuid())) != NULL)
		if ((bsdtar->homedir = strdup(pws->pw_dir)) == NULL)
			bsdtar_errc(bsdtar, 1, ENOMEM, "Cannot allocate memory");

	/* Look up uid of current user for future reference */
	bsdtar->user_uid = geteuid();

	/* Default: preserve mod time on extract */
	bsdtar->extract_flags = ARCHIVE_EXTRACT_TIME;

	/* Default: Perform basic security checks. */
	bsdtar->extract_flags |= SECURITY;

	/* Defaults for root user: */
	if (bsdtar_is_privileged(bsdtar)) {
		/* --same-owner */
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
		/* -p */
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
		bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
	}

	bsdtar->argv = argv;
	bsdtar->argc = argc;

	/* We gather some options in a 'delayed options queue'. */
	bsdtar->delopt = NULL;
	bsdtar->delopt_tail = &bsdtar->delopt;

	/*
	 * Comments following each option indicate where that option
	 * originated:  SUSv2, POSIX, GNU tar, star, etc.  If there's
	 * no such comment, then I don't know of anyone else who
	 * implements that option.
	 */
	while ((opt = bsdtar_getopt(bsdtar)) != -1) {
		switch (opt) {
		case OPTION_AGGRESSIVE_NETWORKING: /* tarsnap */
			optq_push(bsdtar, "aggressive-networking", NULL);
			break;
		case 'B': /* GNU tar */
			/* libarchive doesn't need this; just ignore it. */
			break;
		case 'C': /* GNU tar */
			if (strlen(bsdtar->optarg) == 0)
				bsdtar_errc(bsdtar, 1, 0,
				    "Meaningless option: -C ''");

			set_chdir(bsdtar, bsdtar->optarg);
			break;
		case 'c': /* SUSv2 */
			set_mode(bsdtar, opt, "-c");
			break;
		case OPTION_CACHEDIR: /* multitar */
			optq_push(bsdtar, "cachedir", bsdtar->optarg);
			break;
		case OPTION_CHECK_LINKS: /* GNU tar */
			bsdtar->option_warn_links = 1;
			break;
		case OPTION_CHECKPOINT_BYTES: /* tarsnap */
			optq_push(bsdtar, "checkpoint-bytes", bsdtar->optarg);
			break;
		case OPTION_CHROOT: /* NetBSD */
			bsdtar->option_chroot = 1;
			break;
		case OPTION_CONFIGFILE:
			bsdtar->configfiles[bsdtar->nconfigfiles++] =
			    bsdtar->optarg;
			break;
		case OPTION_CREATIONTIME: /* tarsnap */
			errno = 0;
			bsdtar->creationtime = strtol(bsdtar->optarg,
			    NULL, 0);
			if ((errno) || (bsdtar->creationtime == 0))
				bsdtar_errc(bsdtar, 1, 0,
				    "Invalid --creationtime argument: %s",
				    bsdtar->optarg);
			break;
		case OPTION_CSV_FILE: /* tarsnap */
			if (bsdtar->option_csv_filename != NULL)
				bsdtar_errc(bsdtar, 1, errno,
				    "Two --csv-file options given.\n");
			if ((bsdtar->option_csv_filename = strdup(
			    bsdtar->optarg)) == NULL)
				bsdtar_errc(bsdtar, 1, errno, "Out of memory");
			break;
		case 'd': /* multitar */
			set_mode(bsdtar, opt, "-d");
			break;
		case OPTION_DISK_PAUSE: /* tarsnap */
			optq_push(bsdtar, "disk-pause", bsdtar->optarg);
			break;
		case OPTION_DRYRUN: /* tarsnap */
			bsdtar->option_dryrun = 1;
			break;
		case OPTION_EXCLUDE: /* GNU tar */
			optq_push(bsdtar, "exclude", bsdtar->optarg);
			break;
		case 'f': /* multitar */
			bsdtar->tapenames[bsdtar->ntapes++] = bsdtar->optarg;
			break;
		case OPTION_FSCK: /* multitar */
			set_mode(bsdtar, opt, "--fsck");
			break;
		case OPTION_FSCK_PRUNE: /* multitar */
			set_mode(bsdtar, opt, "--fsck-prune");
			break;
		case 'H': /* BSD convention */
			bsdtar->symlink_mode = 'H';
			break;
		case 'h': /* Linux Standards Base, gtar; synonym for -L */
			bsdtar->symlink_mode = 'L';
			/* Hack: -h by itself is the "help" command. */
			possible_help_request = 1;
			break;
		case OPTION_HELP: /* GNU tar, others */
			long_help(bsdtar);
			exit(0);
			break;
		case OPTION_HUMANIZE_NUMBERS: /* tarsnap */
			optq_push(bsdtar, "humanize-numbers", NULL);
			break;
		case 'I': /* GNU tar */
			/*
			 * TODO: Allow 'names' to come from an archive,
			 * not just a text file.  Design a good UI for
			 * allowing names and mode/owner to be read
			 * from an archive, with contents coming from
			 * disk.  This can be used to "refresh" an
			 * archive or to design archives with special
			 * permissions without having to create those
			 * permissions on disk.
			 */
			bsdtar->names_from_file = bsdtar->optarg;
			break;
		case OPTION_INCLUDE:
			optq_push(bsdtar, "include", bsdtar->optarg);
			break;
		case OPTION_INSANE_FILESYSTEMS:
			optq_push(bsdtar, "insane-filesystems", NULL);
			break;
		case 'k': /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE;
			break;
		case OPTION_KEEP_GOING: /* tarsnap */
			bsdtar->option_keep_going = 1;
			break;
		case OPTION_KEEP_NEWER_FILES: /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
			break;
		case OPTION_KEYFILE: /* tarsnap */
			optq_push(bsdtar, "keyfile", bsdtar->optarg);
			break;
		case 'L': /* BSD convention */
			bsdtar->symlink_mode = 'L';
			break;
	        case 'l': /* SUSv2 and GNU tar beginning with 1.16 */
			/* GNU tar 1.13  used -l for --one-file-system */
			bsdtar->option_warn_links = 1;
			break;
		case OPTION_LIST_ARCHIVES: /* multitar */
			set_mode(bsdtar, opt, "--list-archives");
			break;
		case OPTION_LOWMEM: /* tarsnap */
			optq_push(bsdtar, "lowmem", NULL);
			break;
		case 'm': /* SUSv2 */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_TIME;
			break;
		case OPTION_MAXBW: /* tarsnap */
			optq_push(bsdtar, "maxbw", bsdtar->optarg);
			break;
		case OPTION_MAXBW_RATE: /* tarsnap */
			optq_push(bsdtar, "maxbw-rate", bsdtar->optarg);
			break;
		case OPTION_MAXBW_RATE_DOWN: /* tarsnap */
			optq_push(bsdtar, "maxbw-rate-down", bsdtar->optarg);
			break;
		case OPTION_MAXBW_RATE_UP: /* tarsnap */
			optq_push(bsdtar, "maxbw-rate-up", bsdtar->optarg);
			break;
		case 'n': /* GNU tar */
			bsdtar->option_no_subdirs = 1;
			break;
	        /*
		 * Selecting files by time:
		 *    --newer-?time='date' Only files newer than 'date'
		 *    --newer-?time-than='file' Only files newer than time
		 *         on specified file (useful for incremental backups)
		 * TODO: Add corresponding "older" options to reverse these.
		 */
		case OPTION_NEWER_CTIME: /* GNU tar */
			bsdtar->newer_ctime_sec = get_date(now, bsdtar->optarg);
			break;
		case OPTION_NEWER_CTIME_THAN:
			{
				struct stat st;
				if (stat(bsdtar->optarg, &st) != 0)
					bsdtar_errc(bsdtar, 1, 0,
					    "Can't open file %s", bsdtar->optarg);
				bsdtar->newer_ctime_sec = st.st_ctime;
				bsdtar->newer_ctime_nsec =
				    ARCHIVE_STAT_CTIME_NANOS(&st);
			}
			break;
		case OPTION_NEWER_MTIME: /* GNU tar */
			bsdtar->newer_mtime_sec = get_date(now, bsdtar->optarg);
			break;
		case OPTION_NEWER_MTIME_THAN:
			{
				struct stat st;
				if (stat(bsdtar->optarg, &st) != 0)
					bsdtar_errc(bsdtar, 1, 0,
					    "Can't open file %s", bsdtar->optarg);
				bsdtar->newer_mtime_sec = st.st_mtime;
				bsdtar->newer_mtime_nsec =
				    ARCHIVE_STAT_MTIME_NANOS(&st);
			}
			break;
		case OPTION_NODUMP: /* star */
			optq_push(bsdtar, "nodump", NULL);
			break;
		case OPTION_NOISY_WARNINGS: /* tarsnap */
			tarsnap_opt_noisy_warnings = 1;
			break;
		case OPTION_NORMALMEM:
			optq_push(bsdtar, "normalmem", NULL);
			break;
		case OPTION_NO_AGGRESSIVE_NETWORKING:
			optq_push(bsdtar, "no-aggressive-networking", NULL);
			break;
		case OPTION_NO_CONFIG_EXCLUDE:
			optq_push(bsdtar, "no-config-exclude", NULL);
			break;
		case OPTION_NO_CONFIG_INCLUDE:
			optq_push(bsdtar, "no-config-include", NULL);
			break;
		case OPTION_NO_DEFAULT_CONFIG:
			bsdtar->option_no_default_config = 1;
			break;
		case OPTION_NO_DISK_PAUSE:
			optq_push(bsdtar, "no-disk-pause", NULL);
			break;
		case OPTION_NO_HUMANIZE_NUMBERS:
			optq_push(bsdtar, "no-humanize-numbers", NULL);
			break;
		case OPTION_NO_INSANE_FILESYSTEMS:
			optq_push(bsdtar, "no-insane-filesystems", NULL);
			break;
		case OPTION_NO_MAXBW:
			optq_push(bsdtar, "no-maxbw", NULL);
			break;
		case OPTION_NO_MAXBW_RATE_DOWN:
			optq_push(bsdtar, "no-maxbw-rate-down", NULL);
			break;
		case OPTION_NO_MAXBW_RATE_UP:
			optq_push(bsdtar, "no-maxbw-rate-up", NULL);
			break;
		case OPTION_NO_NODUMP:
			optq_push(bsdtar, "no-nodump", NULL);
			break;
		case OPTION_NO_PRINT_STATS:
			optq_push(bsdtar, "no-print-stats", NULL);
			break;
		case OPTION_NO_QUIET:
			optq_push(bsdtar, "no-quiet", NULL);
			break;
		case OPTION_NO_RETRY_FOREVER:
			optq_push(bsdtar, "no-retry-forever", NULL);
			break;
		case OPTION_NO_SAME_OWNER: /* GNU tar */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_NO_SAME_PERMISSIONS: /* GNU tar */
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_PERM;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_ACL;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_XATTR;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_FFLAGS;
			break;
		case OPTION_NO_SNAPTIME:
			optq_push(bsdtar, "no-snaptime", NULL);
			break;
		case OPTION_NO_STORE_ATIME:
			optq_push(bsdtar, "no-store-atime", NULL);
			break;
		case OPTION_NO_TOTALS:
			optq_push(bsdtar, "no-totals", NULL);
			break;
		case OPTION_NUKE: /* tarsnap */
			set_mode(bsdtar, opt, "--nuke");
			break;
		case OPTION_NULL: /* GNU tar */
			bsdtar->option_null++;
			break;
		case OPTION_NUMERIC_OWNER: /* GNU tar */
			bsdtar->option_numeric_owner++;
			break;
		case 'O': /* GNU tar */
			bsdtar->option_stdout = 1;
			break;
		case 'o':
			bsdtar->option_no_owner = 1;
			bsdtar->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_ONE_FILE_SYSTEM: /* GNU tar */
			bsdtar->option_dont_traverse_mounts = 1;
			break;
		case 'P': /* GNU tar */
			bsdtar->extract_flags &= ~SECURITY;
			bsdtar->option_absolute_paths = 1;
			break;
		case 'p': /* GNU tar, star */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_PERM;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_ACL;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_XATTR;
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
			break;
		case OPTION_PRINT_STATS: /* multitar */
			bsdtar->option_print_stats = 1;
			break;
		case 'q': /* FreeBSD GNU tar --fast-read, NetBSD -q */
			bsdtar->option_fast_read = 1;
			break;
		case OPTION_QUIET:
			optq_push(bsdtar, "quiet", NULL);
			break;
		case 'r': /* multitar */
			set_mode(bsdtar, opt, "-r");
			break;
		case OPTION_RECOVER:
			set_mode(bsdtar, opt, "--recover");
			break;
		case OPTION_RETRY_FOREVER:
			optq_push(bsdtar, "retry-forever", NULL);
			break;
		case OPTION_SNAPTIME: /* multitar */
			optq_push(bsdtar, "snaptime", bsdtar->optarg);
			break;
		case OPTION_STORE_ATIME: /* multitar */
			optq_push(bsdtar, "store-atime", NULL);
			break;
		case 'S': /* NetBSD pax-as-tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_SPARSE;
			break;
		case 's': /* NetBSD pax-as-tar */
#if HAVE_REGEX_H
			add_substitution(bsdtar, bsdtar->optarg);
#else
			bsdtar_warnc(bsdtar, 0,
			    "-s is not supported by this version of tarsnap");
			usage(bsdtar);
#endif
			break;
		case OPTION_SAME_OWNER: /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_OWNER;
			break;
		case OPTION_STRIP_COMPONENTS: /* GNU tar 1.15 */
			errno = 0;
			bsdtar->strip_components = strtol(bsdtar->optarg,
			    NULL, 0);
			if (errno)
				bsdtar_errc(bsdtar, 1, 0,
				    "Invalid --strip-components argument: %s",
				    bsdtar->optarg);
			break;
		case 'T': /* GNU tar */
			bsdtar->names_from_file = bsdtar->optarg;
			break;
		case 't': /* SUSv2 */
			set_mode(bsdtar, opt, "-t");
			bsdtar->verbose++;
			break;
		case OPTION_TOTALS: /* GNU tar */
			optq_push(bsdtar, "totals", NULL);
			break;
		case 'U': /* GNU tar */
			bsdtar->extract_flags |= ARCHIVE_EXTRACT_UNLINK;
			bsdtar->option_unlink_first = 1;
			break;
		case 'v': /* SUSv2 */
			bsdtar->verbose++;
			break;
		case OPTION_VERSION: /* GNU convention */
			version();
			break;
		case OPTION_VERYLOWMEM: /* tarsnap */
			optq_push(bsdtar, "verylowmem", NULL);
			break;
#if 0
		/*
		 * The -W longopt feature is handled inside of
		 * bsdtar_getopt(), so -W is not available here.
		 */
		case 'W': /* Obscure GNU convention. */
			break;
#endif
		case 'w': /* SUSv2 */
			bsdtar->option_interactive = 1;
			break;
		case 'X': /* GNU tar */
			if (exclude_from_file(bsdtar, bsdtar->optarg))
				bsdtar_errc(bsdtar, 1, 0,
				    "failed to process exclusions from file %s",
				    bsdtar->optarg);
			break;
		case 'x': /* SUSv2 */
			set_mode(bsdtar, opt, "-x");
			break;
		default:
			usage(bsdtar);
		}
	}

	/*
	 * Sanity-check options.
	 */

	/*
	 * If --print-stats was specified but no mode was set, then
	 * --print-stats *is* the mode.
	 */
	if ((bsdtar->mode == '\0') && (bsdtar->option_print_stats == 1))
		set_mode(bsdtar, OPTION_PRINT_STATS, "--print-stats");

	/* If no "real" mode was specified, treat -h as --help. */
	if ((bsdtar->mode == '\0') && possible_help_request) {
		long_help(bsdtar);
		exit(0);
	}

	/*
	 * If we're doing a dry run and the user hasn't specified an archive
	 * name via -f, use a fake name.  This will result in the statistics
	 * printed by --print-stats being a few bytes off, since the archive
	 * name is included in the metadata block... but we're going to be a
	 * few bytes off anyway since the command line, including "--dry-run"
	 * is included in the metadata.
	 */
	if (bsdtar->option_dryrun && (bsdtar->ntapes == 0))
		bsdtar->tapenames[bsdtar->ntapes++] = "(dry-run)";

	/* At this point we must have a mode set. */
	if (bsdtar->mode == '\0')
		bsdtar_errc(bsdtar, 1, 0,
		    "Must specify one of -c, -d, -r, -t, -x,"
		    " --list-archives, --print-stats,"
		    " --fsck, --fsck-prune, or --nuke");

	/* Process "delayed" command-line options which we queued earlier. */
	while (bsdtar->delopt != NULL) {
		dooption(bsdtar, bsdtar->delopt->opt_name,
		    bsdtar->delopt->opt_arg, 0);
		optq_pop(bsdtar);
	}

	/* Process config files passed on the command line. */
	for (i = 0; i < bsdtar->nconfigfiles; i++)
		configfile(bsdtar, bsdtar->configfiles[i]);

	/* If we do not have --no-default-config, process default configs. */
	if (bsdtar->option_no_default_config == 0) {
		/* Process options from ~/.tarsnaprc. */
		if (bsdtar->homedir != NULL) {
			if (asprintf(&conffile, "%s/.tarsnaprc",
			    bsdtar->homedir) == -1)
				bsdtar_errc(bsdtar, 1, errno, "No memory");

			configfile(bsdtar, conffile);

			/* Free string allocated by asprintf. */
			free(conffile);
		}

		/* Process options from system-wide tarsnap.conf. */
		configfile(bsdtar, ETC_TARSNAP_CONF);
	}

	/* Continue with more sanity-checking. */
	if ((bsdtar->ntapes == 0) &&
	    (bsdtar->mode != OPTION_PRINT_STATS &&
	     bsdtar->mode != OPTION_LIST_ARCHIVES &&
	     bsdtar->mode != OPTION_RECOVER &&
	     bsdtar->mode != OPTION_FSCK &&
	     bsdtar->mode != OPTION_FSCK_PRUNE &&
	     bsdtar->mode != OPTION_NUKE))
		bsdtar_errc(bsdtar, 1, 0,
		    "Archive name must be specified");
	if ((bsdtar->ntapes > 1) &&
	    (bsdtar->mode != OPTION_PRINT_STATS &&
	     bsdtar->mode != 'd'))
		bsdtar_errc(bsdtar, 1, 0,
		    "Option -f may only be specified once in mode %s",
		    bsdtar->modestr);
	if ((bsdtar->mode == 'c') &&
	    (strlen(bsdtar->tapenames[0]) > 1023))
		bsdtar_errc(bsdtar, 1, 0,
		    "Cannot create an archive with a name > 1023 characters");
	if ((bsdtar->mode == 'c') &&
	    (strlen(bsdtar->tapenames[0]) == 0))
		bsdtar_errc(bsdtar, 1, 0,
		    "Cannot create an archive with an empty name");
	if ((bsdtar->cachedir == NULL) &&
	    (((bsdtar->mode == 'c') && (!bsdtar->option_dryrun)) ||
	     bsdtar->mode == 'd' ||
	     bsdtar->mode == OPTION_RECOVER ||
	     bsdtar->mode == OPTION_FSCK ||
	     bsdtar->mode == OPTION_FSCK_PRUNE ||
	     bsdtar->mode == OPTION_PRINT_STATS))
		bsdtar_errc(bsdtar, 1, 0,
		    "Cache directory must be specified for %s",
		    bsdtar->modestr);
	if (tarsnap_opt_aggressive_networking != 0) {
		if ((bsdtar->bwlimit_rate_up != 0) ||
		    (bsdtar->bwlimit_rate_down != 0)) {
			bsdtar_warnc(bsdtar, 0,
			    "--aggressive-networking is incompatible with"
			    " --maxbw-rate options;\n"
			    "         disabling --aggressive-networking");
			tarsnap_opt_aggressive_networking = 0;
		}
	}

	/*
	 * The -f option doesn't make sense for --list-archives, --fsck,
	 * --fsck-prune, or --nuke.
	 */
	if ((bsdtar->ntapes > 0) &&
	    (bsdtar->mode != OPTION_PRINT_STATS))
		only_mode(bsdtar, "-f", "cxtdr");

	/*
	 * These options don't make sense for the "delete" and "convert to
	 * tar" modes.
	 */
	if (bsdtar->pending_chdir)
		only_mode(bsdtar, "-C", "cxt");
	if (bsdtar->names_from_file)
		only_mode(bsdtar, "-T", "cxt");
	if (bsdtar->newer_ctime_sec || bsdtar->newer_ctime_nsec)
		only_mode(bsdtar, "--newer", "cxt");
	if (bsdtar->newer_mtime_sec || bsdtar->newer_mtime_nsec)
		only_mode(bsdtar, "--newer-mtime", "cxt");
	if (bsdtar->option_absolute_paths)
		only_mode(bsdtar, "-P", "cxt");
	if (bsdtar->option_null)
		only_mode(bsdtar, "--null", "cxt");

	/* Check options only permitted in certain modes. */
	if (bsdtar->option_dont_traverse_mounts)
		only_mode(bsdtar, "--one-file-system", "c");
	if (bsdtar->option_fast_read)
		only_mode(bsdtar, "--fast-read", "xt");
	if (bsdtar->option_no_subdirs)
		only_mode(bsdtar, "-n", "c");
	if (bsdtar->option_no_owner)
		only_mode(bsdtar, "-o", "x");
	if (bsdtar->option_stdout)
		only_mode(bsdtar, "-O", "xt");
	if (bsdtar->option_unlink_first)
		only_mode(bsdtar, "-U", "x");
	if (bsdtar->option_warn_links)
		only_mode(bsdtar, "--check-links", "c");
	if (bsdtar->option_dryrun)
		only_mode(bsdtar, "--dry-run", "c");

	/* Check other parameters only permitted in certain modes. */
	if (bsdtar->symlink_mode != '\0') {
		strcpy(buff, "-?");
		buff[1] = bsdtar->symlink_mode;
		only_mode(bsdtar, buff, "c");
	}
	if (bsdtar->strip_components != 0)
		only_mode(bsdtar, "--strip-components", "xt");

	/*
	 * If the keyfile in the config file is invalid but we're doing a
	 * dryrun, continue anyway (and don't use a cachedir).
	 */
	if (bsdtar->config_file_keyfile_failed && bsdtar->option_dryrun &&
	    bsdtar->cachedir != NULL) {
		bsdtar_warnc(bsdtar, 0,
		    "Ignoring cachedir due to missing or invalid "
		    "keyfile in config file.");
		free(bsdtar->cachedir);
		bsdtar->cachedir = NULL;
	}

	/*
	 * Canonicalize the path to the cache directories.  This is
	 * necessary since the tar code can change directories.
	 */
	if (bsdtar->cachedir != NULL) {
		build_dir(bsdtar, bsdtar->cachedir, "--cachedir");
		if (realpath(bsdtar->cachedir, cachedir) == NULL)
			bsdtar_errc(bsdtar, 1, errno, "realpath(%s)",
			    bsdtar->cachedir);
		free(bsdtar->cachedir);
		if ((bsdtar->cachedir = strdup(cachedir)) == NULL)
			bsdtar_errc(bsdtar, 1, errno, "Out of memory");
	}

	/* If we're running --fsck, figure out which key to use. */
	if (bsdtar->mode == OPTION_FSCK) {
		if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_PUT) == NULL)
			bsdtar->mode = OPTION_FSCK_WRITE;
		else if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_DELETE) == NULL)
			bsdtar->mode = OPTION_FSCK_DELETE;
		else
			bsdtar_errc(bsdtar, 1, 0,
			    "The write or delete authorization key is"
			    " required for --fsck but is not available");
	}

	/* If we're running --recover, figure out which key to use. */
	if (bsdtar->mode == OPTION_RECOVER) {
		if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_PUT) == NULL)
			bsdtar->mode = OPTION_RECOVER_WRITE;
		else if (crypto_keys_missing(CRYPTO_KEYMASK_AUTH_DELETE) == NULL)
			bsdtar->mode = OPTION_RECOVER_DELETE;
		else
			bsdtar_errc(bsdtar, 1, 0,
			    "The write or delete authorization key is"
			    " required for --recover but is not available");
	}

	/* Make sure we have whatever keys we're going to need. */
	if (bsdtar->have_keys == 0) {
		if (!bsdtar->option_dryrun) {
			bsdtar_errc(bsdtar, 1, 0,
			    "Keys must be provided via --keyfile option");
		} else {
			if (bsdtar->cachedir != NULL) {
				bsdtar_errc(bsdtar, 1, 0,
				    "Option mismatch for --dry-run: cachedir"
				    " specified but no keyfile");
			}
			if (crypto_keys_generate(CRYPTO_KEYMASK_USER))
				bsdtar_errc(bsdtar, 1, 0,
				    "Error generating keys");
			if (bsdtar->option_print_stats)
				bsdtar_warnc(bsdtar, 0,
				    "Performing dry-run archival without keys\n"
				    "         (sizes may be slightly "
				    "inaccurate)");
		}
	}

	missingkey = NULL;
	switch (bsdtar->mode) {
	case 'c':
		if (argv_has_archive_directive(bsdtar))
			missingkey = crypto_keys_missing(CRYPTO_KEYMASK_WRITE | CRYPTO_KEYMASK_READ);
		else
			missingkey = crypto_keys_missing(CRYPTO_KEYMASK_WRITE);
		break;
	case OPTION_RECOVER_WRITE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_WRITE);
		break;
	case 'd':
	case OPTION_FSCK_PRUNE:
	case OPTION_FSCK_DELETE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_READ |
		    CRYPTO_KEYMASK_AUTH_DELETE);
		break;
	case OPTION_FSCK_WRITE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_READ |
		    CRYPTO_KEYMASK_AUTH_PUT);
		break;
	case OPTION_NUKE:
	case OPTION_RECOVER_DELETE:
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_AUTH_DELETE);
		break;
	case OPTION_PRINT_STATS:
		/* We don't need keys for printing global stats. */
		if (bsdtar->ntapes == 0)
			break;

		/* FALLTHROUGH */
	case OPTION_LIST_ARCHIVES:
	case 'r':
	case 't':
	case 'x':
		missingkey = crypto_keys_missing(CRYPTO_KEYMASK_READ);
		break;
	}
	if (missingkey != NULL)
		bsdtar_errc(bsdtar, 1, 0,
		    "The %s key is required for %s but is not available",
		    missingkey, bsdtar->modestr);

	/* Tell the network layer how much bandwidth to use. */
	if (bsdtar->bwlimit_rate_up == 0)
		bsdtar->bwlimit_rate_up = 1000000000.;
	if (bsdtar->bwlimit_rate_down == 0)
		bsdtar->bwlimit_rate_down = 1000000000.;
	network_bwlimit(bsdtar->bwlimit_rate_down, bsdtar->bwlimit_rate_up);

	/* Perform the requested operation. */
	switch(bsdtar->mode) {
	case 'c':
		tarsnap_mode_c(bsdtar);
		break;
	case 'd':
		tarsnap_mode_d(bsdtar);
		break;
	case OPTION_FSCK_DELETE:
		tarsnap_mode_fsck(bsdtar, 0, 1);
		break;
	case OPTION_FSCK_PRUNE:
		tarsnap_mode_fsck(bsdtar, 1, 1);
		break;
	case OPTION_FSCK_WRITE:
		tarsnap_mode_fsck(bsdtar, 0, 0);
		break;
	case OPTION_PRINT_STATS:
		tarsnap_mode_print_stats(bsdtar);
		break;
	case OPTION_RECOVER_DELETE:
		tarsnap_mode_recover(bsdtar, 1);
		break;
	case OPTION_RECOVER_WRITE:
		tarsnap_mode_recover(bsdtar, 0);
		break;
	case OPTION_LIST_ARCHIVES:
		tarsnap_mode_list_archives(bsdtar);
		break;
	case OPTION_NUKE:
		tarsnap_mode_nuke(bsdtar);
		break;
	case 'r':
		tarsnap_mode_r(bsdtar);
		break;
	case 't':
		tarsnap_mode_t(bsdtar);
		break;
	case 'x':
		tarsnap_mode_x(bsdtar);
		break;
	}

#ifdef DEBUG_SELECTSTATS
	double N, mu, va, max;

	network_getselectstats(&N, &mu, &va, &max);
	fprintf(stderr, "Time-between-select-calls statistics:\n");
	fprintf(stderr, "N = %6g   mu = %12g ms  "
	    "va = %12g ms^2  max = %12g ms\n",
	    N, mu * 1000, va * 1000000, max * 1000);
#endif

#ifdef PROFILE
	/*
	 * If we're compiling with profiling turned on, chdir to a directory
	 * into which we're likely to be able to write to before exiting.
	 */
	if (bsdtar->cachedir != NULL)
		chdir(cachedir);
#endif

	if (bsdtar->return_value != 0)
		bsdtar_warnc(bsdtar, 0,
		    "Error exit delayed from previous errors.");
	return (bsdtar->return_value);
}
Example #10
0
/* this is called from main() in s_entry.c */
int sys_main(int argc, char **argv)
{
    int i, noprefs;
    char *prefsfile = "";
    sys_externalschedlib = 0;
    sys_extraflags = 0;
#ifdef PD_DEBUG
    fprintf(stderr, "Pd: COMPILED FOR DEBUGGING\n");
#endif
    /* use Win32 "binary" mode by default since we don't want the
     * translation that Win32 does by default */
#ifdef _WIN32
# ifdef _MSC_VER /* MS Visual Studio */
    _set_fmode( _O_BINARY );
# else  /* MinGW */
    {
        extern int _fmode;
        _fmode = _O_BINARY;
    }
# endif /* _MSC_VER */
#endif  /* _WIN32 */
#ifndef _WIN32
    /* long ago Pd used setuid to promote itself to real-time priority.
    Just in case anyone's installation script still makes it setuid, we
    complain to stderr and lose setuid here. */
    if (getuid() != geteuid())
    {
        fprintf(stderr, "warning: canceling setuid privilege\n");
        setuid(getuid());
    }
#endif  /* _WIN32 */
    pd_init();                                  /* start the message system */
    sys_findprogdir(argv[0]);                   /* set sys_progname, guipath */
    for (i = noprefs = 0; i < argc; i++)    /* prescan for prefs override */
    {
        if (!strcmp(argv[i], "-noprefs"))
            noprefs = 1;
        else if (!strcmp(argv[i], "-prefsfile") && i < argc-1)
            prefsfile = argv[i+1];
    }
    if (!noprefs)       /* load preferences before parsing args to allow ... */
        sys_loadpreferences(prefsfile, 1);  /* args to override prefs */
    if (sys_argparse(argc-1, argv+1))           /* parse cmd line args */
        return (1);
    sys_afterargparse();                    /* post-argparse settings */
    if (sys_verbose || sys_version) fprintf(stderr, "%s compiled %s %s\n",
        pd_version, pd_compiletime, pd_compiledate);
    if (sys_version)    /* if we were just asked our version, exit here. */
        return (0);
    sys_setsignalhandlers();
    if (sys_dontstartgui)
        clock_set((sys_fakefromguiclk =
            clock_new(0, (t_method)sys_fakefromgui)), 0);
    else if (sys_startgui(sys_libdir->s_name)) /* start the gui */
        return (1);
    if (sys_hipriority)
        sys_setrealtime(sys_libdir->s_name); /* set desired process priority */
    if (sys_externalschedlib)
        return (sys_run_scheduler(sys_externalschedlibname,
            sys_extraflagsstring));
    else if (sys_batch)
        return (m_batchmain());
    else
    {
            /* open audio and MIDI */
        sys_reopen_midi();
        if (audio_shouldkeepopen())
            sys_reopen_audio();
            /* run scheduler until it quits */
        return (m_mainloop());
    }
}
Example #11
0
int main( int argc, char *argv[] )
{
  QgsDebugMsg( QString( "Starting qgis main" ) );
#ifdef WIN32  // Windows
#ifdef _MSC_VER
  _set_fmode( _O_BINARY );
#else //MinGW
  _fmode = _O_BINARY;
#endif  // _MSC_VER
#endif  // WIN32

#if defined(linux) && !defined(ANDROID)
  // Set up the custom qWarning/qDebug custom handler
  qInstallMsgHandler( myMessageOutput );

  signal( SIGQUIT, qgisCrash );
  signal( SIGILL, qgisCrash );
  signal( SIGFPE, qgisCrash );
  signal( SIGSEGV, qgisCrash );
  signal( SIGBUS, qgisCrash );
  signal( SIGSYS, qgisCrash );
  signal( SIGTRAP, qgisCrash );
  signal( SIGXCPU, qgisCrash );
  signal( SIGXFSZ, qgisCrash );
#endif

#ifdef Q_OS_WIN
  SetUnhandledExceptionFilter( qgisCrashDump );
#endif

  // initialize random number seed
  srand( time( NULL ) );

  /////////////////////////////////////////////////////////////////
  // Command line options 'behaviour' flag setup
  ////////////////////////////////////////////////////////////////

  //
  // Parse the command line arguments, looking to see if the user has asked for any
  // special behaviours. Any remaining non command arguments will be kept aside to
  // be passed as a list of layers and / or a project that should be loaded.
  //

  // This behaviour is used to load the app, snapshot the map,
  // save the image to disk and then exit
  QString mySnapshotFileName = "";
  int mySnapshotWidth = 800;
  int mySnapshotHeight = 600;

  bool myHideSplash = false;
#if defined(ANDROID)
  QgsDebugMsg( QString( "Android: Splash hidden" ) );
  myHideSplash = true;
#endif

  bool myRestorePlugins = true;
  bool myCustomization = true;

  // This behaviour will set initial extent of map canvas, but only if
  // there are no command line arguments. This gives a usable map
  // extent when qgis starts with no layers loaded. When layers are
  // loaded, we let the layers define the initial extent.
  QString myInitialExtent = "";
  if ( argc == 1 )
    myInitialExtent = "-1,-1,1,1";

  // This behaviour will allow you to force the use of a translation file
  // which is useful for testing
  QString myTranslationCode;

  // The user can specify a path which will override the default path of custom
  // user settings (~/.qgis) and it will be used for QSettings INI file
  QString configpath;
  QString optionpath;

  QString pythonfile;

  QString customizationfile;

#if defined(ANDROID)
  QgsDebugMsg( QString( "Android: All params stripped" ) );// Param %1" ).arg( argv[0] ) );
  //put all QGIS settings in the same place
  configpath = QgsApplication::qgisSettingsPath();
  QgsDebugMsg( QString( "Android: configpath set to %1" ).arg( configpath ) );
#elif defined(Q_WS_WIN)
  for ( int i = 1; i < argc; i++ )
  {
    QString arg = argv[i];

    if ( arg == "--help" || arg == "-?" )
    {
      usage( argv[0] );
      return 2;
    }
    else if ( arg == "-nologo" || arg == "-n" )
    {
      myHideSplash = true;
    }
    else if ( arg == "--noplugins" || arg == "-P" )
    {
      myRestorePlugins = false;
    }
    else if ( arg == "--nocustomization" || arg == "-C" )
    {
      myCustomization = false;
    }
    else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) )
    {
      mySnapshotFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() );
    }
    else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) )
    {
      mySnapshotWidth = QString( argv[++i] ).toInt();
    }
    else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) )
    {
      mySnapshotHeight = QString( argv[++i] ).toInt();
    }
    else if ( i + 1 < argc && ( arg == "--lang" || arg == "-l" ) )
    {
      myTranslationCode = argv[++i];
    }
    else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) )
    {
      myProjectFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() );
    }
    else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) )
    {
      myInitialExtent = argv[++i];
    }
    else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) )
    {
      optionpath = argv[++i];
    }
    else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) )
    {
      configpath = argv[++i];
    }
    else if ( i + 1 < argc && ( arg == "--code" || arg == "-f" ) )
    {
      pythonfile = argv[++i];
    }
    else if ( i + 1 < argc && ( arg == "--customizationfile" || arg == "-z" ) )
    {
      customizationfile = argv[++i];
    }
    else
    {
      myFileList.append( QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[i] ) ).absoluteFilePath() ) );
    }
  }
#else
  if ( !bundleclicked( argc, argv ) )
  {

    ////////////////////////////////////////////////////////////////
    // Use the GNU Getopts utility to parse cli arguments
    // Invokes ctor `GetOpt (int argc, char **argv,  char *optstring);'
    ///////////////////////////////////////////////////////////////
    int optionChar;
    while ( 1 )
    {
      static struct option long_options[] =
      {
        /* These options set a flag. */
        {"help", no_argument, 0, '?'},
        {"nologo", no_argument, 0, 'n'},
        {"noplugins", no_argument, 0, 'P'},
        {"nocustomization", no_argument, 0, 'C'},
        /* These options don't set a flag.
         *  We distinguish them by their indices. */
        {"snapshot", required_argument, 0, 's'},
        {"width",    required_argument, 0, 'w'},
        {"height",   required_argument, 0, 'h'},
        {"lang",     required_argument, 0, 'l'},
        {"project",  required_argument, 0, 'p'},
        {"extent",   required_argument, 0, 'e'},
        {"optionspath", required_argument, 0, 'o'},
        {"configpath", required_argument, 0, 'c'},
        {"customizationfile", required_argument, 0, 'z'},
        {"code", required_argument, 0, 'f'},
        {"android", required_argument, 0, 'a'},
        {0, 0, 0, 0}
      };

      /* getopt_long stores the option index here. */
      int option_index = 0;

      optionChar = getopt_long( argc, argv, "swhlpeoc",
                                long_options, &option_index );
      QgsDebugMsg( QString( "Qgis main Debug" ) + optionChar );
      /* Detect the end of the options. */
      if ( optionChar == -1 )
        break;

      switch ( optionChar )
      {
        case 0:
          /* If this option set a flag, do nothing else now. */
          if ( long_options[option_index].flag != 0 )
            break;
          printf( "option %s", long_options[option_index].name );
          if ( optarg )
            printf( " with arg %s", optarg );
          printf( "\n" );
          break;

        case 's':
          mySnapshotFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() );
          break;

        case 'w':
          mySnapshotWidth = QString( optarg ).toInt();
          break;

        case 'h':
          mySnapshotHeight = QString( optarg ).toInt();
          break;

        case 'n':
          myHideSplash = true;
          break;

        case 'l':
          myTranslationCode = optarg;
          break;

        case 'p':
          myProjectFileName = QDir::convertSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() );
          break;

        case 'P':
          myRestorePlugins = false;
          break;

        case 'C':
          myCustomization = false;
          break;

        case 'e':
          myInitialExtent = optarg;
          break;

        case 'o':
          optionpath = optarg;
          break;

        case 'c':
          configpath = optarg;
          break;

        case 'f':
          pythonfile = optarg;
          break;

        case 'z':
          customizationfile = optarg;
          break;

        case '?':
          usage( argv[0] );
          return 2;   // XXX need standard exit codes
          break;

        default:
          QgsDebugMsg( QString( "%1: getopt returned character code %2" ).arg( argv[0] ).arg( optionChar ) );
          return 1;   // XXX need standard exit codes
      }
    }

    // Add any remaining args to the file list - we will attempt to load them
    // as layers in the map view further down....
    QgsDebugMsg( QString( "Files specified on command line: %1" ).arg( optind ) );
    if ( optind < argc )
    {
      while ( optind < argc )
      {
#ifdef QGISDEBUG
        int idx = optind;
        QgsDebugMsg( QString( "%1: %2" ).arg( idx ).arg( argv[idx] ) );
#endif
        myFileList.append( QDir::convertSeparators( QFileInfo( QFile::decodeName( argv[optind++] ) ).absoluteFilePath() ) );
      }
    }
  }
#endif


  /////////////////////////////////////////////////////////////////////
  // Now we have the handlers for the different behaviours...
  ////////////////////////////////////////////////////////////////////

  /////////////////////////////////////////////////////////////////////
  // Initialise the application and the translation stuff
  /////////////////////////////////////////////////////////////////////

#ifdef Q_WS_X11
  bool myUseGuiFlag = getenv( "DISPLAY" ) != 0;
#else
  bool myUseGuiFlag = true;
#endif
  if ( !myUseGuiFlag )
  {
    std::cerr << QObject::tr(
                "QGIS starting in non-interactive mode not supported.\n"
                "You are seeing this message most likely because you "
                "have no DISPLAY environment variable set.\n"
              ).toUtf8().constData();
    exit( 1 ); //exit for now until a version of qgis is capabable of running non interactive
  }

  if ( !optionpath.isEmpty() || !configpath.isEmpty() )
  {
    // tell QSettings to use INI format and save the file in custom config path
    QSettings::setDefaultFormat( QSettings::IniFormat );
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optionpath.isEmpty() ? configpath : optionpath );
  }

  // GUI customization is enabled according to settings (loaded when instance is created)
  // we force disabled here if --nocustomization argument is used
  if ( !myCustomization )
  {
    QgsCustomization::instance()->setEnabled( false );
  }

  QgsApplication myApp( argc, argv, myUseGuiFlag, configpath );

// (if Windows/Mac, use icon from resource)
#if !defined(Q_WS_WIN) && !defined(Q_WS_MAC)
  myApp.setWindowIcon( QPixmap( qgis_xpm ) );        // Linux
#endif

  //
  // Set up the QSettings environment must be done after qapp is created
  QCoreApplication::setOrganizationName( "QGIS" );
  QCoreApplication::setOrganizationDomain( "qgis.org" );
  QCoreApplication::setApplicationName( "QGIS2" );
  QCoreApplication::setAttribute( Qt::AA_DontShowIconsInMenus, false );

  QSettings* customizationsettings;
  if ( !optionpath.isEmpty() || !configpath.isEmpty() )
  {
    // tell QSettings to use INI format and save the file in custom config path
    QSettings::setDefaultFormat( QSettings::IniFormat );
    QString path = optionpath.isEmpty() ? configpath : optionpath;
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, path );
    customizationsettings = new QSettings( QSettings::IniFormat, QSettings::UserScope, "QGIS", "QGISCUSTOMIZATION2" );
  }
  else
  {
    customizationsettings = new QSettings( "QGIS", "QGISCUSTOMIZATION2" );
  }

  // Using the customizationfile option always overrides the option and config path options.
  if ( !customizationfile.isEmpty() )
  {
    customizationsettings = new QSettings( customizationfile, QSettings::IniFormat );
    QgsCustomization::instance()->setEnabled( true );
  }

  // Load and set possible default customization, must be done afterQgsApplication init and QSettings ( QCoreApplication ) init
  QgsCustomization::instance()->setSettings( customizationsettings );
  QgsCustomization::instance()->loadDefault();

#ifdef Q_OS_MACX
  // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH
  // is not already defined, use the GDAL plugins in the application bundle.
  QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) );
  if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) )
  {
    setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 );
  }
#endif

  QSettings mySettings;

  // update any saved setting for older themes to new default 'gis' theme (2013-04-15)
  if ( mySettings.contains( "/Themes" ) )
  {
    QString theme = mySettings.value( "/Themes", "default" ).toString();
    if ( theme == QString( "gis" )
         || theme == QString( "classic" )
         || theme == QString( "nkids" ) )
    {
      mySettings.setValue( "/Themes", QString( "default" ) );
    }
  }


  // custom environment variables
  QMap<QString, QString> systemEnvVars = QgsApplication::systemEnvVars();
  bool useCustomVars = mySettings.value( "qgis/customEnvVarsUse", QVariant( false ) ).toBool();
  if ( useCustomVars )
  {
    QStringList customVarsList = mySettings.value( "qgis/customEnvVars", "" ).toStringList();
    if ( !customVarsList.isEmpty() )
    {
      foreach ( const QString &varStr, customVarsList )
      {
        int pos = varStr.indexOf( QLatin1Char( '|' ) );
        if ( pos == -1 )
          continue;
        QString envVarApply = varStr.left( pos );
        QString varStrNameValue = varStr.mid( pos + 1 );
        pos = varStrNameValue.indexOf( QLatin1Char( '=' ) );
        if ( pos == -1 )
          continue;
        QString envVarName = varStrNameValue.left( pos );
        QString envVarValue = varStrNameValue.mid( pos + 1 );

        if ( systemEnvVars.contains( envVarName ) )
        {
          if ( envVarApply == "prepend" )
          {
            envVarValue += systemEnvVars.value( envVarName );
          }
          else if ( envVarApply == "append" )
          {
            envVarValue = systemEnvVars.value( envVarName ) + envVarValue;
          }
        }

        if ( systemEnvVars.contains( envVarName ) && envVarApply == "unset" )
        {
#ifdef Q_WS_WIN
          putenv( envVarName.toUtf8().constData() );
#else
          unsetenv( envVarName.toUtf8().constData() );
#endif
        }
        else
        {
#ifdef Q_WS_WIN
          if ( envVarApply != "undefined" || !getenv( envVarName.toUtf8().constData() ) )
            putenv( QString( "%1=%2" ).arg( envVarName ).arg( envVarValue ).toUtf8().constData() );
#else
          setenv( envVarName.toUtf8().constData(), envVarValue.toUtf8().constData(), envVarApply == "undefined" ? 0 : 1 );
#endif
        }
      }
    }
Example #12
0
int CInternet::URLPost(const TCHAR *lpszServer, const char *lpszDest)
{
	int bReturn = 0;
//	HINTERNET  hConnect = NULL, hRequest = NULL;
	
	TCHAR szErrMsg[512];
  	char *lpBufferA=NULL;

	LPTSTR AcceptTypes[10] = {TEXT("*/*"), NULL}; 

    DWORD dwRequestFlag = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;

	if(strstr(lpszServer,"https://")!=NULL) //check if it is a HTTPS server
		dwRequestFlag = INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID | INTERNET_FLAG_IGNORE_CERT_CN_INVALID;

	TCHAR szHeaders[] = _T("Content-Type: application/x-www-form-urlencoded"); //content type for post...
	
	TCHAR *HostName = _tcsdup(uc.lpszHostName);
	HostName[uc.dwHostNameLength] = '\0';
	TCHAR *FileName = _tcsdup(uc.lpszUrlPath);
	FileName[uc.dwUrlPathLength] = '\0';
	HINTERNET hCO = InternetConnect(m_hOpen, HostName, uc.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, INTERNET_FLAG_NO_CACHE_WRITE, 0);
	HINTERNET hIS = HttpOpenRequest(hCO, _T("POST"), FileName, NULL, NULL, (LPCTSTR*)AcceptTypes, dwRequestFlag, 0);

again:
	HINTERNET hOU = InternetOpenUrl (m_hOpen, lpszServer, NULL, 0,dwRequestFlag, 0);
	//DWORD dwLength = GetFileLength(hOU);
	if (!HttpSendRequest(hIS, szHeaders, _tcslen(szHeaders), (TCHAR*)&uc.lpszUrlPath[1], _tcslen(&uc.lpszUrlPath[1])))
	{
		DWORD LastError = GetLastError();
		if(LastError == ERROR_INTERNET_INVALID_CA)
		{
			DWORD dwFlags;
			DWORD dwBuffLen = sizeof(dwFlags);

			InternetQueryOption (hIS, INTERNET_OPTION_SECURITY_FLAGS,
			(LPVOID)&dwFlags, &dwBuffLen);

			dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
			InternetSetOption (hIS, INTERNET_OPTION_SECURITY_FLAGS,
			&dwFlags, sizeof (dwFlags) );
			goto again;

		}
	}
	
	FILE *stream = NULL;
	errno_t err = _set_fmode(_O_BINARY);
	if (err == EINVAL)
	{ 
	  OutputDebugString("Invalid mode.\n");
	  return 5;
	}
	
	DWORD dynamicByte = 32000;
	DWORD downloadBytes = 0;
	DWORD dwSize = 0; 
	DWORD availableSize=0;
	do
	{
		lpBufferA = new CHAR [dynamicByte];
		InternetQueryDataAvailable(hIS,&availableSize,0,0);
		sprintf_s(szErrMsg,sizeof(szErrMsg),"Downloaded %d of %d KBytes\n",downloadBytes/1000,availableSize/1000);
		OutputDebugString(szErrMsg);	
	
		if (!InternetReadFile (hIS, (LPVOID)lpBufferA, dynamicByte, &dwSize))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("InternetReadFile Error"),GetLastError());
			OutputDebugString(szErrMsg);
			delete[] lpBufferA;
			goto exit;
		}

		if (dwSize != 0)    
		{	
			downloadBytes+=dwSize;
			if((stream==NULL) && (bReturn==0))
		   		fopen_s(&stream, lpszDest, "w+" );

			if(stream!=NULL)
				 fwrite( lpBufferA, sizeof( CHAR ), dwSize, stream );		
		}    
		if(lpBufferA)
			delete[] lpBufferA; 
		dynamicByte+=1024;
		if(dynamicByte>128000)
			dynamicByte = 128000;

	} while (dwSize);

	if(stream!=NULL)
		fclose(stream);

  goto exitWithNoErr;
exit:
	bReturn = 1;
exitWithNoErr:
	free(HostName);
	free(FileName);

	if (hIS)
	{
		if (!InternetCloseHandle (hIS))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), GetLastError());
			OutputDebugString(szErrMsg);
		}
	}
	if (hCO)
	{
		if (!InternetCloseHandle (hCO))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("ConnectOpen close Error"), GetLastError());
			OutputDebugString(szErrMsg);
		}
	}
    _stprintf_s(szErrMsg, TEXT("Return %d"), bReturn);
	OutputDebugString(szErrMsg);
	return bReturn;
}
Example #13
0
File: cpio.c Project: marccodes/lfl
int
main(int argc, char *argv[])
{
	static char buff[16384];
	struct cpio _cpio; /* Allocated on stack. */
	struct cpio *cpio;
	int uid, gid;
	int opt;

	cpio = &_cpio;
	memset(cpio, 0, sizeof(*cpio));
	cpio->buff = buff;
	cpio->buff_size = sizeof(buff);
#if defined(_WIN32) && !defined(__CYGWIN__)
	/* Make sure open() function will be used with a binary mode. */
	/* on cygwin, we need something similar, but instead link against */
	/* a special startup object, binmode.o */
	_set_fmode(_O_BINARY);
#endif

	/* Need cpio_progname before calling cpio_warnc. */
	if (*argv == NULL)
		cpio_progname = "bsdcpio";
	else {
#if defined(_WIN32) && !defined(__CYGWIN__)
		cpio_progname = strrchr(*argv, '\\');
#else
		cpio_progname = strrchr(*argv, '/');
#endif
		if (cpio_progname != NULL)
			cpio_progname++;
		else
			cpio_progname = *argv;
	}

	cpio->uid_override = -1;
	cpio->gid_override = -1;
	cpio->argv = argv;
	cpio->argc = argc;
	cpio->line_separator = '\n';
	cpio->mode = '\0';
	cpio->verbose = 0;
	cpio->compress = '\0';
	cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
	cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
	cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
	cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
	cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
#if defined(_WIN32) || defined(__CYGWIN__)
	if (bsdcpio_is_privileged())
#else
	if (geteuid() == 0)
#endif
		cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
	cpio->bytes_per_block = 512;
	cpio->filename = NULL;

	while ((opt = cpio_getopt(cpio)) != -1) {
		switch (opt) {
		case '0': /* GNU convention: --null, -0 */
			cpio->line_separator = '\0';
			break;
		case 'A': /* NetBSD/OpenBSD */
			cpio->option_append = 1;
			break;
		case 'a': /* POSIX 1997 */
			cpio->option_atime_restore = 1;
			break;
		case 'B': /* POSIX 1997 */
			cpio->bytes_per_block = 5120;
			break;
		case 'C': /* NetBSD/OpenBSD */
			cpio->bytes_per_block = atoi(cpio->optarg);
			if (cpio->bytes_per_block <= 0)
				cpio_errc(1, 0, "Invalid blocksize %s", cpio->optarg);
			break;
		case 'c': /* POSIX 1997 */
			cpio->format = "odc";
			break;
		case 'd': /* POSIX 1997 */
			cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
			break;
		case 'E': /* NetBSD/OpenBSD */
			include_from_file(cpio, cpio->optarg);
			break;
		case 'F': /* NetBSD/OpenBSD/GNU cpio */
			cpio->filename = cpio->optarg;
			break;
		case 'f': /* POSIX 1997 */
			exclude(cpio, cpio->optarg);
			break;
		case 'H': /* GNU cpio (also --format) */
			cpio->format = cpio->optarg;
			break;
		case 'h':
			long_help();
			break;
		case 'I': /* NetBSD/OpenBSD */
			cpio->filename = cpio->optarg;
			break;
		case 'i': /* POSIX 1997 */
			if (cpio->mode != '\0')
				cpio_errc(1, 0,
				    "Cannot use both -i and -%c", cpio->mode);
			cpio->mode = opt;
			break;
		case OPTION_INSECURE:
			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
			break;
		case 'L': /* GNU cpio */
			cpio->option_follow_links = 1;
			break;
		case 'l': /* POSIX 1997 */
			cpio->option_link = 1;
			break;
		case 'm': /* POSIX 1997 */
			cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
			break;
		case 'n': /* GNU cpio */
			cpio->option_numeric_uid_gid = 1;
			break;
		case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
			cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
			break;
		case 'O': /* GNU cpio */
			cpio->filename = cpio->optarg;
			break;
		case 'o': /* POSIX 1997 */
			if (cpio->mode != '\0')
				cpio_errc(1, 0,
				    "Cannot use both -o and -%c", cpio->mode);
			cpio->mode = opt;
			break;
		case 'p': /* POSIX 1997 */
			if (cpio->mode != '\0')
				cpio_errc(1, 0,
				    "Cannot use both -p and -%c", cpio->mode);
			cpio->mode = opt;
			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
			break;
		case OPTION_QUIET: /* GNU cpio */
			cpio->quiet = 1;
			break;
		case 'R': /* GNU cpio, also --owner */
			if (owner_parse(cpio->optarg, &uid, &gid))
				usage();
			if (uid != -1)
				cpio->uid_override = uid;
			if (gid != -1)
				cpio->gid_override = gid;
			break;
		case 'r': /* POSIX 1997 */
			cpio->option_rename = 1;
			break;
		case 't': /* POSIX 1997 */
			cpio->option_list = 1;
			break;
		case 'u': /* POSIX 1997 */
			cpio->extract_flags
			    &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
			break;
		case 'v': /* POSIX 1997 */
			cpio->verbose++;
			break;
		case OPTION_VERSION: /* GNU convention */
			version();
			break;
#if 0
	        /*
		 * cpio_getopt() handles -W specially, so it's not
		 * available here.
		 */
		case 'W': /* Obscure, but useful GNU convention. */
			break;
#endif
		case 'y': /* tar convention */
#if HAVE_LIBBZ2
			cpio->compress = opt;
#else
			cpio_warnc(0, "bzip2 compression not supported by "
			    "this version of bsdcpio");
#endif
			break;
		case 'Z': /* tar convention */
			cpio->compress = opt;
			break;
		case 'z': /* tar convention */
#if HAVE_LIBZ
			cpio->compress = opt;
#else
			cpio_warnc(0, "gzip compression not supported by "
			    "this version of bsdcpio");
#endif
			break;
		default:
			usage();
		}
	}

	/*
	 * Sanity-check args, error out on nonsensical combinations.
	 */
	/* -t implies -i if no mode was specified. */
	if (cpio->option_list && cpio->mode == '\0')
		cpio->mode = 'i';
	/* -t requires -i */
	if (cpio->option_list && cpio->mode != 'i')
		cpio_errc(1, 0, "Option -t requires -i", cpio->mode);
	/* -n requires -it */
	if (cpio->option_numeric_uid_gid && !cpio->option_list)
		cpio_errc(1, 0, "Option -n requires -it");
	/* Can only specify format when writing */
	if (cpio->format != NULL && cpio->mode != 'o')
		cpio_errc(1, 0, "Option --format requires -o");
	/* -l requires -p */
	if (cpio->option_link && cpio->mode != 'p')
		cpio_errc(1, 0, "Option -l requires -p");
	/* TODO: Flag other nonsensical combinations. */

	switch (cpio->mode) {
	case 'o':
		/* TODO: Implement old binary format in libarchive,
		   use that here. */
		if (cpio->format == NULL)
			cpio->format = "odc"; /* Default format */

		mode_out(cpio);
		break;
	case 'i':
		while (*cpio->argv != NULL) {
			include(cpio, *cpio->argv);
			--cpio->argc;
			++cpio->argv;
		}
		if (cpio->option_list)
			mode_list(cpio);
		else
			mode_in(cpio);
		break;
	case 'p':
		if (*cpio->argv == NULL || **cpio->argv == '\0')
			cpio_errc(1, 0,
			    "-p mode requires a target directory");
		mode_pass(cpio, *cpio->argv);
		break;
	default:
		cpio_errc(1, 0,
		    "Must specify at least one of -i, -o, or -p");
	}

	free_cache(cpio->gname_cache);
	free_cache(cpio->uname_cache);
	return (0);
}
Example #14
0
void fn00000001400011D4(word64 rbx, word64 r8, word64 r13)
{
	word64 rsp_8;
	word64 rbx_9;
	byte SCZO_10;
	word32 ecx_11;
	word32 eax_12;
	word64 rax_13;
	byte al_14;
	byte SZO_15;
	byte C_16;
	byte Z_17;
	word64 rcx_18;
	word64 r8_19;
	word64 r13_20;
	byte bl_21;
	set_app_type();
	fn0000000140001920();
	_set_fmode(dwLoc2C);
	word64 rax_26 = __p__commode();
	fn0000000140001ABC();
	Mem29[rax_26 + 0x00:word32] = 0x00;
	word32 eax_31 = fn000000014000164C(0x01, r8_19, r13_20, qwLoc2C);
	byte al_33 = (byte) eax_31;
	if (al_33 != 0x00)
	{
		fn0000000140001B5C(qwArg00, qwArg04, qwArg08, qwArg0C);
		fn0000000140001854(eax_31);
		fn0000000140001918();
		word64 rsp_74;
		word64 rbx_75;
		byte SCZO_76;
		word32 ecx_77;
		word32 eax_78;
		word64 rax_79;
		byte al_80;
		byte SZO_81;
		byte C_82;
		byte Z_83;
		word64 rcx_84;
		word64 r8_85;
		word64 r13_86;
		byte bl_87;
		configure_narrow_argv();
		if (false)
		{
			fn0000000140001928();
			word32 eax_92 = fn0000000140001958();
			if (eax_92 != 0x00)
			{
				word64 rsp_147;
				word64 rbx_148;
				byte SCZO_149;
				word32 ecx_150;
				word32 eax_151;
				word64 rax_152;
				byte al_153;
				byte SZO_154;
				byte C_155;
				byte Z_156;
				word64 rcx_157;
				word64 r8_158;
				word64 r13_159;
				byte bl_160;
				_setusermatherr();
			}
			fn0000000140001DD0();
			fn0000000140001DD0();
			fn0000000140001ABC();
			word64 rsp_97;
			word64 rbx_98;
			byte SCZO_99;
			word32 ecx_100;
			word32 eax_101;
			word64 rax_102;
			byte al_103;
			byte SZO_104;
			byte C_105;
			byte Z_106;
			word64 rcx_107;
			word64 r8_108;
			word64 r13_109;
			byte bl_110;
			configthreadlocale();
			fn0000000140001938();
			if (0x01 != 0x00)
			{
				word64 rsp_131;
				word64 rbx_132;
				byte SCZO_133;
				word32 ecx_134;
				word32 eax_135;
				word64 rax_136;
				byte al_137;
				byte SZO_138;
				byte C_139;
				byte Z_140;
				word64 rcx_141;
				word64 r8_142;
				word64 r13_143;
				byte bl_144;
				initialize_narrow_environment();
			}
			fn0000000140001ABC();
			return;
		}
	}
	else
	{
		word64 rcx_164;
		byte bl_165;
		fn0000000140001974(0x07, qwLoc04, qwArg00, qwArg04, qwArg0C, out rcx_164, out bl_165);
		int3();
	}
	word64 rcx_68;
	byte bl_69;
	fn0000000140001974(0x07, qwLoc04, qwArg00, qwArg04, qwArg0C, out rcx_68, out bl_69);
	int3();
	int3();
	fn0000000140001290();
	return;
}
Example #15
0
int main(int argc, char **argv) {
	FILE* file;
	double length = 2; // in seconds
	double fps = 25;
	double sample_rate = 48000;
	char *filename;

	int vframe_cnt;
	int vframe_last;

	int total = 0;
	ltcsnd_sample_t *buf;

	LTCEncoder *encoder;
	SMPTETimecode st;

	/* start encoding at this timecode */
	const char timezone[6] = "+0100";
	strcpy(st.timezone, timezone);
	st.years =  8;
	st.months = 12;
	st.days =   31;

	st.hours = 23;
	st.mins = 59;
	st.secs = 59;
	st.frame = 0;

	/* parse commandline args */
	if (argc > 1) {
		filename = argv[1];
		if (argc > 2) {
			sample_rate = atof(argv[2]);
		}
		if (argc > 3) {
			fps = atof(argv[3]);
		}
		if (argc > 4) {
			length = atof(argv[4]);
		}
	} else {
		printf("ltc-encoder - test/example application to encode LTC to a file\n\n");
		printf("Usage: ltc-encoder <filename> [sample rate [frame rate [duration in s]]]\n\n");
		printf("default-values:\n");
		printf(" sample rate: 48000.0 [SPS], frame rate: 25.0 [fps], duration: 2.0 [sec]\n");
		printf("Report bugs to Robin Gareus <*****@*****.**>\n");
		return 1;
	}

#ifdef _WIN32
	// see https://msdn.microsoft.com/en-us/library/ktss1a9b.aspx and
	// https://github.com/x42/libltc/issues/18
	_set_fmode(_O_BINARY);
#endif

	/* open output file */
	file = fopen(filename, "wb");
	if (!file) {
		fprintf(stderr, "Error: can not open file '%s' for writing.\n", filename);
		return 1;
	}

	/* prepare encoder */
	encoder = ltc_encoder_create(sample_rate, fps,
			fps==25?LTC_TV_625_50:LTC_TV_525_60, LTC_USE_DATE);
	ltc_encoder_set_timecode(encoder, &st);

#ifdef USE_LOCAL_BUFFER
	buf = calloc(ltc_encoder_get_buffersize(encoder), sizeof(ltcsnd_sample_t));
	if (!buf) {
		return -1;
	}
#endif

	/* ready to go, print some info first */

	printf("sample rate: %.2f\n", sample_rate);
	printf("frames/sec: %.2f\n", fps);
	printf("secs to write: %.2f\n", length);
	printf("sample format: 8bit unsigned mono\n");

	vframe_cnt = 0;
	vframe_last = length * fps;

	while (vframe_cnt++ < vframe_last) {
#if 1 /* encode and write each of the 80 LTC frame bits (10 bytes) */
		int byte_cnt;
		for (byte_cnt = 0 ; byte_cnt < 10 ; byte_cnt++) {
			ltc_encoder_encode_byte(encoder, byte_cnt, 1.0);

#ifdef USE_LOCAL_BUFFER
			int len = ltc_encoder_get_buffer(encoder, buf);
#else
			int len;
			buf = ltc_encoder_get_bufptr(encoder, &len, 1);
#endif
			if (len > 0) {
				fwrite(buf, sizeof(ltcsnd_sample_t), len, file);
				total+=len;
			}
		}
#else /* encode a complete LTC frame in one step */
		ltc_encoder_encode_frame(encoder);

#ifdef USE_LOCAL_BUFFER
		int len = ltc_encoder_get_buffer(encoder, buf);
#else
		int len;
		buf = ltc_encoder_get_bufptr(encoder, &len, 1);
#endif

		if (len > 0) {
			fwrite(buf, sizeof(ltcsnd_sample_t), len, file);
			total+=len;
		}
#endif

		ltc_encoder_inc_timecode(encoder);
	}
	fclose(file);
	ltc_encoder_free(encoder);

	printf("Done: wrote %d samples to '%s'\n", total, filename);

#ifdef USE_LOCAL_BUFFER
	free(buf);
#endif

	return 0;
}
Example #16
0
/**
 * The main function.
 * @param argc
 * Number of arguments.
 * @param argv
 * Arguments.
 * @return
 * 0.
 */
int main(int argc, char **argv)
{
#ifdef WIN32
    /* Open all files in binary mode by default. */
    _set_fmode(_O_BINARY);
#endif

    init(argc, argv);
    memset(&marker, 0, sizeof(struct obj));

    if (settings.plugin_unit_tests) {
        LOG(INFO, "Running plugin unit tests...");
        object *activator = player_get_dummy(PLAYER_TESTING_NAME1, NULL);
        object *me = player_get_dummy(PLAYER_TESTING_NAME2, NULL);
        trigger_unit_event(activator, me);

        if (!settings.unit_tests) {
            cleanup();
            exit(0);
        }
    }

    if (settings.unit_tests) {
#ifdef HAVE_CHECK
        LOG(INFO, "Running unit tests...");
        cleanup();
        check_main(argc, argv);
        exit(0);
#else
        LOG(ERROR, "Unit tests have not been compiled, aborting.");
        exit(1);
#endif
    }

    atexit(cleanup);

    if (settings.world_maker) {
#ifdef HAVE_WORLD_MAKER
        LOG(INFO, "Running the world maker...");
        world_maker();
        exit(0);
#else
        LOG(ERROR, "Cannot run world maker; server was not compiled with libgd, exiting...");
        exit(1);
#endif
    }

    if (!settings.no_console) {
        console_start_thread();
    }

    process_delay = 0;

    LOG(INFO, "Server ready. Waiting for connections...");

    for (; ; ) {
        if (unlikely(shutdown_timer_check())) {
            break;
        }

        console_command_handle();
        socket_server_process();

        if (++process_delay >= max_time_multiplier) {
            process_delay = 0;
            main_process();
        }

        socket_server_post_process();

        /* Sleep proper amount of time before next tick */
        sleep_delta();
    }

    server_shutdown();

    return 0;
}
Example #17
0
int main( int argc, char *argv[] )
{
#ifdef Q_OS_MACX
  // Increase file resource limits (i.e., number of allowed open files)
  // (from code provided by Larry Biehl, Purdue University, USA, from 'MultiSpec' project)
  // This is generally 256 for the soft limit on Mac
  // NOTE: setrlimit() must come *before* initialization of stdio strings,
  //       e.g. before any debug messages, or setrlimit() gets ignored
  // see: http://stackoverflow.com/a/17726104/2865523
  struct rlimit rescLimit;
  if ( getrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 )
  {
    rlim_t oldSoft( rescLimit.rlim_cur );
    rlim_t oldHard( rescLimit.rlim_max );
#ifdef OPEN_MAX
    rlim_t newSoft( OPEN_MAX );
    rlim_t newHard( std::min( oldHard, newSoft ) );
#else
    rlim_t newSoft( 4096 );
    rlim_t newHard( std::min(( rlim_t )8192, oldHard ) );
#endif
    if ( rescLimit.rlim_cur < newSoft )
    {
      rescLimit.rlim_cur = newSoft;
      rescLimit.rlim_max = newHard;

      if ( setrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 )
      {
        QgsDebugMsg( QString( "Mac RLIMIT_NOFILE Soft/Hard NEW: %1 / %2" )
                     .arg( rescLimit.rlim_cur ).arg( rescLimit.rlim_max ) );
      }
    }
    Q_UNUSED( oldSoft ); //avoid warnings
    QgsDebugMsg( QString( "Mac RLIMIT_NOFILE Soft/Hard ORIG: %1 / %2" )
                 .arg( oldSoft ).arg( oldHard ) );
  }
#endif

  QgsDebugMsg( QString( "Starting qgis main" ) );
#ifdef WIN32  // Windows
#ifdef _MSC_VER
  _set_fmode( _O_BINARY );
#else //MinGW
  _fmode = _O_BINARY;
#endif  // _MSC_VER
#endif  // WIN32

  // Set up the custom qWarning/qDebug custom handler
#ifndef ANDROID
  qInstallMsgHandler( myMessageOutput );
#endif

#if (defined(linux) && !defined(ANDROID)) || defined(__FreeBSD__)
  signal( SIGQUIT, qgisCrash );
  signal( SIGILL, qgisCrash );
  signal( SIGFPE, qgisCrash );
  signal( SIGSEGV, qgisCrash );
  signal( SIGBUS, qgisCrash );
  signal( SIGSYS, qgisCrash );
  signal( SIGTRAP, qgisCrash );
  signal( SIGXCPU, qgisCrash );
  signal( SIGXFSZ, qgisCrash );
#endif

#ifdef Q_OS_WIN
  SetUnhandledExceptionFilter( QgisApp::qgisCrashDump );
#endif

  // initialize random number seed
  qsrand( time( nullptr ) );

  /////////////////////////////////////////////////////////////////
  // Command line options 'behaviour' flag setup
  ////////////////////////////////////////////////////////////////

  //
  // Parse the command line arguments, looking to see if the user has asked for any
  // special behaviours. Any remaining non command arguments will be kept aside to
  // be passed as a list of layers and / or a project that should be loaded.
  //

  // This behaviour is used to load the app, snapshot the map,
  // save the image to disk and then exit
  QString mySnapshotFileName = "";
  int mySnapshotWidth = 800;
  int mySnapshotHeight = 600;

  bool myHideSplash = false;
#if defined(ANDROID)
  QgsDebugMsg( QString( "Android: Splash hidden" ) );
  myHideSplash = true;
#endif

  bool myRestoreDefaultWindowState = false;
  bool myRestorePlugins = true;
  bool myCustomization = true;

  QString dxfOutputFile;
  QgsDxfExport::SymbologyExport dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology;
  double dxfScaleDenom = 50000.0;
  QString dxfEncoding = "CP1252";
  QString dxfPreset;
  QgsRectangle dxfExtent;

  // This behaviour will set initial extent of map canvas, but only if
  // there are no command line arguments. This gives a usable map
  // extent when qgis starts with no layers loaded. When layers are
  // loaded, we let the layers define the initial extent.
  QString myInitialExtent = "";
  if ( argc == 1 )
    myInitialExtent = "-1,-1,1,1";

  // This behaviour will allow you to force the use of a translation file
  // which is useful for testing
  QString myTranslationCode;

  // The user can specify a path which will override the default path of custom
  // user settings (~/.qgis) and it will be used for QSettings INI file
  QString configpath;
  QString optionpath;
  QString authdbdirectory;

  QString pythonfile;

  QString customizationfile;

#if defined(ANDROID)
  QgsDebugMsg( QString( "Android: All params stripped" ) );// Param %1" ).arg( argv[0] ) );
  //put all QGIS settings in the same place
  configpath = QgsApplication::qgisSettingsDirPath();
  QgsDebugMsg( QString( "Android: configpath set to %1" ).arg( configpath ) );
#endif

  QStringList args;

  if ( !bundleclicked( argc, argv ) )
  {
    // Build a local QCoreApplication from arguments. This way, arguments are correctly parsed from their native locale
    // It will use QString::fromLocal8Bit( argv ) under Unix and GetCommandLine() under Windows.
    QCoreApplication coreApp( argc, argv );
    args = QCoreApplication::arguments();

    for ( int i = 1; i < args.size(); ++i )
    {
      const QString &arg = args[i];

      if ( arg == "--help" || arg == "-?" )
      {
        usage( args[0].toStdString() );
        return 2;
      }
      else if ( arg == "--nologo" || arg == "-n" )
      {
        myHideSplash = true;
      }
      else if ( arg == "--noplugins" || arg == "-P" )
      {
        myRestorePlugins = false;
      }
      else if ( arg == "--nocustomization" || arg == "-C" )
      {
        myCustomization = false;
      }
      else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) )
      {
        mySnapshotFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) )
      {
        mySnapshotWidth = QString( args[++i] ).toInt();
      }
      else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) )
      {
        mySnapshotHeight = QString( args[++i] ).toInt();
      }
      else if ( i + 1 < argc && ( arg == "--lang" || arg == "-l" ) )
      {
        myTranslationCode = args[++i];
      }
      else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) )
      {
        myProjectFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) )
      {
        myInitialExtent = args[++i];
      }
      else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) )
      {
        optionpath = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() );
      }
      else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) )
      {
        configpath = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() );
      }
      else if ( i + 1 < argc && ( arg == "--authdbdirectory" || arg == "-a" ) )
      {
        authdbdirectory = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() );
      }
      else if ( i + 1 < argc && ( arg == "--code" || arg == "-f" ) )
      {
        pythonfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--customizationfile" || arg == "-z" ) )
      {
        customizationfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( arg == "--defaultui" || arg == "-d" )
      {
        myRestoreDefaultWindowState = true;
      }
      else if ( arg == "--dxf-export" )
      {
        dxfOutputFile = args[++i];
      }
      else if ( arg == "--dxf-extent" )
      {
        QgsLocaleNumC l;
        QString ext( args[++i] );
        QStringList coords( ext.split( ',' ) );

        if ( coords.size() != 4 )
        {
          std::cerr << "invalid dxf extent " << ext.toStdString() << std::endl;
          return 2;
        }

        for ( int i = 0; i < 4; i++ )
        {
          bool ok;
          double d;

          d = coords[i].toDouble( &ok );
          if ( !ok )
          {
            std::cerr << "invalid dxf coordinate " << coords[i].toStdString() << " in extent " << ext.toStdString() << std::endl;
            return 2;
          }

          switch ( i )
          {
            case 0:
              dxfExtent.setXMinimum( d );
              break;
            case 1:
              dxfExtent.setYMinimum( d );
              break;
            case 2:
              dxfExtent.setXMaximum( d );
              break;
            case 3:
              dxfExtent.setYMaximum( d );
              break;
          }
        }
      }
      else if ( arg == "--dxf-symbology-mode" )
      {
        QString mode( args[++i] );
        if ( mode == "none" )
        {
          dxfSymbologyMode = QgsDxfExport::NoSymbology;
        }
        else if ( mode == "symbollayer" )
        {
          dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology;
        }
        else if ( mode == "feature" )
        {
          dxfSymbologyMode = QgsDxfExport::FeatureSymbology;
        }
        else
        {
          std::cerr << "invalid dxf symbology mode " << mode.toStdString() << std::endl;
          return 2;
        }
      }
      else if ( arg == "--dxf-scale-denom" )
      {
        bool ok;
        QString scale( args[++i] );
        dxfScaleDenom = scale.toDouble( &ok );
        if ( !ok )
        {
          std::cerr << "invalid dxf scale " << scale.toStdString() << std::endl;
          return 2;
        }
      }
      else if ( arg == "--dxf-encoding" )
      {
        dxfEncoding = args[++i];
      }
      else if ( arg == "--dxf-preset" )
      {
        dxfPreset = args[++i];
      }
      else if ( arg == "--" )
      {
        for ( i++; i < args.size(); ++i )
          myFileList.append( QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ) );
      }
      else
      {
        myFileList.append( QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ) );
      }
    }
  }

  /////////////////////////////////////////////////////////////////////
  // If no --project was specified, parse the args to look for a     //
  // .qgs file and set myProjectFileName to it. This allows loading  //
  // of a project file by clicking on it in various desktop managers //
  // where an appropriate mime-type has been set up.                 //
  /////////////////////////////////////////////////////////////////////
  if ( myProjectFileName.isEmpty() )
  {
    // check for a .qgs
    for ( int i = 0; i < args.size(); i++ )
    {
      QString arg = QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() );
      if ( arg.contains( ".qgs" ) )
      {
        myProjectFileName = arg;
        break;
      }
    }
  }


  /////////////////////////////////////////////////////////////////////
  // Now we have the handlers for the different behaviours...
  ////////////////////////////////////////////////////////////////////

  /////////////////////////////////////////////////////////////////////
  // Initialise the application and the translation stuff
  /////////////////////////////////////////////////////////////////////

#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) && !defined(ANDROID)
  bool myUseGuiFlag = nullptr != getenv( "DISPLAY" );
#else
  bool myUseGuiFlag = true;
#endif
  if ( !myUseGuiFlag )
  {
    std::cerr << QObject::tr(
                "QGIS starting in non-interactive mode not supported.\n"
                "You are seeing this message most likely because you "
                "have no DISPLAY environment variable set.\n"
              ).toUtf8().constData();
    exit( 1 ); //exit for now until a version of qgis is capabable of running non interactive
  }

  if ( !optionpath.isEmpty() || !configpath.isEmpty() )
  {
    // tell QSettings to use INI format and save the file in custom config path
    QSettings::setDefaultFormat( QSettings::IniFormat );
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optionpath.isEmpty() ? configpath : optionpath );
  }

  // GUI customization is enabled according to settings (loaded when instance is created)
  // we force disabled here if --nocustomization argument is used
  if ( !myCustomization )
  {
    QgsCustomization::instance()->setEnabled( false );
  }

  QgsApplication myApp( argc, argv, myUseGuiFlag, configpath );

  myApp.setWindowIcon( QIcon( QgsApplication::appIconPath() ) );

  //
  // Set up the QSettings environment must be done after qapp is created
  QCoreApplication::setOrganizationName( QgsApplication::QGIS_ORGANIZATION_NAME );
  QCoreApplication::setOrganizationDomain( QgsApplication::QGIS_ORGANIZATION_DOMAIN );
  QCoreApplication::setApplicationName( QgsApplication::QGIS_APPLICATION_NAME );
  QCoreApplication::setAttribute( Qt::AA_DontShowIconsInMenus, false );

  QSettings* customizationsettings;
  if ( !optionpath.isEmpty() || !configpath.isEmpty() )
  {
    // tell QSettings to use INI format and save the file in custom config path
    QSettings::setDefaultFormat( QSettings::IniFormat );
    QString path = optionpath.isEmpty() ? configpath : optionpath;
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, path );
    customizationsettings = new QSettings( QSettings::IniFormat, QSettings::UserScope, "QGIS", "QGISCUSTOMIZATION2" );
  }
  else
  {
    customizationsettings = new QSettings( "QGIS", "QGISCUSTOMIZATION2" );
  }

  // Using the customizationfile option always overrides the option and config path options.
  if ( !customizationfile.isEmpty() )
  {
    customizationsettings = new QSettings( customizationfile, QSettings::IniFormat );
    QgsCustomization::instance()->setEnabled( true );
  }

  // Load and set possible default customization, must be done afterQgsApplication init and QSettings ( QCoreApplication ) init
  QgsCustomization::instance()->setSettings( customizationsettings );
  QgsCustomization::instance()->loadDefault();

#ifdef Q_OS_MACX
  // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH
  // is not already defined, use the GDAL plugins in the application bundle.
  QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) );
  if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) )
  {
    setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 );
  }

  // Point GDAL_DATA at any GDAL share directory embedded in the app bundle
  if ( !getenv( "GDAL_DATA" ) )
  {
    QStringList gdalShares;
    QString appResources( QDir::cleanPath( QgsApplication::pkgDataPath() ) );
    gdalShares << QCoreApplication::applicationDirPath().append( "/share/gdal" )
    << appResources.append( "/share/gdal" )
    << appResources.append( "/gdal" );
    Q_FOREACH ( const QString& gdalShare, gdalShares )
    {
      if ( QFile::exists( gdalShare ) )
      {
        setenv( "GDAL_DATA", gdalShare.toUtf8().constData(), 1 );
        break;
      }
    }
  }
Example #18
0
int main( int argc, char *argv[] )
{
#ifdef Q_OS_MACX
  // Increase file resource limits (i.e., number of allowed open files)
  // (from code provided by Larry Biehl, Purdue University, USA, from 'MultiSpec' project)
  // This is generally 256 for the soft limit on Mac
  // NOTE: setrlimit() must come *before* initialization of stdio strings,
  //       e.g. before any debug messages, or setrlimit() gets ignored
  // see: http://stackoverflow.com/a/17726104/2865523
  struct rlimit rescLimit;
  if ( getrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 )
  {
    rlim_t oldSoft( rescLimit.rlim_cur );
    rlim_t oldHard( rescLimit.rlim_max );
#ifdef OPEN_MAX
    rlim_t newSoft( OPEN_MAX );
    rlim_t newHard( std::min( oldHard, newSoft ) );
#else
    rlim_t newSoft( 4096 );
    rlim_t newHard( std::min(( rlim_t )8192, oldHard ) );
#endif
    if ( rescLimit.rlim_cur < newSoft )
    {
      rescLimit.rlim_cur = newSoft;
      rescLimit.rlim_max = newHard;

      if ( setrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 )
      {
        QgsDebugMsg( QString( "Mac RLIMIT_NOFILE Soft/Hard NEW: %1 / %2" )
                     .arg( rescLimit.rlim_cur ).arg( rescLimit.rlim_max ) );
      }
    }
    QgsDebugMsg( QString( "Mac RLIMIT_NOFILE Soft/Hard ORIG: %1 / %2" )
                 .arg( oldSoft ).arg( oldHard ) );
  }
#endif

  QgsDebugMsg( QString( "Starting qgis main" ) );
#ifdef WIN32  // Windows
#ifdef _MSC_VER
  _set_fmode( _O_BINARY );
#else //MinGW
  _fmode = _O_BINARY;
#endif  // _MSC_VER
#endif  // WIN32

  // Set up the custom qWarning/qDebug custom handler
#ifndef ANDROID
  qInstallMsgHandler( myMessageOutput );
#endif

#if (defined(linux) && !defined(ANDROID)) || defined(__FreeBSD__)
  signal( SIGQUIT, qgisCrash );
  signal( SIGILL, qgisCrash );
  signal( SIGFPE, qgisCrash );
  signal( SIGSEGV, qgisCrash );
  signal( SIGBUS, qgisCrash );
  signal( SIGSYS, qgisCrash );
  signal( SIGTRAP, qgisCrash );
  signal( SIGXCPU, qgisCrash );
  signal( SIGXFSZ, qgisCrash );
#endif

#ifdef Q_OS_WIN
  SetUnhandledExceptionFilter( QgisApp::qgisCrashDump );
#endif

  // initialize random number seed
  srand( time( NULL ) );

  /////////////////////////////////////////////////////////////////
  // Command line options 'behaviour' flag setup
  ////////////////////////////////////////////////////////////////

  //
  // Parse the command line arguments, looking to see if the user has asked for any
  // special behaviours. Any remaining non command arguments will be kept aside to
  // be passed as a list of layers and / or a project that should be loaded.
  //

  // This behaviour is used to load the app, snapshot the map,
  // save the image to disk and then exit
  QString mySnapshotFileName = "";
  int mySnapshotWidth = 800;
  int mySnapshotHeight = 600;

  bool myHideSplash = false;
#if defined(ANDROID)
  QgsDebugMsg( QString( "Android: Splash hidden" ) );
  myHideSplash = true;
#endif

  bool myRestorePlugins = true;
  bool myCustomization = true;

  // This behaviour will set initial extent of map canvas, but only if
  // there are no command line arguments. This gives a usable map
  // extent when qgis starts with no layers loaded. When layers are
  // loaded, we let the layers define the initial extent.
  QString myInitialExtent = "";
  if ( argc == 1 )
    myInitialExtent = "-1,-1,1,1";

  // This behaviour will allow you to force the use of a translation file
  // which is useful for testing
  QString myTranslationCode;

  // The user can specify a path which will override the default path of custom
  // user settings (~/.qgis) and it will be used for QSettings INI file
  QString configpath;
  QString optionpath;

  QString pythonfile;

  QString customizationfile;

#if defined(ANDROID)
  QgsDebugMsg( QString( "Android: All params stripped" ) );// Param %1" ).arg( argv[0] ) );
  //put all QGIS settings in the same place
  configpath = QgsApplication::qgisSettingsDirPath();
  QgsDebugMsg( QString( "Android: configpath set to %1" ).arg( configpath ) );
#endif

  QStringList args;

  if ( !bundleclicked( argc, argv ) )
  {
    // Build a local QCoreApplication from arguments. This way, arguments are correctly parsed from their native locale
    // It will use QString::fromLocal8Bit( argv ) under Unix and GetCommandLine() under Windows.
    QCoreApplication coreApp( argc, argv );
    args = QCoreApplication::arguments();

    for ( int i = 1; i < args.size(); ++i )
    {
      QString arg = args[i];

      if ( arg == "--help" || arg == "-?" )
      {
        usage( args[0].toStdString() );
        return 2;
      }
      else if ( arg == "--nologo" || arg == "-n" )
      {
        myHideSplash = true;
      }
      else if ( arg == "--noplugins" || arg == "-P" )
      {
        myRestorePlugins = false;
      }
      else if ( arg == "--nocustomization" || arg == "-C" )
      {
        myCustomization = false;
      }
      else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) )
      {
        mySnapshotFileName = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) )
      {
        mySnapshotWidth = QString( args[++i] ).toInt();
      }
      else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) )
      {
        mySnapshotHeight = QString( args[++i] ).toInt();
      }
      else if ( i + 1 < argc && ( arg == "--lang" || arg == "-l" ) )
      {
        myTranslationCode = args[++i];
      }
      else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) )
      {
        myProjectFileName = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) )
      {
        myInitialExtent = args[++i];
      }
      else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) )
      {
        optionpath = QDir::convertSeparators( QDir( args[++i] ).absolutePath() );
      }
      else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) )
      {
        configpath = QDir::convertSeparators( QDir( args[++i] ).absolutePath() );
      }
      else if ( i + 1 < argc && ( arg == "--code" || arg == "-f" ) )
      {
        pythonfile = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else if ( i + 1 < argc && ( arg == "--customizationfile" || arg == "-z" ) )
      {
        customizationfile = QDir::convertSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
      }
      else
      {
        myFileList.append( QDir::convertSeparators( QFileInfo( args[i] ).absoluteFilePath() ) );
      }
    }
  }

  /////////////////////////////////////////////////////////////////////
  // If no --project was specified, parse the args to look for a     //
  // .qgs file and set myProjectFileName to it. This allows loading  //
  // of a project file by clicking on it in various desktop managers //
  // where an appropriate mime-type has been set up.                 //
  /////////////////////////////////////////////////////////////////////
  if ( myProjectFileName.isEmpty() )
  {
    // check for a .qgs
    for ( int i = 0; i < args.size(); i++ )
    {
      QString arg = QDir::convertSeparators( QFileInfo( args[i] ).absoluteFilePath() );
      if ( arg.contains( ".qgs" ) )
      {
        myProjectFileName = arg;
        break;
      }
    }
  }


  /////////////////////////////////////////////////////////////////////
  // Now we have the handlers for the different behaviours...
  ////////////////////////////////////////////////////////////////////

  /////////////////////////////////////////////////////////////////////
  // Initialise the application and the translation stuff
  /////////////////////////////////////////////////////////////////////

#ifdef Q_WS_X11
  bool myUseGuiFlag = getenv( "DISPLAY" ) != 0;
#else
  bool myUseGuiFlag = true;
#endif
  if ( !myUseGuiFlag )
  {
    std::cerr << QObject::tr(
                "QGIS starting in non-interactive mode not supported.\n"
                "You are seeing this message most likely because you "
                "have no DISPLAY environment variable set.\n"
              ).toUtf8().constData();
    exit( 1 ); //exit for now until a version of qgis is capabable of running non interactive
  }

  if ( !optionpath.isEmpty() || !configpath.isEmpty() )
  {
    // tell QSettings to use INI format and save the file in custom config path
    QSettings::setDefaultFormat( QSettings::IniFormat );
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optionpath.isEmpty() ? configpath : optionpath );
  }

  // GUI customization is enabled according to settings (loaded when instance is created)
  // we force disabled here if --nocustomization argument is used
  if ( !myCustomization )
  {
    QgsCustomization::instance()->setEnabled( false );
  }

  QgsApplication myApp( argc, argv, myUseGuiFlag, configpath );

// (if Windows/Mac, use icon from resource)
#if !defined(Q_WS_WIN) && !defined(Q_WS_MAC)
  myApp.setWindowIcon( QIcon( QgsApplication::iconsPath() + "qgis-icon-60x60.png" ) );
#endif

  //
  // Set up the QSettings environment must be done after qapp is created
  QCoreApplication::setOrganizationName( "QGIS" );
  QCoreApplication::setOrganizationDomain( "qgis.org" );
  QCoreApplication::setApplicationName( "QGIS2" );
  QCoreApplication::setAttribute( Qt::AA_DontShowIconsInMenus, false );

  QSettings* customizationsettings;
  if ( !optionpath.isEmpty() || !configpath.isEmpty() )
  {
    // tell QSettings to use INI format and save the file in custom config path
    QSettings::setDefaultFormat( QSettings::IniFormat );
    QString path = optionpath.isEmpty() ? configpath : optionpath;
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, path );
    customizationsettings = new QSettings( QSettings::IniFormat, QSettings::UserScope, "QGIS", "QGISCUSTOMIZATION2" );
  }
  else
  {
    customizationsettings = new QSettings( "QGIS", "QGISCUSTOMIZATION2" );
  }

  // Using the customizationfile option always overrides the option and config path options.
  if ( !customizationfile.isEmpty() )
  {
    customizationsettings = new QSettings( customizationfile, QSettings::IniFormat );
    QgsCustomization::instance()->setEnabled( true );
  }

  // Load and set possible default customization, must be done afterQgsApplication init and QSettings ( QCoreApplication ) init
  QgsCustomization::instance()->setSettings( customizationsettings );
  QgsCustomization::instance()->loadDefault();

#ifdef Q_OS_MACX
  // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH
  // is not already defined, use the GDAL plugins in the application bundle.
  QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) );
  if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) )
  {
    setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 );
  }
#endif

  QSettings mySettings;

  // update any saved setting for older themes to new default 'gis' theme (2013-04-15)
  if ( mySettings.contains( "/Themes" ) )
  {
    QString theme = mySettings.value( "/Themes", "default" ).toString();
    if ( theme == QString( "gis" )
         || theme == QString( "classic" )
         || theme == QString( "nkids" ) )
    {
      mySettings.setValue( "/Themes", QString( "default" ) );
    }
  }


  // custom environment variables
  QMap<QString, QString> systemEnvVars = QgsApplication::systemEnvVars();
  bool useCustomVars = mySettings.value( "qgis/customEnvVarsUse", QVariant( false ) ).toBool();
  if ( useCustomVars )
  {
    QStringList customVarsList = mySettings.value( "qgis/customEnvVars", "" ).toStringList();
    if ( !customVarsList.isEmpty() )
    {
      foreach ( const QString &varStr, customVarsList )
      {
        int pos = varStr.indexOf( QLatin1Char( '|' ) );
        if ( pos == -1 )
          continue;
        QString envVarApply = varStr.left( pos );
        QString varStrNameValue = varStr.mid( pos + 1 );
        pos = varStrNameValue.indexOf( QLatin1Char( '=' ) );
        if ( pos == -1 )
          continue;
        QString envVarName = varStrNameValue.left( pos );
        QString envVarValue = varStrNameValue.mid( pos + 1 );

        if ( systemEnvVars.contains( envVarName ) )
        {
          if ( envVarApply == "prepend" )
          {
            envVarValue += systemEnvVars.value( envVarName );
          }
          else if ( envVarApply == "append" )
          {
            envVarValue = systemEnvVars.value( envVarName ) + envVarValue;
          }
        }

        if ( systemEnvVars.contains( envVarName ) && envVarApply == "unset" )
        {
#ifdef Q_WS_WIN
          putenv( envVarName.toUtf8().constData() );
#else
          unsetenv( envVarName.toUtf8().constData() );
#endif
        }
        else
        {
#ifdef Q_WS_WIN
          if ( envVarApply != "undefined" || !getenv( envVarName.toUtf8().constData() ) )
            putenv( QString( "%1=%2" ).arg( envVarName ).arg( envVarValue ).toUtf8().constData() );
#else
          setenv( envVarName.toUtf8().constData(), envVarValue.toUtf8().constData(), envVarApply == "undefined" ? 0 : 1 );
#endif
        }
      }
    }
Example #19
0
int main(int argc, char **argv)
{
	int ds, dms, ret;
	double mb, rmb;
	struct timeval t1, t2;
#ifndef C_WINDOWS
	struct timezone tz;
	sigset_t sigset;
#endif
	struct optstruct *opts;
	const struct optstruct *opt;

#if defined(C_WINDOWS) && defined(CL_THREAD_SAFE)
    if(!pthread_win32_process_attach_np()) {
	mprintf("!Can't start the win32 pthreads layer\n");
	return 72;
    }
#endif

#if !defined(C_WINDOWS) && !defined(C_BEOS)
    sigemptyset(&sigset);
    sigaddset(&sigset, SIGXFSZ);
    sigprocmask(SIG_SETMASK, &sigset, NULL);
#endif


    if((opts = optparse(NULL, argc, argv, 1, OPT_CLAMSCAN, 0, NULL)) == NULL) {
	mprintf("!Can't parse command line options\n");
	return 40;
    }

    if(optget(opts, "verbose")->enabled) {
	mprintf_verbose = 1;
	logg_verbose = 1;
    }

    if(optget(opts, "quiet")->enabled)
	mprintf_quiet = 1;

    if(optget(opts, "stdout")->enabled)
	mprintf_stdout = 1;


    if(optget(opts, "debug")->enabled) {
#if defined(C_LINUX)
	    /* [email protected]: create a dump if needed */
	    struct rlimit rlim;

	rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
	if(setrlimit(RLIMIT_CORE, &rlim) < 0)
	    perror("setrlimit");
#endif
	cl_debug(); /* enable debug messages */
    }

    if(optget(opts, "version")->enabled) {
	print_version(optget(opts, "database")->strarg);
	optfree(opts);
	return 0;
    }

    if(optget(opts, "help")->enabled) {
	optfree(opts);
    	help();
	return 0;
    }

    if(optget(opts, "recursive")->enabled)
	recursion = 1;

    if(optget(opts, "infected")->enabled)
	printinfected = 1;

    if(optget(opts, "bell")->enabled)
	bell = 1;

    /* initialize logger */
    if((opt = optget(opts, "log"))->enabled) {
	logg_file = opt->strarg;
	if(logg("#\n-------------------------------------------------------------------------------\n\n")) {
	    mprintf("!Problem with internal logger.\n");
	    optfree(opts);
	    return 62;
	}
    } else 
	logg_file = NULL;

    if(actsetup(opts)) {
	optfree(opts);
	logg_close();
	exit(2);
    }

    memset(&info, 0, sizeof(struct s_info));

#ifdef C_WINDOWS
    _set_fmode(_O_BINARY);
#ifdef CL_DEBUG
    {
	_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
    }
#endif	
    gettimeofday(&t1, NULL);
#else
    gettimeofday(&t1, &tz);
#endif

    ret = scanmanager(opts);

    if(!optget(opts, "no-summary")->enabled) {
#ifdef C_WINDOWS
	gettimeofday(&t2, NULL);
#else
	gettimeofday(&t2, &tz);
#endif
	ds = t2.tv_sec - t1.tv_sec;
	dms = t2.tv_usec - t1.tv_usec;
	ds -= (dms < 0) ? (1):(0);
	dms += (dms < 0) ? (1000000):(0);
	logg("\n----------- SCAN SUMMARY -----------\n");
	logg("Known viruses: %u\n", info.sigs);
	logg("Engine version: %s\n", get_version());
	logg("Scanned directories: %u\n", info.dirs);
	logg("Scanned files: %u\n", info.files);
	logg("Infected files: %u\n", info.ifiles);
	if(notremoved) {
	    logg("Not removed: %u\n", notremoved);
	}
	if(notmoved) {
	    logg("Not %s: %u\n", optget(opts, "copy")->enabled ? "moved" : "copied", notmoved);
	}
	mb = info.blocks * (CL_COUNT_PRECISION / 1024) / 1024.0;
	logg("Data scanned: %2.2lf MB\n", mb);
	rmb = info.rblocks * (CL_COUNT_PRECISION / 1024) / 1024.0;
	logg("Data read: %2.2lf MB (ratio %.2f:1)\n", rmb, info.rblocks ? (double)info.blocks/(double)info.rblocks : 0);
	logg("Time: %u.%3.3u sec (%u m %u s)\n", ds, dms/1000, ds/60, ds%60);
    }

    optfree(opts);

#if defined(C_WINDOWS) && defined(CL_THREAD_SAFE)
    if(!pthread_win32_process_detach_np()) {
	logg("!Can't stop the win32 pthreads layer\n");
	return 72;
    }
#endif

    return ret;
}
Example #20
0
int main( int argc, char *argv[] )
{
#ifdef Q_OS_WIN  // Windows
#ifdef _MSC_VER
  _set_fmode( _O_BINARY );
#else //MinGW
  _fmode = _O_BINARY;
#endif  // _MSC_VER
#endif  // Q_OS_WIN

  /////////////////////////////////////////////////////////////////
  // Command line options 'behaviour' flag setup
  ////////////////////////////////////////////////////////////////

  //
  // Parse the command line arguments, looking to see if the user has asked for any
  // special behaviours. Any remaining non command arguments will be kept aside to
  // be passed as a list of layers and / or a project that should be loaded.
  //

  int myIterations = 1;
  QString mySnapshotFileName = QLatin1String( "" );
  QString myLogFileName = QLatin1String( "" );
  QString myPrefixPath = QLatin1String( "" );
  int mySnapshotWidth = 800;
  int mySnapshotHeight = 600;
  QString myQuality = QLatin1String( "" );
  bool myParallel = false;
  QString myPrintTime = QStringLiteral( "total" );

  // This behaviour will set initial extent of map canvas, but only if
  // there are no command line arguments. This gives a usable map
  // extent when qgis starts with no layers loaded. When layers are
  // loaded, we let the layers define the initial extent.
  QString myInitialExtent = QLatin1String( "" );
  if ( argc == 1 )
    myInitialExtent = QStringLiteral( "-1,-1,1,1" );

  // The user can specify a path which will override the default path of custom
  // user settings (~/.qgis) and it will be used for QSettings INI file
  QString configpath;

#ifndef Q_OS_WIN
  ////////////////////////////////////////////////////////////////
  // USe the GNU Getopts utility to parse cli arguments
  // Invokes ctor `GetOpt (int argc, char **argv,  char *optstring);'
  ///////////////////////////////////////////////////////////////
  int optionChar;
  while ( 1 )
  {
    static struct option long_options[] =
    {
      /* These options set a flag. */
      {"help", no_argument, 0, '?'},
      /* These options don't set a flag.
       *  We distinguish them by their indices. */
      {"iterations",    required_argument, 0, 'i'},
      {"snapshot", required_argument, 0, 's'},
      {"log", required_argument, 0, 'l'},
      {"width",    required_argument, 0, 'w'},
      {"height",   required_argument, 0, 'h'},
      {"project",  required_argument, 0, 'p'},
      {"extent",   required_argument, 0, 'e'},
      {"optionspath", required_argument, 0, 'o'},
      {"configpath", required_argument, 0, 'c'},
      {"prefix", required_argument, 0, 'r'},
      {"quality", required_argument, 0, 'q'},
      {"parallel", no_argument, 0, 'P'},
      {"print", required_argument, 0, 'R'},
      {0, 0, 0, 0}
    };

    /* getopt_long stores the option index here. */
    int option_index = 0;

    optionChar = getopt_long( argc, argv, "islwhpeocrq",
                              long_options, &option_index );

    /* Detect the end of the options. */
    if ( optionChar == -1 )
      break;

    switch ( optionChar )
    {
      case 0:
        /* If this option set a flag, do nothing else now. */
        if ( long_options[option_index].flag != 0 )
          break;
        printf( "option %s", long_options[option_index].name );
        if ( optarg )
          printf( " with arg %s", optarg );
        printf( "\n" );
        break;

      case 'i':
        myIterations = QString( optarg ).toInt();
        break;

      case 's':
        mySnapshotFileName = QDir::toNativeSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() );
        break;

      case 'l':
        myLogFileName = QDir::toNativeSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() );
        break;

      case 'w':
        mySnapshotWidth = QString( optarg ).toInt();
        break;

      case 'h':
        mySnapshotHeight = QString( optarg ).toInt();
        break;

      case 'p':
        myProjectFileName = QDir::toNativeSeparators( QFileInfo( QFile::decodeName( optarg ) ).absoluteFilePath() );
        break;

      case 'e':
        myInitialExtent = optarg;
        break;

      case 'o':
        QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optarg );
        break;

      case 'c':
        configpath = optarg;
        break;

      case 'r':
        myPrefixPath = optarg;
        break;

      case 'q':
        myQuality = optarg;
        break;

      case 'P':
        myParallel = true;
        break;

      case 'R':
        myPrintTime = optarg;
        break;

      case '?':
        usage( argv[0] );
        return 2;   // XXX need standard exit codes

      default:
        QgsDebugMsg( QString( "%1: getopt returned character code %2" ).arg( argv[0] ).arg( optionChar ) );
        return 1;   // XXX need standard exit codes
    }
  }

  // Add any remaining args to the file list - we will attempt to load them
  // as layers in the map view further down....
  QgsDebugMsg( QString( "Files specified on command line: %1" ).arg( optind ) );
  if ( optind < argc )
  {
    while ( optind < argc )
    {
#ifdef QGISDEBUG
      int idx = optind;
      QgsDebugMsg( QString( "%1: %2" ).arg( idx ).arg( argv[idx] ) );
#endif
      myFileList.append( QDir::toNativeSeparators( QFileInfo( QFile::decodeName( argv[optind++] ) ).absoluteFilePath() ) );
    }
  }
#else
  for ( int i = 1; i < argc; i++ )
  {
    QString arg = argv[i];

    if ( arg == "--help" || arg == "-?" )
    {
      usage( argv[0] );
      return 2;
    }
    else if ( i + 1 < argc && ( arg == "--iterations" || arg == "-i" ) )
    {
      myIterations = QString( argv[++i] ).toInt();
    }
    else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) )
    {
      mySnapshotFileName = QDir::toNativeSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() );
    }
    else if ( i + 1 < argc && ( arg == "--log" || arg == "-l" ) )
    {
      myLogFileName = QDir::toNativeSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() );
    }
    else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) )
    {
      mySnapshotWidth = QString( argv[++i] ).toInt();
    }
    else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) )
    {
      mySnapshotHeight = QString( argv[++i] ).toInt();
    }
    else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) )
    {
      myProjectFileName = QDir::toNativeSeparators( QFileInfo( QFile::decodeName( argv[++i] ) ).absoluteFilePath() );
    }
    else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) )
    {
      myInitialExtent = argv[++i];
    }
    else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) )
    {
      QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, argv[++i] );
    }
    else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) )
    {
      configpath = argv[++i];
      QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, configpath );
    }
    else if ( i + 1 < argc && ( arg == "--prefix" ) )
    {
      myPrefixPath = argv[++i];
    }
    else if ( i + 1 < argc && ( arg == "--quality" || arg == "-q" ) )
    {
      myQuality = argv[++i];
    }
    else if ( arg == "--parallel" || arg == "-P" )
    {
      myParallel = true;
    }
    else if ( i + 1 < argc && ( arg == "--print" || arg == "-R" ) )
    {
      myPrintTime = argv[++i];
    }
    else
    {
      myFileList.append( QDir::toNativeSeparators( QFileInfo( QFile::decodeName( argv[i] ) ).absoluteFilePath() ) );
    }
  }
#endif // Q_OS_WIN

  /////////////////////////////////////////////////////////////////////
  // Now we have the handlers for the different behaviours...
  ////////////////////////////////////////////////////////////////////

  /////////////////////////////////////////////////////////////////////
  // Initialise the application and the translation stuff
  /////////////////////////////////////////////////////////////////////

  if ( !configpath.isEmpty() )
  {
    // tell QSettings to use INI format and save the file in custom config path
    QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, configpath );
  }

  // TODO: Qt: there should be exactly one QCoreApplication object for console app.
  // but QgsApplication inherits from QApplication (GUI)
  // it is working, but maybe we should make QgsCoreApplication, which
  // could also be used by mapserver
  // Note (mkuhn,20.4.2013): Labeling does not work with QCoreApplication, because
  // fontconfig needs some X11 dependencies which are initialized in QApplication (GUI)
  // using it with QCoreApplication only crashes at the moment.
  // Only use QgsApplication( int, char **, bool GUIenabled, QString) for newer versions
  // so that this program may be run with old libraries
  //QgsApplication myApp( argc, argv, false, configpath );

  QCoreApplication *myApp;

#if VERSION_INT >= 10900
  myApp = new QgsApplication( argc, argv, false );
#else
  myApp = new QCoreApplication( argc, argv );
#endif

  if ( myPrefixPath.isEmpty() )
  {
    QDir dir( QCoreApplication::applicationDirPath() );
    dir.cdUp();
    myPrefixPath = dir.absolutePath();
  }
  QgsApplication::setPrefixPath( myPrefixPath, true );

  // Set up the QSettings environment must be done after qapp is created
  QgsApplication::setOrganizationName( QStringLiteral( "QGIS" ) );
  QgsApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) );
  QgsApplication::setApplicationName( QStringLiteral( "QGIS3" ) );

  QgsProviderRegistry::instance( QgsApplication::pluginPath() );

#ifdef Q_OS_MACX
  // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH
  // is not already defined, use the GDAL plugins in the application bundle.
  QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) );
  if ( QFile::exists( gdalPlugins ) && !getenv( "GDAL_DRIVER_PATH" ) )
  {
    setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 );
  }

  // Point GDAL_DATA at any GDAL share directory embedded in the app bundle
  if ( !getenv( "GDAL_DATA" ) )
  {
    QStringList gdalShares;
    QString appResources( QDir::cleanPath( QgsApplication::pkgDataPath() ) );
    gdalShares << QCoreApplication::applicationDirPath().append( "/share/gdal" )
    << appResources.append( "/share/gdal" )
    << appResources.append( "/gdal" );
    Q_FOREACH ( const QString& gdalShare, gdalShares )
    {
      if ( QFile::exists( gdalShare ) )
      {
        setenv( "GDAL_DATA", gdalShare.toUtf8().constData(), 1 );
        break;
      }
    }
  }
Example #21
0
// This is an example of an exported function.
int  CDownload::HttpFileDownload(char* lpszServer, char* lpszDest, HWND hWndProgress, HWND hWndMsg)
{

  int bReturn = 0;
  
  HINTERNET hOpen = NULL, 
            hRequest = NULL;

  DWORD dwSize = 0, 
        dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE; 

  TCHAR szErrMsg[512];
  
  char *lpBufferA;

  LPTSTR AcceptTypes[10] = {TEXT("*/*"), NULL}; 

  hOpen = InternetOpen (TEXT("HttpFileDownload"), INTERNET_OPEN_TYPE_PRECONFIG , NULL, 0, 0);  

  if (!hOpen)
  {
    _stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("InternetOpen Error"),  GetLastError());
	OutputDebugString(szErrMsg);
    return 1;
  }
    DWORD dwRequestFlag = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;

	if(strstr(lpszServer,"https://")!=NULL) //check if it is a HTTPS server
		dwRequestFlag = INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID | INTERNET_FLAG_IGNORE_CERT_CN_INVALID;

	hRequest = InternetOpenUrl (hOpen, lpszServer, NULL, 0,dwRequestFlag, 0);
    if (hRequest==NULL)
    {
		_stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("InternetOpenUrl Error"),GetLastError());
		OutputDebugString(szErrMsg);
		bReturn = 2;
		goto exit;
    }
 
    char szLength[32];
	
	DWORD dwLength=0,dwBuffLen=sizeof(szLength);

   if(HttpQueryInfo (hRequest, HTTP_QUERY_CONTENT_LENGTH, &szLength,&dwBuffLen, NULL)==FALSE)
   {
		_stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("HttpQueryInfo Error"),GetLastError());
		OutputDebugString(szErrMsg);
   }
	dwLength = (DWORD)atol(szLength) ;
	_stprintf_s(szErrMsg, TEXT("Size to download %d\n"),dwLength);
	OutputDebugString(szErrMsg);

   FILE *stream = NULL;
   errno_t err = _set_fmode(_O_BINARY);
   if (err == EINVAL)
   { 
	  OutputDebugString("Invalid mode.\n");
      return 5;
   }
	if(hWndProgress!=NULL)
	 SendMessage(hWndProgress, PBM_SETRANGE, (WPARAM) 0,MAKELPARAM(0, 100));

		
	  DWORD dynamicByte = 32000;
	  DWORD downloadBytes = 0;
	  do
	  {
		 lpBufferA = new CHAR [dynamicByte];

		 sprintf_s(szErrMsg,sizeof(szErrMsg),"Downloaded %d of %d KBytes\n",downloadBytes/1000,dwLength/1000);
		 OutputDebugString(szErrMsg);

		 if(hWndProgress!=NULL)
		 {
			float percentage =  ((float)downloadBytes /  (float)dwLength) * 100.0f ;
			if(percentage>100.0f)
				percentage = 100;
			HWND hwnMsg = GetDlgItem(hWndProgress,IDC_STATIC_TEXT);
			SendMessage(hWndMsg,WM_SETTEXT,0,(LPARAM)szErrMsg);		
			SendMessage(hWndProgress, PBM_SETPOS, (WPARAM) percentage, 0);
		 }
		
		if (!InternetReadFile (hRequest, (LPVOID)lpBufferA, dynamicByte, &dwSize))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("InternetReadFile Error"),GetLastError());
			OutputDebugString(szErrMsg);
		  delete[] lpBufferA;
		  goto exit;
		}

		if (dwSize != 0)    
		{	
			downloadBytes+=dwSize;
			//Quick check if HTML error has occured
			if(strncmp("<!DOCTYPE",lpBufferA,9)==0)
					bReturn = 100;
			if(strncmp("<HTM",lpBufferA,4)==0)
					bReturn = 100;
			if(strncmp("<htm",lpBufferA,4)==0)
					bReturn = 100;	

			if((stream==NULL) && (bReturn==0))
		   		fopen_s(&stream, lpszDest, "w+" );

			if(stream!=NULL)
				 fwrite( lpBufferA, sizeof( CHAR ), dwSize, stream );		
		}    
		delete[] lpBufferA; 
		dynamicByte+=1024;
		if(dynamicByte>128000)
			dynamicByte = 128000;
			

	  } while (dwSize);


	  if(stream!=NULL)
  		  fclose( stream );


  goto exitWithNoErr;
exit:
	bReturn = 1;
exitWithNoErr:
    if (hRequest)
  {
    if (!InternetCloseHandle (hRequest))
	{
		_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), GetLastError());
		OutputDebugString(szErrMsg);

	}
  }

  // Close the Internet handles.
  if (hOpen)
  {
    if (!InternetCloseHandle (hOpen))
	{
		_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), GetLastError());
		OutputDebugString(szErrMsg);

	}
  }
  
  _stprintf_s(szErrMsg, TEXT("Return %d"), bReturn);
  OutputDebugString(szErrMsg);
  return bReturn;
}