1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
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.
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.
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.
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.
40 ****************************************************************************/
42 #include "qlocalserver.h"
43 #include "qlocalserver_p.h"
44 #include "qlocalsocket.h"
48 #ifndef QT_NO_LOCALSERVER
55 \brief The QLocalServer class provides a local socket based server.
57 This class makes it possible to accept incoming local socket
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.
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.
69 If an error occurs, serverError() returns the type of error, and
70 errorString() can be called to get a human readable description
73 When listening for connections, the name which the server is
74 listening on is available through serverName().
76 Calling close() makes QLocalServer stop listening for incoming connections.
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.
82 \sa QLocalSocket, QTcpServer
86 \enum QLocalServer::SocketOption
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.
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.
111 Create a new local socket server with the given \a parent.
115 QLocalServer::QLocalServer(QObject *parent)
116 : QObject(*new QLocalServerPrivate, parent)
123 Destroys the QLocalServer object. If the server is listening for
124 connections, it is automatically closed.
126 Any client QLocalSockets that are still connected must either
127 disconnect or be reparented before the server is deleted.
131 QLocalServer::~QLocalServer()
138 \property QLocalServer::socketOptions
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.
145 These options must be set before listen() is called.
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.
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.
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.
163 By default none of the flags are set, access permissions
164 are the platform default.
168 void QLocalServer::setSocketOptions(SocketOptions options)
172 d->socketOptions = options;
177 Returns the socket options set on the socket.
179 \sa setSocketOptions()
181 QLocalServer::SocketOptions QLocalServer::socketOptions() const
183 Q_D(const QLocalServer);
184 return d->socketOptions;
188 Stop listening for incoming connections. Existing connections are not
189 effected, but any new connections will be refused.
191 \sa isListening(), listen()
193 void QLocalServer::close()
198 qDeleteAll(d->pendingConnections);
199 d->pendingConnections.clear();
201 d->serverName.clear();
202 d->fullServerName.clear();
203 d->errorString.clear();
204 d->error = QAbstractSocket::UnknownSocketError;
208 Returns the human-readable message appropriate to the current error
209 reported by serverError(). If no suitable string is available, an empty
214 QString QLocalServer::errorString() const
216 Q_D(const QLocalServer);
217 return d->errorString;
221 Returns true if the server has a pending connection; otherwise
224 \sa nextPendingConnection(), setMaxPendingConnections()
226 bool QLocalServer::hasPendingConnections() const
228 Q_D(const QLocalServer);
229 return !(d->pendingConnections.isEmpty());
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.
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.
241 Reimplement this function to alter the server's behavior
242 when a connection is available.
244 \sa newConnection(), nextPendingConnection(),
245 QLocalSocket::setSocketDescriptor()
247 void QLocalServer::incomingConnection(quintptr socketDescriptor)
250 QLocalSocket *socket = new QLocalSocket(this);
251 socket->setSocketDescriptor(socketDescriptor);
252 d->pendingConnections.enqueue(socket);
253 emit newConnection();
257 Returns true if the server is listening for incoming connections
260 \sa listen(), close()
262 bool QLocalServer::isListening() const
264 Q_D(const QLocalServer);
265 return !(d->serverName.isEmpty());
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.
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.
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"
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.
287 \sa serverName(), isListening(), close()
289 bool QLocalServer::listen(const QString &name)
293 qWarning("QLocalServer::listen() called when already listening");
297 if (name.isEmpty()) {
298 d->error = QAbstractSocket::HostNotFoundError;
299 QString function = QLatin1String("QLocalServer::listen");
300 d->errorString = tr("%1: Name error").arg(function);
304 if (!d->listen(name)) {
305 d->serverName.clear();
306 d->fullServerName.clear();
310 d->serverName = name;
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.
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.
328 \sa isListening(), close()
330 bool QLocalServer::listen(qintptr socketDescriptor)
334 qWarning("QLocalServer::listen() called when already listening");
338 d->serverName.clear();
339 d->fullServerName.clear();
341 if (!d->listen(socketDescriptor)) {
349 Returns the maximum number of pending accepted connections.
352 \sa setMaxPendingConnections(), hasPendingConnections()
354 int QLocalServer::maxPendingConnections() const
356 Q_D(const QLocalServer);
357 return d->maxPendingConnections;
361 \fn void QLocalServer::newConnection()
363 This signal is emitted every time a new connection is available.
365 \sa hasPendingConnections(), nextPendingConnection()
369 Returns the next pending connection as a connected QLocalSocket object.
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.
376 0 is returned if this function is called when there are no pending
379 \sa hasPendingConnections(), newConnection(), incomingConnection()
381 QLocalSocket *QLocalServer::nextPendingConnection()
384 if (d->pendingConnections.isEmpty())
386 QLocalSocket *nextSocket = d->pendingConnections.dequeue();
387 #ifndef QT_LOCALSOCKET_TCP
388 if (d->pendingConnections.size() <= d->maxPendingConnections)
390 d->socketNotifier->setEnabled(true);
392 d->connectionEventNotifier->setEnabled(true);
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.
406 On Windows, this function does nothing; on Unix, it removes the socket file
409 \warning Be careful to avoid removing sockets of running instances.
411 bool QLocalServer::removeServer(const QString &name)
413 return QLocalServerPrivate::removeServer(name);
417 Returns the server name if the server is listening for connections;
418 otherwise returns QString()
420 \sa listen(), fullServerName()
422 QString QLocalServer::serverName() const
424 Q_D(const QLocalServer);
425 return d->serverName;
429 Returns the full path that the server is listening on.
431 Note: This is platform specific
433 \sa listen(), serverName()
435 QString QLocalServer::fullServerName() const
437 Q_D(const QLocalServer);
438 return d->fullServerName;
442 Returns the type of error that occurred last or NoError.
446 QAbstractSocket::SocketError QLocalServer::serverError() const
448 Q_D(const QLocalServer);
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()
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.
463 \sa maxPendingConnections(), hasPendingConnections()
465 void QLocalServer::setMaxPendingConnections(int numConnections)
468 d->maxPendingConnections = numConnections;
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.
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.
482 The non-blocking alternative is to connect to the newConnection() signal.
484 If msec is -1, this function will not time out.
486 \sa hasPendingConnections(), nextPendingConnection()
488 bool QLocalServer::waitForNewConnection(int msec, bool *timedOut)
497 d->waitForNewConnection(msec, timedOut);
499 return !d->pendingConnections.isEmpty();
506 #include "moc_qlocalserver.cpp"