File: server.cpp

package info (click to toggle)
qxmlrpc 0.0.svn6-2
  • links: PTS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, stretch, wheezy
  • size: 392 kB
  • ctags: 200
  • sloc: cpp: 1,621; python: 29; makefile: 23
file content (387 lines) | stat: -rw-r--r-- 11,024 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// vim:tabstop=4:shiftwidth=4:foldmethod=marker:expandtab:cinoptions=(s,U1,m1
// Copyright (C) 2005 Dmitry Poplavsky <dima@thekompany.com>

#include "xmlrpc/server.h"
#include "xmlrpc/server_private.h"
#include "xmlrpc/variant.h"
#include "xmlrpc/request.h"
#include "xmlrpc/response.h"
#include "xmlrpc/serverintrospection.h"

#include <QtNetwork>
#include <QtXml>

namespace  xmlrpc {

class Server::Private
{
public:
    Private() 
    {
        lastRequestId = 0;
    }

    
    QTcpServer *server;

    int lastRequestId;
    QMap< int, QPointer<QTcpSocket> > processingRequests;

    // requestId -> type of return value map
    QMap< int, QVariant::Type > expectedReturnTypes;

    QSet<int> keepAliveRequests;

    ServerIntrospection introspection;

    //send 200/OK http response back to socket
    void sendResponse( QTcpSocket *socket, QByteArray data, bool keepAlive );

};

//send http response back to socket
void Server::Private::sendResponse( QTcpSocket *socket, QByteArray data, bool keepAlive )
{
    QHttpResponseHeader header(200,"OK");
    header.setContentType("text/xml");

    if ( keepAlive ) {
        header.setValue( "Connection", "Keep-Alive" );
    } else {
        header.setValue( "Connection", "Close" );
    }

    header.setValue( "Content-Encoding", "UTF-8" );
    header.setContentLength( data.size() );

    socket->write( header.toString().toUtf8() );
    socket->write( data );


    if ( !keepAlive ) {
        //qDebug() << "close connection";
        socket->close();
        socket->disconnectFromHost();
    }
}

/**
 * Create new xmlrpc::Server instance.
 */
Server::Server( QObject * parent)
: QObject( parent )
{
    d = new Private;
    d->server = new QTcpServer(this);

    connect( d->server, SIGNAL(newConnection()), SLOT(newConnection()) );
}

/** Delete xmlrpc::Server instance. */
Server::~Server()
{
    delete d->server;
    delete d;
}

/**
 * Tells the server to listen for incoming connections on
 * address address and port port. If address is QHostAddress::Any, the server
 * will listen on all network interfaces.
 * 
 * Returns true on success; otherwise returns false.
 * 
 * \sa isListening()
 */
bool Server::listen ( quint16 port, const QHostAddress & address )
{
    return d->server->listen( address, port );
}

/**
 * Returns true if the server is currently listening for
 * incoming connections; otherwise returns false.
 * 
 * \sa listen()
 */
bool Server::isListening() const
{
    return d->server->isListening();
}

/**
 * Register method \a methodName as supported by this server
 * instance.
 * 
 * This allows the server to provide information about methods,
 * parameters and return values to clients.
 * 
 * This data is also used to perform checks for supported
 * methodNames and parameter types before incomingRequest()
 * signal is emited. This allows to remove types checks from
 * the methods implementation and avoid of possible bugs.
 * 
 * Methods registration is optional, but if at least one method
 * is registered, all other have to be registered too,
 * since this data will be used for method names checks.
 * 
 * Warning: only top level types are checked. For example if
 * some method has two parametrs: int and QList<double>.
 * Type of the first parameter will be checked, but the second
 * parameter will be only checked to be a list, but type of
 * items in the list must be checked in the implementation of
 * this method.
 */
void Server::registerMethod( QString methodName, QVariant::Type returnType, 
                             QList<QVariant::Type> parameterTypes )
{
    d->introspection.registerMethod(methodName,returnType,parameterTypes);
}

/** This is an overloaded member function, provided
 *  for convenience. */
void Server::registerMethod( QString methodName, QVariant::Type returnType, 
                             QVariant::Type parameter1Type, QVariant::Type parameter2Type, QVariant::Type parameter3Type, QVariant::Type parameter4Type )
{
    QList<QVariant::Type> parameterTypes;
    parameterTypes << parameter1Type << parameter2Type << parameter3Type << parameter4Type;

    registerMethod( methodName, returnType, parameterTypes );
}

/** This is an overloaded member function, provided
 *  for convenience. */
void Server::registerMethod( QString methodName, QVariant::Type returnType, 
                             QVariant::Type parameter1Type, QVariant::Type parameter2Type, QVariant::Type parameter3Type )
{
    QList<QVariant::Type> parameterTypes;
    parameterTypes << parameter1Type << parameter2Type << parameter3Type;

    registerMethod( methodName, returnType, parameterTypes );
}

/** This is an overloaded member function, provided
 *  for convenience. */
void Server::registerMethod( QString methodName, QVariant::Type returnType, 
                             QVariant::Type parameter1Type, QVariant::Type parameter2Type )
{
    QList<QVariant::Type> parameterTypes;
    parameterTypes << parameter1Type << parameter2Type;

    registerMethod( methodName, returnType, parameterTypes );
}

/** This is an overloaded member function, provided
 *  for convenience. */
void Server::registerMethod( QString methodName, QVariant::Type returnType, 
                             QVariant::Type parameter1Type )
{
    QList<QVariant::Type> parameterTypes;
    parameterTypes << parameter1Type;

    registerMethod( methodName, returnType, parameterTypes );
}

/** This is an overloaded member function, provided
 *  for convenience. */
void Server::registerMethod( QString methodName, QVariant::Type returnType )
{
    QList<QVariant::Type> parameterTypes;

    registerMethod( methodName, returnType, parameterTypes );
}

void Server::newConnection()
{
    //qDebug() << "new connection";
    while ( d->server->hasPendingConnections() ) {
        QTcpSocket *socket = d->server->nextPendingConnection();
    
        if ( !socket )
            return;
    
        
        connect(socket, SIGNAL(disconnected()),
                socket, SLOT(deleteLater()));
    
        new IncomingConnection(this, socket);
    }
}

/**
 *  Parse incoming \a request, and emit incomingRequest() signal
 *  or return xmlrpc response back to \a socket */
void Server::processRequest( QByteArray request, QTcpSocket *socket )
{
    d->lastRequestId++;


    int requestId = d->lastRequestId;
    d->processingRequests[ requestId ] = socket;


    int dataPos = request.indexOf("\r\n\r\n")+4;

    if ( dataPos < 0 ) {
        qDebug() << "did not find data part";
        socket->disconnectFromHost();
        return;
    }

    QByteArray requestHeader = request.left( dataPos );
    QByteArray requestData = request.mid( dataPos );

    QHttpRequestHeader httpRequestHeader( QString::fromUtf8(requestHeader) );

    bool keepAlive = httpRequestHeader.value("Connection").toLower() == "keep-alive";
    if ( keepAlive ) {
        d->keepAliveRequests.insert( requestId );
    }

    /*
    qDebug() << "request:";
    if ( request.count() < 1024 )
        qDebug() << QString( request );
    else
        qDebug() << "too long";
    */
    
    Request parsedRequest;
    QString errorMessage;

    if ( !parsedRequest.setContent(requestData,&errorMessage) ) {
        sendFault( requestId, -32600, errorMessage );
        return;
    }

    QString methodName = parsedRequest.methodName();
    QList<Variant> parameters = parsedRequest.parameters();

    //qDebug() << methodName << parameters;

    if ( methodName.startsWith("system.") ) {
        //reserved server methods

        if ( methodName == "system.listMethods" ) {
            sendReturnValue(requestId, Variant( d->introspection.listMethods() ) );
            return;
        }

        if ( methodName == "system.methodSignature" && parameters.count() == 1 ) {
            QString methodName = parameters[0].toString();

            sendReturnValue(requestId, Variant( d->introspection.methodSignatures(methodName) ) );
            return;
        }

        if ( methodName == "system.methodHelp" && parameters.count() == 1 ) {
            QString methodName = parameters[0].toString();

            sendReturnValue(requestId, Variant( d->introspection.methodHelp(methodName) ) );
            return;
        }

        sendFault(requestId, -32601, "Method not found" );
        return;
    }

    if ( !d->introspection.isEmpty() ) {
        // check method name first:

        if ( !d->introspection.isMethodSupported(methodName) ) {
            sendFault(requestId, -32601, "Method not found" );
            return;
        }

        QVariant::Type returnType;

        

        if ( !d->introspection.checkMethodParameters( methodName,
                                                      parameters,
                                                      &returnType ) ) {
            sendFault(requestId, -32602, "Invalid method parameters" );
            return;
        }

        d->expectedReturnTypes[ requestId ] = returnType;
    }

    emit incomingRequest( requestId, methodName, parameters );
}

/**
 * Send method return value back to client.
 * @param requestId id of the request, provided by
 *                  incomingRequest() signal
 * @param value to be returned to client
 */
void Server::sendReturnValue( int requestId, const xmlrpc::Variant& value )
{
    Q_ASSERT( d->processingRequests.contains( requestId ) );

    //check for return type
    if ( d->expectedReturnTypes.contains(requestId) ) {
        Q_ASSERT( value.type() == d->expectedReturnTypes[requestId] );
        d->expectedReturnTypes.remove( requestId );
    }

    Response response( value );

    QTcpSocket *socket =  d->processingRequests.take(requestId);
    d->sendResponse( socket, response.composeResponse(), d->keepAliveRequests.contains(requestId) );
    d->keepAliveRequests.remove( requestId );
    
}

/**
 * Send exception ( faultCode and faultMessage ) back to client.
 * @param requestId id of the request, provided by
 *                  incomingRequest() signal
 */
void Server::sendFault( int requestId, int faultCode, QString faultMessage )
{
    Q_ASSERT( d->processingRequests.contains( requestId ) );

    Response response( faultCode, faultMessage );

    QTcpSocket *socket =  d->processingRequests.take(requestId);

    d->sendResponse( socket, response.composeResponse(), d->keepAliveRequests.contains(requestId) );
    d->keepAliveRequests.remove( requestId );
}



IncomingConnection::IncomingConnection(Server *server, QTcpSocket *socket )
    :QObject(server)
{
    this->server = server;
    this->socket = socket;

    connect( socket, SIGNAL(readyRead()), this, SLOT(readData()) );
    readData();
}

void IncomingConnection::readData()
{
    if ( !socket ) {
        deleteLater();
        return;
    }

    if ( socket->bytesAvailable() == 0 ) 
        return;

    data.append( socket->readAll() );

    if ( data.count() > 15 && data.indexOf( "</methodCall>", data.count()-15 ) != -1 ) {
        server->processRequest( data, socket );
        deleteLater();
    }
}


} // namespace xmlrpc