コード例 #1
0
extern "C" _declspec(dllexport) int main(int argc, char **argv) {
#else
int main(int argc, char **argv) {
#endif
	int res = 0;

	QT_REQUIRE_VERSION(argc, argv, "4.4.0");

#if defined(Q_OS_WIN)
	SetDllDirectory(L"");
#else
#ifndef Q_OS_MAC
	setenv("AVAHI_COMPAT_NOWARN", "1", 1);
#endif
#endif

	// Initialize application object.
	MumbleApplication a(argc, argv);
	a.setApplicationName(QLatin1String("Mumble"));
	a.setOrganizationName(QLatin1String("Mumble"));
	a.setOrganizationDomain(QLatin1String("mumble.sourceforge.net"));
	a.setQuitOnLastWindowClosed(false);

#if QT_VERSION >= 0x050100
	a.setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

#if QT_VERSION >= 0x050000 && defined(Q_OS_WIN)
	a.installNativeEventFilter(&a);
#endif

	MumbleSSL::initialize();

	#ifdef USE_SBCELT
	{
		QDir d(a.applicationVersionRootPath());
		QString helper = d.absoluteFilePath(QString::fromLatin1("sbcelt-helper"));
		setenv("SBCELT_HELPER_BINARY", helper.toUtf8().constData(), 1);
	}
#endif

	Global::g_global_struct = new Global();

	qsrand(QDateTime::currentDateTime().toTime_t());

	g.le = QSharedPointer<LogEmitter>(new LogEmitter());
	g.c = new DeveloperConsole();

	os_init();

	bool bAllowMultiple = false;
	bool suppressIdentity = false;
	bool bRpcMode = false;
	QString rpcCommand;
	QUrl url;
	if (a.arguments().count() > 1) {
		QStringList args = a.arguments();
		for (int i = 1; i < args.count(); ++i) {
			if (args.at(i) == QLatin1String("-h") || args.at(i) == QLatin1String("--help")
#if defined(Q_OS_WIN)
				|| args.at(i) == QLatin1String("/?")
#endif
			) {
				QString helpMessage = MainWindow::tr(
					"Usage: mumble [options] [<url>]\n"
					"\n"
					"<url> specifies a URL to connect to after startup instead of showing\n"
					"the connection window, and has the following form:\n"
					"mumble://[<username>[:<password>]@]<host>[:<port>][/<channel>[/<subchannel>...]][?version=<x.y.z>]\n"
					"\n"
					"The version query parameter has to be set in order to invoke the\n"
					"correct client version. It currently defaults to 1.2.0.\n"
					"\n"
					"Valid options are:\n"
					"  -h, --help    Show this help text and exit.\n"
					"  -m, --multiple\n"
					"                Allow multiple instances of the client to be started.\n"
					"  -n, --noidentity\n"
					"                Suppress loading of identity files (i.e., certificates.)\n"
					"  --license\n"
					"                Show the Mumble license.\n"
					"  --authors\n"
					"                Show the Mumble authors.\n"
					"  --third-party-licenses\n"
					"                Show licenses for third-party software used by Mumble.\n"
					"\n"
				);
				QString rpcHelpBanner = MainWindow::tr(
					"Remote controlling Mumble:\n"
					"\n"
				);
				QString rpcHelpMessage = MainWindow::tr(
					"Usage: mumble rpc <action> [options]\n"
					"\n"
					"It is possible to remote control a running instance of Mumble by using\n"
					"the 'mumble rpc' command.\n"
					"\n"
					"Valid actions are:\n"
					"  mute\n"
					"                Mute self\n"
					"  unmute\n"
					"                Unmute self\n"
					"  togglemute\n"
					"                Toggle self-mute status\n"
					"  deaf\n"
					"                Deafen self\n"
					"  undeaf\n"
					"                Undeafen self\n"
					"  toggledeaf\n"
					"                Toggle self-deafen stauts\n"
					"\n"
				);

				QString helpOutput = helpMessage + rpcHelpBanner + rpcHelpMessage;
				if (bRpcMode) {
					helpOutput = rpcHelpMessage;
				}

#if defined(Q_OS_WIN)
				QMessageBox::information(NULL, MainWindow::tr("Invocation"), helpOutput);
#else
				printf("%s", qPrintable(helpOutput));
#endif
				return 1;
			} else if (args.at(i) == QLatin1String("-m") || args.at(i) == QLatin1String("--multiple")) {
				bAllowMultiple = true;
			} else if (args.at(i) == QLatin1String("-n") || args.at(i) == QLatin1String("--noidentity")) {
				suppressIdentity = true;
				g.s.bSuppressIdentity = true;
			} else if (args.at(i) == QLatin1String("-license") || args.at(i) == QLatin1String("--license")) {
				printf("%s\n", qPrintable(License::license()));
				return 0;
			} else if (args.at(i) == QLatin1String("-authors") || args.at(i) == QLatin1String("--authors")) {
				printf("%s\n", qPrintable(License::authors()));
				return 0;
			} else if (args.at(i) == QLatin1String("-third-party-licenses") || args.at(i) == QLatin1String("--third-party-licenses")) {
				printf("%s", qPrintable(License::printableThirdPartyLicenseInfo()));
				return 0;
			} else if (args.at(i) == QLatin1String("rpc")) {
				bRpcMode = true;
				if (args.count() - 1 > i) {
					rpcCommand = QString(args.at(i + 1));
				}
				else {
					QString rpcError = MainWindow::tr("Error: No RPC command specified");
#if defined(Q_OS_WIN)
					QMessageBox::information(NULL, MainWindow::tr("RPC"), rpcError);
#else
					printf("%s\n", qPrintable(rpcError));
#endif
					return 1;
				}
			} else {
				if (!bRpcMode) {
					QUrl u = QUrl::fromEncoded(args.at(i).toUtf8());
					if (u.isValid() && (u.scheme() == QLatin1String("mumble"))) {
						url = u;
					} else {
						QFile f(args.at(i));
						if (f.exists()) {
							url = QUrl::fromLocalFile(f.fileName());
						}
					}
				}
			}
		}
	}

#ifdef USE_DBUS
#ifdef Q_OS_WIN
	// By default, windbus expects the path to dbus-daemon to be in PATH, and the path
	// should contain bin\\, and the path to the config is hardcoded as ..\etc

	{
		size_t reqSize;
		_wgetenv_s(&reqSize, NULL, 0, L"PATH");
		if (reqSize > 0) {
			STACKVAR(wchar_t, buff, reqSize+1);
			_wgetenv_s(&reqSize, buff, reqSize, L"PATH");
			QString path = QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(MumbleApplication::instance()->applicationVersionRootPath())).arg(QString::fromWCharArray(buff));
			STACKVAR(wchar_t, buffout, path.length() + 1);
			path.toWCharArray(buffout);
			_wputenv_s(L"PATH", buffout);
		}
	}
コード例 #2
0
ファイル: s.c プロジェクト: BirchJD/advancemame-0.106.1-RPi
int os_main(int argc, char* argv[])
{
	int keyboard_id;
	adv_conf* context;
	const char* s;
        char* section_map[1];
	const char** file_map;
	unsigned file_mac;
	int i;
	double latency_time;
	double buffer_time;
	double volume;
	unsigned rate;
	int attenuation;
	adv_bool opt_log;
	adv_bool opt_logsync;

	opt_log = 0;
	opt_logsync = 0;
	file_map = 0;
	file_mac = 0;

	context = conf_init();

	if (os_init(context) != 0)
		goto err_conf;

	mixer_reg(context);

	conf_int_register_limit_default(context, "sound_volume", -32, 0, 0);
	conf_int_register_limit_default(context, "sound_samplerate", 5000, 96000, 44100);
	conf_float_register_limit_default(context, "sound_latency", 0.01, 2.0, 0.1);
	conf_float_register_limit_default(context, "sound_buffer", 0.05, 2.0, 0.1);

	if (conf_input_args_load(context, 0, "", &argc, argv, error_callback, 0) != 0)
		goto err_os;

	file_map = malloc(argc * sizeof(const char*));

	for(i=1;i<argc;++i) {
		if (target_option_compare(argv[i], "log")) {
			opt_log = 1;
		} else if (target_option_compare(argv[i], "logsync")) {
			opt_logsync = 1;
		} else if (target_option_extract(argv[i]) == 0) {
			file_map[file_mac++] = argv[i];
		} else {
			target_err("Unknown command line option '%s'.\n", argv[i]);
			goto err_os;
		}
	}

	if (argc <= 1 || file_mac == 0) {
		target_err("Syntax: advs FILES...\n");
		goto err_os;
	}

	if (opt_log || opt_logsync) {
		const char* log = "advs.log";
		remove(log);
		log_init(log, opt_logsync);
        }

	section_map[0] = "";
	conf_section_set(context, section_map, 1);

	if (mixer_load(context) != 0) {
		goto err_os;
	}

	attenuation = conf_int_get_default(context, "sound_volume");
	latency_time = conf_float_get_default(context, "sound_latency");
	buffer_time = conf_float_get_default(context, "sound_buffer");
	rate = conf_int_get_default(context, "sound_samplerate");
	volume = 1.0;
	while (attenuation++ < 0)
		volume /= 1.122018454; /* = (10 ^ (1/20)) = 1dB */

	if (os_inner_init("AdvanceSOUND") != 0)
		goto err_os;

	if (file_mac > MIXER_CHANNEL_MAX) {
		target_err("Too many files\n");
		goto err_os_inner;
	}

	if (mixer_init(rate, file_mac, 1, buffer_time + latency_time, latency_time) != 0) {
		target_err("%s\n", error_get());
		goto err_os_inner;
	}

	mixer_volume(volume);

	for(i=0;i<file_mac;++i)
		run(i, file_map[i]);

	free(file_map);

	signal(SIGINT, sigint);

	while (!done) {
		for(i=0;i<file_mac;++i)
			if (mixer_is_playing(i))
				break;
		if (i==file_mac)
			break;

		mixer_poll();
		target_idle();
	}

	log_std(("s: shutdown\n"));

	mixer_done();

	os_inner_done();

	log_std(("s: the end\n"));

	if (opt_log || opt_logsync) {
		log_done();
	}

	os_done();
	conf_done(context);

	return EXIT_SUCCESS;

err_os_inner:
	os_inner_done();
	log_done();
err_os:
	os_done();
err_conf:
	conf_done(context);
err:
	return EXIT_FAILURE;

}
コード例 #3
0
ファイル: main.cpp プロジェクト: martijns/mumble
int main(int argc, char **argv) {
	int res = 0;

	QT_REQUIRE_VERSION(argc, argv, "4.4.0");

#if defined(Q_OS_WIN)
	SetDllDirectory(L"");
#else
#ifndef Q_OS_MAC
	setenv("AVAHI_COMPAT_NOWARN", "1", 1);
#endif
#endif

	// Initialize application object.
	QAppMumble a(argc, argv);
	a.setApplicationName(QLatin1String("Mumble"));
	a.setOrganizationName(QLatin1String("Mumble"));
	a.setOrganizationDomain(QLatin1String("mumble.sourceforge.net"));
	a.setQuitOnLastWindowClosed(false);

	Global::g_global_struct = new Global();

	qsrand(QDateTime::currentDateTime().toTime_t());

#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
	os_init();
#endif

	bool bAllowMultiple = false;
	QUrl url;
	if (a.arguments().count() > 1) {
		QStringList args = a.arguments();
		for (int i = 1; i < args.count(); ++i) {
			if (args.at(i) == QLatin1String("-m")) {
				bAllowMultiple = true;
			} else if (args.at(i) == QLatin1String("-n")) {
				g.s.bSuppressIdentity = true;
			} else {
				QUrl u = QUrl::fromEncoded(args.at(i).toUtf8());
				if (u.isValid() && (u.scheme() == QLatin1String("mumble"))) {
					url = u;
				} else {
					QFile f(args.at(i));
					if (f.exists()) {
						url = QUrl::fromLocalFile(f.fileName());
					}
				}
			}
		}
	}

#ifdef USE_DBUS
#ifdef Q_OS_WIN
	// By default, windbus expects the path to dbus-daemon to be in PATH, and the path
	// should contain bin\\, and the path to the config is hardcoded as ..\etc

	{
		size_t reqSize;
		_wgetenv_s(&reqSize, NULL, 0, L"PATH");
		if (reqSize > 0) {
			STACKVAR(wchar_t, buff, reqSize+1);
			_wgetenv_s(&reqSize, buff, reqSize, L"PATH");
			QString path = QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(a.applicationDirPath())).arg(QString::fromWCharArray(buff));
			STACKVAR(wchar_t, buffout, path.length() + 1);
			path.toWCharArray(buffout);
			_wputenv_s(L"PATH", buffout);
		}
	}
コード例 #4
0
int main(int argc, char** argv) 
{
	os_init(argc, argv);

}
コード例 #5
0
ファイル: device.cpp プロジェクト: nyue/embree
  Device::Device (const char* cfg, bool singledevice)
    : State(singledevice)
  {
    /* check CPU */
    if (!hasISA(ISA)) 
      throw_RTCError(RTC_UNSUPPORTED_CPU,"CPU does not support " ISA_STR);

    /* initialize global state */
    State::parseString(cfg);
    if (!ignore_config_files && FileName::executableFolder() != FileName(""))
      State::parseFile(FileName::executableFolder()+FileName(".embree" TOSTRING(RTCORE_VERSION_MAJOR)));
    if (!ignore_config_files && FileName::homeFolder() != FileName(""))
      State::parseFile(FileName::homeFolder()+FileName(".embree" TOSTRING(RTCORE_VERSION_MAJOR)));
    State::verify();

    /*! do some internal tests */
    assert(isa::Cylinder::verify());

    /*! enable huge page support if desired */
#if defined(__WIN32__)
    if (State::enable_selockmemoryprivilege)
      State::hugepages_success &= win_enable_selockmemoryprivilege(State::verbosity(3));
#endif
    State::hugepages_success &= os_init(State::hugepages,State::verbosity(3));
    
    /*! set tessellation cache size */
    setCacheSize( State::tessellation_cache_size );

    /*! enable some floating point exceptions to catch bugs */
    if (State::float_exceptions)
    {
      int exceptions = _MM_MASK_MASK;
      //exceptions &= ~_MM_MASK_INVALID;
      exceptions &= ~_MM_MASK_DENORM;
      exceptions &= ~_MM_MASK_DIV_ZERO;
      //exceptions &= ~_MM_MASK_OVERFLOW;
      //exceptions &= ~_MM_MASK_UNDERFLOW;
      //exceptions &= ~_MM_MASK_INEXACT;
      _MM_SET_EXCEPTION_MASK(exceptions);
    }

    /* print info header */
    if (State::verbosity(1))
      print();
    if (State::verbosity(2)) 
      State::print();

    /* register all algorithms */
    instance_factory = make_unique(new InstanceFactory(enabled_cpu_features));

    bvh4_factory = make_unique(new BVH4Factory(enabled_builder_cpu_features, enabled_cpu_features));

#if defined(EMBREE_TARGET_SIMD8)
    bvh8_factory = make_unique(new BVH8Factory(enabled_builder_cpu_features, enabled_cpu_features));
#endif

    /* setup tasking system */
    initTaskingSystem(numThreads);

    /* ray stream SOA to AOS conversion */
#if defined(EMBREE_RAY_PACKETS)
    RayStreamFilterFuncsType rayStreamFilterFuncs;
    SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2_AVX512KNL_AVX512SKX(enabled_cpu_features,rayStreamFilterFuncs);
    rayStreamFilters = rayStreamFilterFuncs();
#endif
  }
コード例 #6
0
ファイル: lua-socket.c プロジェクト: catinred2/levent
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
    if(fdwReason == DLL_PROCESS_ATTACH) {
        os_init();
    }
    return TRUE;
}
コード例 #7
0
ファイル: kweb.c プロジェクト: klueska/kweb
int main(int argc, char **argv)
{
    int port, pid, socketfd;
    socklen_t length;
    static struct sockaddr_in cli_addr; /* static = initialised to zeros */
    static struct sockaddr_in serv_addr; /* static = initialised to zeros */

    InitializeMagick(*argv);
    /* Verify proper number of args and print usage if invalid */
    if( argc < 3  || argc > 4 || !strcmp(argv[1], "-?") ) {
        printf(""
               "kweb - Version %s\n"
               "Usage: kweb <port_number> <top_directory> [<tpool_size=MAX_INT>]\n"
               "Example: kweb 8181 /home/kwebdir &\n\n"
               "         kweb 8181 /home/kwebdir 50 &\n\n"

               "kweb is a small and safe multi-threaded static web server\n"
               "It only serves files with the extensions named below.\n"
               "It also only serves files from the named directory or its sub-directories.\n\n"

               "Supports:", VERSION);
        for(int i=0; extensions[i].ext != 0; i++)
            printf(" %s", extensions[i].ext);
        printf(""
               "\n"
               "Not Supported: URLs including \"..\", Java, Javascript, CGI\n"
               "Not Supported: directories / /etc /bin /lib /tmp /usr /dev /sbin\n\n"

               "No warranty given or implied\n"
               "Kevin Klues <*****@*****.**>\n"
               "(Adapted from nweb Version 23 by Nigel Griffiths <*****@*****.**>)\n");
        exit(0);
    }

    /* Make sure the specified ROOT directory is a valid one */
    if(!strncmp(argv[2], "/"   , 2 ) || !strncmp(argv[2], "/etc", 5 ) ||
            !strncmp(argv[2], "/bin", 5 ) || !strncmp(argv[2], "/lib", 5 ) ||
            !strncmp(argv[2], "/tmp", 5 ) || !strncmp(argv[2], "/usr", 5 ) ||
            !strncmp(argv[2], "/dev", 5 ) || !strncmp(argv[2], "/sbin", 6)) {
        printf("ERROR: Bad top directory %s, see kweb -?\n", argv[2]);
        exit(1);
    }

    /* Verify that the specified port number is a valid one */
    port = atoi(argv[1]);
    if(port < 0 || port > 60000) {
        printf("ERROR: Invalid port number %d (try 1->60000)\n", port);
        exit(1);
    }

    /* Change to the specified ROOT directory to set it as the ROOT of the fs */
    if(chdir(argv[2]) == -1) {
        printf("ERROR: Can't Change to directory %s\n", argv[2]);
        exit(1);
    }

    /* Change to the specified ROOT directory to set it as the ROOT of the fs */
    if(argc == 4) {
        tpool_size = atoi(argv[3]);
        if(tpool_size < 1 || tpool_size > INT_MAX) {
            printf("ERROR: Invalid tpool size %d. Must be >= 1.\n", tpool_size);
            exit(1);
        }
    }

    /* Setup the network socket */
    if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("ERROR: System call - socket\n");
        exit(1);
    }

    /* Set the sockopts so that we can rebind in case of ungracefully shutting
     * down the server */
    int yes = 1;
    if(setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes))) {
        printf("ERROR: System call - setsockopt\n");
        exit(1);
    }

    /* Bind to the specified address and listen on the specified port */
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(port);
    if(bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        printf("ERROR: System call - bind\n");
        exit(1);
    }
    if(listen(listenfd, 64) < 0) {
        printf("ERROR: System call - listen\n");
        exit(1);
    }

    /* Register a signal handler so we can print out some statistics once we kill
     * the server */
    if(signal(SIGINT, sig_int) == SIG_ERR) {
        printf("\nCan't catch SIGINT\n");
        exit(1);
    }

    /* Register a signal handler for sigpipe in case someone closes a socket
     * while we are in the middle of writing it */
    if(signal(SIGPIPE, sig_pipe) == SIG_ERR) {
        printf("\nCan't catch SIGPIPE\n");
        exit(1);
    }

    /* Initialize necessary data structures */
    os_init();

    /* Get the TSC frequency for our timestamp measurements */
    server_stats.tsc_freq = get_tsc_freq();

    /* Start accepting requests and processing them */
    fflush(stdout);
    logger(LOG, "Starting kweb", argv[1], getpid());
    printf("Server Started\n");
    printf("Thread Pool Size: %d\n", tpool.size);
    printf("TSC Frequency: %lu\n", server_stats.tsc_freq);
    length = sizeof(cli_addr);
    for(;;) {
        if((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &length)) < 0) {
            logger(ERROR, "System call", "accept", 0);
        }
        else {
            dispatch_call(socketfd, (void*)&cli_addr);
        }
    }
}
コード例 #8
0
ファイル: main.cpp プロジェクト: BuddyButterfly/mumble
extern "C" _declspec(dllexport) int main(int argc, char **argv) {
#else
int main(int argc, char **argv) {
#endif
	int res = 0;

	QT_REQUIRE_VERSION(argc, argv, "4.4.0");

#if defined(Q_OS_WIN)
	SetDllDirectory(L"");
#else
#ifndef Q_OS_MAC
	setenv("AVAHI_COMPAT_NOWARN", "1", 1);
#endif
#endif

	// Initialize application object.
	MumbleApplication a(argc, argv);
	a.setApplicationName(QLatin1String("Mumble"));
	a.setOrganizationName(QLatin1String("Mumble"));
	a.setOrganizationDomain(QLatin1String("mumble.sourceforge.net"));
	a.setQuitOnLastWindowClosed(false);

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) && defined(Q_OS_WIN)
	a.installNativeEventFilter(&a);
#endif

	#ifdef USE_SBCELT
	{
		// For now, force Mumble to use sbcelt-helper from the same directory as the 'mumble' executable.
		QDir d(a.applicationDirPath());
		QString helper = d.absoluteFilePath(QString::fromLatin1("sbcelt-helper"));
		setenv("SBCELT_HELPER_BINARY", helper.toUtf8().constData(), 1);
	}
#endif

	Global::g_global_struct = new Global();

	qsrand(QDateTime::currentDateTime().toTime_t());

#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
	os_init();
#endif

	bool bAllowMultiple = false;
	QUrl url;
	if (a.arguments().count() > 1) {
		QStringList args = a.arguments();
		for (int i = 1; i < args.count(); ++i) {
			if (args.at(i) == QLatin1String("-h") || args.at(i) == QLatin1String("--help")
#if defined(Q_OS_WIN)
				|| args.at(i) == QLatin1String("/?")
#endif
			) {
				QString helpmessage = MainWindow::tr( "Usage: mumble [options] [<url>]\n"
					"\n"
					"<url> specifies a URL to connect to after startup instead of showing\n"
					"the connection window, and has the following form:\n"
					"mumble://[<username>[:<password>]@]<host>[:<port>][/<channel>[/<subchannel>...]][?version=<x.y.z>]\n"
					"\n"
					"The version query parameter has to be set in order to invoke the\n"
					"correct client version. It currently defaults to 1.2.0.\n"
					"\n"
					"Valid options are:\n"
					"  -h, --help    Show this help text and exit.\n"
					"  -m, --multiple\n"
					"                Allow multiple instances of the client to be started.\n"
					"  -n, --noidentity\n"
					"                Suppress loading of identity files (i.e., certificates.)\n"
					);
#if defined(Q_OS_WIN)
				QMessageBox::information(NULL, MainWindow::tr("Invocation"), helpmessage);
#else
				printf("%s", qPrintable(helpmessage));
#endif
				return 1;
			} else if (args.at(i) == QLatin1String("-m") || args.at(i) == QLatin1String("--multiple")) {
				bAllowMultiple = true;
			} else if (args.at(i) == QLatin1String("-n") || args.at(i) == QLatin1String("--noidentity")) {
				g.s.bSuppressIdentity = true;
			} else {
				QUrl u = QUrl::fromEncoded(args.at(i).toUtf8());
				if (u.isValid() && (u.scheme() == QLatin1String("mumble"))) {
					url = u;
				} else {
					QFile f(args.at(i));
					if (f.exists()) {
						url = QUrl::fromLocalFile(f.fileName());
					}
				}
			}
		}
	}

#ifdef USE_DBUS
#ifdef Q_OS_WIN
	// By default, windbus expects the path to dbus-daemon to be in PATH, and the path
	// should contain bin\\, and the path to the config is hardcoded as ..\etc

	{
		size_t reqSize;
		_wgetenv_s(&reqSize, NULL, 0, L"PATH");
		if (reqSize > 0) {
			STACKVAR(wchar_t, buff, reqSize+1);
			_wgetenv_s(&reqSize, buff, reqSize, L"PATH");
			QString path = QString::fromLatin1("%1;%2").arg(QDir::toNativeSeparators(a.applicationDirPath())).arg(QString::fromWCharArray(buff));
			STACKVAR(wchar_t, buffout, path.length() + 1);
			path.toWCharArray(buffout);
			_wputenv_s(L"PATH", buffout);
		}
	}
コード例 #9
0
ファイル: runtime.c プロジェクト: r3v01v3r/sbcl-tfb
int
main(int argc, char *argv[], char *envp[])
{
#ifdef LISP_FEATURE_WIN32
    /* Exception handling support structure. Evil Win32 hack. */
    struct lisp_exception_frame exception_frame;
#endif

    /* the name of the core file we're to execute. Note that this is
     * a malloc'ed string which should be freed eventually. */
    char *core = 0;
    char **sbcl_argv = 0;
    os_vm_offset_t embedded_core_offset = 0;
    char *runtime_path = 0;

    /* other command line options */
    boolean noinform = 0;
    boolean end_runtime_options = 0;
    boolean disable_lossage_handler_p = 0;

    lispobj initial_function;
    const char *sbcl_home = getenv("SBCL_HOME");

    interrupt_init();
    block_blockable_signals(0, 0);

    setlocale(LC_ALL, "");

    runtime_options = NULL;

    /* Check early to see if this executable has an embedded core,
     * which also populates runtime_options if the core has runtime
     * options */
    runtime_path = os_get_runtime_executable_path();
    if (runtime_path) {
        os_vm_offset_t offset = search_for_embedded_core(runtime_path);
        if (offset != -1) {
            embedded_core_offset = offset;
            core = runtime_path;
        } else {
            free(runtime_path);
        }
    }


    /* Parse our part of the command line (aka "runtime options"),
     * stripping out those options that we handle. */
    if (runtime_options != NULL) {
        dynamic_space_size = runtime_options->dynamic_space_size;
        thread_control_stack_size = runtime_options->thread_control_stack_size;
        sbcl_argv = argv;
    } else {
        int argi = 1;

        runtime_options = successful_malloc(sizeof(struct runtime_options));

        while (argi < argc) {
            char *arg = argv[argi];
            if (0 == strcmp(arg, "--script")) {
                /* This is both a runtime and a toplevel option. As a
                 * runtime option, it is equivalent to --noinform.
                 * This exits, and does not increment argi, so that
                 * TOPLEVEL-INIT sees the option. */
                noinform = 1;
                end_runtime_options = 1;
                disable_lossage_handler_p = 1;
                lose_on_corruption_p = 1;
                break;
            } else if (0 == strcmp(arg, "--noinform")) {
                noinform = 1;
                ++argi;
            } else if (0 == strcmp(arg, "--core")) {
                if (core) {
                    lose("more than one core file specified\n");
                } else {
                    ++argi;
                    if (argi >= argc) {
                        lose("missing filename for --core argument\n");
                    }
                    core = copied_string(argv[argi]);
                    ++argi;
                }
            } else if (0 == strcmp(arg, "--help")) {
                /* I think this is the (or a) usual convention: upon
                 * seeing "--help" we immediately print our help
                 * string and exit, ignoring everything else. */
                print_help();
                exit(0);
            } else if (0 == strcmp(arg, "--version")) {
                /* As in "--help" case, I think this is expected. */
                print_version();
                exit(0);
            } else if (0 == strcmp(arg, "--dynamic-space-size")) {
                ++argi;
                if (argi >= argc)
                    lose("missing argument for --dynamic-space-size");
                errno = 0;
                dynamic_space_size = strtol(argv[argi++], 0, 0) << 20;
                if (errno)
                    lose("argument to --dynamic-space-size is not a number");
#               ifdef MAX_DYNAMIC_SPACE_END
                if (!((DYNAMIC_SPACE_START <
                       DYNAMIC_SPACE_START+dynamic_space_size) &&
                      (DYNAMIC_SPACE_START+dynamic_space_size <=
                       MAX_DYNAMIC_SPACE_END)))
                    lose("specified --dynamic-space-size too large");
#               endif
            } else if (0 == strcmp(arg, "--control-stack-size")) {
                ++argi;
                if (argi >= argc)
                    lose("missing argument for --control-stack-size");
                errno = 0;
                thread_control_stack_size = strtol(argv[argi++], 0, 0) << 20;
                if (errno)
                    lose("argument to --control-stack-size is not a number");
            } else if (0 == strcmp(arg, "--debug-environment")) {
                int n = 0;
                printf("; Commandline arguments:\n");
                while (n < argc) {
                    printf(";  %2d: \"%s\"\n", n, argv[n]);
                    ++n;
                }
                n = 0;
                printf(";\n; Environment:\n");
                while (ENVIRON[n]) {
                    printf(";  %2d: \"%s\"\n", n, ENVIRON[n]);
                    ++n;
                }
                ++argi;
            } else if (0 == strcmp(arg, "--disable-ldb")) {
                disable_lossage_handler_p = 1;
                ++argi;
            } else if (0 == strcmp(arg, "--lose-on-corruption")) {
                lose_on_corruption_p = 1;
                ++argi;
            } else if (0 == strcmp(arg, "--end-runtime-options")) {
                end_runtime_options = 1;
                ++argi;
                break;
            } else {
                /* This option was unrecognized as a runtime option,
                 * so it must be a toplevel option or a user option,
                 * so we must be past the end of the runtime option
                 * section. */
                break;
            }
        }
        /* This is where we strip out those options that we handle. We
         * also take this opportunity to make sure that we don't find
         * an out-of-place "--end-runtime-options" option. */
        {
            char *argi0 = argv[argi];
            int argj = 1;
            /* (argc - argi) for the arguments, one for the binary,
               and one for the terminating NULL. */
            sbcl_argv = successful_malloc((2 + argc - argi) * sizeof(char *));
            sbcl_argv[0] = argv[0];
            while (argi < argc) {
                char *arg = argv[argi++];
                /* If we encounter --end-runtime-options for the first
                 * time after the point where we had to give up on
                 * runtime options, then the point where we had to
                 * give up on runtime options must've been a user
                 * error. */
                if (!end_runtime_options &&
                    0 == strcmp(arg, "--end-runtime-options")) {
                    lose("bad runtime option \"%s\"\n", argi0);
                }
                sbcl_argv[argj++] = arg;
            }
            sbcl_argv[argj] = 0;
        }
    }

    /* Align down to multiple of page_table page size, and to the appropriate
     * stack alignment. */
    dynamic_space_size &= ~(PAGE_BYTES-1);
    thread_control_stack_size &= ~(CONTROL_STACK_ALIGNMENT_BYTES-1);

    /* Preserve the runtime options for possible future core saving */
    runtime_options->dynamic_space_size = dynamic_space_size;
    runtime_options->thread_control_stack_size = thread_control_stack_size;

    /* KLUDGE: os_vm_page_size is set by os_init(), and on some
     * systems (e.g. Alpha) arch_init() needs need os_vm_page_size, so
     * it must follow os_init(). -- WHN 2000-01-26 */
    os_init(argv, envp);
    arch_init();
    gc_init();
    validate();

    /* If no core file was specified, look for one. */
    if (!core) {
        core = search_for_core();
    }

    /* Make sure that SBCL_HOME is set and not the empty string,
       unless loading an embedded core. */
    if (!(sbcl_home && *sbcl_home) && embedded_core_offset == 0) {
        char *envstring, *copied_core, *dir;
        char *stem = "SBCL_HOME=";
        copied_core = copied_string(core);
        dir = dirname(copied_core);
        envstring = (char *) calloc(strlen(stem) +
                                    strlen(dir) +
                                    1,
                                    sizeof(char));
        sprintf(envstring, "%s%s", stem, dir);
        putenv(envstring);
        free(copied_core);
    }

    if (!noinform && embedded_core_offset == 0) {
        print_banner();
        fflush(stdout);
    }

#if defined(SVR4) || defined(__linux__)
    tzset();
#endif

    define_var("nil", NIL, 1);
    define_var("t", T, 1);

    if (!disable_lossage_handler_p)
        enable_lossage_handler();

    globals_init();

    initial_function = load_core_file(core, embedded_core_offset);
    if (initial_function == NIL) {
        lose("couldn't find initial function\n");
    }
#ifdef LISP_FEATURE_HPUX
    /* -1 = CLOSURE_FUN_OFFSET, 23 = SIMPLE_FUN_CODE_OFFSET, we are
     * not in LANGUAGE_ASSEMBLY so we cant reach them. */
    return_from_lisp_stub = (void *) ((char *)*((unsigned long *)
                 ((char *)initial_function + -1)) + 23);
#endif

    gc_initialize_pointers();

    arch_install_interrupt_handlers();
#ifndef LISP_FEATURE_WIN32
    os_install_interrupt_handlers();
#else
/*     wos_install_interrupt_handlers(handler); */
    wos_install_interrupt_handlers(&exception_frame);
#endif

    /* Pass core filename and the processed argv into Lisp. They'll
     * need to be processed further there, to do locale conversion.
     */
    core_string = core;
    posix_argv = sbcl_argv;

    FSHOW((stderr, "/funcalling initial_function=0x%lx\n",
          (unsigned long)initial_function));
#ifdef LISP_FEATURE_WIN32
    fprintf(stderr, "\n\
This is experimental prerelease support for the Windows platform: use\n\
at your own risk.  \"Your Kitten of Death awaits!\"\n");
    fflush(stdout);
    fflush(stderr);
#endif
    create_initial_thread(initial_function);
    lose("CATS.  CATS ARE NICE.\n");
    return 0;
}
コード例 #10
0
ファイル: v.c プロジェクト: BirchJD/advancemame-0.106.1-RPi
int os_main(int argc, char* argv[])
{
	adv_crtc_container selected;
	adv_crtc_container_iterator i;
	const char* opt_rc;
	adv_bool opt_log;
	adv_bool opt_logsync;
	int j;
	adv_error res;
	char* section_map[1];
	char buffer[1024];

	opt_rc = 0;
	opt_log = 0;
	opt_logsync = 0;
	the_advance = advance_mame;
	the_sound_flag = 1;

	the_config = conf_init();

	if (os_init(the_config)!=0) {
		target_err("Error initializing the OS support.\n");
		goto err_conf;
	}

	video_reg(the_config, 1);
	monitor_register(the_config);
	crtc_container_register(the_config);
	generate_interpolate_register(the_config);
	gtf_register(the_config);
	inputb_reg(the_config, 1);
	inputb_reg_driver_all(the_config);
	
	/* MSDOS requires a special driver sub set */
#ifndef __MSDOS__
	video_reg_driver_all(the_config);
#endif

	if (conf_input_args_load(the_config, 1, "", &argc, argv, error_callback, 0) != 0)
		goto err_os;

	for(j=1;j<argc;++j) {
		if (target_option_compare(argv[j], "rc") && j+1<argc) {
			opt_rc = argv[++j];
		} else if (target_option_compare(argv[j], "log")) {
			opt_log = 1;
		} else if (target_option_compare(argv[j], "logsync")) {
			opt_logsync = 1;
		} else if (target_option_compare(argv[j], "nosound")) {
			the_sound_flag = 0;
		} else if (target_option_compare(argv[j], "advmamev")) {
			the_advance = advance_mame;
		} else if (target_option_compare(argv[j], "advmessv")) {
			the_advance = advance_mess;
		} else if (target_option_compare(argv[j], "advpacv")) {
			the_advance = advance_pac;
		} else if (target_option_compare(argv[j], "advmenuv")) {
			the_advance = advance_menu;
#ifdef __MSDOS__
		} else if (target_option_compare(argv[j], "vgav")) {
			the_advance = advance_vga;
		} else if (target_option_compare(argv[j], "vbev")) {
			the_advance = advance_vbe;
#endif
#ifdef __WIN32__
		} else if (target_option_compare(argv[j], "videowv")) {
			the_advance = advance_videow;
#endif
		} else {
			target_err("Unknown option %s\n", argv[j]);
			goto err;
		}
	}

#ifdef __MSDOS__
	/* WARNING the MSDOS drivers are registered after the command line management. */
	/* It implyes that you cannot specify any driver options on the command line */
	msdos_rut();

	if (the_advance == advance_vga) {
		if (the_advance_vga_active) {
			target_err("The AdvanceVGA utility is active. Disable it before running vgav.\n");
			goto err;
		}
		video_reg_driver(the_config, &video_vgaline_driver);
	} else if (the_advance == advance_vbe) {
		if (the_advance_vbe_active) {
			target_err("The AdvanceVBE utility is active. Disable it before running vbev.\n");
			goto err;
		}
		video_reg_driver(the_config, &video_vbeline_driver);
		video_reg_driver(the_config, &video_vgaline_driver); /* for the text modes */
	} else {
		video_reg_driver_all(the_config);
	}
#endif

	if (!opt_rc) {
		switch (the_advance) {
			case advance_vbe : opt_rc = "vbe.rc"; break;
			case advance_vga : opt_rc = "vga.rc"; break;
			case advance_menu : opt_rc = file_config_file_home("advmenu.rc"); break;
			case advance_mame : opt_rc = file_config_file_home("advmame.rc"); break;
			case advance_mess : opt_rc = file_config_file_home("advmess.rc"); break;
			case advance_pac : opt_rc = file_config_file_home("advpac.rc"); break;
			case advance_videow : opt_rc = file_config_file_home("videow.rc"); break;
			default : opt_rc = "advv.rc"; break;
		}
	}

	if (access(opt_rc, R_OK)!=0) {
		target_err("Configuration file %s not found.\n", opt_rc);
		goto err_os;
	}

	if (conf_input_file_load_adv(the_config, 0, opt_rc, opt_rc, 1, 1, STANDARD, sizeof(STANDARD)/sizeof(STANDARD[0]), error_callback, 0) != 0)
		goto err_os;

	if (opt_log || opt_logsync) {
		const char* log = "advv.log";
		remove(log);
		log_init(log, opt_logsync);
        }

	log_std(("v: %s %s\n", __DATE__, __TIME__));

	section_map[0] = "";
	conf_section_set(the_config, section_map, 1);

	if (video_load(the_config, "") != 0) {
		target_err("Error loading the video options from the configuration file %s.\n", opt_rc);
		target_err("%s\n", error_get());
		goto err_os;
	}

	if (inputb_load(the_config) != 0) {
		target_err("%s\n", error_get());
		goto err_os;
	}

	/* NOTE: After this command all the target_err() string must */
	/* have \n\r at the end to ensure correct newline in graphics mode. */

	if (os_inner_init("AdvanceVIDEO") != 0) {
		goto err_os;
	}

	if (adv_video_init() != 0) {
		target_err("%s\n\r", error_get());
		troubleshotting();
		goto err_os_inner;
	}

	if (video_blit_init() != 0) {
		target_err("%s\n\r", error_get());
		goto err_video;
	}

	if (the_advance != advance_vbe && the_advance != advance_vga) {
		if ((video_mode_generate_driver_flags(VIDEO_DRIVER_FLAGS_MODE_GRAPH_MASK, 0) & VIDEO_DRIVER_FLAGS_PROGRAMMABLE_CLOCK) == 0) {
			target_err("No active video driver is able to program your video board.\n\r");
			troubleshotting();
			goto err_blit;
		}
	}

	if (inputb_init() != 0) {
		target_err("%s\n\r", error_get());
		goto err_blit;
	}

	if (monitor_load(the_config, &the_monitor) != 0) {
		target_err("Error loading the clock options from the configuration file %s.\n\r", opt_rc);
		target_err("%s\n\r", error_get());
		goto err_input;
	}

	monitor_print(buffer, sizeof(buffer), &the_monitor);
	log_std(("v: clock %s\n", buffer));

	/* load generate_linear config */
	res = generate_interpolate_load(the_config, &the_interpolate);
	if (res<0) {
		target_err("Error loading the format options from the configuration file %s.\n\r", opt_rc);
		target_err("%s\n\r", error_get());
		goto err_input;
	}
	if (res>0) {
		generate_default_vga(&the_interpolate.map[0].gen);
		the_interpolate.map[0].hclock = 31500;
		the_interpolate.mac = 1;
	}

	/* load generate_linear config */
	res = gtf_load(the_config, &the_gtf);
	if (res<0) {
		target_err("Error loading the gtf options from the configuration file %s.\n\r", opt_rc);
		target_err("%s\n\r", error_get());
		goto err_input;
	}
	if (res>0) {
		gtf_default_vga(&the_gtf);
	}

	/* all mode */
	crtc_container_init(&selected);

	/* insert modes */
	crtc_container_insert_default_all(&selected);

	/* sort */
	crtc_container_init(&the_modes);
	for(crtc_container_iterator_begin(&i, &selected);!crtc_container_iterator_is_end(&i);crtc_container_iterator_next(&i)) {
		adv_crtc* crtc = crtc_container_iterator_get(&i);
		crtc_container_insert_sort(&the_modes, crtc, crtc_compare);
	}
	crtc_container_done(&selected);

	/* load selected */
	crtc_container_init(&selected);

	if (crtc_container_load(the_config, &selected) != 0) {
		target_err("%s\n\r", error_get());
		goto err_input;
	}

	/* union set */
	for(crtc_container_iterator_begin(&i, &selected);!crtc_container_iterator_is_end(&i);crtc_container_iterator_next(&i)) {
		adv_crtc* crtc = crtc_container_iterator_get(&i);
		adv_bool has = crtc_container_has(&the_modes, crtc, crtc_compare) != 0;
		if (has)
			crtc_container_remove(&the_modes, crtc_select_by_compare, crtc);
		crtc->user_flags |= MODE_FLAGS_USER_BIT0;
		crtc_container_insert_sort(&the_modes, crtc, crtc_compare);
	}
	crtc_container_done(&selected);

	the_modes_modified = 0;

	if (text_init(&the_modes, &the_monitor) != 0) {
		goto err_input;
	}

	if (inputb_enable(0) != 0) {
		goto err_text;
	}

	sound_signal();

	menu_run();

	log_std(("v: shutdown\n"));

	inputb_disable();

	text_done();

	crtc_container_done(&the_modes);

	inputb_done();

	video_blit_done();

	adv_video_done();

	os_inner_done();

	log_std(("v: the end\n"));

	if (opt_log || opt_logsync) {
		log_done();
	}

	os_done();

	conf_save(the_config, 0, 0, error_callback, 0);

	conf_done(the_config);

	return EXIT_SUCCESS;

err_text:
	text_done();
err_input:
	inputb_done();
err_blit:
	video_blit_done();
err_video:
	adv_video_done();
err_os_inner:
	os_inner_done();
err_os:
	if (opt_log || opt_logsync) {
		log_done();
	}
	os_done();
err_conf:
	conf_done(the_config);
err:
	return EXIT_FAILURE;
}
コード例 #11
0
ファイル: main.c プロジェクト: GunioRobot/rtn56u
/**
 * Kick off the daap server and wait for events.
 *
 * This starts the initial db scan, sets up the signal
 * handling, starts the webserver, then sits back and waits
 * for events, as notified by the signal handler and the
 * web interface.  These events are communicated via flags
 * in the config structure.
 *
 * \param argc count of command line arguments
 * \param argv command line argument pointers
 * \returns 0 on success, -1 otherwise
 *
 * \todo split out a ws_init and ws_start, so that the
 * web space handlers can be registered before the webserver
 * starts.
 *
 */
int main(int argc, char *argv[]) {
    int option;
    char *configfile=CONFFILE;
    WSCONFIG ws_config;
    int reload=0;
    int start_time;
    int end_time;
    int rescan_counter=0;
    int old_song_count, song_count;
    int force_non_root=0;
    int skip_initial=1;
    int kill_server=0;
    int convert_conf=0;
    char *db_type,*db_parms,*web_root,*runas, *tmp;
    char **mp3_dir_array;
    char *servername, *iface;
    char *ffid = NULL;
    int appdir = 0;
    char *perr=NULL;
    char txtrecord[255];
    void *phandle;
    char *plugindir;

    int err;
    char *apppath;

    int debuglevel=0;
    int plugins_loaded = 0;

#ifdef ALPHA_CUSTOMIZE
    char *share_path;
    pthread_t thread1;
#endif

    config.use_mdns=1;
    err_setlevel(2);

    config.foreground=0;
    while((option=getopt(argc,argv,"D:d:c:P:mfrysiuvab:Vk")) != -1) {
        switch(option) {
        case 'a':
            appdir = 1;
            break;

        case 'b':
            ffid=optarg;
            break;

        case 'd':
            debuglevel = atoi(optarg);
            err_setlevel(debuglevel);
            break;

        case 'D':
            if(err_setdebugmask(optarg)) {
                usage(argv[0]);
                exit(EXIT_FAILURE);
            }
            break;

        case 'f':
            config.foreground=1;
            err_setdest(err_getdest() | LOGDEST_STDERR);
            break;

        case 'c':
            configfile=optarg;
            break;

        case 'm':
            config.use_mdns=0;
            break;

#ifndef WIN32
        case 'P':
            os_set_pidfile(optarg);
            break;
#endif
        case 'r':
            reload=1;
            break;

        case 's':
            skip_initial=0;
            break;

        case 'y':
            force_non_root=1;
            break;

#ifdef WIN32
        case 'i':
            os_register();
            exit(EXIT_SUCCESS);
            break;

        case 'u':
            os_unregister();
            exit(EXIT_SUCCESS);
            break;
#endif
        case 'v':
            convert_conf=1;
            break;

        case 'k':
            kill_server=1;
            break;

        case 'V':
            fprintf(stderr,"Firefly Media Server: Version %s\n",VERSION);
            exit(EXIT_SUCCESS);
            break;

        default:
            usage(argv[0]);
            exit(EXIT_FAILURE);
            break;
        }
    }

    if((getuid()) && (!force_non_root) && (!convert_conf)) {
        fprintf(stderr,"You are not root.  This is almost certainly wrong.  "
                "If you are\nsure you want to do this, use the -y "
                "command-line switch\n");
        exit(EXIT_FAILURE);
    }


    if(kill_server) {
        os_signal_server(S_STOP);
        exit(0);
    }

    io_init();
    io_set_errhandler(main_io_errhandler);
    ws_set_errhandler(main_ws_errhandler);

    /* read the configfile, if specified, otherwise
     * try defaults */
    config.stats.start_time=start_time=(int)time(NULL);
    config.stop=0;

    /* set appdir first, that way config resolves relative to appdir */
    if(appdir) {
        apppath = os_apppath(argv[0]);
        DPRINTF(E_INF,L_MAIN,"Changing cwd to %s\n",apppath);
        chdir(apppath);
        free(apppath);
        configfile="mt-daapd.conf";
    }

    if(CONF_E_SUCCESS != conf_read(configfile)) {
        fprintf(stderr,"Error reading config file (%s)\n",configfile);
        exit(EXIT_FAILURE);
    }

    if(debuglevel) /* was specified, should override the config file */
        err_setlevel(debuglevel);

    if(convert_conf) {
        fprintf(stderr,"Converting config file...\n");
        if(CONF_E_SUCCESS != conf_write()) {
            fprintf(stderr,"Error writing config file.\n");
            exit(EXIT_FAILURE);
        }
        exit(EXIT_SUCCESS);
    }

    DPRINTF(E_LOG,L_MAIN,"Firefly Version %s: Starting with debuglevel %d\n",
            VERSION,err_getlevel());


    /* load plugins before we drop privs?  Maybe... let the
     * plugins do stuff they might need to */
    plugin_init();
    if((plugindir=conf_alloc_string("plugins","plugin_dir",NULL)) != NULL) {
        /* instead of specifying plugins, let's walk through the directory
         * and load each of them */
        if(!load_plugin_dir(plugindir)) {
            DPRINTF(E_LOG,L_MAIN,"Warning: Could not load plugins\n");
        } else {
            plugins_loaded = TRUE;
        }
        free(plugindir);
    }

    if(!plugins_loaded) {
        if((!load_plugin_dir("/usr/lib/firefly/plugins")) &&
           (!load_plugin_dir("/usr/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/usr/local/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/usr/local/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("/opt/share/firefly/plugins")) &&
           (!load_plugin_dir("/opt/share/mt-daapd/plugins")) &&
           (!load_plugin_dir("/opt/lib/firefly/plugins")) &&
           (!load_plugin_dir("/opt/lib/mt-daapd/plugins")) &&
           (!load_plugin_dir("plugins/.libs"))) {
            DPRINTF(E_FATAL,L_MAIN,"plugins/plugin_dir not specified\n");
        }
    }

    phandle=NULL;
    while((phandle=plugin_enum(phandle))) {
        DPRINTF(E_LOG,L_MAIN,"Plugin loaded: %s\n",plugin_get_description(phandle));
    }

    runas = conf_alloc_string("general","runas","nobody");

#ifndef WITHOUT_MDNS
    if(config.use_mdns) {
        DPRINTF(E_LOG,L_MAIN,"Starting rendezvous daemon\n");
        if(rend_init(runas)) {
            DPRINTF(E_FATAL,L_MAIN|L_REND,"Error in rend_init: %s\n",
                    strerror(errno));
        }
    }
#endif

    if(!os_init(config.foreground,runas)) {
        DPRINTF(E_LOG,L_MAIN,"Could not initialize server\n");
        os_deinit();
        exit(EXIT_FAILURE);
    }

    free(runas);

#ifdef UPNP
    upnp_init();
#endif

    /* this will require that the db be readable by the runas user */
    db_type = conf_alloc_string("general","db_type","sqlite");
    db_parms = conf_alloc_string("general","db_parms","/var/cache/mt-daapd");
    err=db_open(&perr,db_type,db_parms);

    if(err) {
        DPRINTF(E_LOG,L_MAIN|L_DB,"Error opening db: %s\n",perr);
#ifndef WITHOUT_MDNS
        if(config.use_mdns) {
            rend_stop();
        }
#endif
        os_deinit();
        exit(EXIT_FAILURE);
    }

    free(db_type);
    free(db_parms);

    /* Initialize the database before starting */
    DPRINTF(E_LOG,L_MAIN|L_DB,"Initializing database\n");
    if(db_init(reload)) {
        DPRINTF(E_FATAL,L_MAIN|L_DB,"Error in db_init: %s\n",strerror(errno));
    }

    err=db_get_song_count(&perr,&song_count);
    if(err != DB_E_SUCCESS) {
        DPRINTF(E_FATAL,L_MISC,"Error getting song count: %s\n",perr);
    }
    /* do a full reload if the db is empty */
    if(!song_count)
        reload = 1;

    if(conf_get_array("general","mp3_dir",&mp3_dir_array)) {
        if((!skip_initial) || (reload)) {
            DPRINTF(E_LOG,L_MAIN|L_SCAN,"Starting mp3 scan\n");
	#ifdef ALPHA_CUSTOMIZE
	    share_path = conf_alloc_string("general", "mp3_dir", "AAA");
		printf("mp3_dir_array[0] = [%s]\n", mp3_dir_array[0]);
	    if (strlen(share_path) > 0)
	    {
		Cnt_total_file(mp3_dir_array[0]);
		pthread_create( &thread1, NULL, (void*)process_bar, NULL);
		free(share_path);
	    }
	#endif
            plugin_event_dispatch(PLUGIN_EVENT_FULLSCAN_START,0,NULL,0);
            start_time=(int) time(NULL);
            if(scan_init(mp3_dir_array)) {
                DPRINTF(E_LOG,L_MAIN|L_SCAN,"Error scanning MP3 files: %s\n",strerror(errno));
            }
            if(!config.stop) { /* don't send popup when shutting down */
                plugin_event_dispatch(PLUGIN_EVENT_FULLSCAN_END,0,NULL,0);
                err=db_get_song_count(&perr,&song_count);
                end_time=(int) time(NULL);
                DPRINTF(E_LOG,L_MAIN|L_SCAN,"Scanned %d songs in %d seconds\n",
                        song_count,end_time - start_time);
            }
        }
        conf_dispose_array(mp3_dir_array);
    }
    
#ifdef ALPHA_CUSTOMIZE
    thread_exit = 1;
#endif

    /* start up the web server */
    web_root = conf_alloc_string("general","web_root",NULL);
    ws_config.web_root=web_root;
    ws_config.port=conf_get_int("general","port",0);

    DPRINTF(E_LOG,L_MAIN|L_WS,"Starting web server from %s on port %d\n",
            ws_config.web_root, ws_config.port);

    config.server=ws_init(&ws_config);
    if(!config.server) {
        /* pthreads or malloc error */
        DPRINTF(E_FATAL,L_MAIN|L_WS,"Error initializing web server\n");
    }

    if(E_WS_SUCCESS != ws_start(config.server)) {
        /* listen or pthread error */
        DPRINTF(E_FATAL,L_MAIN|L_WS,"Error starting web server\n");
    }

    ws_registerhandler(config.server, "/",main_handler,main_auth,
                       0,1);

#ifndef WITHOUT_MDNS
    if(config.use_mdns) { /* register services */
        servername = conf_get_servername();

        memset(txtrecord,0,sizeof(txtrecord));
        txt_add(txtrecord,"txtvers=1");
        txt_add(txtrecord,"Database ID=%0X",util_djb_hash_str(servername));
        txt_add(txtrecord,"Machine ID=%0X",util_djb_hash_str(servername));
        txt_add(txtrecord,"Machine Name=%s",servername);
        txt_add(txtrecord,"mtd-version=" VERSION);
        txt_add(txtrecord,"iTSh Version=131073"); /* iTunes 6.0.4 */
        txt_add(txtrecord,"Version=196610");      /* iTunes 6.0.4 */
        tmp = conf_alloc_string("general","password",NULL);
        if(tmp && (strlen(tmp)==0)) tmp=NULL;

        txt_add(txtrecord,"Password=%s",tmp ? "true" : "false");
        if(tmp) free(tmp);

        srand((unsigned int)time(NULL));

        if(ffid) {
            txt_add(txtrecord,"ffid=%s",ffid);
        } else {
            txt_add(txtrecord,"ffid=%08x",rand());
        }

        DPRINTF(E_LOG,L_MAIN|L_REND,"Registering rendezvous names\n");
        iface = conf_alloc_string("general","interface","");

        rend_register(servername,"_http._tcp",ws_config.port,iface,txtrecord);

        plugin_rend_register(servername,ws_config.port,iface,txtrecord);

        free(servername);
        free(iface);
    }
#endif

    end_time=(int) time(NULL);

    err=db_get_song_count(&perr,&song_count);
    if(err != DB_E_SUCCESS) {
        DPRINTF(E_FATAL,L_MISC,"Error getting song count: %s\n",perr);
    }

    DPRINTF(E_LOG,L_MAIN,"Serving %d songs.  Startup complete in %d seconds\n",
            song_count,end_time-start_time);

    if(conf_get_int("general","rescan_interval",0) && (!reload) &&
       (!conf_get_int("scanning","skip_first",0)))
        config.reload = 1; /* force a reload on start */

    while(!config.stop) {
        if((conf_get_int("general","rescan_interval",0) &&
            (rescan_counter > conf_get_int("general","rescan_interval",0)))) {
            if((conf_get_int("general","always_scan",0)) ||
                (config_get_session_count())) {
                config.reload=1;
            } else {
                DPRINTF(E_DBG,L_MAIN|L_SCAN|L_DB,"Skipped bground scan... no users\n");
            }
            rescan_counter=0;
        }

        if(config.reload) {
            old_song_count = song_count;
            start_time=(int) time(NULL);

            DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Rescanning database\n");

            if(conf_get_array("general","mp3_dir",&mp3_dir_array)) {
                if(config.full_reload) {
                    config.full_reload=0;
                    db_force_rescan(NULL);
                }

                if(scan_init(mp3_dir_array)) {
                    DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Error rescanning... bad path?\n");
                }

                conf_dispose_array(mp3_dir_array);
            }
            config.reload=0;
            db_get_song_count(NULL,&song_count);
            DPRINTF(E_LOG,L_MAIN|L_DB|L_SCAN,"Scanned %d songs (was %d) in "
                    "%d seconds\n",song_count,old_song_count,
                    time(NULL)-start_time);
        }

        os_wait(MAIN_SLEEP_INTERVAL);
        rescan_counter += MAIN_SLEEP_INTERVAL;
    }

    DPRINTF(E_LOG,L_MAIN,"Stopping gracefully\n");

#ifndef WITHOUT_MDNS
    if(config.use_mdns) {
        DPRINTF(E_LOG,L_MAIN|L_REND,"Stopping rendezvous daemon\n");
        rend_stop();
    }
#endif

#ifdef UPNP
    upnp_deinit();
#endif


    /* Got to find a cleaner way to stop the web server.
     * Closing the fd of the socking accepting doesn't necessarily
     * cause the accept to fail on some libcs.
     *
    DPRINTF(E_LOG,L_MAIN|L_WS,"Stopping web server\n");
    ws_stop(config.server);
    */
    free(web_root);
    conf_close();

    DPRINTF(E_LOG,L_MAIN|L_DB,"Closing database\n");
    db_deinit();

    DPRINTF(E_LOG,L_MAIN,"Done!\n");

    os_deinit();
    io_deinit();
    mem_dump();
    return EXIT_SUCCESS;
}
コード例 #12
0
ファイル: snapraid.c プロジェクト: resnostyle/snapraid
int main(int argc, char* argv[])
{
	int c;
	struct snapraid_option opt;
	char conf[PATH_MAX];
	struct snapraid_state state;
	int operation;
	block_off_t blockstart;
	block_off_t blockcount;
	int ret;
	tommy_list filterlist_file;
	tommy_list filterlist_disk;
	int filter_missing;
	int filter_error;
	int plan;
	int olderthan;
	char* e;
	const char* command;
	const char* import_timestamp;
	const char* import_content;
	const char* log_file;
	int lock;
	const char* gen_conf;
	const char* run;
	int speedtest;
	int period;
	time_t t;
	struct tm* tm;
	int i;

	/* defaults */
	config(conf, sizeof(conf), argv[0]);
	memset(&opt, 0, sizeof(opt));
	opt.io_error_limit = 100;
	blockstart = 0;
	blockcount = 0;
	tommy_list_init(&filterlist_file);
	tommy_list_init(&filterlist_disk);
	period = 1000;
	filter_missing = 0;
	filter_error = 0;
	plan = SCRUB_AUTO;
	olderthan = SCRUB_AUTO;
	import_timestamp = 0;
	import_content = 0;
	log_file = 0;
	lock = 0;
	gen_conf = 0;
	speedtest = 0;
	run = 0;

	opterr = 0;
	while ((c =
#if HAVE_GETOPT_LONG
		getopt_long(argc, argv, OPTIONS, long_options, 0))
#else
		getopt(argc, argv, OPTIONS))
#endif
		!= EOF) {
		switch (c) {
		case 'c' :
			pathimport(conf, sizeof(conf), optarg);
			break;
		case 'f' : {
			struct snapraid_filter* filter = filter_alloc_file(1, optarg);
			if (!filter) {
				/* LCOV_EXCL_START */
				log_fatal("Invalid filter specification '%s'\n", optarg);
				log_fatal("Filters using relative paths are not supported. Ensure to add an initial slash\n");
				exit(EXIT_FAILURE);
				/* LCOV_EXCL_STOP */
			}
			tommy_list_insert_tail(&filterlist_file, &filter->node, filter);
		} break;
		case 'd' : {
			struct snapraid_filter* filter = filter_alloc_disk(1, optarg);
			if (!filter) {
				/* LCOV_EXCL_START */
				log_fatal("Invalid filter specification '%s'\n", optarg);
				exit(EXIT_FAILURE);
				/* LCOV_EXCL_STOP */
			}
			tommy_list_insert_tail(&filterlist_disk, &filter->node, filter);
		} break;
		case 'm' :
			filter_missing = 1;
			opt.expected_missing = 1;
			break;
		case 'e' :
			/* when processing only error, we filter both files and blocks */
			/* and we apply fixes only to synced ones */
			filter_error = 1;
			opt.badonly = 1;
			opt.syncedonly = 1;
			break;
		case 'p' :
			if (strcmp(optarg, "bad") == 0) {
				plan = SCRUB_BAD;
			} else if (strcmp(optarg, "new") == 0) {
				plan = SCRUB_NEW;
			} else if (strcmp(optarg, "full") == 0) {
				plan = SCRUB_FULL;
			} else {
				plan = strtoul(optarg, &e, 10);
				if (!e || *e || plan > 100) {
					/* LCOV_EXCL_START */
					log_fatal("Invalid plan/percentage '%s'\n", optarg);
					exit(EXIT_FAILURE);
					/* LCOV_EXCL_STOP */
				}
			}
			break;
		case 'o' :
			olderthan = strtoul(optarg, &e, 10);
			if (!e || *e || olderthan > 1000) {
				/* LCOV_EXCL_START */
				log_fatal("Invalid number of days '%s'\n", optarg);
				exit(EXIT_FAILURE);
				/* LCOV_EXCL_STOP */
			}
			break;
		case 'S' :
			blockstart = strtoul(optarg, &e, 0);
			if (!e || *e) {
				/* LCOV_EXCL_START */
				log_fatal("Invalid start position '%s'\n", optarg);
				exit(EXIT_FAILURE);
				/* LCOV_EXCL_STOP */
			}
			break;
		case 'B' :
			blockcount = strtoul(optarg, &e, 0);
			if (!e || *e) {
				/* LCOV_EXCL_START */
				log_fatal("Invalid count number '%s'\n", optarg);
				exit(EXIT_FAILURE);
				/* LCOV_EXCL_STOP */
			}
			break;
		case 'L' :
			opt.io_error_limit = strtoul(optarg, &e, 0);
			if (!e || *e) {
				/* LCOV_EXCL_START */
				log_fatal("Invalid error limit number '%s'\n", optarg);
				exit(EXIT_FAILURE);
				/* LCOV_EXCL_STOP */
			}
			break;
		case 'i' :
			if (import_timestamp) {
				/* LCOV_EXCL_START */
				log_fatal("Import directory '%s' already specified as '%s'\n", optarg, import_timestamp);
				exit(EXIT_FAILURE);
				/* LCOV_EXCL_STOP */
			}
			import_timestamp = optarg;
			break;
		case OPT_TEST_IMPORT_CONTENT :
			if (import_content) {
				/* LCOV_EXCL_START */
				log_fatal("Import directory '%s' already specified as '%s'\n", optarg, import_content);
				exit(EXIT_FAILURE);
				/* LCOV_EXCL_STOP */
			}
			import_content = optarg;
			break;
		case 'l' :
			if (log_file) {
				/* LCOV_EXCL_START */
				log_fatal("Log file '%s' already specified as '%s'\n", optarg, log_file);
				exit(EXIT_FAILURE);
				/* LCOV_EXCL_STOP */
			}
			log_file = optarg;
			break;
		case 'Z' :
			opt.force_zero = 1;
			break;
		case 'E' :
			opt.force_empty = 1;
			break;
		case 'U' :
			opt.force_uuid = 1;
			break;
		case 'D' :
			opt.force_device = 1;
			break;
		case 'N' :
			opt.force_nocopy = 1;
			break;
		case 'F' :
			opt.force_full = 1;
			break;
		case 'a' :
			opt.auditonly = 1;
			break;
		case 'h' :
			opt.prehash = 1;
			break;
		case 'v' :
			++msg_level;
			break;
		case 'q' :
			--msg_level;
			break;
		case 'G' :
			opt.gui = 1;
			break;
		case 'H' :
			usage();
			exit(EXIT_SUCCESS);
		case 'V' :
			version();
			exit(EXIT_SUCCESS);
		case 'T' :
			speedtest = 1;
			break;
		case 'C' :
			gen_conf = optarg;
			break;
		case OPT_TEST_KILL_AFTER_SYNC :
			opt.kill_after_sync = 1;
			break;
		case OPT_TEST_EXPECT_UNRECOVERABLE :
			opt.expect_unrecoverable = 1;
			break;
		case OPT_TEST_EXPECT_RECOVERABLE :
			opt.expect_recoverable = 1;
			break;
		case OPT_TEST_SKIP_SELF :
			opt.skip_self = 1;
			break;
		case OPT_TEST_SKIP_SIGN :
			opt.skip_sign = 1;
			break;
		case OPT_TEST_SKIP_FALLOCATE :
			opt.skip_fallocate = 1;
			break;
		case OPT_TEST_SKIP_SEQUENTIAL :
			opt.skip_sequential = 1;
			break;
		case OPT_TEST_SKIP_DEVICE :
			opt.skip_device = 1;
			period = 50; /* reduce period of the speed test */
			break;
		case OPT_TEST_SKIP_CONTENT_CHECK :
			opt.skip_content_check = 1;
			break;
		case OPT_TEST_SKIP_PARITY_ACCESS :
			opt.skip_parity_access = 1;
			break;
		case OPT_TEST_SKIP_DISK_ACCESS :
			opt.skip_disk_access = 1;
			break;
		case OPT_TEST_FORCE_MURMUR3 :
			opt.force_murmur3 = 1;
			break;
		case OPT_TEST_FORCE_SPOOKY2 :
			opt.force_spooky2 = 1;
			break;
		case OPT_TEST_SKIP_LOCK :
			opt.skip_lock = 1;
			break;
		case OPT_TEST_FORCE_ORDER_PHYSICAL :
			opt.force_order = SORT_PHYSICAL;
			break;
		case OPT_TEST_FORCE_ORDER_INODE :
			opt.force_order = SORT_INODE;
			break;
		case OPT_TEST_FORCE_ORDER_ALPHA :
			opt.force_order = SORT_ALPHA;
			break;
		case OPT_TEST_FORCE_ORDER_DIR :
			opt.force_order = SORT_DIR;
			break;
		case OPT_TEST_FORCE_SCRUB_AT :
			opt.force_scrub_at = atoi(optarg);
			break;
		case OPT_TEST_FORCE_SCRUB_EVEN :
			opt.force_scrub_even = 1;
			break;
		case OPT_TEST_FORCE_CONTENT_WRITE :
			opt.force_content_write = 1;
			break;
		case OPT_TEST_EXPECT_FAILURE :
			/* invert the exit codes */
			exit_success = 1;
			exit_failure = 0;
			break;
		case OPT_TEST_EXPECT_NEED_SYNC :
			/* invert the exit codes */
			exit_success = 1;
			exit_sync_needed = 0;
			break;
		case OPT_TEST_RUN :
			run = optarg;
			break;
		case OPT_TEST_FORCE_SCAN_WINFIND :
			opt.force_scan_winfind = 1;
			break;
		case OPT_TEST_FORCE_PROGRESS :
			opt.force_progress = 1;
			break;
		case OPT_TEST_FORCE_AUTOSAVE_AT :
			opt.force_autosave_at = atoi(optarg);
			break;
		case OPT_TEST_FAKE_DEVICE :
			opt.fake_device = 1;
			break;
		case OPT_NO_WARNINGS :
			opt.no_warnings = 1;
			break;
		default :
			/* LCOV_EXCL_START */
			log_fatal("Unknown option '%c'\n", (char)c);
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	}

	os_init(opt.force_scan_winfind);
	raid_init();
	crc32c_init();

	if (speedtest != 0) {
		speed(period);
		os_done();
		exit(EXIT_SUCCESS);
	}

	if (gen_conf != 0) {
		generate_configuration(gen_conf);
		os_done();
		exit(EXIT_SUCCESS);
	}

	if (optind + 1 != argc) {
		/* LCOV_EXCL_START */
		usage();
		exit(EXIT_FAILURE);
		/* LCOV_EXCL_STOP */
	}

	command = argv[optind];
	if (strcmp(command, "diff") == 0) {
		operation = OPERATION_DIFF;
	} else if (strcmp(argv[optind], "sync") == 0) {
		operation = OPERATION_SYNC;
	} else if (strcmp(argv[optind], "check") == 0) {
		operation = OPERATION_CHECK;
	} else if (strcmp(argv[optind], "fix") == 0) {
		operation = OPERATION_FIX;
	} else if (strcmp(argv[optind], "test-dry") == 0) {
		operation = OPERATION_DRY;
	} else if (strcmp(argv[optind], "dup") == 0) {
		operation = OPERATION_DUP;
	} else if (strcmp(argv[optind], "list") == 0) {
		operation = OPERATION_LIST;
	} else if (strcmp(argv[optind], "pool") == 0) {
		operation = OPERATION_POOL;
	} else if (strcmp(argv[optind], "rehash") == 0) {
		operation = OPERATION_REHASH;
	} else if (strcmp(argv[optind], "scrub") == 0) {
		operation = OPERATION_SCRUB;
	} else if (strcmp(argv[optind], "status") == 0) {
		operation = OPERATION_STATUS;
	} else if (strcmp(argv[optind], "test-rewrite") == 0) {
		operation = OPERATION_REWRITE;
	} else if (strcmp(argv[optind], "test-read") == 0) {
		operation = OPERATION_READ;
	} else if (strcmp(argv[optind], "test-nano") == 0) {
		operation = OPERATION_NANO;
	} else if (strcmp(argv[optind], "up") == 0) {
		operation = OPERATION_SPINUP;
	} else if (strcmp(argv[optind], "down") == 0) {
		operation = OPERATION_SPINDOWN;
	} else if (strcmp(argv[optind], "devices") == 0) {
		operation = OPERATION_DEVICES;
	} else if (strcmp(argv[optind], "smart") == 0) {
		operation = OPERATION_SMART;
	} else {
		/* LCOV_EXCL_START */
		log_fatal("Unknown command '%s'\n", argv[optind]);
		exit(EXIT_FAILURE);
		/* LCOV_EXCL_STOP */
	}

	/* check options compatibility */
	switch (operation) {
	case OPERATION_CHECK :
		break;
	default :
		if (opt.auditonly) {
			/* LCOV_EXCL_START */
			log_fatal("You cannot use -a, --audit-only with the '%s' command\n", command);
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	}

	switch (operation) {
	case OPERATION_FIX :
		break;
	default :
		if (opt.force_device) {
			/* LCOV_EXCL_START */
			log_fatal("You cannot use -D, --force-device with the '%s' command\n", command);
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	}

	switch (operation) {
	case OPERATION_SYNC :
	case OPERATION_CHECK :
	case OPERATION_FIX :
		break;
	default :
		if (opt.force_nocopy) {
			/* LCOV_EXCL_START */
			log_fatal("You cannot use -N, --force-nocopy with the '%s' command\n", command);
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	}

	switch (operation) {
	case OPERATION_SYNC :
		break;
	default :
		if (opt.prehash) {
			/* LCOV_EXCL_START */
			log_fatal("You cannot use -h, --pre-hash with the '%s' command\n", command);
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}

		if (opt.force_full) {
			/* LCOV_EXCL_START */
			log_fatal("You cannot use -F, --force-full with the '%s' command\n", command);
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	}

	if (opt.force_full && opt.force_nocopy) {
		/* LCOV_EXCL_START */
		log_fatal("You cannot use the -F, --force-full and -N, --force-nocopy options at the same time\n");
		exit(EXIT_FAILURE);
		/* LCOV_EXCL_STOP */
	}

	if (opt.prehash && opt.force_nocopy) {
		/* LCOV_EXCL_START */
		log_fatal("You cannot use the -h, --pre-hash and -N, --force-nocopy options at the same time\n");
		exit(EXIT_FAILURE);
		/* LCOV_EXCL_STOP */
	}

	switch (operation) {
	case OPERATION_CHECK :
	case OPERATION_FIX :
	case OPERATION_DRY :
		break;
	default :
		if (!tommy_list_empty(&filterlist_file)) {
			/* LCOV_EXCL_START */
			log_fatal("You cannot use -f, --filter with the '%s' command\n", command);
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
		if (!tommy_list_empty(&filterlist_disk)) {
			/* LCOV_EXCL_START */
			log_fatal("You cannot use -d, --filter-disk with the '%s' command\n", command);
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
		if (filter_missing != 0) {
			/* LCOV_EXCL_START */
			log_fatal("You cannot use -m, --filter-missing with the '%s' command\n", command);
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
		if (filter_error != 0) {
			/* LCOV_EXCL_START */
			log_fatal("You cannot use -e, --filter-error with the '%s' command\n", command);
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	}

	/* errors must be always fixed on all disks */
	/* becasue we don't keep the information on what disk is the error */
	if (filter_error != 0 && !tommy_list_empty(&filterlist_disk)) {
		/* LCOV_EXCL_START */
		log_fatal("You cannot use -e, --filter-error and -d, --filter-disk at the same time\n");
		exit(EXIT_FAILURE);
		/* LCOV_EXCL_STOP */
	}

	switch (operation) {
	case OPERATION_CHECK :
	case OPERATION_FIX :
		break;
	default :
		if (import_timestamp != 0 || import_content != 0) {
			/* LCOV_EXCL_START */
			log_fatal("You cannot import with the '%s' command\n", command);
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	}

	switch (operation) {
	case OPERATION_LIST :
	case OPERATION_DUP :
	case OPERATION_STATUS :
	case OPERATION_REWRITE :
	case OPERATION_READ :
	case OPERATION_REHASH :
	case OPERATION_SPINUP : /* we want to do it in different threads to avoid blocking */
		/* avoid to check and access data disks if not needed */
		opt.skip_disk_access = 1;
		break;
	}

	switch (operation) {
	case OPERATION_DIFF :
	case OPERATION_LIST :
	case OPERATION_DUP :
	case OPERATION_POOL :
	case OPERATION_STATUS :
	case OPERATION_REWRITE :
	case OPERATION_READ :
	case OPERATION_REHASH :
	case OPERATION_NANO :
	case OPERATION_SPINUP : /* we want to do it in different threads to avoid blocking */
		/* avoid to check and access parity disks if not needed */
		opt.skip_parity_access = 1;
		break;
	}

	switch (operation) {
	case OPERATION_FIX :
	case OPERATION_CHECK :
		/* avoid to stop processing if a content file is not accessible */
		opt.skip_content_access = 1;
		break;
	}

	switch (operation) {
	case OPERATION_DIFF :
	case OPERATION_LIST :
	case OPERATION_DUP :
	case OPERATION_POOL :
	case OPERATION_NANO :
	case OPERATION_SPINUP :
	case OPERATION_SPINDOWN :
	case OPERATION_DEVICES :
	case OPERATION_SMART :
		opt.skip_self = 1;
		break;
	}

	switch (operation) {
	case OPERATION_DEVICES :
	case OPERATION_SMART :
		/* we may need to use these commands during operations */
		opt.skip_lock = 1;
		break;
	}

	/* open the log file */
	log_open(log_file);

	/* print generic info into the log */
	t = time(0);
	tm = localtime(&t);
	log_tag("version:%s\n", PACKAGE_VERSION);
	log_tag("unixtime:%" PRIi64 "\n", (int64_t)t);
	if (tm) {
		char datetime[64];
		strftime(datetime, sizeof(datetime), "%Y-%m-%d %H:%M:%S", tm);
		log_tag("time:%s\n", datetime);
	}
	log_tag("command:%s\n", command);
	for (i = 0; i < argc; ++i)
		log_tag("argv:%u:%s\n", i, argv[i]);
	log_flush();

	if (!opt.skip_self)
		selftest();

	state_init(&state);

	/* read the configuration file */
	state_config(&state, conf, command, &opt, &filterlist_disk);

	/* set the raid mode */
	raid_mode(state.raid_mode);

#if HAVE_LOCKFILE
	/* create the lock file */
	if (!opt.skip_lock && state.lockfile[0]) {
		lock = lock_lock(state.lockfile);
		if (lock == -1) {
			/* LCOV_EXCL_START */
			if (errno != EWOULDBLOCK) {
				log_fatal("Error creating the lock file '%s'. %s.\n", state.lockfile, strerror(errno));
			} else {
				log_fatal("The lock file '%s' is already locked!\n", state.lockfile);
				log_fatal("SnapRAID is already in use!\n");
			}
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	}
#else
	(void)lock;
#endif

	if (operation == OPERATION_DIFF) {
		state_read(&state);

		ret = state_diff(&state);

		/* abort if sync needed */
		if (ret > 0)
			exit(EXIT_SYNC_NEEDED);
	} else if (operation == OPERATION_SYNC) {

		/* in the next state read ensures to clear all the past hashes in case */
		/* we are reading from an incomplete sync */
		/* The undeterminated hash are only for CHG/DELETED blocks for which we don't */
		/* know if the previous interrupted sync was able to update or not the parity. */
		/* The sync process instead needs to trust this information because it's used */
		/* to avoid to recompute the parity if all the input are equals as before. */

		/* In these cases we don't know if the old state is still the one */
		/* stored inside the parity, because after an aborted sync, the parity */
		/* may be or may be not have been updated with the data that may be now */
		/* deleted. Then we reset the hash to a bogus value. */

		/* An example for CHG blocks is: */
		/* - One file is added creating a CHG block with ZERO state */
		/* - Sync aborted after updating the parity to the new state, */
		/*   but without saving the content file representing this new BLK state. */
		/* - File is now deleted after the aborted sync */
		/* - Sync again, deleting the blocks overt the CHG ones */
		/*   with the hash of CHG blocks not represeting the real parity state */

		/* An example for DELETED blocks is: */
		/* - One file is deleted creating DELETED blocks */
		/* - Sync aborted after, updating the parity to the new state, */
		/*   but without saving the content file representing this new EMPTY state. */
		/* - Another file is added again over the DELETE ones */
		/*   with the hash of DELETED blocks not represeting the real parity state */
		state.clear_past_hash = 1;

		state_read(&state);

		state_scan(&state);

		/* refresh the size info before the content write */
		state_refresh(&state);

		memory();

		/* intercept signals while operating */
		signal_init();

		/* save the new state before the sync */
		/* this allow to recover the case of the changes in the array after an aborted sync. */

		/* for example, think at this case: */
		/* - add some files at the array */
		/* - run a sync command, it will recompute the parity adding the new files */
		/* - abort the sync command before it stores the new content file */
		/* - delete the not yet synced files from the array */
		/* - run a new sync command */

		/* the new sync command has now way to know that the parity file was modified */
		/* because the files triggering these changes are now deleted */
		/* and they aren't listed in the content file */

		if (state.need_write)
			state_write(&state);

		/* run a test command if required */
		if (run != 0) {
			ret = system(run); /* ignore error */
			if (ret != 0) {
				/* LCOV_EXCL_START */
				log_fatal("Error in running command '%s'.\n", run);
				exit(EXIT_FAILURE);
				/* LCOV_EXCL_STOP */
			}
		}

		/* waits some time to ensure that any concurrent modification done at the files, */
		/* using the same mtime read by the scan process, will be read by sync. */
		/* Note that any later modification done, potentially not read by sync, will have */
		/* a different mtime, and it will be syncronized at the next sync. */
		/* The worst case is the FAT filesystem with a two seconds resolution for mtime. */
		/* If you don't use FAT, the wait is not needed, because most filesystems have now */
		/* at least microseconds resolution, but better to be safe. */
		if (!opt.skip_self)
			sleep(2);

		ret = state_sync(&state, blockstart, blockcount);

		/* save the new state if required */
		if (!opt.kill_after_sync && (state.need_write || state.opt.force_content_write))
			state_write(&state);

		/* abort if required */
		if (ret != 0) {
			/* LCOV_EXCL_START */
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	} else if (operation == OPERATION_DRY) {
		state_read(&state);

		/* filter */
		state_skip(&state);
		state_filter(&state, &filterlist_file, &filterlist_disk, filter_missing, filter_error);

		memory();

		/* intercept signals while operating */
		signal_init();

		state_dry(&state, blockstart, blockcount);
	} else if (operation == OPERATION_REHASH) {
		state_read(&state);

		/* intercept signals while operating */
		signal_init();

		state_rehash(&state);

		/* save the new state if required */
		if (state.need_write)
			state_write(&state);
	} else if (operation == OPERATION_SCRUB) {
		state_read(&state);

		memory();

		/* intercept signals while operating */
		signal_init();

		ret = state_scrub(&state, plan, olderthan);

		/* save the new state if required */
		if (state.need_write || state.opt.force_content_write)
			state_write(&state);

		/* abort if required */
		if (ret != 0) {
			/* LCOV_EXCL_START */
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	} else if (operation == OPERATION_REWRITE) {
		state_read(&state);

		/* intercept signals while operating */
		signal_init();

		state_write(&state);

		memory();
	} else if (operation == OPERATION_READ) {
		state_read(&state);

		memory();
	} else if (operation == OPERATION_NANO) {
		state_read(&state);

		state_nano(&state);

		/* intercept signals while operating */
		signal_init();

		state_write(&state);

		memory();
	} else if (operation == OPERATION_SPINUP) {
		state_device(&state, DEVICE_UP);
	} else if (operation == OPERATION_SPINDOWN) {
		state_device(&state, DEVICE_DOWN);
	} else if (operation == OPERATION_DEVICES) {
		state_device(&state, DEVICE_LIST);
	} else if (operation == OPERATION_SMART) {
		state_device(&state, DEVICE_SMART);
	} else if (operation == OPERATION_STATUS) {
		state_read(&state);

		memory();

		state_status(&state);
	} else if (operation == OPERATION_DUP) {
		state_read(&state);

		state_dup(&state);
	} else if (operation == OPERATION_LIST) {
		state_read(&state);

		state_list(&state);
	} else if (operation == OPERATION_POOL) {
		state_read(&state);

		state_pool(&state);
	} else {
		state_read(&state);

		/* if we are also trying to recover */
		if (!state.opt.auditonly) {
			/* import the user specified dirs */
			if (import_timestamp != 0)
				state_search(&state, import_timestamp);
			if (import_content != 0)
				state_import(&state, import_content);

			/* import from all the array */
			if (!state.opt.force_nocopy)
				state_search_array(&state);
		}

		/* filter */
		state_skip(&state);
		state_filter(&state, &filterlist_file, &filterlist_disk, filter_missing, filter_error);

		memory();

		/* intercept signals while operating */
		signal_init();

		if (operation == OPERATION_CHECK) {
			ret = state_check(&state, 0, blockstart, blockcount);
		} else { /* it's fix */
			ret = state_check(&state, 1, blockstart, blockcount);
		}

		/* abort if required */
		if (ret != 0) {
			/* LCOV_EXCL_START */
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	}

	/* close log file */
	log_close(log_file);

#if HAVE_LOCKFILE
	if (!opt.skip_lock && state.lockfile[0]) {
		if (lock_unlock(lock) == -1) {
			/* LCOV_EXCL_START */
			log_fatal("Error closing the lock file '%s'. %s.\n", state.lockfile, strerror(errno));
			exit(EXIT_FAILURE);
			/* LCOV_EXCL_STOP */
		}
	}
#endif

	state_done(&state);
	tommy_list_foreach(&filterlist_file, (tommy_foreach_func*)filter_free);
	tommy_list_foreach(&filterlist_disk, (tommy_foreach_func*)filter_free);

	os_done();

	return EXIT_SUCCESS;
}
コード例 #13
0
ファイル: j.c プロジェクト: robmcmullen/advancemame
int os_main(int argc, char* argv[])
{
	int i;
	adv_conf* context;
	const char* section_map[1];
	adv_bool opt_log;
	adv_bool opt_logsync;

	opt_log = 0;
	opt_logsync = 0;

	context = conf_init();

	if (os_init(context) != 0)
		goto err_conf;

	joystickb_reg(context, 1);
	joystickb_reg_driver_all(context);

	if (conf_input_args_load(context, 0, "", &argc, argv, error_callback, 0) != 0)
		goto err_os;

	for (i = 1; i < argc; ++i) {
		if (target_option_compare(argv[i], "log")) {
			opt_log = 1;
		} else if (target_option_compare(argv[i], "logsync")) {
			opt_logsync = 1;
		} else {
			fprintf(stderr, "Unknown argument '%s'\n", argv[1]);
			goto err_os;
		}
	}

	if (opt_log || opt_logsync) {
		const char* log = "advj.log";
		remove(log);
		log_init(log, opt_logsync);
	}

	log_std(("j: %s %s %s %s\n", "AdvanceJOYSTICK", ADV_VERSION, __DATE__, __TIME__));

	section_map[0] = "";
	conf_section_set(context, section_map, 1);

	if (joystickb_load(context) != 0)
		goto err_os;

	if (os_inner_init("AdvanceJOYSTICK") != 0)
		goto err_os;

	if (joystickb_init() != 0) {
		target_err("%s\n", error_get());
		goto err_os_inner;
	}

	probe();
	calibrate();
	run();

	joystickb_done();
	os_inner_done();

	log_std(("j: the end\n"));

	if (opt_log || opt_logsync) {
		log_done();
	}

	os_done();
	conf_done(context);

	return EXIT_SUCCESS;

err_os_inner:
	os_inner_done();
	log_done();
err_os:
	os_done();
err_conf:
	conf_done(context);
	return EXIT_FAILURE;
}
コード例 #14
0
ファイル: iaxclient_lib.c プロジェクト: Garalv/miumiu
EXPORT int iaxc_initialize(int num_calls)
{
	int i;
	int port;

	os_init();

	setup_jb_output();

	MUTEXINIT(&iaxc_lock);
	MUTEXINIT(&event_queue_lock);

	iaxc_set_audio_prefs(0);

	if ( iaxc_recvfrom != (iaxc_recvfrom_t)recvfrom )
		iax_set_networking(iaxc_sendto, iaxc_recvfrom);

	/* Note that iax_init() only sets up the receive port when the
	 * sendto/recvfrom functions have not been replaced. We need
	 * to call iaxc_init in either case because there is other
	 * initialization beyond the socket setup that needs to be done.
	 */
	if ( (port = iax_init(source_udp_port)) < 0 )
	{
		iaxci_usermsg(IAXC_ERROR,
				"Fatal error: failed to initialize iax with port %d",
				port);
		return -1;
	}

	if ( iaxc_recvfrom == (iaxc_recvfrom_t)recvfrom )
		iaxci_bound_port = port;
	else
		iaxci_bound_port = -1;

	/* tweak the jitterbuffer settings */
	iax_set_jb_target_extra( jb_target_extra );

	max_calls = num_calls;
	/* initialize calls */
	if ( max_calls <= 0 )
		max_calls = 1; /* 0 == Default? */

	/* calloc zeroes for us */
	calls = (struct iaxc_call *)calloc(sizeof(struct iaxc_call), max_calls);
	if ( !calls )
	{
		iaxci_usermsg(IAXC_ERROR, "Fatal error: can't allocate memory");
		return -1;
	}

	selected_call = -1;

	for ( i = 0; i < max_calls; i++ )
	{
		strncpy(calls[i].callerid_name,   DEFAULT_CALLERID_NAME,   IAXC_EVENT_BUFSIZ);
		strncpy(calls[i].callerid_number, DEFAULT_CALLERID_NUMBER, IAXC_EVENT_BUFSIZ);
	}

	if ( !test_mode )
	{
#ifndef AUDIO_ALSA
		if ( pa_initialize(&audio_driver, 8000) )
		{
			iaxci_usermsg(IAXC_ERROR, "failed pa_initialize");
			return -1;
		}
#else
		/* TODO: It is unknown whether this stuff for direct access to
		* alsa should be left in iaxclient. We're leaving it in here for
		* the time being, but unless it becomes clear that someone cares
		* about having it, it will be removed. Also note that portaudio
		* is capable of using alsa. This is another reason why this
		* direct alsa access may be unneeded.
		*/
		if ( alsa_initialize(&audio_driver, 8000) )
			return -1;
#endif
	}
#ifdef USE_VIDEO
	if ( video_initialize() )
		iaxci_usermsg(IAXC_ERROR,
				"iaxc_initialize: cannot initialize video!\n");
#endif

	/* Default audio format capabilities */
	audio_format_capability =
	    IAXC_FORMAT_ULAW |
	    IAXC_FORMAT_ALAW |
#ifdef CODEC_GSM
	    IAXC_FORMAT_GSM |
#endif
	    IAXC_FORMAT_SPEEX;
	audio_format_preferred = IAXC_FORMAT_SPEEX;

	return 0;
}
コード例 #15
0
overlapSet *os_dup(overlapSet *os) {
    int i;
    overlapSet *os2 = os_init(os->tree);
    for(i=0; i<os->l; i++) os_push(os2, os->overlaps[i]);
    return os2;
}
コード例 #16
0
ファイル: iaxclient_lib.c プロジェクト: ACSPRI/iaxclient-1
EXPORT int iaxc_initialize(int num_calls)
{
    printf("ESTOY IAXC 0\n");
	int i;
	int port;

	os_init();

	setup_jb_output();

	MUTEXINIT(&iaxc_lock);
	MUTEXINIT(&event_queue_lock);

	iaxc_set_audio_prefs(0);

	if ( iaxc_recvfrom != (iaxc_recvfrom_t)recvfrom )
		iax_set_networking(iaxc_sendto, iaxc_recvfrom);

	/* Note that iax_init() only sets up the receive port when the
	 * sendto/recvfrom functions have not been replaced. We need
	 * to call iaxc_init in either case because there is other
	 * initialization beyond the socket setup that needs to be done.
	 */
	if ( (port = iax_init(source_udp_port)) < 0 )
	{
		iaxci_usermsg(IAXC_ERROR,
				"Fatal error: failed to initialize iax with port %d",
				port);
		return -1;
	}

	if ( iaxc_recvfrom == (iaxc_recvfrom_t)recvfrom )
		iaxci_bound_port = port;
	else
		iaxci_bound_port = -1;

	/* tweak the jitterbuffer settings */
	iax_set_jb_target_extra( jb_target_extra );

	max_calls = num_calls;
	/* initialize calls */
	if ( max_calls <= 0 )
		max_calls = 1; /* 0 == Default? */

	/* calloc zeroes for us */
	calls = (struct iaxc_call *)calloc(sizeof(struct iaxc_call), max_calls);
	if ( !calls )
	{
		iaxci_usermsg(IAXC_ERROR, "Fatal error: can't allocate memory");
		return -1;
	}

	selected_call = -1;

	for ( i = 0; i < max_calls; i++ )
	{
		strncpy(calls[i].callerid_name,   DEFAULT_CALLERID_NAME,   IAXC_EVENT_BUFSIZ);
		strncpy(calls[i].callerid_number, DEFAULT_CALLERID_NUMBER, IAXC_EVENT_BUFSIZ);
	}
    printf("ESTOY IAXC\n");

    if ( alsa_initialize(&audio_driver, 8000) )
    {
        iaxci_usermsg(IAXC_ERROR, "failed alsa_initialize");
        return -1;
    }
#ifdef USE_VIDEO
	if ( video_initialize() )
		iaxci_usermsg(IAXC_ERROR,
				"iaxc_initialize: cannot initialize video!\n");
#endif

	/* Default audio format capabilities */
	audio_format_capability =
	    IAXC_FORMAT_ULAW |
	    IAXC_FORMAT_ALAW |
#ifdef CODEC_GSM
	    IAXC_FORMAT_GSM |
#endif
	    IAXC_FORMAT_SPEEX;
	audio_format_preferred = IAXC_FORMAT_SPEEX;

	return 0;
}
コード例 #17
0
ファイル: BOOT.C プロジェクト: polaco1782/ultrahle
void boot_boot(void)
{
    int a;

    // memory init (Must do before cpuinit!)
    mem_init(RDRAMSIZE);

    // cpu/compiler init
    cpu_init();

    // os emulator structures
    os_init();

    // map cart into memory (read only)
    for(a=0;a<cart.size;a+=4096)
    {
        mem_mapexternal(0x10000000+a,MAP_R,cart.data+a);
        mem_mapexternal(0x90000000+a,MAP_R,cart.data+a);
        mem_mapexternal(0xb0000000+a,MAP_R,cart.data+a);
    }

    // copy pif rom
#ifdef PIFROM
    memcpy(RPIF,pifRomImage,0x7c0);
    memcpy(WPIF,pifRomImage,0x7c0);
#endif

    cart.codebase=mem_read32(0x10000008);
    cart.codesize=0x100000; // guess, always same?

    if(cart.codesize>4096*1024)
    {
        print("error: codeblock too large");
        return;
    }

    if(mem_read32(0x10000540)!=0) cart.bootloader=1;

    if(cart.bootloader==1)
    {
        print("Alternate boot loader. ");
        cart.codebase&=~0x300000; // fzero
    }

    if(0)
    { // RealBoot
        mem_writerangeraw(0xa4000000,4096,cart.data);
        cpu_goto(0xa4000000);
    }
    else
    { // C-Boot
        mem_writerangeraw(cart.codebase,cart.codesize,cart.data+0x1000);
        sym_load(cart.symname);
        cpu_goto(cart.codebase);
    }

    st.framesync=cart.framesync;

    view.codebase=cart.codebase;
    view_changed(VIEW_CODE);
}