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