Пример #1
0
int *
init_server(struct Config *c) {
    config = c;

    signal(SIGINT, sig_handler);
    signal(SIGTERM, sig_handler);
    signal(SIGHUP, sig_handler);
    signal(SIGUSR1, sig_handler);
    /* ignore SIGPIPE, or it will kill us */
    signal(SIGPIPE, SIG_IGN);

    init_tables(&config->tables);

    return init_listeners(&config->listeners, &config->tables);
}
Пример #2
0
int
main(int argc, char **argv) {
    const char *config_file = "/etc/sniproxy.conf";
    int background_flag = 1;
    int max_nofiles = 65536;
    int opt;

    while ((opt = getopt(argc, argv, "fc:n:V")) != -1) {
        switch (opt) {
            case 'c':
                config_file = optarg;
                break;
            case 'f': /* foreground */
                background_flag = 0;
                break;
            case 'n':
                max_nofiles = atoi(optarg);
                break;
            case 'V':
                printf("sniproxy %s\n", sniproxy_version);
#ifdef HAVE_LIBUDNS
                printf("compiled with udns support\n");
#endif
                return EXIT_SUCCESS;
            default:
                usage();
                return EXIT_FAILURE;
        }
    }

    config = init_config(config_file, EV_DEFAULT);
    if (config == NULL) {
        fprintf(stderr, "Unable to load %s\n", config_file);
        usage();
        return EXIT_FAILURE;
    }

    /* ignore SIGPIPE, or it will kill us */
    signal(SIGPIPE, SIG_IGN);

    if (background_flag) {
        if (config->pidfile != NULL)
            remove(config->pidfile);

        daemonize();


        if (config->pidfile != NULL)
            write_pidfile(config->pidfile, getpid());
    }

    start_binder();

    set_limits(max_nofiles);

    init_listeners(&config->listeners, &config->tables, EV_DEFAULT);

    /* Drop permissions only when we can */
    drop_perms(config->user ? config->user : default_username);

    ev_signal_init(&sighup_watcher, signal_cb, SIGHUP);
    ev_signal_init(&sigusr1_watcher, signal_cb, SIGUSR1);
    ev_signal_init(&sigusr2_watcher, signal_cb, SIGUSR2);
    ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
    ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
    ev_signal_start(EV_DEFAULT, &sighup_watcher);
    ev_signal_start(EV_DEFAULT, &sigusr1_watcher);
    ev_signal_start(EV_DEFAULT, &sigusr2_watcher);
    ev_signal_start(EV_DEFAULT, &sigint_watcher);
    ev_signal_start(EV_DEFAULT, &sigterm_watcher);

    resolv_init(EV_DEFAULT, config->resolver.nameservers,
            config->resolver.search, config->resolver.mode);

    init_connections();

    ev_run(EV_DEFAULT, 0);

    free_connections(EV_DEFAULT);
    resolv_shutdown(EV_DEFAULT);

    free_config(config, EV_DEFAULT);

    stop_binder();

    return 0;
}
Пример #3
0
static void process_options(int ac, char *av[])
{
    ac-=ac>0; av+=ac>0;
    option::Stats stats(usage, ac, av);
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wvla"
    option::Option options[stats.options_max], buffer[stats.buffer_max];
#pragma GCC diagnostic pop
    option::Parser parse(usage, ac, av, options, buffer);
#else
    auto options = std::make_unique<option::Option[]>(stats.options_max);
    auto buffer = std::make_unique<option::Option[]>(stats.buffer_max);
    option::Parser parse(usage, ac, av, options.get(), buffer.get());
#endif
    if (parse.error())
        std::exit(EXIT_FAILURE);
    if (options[OPT_HELP]) {
        uint16_t col{80};
        const auto cols = getenv("COLUMNS");
        if (cols) col = nk::str_to_u16(cols);
        option::printUsage(fwrite, stdout, usage, col);
        std::exit(EXIT_FAILURE);
    }
    if (options[OPT_VERSION]) {
        print_version();
        std::exit(EXIT_FAILURE);
    }

    std::vector<std::string> addrlist;
    std::string pidfile, chroot_path;

    for (int i = 0; i < parse.optionsCount(); ++i) {
        option::Option &opt = buffer[i];
        switch (opt.index()) {
            case OPT_BACKGROUND: gflags_detach = 1; break;
            case OPT_CONFIG: configfile = std::string(opt.arg); break;
            case OPT_LEASEFILE: leasefile = std::string(opt.arg); break;
            case OPT_PIDFILE: pidfile = std::string(opt.arg); break;
            case OPT_CHROOT: chroot_path = std::string(opt.arg); break;
            case OPT_USER: {
                if (nk_uidgidbyname(opt.arg, &nrad6_uid, &nrad6_gid)) {
                    fmt::print(stderr, "invalid user '{}' specified\n", opt.arg);
                    std::exit(EXIT_FAILURE);
                }
                break;
            }
            case OPT_SECCOMP: use_seccomp = true; break;
            case OPT_QUIET: gflags_quiet = 1; break;
        }
    }

    init_prng();
    if (configfile.size())
        parse_config(configfile);

    for (int i = 0; i < parse.nonOptionsCount(); ++i)
        parse_config(parse.nonOption(i));

    if (!bound_interfaces_count()) {
        fmt::print(stderr, "No interfaces have been bound\n");
        std::exit(EXIT_FAILURE);
    }

    if (!leasefile.size()) {
        leasefile = chroot_path.size() ? "/store/dynlease.txt"
                                       : "/var/lib/ndhs/store/dynlease.txt";
    }

    nl_socket = std::make_unique<NLSocket>(io_service);
    init_listeners();

    if (gflags_detach && daemon(0,0)) {
        fmt::print(stderr, "detaching fork failed\n");
        std::exit(EXIT_FAILURE);
    }

    if (pidfile.size() && file_exists(pidfile.c_str(), "w"))
        write_pid(pidfile.c_str());

    umask(077);
    process_signals();

    if (chroot_path.size()) {
        nk_set_chroot(chroot_path.c_str());
    }
    dynlease_deserialize(leasefile);
    if (nrad6_uid || nrad6_gid)
        nk_set_uidgid(nrad6_uid, nrad6_gid, NULL, 0);

    if (enforce_seccomp(nrad6_uid || nrad6_gid)) {
        fmt::print(stderr, "seccomp filter cannot be installed\n");
        std::exit(EXIT_FAILURE);
    }
}
Пример #4
0
//ToDo(robin): add support for log
int main(int argc, char ** argv) {
  CommandLineOptions options(argc, argv);
	Window * window = new Window(800, 600, APPLICATION_NAME);
	buffer points;
	buffer lines;
	int count = 1;

	std::vector<float> lines_buffer;
	std::vector<float> points_buffer;
	std::vector<ObjectInfo> obj_buffer;

	bool mouseDown = false;
	int mouseX = 0, mouseY = 0, mouseDX = 0, mouseDY = 0, screenSizeX = window->getSize().x, screenSizeY =  window->getSize().y;

	float scale[2] = {1.0, 1.0}, centerX = 0.0, centerY = 0.0, mouseDXScreen = 0.0, mouseDYScreen = 0.0;
	float radius = 50;
	unsigned int samplerate = options.samplerate();

	std::vector<SoundProcessor::v3> listener;

	std::signal(SIGTERM, terminate);
	std::signal(SIGINT, terminate);
	std::signal(SIGABRT, terminate);

	double distBetween = 0.42;

	double * mics = options.mics();

	for(int i = 0; i < options.micCount(); i++) {
		listener.push_back(SoundProcessor::v3(mics[3 * i], mics[3 * i + 1], mics[3 * i + 2]));
	}

	std::cout << "mics: [" << std::endl;
	for(auto l : listener) {
		std::cout << "[" << l.x << ", "
				  << l.y << ", "
				  << l.z << "]" << std::endl;

	}
	std::cout << "]" << std::endl;

	SoundProcessor soundProcessor(samplerate, listener);

	glew_init();

	int listener_count = init_listeners(listener, points_buffer, soundProcessor, radius);

	server = new Server(options.audioPort(), [listener](sf::TcpSocket * socket) {
			unsigned int size = listener.size();

			socket->send(&size, sizeof(int));
			std::cout << "client connected: " << socket->getRemoteAddress() << ":" << socket->getRemotePort() << std::endl;
		});

    GuiServer gserver(options.guiPort());

	count = listener.size();

	glGenBuffers(1, &points.vbo);
	glGenVertexArrays(1, &points.vao);

	glBindBuffer(GL_ARRAY_BUFFER, points.vbo);
	glBufferData(GL_ARRAY_BUFFER, 6 * count * sizeof(float), points_buffer.data(), GL_STREAM_DRAW);
	glBindVertexArray(points.vao);

	ShaderProgram * shaderProgram = new ShaderProgram("#version 130\n"
													  "uniform vec2 center;\n"
													  "uniform vec2 scale;\n"
													  "in vec3 vp;\n"
													  "in vec3 color;\n"
													  "out vec3 Color;\n"
													  "void main() {\n"
													  "   gl_Position = vec4((vp.x + center.x) / scale.x, (vp.y - center.y) / scale.y, 0.0, 1.0);\n"
													  "   gl_PointSize = vp.z / scale.x;\n"
													  "   Color = color;\n"
													  "}\n"
													  , "#version 130\n"
													  "in vec3 Color;\n"
													  "out vec4 frag_colour;\n"
													  "void main () {\n"
													  "    gl_FragColor = vec4(Color, 1.0);\n"
 													  "}");

	shaderProgram->vertexAttribPointer("color", 3, GL_FLOAT, false, 24, (void *) 12);
	shaderProgram->vertexAttribPointer("vp", 3, GL_FLOAT, false, 24, 0);

	lines_buffer.push_back(-1);
	lines_buffer.push_back(0);
	lines_buffer.push_back(1);
	lines_buffer.push_back(0);
	lines_buffer.push_back(1);
	lines_buffer.push_back(0);

	lines_buffer.push_back(1);
	lines_buffer.push_back(0);
	lines_buffer.push_back(1);
	lines_buffer.push_back(0);
	lines_buffer.push_back(1);
	lines_buffer.push_back(0);

	lines_buffer.push_back(0);
	lines_buffer.push_back(-1);
	lines_buffer.push_back(1);
	lines_buffer.push_back(0);
	lines_buffer.push_back(1);
	lines_buffer.push_back(0);

	lines_buffer.push_back(0);
	lines_buffer.push_back(1);
	lines_buffer.push_back(1);
	lines_buffer.push_back(0);
	lines_buffer.push_back(1);
	lines_buffer.push_back(0);

	glGenBuffers(1, &lines.vbo);
	glGenVertexArrays(1, &lines.vao);

	glBindBuffer(GL_ARRAY_BUFFER, lines.vbo);
	glBufferData(GL_ARRAY_BUFFER, lines_buffer.size() * sizeof(float), lines_buffer.data(), GL_STREAM_DRAW);
	glBindVertexArray(lines.vao);

	shaderProgram->vertexAttribPointer("color", 3, GL_FLOAT, false, 24, (void *) 12);
	shaderProgram->vertexAttribPointer("vp", 3, GL_FLOAT, false, 24, 0);

    glEnable(GL_POINT_SMOOTH);
	glEnable(GL_LINE_SMOOTH);
	glEnable(GL_PROGRAM_POINT_SIZE);

    glPointSize(20.0);
	glLineWidth(3.0);

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);

	glClearColor(1, 1, 1, 1);

	screenSizeX = window->getSize().x;
	screenSizeY = window->getSize().y;

	float freq = 100;
	auto now = std::chrono::high_resolution_clock::now();

	Stopwatch::getInstance().setCustomSignature(32435);

	int id = 0;

	while (window->open()) {
		TICK("simulation_total");
		TICK("simulation_process_events");

		auto events = window->pollEvents();

		for(auto event : events) {
			switch (event.type) {
			case sf::Event::Closed: {
				window->close();
				break;
			}
			case sf::Event::KeyPressed: {
				if(event.key.code == sf::Keyboard::Space && gserver.buffer != nullptr) {
					std::cout << id++ << ", "
							  << gserver.buffer[0] << ", "
							  << gserver.buffer[1] << ", "
							  << gserver.buffer[2] << std::endl;
				}
				break;
			}
			case sf::Event::Resized: {
                glViewport(0, 0, event.size.width, event.size.height);
				screenSizeX = event.size.width;
				screenSizeY = event.size.height;
				break;
			}
			case sf::Event::MouseButtonPressed: {
				if(event.mouseButton.button == sf::Mouse::Left) {
					mouseDown = true;

					mouseX = sf::Mouse::getPosition().x;
					mouseY = sf::Mouse::getPosition().y;
				}
				else if(event.mouseButton.button == sf::Mouse::Right) {
					float x = event.mouseButton.x, y = event.mouseButton.y, dx, dy;
					bool add = true;

					x = (2.0 * (x / screenSizeX) - 1.0) * scale[0] - centerX;
					y = -(2.0 * (y / screenSizeY) - 1.0) * scale[1] + centerY;

					for(int i = (points_buffer.size() / 6) - 1; i > listener.size() - 1; i--) {
						dx = (points_buffer[6 * i] - x) * screenSizeX * scale[0];
						dy = (points_buffer[6 * i + 1] - y) * screenSizeY * scale[1];

						if(sqrt(dx * dx + dy * dy) < radius * scale[0]) {
							soundProcessor.remove(points_buffer[6 * i], points_buffer[6 * i + 1]);
							points_buffer.erase(points_buffer.begin() + 6 * i - 1, points_buffer.begin() + 6 * i + 5);
							obj_buffer.erase(obj_buffer.begin() + i - listener.size());

							count--;
							add = false;

							break;
						}
					}

					if(add) {
						points_buffer.push_back(x);
						points_buffer.push_back(y);
						points_buffer.push_back(radius);
						points_buffer.push_back(0);
						points_buffer.push_back(0);
						points_buffer.push_back(0);

						ObjectInfo oinfo;
						SoundProcessor::SoundObject * obj = new SoundProcessor::SoundObject(x, y, freq);

						oinfo.id = soundProcessor.add(obj);

						obj_buffer.push_back(oinfo);

						std::cout << "adding with freq: " << freq << std::endl;

						//freq += 0;
						freq += FREQUENCY_INCREMENT;

						count++;
					}

					glBindBuffer(GL_ARRAY_BUFFER, points.vbo);
					glBufferData(GL_ARRAY_BUFFER, 6 * count * sizeof(float), points_buffer.data(), GL_STREAM_DRAW);
				}
				break;
			}
			case sf::Event::MouseButtonReleased: {
				if(event.mouseButton.button == sf::Mouse::Left) {
					mouseDown = false;
					centerX = centerX - mouseDXScreen;
					centerY = centerY - mouseDYScreen;
					mouseDXScreen = 0.0;
					mouseDYScreen = 0.0;
				}
				break;
			}
			case sf::Event::MouseWheelScrolled: {
				scale[0] *= (event.mouseWheelScroll.delta > 0 ? 0.9 : 1.11111111);
				scale[1] *= (event.mouseWheelScroll.delta > 0 ? 0.9 : 1.11111111);

				break;
			}
			default:
				break;
			}
		}

		glClear(GL_COLOR_BUFFER_BIT);

		if (mouseDown) {
			mouseDX = mouseX - sf::Mouse::getPosition().x;
			mouseDY = mouseY - sf::Mouse::getPosition().y;

			mouseDXScreen = ((((double) mouseDX * 2) / (double) screenSizeX)) * scale[0];
			mouseDYScreen = ((((double) mouseDY * 2) / (double) screenSizeY)) * scale[1];
		}

		TOCK("simulation_process_events");

		double time = (std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock().now() - now).count()) / 1000000000.0;
		now = std::chrono::high_resolution_clock().now();
		unsigned int samples = (float) samplerate * time;

		TICK("simulation_generate_samples");

		double * current_samples = soundProcessor.sample(samples);

		TOCK("simulation_generate_samples");

		server->send(current_samples, samples * listener.size());

		free(current_samples);

		TICK("simulation_draw");

	    glBindVertexArray(points.vao);

		shaderProgram->uniform2f("center", centerX - mouseDXScreen, centerY - mouseDYScreen);
		shaderProgram->uniform2f("scale", scale[0], scale[1]);

		glBufferData(GL_ARRAY_BUFFER, 6 * count * sizeof(float), points_buffer.data(), GL_STREAM_DRAW);

		glDrawArrays(GL_POINTS, 0, count);

		glBindVertexArray(lines.vao);

		std::vector<float> data = gserver.getPoints();

		lines_buffer.clear();
		lines_buffer.insert(lines_buffer.begin(), data.begin(), data.end());

		glBindBuffer(GL_ARRAY_BUFFER, lines.vbo);

		glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(float), data.data(), GL_STREAM_DRAW);

		// ToDo(robin): better solution!!
		//if(count > listener.size())
			glDrawArrays(GL_POINTS, 0, data.size() / 6);

		window->display();
		TOCK("simulation_draw");

		TOCK("simulation_total");

        Stopwatch::getInstance().sendAll();
    }

	terminate(0);

	return 0;
}