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() };
208 std::cout << QObject::tr(
"QGIS Development Server listening on http://%1:%2" )
209 .arg( ipAddress ).arg( port ).toStdString() << std::endl;
212 std::cout << QObject::tr(
"CTRL+C to exit" ).toStdString() << std::endl;
215 QAtomicInt connCounter { 0 };
217 static const QMap<int, QString> knownStatuses
219 { 200, QStringLiteral(
"OK" ) },
220 { 201, QStringLiteral(
"Created" ) },
221 { 202, QStringLiteral(
"Accepted" ) },
222 { 204, QStringLiteral(
"No Content" ) },
223 { 301, QStringLiteral(
"Moved Permanently" ) },
224 { 302, QStringLiteral(
"Moved Temporarily" ) },
225 { 304, QStringLiteral(
"Not Modified" ) },
226 { 400, QStringLiteral(
"Bad Request" ) },
227 { 401, QStringLiteral(
"Unauthorized" ) },
228 { 403, QStringLiteral(
"Forbidden" ) },
229 { 404, QStringLiteral(
"Not Found" ) },
230 { 500, QStringLiteral(
"Internal Server Error" ) },
231 { 501, QStringLiteral(
"Not Implemented" ) },
232 { 502, QStringLiteral(
"Bad Gateway" ) },
233 { 503, QStringLiteral(
"Service Unavailable" ) }
238 #ifdef HAVE_SERVER_PYTHON_PLUGINS 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 );
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 ) );
326 QString url { qgetenv(
"REQUEST_URI" ) };
330 const QString path { firstLinePieces.at( 1 )};
331 url = QStringLiteral(
"http://%1:%2%3" ).arg( ipAddress ).arg( port ).arg( path );
334 const QString protocol { firstLinePieces.at( 2 )};
335 if ( protocol != QStringLiteral(
"HTTP/1.0" ) && protocol != QStringLiteral(
"HTTP/1.1" ) )
337 throw HttpException( QStringLiteral(
"HTTP error unsupported protocol: %1" ).arg( protocol ) );
342 int endHeadersPos { incomingData.indexOf(
"\r\n\r\n" ) };
344 if ( endHeadersPos == -1 )
346 throw HttpException( QStringLiteral(
"HTTP error finding headers" ) );
349 const QStringList httpHeaders { incomingData.mid( firstLinePos + 2, endHeadersPos - firstLinePos ).split(
"\r\n" ) };
351 for (
const auto &headerLine : httpHeaders )
353 const int headerColonPos { headerLine.indexOf(
':' ) };
354 if ( headerColonPos > 0 )
356 headers.insert( headerLine.left( headerColonPos ), headerLine.mid( headerColonPos + 2 ) );
361 QByteArray data { incomingData.mid( endHeadersPos + 4 ).toUtf8() };
363 auto start = std::chrono::steady_clock::now();
372 if ( clientConnection->state() == QAbstractSocket::SocketState::ConnectedState )
374 clientConnection->connect( clientConnection, &QAbstractSocket::disconnected,
375 clientConnection, connectionDeleter );
380 clientConnection->deleteLater();
384 auto elapsedTime { std::chrono::steady_clock::now() - start };
386 if ( ! knownStatuses.contains( response.
statusCode() ) )
388 throw HttpException( QStringLiteral(
"HTTP error unsupported status code: %1" ).arg( response.
statusCode() ) );
392 clientConnection->write( QStringLiteral(
"HTTP/1.0 %1 %2\r\n" ).arg( response.
statusCode() ).arg( knownStatuses.value( response.
statusCode() ) ).toUtf8() );
393 clientConnection->write( QStringLiteral(
"Server: QGIS\r\n" ).toUtf8() );
394 const auto responseHeaders { response.
headers() };
395 for (
auto it = responseHeaders.constBegin(); it != responseHeaders.constEnd(); ++it )
397 clientConnection->write( QStringLiteral(
"%1: %2\r\n" ).arg( it.key(), it.value() ).toUtf8() );
399 clientConnection->write(
"\r\n" );
400 const QByteArray body { response.
body() };
401 clientConnection->write( body );
404 std::cout << QStringLiteral(
"%1 [%2] %3 %4ms \"%5\" %6" )
405 .arg( clientConnection->peerAddress().toString(),
406 QDateTime::currentDateTime().toString(),
407 QString::number( body.size() ),
408 QString::number( std::chrono::duration_cast<std::chrono::milliseconds>( elapsedTime ).count() ),
409 firstLinePieces.join(
' ' ),
414 clientConnection->disconnectFromHost();
416 catch ( HttpException &ex )
419 if ( clientConnection->state() == QAbstractSocket::SocketState::ConnectedState )
421 clientConnection->connect( clientConnection, &QAbstractSocket::disconnected,
422 clientConnection, connectionDeleter );
427 clientConnection->deleteLater();
432 clientConnection->write( QStringLiteral(
"HTTP/1.0 %1 %2\r\n" ).arg( 500 ).arg( knownStatuses.value( 500 ) ).toUtf8() );
433 clientConnection->write( QStringLiteral(
"Server: QGIS\r\n" ).toUtf8() );
434 clientConnection->write(
"\r\n" );
435 clientConnection->write( ex.message().toUtf8() );
437 std::cout << QStringLiteral(
"%1 [%2] \"%3\" - - 500" )
438 .arg( clientConnection->peerAddress().toString() )
439 .arg( QDateTime::currentDateTime().toString() )
440 .arg( ex.message() ).toStdString() << std::endl;
442 clientConnection->disconnectFromHost();
454 auto exitHandler = [ ](
int signal )
456 std::cout << QStringLiteral(
"Signal %1 received: quitting" ).arg( signal ).toStdString() << std::endl;
460 signal( SIGTERM, exitHandler );
461 signal( SIGABRT, exitHandler );
462 signal( SIGINT, exitHandler );
463 signal( SIGPIPE, [ ](
int )
465 std::cerr << QStringLiteral(
"Signal SIGPIPE received: ignoring" ).toStdString() << std::endl;
Extends QApplication to provide access to QGIS specific resources such as theme paths, database paths etc.
int main(int argc, char *argv[])
Method
HTTP Method (or equivalent) used for the request.
QMap< QString, QString > Headers
Class defining request with data.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
QByteArray body() const
Returns body.
Class defining buffered response.
static const char * QGIS_ORGANIZATION_NAME
The QgsServer class provides OGC web services.
int statusCode() const override
Returns the http status code.
QMap< QString, QString > headers() const override
Returns all the headers.
static const char * QGIS_ORGANIZATION_DOMAIN
void handleRequest(QgsServerRequest &request, QgsServerResponse &response, const QgsProject *project=nullptr)
Handles the request.