Doc: Modularize QtNetwork documentation.
[profile/ivi/qtbase.git] / src / network / socket / qtcpserver.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 //#define QTCPSERVER_DEBUG
43
44 /*! \class QTcpServer
45
46     \brief The QTcpServer class provides a TCP-based server.
47
48     \reentrant
49     \ingroup network
50     \inmodule QtNetwork
51
52     This class makes it possible to accept incoming TCP connections.
53     You can specify the port or have QTcpServer pick one
54     automatically. You can listen on a specific address or on all the
55     machine's addresses.
56
57     Call listen() to have the server listen for incoming connections.
58     The newConnection() signal is then emitted each time a client
59     connects to the server.
60
61     Call nextPendingConnection() to accept the pending connection as
62     a connected QTcpSocket. The function returns a pointer to a
63     QTcpSocket in QAbstractSocket::ConnectedState that you can use for
64     communicating with the client.
65
66     If an error occurs, serverError() returns the type of error, and
67     errorString() can be called to get a human readable description of
68     what happened.
69
70     When listening for connections, the address and port on which the
71     server is listening are available as serverAddress() and
72     serverPort().
73
74     Calling close() makes QTcpServer stop listening for incoming
75     connections.
76
77     Although QTcpServer is mostly designed for use with an event
78     loop, it's possible to use it without one. In that case, you must
79     use waitForNewConnection(), which blocks until either a
80     connection is available or a timeout expires.
81
82     \sa QTcpSocket, {Fortune Server Example}, {Threaded Fortune Server Example},
83         {Loopback Example}, {Torrent Example}
84 */
85
86 /*! \fn void QTcpServer::newConnection()
87
88     This signal is emitted every time a new connection is available.
89
90     \sa hasPendingConnections(), nextPendingConnection()
91 */
92
93 #include "private/qobject_p.h"
94 #include "qalgorithms.h"
95 #include "qhostaddress.h"
96 #include "qlist.h"
97 #include "qpointer.h"
98 #include "qabstractsocketengine_p.h"
99 #include "qtcpserver.h"
100 #include "qtcpsocket.h"
101 #include "qnetworkproxy.h"
102
103 QT_BEGIN_NAMESPACE
104
105 #define Q_CHECK_SOCKETENGINE(returnValue) do { \
106     if (!d->socketEngine) { \
107         return returnValue; \
108     } } while (0)
109
110 class QTcpServerPrivate : public QObjectPrivate, public QAbstractSocketEngineReceiver
111 {
112     Q_DECLARE_PUBLIC(QTcpServer)
113 public:
114     QTcpServerPrivate();
115     ~QTcpServerPrivate();
116
117     QList<QTcpSocket *> pendingConnections;
118
119     quint16 port;
120     QHostAddress address;
121
122     QAbstractSocket::SocketState state;
123     QAbstractSocketEngine *socketEngine;
124
125     QAbstractSocket::SocketError serverSocketError;
126     QString serverSocketErrorString;
127
128     int maxConnections;
129
130 #ifndef QT_NO_NETWORKPROXY
131     QNetworkProxy proxy;
132     QNetworkProxy resolveProxy(const QHostAddress &address, quint16 port);
133 #endif
134
135     // from QAbstractSocketEngineReceiver
136     void readNotification();
137     inline void writeNotification() {}
138     inline void exceptionNotification() {}
139     inline void connectionNotification() {}
140 #ifndef QT_NO_NETWORKPROXY
141     inline void proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *) {}
142 #endif
143
144 };
145
146 /*! \internal
147 */
148 QTcpServerPrivate::QTcpServerPrivate()
149  : port(0)
150  , state(QAbstractSocket::UnconnectedState)
151  , socketEngine(0)
152  , serverSocketError(QAbstractSocket::UnknownSocketError)
153  , maxConnections(30)
154 {
155 }
156
157 /*! \internal
158 */
159 QTcpServerPrivate::~QTcpServerPrivate()
160 {
161 }
162
163 #ifndef QT_NO_NETWORKPROXY
164 /*! \internal
165
166     Resolve the proxy to its final value.
167 */
168 QNetworkProxy QTcpServerPrivate::resolveProxy(const QHostAddress &address, quint16 port)
169 {
170     if (address.isLoopback())
171         return QNetworkProxy::NoProxy;
172
173     QList<QNetworkProxy> proxies;
174     if (proxy.type() != QNetworkProxy::DefaultProxy) {
175         // a non-default proxy was set with setProxy
176         proxies << proxy;
177     } else {
178         // try the application settings instead
179         QNetworkProxyQuery query(port, QString(), QNetworkProxyQuery::TcpServer);
180         proxies = QNetworkProxyFactory::proxyForQuery(query);
181     }
182
183     // return the first that we can use
184     foreach (const QNetworkProxy &p, proxies) {
185         if (p.capabilities() & QNetworkProxy::ListeningCapability)
186             return p;
187     }
188
189     // no proxy found
190     // DefaultProxy will raise an error
191     return QNetworkProxy(QNetworkProxy::DefaultProxy);
192 }
193 #endif
194
195 /*! \internal
196 */
197 void QTcpServerPrivate::readNotification()
198 {
199     Q_Q(QTcpServer);
200     for (;;) {
201         if (pendingConnections.count() >= maxConnections) {
202 #if defined (QTCPSERVER_DEBUG)
203             qDebug("QTcpServerPrivate::_q_processIncomingConnection() too many connections");
204 #endif
205             if (socketEngine->isReadNotificationEnabled())
206                 socketEngine->setReadNotificationEnabled(false);
207             return;
208         }
209
210         int descriptor = socketEngine->accept();
211         if (descriptor == -1)
212             break;
213 #if defined (QTCPSERVER_DEBUG)
214         qDebug("QTcpServerPrivate::_q_processIncomingConnection() accepted socket %i", descriptor);
215 #endif
216         q->incomingConnection(descriptor);
217
218         QPointer<QTcpServer> that = q;
219         emit q->newConnection();
220         if (!that || !q->isListening())
221             return;
222     }
223 }
224
225 /*!
226     Constructs a QTcpServer object.
227
228     \a parent is passed to the QObject constructor.
229
230     \sa listen(), setSocketDescriptor()
231 */
232 QTcpServer::QTcpServer(QObject *parent)
233     : QObject(*new QTcpServerPrivate, parent)
234 {
235 }
236
237 /*!
238     Destroys the QTcpServer object. If the server is listening for
239     connections, the socket is automatically closed.
240
241     Any client \l{QTcpSocket}s that are still connected must either
242     disconnect or be reparented before the server is deleted.
243
244     \sa close()
245 */
246 QTcpServer::~QTcpServer()
247 {
248     close();
249 }
250
251 /*!
252     Tells the server to listen for incoming connections on address \a
253     address and port \a port. If \a port is 0, a port is chosen
254     automatically. If \a address is QHostAddress::Any, the server
255     will listen on all network interfaces.
256
257     Returns true on success; otherwise returns false.
258
259     \sa isListening()
260 */
261 bool QTcpServer::listen(const QHostAddress &address, quint16 port)
262 {
263     Q_D(QTcpServer);
264     if (d->state == QAbstractSocket::ListeningState) {
265         qWarning("QTcpServer::listen() called when already listening");
266         return false;
267     }
268
269     QAbstractSocket::NetworkLayerProtocol proto = address.protocol();
270
271 #ifdef QT_NO_NETWORKPROXY
272     static const QNetworkProxy &proxy = *(QNetworkProxy *)0;
273 #else
274     QNetworkProxy proxy = d->resolveProxy(address, port);
275 #endif
276
277     delete d->socketEngine;
278     d->socketEngine = QAbstractSocketEngine::createSocketEngine(QAbstractSocket::TcpSocket, proxy, this);
279     if (!d->socketEngine) {
280         d->serverSocketError = QAbstractSocket::UnsupportedSocketOperationError;
281         d->serverSocketErrorString = tr("Operation on socket is not supported");
282         return false;
283     }
284 #ifndef QT_NO_BEARERMANAGEMENT
285     //copy network session down to the socket engine (if it has been set)
286     d->socketEngine->setProperty("_q_networksession", property("_q_networksession"));
287 #endif
288     if (!d->socketEngine->initialize(QAbstractSocket::TcpSocket, proto)) {
289         d->serverSocketError = d->socketEngine->error();
290         d->serverSocketErrorString = d->socketEngine->errorString();
291         return false;
292     }
293
294 #if defined(Q_OS_UNIX)
295     // Under Unix, we want to be able to bind to the port, even if a socket on
296     // the same address-port is in TIME_WAIT. Under Windows this is possible
297     // anyway -- furthermore, the meaning of reusable on Windows is different:
298     // it means that you can use the same address-port for multiple listening
299     // sockets.
300     // Don't abort though if we can't set that option. For example the socks
301     // engine doesn't support that option, but that shouldn't prevent us from
302     // trying to bind/listen.
303     d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
304 #endif
305
306     if (!d->socketEngine->bind(address, port)) {
307         d->serverSocketError = d->socketEngine->error();
308         d->serverSocketErrorString = d->socketEngine->errorString();
309         return false;
310     }
311
312     if (!d->socketEngine->listen()) {
313         d->serverSocketError = d->socketEngine->error();
314         d->serverSocketErrorString = d->socketEngine->errorString();
315         return false;
316     }
317
318     d->socketEngine->setReceiver(d);
319     d->socketEngine->setReadNotificationEnabled(true);
320
321     d->state = QAbstractSocket::ListeningState;
322     d->address = d->socketEngine->localAddress();
323     d->port = d->socketEngine->localPort();
324
325 #if defined (QTCPSERVER_DEBUG)
326     qDebug("QTcpServer::listen(%i, \"%s\") == true (listening on port %i)", port,
327            address.toString().toLatin1().constData(), d->socketEngine->localPort());
328 #endif
329     return true;
330 }
331
332 /*!
333     Returns true if the server is currently listening for incoming
334     connections; otherwise returns false.
335
336     \sa listen()
337 */
338 bool QTcpServer::isListening() const
339 {
340     Q_D(const QTcpServer);
341     Q_CHECK_SOCKETENGINE(false);
342     return d->socketEngine->state() == QAbstractSocket::ListeningState;
343 }
344
345 /*!
346     Closes the server. The server will no longer listen for incoming
347     connections.
348
349     \sa listen()
350 */
351 void QTcpServer::close()
352 {
353     Q_D(QTcpServer);
354
355     qDeleteAll(d->pendingConnections);
356     d->pendingConnections.clear();
357
358     if (d->socketEngine) {
359         d->socketEngine->close();
360         QT_TRY {
361             d->socketEngine->deleteLater();
362         } QT_CATCH(const std::bad_alloc &) {
363             // in out of memory situations, the socketEngine
364             // will be deleted in ~QTcpServer (it's a child-object of this)
365         }
366         d->socketEngine = 0;
367     }
368
369     d->state = QAbstractSocket::UnconnectedState;
370 }
371
372 /*!
373     Returns the native socket descriptor the server uses to listen
374     for incoming instructions, or -1 if the server is not listening.
375
376     If the server is using QNetworkProxy, the returned descriptor may
377     not be usable with native socket functions.
378
379     \sa setSocketDescriptor(), isListening()
380 */
381 qintptr QTcpServer::socketDescriptor() const
382 {
383     Q_D(const QTcpServer);
384     Q_CHECK_SOCKETENGINE(-1);
385     return d->socketEngine->socketDescriptor();
386 }
387
388 /*!
389     Sets the socket descriptor this server should use when listening
390     for incoming connections to \a socketDescriptor. Returns true if
391     the socket is set successfully; otherwise returns false.
392
393     The socket is assumed to be in listening state.
394
395     \sa socketDescriptor(), isListening()
396 */
397 bool QTcpServer::setSocketDescriptor(qintptr socketDescriptor)
398 {
399     Q_D(QTcpServer);
400     if (isListening()) {
401         qWarning("QTcpServer::setSocketDescriptor() called when already listening");
402         return false;
403     }
404
405     if (d->socketEngine)
406         delete d->socketEngine;
407     d->socketEngine = QAbstractSocketEngine::createSocketEngine(socketDescriptor, this);
408     if (!d->socketEngine) {
409         d->serverSocketError = QAbstractSocket::UnsupportedSocketOperationError;
410         d->serverSocketErrorString = tr("Operation on socket is not supported");
411         return false;
412     }
413 #ifndef QT_NO_BEARERMANAGEMENT
414     //copy network session down to the socket engine (if it has been set)
415     d->socketEngine->setProperty("_q_networksession", property("_q_networksession"));
416 #endif
417     if (!d->socketEngine->initialize(socketDescriptor, QAbstractSocket::ListeningState)) {
418         d->serverSocketError = d->socketEngine->error();
419         d->serverSocketErrorString = d->socketEngine->errorString();
420 #if defined (QTCPSERVER_DEBUG)
421         qDebug("QTcpServer::setSocketDescriptor(%i) failed (%s)", socketDescriptor,
422                d->serverSocketErrorString.toLatin1().constData());
423 #endif
424         return false;
425     }
426
427     d->socketEngine->setReceiver(d);
428     d->socketEngine->setReadNotificationEnabled(true);
429
430     d->state = d->socketEngine->state();
431     d->address = d->socketEngine->localAddress();
432     d->port = d->socketEngine->localPort();
433
434 #if defined (QTCPSERVER_DEBUG)
435     qDebug("QTcpServer::setSocketDescriptor(%i) succeeded.", socketDescriptor);
436 #endif
437     return true;
438 }
439
440 /*!
441     Returns the server's port if the server is listening for
442     connections; otherwise returns 0.
443
444     \sa serverAddress(), listen()
445 */
446 quint16 QTcpServer::serverPort() const
447 {
448     Q_D(const QTcpServer);
449     Q_CHECK_SOCKETENGINE(0);
450     return d->socketEngine->localPort();
451 }
452
453 /*!
454     Returns the server's address if the server is listening for
455     connections; otherwise returns QHostAddress::Null.
456
457     \sa serverPort(), listen()
458 */
459 QHostAddress QTcpServer::serverAddress() const
460 {
461     Q_D(const QTcpServer);
462     Q_CHECK_SOCKETENGINE(QHostAddress(QHostAddress::Null));
463     return d->socketEngine->localAddress();
464 }
465
466 /*!
467     Waits for at most \a msec milliseconds or until an incoming
468     connection is available. Returns true if a connection is
469     available; otherwise returns false. If the operation timed out
470     and \a timedOut is not 0, *\a timedOut will be set to true.
471
472     This is a blocking function call. Its use is disadvised in a
473     single-threaded GUI application, since the whole application will
474     stop responding until the function returns.
475     waitForNewConnection() is mostly useful when there is no event
476     loop available.
477
478     The non-blocking alternative is to connect to the newConnection()
479     signal.
480
481     If msec is -1, this function will not time out.
482
483     \sa hasPendingConnections(), nextPendingConnection()
484 */
485 bool QTcpServer::waitForNewConnection(int msec, bool *timedOut)
486 {
487     Q_D(QTcpServer);
488     if (d->state != QAbstractSocket::ListeningState)
489         return false;
490
491     if (!d->socketEngine->waitForRead(msec, timedOut)) {
492         d->serverSocketError = d->socketEngine->error();
493         d->serverSocketErrorString = d->socketEngine->errorString();
494         return false;
495     }
496
497     if (timedOut && *timedOut)
498         return false;
499
500     d->readNotification();
501
502     return true;
503 }
504
505 /*!
506     Returns true if the server has a pending connection; otherwise
507     returns false.
508
509     \sa nextPendingConnection(), setMaxPendingConnections()
510 */
511 bool QTcpServer::hasPendingConnections() const
512 {
513     return !d_func()->pendingConnections.isEmpty();
514 }
515
516 /*!
517     Returns the next pending connection as a connected QTcpSocket
518     object.
519
520     The socket is created as a child of the server, which means that
521     it is automatically deleted when the QTcpServer object is
522     destroyed. It is still a good idea to delete the object
523     explicitly when you are done with it, to avoid wasting memory.
524
525     0 is returned if this function is called when there are no pending
526     connections.
527
528     \note The returned QTcpSocket object cannot be used from another
529     thread. If you want to use an incoming connection from another thread,
530     you need to override incomingConnection().
531
532     \sa hasPendingConnections()
533 */
534 QTcpSocket *QTcpServer::nextPendingConnection()
535 {
536     Q_D(QTcpServer);
537     if (d->pendingConnections.isEmpty())
538         return 0;
539
540     if (!d->socketEngine->isReadNotificationEnabled())
541         d->socketEngine->setReadNotificationEnabled(true);
542
543     return d->pendingConnections.takeFirst();
544 }
545
546 /*!
547     This virtual function is called by QTcpServer when a new
548     connection is available. The \a socketDescriptor argument is the
549     native socket descriptor for the accepted connection.
550
551     The base implementation creates a QTcpSocket, sets the socket
552     descriptor and then stores the QTcpSocket in an internal list of
553     pending connections. Finally newConnection() is emitted.
554
555     Reimplement this function to alter the server's behavior when a
556     connection is available.
557
558     If this server is using QNetworkProxy then the \a socketDescriptor
559     may not be usable with native socket functions, and should only be
560     used with QTcpSocket::setSocketDescriptor().
561
562     \note If you want to handle an incoming connection as a new QTcpSocket
563     object in another thread you have to pass the socketDescriptor
564     to the other thread and create the QTcpSocket object there and
565     use its setSocketDescriptor() method.
566
567     \sa newConnection(), nextPendingConnection(), addPendingConnection()
568 */
569 void QTcpServer::incomingConnection(qintptr socketDescriptor)
570 {
571 #if defined (QTCPSERVER_DEBUG)
572     qDebug("QTcpServer::incomingConnection(%i)", socketDescriptor);
573 #endif
574
575     QTcpSocket *socket = new QTcpSocket(this);
576     socket->setSocketDescriptor(socketDescriptor);
577     addPendingConnection(socket);
578 }
579
580 /*!
581     This function is called by QTcpServer::incomingConnection()
582     to add the \a socket to the list of pending incoming connections.
583
584     \note Don't forget to call this member from reimplemented
585     incomingConnection() if you do not want to break the
586     Pending Connections mechanism.
587
588     \sa incomingConnection()
589     \since 4.7
590 */
591 void QTcpServer::addPendingConnection(QTcpSocket* socket)
592 {
593     d_func()->pendingConnections.append(socket);
594 }
595
596 /*!
597     Sets the maximum number of pending accepted connections to \a
598     numConnections. QTcpServer will accept no more than \a
599     numConnections incoming connections before
600     nextPendingConnection() is called. By default, the limit is 30
601     pending connections.
602
603     Clients may still able to connect after the server has reached
604     its maximum number of pending connections (i.e., QTcpSocket can
605     still emit the connected() signal). QTcpServer will stop
606     accepting the new connections, but the operating system may
607     still keep them in queue.
608
609     \sa maxPendingConnections(), hasPendingConnections()
610 */
611 void QTcpServer::setMaxPendingConnections(int numConnections)
612 {
613     d_func()->maxConnections = numConnections;
614 }
615
616 /*!
617     Returns the maximum number of pending accepted connections. The
618     default is 30.
619
620     \sa setMaxPendingConnections(), hasPendingConnections()
621 */
622 int QTcpServer::maxPendingConnections() const
623 {
624     return d_func()->maxConnections;
625 }
626
627 /*!
628     Returns an error code for the last error that occurred.
629
630     \sa errorString()
631 */
632 QAbstractSocket::SocketError QTcpServer::serverError() const
633 {
634     return d_func()->serverSocketError;
635 }
636
637 /*!
638     Returns a human readable description of the last error that
639     occurred.
640
641     \sa serverError()
642 */
643 QString QTcpServer::errorString() const
644 {
645     return d_func()->serverSocketErrorString;
646 }
647
648 #ifndef QT_NO_NETWORKPROXY
649 /*!
650     \since 4.1
651
652     Sets the explicit network proxy for this socket to \a networkProxy.
653
654     To disable the use of a proxy for this socket, use the
655     QNetworkProxy::NoProxy proxy type:
656
657     \snippet code/src_network_socket_qtcpserver.cpp 0
658
659     \sa proxy(), QNetworkProxy
660 */
661 void QTcpServer::setProxy(const QNetworkProxy &networkProxy)
662 {
663     Q_D(QTcpServer);
664     d->proxy = networkProxy;
665 }
666
667 /*!
668     \since 4.1
669
670     Returns the network proxy for this socket.
671     By default QNetworkProxy::DefaultProxy is used.
672
673     \sa setProxy(), QNetworkProxy
674 */
675 QNetworkProxy QTcpServer::proxy() const
676 {
677     Q_D(const QTcpServer);
678     return d->proxy;
679 }
680 #endif // QT_NO_NETWORKPROXY
681
682 QT_END_NAMESPACE
683
684 #include "moc_qtcpserver.cpp"
685