Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ Merged since v2.5.0, not yet released.
`printToPathe` or `plot_simulation` is called. `plt`, `cm`, `mpath`,
`mpatches` and `ListedColormap` are no longer reachable as `pyforefire`
attributes. ([#193])
- `listenHTTP[]` binds to `localhost` by default and to the host given in
`listenHTTP[host:port]`; use `listenHTTP[0.0.0.0:8000]` for the network
(and inside Docker), which prints a warning.
`systemExec` is refused over HTTP, the static file server only serves the run
directory and `FOREFIREHOME/tools/htdocs`, and commands from another site or
host name are refused. Other commands can still read and write files, so the
server is meant for trusted local use. ([#199])

## [v2.5.0] — 2026-08-11

Expand Down Expand Up @@ -214,3 +221,4 @@ repository stays easy to return to.
[#194]: https://github.com/forefireAPI/forefire/pull/194
[#196]: https://github.com/forefireAPI/forefire/issues/196
[#202]: https://github.com/forefireAPI/forefire/pull/202
[#199]: https://github.com/forefireAPI/forefire/pull/199
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,14 +119,16 @@ The easiest way to get started is often using Docker and the interactive console

```

5. Launch the HTTP server from the console:
5. Launch the HTTP server from the console. Inside the container, bind to all
interfaces so the published port reaches it (`listenHTTP[]` alone only
listens on the container's own localhost):
```bash
listenHTTP[]
listenHTTP[0.0.0.0:8000]
```
the output should be :

```bash
>> ForeFire HTTP command server listening at http://localhost:8000
>> ForeFire HTTP command server listening at http://0.0.0.0:8000
```

This server provides a graphical user interface that you can access on your browser at http://localhost:8000/
Expand Down
2 changes: 2 additions & 0 deletions docs/source/getting_started/execution_modes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,8 @@ This method, which you may have already used in the :doc:`quickstart` guide, use

forefire -l

Both bind to ``localhost``. Inside a Docker container, use ``listenHTTP[0.0.0.0:8000]`` instead so the published port reaches the server.

4. **Use the Web Interface:**

- Open your browser to ``http://localhost:8000/`` (or the specified port).
Expand Down
5 changes: 3 additions & 2 deletions docs/source/getting_started/quickstart.rst
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,10 @@ Steps

.. code-block:: none

forefire> listenHTTP[]
forefire> listenHTTP[0.0.0.0:8000]

You should see the output : `>> ForeFire HTTP command server listening at http://localhost:8000`
You should see the output : `>> ForeFire HTTP command server listening at http://0.0.0.0:8000`, followed by a warning that the server is reachable from the network.
Inside a container this is needed: ``listenHTTP[]`` alone only listens on the container's own localhost, which the published port cannot reach.

7. **Access the Web Console:**

Expand Down
2 changes: 1 addition & 1 deletion docs/source/reference/commands.rst
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,7 @@ Launches an HTTP server (on the machine running ForeFire) that listens for simul

**Arguments:**

* Positional 1: Hostname or IP address to bind the server to, followed by a colon, followed by the port number (e.g., `127.0.0.1:8000`, `0.0.0.0:8080`).
* Positional 1: Hostname or IP address to bind the server to, followed by a colon, followed by the port number (e.g., `127.0.0.1:8000`, `0.0.0.0:8080`). Without a host (``listenHTTP[]`` or ``listenHTTP[:8000]``) the server binds to ``localhost``. ``0.0.0.0`` opens it to the network, as needed inside a Docker container.

**Example:**

Expand Down
42 changes: 28 additions & 14 deletions src/Command.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ namespace libforefire

bool Command::firstCommand = true;
bool Command::quitAsked = false;
thread_local bool Command::remoteCommand = false;
size_t Command::refTabs = 0;

FFPoint *Command::lastReadLoc = 0;
Expand Down Expand Up @@ -1186,6 +1187,13 @@ namespace libforefire
}
int Command::systemExec(const string &arg, size_t &numTabs)
{
// No shell commands from the network, even through include[] or @t=.
if (remoteCommand)
{
cout << "systemExec is not available over HTTP" << endl;
return error;
}

SimulationParameters *simParam = SimulationParameters::GetInstance();
string finalStr;

Expand Down Expand Up @@ -3400,14 +3408,16 @@ namespace libforefire
std::string Command::executeCommandAndCaptureOutput(const std::string &cmd)
{
// 'cmd' is assumed to be the command text after the "ff:" prefix.
std::streambuf *oldbuf = std::cout.rdbuf();
std::ostringstream captured;
std::cout.rdbuf(captured.rdbuf());
// Restore cout even if the command throws.
struct CoutRedirect {
std::streambuf *old;
explicit CoutRedirect(std::streambuf *buf) : old(std::cout.rdbuf(buf)) {}
~CoutRedirect() { std::cout.rdbuf(old); }
} redirect(captured.rdbuf());
RemoteCommandScope remote(true);
std::string fireCommand = cmd;
// Execute the command. (Assuming ExecuteCommand is defined elsewhere.)
ExecuteCommand(fireCommand);

std::cout.rdbuf(oldbuf);
return captured.str();
}

Expand Down Expand Up @@ -3439,14 +3449,13 @@ namespace libforefire
}
}

char hostname[256];
if (gethostname(hostname, sizeof(hostname)) != 0)
{
cout << "Cannot get hostname info " << endl;
return error;
}

std::string address = arg.empty() ? std::string(hostname) + ":" + std::to_string(port) : arg;
// Local only by default; listenHTTP[0.0.0.0:8000] to open it to the network.
std::string address = arg.empty() ? defaultHostname + ":" + std::to_string(port) : arg;
if (address.compare(0, 5, "host=") == 0)
address = address.substr(5);
// listenHTTP[:8000] means localhost too.
if (!address.empty() && address[0] == ':')
address = defaultHostname + address;

// Allocate a new HTTP server if none exists.
if (currentSession.server == 0)
Expand All @@ -3463,10 +3472,15 @@ namespace libforefire
}
else
{
// Other nodes need the machine name, not the wildcard address.
std::string connectAddress = address;
char hostname[256];
if (address.compare(0, 8, "0.0.0.0:") == 0 && gethostname(hostname, sizeof(hostname)) == 0)
connectAddress = std::string(hostname) + address.substr(7);
std::ofstream infoFile("httpConnectInfo.txt");
if (infoFile)
{
infoFile << hostname << ":" << port << std::endl;
infoFile << connectAddress << std::endl;
infoFile.close();
}
else
Expand Down
9 changes: 9 additions & 0 deletions src/Command.h
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,15 @@ class Command {
static bool quitRequested();
/*! \brief forgets a pending quit request */
static void clearQuitRequest();
// True while running a command received over HTTP (or scheduled by one)
static thread_local bool remoteCommand;

// Sets remoteCommand for a scope and restores the previous value, even on exceptions
struct RemoteCommandScope {
bool previous;
explicit RemoteCommandScope(bool remote) : previous(remoteCommand) { remoteCommand = remote; }
~RemoteCommandScope() { remoteCommand = previous; }
};

// Reference time
static double refTime;
Expand Down
2 changes: 2 additions & 0 deletions src/EventCommand.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ namespace libforefire{

EventCommand::EventCommand(string scommand, double schedueledTime) : ForeFireAtom(schedueledTime) {
schedueledCommand = scommand;
remote = Command::remoteCommand;

};

Expand All @@ -29,6 +30,7 @@ EventCommand::~EventCommand() {};


void EventCommand::update(){
Command::RemoteCommandScope scope(remote);
Command::ExecuteCommand(schedueledCommand);
}
void EventCommand::timeAdvance(){
Expand Down
3 changes: 2 additions & 1 deletion src/EventCommand.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ namespace libforefire{
class EventCommand: public ForeFireAtom {

string schedueledCommand;
bool remote; // scheduled by a command received over HTTP

public:
/*! \brief Default constructor */
EventCommand() : ForeFireAtom(0.) {};
EventCommand() : ForeFireAtom(0.), remote(false) {};
/*! \brief standard constructor */
EventCommand( string, double ) ;
/*! \brief Default destructor */
Expand Down
103 changes: 95 additions & 8 deletions src/HttpCommandServer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <sys/stat.h>
#include <dirent.h>

// POSIX headers for sockets
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>

namespace http_command {
Expand All @@ -48,6 +50,20 @@ namespace http_command {
return false;
}
int port = std::stoi(address.substr(colon + 1));
std::string host = address.substr(0, colon);

// Bind to the requested host only (0.0.0.0 for all interfaces).
addrinfo hints;
std::memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
addrinfo *resolved = nullptr;
if (getaddrinfo(host.c_str(), nullptr, &hints, &resolved) != 0 || resolved == nullptr) {
std::cerr << "Cannot resolve host " << host << std::endl;
return false;
}
in_addr bindAddr = reinterpret_cast<sockaddr_in*>(resolved->ai_addr)->sin_addr;
freeaddrinfo(resolved);

server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
Expand All @@ -60,24 +76,37 @@ namespace http_command {
sockaddr_in addr;
std::memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_addr = bindAddr;
addr.sin_port = htons(port);
if (::bind(server_fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
perror("bind");
close(server_fd);
server_fd = -1;
return false;
}
if (::listen(server_fd, 10) < 0) {
perror("listen");
close(server_fd);
server_fd = -1;
return false;
}
loopbackOnly = (ntohl(bindAddr.s_addr) >> 24) == 127;
running = true;
server_thread = std::thread(&HttpCommandServer::acceptLoop, this);
std::cout
<< "\033[35m" // start color
<< "ForeFire HTTP command server listening at http://localhost:" << port
<< "ForeFire HTTP command server listening at http://" << host << ":" << port
<< "\033[0m"
<< std::endl;

if (!loopbackOnly) {
std::cout
<< "\033[31m" // start red
<< "WARNING: development server, reachable from the network. Anyone who can reach this port can run ForeFire commands. Use listenHTTP[localhost:" << port << "] unless you need remote access."
<< "\033[0m"
<< std::endl;
}

std::cout
<< "\033[33m" // start yellow
<< "To stop the server, press Ctrl-C or type quit in the ForeFire shell."
Expand Down Expand Up @@ -137,6 +166,13 @@ namespace http_command {
std::string method, uri, version;
requestStream >> method >> uri >> version;

if (!allowedHost(request)) {
std::string refused = buildSimpleResponse("403 Forbidden", "Forbidden request");
ssize_t refused_written = write(client_fd, refused.data(), refused.size());
(void)refused_written;
return;
}

std::string complete_response;
// Handle POST requests: look for an ff: command in the body.
if (method == "POST") {
Expand All @@ -146,19 +182,15 @@ namespace http_command {
body = request.substr(pos + 4);
}
if (body.size() > 3 && (body.substr(0, 3) == "ff:" || body.substr(0, 3) == "FF:")) {
std::string fireCommand = body.substr(3);
std::string result = callback(fireCommand);
complete_response = buildResponse("200 OK", "text/plain; charset=UTF-8", result);
complete_response = runCommand(request, body.substr(3));
} else {
complete_response = serveFileOrDirectory(uri);
}
}
// Handle GET requests.
else {
if (uri.size() > 4 && (uri.substr(0, 4) == "/ff:" || uri.substr(0, 4) == "/FF:")) {
std::string fireCommand = uri.substr(4);
std::string result = callback(fireCommand);
complete_response = buildResponse("200 OK", "text/plain; charset=UTF-8", result);
complete_response = runCommand(request, uri.substr(4));
} else {
complete_response = serveFileOrDirectory(uri);
}
Expand All @@ -167,6 +199,56 @@ namespace http_command {
(void)bytes_written;
}

// Value of an HTTP header (name in lowercase), empty if absent.
static std::string headerValue(const std::string &request, const std::string &name) {
std::istringstream lines(request);
std::string line;
std::getline(lines, line); // request line
while (std::getline(lines, line) && line != "\r" && !line.empty()) {
size_t colon = line.find(':');
if (colon == std::string::npos)
continue;
std::string key = line.substr(0, colon);
for (char &c : key)
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
if (key != name)
continue;
size_t start = line.find_first_not_of(" \t", colon + 1);
size_t end = line.find_last_not_of(" \t\r");
return (start == std::string::npos) ? "" : line.substr(start, end - start + 1);
}
return "";
}

static bool isLoopbackHost(std::string host) {
if (!host.empty() && host[0] == '[')
return host.compare(0, 5, "[::1]") == 0;
host = host.substr(0, host.find(':'));
return host == "localhost" || host.compare(0, 4, "127.") == 0;
}

// DNS rebinding: a local server only answers to local names.
bool allowedHost(const std::string &request) {
std::string host = headerValue(request, "host");
return !loopbackOnly || host.empty() || isLoopbackHost(host);
}

// Commands only from the server's own pages or non-browser clients,
// not from another site (e.g. <img src=.../ff:...>).
static bool sameOriginCommand(const std::string &request) {
std::string site = headerValue(request, "sec-fetch-site");
if (!site.empty() && site != "same-origin" && site != "none")
return false;
std::string origin = headerValue(request, "origin");
return origin.empty() || origin == "http://" + headerValue(request, "host");
}

std::string runCommand(const std::string &request, const std::string &fireCommand) {
if (!sameOriginCommand(request))
return buildSimpleResponse("403 Forbidden", "Cross-site command refused");
return buildResponse("200 OK", "text/plain; charset=UTF-8", callback(fireCommand));
}

// Check whether a file exists.
bool fileExists(const std::string &path) {
std::ifstream file(path, std::ios::binary);
Expand Down Expand Up @@ -270,6 +352,10 @@ namespace http_command {
if (!path.empty() && path[0] == '/')
path = path.substr(1);

// Only files under the run directory or FOREFIREHOME/tools/htdocs.
if ((!path.empty() && path[0] == '/') || ("/" + path + "/").find("/../") != std::string::npos)
return buildSimpleResponse("403 Forbidden", "Forbidden path: " + uri);

// For an empty path, try current directory's index.html;
// if not available, check the FOREFIREHOME environment variable.
if (path.empty()) {
Expand Down Expand Up @@ -318,6 +404,7 @@ namespace http_command {
}

int server_fd;
bool loopbackOnly = true;
std::atomic<bool> running;
std::thread server_thread;
CommandCallback callback;
Expand Down
Loading