Example #1
0
bool Lounge::createRoom(std::shared_ptr<
                        TBSystem::network::sockets::ITcpSocket>& socket,
                        std::string params, int playerId)
{
    std::string err;
    bool hasErr = false;

    if (std::find_if(_clients.begin(), _clients.end(), [playerId](Client& p) {
    return p.getId() == playerId;
    })->isInRoom()) {
        err = "Your are already in a room\r\n";
        log::debug << "MAIS iH " << err << log::endl;
        hasErr = true;
    }
    if (_rooms.size() > 50) {
        err = "err to much room already exist, try later\r\n";
        log::debug << "MAIS aH " << err << log::endl;
        hasErr = true;
    }
    if (hasErr == true) {
        log::debug << "MAIS OH " << err << log::endl;
        socket->send(err.c_str(), err.size());
        return true;
    }
    log::debug << "hello" << log::endl;
    _rooms.emplace_back(4, *this);

    std::string rep("rep join " + std::to_string(_rooms.back().getId())
                    + "\r\n");
    movePlayerToRoom(playerId, _rooms.back().getId());
    socket->send(rep.c_str(), rep.size());
    sendRoomlistGlobally();
    return true;
}
Example #2
0
bool Lounge::sendRoomDetails(std::shared_ptr<
                             TBSystem::network::sockets::ITcpSocket>& socket,
                             std::string params) const
{
    std::stringstream ss(params);
    std::string junk;
    int id = -1;

    // drop command
    ss >> junk;
    // get the room asked id
    ss >> id;
    log::debug << "les animations de thibault c'est de la merde = " << id << log::endl;
    auto room = std::find_if(_rooms.begin(), _rooms.end(),
    [id](const Room& room) -> bool {
        return id == room.getId();
    });
    if (room != _rooms.end()) {
        std::string ret("rep room_details " + std::to_string(id) + " start\r\n");

        std::vector<std::string> vec = room->playersStateStrings();
        for (auto& p : vec) {
            ret += "rep room_details " + std::to_string(id) + " player " + p + "\r\n";
        }
        ret += "rep room_details " + std::to_string(id) + " end\r\n";
        socket->send(ret.c_str(), ret.size());
    }
    else {
        std::string error("err no such room\r\n");

        socket->send(error.c_str(), error.size());
    }
    return true;
}
Example #3
0
    virtual bool exec(RClient *rc, const std::shared_ptr<Connection> &connection) override
    {
        bool escape = false;
        switch (rc->mEscapeMode) {
        case RClient::Escape_Auto:
            escape = (escapeMode == RClient::Escape_Do);
            break;
        case RClient::Escape_Do:
            escape = true;
            break;
        case RClient::Escape_Dont:
            escape = false;
            break;
        }
        IndexMessage msg;
        msg.init(rc->argc(), rc->argv());
        msg.setWorkingDirectory(cwd);
        msg.setFlag(IndexMessage::Escape, escape);
        msg.setFlag(IndexMessage::GuessFlags, rc->mGuessFlags);
        msg.setArguments(args);
        msg.setCompilationDatabaseDir(compilationDatabaseDir);
        msg.setPathEnvironment(rc->pathEnvironment());
        if (!rc->projectRoot().isEmpty())
            msg.setProjectRoot(rc->projectRoot());

        return connection->send(msg);
    }
Example #4
0
 void send_2p( char* buf_, size_t n )
 {
     if( connection_2p )
     {
         connection_2p->send( buf_, n, 0 );
     }
 }
Example #5
0
 void send_2p()
 {
     if( connection_2p )
     {
         connection_2p->send( "\0", 1, 0 );
     }
 }
Example #6
0
 void send_1p()
 {
     if( connection_1p )
     {
         connection_1p->send( "\0", 1, 0 );
     }
 }
	// Implement echo
	virtual bool handler(std::shared_ptr<IComms> comms)
	{
std::cerr << "<TEST> handler - START" << std::endl;

		while (comms->isOpen())
		{
			TimeUtils::msSleep(200) ;
			if (!comms->isOpen())
				break ;

			std::string rx ;
			std::cerr << "<TEST> handler - Receive..." << std::endl;
			if (!comms->receive(rx))
				break ;

			// echo back
			if (!rx.empty())
			{
				std::cerr << "<TEST> handler - Echo" << std::endl;
				comms->send(rx) ;
			}
		}

std::cerr << "<TEST> handler - END" << std::endl;
		return false ;
	}
Example #8
0
void Service::process(std::shared_ptr<Channel>c, const std::string &message)
{
	Json::Value root;
	Json::Reader reader;
	
	if(! reader.parse(message, root)) {
		c->send("{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32700, \"message\": \"Parse error\"}, \"id\": null}");
		return;
	}

	if(root.isArray() && root.size() == 0) {
		c->send("{\"jsonrpc\": \"2.0\", \"error\": {\"code\": -32600, \"message\": \"Invalid Request\"}, \"id\": null}");
		return;
	}


	auto request = new Request(root.isArray());
	_channels[request] = c;

	if(root.isArray()) {
		for (auto entry: root) {
			process_single_entry(*request, entry);
		}
	}
	else if (root.isObject()) {
		process_single_entry(*request, root);
	}

	/* Do nothing if there is nothing to return */
	if (request->empty()) {
		/* TODO: somehow signal this condition
		   to HTTP-like transports */
		clean_up(request);
		return;
	}

	/* If all results have been set by now
	   call completion handler, otherwise
	   set up a event listener */
	if (request->completed()) {
		on_request_completed(request);
	} else {
		request->signal_completed.connect(
			boost::bind(&Service::on_request_completed, this, request)
		);
	}
}
Example #9
0
 virtual bool exec(RClient *rc, const std::shared_ptr<Connection> &connection) override
 {
     unsigned int flags = RTagsLogOutput::None;
     if (rc->queryFlags() & QueryMessage::Elisp)
         flags |= RTagsLogOutput::Elisp;
     const LogLevel level = mLevel == Default ? rc->logLevel() : mLevel;
     LogOutputMessage msg(level, flags);
     msg.init(rc->argc(), rc->argv());
     return connection->send(msg);
 }
Example #10
0
void FileServerRequestHandler::preprocessAdminFile(const HTTPRequest& request,const std::shared_ptr<StreamSocket>& socket)
{
    Poco::Net::HTTPResponse response;

    if (!LOOLWSD::AdminEnabled)
        throw Poco::FileAccessDeniedException("Admin console disabled");

    if (!FileServerRequestHandler::isAdminLoggedIn(request, response))
        throw Poco::Net::NotAuthenticatedException("Invalid admin login");

    static const std::string scriptJS("<script src=\"%s/loleaflet/" LOOLWSD_VERSION_HASH "/%s.js\"></script>");
    static const std::string footerPage("<div class=\"footer navbar-fixed-bottom text-info text-center\"><strong>Key:</strong> %s &nbsp;&nbsp;<strong>Expiry Date:</strong> %s</div>");

    const std::string relPath = getRequestPathname(request);
    LOG_DBG("Preprocessing file: " << relPath);
    std::string adminFile = *getUncompressedFile(relPath);
    std::string brandJS(Poco::format(scriptJS, LOOLWSD::ServiceRoot, std::string(BRANDING)));
    std::string brandFooter;

#if ENABLE_SUPPORT_KEY
    const auto& config = Application::instance().config();
    const std::string keyString = config.getString("support_key", "");
    SupportKey key(keyString);

    if (!key.verify() || key.validDaysRemaining() <= 0)
    {
        brandJS = Poco::format(scriptJS, std::string(BRANDING_UNSUPPORTED));
        brandFooter = Poco::format(footerPage, key.data(), Poco::DateTimeFormatter::format(key.expiry(), Poco::DateTimeFormat::RFC822_FORMAT));
    }
#endif

    Poco::replaceInPlace(adminFile, std::string("<!--%BRANDING_JS%-->"), brandJS);
    Poco::replaceInPlace(adminFile, std::string("<!--%FOOTER%-->"), brandFooter);
    Poco::replaceInPlace(adminFile, std::string("%VERSION%"), std::string(LOOLWSD_VERSION_HASH));
    Poco::replaceInPlace(adminFile, std::string("%SERVICE_ROOT%"), LOOLWSD::ServiceRoot);

    // Ask UAs to block if they detect any XSS attempt
    response.add("X-XSS-Protection", "1; mode=block");
    // No referrer-policy
    response.add("Referrer-Policy", "no-referrer");
    response.add("X-Content-Type-Options", "nosniff");
    response.set("User-Agent", HTTP_AGENT_STRING);
    response.set("Date", Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT));

    response.setContentType("text/html");
    response.setChunkedTransferEncoding(false);

    std::ostringstream oss;
    response.write(oss);
    oss << adminFile;
    socket->send(oss.str());
}
Example #11
0
Sluift::Response SluiftClient::doSendRequest(std::shared_ptr<Request> request, int timeout) {
    requestResponse.reset();
    requestError.reset();
    requestResponseReceived = false;
    request->send();

    Watchdog watchdog(timeout, networkFactories->getTimerFactory());
    while (!watchdog.getTimedOut() && !requestResponseReceived) {
        eventLoop->runUntilEvents();
    }
    return Sluift::Response(requestResponse, watchdog.getTimedOut() ?
            std::make_shared<ErrorPayload>(ErrorPayload::RemoteServerTimeout) : requestError);
}
Example #12
0
void client_work(std::shared_ptr<Socket> client)
{
    client->setRcvTimeout(/*sec*/30, /*microsec*/0);
    while (true) try
    {
        std::string line = client->recv();
        client->send("echo: " + line + "\n");
    }
    catch(const std::exception &e)
    {
        std::cerr << "exception: " << e.what() << std::endl;
        return;
    }
}
bool ExceptionEncounteredSenderTest::testExceptionEncounteredSucceeds(
    const std::string& unparsedDirective,
    avs::ExceptionErrorType error,
    const std::string& errorDescription) {
    bool done = false;
    m_exceptionEncounteredEvent =
        std::make_shared<ExceptionEncounteredEvent>(unparsedDirective, error, errorDescription);

    EXPECT_CALL(*m_mockMessageSender, sendMessage(_))
        .WillOnce(Invoke(m_exceptionEncounteredEvent.get(), &ExceptionEncounteredEvent::verifyMessage));
    m_exceptionEncounteredEvent->send(m_exceptionEncounteredSender);
    done = true;
    return done;
}
Example #14
0
 virtual bool exec(RClient *rc, const std::shared_ptr<Connection> &connection) override
 {
     QueryMessage msg(type);
     msg.init(rc->argc(), rc->argv());
     msg.setQuery(query);
     msg.setBuildIndex(rc->buildIndex());
     msg.setUnsavedFiles(rc->unsavedFiles());
     msg.setFlags(extraQueryFlags | rc->queryFlags());
     msg.setMax(rc->max());
     msg.setPathFilters(rc->pathFilters());
     msg.setKindFilters(rc->kindFilters());
     msg.setRangeFilter(rc->minOffset(), rc->maxOffset());
     msg.setCurrentFile(rc->currentFile());
     return connection->send(msg);
 }
Example #15
0
bool Lounge::sendRoomlist(std::shared_ptr<
                          TBSystem::network::sockets::ITcpSocket>& socket,
                          std::string params) const
{
    std::string ret;

    ret  = "rep roomlist start\r\n";
    for (auto& r : _rooms) {
        if (!r.isInGame()) {
            ret += "rep roomlist room " + r.toString() + "\r\n";
        }
    }
    ret += "rep roomlist end\r\n";
    socket->send(ret.c_str(), ret.size());
    return true;
}
Example #16
0
static Future<Nothing> _send(
    const std::shared_ptr<SocketImpl>& impl,
    Owned<string> data,
    size_t index,
    size_t length)
{
  // Increment the index into the data.
  index += length;

  // Check if we've sent all of the data.
  if (index == data->size()) {
    return Nothing();
  }

  // Keep sending!
  return impl->send(data->data() + index, data->size() - index)
    .then(lambda::bind(&_send, impl, data, index, lambda::_1));
}
Example #17
0
void FileServerRequestHandler::sendError(int errorCode, const Poco::Net::HTTPRequest& request,
                                         const std::shared_ptr<StreamSocket>& socket,
                                         const std::string& shortMessage, const std::string& longMessage,
                                         const std::string& extraHeader)
{
    Poco::URI requestUri(request.getURI());
    const std::string& path = requestUri.getPath();
    std::ostringstream oss;
    oss << "HTTP/1.1 " << errorCode << "\r\n"
        << "Content-Type: text/html charset=UTF-8\r\n"
        << "Date: " << Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT) << "\r\n"
        << "User-Agent: " << WOPI_AGENT_STRING << "\r\n"
        << extraHeader
        << "\r\n";
    if (!shortMessage.empty())
    {
        oss << "<h1>Error: " << shortMessage << "</h1>"
            << "<p>" << longMessage << " " << path << "</p>"
            << "<p>Please contact your system administrator.</p>";
    }
    socket->send(oss.str());
}
Example #18
0
bool App::sendAck(std::shared_ptr<zmq::socket_t> socket)
{
    uint8_t ack = 1;
    zmq::message_t msg(&ack, sizeof(uint8_t));
    return socket->send(msg);
}
Example #19
0
void MiniWebServer::accepted(std::shared_ptr<Socket> psock, long long connectionId) {
    char buf[4096];
    int len = 0;
    try {
#ifdef MONGO_CONFIG_SSL
        psock->doSSLHandshake();
#endif
        psock->setTimeout(8);
        while (1) {
            int left = sizeof(buf) - 1 - len;
            if (left == 0)
                break;
            int x;
            try {
                x = psock->unsafe_recv(buf + len, left);
            } catch (const SocketException&) {
                psock->close();
                return;
            }
            len += x;
            buf[len] = 0;
            if (fullReceive(buf)) {
                break;
            }
        }
    } catch (const SocketException& e) {
        LOG(1) << "couldn't recv data via http client: " << e << endl;
        return;
    }
    buf[len] = 0;

    string responseMsg;
    int responseCode = 599;
    vector<string> headers;

    try {
        doRequest(buf, parseURL(buf), responseMsg, responseCode, headers, psock->remoteAddr());
    } catch (std::exception& e) {
        responseCode = 500;
        responseMsg = "error loading page: ";
        responseMsg += e.what();
    } catch (...) {
        responseCode = 500;
        responseMsg = "unknown error loading page";
    }

    stringstream ss;
    ss << "HTTP/1.0 " << responseCode;
    if (responseCode == 200)
        ss << " OK";
    ss << "\r\n";
    if (headers.empty()) {
        ss << "Content-Type: text/html\r\n";
    } else {
        for (vector<string>::iterator i = headers.begin(); i != headers.end(); i++) {
            verify(strncmp("Content-Length", i->c_str(), 14));
            ss << *i << "\r\n";
        }
    }
    ss << "Connection: close\r\n";
    ss << "Content-Length: " << responseMsg.size() << "\r\n";
    ss << "\r\n";
    ss << responseMsg;
    string response = ss.str();

    try {
        psock->send(response.c_str(), response.size(), "http response");
        psock->close();
    } catch (SocketException& e) {
        LOG(1) << "couldn't send data to http client: " << e << endl;
    }
}
Example #20
0
	virtual void run() {

		for(;;) {

			auto commands = socket->read();
			auto cmd = commands.at(0);
	
			logger->info("processing request: " + cmd);
	
			if (cmd == "getTemplates") {
				for (auto& kv : controller->getTemplates())
					socket->write(kv.second->serialize());
			}
	
			else if (cmd == "getInstances") {
				if (controller->getInstances().size() == 0)
					socket->write("");
				else
					for (auto& kv : controller->getInstances())
						socket->write(kv.second->getInstanceInfo()->serialize());
			}
	
			else if (cmd == "instantiate") {

				auto inst = Vm::InstanceInfo::deserialize(vector<string>(commands.begin()+1, commands.end()));
				auto tmpls = controller->getTemplates();
	
				try {
	
					auto tmplName = inst->getTemplate();
	
					if (tmpls.find(tmplName) == tmpls.end()) {
						// template not found
						logger->warn("non-existent template " + tmplName + " instantiation required");
						socket->write(inst->serialize());
					} else {
						auto tmpl = tmpls[tmplName];
						auto realInst = controller->instantiate(tmpl, inst->getMemory(), inst->getCpus());
						// controller->run(realInst->getId());
						socket->write(realInst->getInstanceInfo()->serialize());
					}
	
				} catch(...) {
					// invalid arguments
					socket->write(inst->serialize());
				}
			}

			else if (cmd == "run") {

				bool result = false;

				try { result = controller->run(stoi(commands[1])); }
				catch (...) { }

				socket->write(to_string((int)result));
			}

			else if (cmd == "kill") {

				bool result = false;

				try { result = controller->kill(stoi(commands[1])); }
				catch (...) { }

				socket->write(to_string((int)result));
			}
	
			else {
				socket->write("unknown command");
			}

			socket->send();
		}
	}
	void test_block_solver () {
		if (!process_messenger) process_messenger.reset (new mpi::messenger ());	

		int timesteps = 1;
		int id = process_messenger->get_id ();
		int np = process_messenger->get_np ();
		int n = 10, nrhs = 10, ntop = 0, nbot = 0;
		if (id != 0) {
			ntop = 1;
		}
		if (id != np - 1) {
			nbot = 1;
		}
		int lda = n + ntop + nbot, ldx = 0, ldb = lda;
	
		std::vector <int> ns (process_messenger->get_np ());
		process_messenger->gather <int> (1, &ntop, &ns [0]);
		if (process_messenger->get_id () == 0) {
			for (int i = 0; i < process_messenger->get_np (); ++i) {
				ldx += ns [i];
			}
		} else {
			ldx = ntop + nbot;
		}
		
		std::vector <double> bufftop (ntop * nrhs), buffbot (nbot * nrhs), rbufftop (ntop * nrhs), rbuffbot (nbot * nrhs);
	
		std::vector <double> a (lda * lda), acopy (lda * lda);
		std::vector <double> b (lda * nrhs), bcopy (lda * nrhs);
		std::vector <int> ipiv (lda);
		std::vector <double> x (ldx * ldx);
		std::vector <int> xipiv (ldx);
		int info;
	
		srand (2);
	
		for (int i = 0; i < lda; ++i) {
			for (int j = 0; j < lda; ++j) {
				a [j * lda + i] = rand () % 100;
			}
			for (int j = 0; j < nrhs; ++j) {
				b [j * ldb + i] = rand () % 100;
				bcopy [j * ldb + i] = b [j * ldb + i];
			}
		}
	
		linalg::matrix_copy (lda, lda, &a [0], &acopy [0], lda, lda);
	
		// clock_t corig_begin, corig_end;
		// std::chrono::time_point <std::chrono::system_clock> orig_begin, orig_end;
	
		// corig_begin = clock ();
		// orig_begin = std::chrono::system_clock::now ();
	
		linalg::matrix_factorize (n, n, &a [0], &ipiv [0], &info, lda);
		linalg::matrix_solve (n, &a [0], &ipiv [0], &b [0], &info, nrhs, lda, ldb);
	
		// corig_end = clock ();
		// orig_end = std::chrono::system_clock::now ();
	
		// std::chrono::duration <double> orig_total = orig_end - orig_begin;
	
		// printf ("[%i] Orig CPU Time: %f\n", id, ((double) (corig_end - corig_begin))/CLOCKS_PER_SEC);
		// printf ("[%i] Orig Wall Time: %f\n", id, (double) orig_total.count ());
	
		// clock_t cbegin, cmid, cend;
		// std::chrono::time_point <std::chrono::system_clock> begin, mid, end;
	
		// std::chrono::duration <double> mb, em, eb;
		// double cmb = 0.0, cem = 0.0, ceb = 0.0;
	
		for (int i = 0; i < timesteps; ++i) {
			for (int i = 0; i < lda; ++i) {
				for (int j = 0; j < lda; ++j) {
					a [j * lda + i] = rand () % 100;
					acopy [j * lda + i] = a [j * lda + i];
				}
				for (int j = 0; j < nrhs; ++j) {
					b [j * ldb + i] = rand () % 100;
					bcopy [j * ldb + i] = b [j * ldb + i];
				}
			}
			
			// cbegin = clock ();
			// begin = std::chrono::system_clock::now ();
		
			linalg::block::matrix_factorize (process_messenger->get_id (), process_messenger->get_np (), n, ntop, nbot, &a [0], &ipiv [0], &x [0], &xipiv [0], &ns [0], &info, lda, ldx);
	
			// cmid = clock ();
			// mid = std::chrono::system_clock::now ();
		
			// mb += mid - begin;
			// cmb += cmid - cbegin;
		
			linalg::block::matrix_solve (process_messenger->get_id (), process_messenger->get_np (), n, ntop, nbot, &a [0], &ipiv [0], &b [0], &x [0], &xipiv [0], &ns [0], &info, nrhs, lda, ldx, ldb);
	
			// cend = clock ();
			// end = std::chrono::system_clock::now ();
		
			// em += end - mid;
			// eb += end - begin;
			// cem += cend - cmid;
			// ceb += cend - cbegin;
			
			linalg::matrix_matrix_multiply (n + ntop + nbot, nrhs, n + ntop + nbot, 1.0, &acopy [0], &b [0], -1.0, &bcopy [0]);
			
			if (id != 0) {
				linalg::matrix_copy (ntop, nrhs, &bcopy [0], &bufftop [0], ldb, ntop);
				process_messenger->send (ntop * nrhs, &bufftop [0], id - 1, 0);
			}
			if (id != np - 1) {
				linalg::matrix_copy (nbot, nrhs, &bcopy [n + ntop], &buffbot [0], ldb, nbot);
				process_messenger->recv (nbot * nrhs, &rbuffbot [0], id + 1, 0);
				process_messenger->send (nbot * nrhs, &buffbot [0], id + 1, 1);
				linalg::matrix_add_scaled (nbot, nrhs, 1.0, &rbuffbot [0], &bcopy [n + ntop], nbot, ldb);
			}
			if (id != 0) {
				process_messenger->recv (ntop * nrhs, &rbufftop [0], id - 1, 1);
				linalg::matrix_add_scaled (ntop, nrhs, 1.0, &rbufftop [0], &bcopy [0], ntop, ldb);
			}
			
			for (int i = 0; i < n + ntop + nbot; ++i) {
				for (int j = 0; j < nrhs; ++j) {
					TSM_ASSERT_DELTA ("Block solver failure", bcopy [j * ldb + i], 0.0, TEST_TINY);
				}
			}
		}
	
		// printf ("[%i] Avg CPU Time: %f + %f = %f\n", id, ((double) (cmb))/CLOCKS_PER_SEC/timesteps, ((double) (cem))/CLOCKS_PER_SEC/timesteps, ((double) (ceb))/CLOCKS_PER_SEC/timesteps);
		// printf ("[%i] Avg Wall Time: %f + %f = %f\n", id, (double) mb.count ()/timesteps, (double) em.count ()/timesteps, (double) eb.count ()/timesteps);
	}
	void test_block_tridiagonal_solve () {
		// io::parameters <double> params ("../input/block_parameters.txt");
		// omp_set_num_threads(params.nmp);

		int id = process_messenger->get_id ();
		int np = process_messenger->get_np ();
		int n = 60, nrhs = 70, ntop = 0, nbot = 0;
		if (id != 0) {
			ntop = 1;
		}
		if (id != np - 1) {
			nbot = 1;
		}

		std::vector <double> sub (n * nrhs, 0.0);
		std::vector <double> diag (n * nrhs, 0.0);
		std::vector <double> sup (n * nrhs, 0.0);
		std::vector <double> subcopy (n * nrhs, 0.0);
		std::vector <double> diagcopy (n * nrhs, 0.0);
		std::vector <double> supcopy (n * nrhs, 0.0);
		std::vector <double> supsup (n * nrhs, 0.0);
		std::vector <int> ipiv (n * nrhs, 0);

		std::vector <double> x (2 * n * nrhs + 8 * np * nrhs, 0.0);
		std::vector <int> xipiv (2 * np * nrhs, 0);

		std::vector <double> b (n * nrhs, 0.0);
		std::vector <double> bcopy (n * nrhs, 0.0);

		int info;

		srand (1);
		for (int i = 0; i < nrhs; ++i) {
			for (int j = 0; j < n; ++j) {
				sub [i * n + j] = rand () % 100;
				subcopy [i * n + j] = sub [i * n + j];
				diag [i * n + j] = rand () % 100;
				diagcopy [i * n + j] = diag [i * n + j];
				sup [i * n + j] = rand () % 100;
				supcopy [i * n + j] = sup [i * n + j];
				b [i * n + j] = rand () % 100;
				bcopy [i * n + j] = b [i * n + j];
			}
		}
		
		try {
			linalg::block::tridiag_factorize (id, np, n - ntop - nbot, &sub [0], &diag [0], &sup [0], &supsup [0], &ipiv [0], &x [0], &xipiv [0], &info, nrhs);

			linalg::block::tridiag_solve (id, np, n - ntop - nbot,  &sub [0], &diag [0], &sup [0], &supsup [0], &ipiv [0], &b [0], &x [0], &xipiv [0], &info, nrhs);
		} catch (std::exception& except) {
			std::cout << except.what () << '\n';
		}

		for (int j = 0; j < nrhs; ++j) {
			bcopy [j * n] -= diagcopy [j * n] * b [j * n] + supcopy [j * n] * b [1 + j * n];
			for (int i = 1; i < n - 1; ++i) {
				bcopy [i + j * n] -= subcopy [i + j * n] * b [i - 1 + j * n] + diagcopy [i + j * n] * b [i + j * n] + supcopy [i + j * n] * b [i + 1 + j * n];
			}
			bcopy [n - 1 + j * n] -= subcopy [n - 1 + j * n] * b [n - 2 + j * n] + diagcopy [n - 1 + j * n] * b [n - 1 + j * n];
		}
	
		std::vector <double> edge_0 (nrhs), edge_n (nrhs), redge_0 (nrhs), redge_n (nrhs);
	
		for (int i = 0; i < nrhs; ++i) {
			edge_0 [i] = b [i * n];
			edge_n [i] = b [i * n + n - 1];
		}

		if (id != 0) {
			process_messenger->send (nrhs, &edge_0 [0], id - 1, 0);
		}
		if (id != np - 1) {
			process_messenger->recv (nrhs, &redge_n [0], id + 1, 0);
			for (int i = 0; i < nrhs; ++i) {
				bcopy [i * n + n - 1] -= supcopy [i * n + n - 1] * redge_n [i];
			}
		}
		if (id != np - 1) {
			process_messenger->send (nrhs, &edge_n [0], id + 1, 1);
		}
		if (id != 0) {
			process_messenger->recv (nrhs, &redge_0 [0], id - 1, 1);
			for (int i = 0; i < nrhs; ++i) {
				bcopy [i * n] -= subcopy [i * n] * redge_0 [i];
			}
		}
		
		for (int i = 0; i < n; ++i) {
			for (int j = 0; j < nrhs; ++j) {
				TSM_ASSERT_DELTA ("Tridiagonal block solver failure", bcopy [j * n + i], 0.0, TEST_TINY);
			}
		}
	}
Example #23
0
void FileServerRequestHandler::handleRequest(const HTTPRequest& request, Poco::MemoryInputStream& message,
                                             const std::shared_ptr<StreamSocket>& socket)
{
    try
    {
        bool noCache = false;
#if ENABLE_DEBUG
        noCache = true;
#endif
        Poco::Net::HTTPResponse response;
        Poco::URI requestUri(request.getURI());
        LOG_TRC("Fileserver request: " << requestUri.toString());
        requestUri.normalize(); // avoid .'s and ..'s

        std::string path(requestUri.getPath());
        if (path.find("loleaflet/" LOOLWSD_VERSION_HASH "/") == std::string::npos)
        {
            LOG_WRN("client - server version mismatch, disabling browser cache.");
            noCache = true;
        }

        std::vector<std::string> requestSegments;
        requestUri.getPathSegments(requestSegments);
        const std::string relPath = getRequestPathname(request);
        // Is this a file we read at startup - if not; its not for serving.
        if (requestSegments.size() < 1 || FileHash.find(relPath) == FileHash.end())
            throw Poco::FileNotFoundException("Invalid URI request: [" + requestUri.toString() + "].");

        const auto& config = Application::instance().config();
        const std::string loleafletHtml = config.getString("loleaflet_html", "loleaflet.html");
        const std::string endPoint = requestSegments[requestSegments.size() - 1];
        if (endPoint == loleafletHtml)
        {
            preprocessFile(request, message, socket);
            return;
        }

        if (request.getMethod() == HTTPRequest::HTTP_GET)
        {
            if (endPoint == "admin.html" ||
                endPoint == "adminSettings.html" ||
                endPoint == "adminHistory.html" ||
                endPoint == "adminAnalytics.html")
            {
                preprocessAdminFile(request, socket);
                return;
            }

            if (endPoint == "admin-bundle.js" ||
                endPoint == "admin-localizations.js")
            {
                noCache = true;

                if (!LOOLWSD::AdminEnabled)
                    throw Poco::FileAccessDeniedException("Admin console disabled");

                if (!FileServerRequestHandler::isAdminLoggedIn(request, response))
                    throw Poco::Net::NotAuthenticatedException("Invalid admin login");

                // Ask UAs to block if they detect any XSS attempt
                response.add("X-XSS-Protection", "1; mode=block");
                // No referrer-policy
                response.add("Referrer-Policy", "no-referrer");
            }

            // Do we have an extension.
            const std::size_t extPoint = endPoint.find_last_of('.');
            if (extPoint == std::string::npos)
                throw Poco::FileNotFoundException("Invalid file.");

            const std::string fileType = endPoint.substr(extPoint + 1);
            std::string mimeType;
            if (fileType == "js")
                mimeType = "application/javascript";
            else if (fileType == "css")
                mimeType = "text/css";
            else if (fileType == "html")
                mimeType = "text/html";
            else if (fileType == "png")
                mimeType = "image/png";
            else if (fileType == "svg")
                mimeType = "image/svg+xml";
            else
                mimeType = "text/plain";

            auto it = request.find("If-None-Match");
            if (it != request.end())
            {
                // if ETags match avoid re-sending the file.
                if (!noCache && it->second == "\"" LOOLWSD_VERSION_HASH "\"")
                {
                    // TESTME: harder ... - do we even want ETag support ?
                    std::ostringstream oss;
                    Poco::DateTime now;
                    Poco::DateTime later(now.utcTime(), int64_t(1000)*1000 * 60 * 60 * 24 * 128);
                    oss << "HTTP/1.1 304 Not Modified\r\n"
                        << "Date: " << Poco::DateTimeFormatter::format(
                            now, Poco::DateTimeFormat::HTTP_FORMAT) << "\r\n"
                        << "Expires: " << Poco::DateTimeFormatter::format(
                            later, Poco::DateTimeFormat::HTTP_FORMAT) << "\r\n"
                        << "User-Agent: " << WOPI_AGENT_STRING << "\r\n"
                        << "Cache-Control: max-age=11059200\r\n"
                        << "\r\n";
                    socket->send(oss.str());
                    socket->shutdown();
                    return;
                }
            }

            response.set("User-Agent", HTTP_AGENT_STRING);
            response.set("Date", Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT));

            bool gzip = request.hasToken("Accept-Encoding", "gzip");
            const std::string *content;
#if ENABLE_DEBUG
            if (std::getenv("LOOL_SERVE_FROM_FS"))
            {
                // Useful to not serve from memory sometimes especially during loleaflet development
                // Avoids having to restart loolwsd everytime you make a change in loleaflet
                const std::string filePath = Poco::Path(LOOLWSD::FileServerRoot, relPath).absolute().toString();
                HttpHelper::sendFile(socket, filePath, mimeType, response, noCache);
                return;
            }
#endif
            if (gzip)
            {
                response.set("Content-Encoding", "gzip");
                content = getCompressedFile(relPath);
            }
            else
                content = getUncompressedFile(relPath);

            if (!noCache)
            {
                // 60 * 60 * 24 * 128 (days) = 11059200
                response.set("Cache-Control", "max-age=11059200");
                response.set("ETag", "\"" LOOLWSD_VERSION_HASH "\"");
            }
            response.setContentType(mimeType);
            response.add("X-Content-Type-Options", "nosniff");

            std::ostringstream oss;
            response.write(oss);
            const std::string header = oss.str();
            LOG_TRC("#" << socket->getFD() << ": Sending " <<
                    (!gzip ? "un":"") << "compressed : file [" << relPath << "]: " << header);
            socket->send(header);
            socket->send(*content);
        }
    }
    catch (const Poco::Net::NotAuthenticatedException& exc)
    {
        LOG_ERR("FileServerRequestHandler::NotAuthenticated: " << exc.displayText());
        sendError(401, request, socket, "", "", "WWW-authenticate: Basic realm=\"online\"\r\n");
    }
    catch (const Poco::FileAccessDeniedException& exc)
    {
        LOG_ERR("FileServerRequestHandler: " << exc.displayText());
        sendError(403, request, socket, "403 - Access denied!",
                  "You are unable to access");
    }
    catch (const Poco::FileNotFoundException& exc)
    {
        LOG_WRN("FileServerRequestHandler: " << exc.displayText());
        sendError(404, request, socket, "404 - file not found!",
                  "There seems to be a problem locating");
    }
}
Example #24
0
 virtual bool exec(RClient *, const std::shared_ptr<Connection> &connection) override
 {
     const QuitMessage msg(mExitCode);
     return connection->send(msg);
 }
Example #25
0
	/** Sends the response to the client. */
	void send() {
		m_response->type(m_content_type);
		m_response->status(m_status);
		m_response->send(m_body.str());
	}
Example #26
0
void FileServerRequestHandler::preprocessFile(const HTTPRequest& request, Poco::MemoryInputStream& message, const std::shared_ptr<StreamSocket>& socket)
{
    const auto host = ((LOOLWSD::isSSLEnabled() || LOOLWSD::isSSLTermination()) ? "wss://" : "ws://") + (LOOLWSD::ServerName.empty() ? request.getHost() : LOOLWSD::ServerName);
    const Poco::URI::QueryParameters params = Poco::URI(request.getURI()).getQueryParameters();

    // Is this a file we read at startup - if not; its not for serving.
    const std::string relPath = getRequestPathname(request);
    LOG_DBG("Preprocessing file: " << relPath);
    std::string preprocess = *getUncompressedFile(relPath);

    HTMLForm form(request, message);
    const std::string accessToken = form.get("access_token", "");
    const std::string accessTokenTtl = form.get("access_token_ttl", "");
    LOG_TRC("access_token=" << accessToken << ", access_token_ttl=" << accessTokenTtl);
    const std::string accessHeader = form.get("access_header", "");
    LOG_TRC("access_header=" << accessHeader);

    // Escape bad characters in access token.
    // This is placed directly in javascript in loleaflet.html, we need to make sure
    // that no one can do anything nasty with their clever inputs.
    std::string escapedAccessToken, escapedAccessHeader;
    Poco::URI::encode(accessToken, "'", escapedAccessToken);
    Poco::URI::encode(accessHeader, "'", escapedAccessHeader);

    unsigned long tokenTtl = 0;
    if (!accessToken.empty())
    {
        if (!accessTokenTtl.empty())
        {
            try
            {
                tokenTtl = std::stoul(accessTokenTtl);
            }
            catch (const std::exception& exc)
            {
                LOG_ERR("access_token_ttl must be represented as the number of milliseconds since January 1, 1970 UTC, when the token will expire");
            }
        }
        else
        {
            LOG_INF("WOPI host did not pass optional access_token_ttl");
        }
    }

    Poco::replaceInPlace(preprocess, std::string("%ACCESS_TOKEN%"), escapedAccessToken);
    Poco::replaceInPlace(preprocess, std::string("%ACCESS_TOKEN_TTL%"), std::to_string(tokenTtl));
    Poco::replaceInPlace(preprocess, std::string("%ACCESS_HEADER%"), escapedAccessHeader);
    Poco::replaceInPlace(preprocess, std::string("%HOST%"), host);
    Poco::replaceInPlace(preprocess, std::string("%VERSION%"), std::string(LOOLWSD_VERSION_HASH));
    Poco::replaceInPlace(preprocess, std::string("%SERVICE_ROOT%"), LOOLWSD::ServiceRoot);

    static const std::string linkCSS("<link rel=\"stylesheet\" href=\"%s/loleaflet/" LOOLWSD_VERSION_HASH "/%s.css\">");
    static const std::string scriptJS("<script src=\"%s/loleaflet/" LOOLWSD_VERSION_HASH "/%s.js\"></script>");

    std::string brandCSS(Poco::format(linkCSS, LOOLWSD::ServiceRoot, std::string(BRANDING)));
    std::string brandJS(Poco::format(scriptJS, LOOLWSD::ServiceRoot, std::string(BRANDING)));

    const auto& config = Application::instance().config();
#if ENABLE_SUPPORT_KEY
    const std::string keyString = config.getString("support_key", "");
    SupportKey key(keyString);
    if (!key.verify() || key.validDaysRemaining() <= 0)
    {
        brandCSS = Poco::format(linkCSS, LOOLWSD::ServiceRoot, std::string(BRANDING_UNSUPPORTED));
        brandJS = Poco::format(scriptJS, LOOLWSD::ServiceRoot, std::string(BRANDING_UNSUPPORTED));
    }
#endif

    Poco::replaceInPlace(preprocess, std::string("<!--%BRANDING_CSS%-->"), brandCSS);
    Poco::replaceInPlace(preprocess, std::string("<!--%BRANDING_JS%-->"), brandJS);

    // Customization related to document signing.
    std::string documentSigningDiv;
    const std::string documentSigningURL = config.getString("per_document.document_signing_url", "");
    if (!documentSigningURL.empty())
    {
        documentSigningDiv = "<div id=\"document-signing-bar\"></div>";
    }
    Poco::replaceInPlace(preprocess, std::string("<!--%DOCUMENT_SIGNING_DIV%-->"), documentSigningDiv);
    Poco::replaceInPlace(preprocess, std::string("%DOCUMENT_SIGNING_URL%"), documentSigningURL);

    const auto loleafletLogging = config.getString("loleaflet_logging", "false");
    Poco::replaceInPlace(preprocess, std::string("%LOLEAFLET_LOGGING%"), loleafletLogging);
    const std::string outOfFocusTimeoutSecs= config.getString("per_view.out_of_focus_timeout_secs", "60");
    Poco::replaceInPlace(preprocess, std::string("%OUT_OF_FOCUS_TIMEOUT_SECS%"), outOfFocusTimeoutSecs);
    const std::string idleTimeoutSecs= config.getString("per_view.idle_timeout_secs", "900");
    Poco::replaceInPlace(preprocess, std::string("%IDLE_TIMEOUT_SECS%"), idleTimeoutSecs);

    const std::string mimeType = "text/html";

    std::ostringstream oss;
    oss << "HTTP/1.1 200 OK\r\n"
        << "Date: " << Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT) << "\r\n"
        << "Last-Modified: " << Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT) << "\r\n"
        << "User-Agent: " << WOPI_AGENT_STRING << "\r\n"
        << "Cache-Control:max-age=11059200\r\n"
        << "ETag: \"" LOOLWSD_VERSION_HASH "\"\r\n"
        << "Content-Length: " << preprocess.size() << "\r\n"
        << "Content-Type: " << mimeType << "\r\n"
        << "X-Content-Type-Options: nosniff\r\n"
        << "X-XSS-Protection: 1; mode=block\r\n"
        << "Referrer-Policy: no-referrer\r\n";

    // Document signing: if endpoint URL is configured, whitelist that for
    // iframe purposes.
    std::ostringstream cspOss;
    cspOss << "Content-Security-Policy: default-src 'none'; "
           << "frame-src 'self' blob: " << documentSigningURL << "; "
           << "connect-src 'self' " << host << "; "
           << "script-src 'unsafe-inline' 'self'; "
           << "style-src 'self' 'unsafe-inline'; "
           << "font-src 'self' data:; "
           << "object-src blob:; ";

    // Frame ancestors: Allow loolwsd host, wopi host and anything configured.
    std::string configFrameAncestor = config.getString("net.frame_ancestors", "");
    std::string frameAncestors = configFrameAncestor;
    Poco::URI uriHost(host);
    if (uriHost.getHost() != configFrameAncestor)
        frameAncestors += " " + uriHost.getHost() + ":*";

    for (const auto& param : params)
    {
        if (param.first == "WOPISrc")
        {
            std::string wopiFrameAncestor;
            Poco::URI::decode(param.second, wopiFrameAncestor);
            Poco::URI uriWopiFrameAncestor(wopiFrameAncestor);
            // Remove parameters from URL
            wopiFrameAncestor = uriWopiFrameAncestor.getHost();
            if (wopiFrameAncestor != uriHost.getHost() && wopiFrameAncestor != configFrameAncestor)
            {
                frameAncestors += " " + wopiFrameAncestor + ":*";
                LOG_TRC("Picking frame ancestor from WOPISrc: " << wopiFrameAncestor);
            }
            break;
        }
    }

    if (!frameAncestors.empty())
    {
        LOG_TRC("Allowed frame ancestors: " << frameAncestors);
        // X-Frame-Options supports only one ancestor, ignore that
        //(it's deprecated anyway and CSP works in all major browsers)
        cspOss << "img-src 'self' data: " << frameAncestors << "; "
                << "frame-ancestors " << frameAncestors;
    }
    else
    {
        LOG_TRC("Denied all frame ancestors");
        cspOss << "img-src 'self' data: none;";
    }
    cspOss << "\r\n";
    // Append CSP to response headers too
    oss << cspOss.str();

    // Setup HTTP Public key pinning
    if ((LOOLWSD::isSSLEnabled() || LOOLWSD::isSSLTermination()) && config.getBool("ssl.hpkp[@enable]", false))
    {
        size_t i = 0;
        std::string pinPath = "ssl.hpkp.pins.pin[" + std::to_string(i) + "]";
        std::ostringstream hpkpOss;
        bool keysPinned = false;
        while (config.has(pinPath))
        {
            const std::string pin = config.getString(pinPath, "");
            if (!pin.empty())
            {
                hpkpOss << "pin-sha256=\"" << pin << "\"; ";
                keysPinned = true;
            }
            pinPath = "ssl.hpkp.pins.pin[" + std::to_string(++i) + "]";
        }

        if (keysPinned && config.getBool("ssl.hpkp.max_age[@enable]", false))
        {
            int maxAge = 1000; // seconds
            try
            {
                maxAge = config.getInt("ssl.hpkp.max_age", maxAge);
            }
            catch (Poco::SyntaxException& exc)
            {
                LOG_WRN("Invalid value of HPKP's max-age directive found in config file. Defaulting to "
                        << maxAge);
            }
            hpkpOss << "max-age=" << maxAge << "; ";
        }

        if (keysPinned && config.getBool("ssl.hpkp.report_uri[@enable]", false))
        {
            const std::string reportUri = config.getString("ssl.hpkp.report_uri", "");
            if (!reportUri.empty())
            {
                hpkpOss << "report-uri=" << reportUri << "; ";
            }
        }

        if (!hpkpOss.str().empty())
        {
            if (config.getBool("ssl.hpkp[@report_only]", false))
            {
                // Only send validation failure reports to reportUri while still allowing UAs to
                // connect to the server
                oss << "Public-Key-Pins-Report-Only: " << hpkpOss.str() << "\r\n";
            }
            else
            {
                oss << "Public-Key-Pins: " << hpkpOss.str() << "\r\n";
            }
        }
    }

    oss << "\r\n"
        << preprocess;

    socket->send(oss.str());
    LOG_DBG("Sent file: " << relPath << ": " << preprocess);
}
Example #27
0
void ReceiveServer::on_connected(const std::shared_ptr<ynet::Connection>& connection)
{
	while (connection->send(_buffer.data(), _buffer.size()));
}
Example #28
0
void AsyncRunner::performAsyncOperation() {
  // We don't support throttled QPS right now.  The right way to do
  // this requires an AsyncIntervalTimer

  uint32_t opType = config_->pickOpType();
  scoreboard_->opStarted(opType);

  OpData *d = &(outstandingOps_[writePos_]);
  writePos_ = (writePos_ + 1) % (q_size_);

  d->opType_ = opType;
  n_outstanding_++;
  ctr_--;
  curOpData_ = d;

  switch (static_cast<ClientLoadConfig::OperationEnum>(opType)) {
    case ClientLoadConfig::OP_NOOP:
      return client_->noop(recvCob);
    case ClientLoadConfig::OP_ONEWAY_NOOP:
      return client_->onewayNoop(recvCob);
    case ClientLoadConfig::OP_ASYNC_NOOP:
      return client_->asyncNoop(recvCob);
    case ClientLoadConfig::OP_SLEEP:
      return client_->sleep(recvCob, config_->pickSleepUsec());
    case ClientLoadConfig::OP_ONEWAY_SLEEP:
      return client_->onewaySleep(recvCob, config_->pickSleepUsec());
    case ClientLoadConfig::OP_BURN:
      return client_->burn(recvCob, config_->pickBurnUsec());
    case ClientLoadConfig::OP_ONEWAY_BURN:
      return client_->onewayBurn(recvCob, config_->pickBurnUsec());
    case ClientLoadConfig::OP_BAD_SLEEP:
      return client_->badSleep(recvCob, config_->pickSleepUsec());
    case ClientLoadConfig::OP_BAD_BURN:
      return client_->badBurn(recvCob, config_->pickBurnUsec());
    case ClientLoadConfig::OP_THROW_ERROR:
      d->code = loadgen::RNG::getU32();
      return client_->throwError(recvCob, d->code);
    case ClientLoadConfig::OP_THROW_UNEXPECTED:
      return client_->throwUnexpected(recvCob, loadgen::RNG::getU32());
    case ClientLoadConfig::OP_ONEWAY_THROW:
      return client_->onewayThrow(recvCob, loadgen::RNG::getU32());
    case ClientLoadConfig::OP_SEND:
    {
      std::string str(config_->pickSendSize(), 'a');
      return client_->send(recvCob, str);
    }
    case ClientLoadConfig::OP_ONEWAY_SEND:
    {
      std::string str(config_->pickSendSize(), 'a');
      return client_->onewaySend(recvCob, str);
    }
    case ClientLoadConfig::OP_RECV:
      return client_->recv(recvCob, config_->pickRecvSize());
    case ClientLoadConfig::OP_SENDRECV:
    {
      std::string str(config_->pickSendSize(), 'a');
      return client_->sendrecv(recvCob, str, config_->pickRecvSize());
    }
    case ClientLoadConfig::OP_ECHO:
    {
      std::string str(config_->pickSendSize(), 'a');
      return client_->echo(recvCob, str);
    }
    case ClientLoadConfig::OP_ADD:
    {
      boost::uniform_int<int64_t> distribution;
      curOpData_->a = distribution(loadgen::RNG::getRNG());
      curOpData_->b = distribution(loadgen::RNG::getRNG());

      return client_->add(recvCob, curOpData_->a, curOpData_->b);
    }
    case ClientLoadConfig::NUM_OPS:
      // fall through
      break;
      // no default case, so gcc will warn us if a new op is added
      // and this switch statement is not updated
  }

  T_ERROR("AsyncClientWorker::performOperation() got unknown operation %"
          PRIu32, opType);
  assert(false);
}