Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qlocalsocket.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include <QtNetwork/private/qtnetworkglobal_p.h>
6
7#include "qlocalsocket.h"
9
10#include <QtCore/qdebug.h>
11
13
14/*!
15 \class QLocalSocket
16 \since 4.4
17 \inmodule QtNetwork
18
19 \brief The QLocalSocket class provides a local socket.
20
21 On Windows this is a named pipe and on Unix this is a local domain socket.
22
23 If an error occurs, error() returns the type of error, and
24 errorString() can be called to get a human readable description
25 of what happened.
26
27 Although QLocalSocket is designed for use with an event loop, it's possible
28 to use it without one. In that case, you must use waitForConnected(),
29 waitForReadyRead(), waitForBytesWritten(), and waitForDisconnected()
30 which blocks until the operation is complete or the timeout expires.
31
32 \sa QLocalServer
33*/
34
35/*!
36 \enum QLocalSocket::SocketOption
37 \since 6.2
38 This enum describes the possible options that can be used to connect to
39 a server. Currently, on Linux and Android it is used for specifying
40 connection to a server listening to a socket bound to an abstract address.
41
42 \value NoOptions No options have been set.
43 \value AbstractNamespaceOption
44 The socket will try to connect to an abstract address. This flag is specific
45 to Linux and Android. On other platforms is ignored.
46
47 \sa socketOptions
48*/
49
50/*!
51 \fn void QLocalSocket::connectToServer(OpenMode openMode)
52 \since 5.1
53
54 Attempts to make a connection to serverName().
55 setServerName() must be called before you open the connection.
56 Alternatively you can use connectToServer(const QString &name, OpenMode openMode);
57
58 The socket is opened in the given \a openMode and first enters ConnectingState.
59 If a connection is established, QLocalSocket enters ConnectedState and emits connected().
60
61 After calling this function, the socket can emit errorOccurred() to signal that an error occurred.
62
63 \sa state(), serverName(), waitForConnected()
64*/
65
66/*!
67 \fn void QLocalSocket::open(OpenMode openMode)
68
69 Equivalent to connectToServer(OpenMode mode).
70 The socket is opened in the given \a openMode to the server defined by setServerName().
71
72 Note that unlike in most other QIODevice subclasses, open() may not open the device directly.
73 The function return false if the socket was already connected or if the server to connect
74 to was not defined and true in any other case. The connected() or errorOccurred() signals will be
75 emitted once the device is actually open (or the connection failed).
76
77 See connectToServer() for more details.
78*/
79
80/*!
81 \fn void QLocalSocket::connected()
82
83 This signal is emitted after connectToServer() has been called and
84 a connection has been successfully established.
85
86 \sa connectToServer(), disconnected()
87*/
88
89/*!
90 \fn bool QLocalSocket::setSocketDescriptor(qintptr socketDescriptor,
91 LocalSocketState socketState, OpenMode openMode)
92
93 Initializes QLocalSocket with the native socket descriptor
94 \a socketDescriptor. Returns \c true if socketDescriptor is accepted
95 as a valid socket descriptor; otherwise returns \c false. The socket is
96 opened in the mode specified by \a openMode, and enters the socket state
97 specified by \a socketState.
98
99 \note It is not possible to initialize two local sockets with the same
100 native socket descriptor.
101
102 \sa socketDescriptor(), state(), openMode()
103*/
104
105/*!
106 \fn qintptr QLocalSocket::socketDescriptor() const
107
108 Returns the native socket descriptor of the QLocalSocket object if
109 this is available; otherwise returns -1.
110
111 The socket descriptor is not available when QLocalSocket
112 is in UnconnectedState.
113 The type of the descriptor depends on the platform:
114
115 \list
116 \li On Windows, the returned value is a
117 \l{Winsock 2 Socket Handle}.
118
119 \li On INTEGRITY, the returned value is the
120 QTcpSocket socket descriptor and the type is defined by
121 \l{QTcpSocket::socketDescriptor}{socketDescriptor}.
122
123 \li On all other UNIX-like operating systems, the type is
124 a file descriptor representing a socket.
125 \endlist
126
127 \sa setSocketDescriptor()
128*/
129
130/*!
131 \fn qint64 QLocalSocket::readData(char *data, qint64 c)
132 \reimp
133*/
134
135/*!
136 \fn qint64 QLocalSocket::readLineData(char *data, qint64 maxSize)
137 \reimp
138*/
139
140/*!
141 \fn qint64 QLocalSocket::skipData(qint64 maxSize)
142 \reimp
143*/
144
145/*!
146 \fn qint64 QLocalSocket::writeData(const char *data, qint64 c)
147 \reimp
148*/
149
150/*!
151 \fn void QLocalSocket::abort()
152
153 Aborts the current connection and resets the socket.
154 Unlike disconnectFromServer(), this function immediately closes the socket,
155 clearing any pending data in the write buffer.
156
157 \sa disconnectFromServer(), close()
158*/
159
160/*!
161 \fn qint64 QLocalSocket::bytesAvailable() const
162 \reimp
163*/
164
165/*!
166 \fn qint64 QLocalSocket::bytesToWrite() const
167 \reimp
168*/
169
170/*!
171 \fn bool QLocalSocket::canReadLine() const
172 \reimp
173*/
174
175/*!
176 \fn void QLocalSocket::close()
177
178 Closes the I/O device for the socket and calls disconnectFromServer()
179 to close the socket's connection.
180
181 See QIODevice::close() for a description of the actions that occur when an I/O
182 device is closed.
183
184 \sa abort()
185*/
186
187/*!
188 \fn bool QLocalSocket::waitForBytesWritten(int msecs)
189 \reimp
190*/
191
192/*!
193 \fn bool QLocalSocket::flush()
194
195 This function writes as much as possible from the internal write buffer
196 to the socket, without blocking. If any data was written, this function
197 returns \c true; otherwise false is returned.
198
199 Call this function if you need QLocalSocket to start sending buffered data
200 immediately. The number of bytes successfully written depends on the
201 operating system. In most cases, you do not need to call this function,
202 because QLocalSocket will start sending data automatically once control
203 goes back to the event loop. In the absence of an event loop, call
204 waitForBytesWritten() instead.
205
206 \sa write(), waitForBytesWritten()
207*/
208
209/*!
210 \fn void QLocalSocket::disconnectFromServer()
211
212 Attempts to close the socket. If there is pending data waiting to be
213 written, QLocalSocket will enter ClosingState and wait until all data
214 has been written. Eventually, it will enter UnconnectedState and emit
215 the disconnected() signal.
216
217 \sa connectToServer()
218*/
219
220/*!
221 \fn QLocalSocket::LocalSocketError QLocalSocket::error() const
222
223 Returns the type of error that last occurred.
224
225 \sa state(), errorString()
226*/
227
228/*!
229 \fn bool QLocalSocket::isValid() const
230
231 Returns \c true if the socket is valid and ready for use; otherwise
232 returns \c false.
233
234 \note The socket's state must be ConnectedState before reading
235 and writing can occur.
236
237 \sa state(), connectToServer()
238*/
239
240/*!
241 \fn qint64 QLocalSocket::readBufferSize() const
242
243 Returns the size of the internal read buffer. This limits the amount of
244 data that the client can receive before you call read() or readAll().
245 A read buffer size of 0 (the default) means that the buffer has no size
246 limit, ensuring that no data is lost.
247
248 \sa setReadBufferSize(), read()
249*/
250
251/*!
252 \fn void QLocalSocket::setReadBufferSize(qint64 size)
253
254 Sets the size of QLocalSocket's internal read buffer to be \a size bytes.
255
256 If the buffer size is limited to a certain size, QLocalSocket won't
257 buffer more than this size of data. Exceptionally, a buffer size of 0
258 means that the read buffer is unlimited and all incoming data is buffered.
259 This is the default.
260
261 This option is useful if you only read the data at certain points in
262 time (e.g., in a real-time streaming application) or if you want to
263 protect your socket against receiving too much data, which may eventually
264 cause your application to run out of memory.
265
266 \sa readBufferSize(), read()
267*/
268
269/*!
270 \fn bool QLocalSocket::waitForConnected(int msecs)
271
272 Waits until the socket is connected, up to \a msecs milliseconds. If the
273 connection has been established, this function returns \c true; otherwise
274 it returns \c false. In the case where it returns \c false, you can call
275 error() to determine the cause of the error.
276
277 The following example waits up to one second for a connection
278 to be established:
279
280 \snippet code/src_network_socket_qlocalsocket_unix.cpp 0
281
282 If \a msecs is -1, this function will not time out.
283
284 \sa connectToServer(), connected()
285*/
286
287/*!
288 \fn bool QLocalSocket::waitForDisconnected(int msecs)
289
290 Waits until the socket has disconnected, up to \a msecs milliseconds. If the
291 connection was successfully disconnected, this function returns \c true;
292 otherwise it returns \c false (if the operation timed out, if an error
293 occurred, or if this QLocalSocket is already disconnected). In the case
294 where it returns \c false, you can call error() to determine the cause of
295 the error.
296
297 The following example waits up to one second for a connection
298 to be closed:
299
300 \snippet code/src_network_socket_qlocalsocket_unix.cpp 1
301
302 If \a msecs is -1, this function will not time out.
303
304 \sa disconnectFromServer(), close()
305*/
306
307/*!
308 \fn bool QLocalSocket::waitForReadyRead(int msecs)
309
310 This function blocks until data is available for reading and the
311 \l{QIODevice::}{readyRead()} signal has been emitted. The function
312 will timeout after \a msecs milliseconds; the default timeout is
313 30000 milliseconds.
314
315 The function returns \c true if data is available for reading;
316 otherwise it returns \c false (if an error occurred or the
317 operation timed out).
318
319 \sa waitForBytesWritten()
320*/
321
322/*!
323 \fn void QLocalSocket::disconnected()
324
325 This signal is emitted when the socket has been disconnected.
326
327 \sa connectToServer(), disconnectFromServer(), abort(), connected()
328*/
329
330/*!
331 \fn void QLocalSocket::errorOccurred(QLocalSocket::LocalSocketError socketError)
332 \since 5.15
333
334 This signal is emitted after an error occurred. The \a socketError
335 parameter describes the type of error that occurred.
336
337 QLocalSocket::LocalSocketError is not a registered metatype, so for queued
338 connections, you will have to register it with Q_DECLARE_METATYPE() and
339 qRegisterMetaType().
340
341 \sa error(), errorString(), {Creating Custom Qt Types}
342*/
343
344/*!
345 \fn void QLocalSocket::stateChanged(QLocalSocket::LocalSocketState socketState)
346
347 This signal is emitted whenever QLocalSocket's state changes.
348 The \a socketState parameter is the new state.
349
350 QLocalSocket::SocketState is not a registered metatype, so for queued
351 connections, you will have to register it with Q_DECLARE_METATYPE() and
352 qRegisterMetaType().
353
354 \sa state(), {Creating Custom Qt Types}
355*/
356
357/*!
358 Creates a new local socket. The \a parent argument is passed to
359 QObject's constructor.
360 */
361QLocalSocket::QLocalSocket(QObject * parent)
362 : QIODevice(*new QLocalSocketPrivate, parent)
363{
364 Q_D(QLocalSocket);
365
366 d->readBufferChunkSize = 0; // force QIODevice unbuffered mode
367 d->init();
368}
369
370/*!
371 Destroys the socket, closing the connection if necessary.
372 */
373QLocalSocket::~QLocalSocket()
374{
375 abort();
376#if !defined(Q_OS_WIN) && !defined(QT_LOCALSOCKET_TCP)
377 Q_D(QLocalSocket);
378 d->unixSocket.setParent(nullptr);
379#endif
380}
381
382bool QLocalSocket::open(OpenMode openMode)
383{
384 connectToServer(openMode);
385 return isOpen();
386}
387
388/*! \overload
389
390 Set the server \a name and attempts to make a connection to it.
391
392 The socket is opened in the given \a openMode and first enters ConnectingState.
393 If a connection is established, QLocalSocket enters ConnectedState and emits connected().
394
395 After calling this function, the socket can emit errorOccurred() to signal that an error occurred.
396
397 \sa state(), serverName(), waitForConnected()
398*/
399void QLocalSocket::connectToServer(const QString &name, OpenMode openMode)
400{
401 setServerName(name);
402 connectToServer(openMode);
403}
404
405/*!
406 \since 5.1
407
408 Set the \a name of the peer to connect to.
409 On Windows name is the name of a named pipe; on Unix name is the name of a local domain socket.
410
411 This function must be called when the socket is not connected.
412*/
413void QLocalSocket::setServerName(const QString & name)
414{
415 Q_D(QLocalSocket);
416 if (d->state != UnconnectedState) {
417 qWarning("QLocalSocket::setServerName() called while not in unconnected state");
418 return;
419 }
420 d->serverName = name;
421}
422
423/*!
424 Returns the name of the peer as specified by setServerName(), or an
425 empty QString if setServerName() has not been called or connectToServer() failed.
426
427 \sa connectToServer(), fullServerName()
428
429 */
430QString QLocalSocket::serverName() const
431{
432 Q_D(const QLocalSocket);
433 return d->serverName;
434}
435
436/*!
437 \property QLocalSocket::socketOptions
438 \since 6.2
439 \brief the socket options.
440
441 Options must be set while the socket is in \l{UnconnectedState} state.
442
443 \sa connectToServer()
444 */
445QLocalSocket::SocketOptions QLocalSocket::socketOptions() const
446{
447 Q_D(const QLocalSocket);
448 return d->socketOptions;
449}
450
451void QLocalSocket::setSocketOptions(QLocalSocket::SocketOptions option)
452{
453 Q_D(QLocalSocket);
454 if (d->state != UnconnectedState) {
455 qWarning("QLocalSocket::setSocketOptions() called while not in unconnected state");
456 return;
457 }
458 d->socketOptions = option;
459}
460
461QBindable<QLocalSocket::SocketOptions> QLocalSocket::bindableSocketOptions()
462{
463 Q_D(QLocalSocket);
464 return &d->socketOptions;
465}
466
467/*!
468 Returns the server path that the socket is connected to.
469
470 \note The return value of this function is platform specific.
471
472 \sa connectToServer(), serverName()
473 */
474QString QLocalSocket::fullServerName() const
475{
476 Q_D(const QLocalSocket);
477 return d->fullServerName;
478}
479
480/*!
481 Returns the state of the socket.
482
483 \sa error()
484 */
485QLocalSocket::LocalSocketState QLocalSocket::state() const
486{
487 Q_D(const QLocalSocket);
488 return d->state;
489}
490
491/*! \reimp
492*/
493bool QLocalSocket::isSequential() const
494{
495 return true;
496}
497
498/*!
499 \enum QLocalSocket::LocalSocketError
500
501 The LocalServerError enumeration represents the errors that can occur.
502 The most recent error can be retrieved through a call to
503 \l QLocalSocket::error().
504
505 \value ConnectionRefusedError The connection was refused by
506 the peer (or timed out).
507 \value PeerClosedError The remote socket closed the connection.
508 Note that the client socket (i.e., this socket) will be closed
509 after the remote close notification has been sent.
510 \value ServerNotFoundError The local socket name was not found.
511 \value SocketAccessError The socket operation failed because the
512 application lacked the required privileges.
513 \value SocketResourceError The local system ran out of resources
514 (e.g., too many sockets).
515 \value SocketTimeoutError The socket operation timed out.
516 \value DatagramTooLargeError The datagram was larger than the operating
517 system's limit (which can be as low as 8192 bytes).
518 \value ConnectionError An error occurred with the connection.
519 \value UnsupportedSocketOperationError The requested socket operation
520 is not supported by the local operating system.
521 \value OperationError An operation was attempted while the socket was in a state that
522 did not permit it.
523 \value UnknownSocketError An unidentified error occurred.
524 */
525
526/*!
527 \enum QLocalSocket::LocalSocketState
528
529 This enum describes the different states in which a socket can be.
530
531 \sa QLocalSocket::state()
532
533 \value UnconnectedState The socket is not connected.
534 \value ConnectingState The socket has started establishing a connection.
535 \value ConnectedState A connection is established.
536 \value ClosingState The socket is about to close
537 (data may still be waiting to be written).
538 */
539
540#ifndef QT_NO_DEBUG_STREAM
541QDebug operator<<(QDebug debug, QLocalSocket::LocalSocketError error)
542{
543 QDebugStateSaver saver(debug);
544 debug.resetFormat().nospace();
545 switch (error) {
546 case QLocalSocket::ConnectionRefusedError:
547 debug << "QLocalSocket::ConnectionRefusedError";
548 break;
549 case QLocalSocket::PeerClosedError:
550 debug << "QLocalSocket::PeerClosedError";
551 break;
552 case QLocalSocket::ServerNotFoundError:
553 debug << "QLocalSocket::ServerNotFoundError";
554 break;
555 case QLocalSocket::SocketAccessError:
556 debug << "QLocalSocket::SocketAccessError";
557 break;
558 case QLocalSocket::SocketResourceError:
559 debug << "QLocalSocket::SocketResourceError";
560 break;
561 case QLocalSocket::SocketTimeoutError:
562 debug << "QLocalSocket::SocketTimeoutError";
563 break;
564 case QLocalSocket::DatagramTooLargeError:
565 debug << "QLocalSocket::DatagramTooLargeError";
566 break;
567 case QLocalSocket::ConnectionError:
568 debug << "QLocalSocket::ConnectionError";
569 break;
570 case QLocalSocket::UnsupportedSocketOperationError:
571 debug << "QLocalSocket::UnsupportedSocketOperationError";
572 break;
573 case QLocalSocket::UnknownSocketError:
574 debug << "QLocalSocket::UnknownSocketError";
575 break;
576 case QLocalSocket::OperationError:
577 debug << "QLocalSocket::OperationError";
578 break;
579 default:
580 debug << "QLocalSocket::SocketError(" << int(error) << ')';
581 break;
582 }
583 return debug;
584}
585
586QDebug operator<<(QDebug debug, QLocalSocket::LocalSocketState state)
587{
588 QDebugStateSaver saver(debug);
589 debug.resetFormat().nospace();
590 switch (state) {
591 case QLocalSocket::UnconnectedState:
592 debug << "QLocalSocket::UnconnectedState";
593 break;
594 case QLocalSocket::ConnectingState:
595 debug << "QLocalSocket::ConnectingState";
596 break;
597 case QLocalSocket::ConnectedState:
598 debug << "QLocalSocket::ConnectedState";
599 break;
600 case QLocalSocket::ClosingState:
601 debug << "QLocalSocket::ClosingState";
602 break;
603 default:
604 debug << "QLocalSocket::SocketState(" << int(state) << ')';
605 break;
606 }
607 return debug;
608}
609#endif
610
611QT_END_NAMESPACE
612
613#include "moc_qlocalsocket.cpp"