QGIS API Documentation 3.41.0-Master (45a0abf3bec)
Loading...
Searching...
No Matches
qgsfcgiserverresponse.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsfcgiserverresponse.cpp
3
4 Define response wrapper for fcgi response
5 -------------------
6 begin : 2017-01-03
7 copyright : (C) 2017 by David Marteau
8 email : david dot marteau at 3liz dot com
9 ***************************************************************************/
10
11/***************************************************************************
12 * *
13 * This program is free software; you can redistribute it and/or modify *
14 * it under the terms of the GNU General Public License as published by *
15 * the Free Software Foundation; either version 2 of the License, or *
16 * (at your option) any later version. *
17 * *
18 ***************************************************************************/
19
20#include "qgis.h"
22#include "moc_qgsfcgiserverresponse.cpp"
23#include "qgsmessagelog.h"
24#include <fcgi_stdio.h>
25#include <QDebug>
26
27#include "qgslogger.h"
28
29#if defined(Q_OS_UNIX) && !defined(Q_OS_ANDROID)
30#include <sys/types.h>
31#include <sys/socket.h>
32
33//
34// QgsFCGXStreamData copied from libfcgi FCGX_Stream_Data
35//
36typedef struct QgsFCGXStreamData
37{
38 unsigned char *buff; /* buffer after alignment */
39 int bufflen; /* number of bytes buff can store */
40 unsigned char *mBuff; /* buffer as returned by Malloc */
41 unsigned char *buffStop; /* reader: last valid byte + 1 of entire buffer.
42 * stop generally differs from buffStop for
43 * readers because of record structure.
44 * writer: buff + bufflen */
45 int type; /* reader: FCGI_PARAMS or FCGI_STDIN
46 * writer: FCGI_STDOUT or FCGI_STDERR */
47 int eorStop; /* reader: stop stream at end-of-record */
48 int skip; /* reader: don't deliver content bytes */
49 int contentLen; /* reader: bytes of unread content */
50 int paddingLen; /* reader: bytes of unread padding */
51 int isAnythingWritten; /* writer: data has been written to ipcFd */
52 int rawWrite; /* writer: write data without stream headers */
53 FCGX_Request *reqDataPtr; /* request data not specific to one stream */
54} QgsFCGXStreamData;
55#endif
56
58 : mIsResponseFinished( isResponseFinished )
59 , mFeedback( feedback )
60 , mIpcFd( -1 )
61{
62 setObjectName( "FCGI socket monitor" );
63 Q_ASSERT( mIsResponseFinished );
64 Q_ASSERT( mFeedback );
65
66#if defined(Q_OS_UNIX) && !defined(Q_OS_ANDROID)
67 if ( FCGI_stdout && FCGI_stdout->fcgx_stream && FCGI_stdout->fcgx_stream->data )
68 {
69 QgsFCGXStreamData *stream = static_cast<QgsFCGXStreamData *>( FCGI_stdin->fcgx_stream->data );
70 if ( stream && stream->reqDataPtr )
71 {
72 mIpcFd = stream->reqDataPtr->ipcFd;
73 }
74 else
75 {
76 QgsMessageLog::logMessage( QStringLiteral( "FCGI_stdin stream data is null! Socket monitoring disable." ),
77 QStringLiteral( "FCGIServer" ),
79 }
80 }
81 else
82 {
83 QgsMessageLog::logMessage( QStringLiteral( "FCGI_stdin is null! Socket monitoring disable." ),
84 QStringLiteral( "FCGIServer" ),
86 }
87#endif
88}
89
91{
92 if ( mIpcFd < 0 )
93 {
94 QgsMessageLog::logMessage( QStringLiteral( "Socket monitoring disabled: no socket fd!" ),
95 QStringLiteral( "FCGIServer" ),
97 return;
98 }
99
100#if defined(Q_OS_UNIX) && !defined(Q_OS_ANDROID)
101 char c;
102 while ( !*mIsResponseFinished )
103 {
104 const ssize_t x = recv( mIpcFd, &c, 1, MSG_PEEK | MSG_DONTWAIT ); // see https://stackoverflow.com/a/12402596
105 if ( x < 0 )
106 {
107 // Ie. we are still connected but we have an 'error' as there is nothing to read
108 QgsDebugMsgLevel( QStringLiteral( "FCGIServer: remote socket still connected. errno: %1" ).arg( errno ), 5 );
109 }
110 else
111 {
112 // socket closed, nothing can be read
113 QgsDebugMsgLevel( QStringLiteral( "FCGIServer: remote socket has been closed! errno: %1" ).arg( errno ), 2 );
114 mFeedback->cancel();
115 break;
116 }
117
118 QThread::msleep( 333L );
119 }
120
121 if ( *mIsResponseFinished )
122 {
123 QgsDebugMsgLevel( QStringLiteral( "FCGIServer: socket monitoring quits normally." ), 2 );
124 }
125 else
126 {
127 QgsDebugMsgLevel( QStringLiteral( "FCGIServer: socket monitoring quits: no more socket." ), 2 );
128 }
129#endif
130}
131
132
133
134//
135// QgsFcgiServerResponse
136//
138 : mMethod( method )
139 , mFeedback( new QgsFeedback )
140{
141 mBuffer.open( QIODevice::ReadWrite );
143
144 mSocketMonitoringThread = std::make_unique<QgsSocketMonitoringThread>( &mFinished, mFeedback.get() );
145 mSocketMonitoringThread->start();
146}
147
149{
150 mFinished = true;
151 mSocketMonitoringThread->exit();
152 mSocketMonitoringThread->wait();
153}
154
155void QgsFcgiServerResponse::removeHeader( const QString &key )
156{
157 mHeaders.remove( key );
158}
159
160void QgsFcgiServerResponse::setHeader( const QString &key, const QString &value )
161{
162 mHeaders.insert( key, value );
163}
164
165QString QgsFcgiServerResponse::header( const QString &key ) const
166{
167 return mHeaders.value( key );
168}
169
171{
172 return mHeadersSent;
173}
174
176{
177 // fcgi applications must return HTTP status in header
178 mHeaders.insert( QStringLiteral( "Status" ), QStringLiteral( " %1" ).arg( code ) );
179 // Store the code to make it available for plugins
180 mStatusCode = code;
181}
182
183void QgsFcgiServerResponse::sendError( int code, const QString &message )
184{
185 if ( mHeadersSent )
186 {
187 QgsMessageLog::logMessage( "Cannot send error after headers written",
188 QStringLiteral( "FCGIServer" ),
190 return;
191 }
192
193 clear();
194 setStatusCode( code );
195 setHeader( QStringLiteral( "Content-Type" ), QStringLiteral( "text/html;charset=utf-8" ) );
196 write( QStringLiteral( "<html><body>%1</body></html>" ).arg( message ) );
197 finish();
198}
199
201{
202 return &mBuffer;
203}
204
206{
207 if ( mFinished )
208 {
209 QgsMessageLog::logMessage( "finish() called twice",
210 QStringLiteral( "FCGIServer" ),
212 return;
213 }
214
215 if ( mFeedback->isCanceled() )
216 {
217 clear(); // we clear all buffers as the socket is dead
218 FCGI_stdout->fcgx_stream->wasFCloseCalled = true; // avoid sending FCGI end protocol as the socket is dead
219 mFinished = true;
220 return;
221 }
222
223 if ( !mHeadersSent )
224 {
225 if ( ! mHeaders.contains( "Content-Length" ) )
226 {
227 mHeaders.insert( QStringLiteral( "Content-Length" ), QString::number( mBuffer.pos() ) );
228 }
229 }
230 flush();
231 mFinished = true;
232}
233
235{
236 if ( ! mHeadersSent )
237 {
238 // Send all headers
239 QMap<QString, QString>::const_iterator it;
240 for ( it = mHeaders.constBegin(); it != mHeaders.constEnd(); ++it )
241 {
242 fputs( it.key().toUtf8(), FCGI_stdout );
243 fputs( ": ", FCGI_stdout );
244 fputs( it.value().toUtf8(), FCGI_stdout );
245 fputs( "\n", FCGI_stdout );
246 }
247 fputs( "\n", FCGI_stdout );
248 mHeadersSent = true;
249 }
250
251 mBuffer.seek( 0 );
252 if ( mMethod == QgsServerRequest::HeadMethod )
253 {
254 // Ignore data for head method as we only
255 // write headers for HEAD requests
256 mBuffer.buffer().clear();
257 }
258 else if ( mBuffer.bytesAvailable() > 0 )
259 {
260 QByteArray &ba = mBuffer.buffer();
261 const size_t count = fwrite( ( void * )ba.data(), ba.size(), 1, FCGI_stdout );
262#ifdef QGISDEBUG
263 qDebug() << QStringLiteral( "Sent %1 blocks of %2 bytes" ).arg( count ).arg( ba.size() );
264#else
265 Q_UNUSED( count )
266#endif
267 // Reset the internal buffer
268 ba.clear();
269 }
270}
271
272
274{
275 mHeaders.clear();
276 mBuffer.seek( 0 );
277 mBuffer.buffer().clear();
278
279 // Restore default headers
281}
282
283
285{
286 return mBuffer.data();
287}
288
289
291{
292 mBuffer.seek( 0 );
293 mBuffer.buffer().clear();
294}
295
296
298{
299 setHeader( QStringLiteral( "Server" ), QStringLiteral( " QGIS FCGI server - QGIS version %1" ).arg( Qgis::version() ) );
300}
static QString version()
Version string.
Definition qgis.cpp:259
@ Warning
Warning message.
Definition qgis.h:156
void setDefaultHeaders()
Set the default headers.
void clear() override
Reset all headers and content for this response.
void setHeader(const QString &key, const QString &value) override
Set Header entry Add Header entry to the response Note that it is usually an error to set Header afte...
void flush() override
Flushes the current output buffer to the network.
void removeHeader(const QString &key) override
Clear header Undo a previous 'setHeader' call.
QByteArray data() const override
Gets the data written so far.
QIODevice * io() override
Returns the underlying QIODevice.
bool headersSent() const override
Returns true if the headers have already been sent.
void setStatusCode(int code) override
Set the http status code.
QgsFcgiServerResponse(QgsServerRequest::Method method=QgsServerRequest::GetMethod)
Constructor for QgsFcgiServerResponse.
void sendError(int code, const QString &message) override
Send error This method delegates error handling at the server level.
void truncate() override
Truncate data.
void finish() override
Finish the response, ending the transaction.
QString header(const QString &key) const override
Returns the header value.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
void cancel()
Tells the internal routines that the current operation should be canceled. This should be run by the ...
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).
Method
HTTP Method (or equivalent) used for the request.
virtual void write(const QString &data)
Write string This is a convenient method that will write directly to the underlying I/O device.
QgsSocketMonitoringThread(bool *isResponseFinished, QgsFeedback *feedback)
QgsSocketMonitoringThread.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:39