QGIS API Documentation 3.41.0-Master (af5edcb665c)
Loading...
Searching...
No Matches
qgis_mapserver.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgs_mapserver.cpp
3
4A QGIS development HTTP server for testing/development purposes.
5The server listens to localhost:8000, the address and port can be changed with the
6environment variable QGIS_SERVER_ADDRESS and QGIS_SERVER_PORT or passing <address>:<port>
7on the command line.
8
9All requests and application messages are printed to the standard output,
10while QGIS server internal logging is printed to stderr.
11
12 -------------------
13 begin : Jan 17 2020
14 copyright : (C) 2020 by Alessandro Pasotti
15 email : elpaso at itopen dot it
16 ***************************************************************************/
17
18/***************************************************************************
19 * *
20 * This program is free software; you can redistribute it and/or modify *
21 * it under the terms of the GNU General Public License as published by *
22 * the Free Software Foundation; either version 2 of the License, or *
23 * (at your option) any later version. *
24 * *
25 ***************************************************************************/
26
27#include <thread>
28#include <string>
29#include <chrono>
30#include <condition_variable>
31
32//for CMAKE_INSTALL_PREFIX
33#include "qgscommandlineutils.h"
34#include "qgsconfig.h"
35#include "qgsserver.h"
38#include "qgsapplication.h"
39#include "qgsmessagelog.h"
40
41#include <QFontDatabase>
42#include <QString>
43#include <QTcpServer>
44#include <QTcpSocket>
45#include <QNetworkInterface>
46#include <QCommandLineParser>
47#include <QObject>
48#include <QQueue>
49#include <QThread>
50#include <QPointer>
51
52#ifndef Q_OS_WIN
53#include <csignal>
54#endif
55
57
58// For the signal exit handler
59QAtomicInt IS_RUNNING = 1;
60
61QString ipAddress;
62QString serverPort;
63
64std::condition_variable REQUEST_WAIT_CONDITION;
65std::mutex REQUEST_QUEUE_MUTEX;
66std::mutex SERVER_MUTEX;
67
68struct RequestContext
69{
70 QPointer<QTcpSocket> clientConnection;
71 QString httpHeader;
72 std::chrono::steady_clock::time_point startTime;
75};
76
77
78QQueue<RequestContext *> REQUEST_QUEUE;
79
80const QMap<int, QString> knownStatuses {
81 { 200, QStringLiteral( "OK" ) },
82 { 201, QStringLiteral( "Created" ) },
83 { 202, QStringLiteral( "Accepted" ) },
84 { 204, QStringLiteral( "No Content" ) },
85 { 301, QStringLiteral( "Moved Permanently" ) },
86 { 302, QStringLiteral( "Moved Temporarily" ) },
87 { 304, QStringLiteral( "Not Modified" ) },
88 { 400, QStringLiteral( "Bad Request" ) },
89 { 401, QStringLiteral( "Unauthorized" ) },
90 { 403, QStringLiteral( "Forbidden" ) },
91 { 404, QStringLiteral( "Not Found" ) },
92 { 500, QStringLiteral( "Internal Server Error" ) },
93 { 501, QStringLiteral( "Not Implemented" ) },
94 { 502, QStringLiteral( "Bad Gateway" ) },
95 { 503, QStringLiteral( "Service Unavailable" ) }
96};
97
101class HttpException : public std::exception
102{
103 public:
107 HttpException( const QString &message )
108 : mMessage( message )
109 {
110 }
111
115 QString message()
116 {
117 return mMessage;
118 }
119
120 private:
121 QString mMessage;
122};
123
124
125class TcpServerWorker : public QObject
126{
127 Q_OBJECT
128
129 public:
130 TcpServerWorker( const QString &ipAddress, int port )
131 {
132 QHostAddress address { QHostAddress::AnyIPv4 };
133 address.setAddress( ipAddress );
134
135 if ( !mTcpServer.listen( address, port ) )
136 {
137 std::cerr << tr( "Unable to start the server: %1." )
138 .arg( mTcpServer.errorString() )
139 .toStdString()
140 << std::endl;
141 }
142 else
143 {
144 const int port { mTcpServer.serverPort() };
145
146 std::cout << tr( "QGIS Development Server listening on http://%1:%2" ).arg( ipAddress ).arg( port ).toStdString() << std::endl;
147#ifndef Q_OS_WIN
148 std::cout << tr( "CTRL+C to exit" ).toStdString() << std::endl;
149#endif
150
151 mIsListening = true;
152
153 // Incoming connection handler
154 QTcpServer::connect( &mTcpServer, &QTcpServer::newConnection, this, [=] {
155 QTcpSocket *clientConnection = mTcpServer.nextPendingConnection();
156
157 mConnectionCounter++;
158
159 //qDebug() << "Active connections: " << mConnectionCounter;
160
161 QString *incomingData = new QString();
162
163 // Lambda disconnect context
164 QObject *context { new QObject };
165
166 // Deletes the connection later
167 auto connectionDeleter = [=]() {
168 clientConnection->deleteLater();
169 mConnectionCounter--;
170 delete incomingData;
171 };
172
173 // This will delete the connection
174 QObject::connect( clientConnection, &QAbstractSocket::disconnected, clientConnection, connectionDeleter, Qt::QueuedConnection );
175
176#if 0 // Debugging output
177 clientConnection->connect( clientConnection, &QAbstractSocket::errorOccurred, clientConnection, [ = ]( QAbstractSocket::SocketError socketError )
178 {
179 qDebug() << "Socket error #" << socketError;
180 }, Qt::QueuedConnection );
181#endif
182
183 // Incoming connection parser
184 QObject::connect( clientConnection, &QIODevice::readyRead, context, [=] {
185 // Read all incoming data
186 while ( clientConnection->bytesAvailable() > 0 )
187 {
188 incomingData->append( clientConnection->readAll() );
189 }
190
191 try
192 {
193 // Parse protocol and URL GET /path HTTP/1.1
194 const auto firstLinePos { incomingData->indexOf( "\r\n" ) };
195 if ( firstLinePos == -1 )
196 {
197 throw HttpException( QStringLiteral( "HTTP error finding protocol header" ) );
198 }
199
200 const QString firstLine { incomingData->left( firstLinePos ) };
201 const QStringList firstLinePieces { firstLine.split( ' ' ) };
202 if ( firstLinePieces.size() != 3 )
203 {
204 throw HttpException( QStringLiteral( "HTTP error splitting protocol header" ) );
205 }
206
207 const QString methodString { firstLinePieces.at( 0 ) };
208
210 if ( methodString == "GET" )
211 {
213 }
214 else if ( methodString == "POST" )
215 {
217 }
218 else if ( methodString == "HEAD" )
219 {
221 }
222 else if ( methodString == "PUT" )
223 {
225 }
226 else if ( methodString == "PATCH" )
227 {
229 }
230 else if ( methodString == "DELETE" )
231 {
233 }
234 else
235 {
236 throw HttpException( QStringLiteral( "HTTP error unsupported method: %1" ).arg( methodString ) );
237 }
238
239 // cppcheck-suppress containerOutOfBounds
240 const QString protocol { firstLinePieces.at( 2 ) };
241 if ( protocol != QLatin1String( "HTTP/1.0" ) && protocol != QLatin1String( "HTTP/1.1" ) )
242 {
243 throw HttpException( QStringLiteral( "HTTP error unsupported protocol: %1" ).arg( protocol ) );
244 }
245
246 // Headers
248 const auto endHeadersPos { incomingData->indexOf( "\r\n\r\n" ) };
249
250 if ( endHeadersPos == -1 )
251 {
252 throw HttpException( QStringLiteral( "HTTP error finding headers" ) );
253 }
254
255 const QStringList httpHeaders { incomingData->mid( firstLinePos + 2, endHeadersPos - firstLinePos ).split( "\r\n" ) };
256
257 for ( const auto &headerLine : httpHeaders )
258 {
259 const auto headerColonPos { headerLine.indexOf( ':' ) };
260 if ( headerColonPos > 0 )
261 {
262 headers.insert( headerLine.left( headerColonPos ), headerLine.mid( headerColonPos + 2 ) );
263 }
264 }
265
266 const auto headersSize { endHeadersPos + 4 };
267
268 // Check for content length and if we have got all data
269 if ( headers.contains( QStringLiteral( "Content-Length" ) ) )
270 {
271 bool ok;
272 const int contentLength { headers.value( QStringLiteral( "Content-Length" ) ).toInt( &ok ) };
273 if ( ok && contentLength > incomingData->length() - headersSize )
274 {
275 return;
276 }
277 }
278
279 // At this point we should have read all data:
280 // disconnect the lambdas
281 delete context;
282
283 // Build URL from env ...
284 QString url { qgetenv( "REQUEST_URI" ) };
285 // ... or from server ip/port and request path
286 if ( url.isEmpty() )
287 {
288 // cppcheck-suppress containerOutOfBounds
289 const QString path { firstLinePieces.at( 1 ) };
290 // Take Host header if defined
291 if ( headers.contains( QStringLiteral( "Host" ) ) )
292 {
293 url = QStringLiteral( "http://%1%2" ).arg( headers.value( QStringLiteral( "Host" ) ), path );
294 }
295 else
296 {
297 url = QStringLiteral( "http://%1:%2%3" ).arg( ipAddress ).arg( port ).arg( path );
298 }
299 }
300
301 // Inefficient copy :(
302 QByteArray data { incomingData->mid( headersSize ).toUtf8() };
303
304 if ( !incomingData->isEmpty() && clientConnection->state() == QAbstractSocket::SocketState::ConnectedState )
305 {
306 auto requestContext = new RequestContext {
307 clientConnection,
308 firstLinePieces.join( ' ' ),
309 std::chrono::steady_clock::now(),
310 { url, method, headers, &data },
311 {},
312 };
313 REQUEST_QUEUE_MUTEX.lock();
314 REQUEST_QUEUE.enqueue( requestContext );
315 REQUEST_QUEUE_MUTEX.unlock();
316 REQUEST_WAIT_CONDITION.notify_one();
317 }
318 }
319 catch ( HttpException &ex )
320 {
321 if ( clientConnection->state() == QAbstractSocket::SocketState::ConnectedState )
322 {
323 // Output stream: send error
324 clientConnection->write( QStringLiteral( "HTTP/1.0 %1 %2\r\n" ).arg( 500 ).arg( knownStatuses.value( 500 ) ).toUtf8() );
325 clientConnection->write( QStringLiteral( "Server: QGIS\r\n" ).toUtf8() );
326 clientConnection->write( "\r\n" );
327 clientConnection->write( ex.message().toUtf8() );
328
329 std::cout << QStringLiteral( "\033[1;31m%1 [%2] \"%3\" - - 500\033[0m" )
330 .arg( clientConnection->peerAddress().toString() )
331 .arg( QDateTime::currentDateTime().toString() )
332 .arg( ex.message() )
333 .toStdString()
334 << std::endl;
335
336 clientConnection->disconnectFromHost();
337 }
338 }
339 } );
340 } );
341 }
342 }
343
344 ~TcpServerWorker()
345 {
346 mTcpServer.close();
347 }
348
349 bool isListening() const
350 {
351 return mIsListening;
352 }
353
354 public slots:
355
356 // Outgoing connection handler
357 void responseReady( RequestContext *requestContext ) //#spellok
358 {
359 std::unique_ptr<RequestContext> request { requestContext };
360 const auto elapsedTime { std::chrono::steady_clock::now() - request->startTime };
361
362 const auto &response { request->response };
363 const auto &clientConnection { request->clientConnection };
364
365 if ( !clientConnection || clientConnection->state() != QAbstractSocket::SocketState::ConnectedState )
366 {
367 std::cout << "Connection reset by peer" << std::endl;
368 return;
369 }
370
371 // Output stream
372 if ( -1 == clientConnection->write( QStringLiteral( "HTTP/1.0 %1 %2\r\n" ).arg( response.statusCode() ).arg( knownStatuses.value( response.statusCode(), QStringLiteral( "Unknown response code" ) ) ).toUtf8() ) )
373 {
374 std::cout << "Cannot write to output socket" << std::endl;
375 clientConnection->disconnectFromHost();
376 return;
377 }
378
379 clientConnection->write( QStringLiteral( "Server: QGIS\r\n" ).toUtf8() );
380 const auto responseHeaders { response.headers() };
381 for ( auto it = responseHeaders.constBegin(); it != responseHeaders.constEnd(); ++it )
382 {
383 clientConnection->write( QStringLiteral( "%1: %2\r\n" ).arg( it.key(), it.value() ).toUtf8() );
384 }
385 clientConnection->write( "\r\n" );
386 const QByteArray body { response.body() };
387 clientConnection->write( body );
388
389 // 10.185.248.71 [09/Jan/2015:19:12:06 +0000] 808840 <time> "GET / HTTP/1.1" 500"
390 std::cout << QStringLiteral( "\033[1;92m%1 [%2] %3 %4ms \"%5\" %6\033[0m" )
391 .arg( clientConnection->peerAddress().toString(), QDateTime::currentDateTime().toString(), QString::number( body.size() ), QString::number( std::chrono::duration_cast<std::chrono::milliseconds>( elapsedTime ).count() ), request->httpHeader, QString::number( response.statusCode() ) )
392 .toStdString()
393 << std::endl;
394
395 // This will trigger delete later on the socket object
396 clientConnection->disconnectFromHost();
397 }
398
399 private:
400 QTcpServer mTcpServer;
401 qlonglong mConnectionCounter = 0;
402 bool mIsListening = false;
403};
404
405
406class TcpServerThread : public QThread
407{
408 Q_OBJECT
409
410 public:
411 TcpServerThread( const QString &ipAddress, const int port )
412 : mIpAddress( ipAddress )
413 , mPort( port )
414 {
415 }
416
417 void emitResponseReady( RequestContext *requestContext ) //#spellok
418 {
419 if ( requestContext->clientConnection )
420 emit responseReady( requestContext ); //#spellok
421 }
422
423 void run()
424 {
425 const TcpServerWorker worker( mIpAddress, mPort );
426 if ( !worker.isListening() )
427 {
428 emit serverError();
429 }
430 else
431 {
432 // Forward signal to worker
433 connect( this, &TcpServerThread::responseReady, &worker, &TcpServerWorker::responseReady ); //#spellok
434 QThread::run();
435 }
436 }
437
438 signals:
439
440 void responseReady( RequestContext *requestContext ); //#spellok
441 void serverError();
442
443 private:
444 QString mIpAddress;
445 int mPort;
446};
447
448
449class QueueMonitorThread : public QThread
450{
451 Q_OBJECT
452
453 public:
454 void run()
455 {
456 while ( mIsRunning )
457 {
458 std::unique_lock<std::mutex> requestLocker( REQUEST_QUEUE_MUTEX );
459 REQUEST_WAIT_CONDITION.wait( requestLocker, [=] { return !mIsRunning || !REQUEST_QUEUE.isEmpty(); } );
460 if ( mIsRunning )
461 {
462 // Lock if server is running
463 SERVER_MUTEX.lock();
464 emit requestReady( REQUEST_QUEUE.dequeue() );
465 }
466 }
467 }
468
469 signals:
470
471 void requestReady( RequestContext *requestContext );
472
473 public slots:
474
475 void stop()
476 {
477 mIsRunning = false;
478 }
479
480 private:
481 bool mIsRunning = true;
482};
483
484int main( int argc, char *argv[] )
485{
486 // Test if the environ variable DISPLAY is defined
487 // if it's not, the server is running in offscreen mode
488 // Qt supports using various QPA (Qt Platform Abstraction) back ends
489 // for rendering. You can specify the back end to use with the environment
490 // variable QT_QPA_PLATFORM when invoking a Qt-based application.
491 // Available platform plugins are: directfbegl, directfb, eglfs, linuxfb,
492 // minimal, minimalegl, offscreen, wayland-egl, wayland, xcb.
493 // https://www.ics.com/blog/qt-tips-and-tricks-part-1
494 // http://doc.qt.io/qt-5/qpa.html
495 const QString display { qgetenv( "DISPLAY" ) };
496 bool withDisplay = true;
497 if ( display.isEmpty() )
498 {
499 withDisplay = false;
500 qputenv( "QT_QPA_PLATFORM", "offscreen" );
501 }
502
503 // since version 3.0 QgsServer now needs a qApp so initialize QgsApplication
504 const QgsApplication app( argc, argv, withDisplay, QString(), QStringLiteral( "QGIS Development Server" ) );
505
506 QCoreApplication::setOrganizationName( QgsApplication::QGIS_ORGANIZATION_NAME );
507 QCoreApplication::setOrganizationDomain( QgsApplication::QGIS_ORGANIZATION_DOMAIN );
508 QCoreApplication::setApplicationName( "QGIS Development Server" );
509 QCoreApplication::setApplicationVersion( VERSION );
510
511 if ( !withDisplay )
512 {
513 QgsMessageLog::logMessage( "DISPLAY environment variable is not set, running in offscreen mode, all printing capabilities will not be available.\n"
514 "Consider installing an X server like 'xvfb' and export DISPLAY to the actual display value.",
515 "Server", Qgis::MessageLevel::Warning );
516 }
517
518#ifdef Q_OS_WIN
519 // Initialize font database before fcgi_accept.
520 // When using FCGI with IIS, environment variables (QT_QPA_FONTDIR in this case) are lost after fcgi_accept().
521 QFontDatabase fontDB;
522#endif
523
524 // The port to listen
525 serverPort = qgetenv( "QGIS_SERVER_PORT" );
526 // The address to listen
527 ipAddress = qgetenv( "QGIS_SERVER_ADDRESS" );
528
529 if ( serverPort.isEmpty() )
530 {
531 serverPort = QStringLiteral( "8000" );
532 }
533
534 if ( ipAddress.isEmpty() )
535 {
536 ipAddress = QStringLiteral( "localhost" );
537 }
538
539 QCommandLineParser parser;
540 parser.setApplicationDescription( QObject::tr( "QGIS Development Server %1" ).arg( VERSION ) );
541 parser.addHelpOption();
542
543 const QCommandLineOption versionOption( QStringList() << "v" << "version", QObject::tr( "Version of QGIS and libraries" ) );
544 parser.addOption( versionOption );
545
546 parser.addPositionalArgument( QStringLiteral( "addressAndPort" ), QObject::tr( "Address and port (default: \"localhost:8000\")\n"
547 "address and port can also be specified with the environment\n"
548 "variables QGIS_SERVER_ADDRESS and QGIS_SERVER_PORT." ),
549 QStringLiteral( "[address:port]" ) );
550 const QCommandLineOption logLevelOption( "l", QObject::tr( "Log level (default: 0)\n"
551 "0: INFO\n"
552 "1: WARNING\n"
553 "2: CRITICAL" ),
554 "logLevel", "0" );
555 parser.addOption( logLevelOption );
556
557 const QCommandLineOption projectOption( "p", QObject::tr( "Path to a QGIS project file (*.qgs or *.qgz),\n"
558 "if specified it will override the query string MAP argument\n"
559 "and the QGIS_PROJECT_FILE environment variable." ),
560 "projectPath", "" );
561 parser.addOption( projectOption );
562
563 parser.process( app );
564
565 if ( parser.isSet( versionOption ) )
566 {
567 std::cout << QgsCommandLineUtils::allVersions().toStdString();
568 return 0;
569 }
570
571 const QStringList args = parser.positionalArguments();
572
573 if ( args.size() == 1 )
574 {
575 const QStringList addressAndPort { args.at( 0 ).split( ':' ) };
576 if ( addressAndPort.size() == 2 )
577 {
578 ipAddress = addressAndPort.at( 0 );
579 // cppcheck-suppress containerOutOfBounds
580 serverPort = addressAndPort.at( 1 );
581 }
582 }
583
584 const QString logLevel = parser.value( logLevelOption );
585 qunsetenv( "QGIS_SERVER_LOG_FILE" );
586 qputenv( "QGIS_SERVER_LOG_LEVEL", logLevel.toUtf8() );
587 qputenv( "QGIS_SERVER_LOG_STDERR", "1" );
588
589 QgsServer server;
590
591 if ( !parser.value( projectOption ).isEmpty() )
592 {
593 // Check it!
594 const QString projectFilePath { parser.value( projectOption ) };
596 {
597 std::cout << QObject::tr( "Project file not found, the option will be ignored." ).toStdString() << std::endl;
598 }
599 else
600 {
601 qputenv( "QGIS_PROJECT_FILE", projectFilePath.toUtf8() );
602 }
603 }
604
605 // Disable parallel rendering because if its internal loop
606 //qputenv( "QGIS_SERVER_PARALLEL_RENDERING", "0" );
607
608
609#ifdef HAVE_SERVER_PYTHON_PLUGINS
610 server.initPython();
611#endif
612
613 // TCP thread
614 TcpServerThread tcpServerThread { ipAddress, serverPort.toInt() };
615
616 bool isTcpError = false;
617 TcpServerThread::connect( &tcpServerThread, &TcpServerThread::serverError, qApp, [&] {
618 isTcpError = true;
619 qApp->quit(); }, Qt::QueuedConnection );
620
621 // Monitoring thread
622 QueueMonitorThread queueMonitorThread;
623 QueueMonitorThread::connect( &queueMonitorThread, &QueueMonitorThread::requestReady, qApp, [&]( RequestContext *requestContext ) {
624 if ( requestContext->clientConnection && requestContext->clientConnection->isValid() )
625 {
626 server.handleRequest( requestContext->request, requestContext->response );
627 SERVER_MUTEX.unlock();
628 }
629 else
630 {
631 delete requestContext;
632 SERVER_MUTEX.unlock();
633 return;
634 }
635 if ( requestContext->clientConnection && requestContext->clientConnection->isValid() )
636 tcpServerThread.emitResponseReady( requestContext ); //#spellok
637 else
638 delete requestContext;
639 } );
640
641 // Exit handlers
642#ifndef Q_OS_WIN
643
644 auto exitHandler = []( int signal ) {
645 std::cout << QStringLiteral( "Signal %1 received: quitting" ).arg( signal ).toStdString() << std::endl;
646 IS_RUNNING = 0;
647 qApp->quit();
648 };
649
650 signal( SIGTERM, exitHandler );
651 signal( SIGABRT, exitHandler );
652 signal( SIGINT, exitHandler );
653 signal( SIGPIPE, []( int ) {
654 std::cerr << QStringLiteral( "Signal SIGPIPE received: ignoring" ).toStdString() << std::endl;
655 } );
656
657#endif
658
659 tcpServerThread.start();
660 queueMonitorThread.start();
661
662 QgsApplication::exec();
663 // Wait for threads
664 tcpServerThread.exit();
665 tcpServerThread.wait();
666 queueMonitorThread.stop();
667 REQUEST_WAIT_CONDITION.notify_all();
668 queueMonitorThread.wait();
670
671 return isTcpError ? 1 : 0;
672}
673
674#include "qgis_mapserver.moc"
675
@ DontLoad3DViews
Skip loading 3D views.
@ DontStoreOriginalStyles
Skip the initial XML style storage for layers. Useful for minimising project load times in non-intera...
@ DontUpgradeAnnotations
Don't upgrade old annotation items to QgsAnnotationItem.
@ DontLoadLayouts
Don't load print layouts. Improves project read time if layouts are not required, and allows projects...
@ DontResolveLayers
Don't resolve layer paths (i.e. don't load any layer content). Dramatically improves project read tim...
@ Warning
Warning message.
Definition qgis.h:156
Extends QApplication to provide access to QGIS specific resources such as theme paths,...
static void exitQgis()
deletes provider registry and map layer registry
static const char * QGIS_ORGANIZATION_DOMAIN
static const char * QGIS_ORGANIZATION_NAME
Class defining request with data.
Class defining buffered response.
static QString allVersions()
Display all versions in the standard output stream.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
static QgsProject * instance()
Returns the QgsProject singleton instance.
Method
HTTP Method (or equivalent) used for the request.
QMap< QString, QString > Headers
The QgsServer class provides OGC web services.
Definition qgsserver.h:49
int main(int argc, char *argv[])