summaryrefslogtreecommitdiffstats
path: root/src/gui/embedded/qunixsocketserver.cpp
blob: 6e9347b8afcca68d8c1445f4641accb93382d313 (plain)
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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qunixsocketserver_p.h"

// #define QUNIXSOCKETSERVER_DEBUG

#ifdef QUNIXSOCKETSERVER_DEBUG
#include <QDebug>
#endif

#include <QtCore/qsocketnotifier.h>

extern "C" {
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <errno.h>
};

#define UNIX_PATH_MAX 108 // From unix(7)

QT_BEGIN_NAMESPACE

class QUnixSocketServerPrivate : public QObject
{
Q_OBJECT
public:
    QUnixSocketServerPrivate(QUnixSocketServer * parent)
    : QObject(), me(parent), fd(-1), maxConns(30),
      error(QUnixSocketServer::NoError), acceptNotifier(0)
    {}

    QUnixSocketServer * me;
    int fd;
    int maxConns;
    QByteArray address;
    QUnixSocketServer::ServerError error;
    QSocketNotifier * acceptNotifier;
public slots:
    void acceptActivated();
};

/*!
  \class QUnixSocketServer
  \internal

  \brief The QUnixSocketServer class provides a Unix domain socket based server.
  \omit
  \ingroup Platform::DeviceSpecific
  \ingroup Platform::OS
  \ingroup Platform::Communications
  \endomit
  \ingroup qws

  This class makes it possible to accept incoming Unix domain socket
  connections.  Call \l QUnixSocketServer::listen() to have the server listen
  for incoming connections on a specified path.  The pure virtual
  \l QUnixSocketServer::incomingConnection() is called each time a new
  connection is established.  Users must inherit from QUnixSocketServer and
  implement this method.

  If an error occurs, \l QUnixSocketServer::serverError() returns the type of
  error.  Errors can only occur during server establishment - that is, during a
  call to \l QUnixSocketServer::listen().  Calling \l QUnixSocketServer::close()
  causes QUnixSocketServer to stop listening for connections and reset its
  state.

  QUnixSocketServer is often used in conjunction with the \l QUnixSocket class.

  \sa QUnixSocket
*/

/*!
  \enum QUnixSocketServer::ServerError

  The ServerError enumeration represents the errors that can occur during server
  establishment.  The most recent error can be retrieved through a call to
  \l QUnixSocketServer::serverError().

  \value NoError No error has occurred.
  \value InvalidPath An invalid path endpoint was passed to
         \l QUnixSocketServer::listen().  As defined by unix(7), invalid paths
         include an empty path, or what more than 107 characters long.
  \value ResourceError An error acquiring or manipulating the system's socket
         resources occurred.  For example, if the process runs out of available
         socket descriptors, a ResourceError will occur.
  \value BindError The server was unable to bind to the specified path.
  \value ListenError The server was unable to listen on the specified path for
         incoming connections.
  */

/*!
  Create a new Unix socket server with the given \a parent.
  */
QUnixSocketServer::QUnixSocketServer(QObject *parent)
: QObject(parent), d(0)
{
}

/*!
  Stops listening for incoming connection and destroys the Unix socket server.
  */
QUnixSocketServer::~QUnixSocketServer()
{
    close();
    if(d)
        delete d;
}

/*!
  Stop listening for incoming connections and resets the Unix socket server's
  state.  Calling this method while \l {QUnixSocketServer::isListening()}{not listening } for incoming connections is a no-op.

  \sa QUnixSocketServer::listen()
  */
void QUnixSocketServer::close()
{
    if(!d)
        return;

    if(d->acceptNotifier) {
        d->acceptNotifier->setEnabled(false);
        delete d->acceptNotifier;
    }
    d->acceptNotifier = 0;

    if(-1 != d->fd) {
#ifdef QUNIXSOCKET_DEBUG
        int closerv =
#endif
            ::close(d->fd);
#ifdef QUNIXSOCKET_DEBUG
        if(0 != closerv) {
            qDebug() << "QUnixSocketServer: Unable to close socket ("
                     << strerror(errno) << ")";
        }
#endif
    }
    d->fd = -1;
    d->address = QByteArray();
    d->error = NoError;
}

/*!
  Returns the last server error.  Errors may only occur within a call to
  \l QUnixSocketServer::listen(), and only when such a call fails.

  This method is not destructive, so multiple calls to
  QUnixSocketServer::serverError() will return the same value.  The error is
  only reset by an explicit call to \l QUnixSocketServer::close() or
  by further calls to \l QUnixSocketServer::listen().
  */
QUnixSocketServer::ServerError QUnixSocketServer::serverError() const
{
    if(!d)
        return NoError;

    return d->error;
}

/*!
  Returns true if this server is listening for incoming connections, false
  otherwise.

  \sa QUnixSocketServer::listen()
  */
bool QUnixSocketServer::isListening() const
{
    if(!d)
        return false;

    return (-1 != d->fd);
}

/*!
  Tells the server to listen for incoming connections on \a path.  Returns true
  if it successfully initializes, false otherwise.  In the case of failure, the
  \l QUnixSocketServer::serverError() error status is set accordingly.

  Calling this method while the server is already running will result in the
  server begin reset, and then attempting to listen on \a path.  This will not
  affect connections established prior to the server being reset, but further
  incoming connections on the previous path will be refused.

  The server can be explicitly reset by a call to \l QUnixSocketServer::close().

  \sa QUnixSocketServer::close()
  */
bool QUnixSocketServer::listen(const QByteArray & path)
{
    if(d) {
        close(); // Any existing server is destroyed
    } else {
        d = new QUnixSocketServerPrivate(this);
    }

    if(path.isEmpty() || path.size() > UNIX_PATH_MAX) {
        d->error = InvalidPath;
        return false;
    }
    unlink( path );  // ok if this fails

    // Create the socket
    d->fd = ::socket(PF_UNIX, SOCK_STREAM, 0);
    if(-1 == d->fd) {
#ifdef QUNIXSOCKETSERVER_DEBUG
        qDebug() << "QUnixSocketServer: Unable to create socket ("
                 << strerror(errno) << ")";
#endif
        close();
        d->error = ResourceError;
        return false;
    }

    // Construct our unix address
    struct ::sockaddr_un addr;
    addr.sun_family = AF_UNIX;
    ::memcpy(addr.sun_path, path.data(), path.size());
    if(path.size() < UNIX_PATH_MAX)
        addr.sun_path[path.size()] = '\0';

    // Attempt to bind
    if(-1 == ::bind(d->fd, (sockaddr *)&addr, sizeof(sockaddr_un))) {
#ifdef QUNIXSOCKETSERVER_DEBUG
        qDebug() << "QUnixSocketServer: Unable to bind socket ("
                 << strerror(errno) << ")";
#endif
        close();
        d->error = BindError;
        return false;
    }

    // Listen to socket
    if(-1 == ::listen(d->fd, d->maxConns)) {
#ifdef QUNIXSOCKETSERVER_DEBUG
        qDebug() << "QUnixSocketServer: Unable to listen socket ("
                 << strerror(errno) << ")";
#endif
        close();
        d->error = ListenError;
        return false;
    }

    // Success!
    d->address = path;
    d->acceptNotifier = new QSocketNotifier(d->fd, QSocketNotifier::Read, d);
    d->acceptNotifier->setEnabled(true);
    QObject::connect(d->acceptNotifier, SIGNAL(activated(int)),
                     d, SLOT(acceptActivated()));

    return true;
}

/*!
  Returns the Unix path on which this server is listening.  If this server is
  not listening, and empty address will be returned.
  */
QByteArray QUnixSocketServer::serverAddress() const
{
    if(!d)
        return QByteArray();
    return d->address;
}

int QUnixSocketServer::socketDescriptor() const
{
    if (!d)
        return -1;
    return d->fd;
}


/*!
  Returns the maximum length the queue of pending connections may grow to.  That
  is, the maximum number of clients attempting to connect for which the Unix
  socket server has not yet accepted and passed to
  \l QUnixSocketServer::incomingConnection().  If a connection request arrives
  with the queue full, the client may receive a connection refused notification.

  By default a queue length of 30 is used.

  \sa QUnixSocketServer::setMaxPendingConnections()
  */
int QUnixSocketServer::maxPendingConnections() const
{
    if(!d)
        return 30;

    return d->maxConns;
}

/*!
  Sets the maximum length the queue of pending connections may grow to
  \a numConnections.  This value will only apply to
  \l QUnixSocketServer::listen() calls made following the value change - it will
  not be retroactively applied.

  \sa QUnixSocketServer::maxPendingConnections()
  */
void QUnixSocketServer::setMaxPendingConnections(int numConnections)
{
    Q_ASSERT(numConnections >= 1);
    if(!d)
        d = new QUnixSocketServerPrivate(this);

    d->maxConns = numConnections;
}

/*!
  \fn void QUnixSocketServer::incomingConnection(int socketDescriptor)

  This method is invoked each time a new incoming connection is established with
  the server.  Clients must reimplement this function in their QUnixSocketServer
  derived class to handle the connection.

  A common approach to handling the connection is to pass \a socketDescriptor to
  a QUnixSocket instance.

  \sa QUnixSocket
  */

void QUnixSocketServerPrivate::acceptActivated()
{
    ::sockaddr_un r;
    socklen_t len = sizeof(sockaddr_un);
    int connsock = ::accept(fd, (sockaddr *)&r, &len);
#ifdef QUNIXSOCKETSERVER_DEBUG
    qDebug() << "QUnixSocketServer: Accept connection " << connsock;
#endif
    if(-1 != connsock)
        me->incomingConnection(connsock);
}

QT_END_NAMESPACE

#include "qunixsocketserver.moc"