28 #include "qgsconfig.h"
35 #include <QFontDatabase>
39 #include <QNetworkInterface>
40 #include <QCommandLineParser>
56 class HttpException:
public std::exception
64 HttpException(
const QString &message )
83 int main(
int argc,
char *argv[] )
94 const QString display { qgetenv(
"DISPLAY" ) };
95 bool withDisplay =
true;
96 if ( display.isEmpty() )
99 qputenv(
"QT_QPA_PLATFORM",
"offscreen" );
103 QgsApplication app( argc, argv, withDisplay, QString(), QStringLiteral(
"QGIS Development Server" ) );
107 QCoreApplication::setApplicationName(
"QGIS Development Server" );
108 QCoreApplication::setApplicationVersion(
"1.0" );
112 QgsMessageLog::logMessage(
"DISPLAY environment variable is not set, running in offscreen mode, all printing capabilities will not be available.\n"
113 "Consider installing an X server like 'xvfb' and export DISPLAY to the actual display value.",
"Server",
Qgis::Warning );
119 QFontDatabase fontDB;
123 QString serverPort { qgetenv(
"QGIS_SERVER_PORT" ) };
125 QString ipAddress { qgetenv(
"QGIS_SERVER_ADDRESS" ) };
127 if ( serverPort.isEmpty() )
129 serverPort = QStringLiteral(
"8000" );
132 if ( ipAddress.isEmpty() )
134 ipAddress = QStringLiteral(
"localhost" );
137 QCommandLineParser parser;
138 parser.setApplicationDescription( QObject::tr(
"QGIS Development Server" ) );
139 parser.addHelpOption();
140 parser.addVersionOption();
141 parser.addPositionalArgument( QStringLiteral(
"addressAndPort" ),
142 QObject::tr(
"Address and port (default: \"localhost:8000\")\n"
143 "address and port can also be specified with the environment\n"
144 "variables QGIS_SERVER_ADDRESS and QGIS_SERVER_PORT." ), QStringLiteral(
"[address:port]" ) );
145 QCommandLineOption logLevelOption(
"l", QObject::tr(
"Log level (default: 0)\n"
148 "2: CRITICAL" ),
"logLevel",
"0" );
149 parser.addOption( logLevelOption );
151 QCommandLineOption projectOption(
"p", QObject::tr(
"Path to a QGIS project file (*.qgs or *.qgz),\n"
152 "if specified it will override the query string MAP argument\n"
153 "and the QGIS_PROJECT_FILE environment variable." ),
"projectPath",
"" );
154 parser.addOption( projectOption );
156 parser.process( app );
157 const QStringList args = parser.positionalArguments();
159 if ( args.size() == 1 )
161 QStringList addressAndPort { args.at( 0 ).split(
':' ) };
162 if ( addressAndPort.size() == 2 )
164 ipAddress = addressAndPort.at( 0 );
165 serverPort = addressAndPort.at( 1 );
169 QString logLevel = parser.value( logLevelOption );
170 qunsetenv(
"QGIS_SERVER_LOG_FILE" );
171 qputenv(
"QGIS_SERVER_LOG_LEVEL", logLevel.toUtf8() );
172 qputenv(
"QGIS_SERVER_LOG_STDERR",
"1" );
174 if ( ! parser.value( projectOption ).isEmpty( ) )
177 const QString projectFilePath { parser.value( projectOption ) };
178 if ( ! QFile::exists( projectFilePath ) )
180 std::cout << QObject::tr(
"Project file not found, the option will be ignored." ).toStdString() << std::endl;
184 qputenv(
"QGIS_PROJECT_FILE", projectFilePath.toUtf8() );
192 QTcpServer tcpServer;
194 QHostAddress address { QHostAddress::AnyIPv4 };
195 address.setAddress( ipAddress );
197 if ( ! tcpServer.listen( address, serverPort.toInt( ) ) )
199 std::cerr << QObject::tr(
"Unable to start the server: %1." )
200 .arg( tcpServer.errorString() ).toStdString() << std::endl;
207 const int port { tcpServer.serverPort() };
209 QAtomicInt connCounter { 0 };
211 static const QMap<int, QString> knownStatuses
213 { 200, QStringLiteral(
"OK" ) },
214 { 201, QStringLiteral(
"Created" ) },
215 { 202, QStringLiteral(
"Accepted" ) },
216 { 204, QStringLiteral(
"No Content" ) },
217 { 301, QStringLiteral(
"Moved Permanently" ) },
218 { 302, QStringLiteral(
"Moved Temporarily" ) },
219 { 304, QStringLiteral(
"Not Modified" ) },
220 { 400, QStringLiteral(
"Bad Request" ) },
221 { 401, QStringLiteral(
"Unauthorized" ) },
222 { 403, QStringLiteral(
"Forbidden" ) },
223 { 404, QStringLiteral(
"Not Found" ) },
224 { 500, QStringLiteral(
"Internal Server Error" ) },
225 { 501, QStringLiteral(
"Not Implemented" ) },
226 { 502, QStringLiteral(
"Bad Gateway" ) },
227 { 503, QStringLiteral(
"Service Unavailable" ) }
232 #ifdef HAVE_SERVER_PYTHON_PLUGINS
236 std::cout << QObject::tr(
"QGIS Development Server listening on http://%1:%2" )
237 .arg( ipAddress ).arg( port ).toStdString() << std::endl;
239 std::cout << QObject::tr(
"CTRL+C to exit" ).toStdString() << std::endl;
243 tcpServer.connect( &tcpServer, &QTcpServer::newConnection, [ & ]
245 QTcpSocket *clientConnection = tcpServer.nextPendingConnection();
252 QObject *context {
new QObject };
255 auto connectionDeleter = [ =, &connCounter ]()
257 clientConnection->deleteLater();
262 clientConnection->connect( clientConnection, &QAbstractSocket::disconnected, context, connectionDeleter, Qt::QueuedConnection );
265 clientConnection->connect( clientConnection, &QIODevice::readyRead, context, [ =, &server, &connCounter ] {
271 QString incomingData;
272 while ( clientConnection->bytesAvailable() > 0 )
274 incomingData += clientConnection->readAll();
280 int firstLinePos { incomingData.indexOf(
"\r\n" ) };
281 if ( firstLinePos == -1 )
283 throw HttpException( QStringLiteral(
"HTTP error finding protocol header" ) );
286 const QString firstLine { incomingData.left( firstLinePos ) };
287 const QStringList firstLinePieces { firstLine.split(
' ' ) };
288 if ( firstLinePieces.size() != 3 )
290 throw HttpException( QStringLiteral(
"HTTP error splitting protocol header" ) );
293 const QString methodString { firstLinePieces.at( 0 ) };
296 if ( methodString ==
"GET" )
298 method = QgsServerRequest::Method::GetMethod;
300 else if ( methodString ==
"POST" )
302 method = QgsServerRequest::Method::PostMethod;
304 else if ( methodString ==
"HEAD" )
306 method = QgsServerRequest::Method::HeadMethod;
308 else if ( methodString ==
"PUT" )
310 method = QgsServerRequest::Method::PutMethod;
312 else if ( methodString ==
"PATCH" )
314 method = QgsServerRequest::Method::PatchMethod;
316 else if ( methodString ==
"DELETE" )
318 method = QgsServerRequest::Method::DeleteMethod;
322 throw HttpException( QStringLiteral(
"HTTP error unsupported method: %1" ).arg( methodString ) );
325 const QString protocol { firstLinePieces.at( 2 )};
326 if ( protocol != QStringLiteral(
"HTTP/1.0" ) && protocol != QStringLiteral(
"HTTP/1.1" ) )
328 throw HttpException( QStringLiteral(
"HTTP error unsupported protocol: %1" ).arg( protocol ) );
333 int endHeadersPos { incomingData.indexOf(
"\r\n\r\n" ) };
335 if ( endHeadersPos == -1 )
337 throw HttpException( QStringLiteral(
"HTTP error finding headers" ) );
340 const QStringList httpHeaders { incomingData.mid( firstLinePos + 2, endHeadersPos - firstLinePos ).split(
"\r\n" ) };
342 for (
const auto &headerLine : httpHeaders )
344 const int headerColonPos { headerLine.indexOf(
':' ) };
345 if ( headerColonPos > 0 )
347 headers.insert( headerLine.left( headerColonPos ), headerLine.mid( headerColonPos + 2 ) );
352 QString url { qgetenv(
"REQUEST_URI" ) };
356 const QString path { firstLinePieces.at( 1 )};
358 if ( headers.contains( QStringLiteral(
"Host" ) ) )
360 url = QStringLiteral(
"http://%1%2" ).arg( headers.value( QStringLiteral(
"Host" ) ) ).arg( path );
364 url = QStringLiteral(
"http://%1:%2%3" ).arg( ipAddress ).arg( port ).arg( path );
369 QByteArray data { incomingData.mid( endHeadersPos + 4 ).toUtf8() };
371 auto start = std::chrono::steady_clock::now();
380 if ( clientConnection->state() == QAbstractSocket::SocketState::ConnectedState )
382 clientConnection->connect( clientConnection, &QAbstractSocket::disconnected,
383 clientConnection, connectionDeleter, Qt::QueuedConnection );
388 clientConnection->deleteLater();
392 auto elapsedTime { std::chrono::steady_clock::now() - start };
394 if ( ! knownStatuses.contains( response.
statusCode() ) )
396 throw HttpException( QStringLiteral(
"HTTP error unsupported status code: %1" ).arg( response.
statusCode() ) );
400 clientConnection->write( QStringLiteral(
"HTTP/1.0 %1 %2\r\n" ).arg( response.
statusCode() ).arg( knownStatuses.value( response.
statusCode() ) ).toUtf8() );
401 clientConnection->write( QStringLiteral(
"Server: QGIS\r\n" ).toUtf8() );
402 const auto responseHeaders { response.
headers() };
403 for (
auto it = responseHeaders.constBegin(); it != responseHeaders.constEnd(); ++it )
405 clientConnection->write( QStringLiteral(
"%1: %2\r\n" ).arg( it.key(), it.value() ).toUtf8() );
407 clientConnection->write(
"\r\n" );
408 const QByteArray body { response.
body() };
409 clientConnection->write( body );
412 std::cout << QStringLiteral(
"%1 [%2] %3 %4ms \"%5\" %6" )
413 .arg( clientConnection->peerAddress().toString(),
414 QDateTime::currentDateTime().toString(),
415 QString::number( body.size() ),
416 QString::number( std::chrono::duration_cast<std::chrono::milliseconds>( elapsedTime ).count() ),
417 firstLinePieces.join(
' ' ),
422 clientConnection->disconnectFromHost();
424 catch ( HttpException &ex )
427 if ( clientConnection->state() == QAbstractSocket::SocketState::ConnectedState )
429 clientConnection->connect( clientConnection, &QAbstractSocket::disconnected,
430 clientConnection, connectionDeleter );
435 clientConnection->deleteLater();
440 clientConnection->write( QStringLiteral(
"HTTP/1.0 %1 %2\r\n" ).arg( 500 ).arg( knownStatuses.value( 500 ) ).toUtf8() );
441 clientConnection->write( QStringLiteral(
"Server: QGIS\r\n" ).toUtf8() );
442 clientConnection->write(
"\r\n" );
443 clientConnection->write( ex.message().toUtf8() );
445 std::cout << QStringLiteral(
"%1 [%2] \"%3\" - - 500" )
446 .arg( clientConnection->peerAddress().toString() )
447 .arg( QDateTime::currentDateTime().toString() )
448 .arg( ex.message() ).toStdString() << std::endl;
450 clientConnection->disconnectFromHost();
453 }, Qt::QueuedConnection );
462 auto exitHandler = [ ](
int signal )
464 std::cout << QStringLiteral(
"Signal %1 received: quitting" ).arg( signal ).toStdString() << std::endl;
468 signal( SIGTERM, exitHandler );
469 signal( SIGABRT, exitHandler );
470 signal( SIGINT, exitHandler );
471 signal( SIGPIPE, [ ](
int )
473 std::cerr << QStringLiteral(
"Signal SIGPIPE received: ignoring" ).toStdString() << std::endl;