QGIS API Documentation  3.12.1-București (121cc00ff0)
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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  std::cout << QObject::tr( "QGIS Development Server listening on http://%1:%2" )
209  .arg( ipAddress ).arg( port ).toStdString() << std::endl;
210 
211 #ifndef Q_OS_WIN
212  std::cout << QObject::tr( "CTRL+C to exit" ).toStdString() << std::endl;
213 #endif
214 
215  QAtomicInt connCounter { 0 };
216 
217  static const QMap<int, QString> knownStatuses
218  {
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" ) }
234  };
235 
236  QgsServer server;
237 
238 #ifdef HAVE_SERVER_PYTHON_PLUGINS
239  server.initPython();
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 );
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  // Build URL from env ...
326  QString url { qgetenv( "REQUEST_URI" ) };
327  // ... or from server ip/port and request path
328  if ( url.isEmpty() )
329  {
330  const QString path { firstLinePieces.at( 1 )};
331  url = QStringLiteral( "http://%1:%2%3" ).arg( ipAddress ).arg( port ).arg( path );
332  }
333 
334  const QString protocol { firstLinePieces.at( 2 )};
335  if ( protocol != QStringLiteral( "HTTP/1.0" ) && protocol != QStringLiteral( "HTTP/1.1" ) )
336  {
337  throw HttpException( QStringLiteral( "HTTP error unsupported protocol: %1" ).arg( protocol ) );
338  }
339 
340  // Headers
342  int endHeadersPos { incomingData.indexOf( "\r\n\r\n" ) };
343 
344  if ( endHeadersPos == -1 )
345  {
346  throw HttpException( QStringLiteral( "HTTP error finding headers" ) );
347  }
348 
349  const QStringList httpHeaders { incomingData.mid( firstLinePos + 2, endHeadersPos - firstLinePos ).split( "\r\n" ) };
350 
351  for ( const auto &headerLine : httpHeaders )
352  {
353  const int headerColonPos { headerLine.indexOf( ':' ) };
354  if ( headerColonPos > 0 )
355  {
356  headers.insert( headerLine.left( headerColonPos ), headerLine.mid( headerColonPos + 2 ) );
357  }
358  }
359 
360  // Inefficient copy :(
361  QByteArray data { incomingData.mid( endHeadersPos + 4 ).toUtf8() };
362 
363  auto start = std::chrono::steady_clock::now();
364 
365  QgsBufferServerRequest request { url, method, headers, &data };
366  QgsBufferServerResponse response;
367 
368  server.handleRequest( request, response );
369 
370  // The QGIS server machinery calls processEvents and has internal loop events
371  // that might change the connection state
372  if ( clientConnection->state() == QAbstractSocket::SocketState::ConnectedState )
373  {
374  clientConnection->connect( clientConnection, &QAbstractSocket::disconnected,
375  clientConnection, connectionDeleter );
376  }
377  else
378  {
379  connCounter --;
380  clientConnection->deleteLater();
381  return;
382  }
383 
384  auto elapsedTime { std::chrono::steady_clock::now() - start };
385 
386  if ( ! knownStatuses.contains( response.statusCode() ) )
387  {
388  throw HttpException( QStringLiteral( "HTTP error unsupported status code: %1" ).arg( response.statusCode() ) );
389  }
390 
391  // Output stream
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 )
396  {
397  clientConnection->write( QStringLiteral( "%1: %2\r\n" ).arg( it.key(), it.value() ).toUtf8() );
398  }
399  clientConnection->write( "\r\n" );
400  const QByteArray body { response.body() };
401  clientConnection->write( body );
402 
403  // 10.185.248.71 [09/Jan/2015:19:12:06 +0000] 808840 <time> "GET / HTTP/1.1" 500"
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( ' ' ),
410  QString::number( response.statusCode() ) )
411  .toStdString()
412  << std::endl;
413 
414  clientConnection->disconnectFromHost();
415  }
416  catch ( HttpException &ex )
417  {
418 
419  if ( clientConnection->state() == QAbstractSocket::SocketState::ConnectedState )
420  {
421  clientConnection->connect( clientConnection, &QAbstractSocket::disconnected,
422  clientConnection, connectionDeleter );
423  }
424  else
425  {
426  connCounter --;
427  clientConnection->deleteLater();
428  return;
429  }
430 
431  // Output stream: send error
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() );
436 
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;
441 
442  clientConnection->disconnectFromHost();
443  }
444 
445  } );
446 
447  } );
448 
449  }
450 
451  // Exit handlers
452 #ifndef Q_OS_WIN
453 
454  auto exitHandler = [ ]( int signal )
455  {
456  std::cout << QStringLiteral( "Signal %1 received: quitting" ).arg( signal ).toStdString() << std::endl;
457  qApp->quit();
458  };
459 
460  signal( SIGTERM, exitHandler );
461  signal( SIGABRT, exitHandler );
462  signal( SIGINT, exitHandler );
463  signal( SIGPIPE, [ ]( int )
464  {
465  std::cerr << QStringLiteral( "Signal SIGPIPE received: ignoring" ).toStdString() << std::endl;
466  } );
467 
468 #endif
469 
470  app.exec();
471  app.exitQgis();
472  return 0;
473 }
474 
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.
Definition: qgsserver.h:48
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.
Definition: qgsserver.cpp:304