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

source code of qtbase/src/network/socket/qlocalsocket.cpp