Beispiel #1
0
void Owncloudclient::writeElement( QXmlStreamWriter &xml )
{
  xml.writeStartElement( "owncloudclient" );
  if ( !version().isEmpty() ) {
    xml.writeTextElement(  "version", version() );
  }
  if ( !versionstring().isEmpty() ) {
    xml.writeTextElement(  "versionstring", versionstring() );
  }
  if ( !web().isEmpty() ) {
    xml.writeTextElement(  "web", web() );
  }
  xml.writeEndElement();
}
Beispiel #2
0
    bool Head::every_m_lines(Vect<float> &top, float &n_top_x, float const &y, float &web_width, float &num_webs, bool const &start, bool &top_flag, Vect<float> &right,
                             Vect<float> &left, float const &right_last_x, float const &left_last_x,
                             float &web_surface, float &web_surface_last, Vect<float> &bottom, float &n_bottom_x, Vect<float> &neck) {
        // every m_lines lines
        // toutes les m_lines lines
        if (web_width >= m_lines && start) {

            // fin du calcul de la moyenne horizontale du haut de la tête
            // end of averaging the horizontal top of the head
            top_flag = false;

            // calcule à nouveau la largeur de la nouvelle bande
            // Calculate the new bandwidth again
            web_width = 0;

            // num_webs is the number of bands with width = m_lines
            ++num_webs;

            if(web(top, n_top_x, y, web_surface, web_surface_last, num_webs, bottom, n_bottom_x, right, left, neck))
                return true;

            right.x = right_last_x;
            left.x = left_last_x;

            web_surface_last = web_surface;
            web_surface = 0;

            bottom.x = 0;
            n_bottom_x = 0;
        }
        return false;
    }
int
main (int argc, char **argv)
{
	int listenfd, socketfd, pid;
	size_t length;
	static struct sockaddr_in serv_addr;
	static struct sockaddr_in cli_addr;
	// Se crea el socket de escuaha
	listenfd = socket (AF_INET, SOCK_STREAM, 0);
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = htonl (INADDR_ANY);
	serv_addr.sin_port = htons (PORT);
	// Se asociamos la direccion con el socket
	bind (listenfd, (struct sockaddr *) &serv_addr, sizeof (serv_addr));
	listen (listenfd, LISTENQ);
	// Creamos los hijos(fork) para manejar las solicitudes 
	for (; ;) {
		length = sizeof (cli_addr);
		socketfd = accept (listenfd, (struct sockaddr *) &cli_addr, &length);
		if ((pid = fork ()) == 0) {
			close (listenfd);
			web (socketfd);
		} else {
			close (socketfd);
		}
	}
}
Beispiel #4
0
void UpdateInfo::writeElement( QXmlStreamWriter &xml )
{
  xml.writeStartElement( QLatin1String("owncloudclient") );
  if ( !version().isEmpty() ) {
    xml.writeTextElement(  QLatin1String("version"), version() );
  }
  if ( !versionString().isEmpty() ) {
    xml.writeTextElement(  QLatin1String("versionstring"), versionString() );
  }
  if ( !web().isEmpty() ) {
    xml.writeTextElement(  QLatin1String("web"), web() );
  }
  if ( !downloadUrl().isEmpty() ) {
    xml.writeTextElement(  QLatin1String("downloadurl"), web() );
  }
  xml.writeEndElement();
}
Beispiel #5
0
void SmugWidget::updateLabels(const QString& email, const QString& name, const QString& nick)
{
    m_email->setText(email);
    m_userName->setText(QString("<b>%1</b>").arg(name));
    QString web("www");
    if (!nick.isEmpty())
        web = nick;
    m_headerLbl->setText(QString("<b><h2><a href='http://%1.smugmug.com.'>"
                                   "<font color=\"#9ACD32\">SmugMug</font>"
                                   "</a></h2></b>").arg(web));
}
Beispiel #6
0
int main(){
    int pid;
	SOCKET socketfd;
    socklen_t length;
    static struct sockaddr_in clientAddress;

	setLogLevel(LOG_WARN);
	setAppName("WEB");
	setLogToFile(TRUE);

    signal(SIGCHLD, SIG_IGN); /* ignore child death */
	signal(SIGINT,  sigHandler);	// Trap Ctrl-C in case we are running interactively
	signal(SIGTERM, sigHandler);	// Trap termination requests from the system

    readDbConfig();

    listener = setupListener();

    while (1){
        length = sizeof(clientAddress);

        socketfd = accept(listener, (struct sockaddr *) &clientAddress, &length);
   		
        if (socketfd < 0){
            logMsg(LOG_ERR, "accept() returned %d, %s", socketfd, strerror(errno));
        } else {
            pid = fork();
            //TODO drop privs after fork
            if (pid == 0){
             // We are in the child process
                close(listener);
                web(socketfd);

            } else if (pid > 0){
             // We are still in the parent process
                close(socketfd);

            } else {
                logMsg(LOG_ERR, "fork() returned %d, %s", pid, strerror(errno));
                exit(1);
            }
        }
    }

    return 0;
}
Beispiel #7
0
    void listen(int port) {
        //testTheDb();
        MessageServer::Options options;
        options.port = port;
        options.ipList = cmdLine.bind_ip;

        MessageServer * server = createServer( options , new MyMessageHandler() );
        server->setAsTimeTracker();

        startReplication();
        if ( !noHttpInterface )
            boost::thread web( boost::bind(&webServerThread, new RestAdminAccess() /* takes ownership */));

#if(TESTEXHAUST)
        boost::thread thr(testExhaust);
#endif
        server->run();
    }
Beispiel #8
0
void WmWidget::updateLabels(const QString& name, const QString& url)
{
    QString web("http://commons.wikimedia.org");

    if (!url.isEmpty())
        web = url;

    m_headerLbl->setText(QString("<b><h2><a href='%1'>"
                                 "<font color=\"#3B5998\">%2</font>"
                                 "</a></h2></b>").arg(web).arg(i18n("Wikimedia commons")));
    if (name.isEmpty())
    {
        m_userNameDisplayLbl->clear();
    }
    else
    {
        m_userNameDisplayLbl->setText(QString::fromLatin1("<b>%1</b>").arg(name));
    }
}
Beispiel #9
0
void FbWidget::updateLabels(const QString& name, const QString& url)
{
    QString web(QString::fromLatin1("http://www.facebook.com"));

    if (!url.isEmpty())
        web = url;

    getHeaderLbl()->setText(QString::fromLatin1(
        "<b><h2><a href='%1'>"
        "<font color=\"#3B5998\">facebook</font>"
        "</a></h2></b>").arg(web));
    if (name.isEmpty())
    {
        getUserNameLabel()->clear();
    }
    else
    {
        getUserNameLabel()->setText(QString::fromLatin1("<b>%1</b>").arg(name));
    }
}
Beispiel #10
0
void Image::download()
{
	if (m_status != down_undone) return;
	
	std::string file;
	
	if (m_filename == "")
		file = (m_dir + getFile(m_url));
	else
		file = m_dir + m_filename + getExtension(m_url);
	FILE* f = fopen(file.c_str(), "rb");
	
	if (f != NULL) //Cover was alreayd downloaded
	{
		m_status = down_done;
	}
	
	if (m_status == down_done) return;
	
	m_status = down_started;
	sf::Http web(getHost(m_url));
	sf::Http::Request request(getUri(m_url));
	std::cout<<"Downloading "<<m_url<<"\n";
	sf::Http::Response response = web.sendRequest(request);
	
	
	sf::Http::Response::Status status = response.getStatus();
	
	if (status == sf::Http::Response::Ok)
	{
		f = fopen(file.c_str(), "wb");
		fwrite(response.getBody().c_str(), sizeof(char), response.getBody().size(), f);
		fclose(f);
		m_status = down_done;
	}
	else
	{
		std::cerr<<"Download fail, error: "<<status<<"\n";
		m_status = down_fail;
	}
}
Beispiel #11
0
void DropboxWidget::updateLabels(const QString& name, const QString& url)
{
    QString web(QString::fromLatin1("https://www.dropbox.com/"));

    if (!url.isEmpty())
        web = url;

    getHeaderLbl()->setText(QString::fromLatin1(
        "<b><h2><a href='%1'>"
        "<font color=\"#9ACD32\">Dropbox</font>"
        "</a></h2></b>").arg(web));

    if (name.isEmpty())
    {
        getUserNameLabel()->clear();
    }
    else
    {
        getUserNameLabel()->setText(QString::fromLatin1("<b>%1</b>").arg(name));
    }
}
Beispiel #12
0
int main(int argc, char *argv[])
{
  int ld, sd, r;
  static struct sockaddr_in addr;

  if ((ld = socket(AF_INET, SOCK_STREAM,0)) < 0) fatal("socket()");
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = htonl(INADDR_ANY);
  addr.sin_port = htons((argc == 2) ? atoi(argv[1]) : 80);
  if (bind(ld, (struct sockaddr *) &addr, sizeof(addr))) fatal("bind()");
  if (listen(ld, 1) < 0) fatal("listen()");

  for (;;) {
    if ((sd = accept(ld, 0, 0)) < 0) fatal("accept()");
    if ((r = fork()) < 0) fatal("fork()");
    if (!r) {
      close(ld);
      return web(sd);
    }
    close(sd);
  }
}
Beispiel #13
0
    void listen(int port) {
        //testTheDb();
        MessageServer::Options options;
        options.port = port;
        options.ipList = serverGlobalParams.bind_ip;

        MessageServer * server = createServer( options , new MyMessageHandler() );
        server->setAsTimeTracker();
        // we must setupSockets prior to logStartup() to avoid getting too high
        // a file descriptor for our calls to select()
        server->setupSockets();

        logStartup();
        startReplication();
        if (serverGlobalParams.isHttpInterfaceEnabled)
            boost::thread web( boost::bind(&webServerThread, new RestAdminAccess() /* takes ownership */));

#if(TESTEXHAUST)
        boost::thread thr(testExhaust);
#endif
        server->run();
    }
Beispiel #14
0
void Chapter::download()
{
	sf::Http web(Manga::MangaHost);
	
	sf::Http::Request request(m_uri);
	
	sf::Http::Response response = web.sendRequest(request);
	
	sf::Http::Response::Status status = response.getStatus();
	
	if (status == sf::Http::Response::Ok)
	{
		std::string body(response.getBody());
		
		//Erase all of the \n
		eraseN(body);
		
		if (testing)
		{
			char html_file[300];
			sprintf(html_file, "test/chapter_%u_page1.html", m_num_chapter);
			FILE* f = fopen(html_file, "w");
			fwrite(body.c_str(), sizeof(char), body.size(), f);
			fclose(f);
			
			std::cout<<"Html page output to file: "<<html_file<<"\n";
			
		}
		
		sscanf(getParse(body, Manga::parseChapterPages).c_str(), "%u", &m_pages);
		
		if (testing)
			std::cout<<"number of pages for chapter "<<m_num_chapter<<" parsed: "<<m_pages<<"\n";
		
		//Clean images
		for (std::vector<Image*>::iterator it(m_images.begin()); it != m_images.end(); ++it)
			delete *it;
		
		m_images.resize(m_pages);
		for (unsigned int i(0); i<m_images.size(); ++i)
			m_images[i] = new Image;
		
		//we ad the fisrt image
		m_images[0]->setUrl(getParse(body, Manga::parsePageImg));
		m_images[0]->setDir(m_dir);
		char filename[300];
		sprintf(filename, "%s %u-1", m_manga->m_name.c_str(), m_num_chapter);
		m_images[0]->setFileName(filename);
		if (!testing)
		{
			m_images[0]->thDownload();
			std::cout<<"Image 1/"<<m_images.size()<<" found.\n";
		}
	
		
		std::string next_page(getParse(body, Manga::parsePageNext));
		
		switch (Manga::mangaPath) {
			case URL_uri:
				break;
			case URL_absolute:
				next_page = getUri(next_page);
				break;
			case URL_relative:
				next_page = getWorkingDirectory(m_uri) + next_page;
				break;
			default:
				break;
		}
		
		if (testing)
			std::cout<<"Image 1 parsed: "<<m_images[0]->getUrl()<<"\nNext page parsed (Uri format): "<<next_page<<"\n";
		
		for (unsigned int i(1); i<m_images.size(); ++i)
		{
			request.setUri(next_page);
			response = web.sendRequest(request);
			status = response.getStatus();
			
			if (status == sf::Http::Response::Ok)
			{
				std::string body(response.getBody());
				
				//Erase all of the \n
				eraseN(body);
				
				if (testing && i == 1)
				{
					char html_file[300];
					sprintf(html_file, "test/chapter_%u_other_page.html", m_num_chapter);
					FILE* f = fopen(html_file, "w");
					fwrite(body.c_str(), sizeof(char), body.size(), f);
					fclose(f);
					
					std::cout<<"Html page output to file: "<<html_file<<"\n";
					
				}
				
				m_images[i]->setUrl(getParse(body, Manga::parsePageImg));
				m_images[i]->setDir(m_dir);
				sprintf(filename, "%s %u-%u", m_manga->m_name.c_str(), m_num_chapter, i+1);
				m_images[i]->setFileName(filename);
				if (!testing)
				{
					m_images[i]->thDownload();
					std::cout<<"Image "<<i+1<<"/"<<m_images.size()<<" found.\n";
				}
				
				next_page = getParse(body, Manga::parsePageNext);
				switch (Manga::mangaPath) {
					case URL_uri:
						break;
					case URL_absolute:
						next_page = getUri(next_page);
						break;
					case URL_relative:
						next_page = getWorkingDirectory(m_uri) + next_page;
						break;
					default:
						break;
				}
				
				if (testing)
					std::cout<<"Image "<<i+1<<" parsed: "<<m_images[i]->getUrl()<<"\nNext page parsed: "<<next_page<<"\n";
			}
			else
				std::cout<<"Error getting page: "<<status<<"\n";
		}
		
		//std::cout<<"img:"<<getParse(body, Manga::parsePageImg)<<" next page: "<<getParse(body, Manga::parsePageNext)<<"\n";
		//Download imgs
		
		//for (int i=0; i<1; ++i) m_images[i]->thDownload();
		
	}
	else
		std::cout<<"Error checking chapter: "<<status<<"\n";
}
Beispiel #15
0
ExitCode _initAndListen(int listenPort) {
    Client::initThread("initandlisten");

    _initWireSpec();
    auto globalServiceContext = getGlobalServiceContext();

    globalServiceContext->setFastClockSource(FastClockSourceFactory::create(Milliseconds(10)));
    globalServiceContext->setOpObserver(stdx::make_unique<OpObserver>());

    DBDirectClientFactory::get(globalServiceContext)
        .registerImplementation([](OperationContext* txn) {
            return std::unique_ptr<DBClientBase>(new DBDirectClient(txn));
        });

    const repl::ReplSettings& replSettings = repl::getGlobalReplicationCoordinator()->getSettings();

    {
        ProcessId pid = ProcessId::getCurrent();
        LogstreamBuilder l = log(LogComponent::kControl);
        l << "MongoDB starting : pid=" << pid << " port=" << serverGlobalParams.port
          << " dbpath=" << storageGlobalParams.dbpath;
        if (replSettings.isMaster())
            l << " master=" << replSettings.isMaster();
        if (replSettings.isSlave())
            l << " slave=" << (int)replSettings.isSlave();

        const bool is32bit = sizeof(int*) == 4;
        l << (is32bit ? " 32" : " 64") << "-bit host=" << getHostNameCached() << endl;
    }

    DEV log(LogComponent::kControl) << "DEBUG build (which is slower)" << endl;

#if defined(_WIN32)
    VersionInfoInterface::instance().logTargetMinOS();
#endif

    logProcessDetails();

    checked_cast<ServiceContextMongoD*>(getGlobalServiceContext())->createLockFile();

    transport::TransportLayerLegacy::Options options;
    options.port = listenPort;
    options.ipList = serverGlobalParams.bind_ip;

    auto sep =
        stdx::make_unique<ServiceEntryPointMongod>(getGlobalServiceContext()->getTransportLayer());
    auto sepPtr = sep.get();

    getGlobalServiceContext()->setServiceEntryPoint(std::move(sep));

    // Create, start, and attach the TL
    auto transportLayer = stdx::make_unique<transport::TransportLayerLegacy>(options, sepPtr);
    auto res = transportLayer->setup();
    if (!res.isOK()) {
        error() << "Failed to set up listener: " << res;
        return EXIT_NET_ERROR;
    }

    std::shared_ptr<DbWebServer> dbWebServer;
    if (serverGlobalParams.isHttpInterfaceEnabled) {
        dbWebServer.reset(new DbWebServer(serverGlobalParams.bind_ip,
                                          serverGlobalParams.port + 1000,
                                          getGlobalServiceContext(),
                                          new RestAdminAccess()));
        if (!dbWebServer->setupSockets()) {
            error() << "Failed to set up sockets for HTTP interface during startup.";
            return EXIT_NET_ERROR;
        }
    }

    getGlobalServiceContext()->initializeGlobalStorageEngine();

#ifdef MONGO_CONFIG_WIREDTIGER_ENABLED
    if (WiredTigerCustomizationHooks::get(getGlobalServiceContext())->restartRequired()) {
        exitCleanly(EXIT_CLEAN);
    }
#endif

    // Warn if we detect configurations for multiple registered storage engines in
    // the same configuration file/environment.
    if (serverGlobalParams.parsedOpts.hasField("storage")) {
        BSONElement storageElement = serverGlobalParams.parsedOpts.getField("storage");
        invariant(storageElement.isABSONObj());
        BSONObj storageParamsObj = storageElement.Obj();
        BSONObjIterator i = storageParamsObj.begin();
        while (i.more()) {
            BSONElement e = i.next();
            // Ignore if field name under "storage" matches current storage engine.
            if (storageGlobalParams.engine == e.fieldName()) {
                continue;
            }

            // Warn if field name matches non-active registered storage engine.
            if (getGlobalServiceContext()->isRegisteredStorageEngine(e.fieldName())) {
                warning() << "Detected configuration for non-active storage engine "
                          << e.fieldName() << " when current storage engine is "
                          << storageGlobalParams.engine;
            }
        }
    }

    if (!getGlobalServiceContext()->getGlobalStorageEngine()->getSnapshotManager()) {
        if (moe::startupOptionsParsed.count("replication.enableMajorityReadConcern") &&
            moe::startupOptionsParsed["replication.enableMajorityReadConcern"].as<bool>()) {
            // Note: we are intentionally only erroring if the user explicitly requested that we
            // enable majority read concern. We do not error if the they are implicitly enabled for
            // CSRS because a required step in the upgrade procedure can involve an mmapv1 node in
            // the CSRS in the REMOVED state. This is handled by the TopologyCoordinator.
            invariant(replSettings.isMajorityReadConcernEnabled());
            severe() << "Majority read concern requires a storage engine that supports"
                     << " snapshots, such as wiredTiger. " << storageGlobalParams.engine
                     << " does not support snapshots.";
            exitCleanly(EXIT_BADOPTIONS);
        }
    }

    logMongodStartupWarnings(storageGlobalParams, serverGlobalParams);

    {
        stringstream ss;
        ss << endl;
        ss << "*********************************************************************" << endl;
        ss << " ERROR: dbpath (" << storageGlobalParams.dbpath << ") does not exist." << endl;
        ss << " Create this directory or give existing directory in --dbpath." << endl;
        ss << " See http://dochub.mongodb.org/core/startingandstoppingmongo" << endl;
        ss << "*********************************************************************" << endl;
        uassert(10296, ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.dbpath));
    }

    {
        stringstream ss;
        ss << "repairpath (" << storageGlobalParams.repairpath << ") does not exist";
        uassert(12590, ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.repairpath));
    }

    // TODO:  This should go into a MONGO_INITIALIZER once we have figured out the correct
    // dependencies.
    if (snmpInit) {
        snmpInit();
    }

    if (!storageGlobalParams.readOnly) {
        boost::filesystem::remove_all(storageGlobalParams.dbpath + "/_tmp/");
    }

    if (mmapv1GlobalOptions.journalOptions & MMAPV1Options::JournalRecoverOnly)
        return EXIT_NET_ERROR;

    if (mongodGlobalParams.scriptingEnabled) {
        ScriptEngine::setup();
    }

    auto startupOpCtx = getGlobalServiceContext()->makeOperationContext(&cc());

    repairDatabasesAndCheckVersion(startupOpCtx.get());

    if (storageGlobalParams.upgrade) {
        log() << "finished checking dbs";
        exitCleanly(EXIT_CLEAN);
    }

    uassertStatusOK(getGlobalAuthorizationManager()->initialize(startupOpCtx.get()));

    /* this is for security on certain platforms (nonce generation) */
    srand((unsigned)(curTimeMicros64() ^ startupSrandTimer.micros()));

    // The snapshot thread provides historical collection level and lock statistics for use
    // by the web interface. Only needed when HTTP is enabled.
    if (serverGlobalParams.isHttpInterfaceEnabled) {
        statsSnapshotThread.go();

        invariant(dbWebServer);
        stdx::thread web(stdx::bind(&webServerListenThread, dbWebServer));
        web.detach();
    }

#ifndef _WIN32
    mongo::signalForkSuccess();
#endif
    AuthorizationManager* globalAuthzManager = getGlobalAuthorizationManager();
    if (globalAuthzManager->shouldValidateAuthSchemaOnStartup()) {
        Status status = authindex::verifySystemIndexes(startupOpCtx.get());
        if (!status.isOK()) {
            log() << redact(status);
            exitCleanly(EXIT_NEED_UPGRADE);
        }

        // SERVER-14090: Verify that auth schema version is schemaVersion26Final.
        int foundSchemaVersion;
        status =
            globalAuthzManager->getAuthorizationVersion(startupOpCtx.get(), &foundSchemaVersion);
        if (!status.isOK()) {
            log() << "Auth schema version is incompatible: "
                  << "User and role management commands require auth data to have "
                  << "at least schema version " << AuthorizationManager::schemaVersion26Final
                  << " but startup could not verify schema version: " << status;
            exitCleanly(EXIT_NEED_UPGRADE);
        }
        if (foundSchemaVersion < AuthorizationManager::schemaVersion26Final) {
            log() << "Auth schema version is incompatible: "
                  << "User and role management commands require auth data to have "
                  << "at least schema version " << AuthorizationManager::schemaVersion26Final
                  << " but found " << foundSchemaVersion << ". In order to upgrade "
                  << "the auth schema, first downgrade MongoDB binaries to version "
                  << "2.6 and then run the authSchemaUpgrade command.";
            exitCleanly(EXIT_NEED_UPGRADE);
        }
    } else if (globalAuthzManager->isAuthEnabled()) {
        error() << "Auth must be disabled when starting without auth schema validation";
        exitCleanly(EXIT_BADOPTIONS);
    } else {
        // If authSchemaValidation is disabled and server is running without auth,
        // warn the user and continue startup without authSchema metadata checks.
        log() << startupWarningsLog;
        log() << "** WARNING: Startup auth schema validation checks are disabled for the "
                 "database."
              << startupWarningsLog;
        log() << "**          This mode should only be used to manually repair corrupted auth "
                 "data."
              << startupWarningsLog;
    }

    auto shardingInitialized =
        uassertStatusOK(ShardingState::get(startupOpCtx.get())
                            ->initializeShardingAwarenessIfNeeded(startupOpCtx.get()));
    if (shardingInitialized) {
        reloadShardRegistryUntilSuccess(startupOpCtx.get());
    }

    if (!storageGlobalParams.readOnly) {
        logStartup(startupOpCtx.get());

        startFTDC();

        getDeleter()->startWorkers();

        restartInProgressIndexesFromLastShutdown(startupOpCtx.get());

        if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) {
            // Note: For replica sets, ShardingStateRecovery happens on transition to primary.
            if (!repl::getGlobalReplicationCoordinator()->isReplEnabled()) {
                uassertStatusOK(ShardingStateRecovery::recover(startupOpCtx.get()));
            }
        } else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
            uassertStatusOK(
                initializeGlobalShardingStateForMongod(startupOpCtx.get(),
                                                       ConnectionString::forLocal(),
                                                       kDistLockProcessIdForConfigServer));
            Balancer::create(startupOpCtx->getServiceContext());
        }

        repl::getGlobalReplicationCoordinator()->startup(startupOpCtx.get());

        const unsigned long long missingRepl =
            checkIfReplMissingFromCommandLine(startupOpCtx.get());
        if (missingRepl) {
            log() << startupWarningsLog;
            log() << "** WARNING: mongod started without --replSet yet " << missingRepl
                  << " documents are present in local.system.replset" << startupWarningsLog;
            log() << "**          Restart with --replSet unless you are doing maintenance and "
                  << " no other clients are connected." << startupWarningsLog;
            log() << "**          The TTL collection monitor will not start because of this."
                  << startupWarningsLog;
            log() << "**         ";
            log() << " For more info see http://dochub.mongodb.org/core/ttlcollections";
            log() << startupWarningsLog;
        } else {
            startTTLBackgroundJob();
        }

        if (!replSettings.usingReplSets() && !replSettings.isSlave() &&
            storageGlobalParams.engine != "devnull") {
            ScopedTransaction transaction(startupOpCtx.get(), MODE_X);
            Lock::GlobalWrite lk(startupOpCtx.get()->lockState());
            FeatureCompatibilityVersion::setIfCleanStartup(
                startupOpCtx.get(), repl::StorageInterface::get(getGlobalServiceContext()));
        }
    }

    startClientCursorMonitor();

    PeriodicTask::startRunningPeriodicTasks();

    // MessageServer::run will return when exit code closes its socket and we don't need the
    // operation context anymore
    startupOpCtx.reset();

    auto start = getGlobalServiceContext()->addAndStartTransportLayer(std::move(transportLayer));
    if (!start.isOK()) {
        error() << "Failed to start the listener: " << start.toString();
        return EXIT_NET_ERROR;
    }

    return waitForShutdown();
}
Beispiel #16
0
int main(int argc, char **argv)
{
	int i, port, pid, listenfd, socketfd, hit;
	socklen_t length;
	static struct sockaddr_in cli_addr; /* static = initialised to zeros */
	static struct sockaddr_in serv_addr; /* static = initialised to zeros */

	if( argc < 3  || argc > 3 || !strcmp(argv[1], "-?") ) {
		(void)printf("hint: nweb Port-Number Top-Directory\t\tversion %d\n\n"
	"\tnweb is a small and very safe mini web server\n"
	"\tnweb only servers out file/web pages with extensions named below\n"
	"\t and only from the named directory or its sub-directories.\n"
	"\tThere is no fancy features = safe and secure.\n\n"
	"\tExample: nweb 8181 /home/nwebdir &\n\n"
	"\tOnly Supports:", VERSION);
		for(i=0;extensions[i].ext != 0;i++)
			(void)printf(" %s",extensions[i].ext);

		(void)printf("\n\tNot Supported: URLs including \"..\", Java, Javascript, CGI\n"
	"\tNot Supported: directories / /etc /bin /lib /tmp /usr /dev /sbin \n"
	"\tNo warranty given or implied\n\tNigel Griffiths [email protected]\n"  );
		exit(0);
	}
	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) ){
		(void)printf("ERROR: Bad top directory %s, see nweb -?\n",argv[2]);
		exit(3);
	}
	if(chdir(argv[2]) == -1){ 
		(void)printf("ERROR: Can't Change to directory %s\n",argv[2]);
		exit(4);
	}
	/* Become deamon + unstopable */
	if(fork() != 0)
		return 0; /* parent returns OK to shell */
	signal(SIGCHLD, sigchild);
	signal(SIGHUP, SIG_IGN); /* ignore terminal hangups */
	for(i=0;i<32;i++)
		(void)close(i);		/* close open files */
	(void)setpgid(0, 0);		/* break away from process group */
	/* setup the network socket */
	if((listenfd = socket(AF_INET, SOCK_STREAM,0)) <0)
		logger(ERROR,0);
	port = atoi(argv[1]);
	if(port < 0 || port >65535)
		logger(ERROR,0);
	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)
		logger(ERROR,0);
	if( listen(listenfd,64) <0)
		logger(ERROR,0);
	for(hit=1; ;hit++) {
		length = sizeof(cli_addr);
		if((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &length)) < 0)
			logger(ERROR,0);
		if((pid = fork()) < 0) {
			logger(ERROR,0);
		}
		else {
			if(pid == 0) { 	/* child */
				(void)close(listenfd);
				web(socketfd,hit); /* never returns */
			} else { 	/* parent */
				(void)close(socketfd);
			}
		}
	}
}
int main(int argc, char** argv)
{
    signal(SIGHUP, HUPhandler);
	 signal(SIGTERM, killhandler);
	 signal(SIGINT, killhandler);
	 signal(SIGQUIT, killhandler);
	 signal(SIGALRM, deathklockhandler);
    //signal(SIGINT, killhandler);
    printf("My process ID : %d\n", getpid());
	pid_t g_mainpid = getpid();
    //Load the config for the first time
    g_configstruct = loadConf();
    //Fork off the log processes
    pid_t logpid;

    //logfork

    logpid = fork();
    if(logpid < 0)
    {
        printf("Error");
        exit(1);
    }
    else if (logpid==0)
    {
        srvlog();
    }
	
    //makelogfifio
    mkfifo(g_logfifo, 0666);
    g_logfifofd = open(g_logfifo, O_WRONLY);
	
	if(!g_killflag) //prevent log from starting 
	{
    sendLog("status_ready");
	}
	
    //Main program loop
    while(1)
    {
        //printf("Waiting for log\n");
        fflush(stdout);
        //write(g_logfifofd, "status_ready", sizeof("status_ready"));
        if(g_killflag==1)
        {

            fflush(stdout);
            break;
		 }
		 web();
        fflush(stdout);
    }
    //The final countdown!
	g_deathklock = logpid;
	 alarm(5);
    sendLog("status_shutdown");
    waitpid(logpid,NULL,0);
	printf("logger shutdown!\n");
	 alarm(0);
    close(g_logfifofd);
    unlink(g_logfifo);
    printf("Application Terminated Successfully\n\n");
    fflush(stdout);
    return 0;
}
Beispiel #18
0
int main(int argc, char **argv)
{
   int i, port, pid, listenfd, socketfd, hit;
   socklen_t length;
   static struct sockaddr_in cli_addr; /* static = initialised to zeros */
   static struct sockaddr_in serv_addr; /* static = initialised to zeros */

   if( argc < 3  || argc > 4 || !strcmp(argv[1], "-?") ) {
      (void)printf("hint: server Port-Number Top-Directory [Token]\t\tversion %d\n\n"
            "\twebhook is a mini web server desinged to handle github's webhooks\n"
            "\tThere are no fancy features = safe and secure.\n\n"
            "\tExample: webhook 8181 /home/webhook/scripts ABC123 &\n\n", VERSION);
      exit(0);
   }

   for(i=0;i<KEY_LAST;i++){
      settings[i] = &bufSettings[i* SETTING_MAX];
   }
   strncpy(settings[KEY_PORT],argv[1],SETTING_MAX);
   strncpy(settings[KEY_TOKEN],TOKEN,SETTING_MAX);
   if(argc == 4)
      strncpy(settings[KEY_TOKEN],argv[3],SETTING_MAX);
   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) ){
      (void)printf("ERROR: Bad top directory %s, see server -?\n",argv[2]);
      exit(3);
   }
   if(chdir(argv[2]) == -1){ 
      (void)printf("ERROR: Can't Change to directory %s\n",argv[2]);
      exit(4);
   }
#ifdef DEAMONIZED
   /* Become deamon + unstopable and no zombies children (= no wait()) */
   if(fork() != 0)
      return 0;                         /* parent returns OK to shell */
   (void)signal(SIGCLD, SIG_IGN);         /* ignore child death */
   (void)signal(SIGHUP, SIG_IGN);         /* ignore terminal hangups */
   for(i=0;i<32;i++)
      (void)close(i);		          /* close open files */
   (void)setpgrp();	                  /* break away from process group */
#endif
   logger(LOG,"server starting",settings[KEY_TOKEN],getpid());

   /* setup the network socket */
   if((listenfd = socket(AF_INET, SOCK_STREAM,0)) <0)
      logger(ERROR, "system call","socket",0);
   port = atoi(settings[KEY_PORT]);
   if(port < 0 || port >60000)
      logger(ERROR,"Invalid port number (try 1->60000)",settings[KEY_PORT],0);

   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)
      logger(ERROR,"system call","bind",0);
   if( listen(listenfd,64) <0)
      logger(ERROR,"system call","listen",0);

   for(hit=1; ;hit++) {
      length = sizeof(cli_addr);
      if((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &length)) < 0)
         logger(ERROR,"system call","accept",0);
      if((pid = fork()) < 0) {
         logger(ERROR,"system call","fork",0);
      }
      else {
         if(pid == 0) {             /* child */
            (void)close(listenfd);
            web(socketfd,hit);      /* never returns */
         } else { 	            /* parent */
            (void)close(socketfd);
         }
      }
   }
}
Beispiel #19
0
int main(int argc, char **argv)
{
    static struct sockaddr_in cli_addr;
    static struct sockaddr_in serv_addr;
    long string_as_number;
    unsigned short port;
    int status;
    int pid, listenfd, hit;
    register int i;

    if (argc < 3  || argc > 3 || !strcmp(argv[1], "-?")) {
        printf(
            "usage: server [port] [server directory] &"
            "\tExample: server 80 ./ &\n\n"
            "\tOnly Supports: "
        );
        for (i = 0; extensions[i].ext != 0; i++) {
            putchar(' ');
            fputs(extensions[i].ext, stdout);
        }

        putchar('\n');
        exit(0);
    }
    for (i = 0; i < 8; i++) {
        if (strncmp(argv[2], baddirs[i], strlen(baddirs[i])) == 0) {
            printf("ERROR:  Bad top directory %s, see server -?\n", argv[2]);
            exit(3);
        }
    }
    if (chdir(argv[2]) == -1) {
        printf("ERROR: Can't Change to directory %s\n", argv[2]);
        exit(4);
    }

    if (fork() != 0)
        return 0;
    signal(SIGCHLD, SIG_IGN);
    signal(SIGHUP, SIG_IGN);
    for (i = 0; i < 32; i++)
        close(i);

    status = setpgrp();
    if (status != 0)
        fprintf(stderr, "Process group set failed with error %i.\n", status);

    my_log(LOG, "http server starting", argv[1], getpid());

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd < 0)
        my_log(ERROR, "system call", "socket", 0);

    string_as_number = strtol(argv[1], NULL, 0);
    if (string_as_number < 0 || string_as_number > 60000) {
        fprintf(stderr, "Invalid port number:  %li\n", string_as_number);
        return 1;
    }
    port = (unsigned short)string_as_number;

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(port);

    status = bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
    if (status != 0)
        my_log(ERROR, "system call", "bind", 0);
    if (listen(listenfd, 64) < 0)
        my_log(ERROR, "system call", "listen", 0);

    for (hit = 1; ; hit++) {
        socklen_t length;
        int socketfd;

        length = sizeof(cli_addr);
        socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &length);
        if (socketfd < 0)
            my_log(ERROR, "system call", "accept", 0);

        if ((pid = fork()) < 0) {
            my_log(ERROR, "system call", "fork", 0);
        } else {
            if (pid == 0) {
                close(listenfd);
                web(socketfd, hit);
            } else {
                close(socketfd);
            }
        }
    }
}
Beispiel #20
0
int mame_execute(emu_options &options, osd_interface &osd)
{
	bool firstgame = true;
	bool firstrun = true;

	// extract the verbose printing option
	if (options.verbose())
		print_verbose = true;

	// loop across multiple hard resets
	bool exit_pending = false;
	int error = MAMERR_NONE;

		// We need to preprocess the config files once to determine the web server's configuration
		if (options.read_config())
		{
			options.revert(OPTION_PRIORITY_INI);
			astring errors;
			options.parse_standard_inis(errors);
		}

	web_engine web(options);

	while (error == MAMERR_NONE && !exit_pending)
	{
		// if no driver, use the internal empty driver
		const game_driver *system = options.system();
		if (system == NULL)
		{
			system = &GAME_NAME(___empty);
			if (firstgame)
				started_empty = true;
		}

		firstgame = false;

		// parse any INI files as the first thing
		if (options.read_config())
		{
			options.revert(OPTION_PRIORITY_INI);
			astring errors;
			options.parse_standard_inis(errors);
		}
		// otherwise, perform validity checks before anything else
		if (system != NULL)
		{
			validity_checker valid(options);
			valid.check_shared_source(*system);
		}

		// create the machine configuration
		machine_config config(*system, options);

		// create the machine structure and driver
		running_machine machine(config, osd, started_empty);

		ui_show_mouse(machine.system().flags & GAME_CLICKABLE_ARTWORK);

		// looooong term: remove this
		global_machine = &machine;

		web.set_machine(machine);
		web.push_message("update_machine");
		// run the machine
		error = machine.run(firstrun);
		firstrun = false;

		// check the state of the machine
		if (machine.new_driver_pending())
		{
			options.set_system_name(machine.new_driver_name());
			firstrun = true;
		}
		if (machine.exit_pending())
			exit_pending = true;

		// machine will go away when we exit scope
		global_machine = NULL;
	}
	// return an error
	return error;
}
Beispiel #21
0
int main(int argc, char **argv)
{
	int i, port, pid, listenfd, socketfd, hit;
	size_t length;
	static struct sockaddr_in cli_addr; 
	static struct sockaddr_in serv_addr;

	(void)printf("Programe starting\n");

	if( argc < 3  || argc > 3 || !strcmp(argv[1], "-?") ) {
		(void)printf("usage: server [port] [server directory] &"
	"\tExample: server 80 ./ &\n\n"
	"\tOnly Supports:");
		for(i=0;extensions[i].ext != 0;i++)
			(void)printf(" %s",extensions[i].ext);

		(void)printf("\n\tNot Supported: directories / /etc /bin /lib /tmp /usr /dev /sbin \n"
		    );
		exit(0);
	}
	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) ){
		(void)printf("ERROR: Bad top directory %s, see server -?\n",argv[2]);
		exit(3);
	}
	if(chdir(argv[2]) == -1){ 
		(void)printf("ERROR: Can't Change to directory %s\n",argv[2]);
		exit(4);
	}

	if(fork() != 0)
		return 0; 
	(void)signal(SIGCHLD, SIG_IGN); 
	(void)signal(SIGHUP, SIG_IGN); 
	for(i=0;i<32;i++)
		(void)close(i);	
	(void)setpgrp();	

	log(LOG,"http server starting",argv[1],getpid());

	if((listenfd = socket(AF_INET, SOCK_STREAM,0)) <0)
		log(ERROR, "system call","socket",0);
	port = atoi(argv[1]);
	if(port < 0 || port >60000)
		log(ERROR,"Invalid port number try [1,60000]",argv[1],0);
	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)
		log(ERROR,"system call","bind",0);
	if( listen(listenfd,64) <0)
		log(ERROR,"system call","listen",0);

	for(hit=1; ;hit++) {
		length = sizeof(cli_addr);
		if((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &length)) < 0)
			log(ERROR,"system call","accept",0);

		if((pid = fork()) < 0) {
			log(ERROR,"system call","fork",0);
		}
		else {
			if(pid == 0) {
				(void)close(listenfd);
				web(socketfd,hit);
			} else {
				(void)close(socketfd);
			}
		}
	}
}
Beispiel #22
0
void Manga::downloadInformation()
{
	sf::Http web(MangaHost);
	
	sf::Http::Request request(m_uri);
	
	sf::Http::Response response = web.sendRequest(request);
	
	sf::Http::Response::Status status = response.getStatus();
	
	if (status == sf::Http::Response::Ok)
	{
		//std::cout<<"Link is valid\n";
		
		std::string body(response.getBody());
		
		//Erase all of the \n
		eraseN(body);
		
		if (testing)
		{
			if (!directoryExists("test"))
				createDirectory("test");
			
			FILE* f = fopen("test/body.html", "w");
			fwrite(body.c_str(), sizeof(char), body.size(), f);
			fclose(f);
			
			std::cout<<"Html page output to file: test/body.html\n";
			
		}
		
		//Start parsing
		m_name = getParse(body, parseMangaName);
		
		//Supress all white spaces at the end of the name!!
		
		for (int i(m_name.size()-1); i>=0; --i)
		{
			if (m_name[i] == ' ')
				m_name.resize(i);
			else
				break;
		}
		
		
		std::string last_chapter(getParse(body, parseChapters));
		sscanf(last_chapter.c_str(), "%u", &m_num_chapters);
		
		if (testing)
			std::cout<<"Name parsed: "<<m_name<<".\nChapter count parsed: "<<last_chapter<<"\n";
		if (!testing)
		{
			if (!directoryExists("mangas"))
				createDirectory("mangas");
			
			if (!directoryExists("mangas/" + m_name))
				createDirectory("mangas/" + m_name);
		}
		
		
		if (m_cover != NULL)
			delete m_cover;
		m_cover = new Image(getParse(body, parseCover), "mangas/" + m_name + "/");
		
		if (!testing)
			m_cover->thDownload();
		else
			std::cout<<"Cover parsed: "<<m_cover->getUrl()<<"\n";
		
		m_loaded = true;
		
		
		//Fill list of chapters
		sf::Clock clock;
		size_t first(0);
		std::string chapter_web_list(getParse(body, parseChapterList));
		//erase all the \n!!
		eraseN(chapter_web_list);
		
		if (testing)
		{
			FILE* f = fopen("test/chapter_list.html", "w");
			fwrite(chapter_web_list.c_str(), sizeof(char), chapter_web_list.size(), f);
			fclose(f);
			
			std::cout<<"Html page output to file: test/chapter_list.html\n";
			
		}
		
		unsigned int chapter_i(1);
		
		while(true)
		{
			first = chapter_web_list.find(parseChapterListElement.begin[0], first);
			if (first == chapter_web_list.npos)
				break;
			else
				first += parseChapterListElement.begin[0].size();
			
			std::string chapter_url, chapter_name(getParse(chapter_web_list.substr(first), Manga::parseChapterListName));
			switch (Manga::chapterPath) {
				case URL_uri:
					chapter_url = getParse(chapter_web_list.substr(first), parseChapterListUri);
					break;
					
				case URL_absolute:
					//std::cout<<getParse(chapter_web_list.substr(first), parseChapterListUri)<<" tachan!\n";
					chapter_url = getUri(getParse(chapter_web_list.substr(first), parseChapterListUri));
					break;
					
				case URL_relative:
					chapter_url = getWorkingDirectory(m_uri) + getParse(chapter_web_list.substr(first), parseChapterListUri);
					break;
					
				default:
					break;
			}
			m_chapters.push_back(Chapter(chapter_url, this, chapter_i, chapter_name));
			
			//std::cout<<"Added chapter: "<<m_chapters.back()<<"\n";
			++chapter_i;
			
		}
		
		if (Manga::chapterListReversed) // reverse the chapter list
		{
			m_chapters.reverse();
			chapter_i = 1;
			
			for (std::list<Chapter>::iterator it(m_chapters.begin()); it != m_chapters.end(); ++it)
			{
				it->setChapter(chapter_i);
				++chapter_i;
			}
		}
		
		if (testing)
		{
			std::cout<<m_chapters.size()<<" chapters were parsed\n";
			
			for (std::list<Chapter>::iterator it(m_chapters.begin()); it != m_chapters.end(); ++it)
				std::cout<<"Chapter "<<it->m_num_chapter<<" parsed: "<<it->m_name<<" at "<<it->m_uri<<"\n";
		}
		
		//std::cout<<"Chapter list created in: "<<clock.getElapsedTime().asSeconds()<<" sec\n";
		
	}
	else
		std::cout<<"Error downloading manga info: "<<status<<"\n";
}