Fix network doc links.
[profile/ivi/qtbase.git] / src / network / socket / qlocalserver.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 #include "qlocalserver.h"
43 #include "qlocalserver_p.h"
44 #include "qlocalsocket.h"
45
46 QT_BEGIN_NAMESPACE
47
48 #ifndef QT_NO_LOCALSERVER
49
50 /*!
51     \class QLocalServer
52     \since 4.4
53     \inmodule QtNetwork
54
55     \brief The QLocalServer class provides a local socket based server.
56
57     This class makes it possible to accept incoming local socket
58     connections.
59
60     Call listen() to have the server start listening
61     for incoming connections on a specified key.  The
62     newConnection() signal is then emitted each time a client
63     connects to the server.
64
65     Call nextPendingConnection() to accept the pending connection
66     as a connected QLocalSocket.  The function returns a pointer to a
67     QLocalSocket that can be used for communicating with the client.
68
69     If an error occurs, serverError() returns the type of error, and
70     errorString() can be called to get a human readable description
71     of what happened.
72
73     When listening for connections, the name which the server is
74     listening on is available through serverName().
75
76     Calling close() makes QLocalServer stop listening for incoming connections.
77
78     Although QLocalServer is designed for use with an event loop, it's possible
79     to use it without one. In that case, you must use waitForNewConnection(),
80     which blocks until either a connection is available or a timeout expires.
81
82     \sa QLocalSocket, QTcpServer
83 */
84
85 /*!
86     \enum QLocalServer::SocketOption
87     \since 5.0
88
89     This enum describes the possible options that can be used to create the
90     socket. This changes the access permissions on platforms (Linux, Windows)
91     that support access permissions on the socket. Both GroupAccess and OtherAccess
92     may vary slightly in meanings depending on the platform.
93
94     \value NoOptions No access restrictions have been set.
95     \value UserAccessOption
96     Access is restricted to the same user as the process that created the socket.
97     \value GroupAccessOption
98     Access is restricted to the same group but not the user that created the socket on Linux.
99     Access is restricted to the primary group of the process on Windows
100     \value OtherAccessOption
101     Access is available to everyone but the user and group that created the socket on Linux.
102     Access is available to everyone on Windows.
103     \value WorldAccessOption
104     No access restrictions.
105
106     \sa socketOptions
107 */
108
109
110 /*!
111     Create a new local socket server with the given \a parent.
112
113     \sa listen()
114  */
115 QLocalServer::QLocalServer(QObject *parent)
116         : QObject(*new QLocalServerPrivate, parent)
117 {
118     Q_D(QLocalServer);
119     d->init();
120 }
121
122 /*!
123     Destroys the QLocalServer object.  If the server is listening for
124     connections, it is automatically closed.
125
126     Any client QLocalSockets that are still connected must either
127     disconnect or be reparented before the server is deleted.
128
129     \sa close()
130  */
131 QLocalServer::~QLocalServer()
132 {
133     if (isListening())
134         close();
135 }
136
137 /*!
138     \property QLocalServer::socketOptions
139     \since 5.0
140
141     The setSocketOptions method controls how the socket operates.
142     For example the socket may restrict access to what user ids can
143     connect to the socket.
144
145     These options must be set before listen() is called.
146
147     In some cases, such as with Unix domain sockets on Linux, the
148     access to the socket will be determined by file system permissions,
149     and are created based on the umask. Setting the access flags will
150     overide this and will restrict or permit access as specified.
151
152     Other Unix-based operating systems, such as Mac OS X, do not
153     honor file permissions for Unix domain sockets and by default
154     have WorldAccess and these permission flags will have no effect.
155
156     On Windows, UserAccessOption is sufficient to allow a non
157     elevated process to connect to a local server created by an
158     elevated process run by the same user. GroupAccessOption
159     refers to the primary group of the process (see TokenPrimaryGroup
160     in the Windows documentation). OtherAccessOption refers to
161     the well known "Everyone" group.
162
163     By default none of the flags are set, access permissions
164     are the platform default.
165
166     \sa listen()
167 */
168 void QLocalServer::setSocketOptions(SocketOptions options)
169 {
170     Q_D(QLocalServer);
171
172     d->socketOptions = options;
173 }
174
175 /*!
176     \since 5.0
177     Returns the socket options set on the socket.
178
179     \sa setSocketOptions()
180  */
181 QLocalServer::SocketOptions QLocalServer::socketOptions() const
182 {
183     Q_D(const QLocalServer);
184     return d->socketOptions;
185 }
186
187 /*!
188     Stop listening for incoming connections.  Existing connections are not
189     effected, but any new connections will be refused.
190
191     \sa isListening(), listen()
192  */
193 void QLocalServer::close()
194 {
195     Q_D(QLocalServer);
196     if (!isListening())
197         return;
198     qDeleteAll(d->pendingConnections);
199     d->pendingConnections.clear();
200     d->closeServer();
201     d->serverName.clear();
202     d->fullServerName.clear();
203     d->errorString.clear();
204     d->error = QAbstractSocket::UnknownSocketError;
205 }
206
207 /*!
208     Returns the human-readable message appropriate to the current error
209     reported by serverError(). If no suitable string is available, an empty
210     string is returned.
211
212     \sa serverError()
213  */
214 QString QLocalServer::errorString() const
215 {
216     Q_D(const QLocalServer);
217     return d->errorString;
218 }
219
220 /*!
221     Returns true if the server has a pending connection; otherwise
222     returns false.
223
224     \sa nextPendingConnection(), setMaxPendingConnections()
225  */
226 bool QLocalServer::hasPendingConnections() const
227 {
228     Q_D(const QLocalServer);
229     return !(d->pendingConnections.isEmpty());
230 }
231
232 /*!
233     This virtual function is called by QLocalServer when a new connection
234     is available. \a socketDescriptor is the native socket descriptor for
235     the accepted connection.
236
237     The base implementation creates a QLocalSocket, sets the socket descriptor
238     and then stores the QLocalSocket in an internal list of pending
239     connections. Finally newConnection() is emitted.
240
241     Reimplement this function to alter the server's behavior
242     when a connection is available.
243
244     \sa newConnection(), nextPendingConnection(),
245     QLocalSocket::setSocketDescriptor()
246  */
247 void QLocalServer::incomingConnection(quintptr socketDescriptor)
248 {
249     Q_D(QLocalServer);
250     QLocalSocket *socket = new QLocalSocket(this);
251     socket->setSocketDescriptor(socketDescriptor);
252     d->pendingConnections.enqueue(socket);
253     emit newConnection();
254 }
255
256 /*!
257     Returns true if the server is listening for incoming connections
258     otherwise false.
259
260     \sa listen(), close()
261  */
262 bool QLocalServer::isListening() const
263 {
264     Q_D(const QLocalServer);
265     return !(d->serverName.isEmpty());
266 }
267
268 /*!
269     Tells the server to listen for incoming connections on \a name.
270     If the server is currently listening then it will return false.
271     Return true on success otherwise false.
272
273     \a name can be a single name and QLocalServer will determine
274     the correct platform specific path.  serverName() will return
275     the name that is passed into listen.
276
277     Usually you would just pass in a name like "foo", but on Unix this
278     could also be a path such as "/tmp/foo" and on Windows this could
279     be a pipe path such as "\\\\.\\pipe\\foo"
280
281     Note:
282     On Unix if the server crashes without closing listen will fail
283     with AddressInUseError.  To create a new server the file should be removed.
284     On Windows two local servers can listen to the same pipe at the same
285     time, but any connections will go to one of the server.
286
287     \sa serverName(), isListening(), close()
288  */
289 bool QLocalServer::listen(const QString &name)
290 {
291     Q_D(QLocalServer);
292     if (isListening()) {
293         qWarning("QLocalServer::listen() called when already listening");
294         return false;
295     }
296
297     if (name.isEmpty()) {
298         d->error = QAbstractSocket::HostNotFoundError;
299         QString function = QLatin1String("QLocalServer::listen");
300         d->errorString = tr("%1: Name error").arg(function);
301         return false;
302     }
303
304     if (!d->listen(name)) {
305         d->serverName.clear();
306         d->fullServerName.clear();
307         return false;
308     }
309
310     d->serverName = name;
311     return true;
312 }
313
314 /*!
315     \since 5.0
316
317     Instructs the server to listen for incoming connections on
318     \a socketDescriptor. The property returns \c false if the server is
319     currently listening. It returns \c true on success; otherwise,
320     it returns \c false. The socket must be ready to accept
321     new connections with no extra platform-specific functions
322     called. The socket is set into non-blocking mode.
323
324     serverName(), fullServerName() may return a string with
325     a name if this option is supported by the platform;
326     otherwise, they return an empty QString.
327
328     \sa isListening(), close()
329  */
330 bool QLocalServer::listen(qintptr socketDescriptor)
331 {
332     Q_D(QLocalServer);
333     if (isListening()) {
334         qWarning("QLocalServer::listen() called when already listening");
335         return false;
336     }
337
338     d->serverName.clear();
339     d->fullServerName.clear();
340
341     if (!d->listen(socketDescriptor)) {
342         return false;
343     }
344
345     return true;
346 }
347
348 /*!
349     Returns the maximum number of pending accepted connections.
350     The default is 30.
351
352     \sa setMaxPendingConnections(), hasPendingConnections()
353  */
354 int QLocalServer::maxPendingConnections() const
355 {
356     Q_D(const QLocalServer);
357     return d->maxPendingConnections;
358 }
359
360 /*!
361     \fn void QLocalServer::newConnection()
362
363     This signal is emitted every time a new connection is available.
364
365     \sa hasPendingConnections(), nextPendingConnection()
366 */
367
368 /*!
369     Returns the next pending connection as a connected QLocalSocket object.
370
371     The socket is created as a child of the server, which means that it is
372     automatically deleted when the QLocalServer object is destroyed. It is
373     still a good idea to delete the object explicitly when you are done with
374     it, to avoid wasting memory.
375
376     0 is returned if this function is called when there are no pending
377     connections.
378
379     \sa hasPendingConnections(), newConnection(), incomingConnection()
380  */
381 QLocalSocket *QLocalServer::nextPendingConnection()
382 {
383     Q_D(QLocalServer);
384     if (d->pendingConnections.isEmpty())
385         return 0;
386     QLocalSocket *nextSocket = d->pendingConnections.dequeue();
387 #ifndef QT_LOCALSOCKET_TCP
388     if (d->pendingConnections.size() <= d->maxPendingConnections)
389 #ifndef Q_OS_WIN
390         d->socketNotifier->setEnabled(true);
391 #else
392         d->connectionEventNotifier->setEnabled(true);
393 #endif
394 #endif
395     return nextSocket;
396 }
397
398 /*!
399     \since 4.5
400
401     Removes any server instance that might cause a call to listen() to fail
402     and returns true if successful; otherwise returns false.
403     This function is meant to recover from a crash, when the previous server
404     instance has not been cleaned up.
405
406     On Windows, this function does nothing; on Unix, it removes the socket file
407     given by \a name.
408
409     \warning Be careful to avoid removing sockets of running instances.
410 */
411 bool QLocalServer::removeServer(const QString &name)
412 {
413     return QLocalServerPrivate::removeServer(name);
414 }
415
416 /*!
417     Returns the server name if the server is listening for connections;
418     otherwise returns QString()
419
420     \sa listen(), fullServerName()
421  */
422 QString QLocalServer::serverName() const
423 {
424     Q_D(const QLocalServer);
425     return d->serverName;
426 }
427
428 /*!
429     Returns the full path that the server is listening on.
430
431     Note: This is platform specific
432
433     \sa listen(), serverName()
434  */
435 QString QLocalServer::fullServerName() const
436 {
437     Q_D(const QLocalServer);
438     return d->fullServerName;
439 }
440
441 /*!
442     Returns the type of error that occurred last or NoError.
443
444     \sa errorString()
445  */
446 QAbstractSocket::SocketError QLocalServer::serverError() const
447 {
448     Q_D(const QLocalServer);
449     return d->error;
450 }
451
452 /*!
453     Sets the maximum number of pending accepted connections to
454     \a numConnections.  QLocalServer will accept no more than
455     \a numConnections incoming connections before nextPendingConnection()
456     is called.
457
458     Note: Even though QLocalServer will stop accepting new connections
459     after it has reached its maximum number of pending connections,
460     the operating system may still keep them in queue which will result
461     in clients signaling that it is connected.
462
463     \sa maxPendingConnections(), hasPendingConnections()
464  */
465 void QLocalServer::setMaxPendingConnections(int numConnections)
466 {
467     Q_D(QLocalServer);
468     d->maxPendingConnections = numConnections;
469 }
470
471 /*!
472     Waits for at most \a msec milliseconds or until an incoming connection
473     is available.  Returns true if a connection is available; otherwise
474     returns false.  If the operation timed out and \a timedOut is not 0,
475     *timedOut will be set to true.
476
477     This is a blocking function call. Its use is ill-advised in a
478     single-threaded GUI application, since the whole application will stop
479     responding until the function returns. waitForNewConnection() is mostly
480     useful when there is no event loop available.
481
482     The non-blocking alternative is to connect to the newConnection() signal.
483
484     If msec is -1, this function will not time out.
485
486     \sa hasPendingConnections(), nextPendingConnection()
487  */
488 bool QLocalServer::waitForNewConnection(int msec, bool *timedOut)
489 {
490     Q_D(QLocalServer);
491     if (timedOut)
492         *timedOut = false;
493
494     if (!isListening())
495         return false;
496
497     d->waitForNewConnection(msec, timedOut);
498
499     return !d->pendingConnections.isEmpty();
500 }
501
502 #endif
503
504 QT_END_NAMESPACE
505
506 #include "moc_qlocalserver.cpp"
507