QGIS API Documentation  3.14.0-Pi (9f7028fd23)
qgis_mapserver.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgs_mapserver.cpp
3 
4 A QGIS development HTTP server for testing/development purposes.
5 The server listens to localhost:8000, the address and port can be changed with the
6 environment variable QGIS_SERVER_ADDRESS and QGIS_SERVER_PORT or passing <address>:<port>
7 on the command line.
8 
9 All requests and application messages are printed to the standard output,
10 while QGIS server internal logging is printed to stderr.
11 
12  -------------------
13  begin : Jan 17 2020
14  copyright : (C) 2020by 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 //for CMAKE_INSTALL_PREFIX
28 #include "qgsconfig.h"
29 #include "qgsserver.h"
30 #include "qgsbufferserverrequest.h"
32 #include "qgsapplication.h"
33 #include "qgsmessagelog.h"
34 
35 #include <QFontDatabase>
36 #include <QString>
37 #include <QTcpServer>
38 #include <QTcpSocket>
39 #include <QNetworkInterface>
40 #include <QCommandLineParser>
41 #include <QObject>
42 
43 
44 #ifndef Q_OS_WIN
45 #include <csignal>
46 #endif
47 
48 #include <string>
49 #include <chrono>
50 
52 
56 class HttpException: public std::exception
57 {
58 
59  public:
60 
64  HttpException( const QString &message )
65  : mMessage( message )
66  {
67  }
68 
72  QString message( )
73  {
74  return mMessage;
75  }
76 
77  private:
78 
79  QString mMessage;
80 
81 };
82 
83 int main( int argc, char *argv[] )
84 {
85  // Test if the environ variable DISPLAY is defined
86  // if it's not, the server is running in offscreen mode
87  // Qt supports using various QPA (Qt Platform Abstraction) back ends
88  // for rendering. You can specify the back end to use with the environment
89  // variable QT_QPA_PLATFORM when invoking a Qt-based application.
90  // Available platform plugins are: directfbegl, directfb, eglfs, linuxfb,
91  // minimal, minimalegl, offscreen, wayland-egl, wayland, xcb.
92  // https://www.ics.com/blog/qt-tips-and-tricks-part-1
93  // http://doc.qt.io/qt-5/qpa.html
94  const QString display { qgetenv( "DISPLAY" ) };
95  bool withDisplay = true;
96  if ( display.isEmpty() )
97  {
98  withDisplay = false;
99  qputenv( "QT_QPA_PLATFORM", "offscreen" );
100  }
101 
102  // since version 3.0 QgsServer now needs a qApp so initialize QgsApplication
103  QgsApplication app( argc, argv, withDisplay, QString(), QStringLiteral( "QGIS Development Server" ) );
104 
105  QCoreApplication::setOrganizationName( QgsApplication::QGIS_ORGANIZATION_NAME );
106  QCoreApplication::setOrganizationDomain( QgsApplication::QGIS_ORGANIZATION_DOMAIN );
107  QCoreApplication::setApplicationName( "QGIS Development Server" );
108  QCoreApplication::setApplicationVersion( "1.0" );
109 
110  if ( ! withDisplay )
111  {
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 );
114  }
115 
116 #ifdef Q_OS_WIN
117  // Initialize font database before fcgi_accept.
118  // When using FCGI with IIS, environment variables (QT_QPA_FONTDIR in this case) are lost after fcgi_accept().
119  QFontDatabase fontDB;
120 #endif
121 
122  // The port to listen
123  QString serverPort { qgetenv( "QGIS_SERVER_PORT" ) };
124  // The address to listen
125  QString ipAddress { qgetenv( "QGIS_SERVER_ADDRESS" ) };
126 
127  if ( serverPort.isEmpty() )
128  {
129  serverPort = QStringLiteral( "8000" );
130  }
131 
132  if ( ipAddress.isEmpty() )
133  {
134  ipAddress = QStringLiteral( "localhost" );
135  }
136 
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"
146  "0: INFO\n"
147  "1: WARNING\n"
148  "2: CRITICAL" ), "logLevel", "0" );
149  parser.addOption( logLevelOption );
150 
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 );
155 
156  parser.process( app );
157  const QStringList args = parser.positionalArguments();
158 
159  if ( args.size() == 1 )
160  {
161  QStringList addressAndPort { args.at( 0 ).split( ':' ) };
162  if ( addressAndPort.size() == 2 )
163  {
164  ipAddress = addressAndPort.at( 0 );
165  serverPort = addressAndPort.at( 1 );
166  }
167  }
168 
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" );
173 
174  if ( ! parser.value( projectOption ).isEmpty( ) )
175  {
176  // Check it!
177  const QString projectFilePath { parser.value( projectOption ) };
178  if ( ! QFile::exists( projectFilePath ) )
179  {
180  std::cout << QObject::tr( "Project file not found, the option will be ignored." ).toStdString() << std::endl;
181  }
182  else
183  {
184  qputenv( "QGIS_PROJECT_FILE", projectFilePath.toUtf8() );
185  }
186  }
187 
188  // Disable parallel rendering because if its internal loop
189  //qputenv( "QGIS_SERVER_PARALLEL_RENDERING", "0" );
190 
191  // Create server
192  QTcpServer tcpServer;
193 
194  QHostAddress address { QHostAddress::AnyIPv4 };
195  address.setAddress( ipAddress );
196 
197  if ( ! tcpServer.listen( address, serverPort.toInt( ) ) )
198  {
199  std::cerr << QObject::tr( "Unable to start the server: %1." )
200  .arg( tcpServer.errorString() ).toStdString() << std::endl;
201  tcpServer.close();
202  app.exitQgis();
203  return 1;
204  }
205  else
206  {
207  const int port { tcpServer.serverPort() };
208 
209  QAtomicInt connCounter { 0 };
210 
211  static const QMap<int, QString> knownStatuses
212  {
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" ) }
228  };
229 
230  QgsServer server;
231 
232 #ifdef HAVE_SERVER_PYTHON_PLUGINS
233  server.initPython();
234 #endif
235 
236  std::cout << QObject::tr( "QGIS Development Server listening on http://%1:%2" )
237  .arg( ipAddress ).arg( port ).toStdString() << std::endl;
238 #ifndef Q_OS_WIN
239  std::cout << QObject::tr( "CTRL+C to exit" ).toStdString() << std::endl;
240 #endif
241 
242  // Starts HTTP loop with a poor man's HTTP parser
243  tcpServer.connect( &tcpServer, &QTcpServer::newConnection, [ & ]
244  {
245  QTcpSocket *clientConnection = tcpServer.nextPendingConnection();
246 
247  connCounter++;
248 
249  //qDebug() << "Active connections: " << connCounter;
250 
251  // Lambda disconnect context
252  QObject *context { new QObject };
253 
254  // Deletes the connection later
255  auto connectionDeleter = [ =, &connCounter ]()
256  {
257  clientConnection->deleteLater();
258  connCounter--;
259  };
260 
261  // This will delete the connection when disconnected before ready read is called
262  clientConnection->connect( clientConnection, &QAbstractSocket::disconnected, context, connectionDeleter, Qt::QueuedConnection );
263 
264  // Incoming connection parser
265  clientConnection->connect( clientConnection, &QIODevice::readyRead, context, [ =, &server, &connCounter ] {
266 
267  // Disconnect the lambdas
268  delete context;
269 
270  // Read all incoming data
271  QString incomingData;
272  while ( clientConnection->bytesAvailable() > 0 )
273  {
274  incomingData += clientConnection->readAll();
275  }
276 
277  try
278  {
279  // Parse protocol and URL GET /path HTTP/1.1
280  int firstLinePos { incomingData.indexOf( "\r\n" ) };
281  if ( firstLinePos == -1 )
282  {
283  throw HttpException( QStringLiteral( "HTTP error finding protocol header" ) );
284  }
285 
286  const QString firstLine { incomingData.left( firstLinePos ) };
287  const QStringList firstLinePieces { firstLine.split( ' ' ) };
288  if ( firstLinePieces.size() != 3 )
289  {
290  throw HttpException( QStringLiteral( "HTTP error splitting protocol header" ) );
291  }
292 
293  const QString methodString { firstLinePieces.at( 0 ) };
294 
296  if ( methodString == "GET" )
297  {
298  method = QgsServerRequest::Method::GetMethod;
299  }
300  else if ( methodString == "POST" )
301  {
302  method = QgsServerRequest::Method::PostMethod;
303  }
304  else if ( methodString == "HEAD" )
305  {
306  method = QgsServerRequest::Method::HeadMethod;
307  }
308  else if ( methodString == "PUT" )
309  {
310  method = QgsServerRequest::Method::PutMethod;
311  }
312  else if ( methodString == "PATCH" )
313  {
314  method = QgsServerRequest::Method::PatchMethod;
315  }
316  else if ( methodString == "DELETE" )
317  {
318  method = QgsServerRequest::Method::DeleteMethod;
319  }
320  else
321  {
322  throw HttpException( QStringLiteral( "HTTP error unsupported method: %1" ).arg( methodString ) );
323  }
324 
325  const QString protocol { firstLinePieces.at( 2 )};
326  if ( protocol != QStringLiteral( "HTTP/1.0" ) && protocol != QStringLiteral( "HTTP/1.1" ) )
327  {
328  throw HttpException( QStringLiteral( "HTTP error unsupported protocol: %1" ).arg( protocol ) );
329  }
330 
331  // Headers
333  int endHeadersPos { incomingData.indexOf( "\r\n\r\n" ) };
334 
335  if ( endHeadersPos == -1 )
336  {
337  throw HttpException( QStringLiteral( "HTTP error finding headers" ) );
338  }
339 
340  const QStringList httpHeaders { incomingData.mid( firstLinePos + 2, endHeadersPos - firstLinePos ).split( "\r\n" ) };
341 
342  for ( const auto &headerLine : httpHeaders )
343  {
344  const int headerColonPos { headerLine.indexOf( ':' ) };
345  if ( headerColonPos > 0 )
346  {
347  headers.insert( headerLine.left( headerColonPos ), headerLine.mid( headerColonPos + 2 ) );
348  }
349  }
350 
351  // Build URL from env ...
352  QString url { qgetenv( "REQUEST_URI" ) };
353  // ... or from server ip/port and request path
354  if ( url.isEmpty() )
355  {
356  const QString path { firstLinePieces.at( 1 )};
357  // Take Host header if defined
358  if ( headers.contains( QStringLiteral( "Host" ) ) )
359  {
360  url = QStringLiteral( "http://%1%2" ).arg( headers.value( QStringLiteral( "Host" ) ) ).arg( path );
361  }
362  else
363  {
364  url = QStringLiteral( "http://%1:%2%3" ).arg( ipAddress ).arg( port ).arg( path );
365  }
366  }
367 
368  // Inefficient copy :(
369  QByteArray data { incomingData.mid( endHeadersPos + 4 ).toUtf8() };
370 
371  auto start = std::chrono::steady_clock::now();
372 
373  QgsBufferServerRequest request { url, method, headers, &data };
374  QgsBufferServerResponse response;
375 
376  server.handleRequest( request, response );
377 
378  // The QGIS server machinery calls processEvents and has internal loop events
379  // that might change the connection state
380  if ( clientConnection->state() == QAbstractSocket::SocketState::ConnectedState )
381  {
382  clientConnection->connect( clientConnection, &QAbstractSocket::disconnected,
383  clientConnection, connectionDeleter, Qt::QueuedConnection );
384  }
385  else
386  {
387  connCounter --;
388  clientConnection->deleteLater();
389  return;
390  }
391 
392  auto elapsedTime { std::chrono::steady_clock::now() - start };
393 
394  if ( ! knownStatuses.contains( response.statusCode() ) )
395  {
396  throw HttpException( QStringLiteral( "HTTP error unsupported status code: %1" ).arg( response.statusCode() ) );
397  }
398 
399  // Output stream
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 )
404  {
405  clientConnection->write( QStringLiteral( "%1: %2\r\n" ).arg( it.key(), it.value() ).toUtf8() );
406  }
407  clientConnection->write( "\r\n" );
408  const QByteArray body { response.body() };
409  clientConnection->write( body );
410 
411  // 10.185.248.71 [09/Jan/2015:19:12:06 +0000] 808840 <time> "GET / HTTP/1.1" 500"
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( ' ' ),
418  QString::number( response.statusCode() ) )
419  .toStdString()
420  << std::endl;
421 
422  clientConnection->disconnectFromHost();
423  }
424  catch ( HttpException &ex )
425  {
426 
427  if ( clientConnection->state() == QAbstractSocket::SocketState::ConnectedState )
428  {
429  clientConnection->connect( clientConnection, &QAbstractSocket::disconnected,
430  clientConnection, connectionDeleter );
431  }
432  else
433  {
434  connCounter --;
435  clientConnection->deleteLater();
436  return;
437  }
438 
439  // Output stream: send error
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() );
444 
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;
449 
450  clientConnection->disconnectFromHost();
451  }
452 
453  }, Qt::QueuedConnection );
454 
455  } );
456 
457  }
458 
459  // Exit handlers
460 #ifndef Q_OS_WIN
461 
462  auto exitHandler = [ ]( int signal )
463  {
464  std::cout << QStringLiteral( "Signal %1 received: quitting" ).arg( signal ).toStdString() << std::endl;
465  qApp->quit();
466  };
467 
468  signal( SIGTERM, exitHandler );
469  signal( SIGABRT, exitHandler );
470  signal( SIGINT, exitHandler );
471  signal( SIGPIPE, [ ]( int )
472  {
473  std::cerr << QStringLiteral( "Signal SIGPIPE received: ignoring" ).toStdString() << std::endl;
474  } );
475 
476 #endif
477 
478  app.exec();
479  app.exitQgis();
480  return 0;
481 }
482 
QgsApplication::QGIS_ORGANIZATION_NAME
static const char * QGIS_ORGANIZATION_NAME
Definition: qgsapplication.h:147
main
int main(int argc, char *argv[])
Definition: qgis_map_serv.cpp:44
QgsBufferServerResponse
Class defining buffered response.
Definition: qgsbufferserverresponse.h:37
QgsServer::handleRequest
void handleRequest(QgsServerRequest &request, QgsServerResponse &response, const QgsProject *project=nullptr)
Handles the request.
Definition: qgsserver.cpp:297
Qgis::Warning
@ Warning
Definition: qgis.h:104
QgsBufferServerRequest
Class defining request with data.
Definition: qgsbufferserverrequest.h:31
qgsapplication.h
QgsBufferServerResponse::headers
QMap< QString, QString > headers() const override
Returns all the headers.
Definition: qgsbufferserverresponse.h:67
QgsBufferServerResponse::body
QByteArray body() const
Returns body.
Definition: qgsbufferserverresponse.h:140
qgsserver.h
QgsBufferServerResponse::statusCode
int statusCode() const override
Returns the http status code.
Definition: qgsbufferserverresponse.h:83
qgsbufferserverrequest.h
QgsApplication
Definition: qgsapplication.h:78
QgsServer
Definition: qgsserver.h:48
QgsMessageLog::logMessage
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).
Definition: qgsmessagelog.cpp:27
QgsServerRequest::Method
Method
HTTP Method (or equivalent) used for the request.
Definition: qgsserverrequest.h:65
QgsServerRequest::Headers
QMap< QString, QString > Headers
Definition: qgsserverrequest.h:60
qgsbufferserverresponse.h
QgsApplication::QGIS_ORGANIZATION_DOMAIN
static const char * QGIS_ORGANIZATION_DOMAIN
Definition: qgsapplication.h:148
qgsmessagelog.h