source: trunk/src/network/qsocket.cpp@ 8

Last change on this file since 8 was 2, checked in by dmik, 20 years ago

Imported xplatform parts of the official release 3.3.1 from Trolltech

  • Property svn:keywords set to Id
File size: 41.0 KB
Line 
1/****************************************************************************
2** $Id: qsocket.cpp 2 2005-11-16 15:49:26Z dmik $
3**
4** Implementation of QSocket class.
5**
6** Created : 970521
7**
8** Copyright (C) 1992-2002 Trolltech AS. All rights reserved.
9**
10** This file is part of the network module of the Qt GUI Toolkit.
11**
12** This file may be distributed under the terms of the Q Public License
13** as defined by Trolltech AS of Norway and appearing in the file
14** LICENSE.QPL included in the packaging of this file.
15**
16** This file may be distributed and/or modified under the terms of the
17** GNU General Public License version 2 as published by the Free Software
18** Foundation and appearing in the file LICENSE.GPL included in the
19** packaging of this file.
20**
21** Licensees holding valid Qt Enterprise Edition licenses may use this
22** file in accordance with the Qt Commercial License Agreement provided
23** with the Software.
24**
25** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
26** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27**
28** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
29** information about Qt Commercial License Agreements.
30** See http://www.trolltech.com/qpl/ for QPL licensing information.
31** See http://www.trolltech.com/gpl/ for GPL licensing information.
32**
33** Contact info@trolltech.com if any conditions of this licensing are
34** not clear to you.
35**
36**********************************************************************/
37
38#include "qsocket.h"
39#ifndef QT_NO_NETWORK
40#include "qptrlist.h"
41#include "qtimer.h"
42#include "qsocketdevice.h"
43#include "qdns.h"
44#include "private/qinternal_p.h"
45
46#include <string.h>
47#ifndef NO_ERRNO_H
48#include <errno.h>
49#endif
50
51//#define QSOCKET_DEBUG
52
53/*
54 Perhaps this private functionality needs to be refactored.
55
56 Comment from Robert D Gatlin (Intel):
57
58 It would be nice to have the functionality inherent in QSocket available
59 as a separate class as a standard part of the Qt library, something along
60 the line of:
61
62 class QByteBuffer : public QIODevice { ... }
63
64 The same class could/would be used within QSocket for the Read/Write
65 buffers.
66
67 The above class could be used in the following way(s):
68
69 buffer.open( IO_WriteOnly | IO_Append );
70 buffer.writeBlock( a ); // a = QByteArray
71 buffer.close();
72
73 QByteArray b;
74 b.resize( buffer.size() );
75 buffer.open( IO_ReadOnly );
76 buffer.readBlock( b.data(), b.size() );
77 buffer.close();
78
79 But would also be useable with QDataStream (via QIODevice) with:
80
81 buffer.open( IO_WriteOnly | IO_Append );
82 QDataStream is( &buffer );
83 is << 100;
84 buffer.close();
85
86 buffer.open( IO_ReadOnly );
87 QDataStream os( &buffer );
88 Q_UINT32 x;
89 os >> x;
90 buffer.close();
91
92 The real usefulness is with any situations where data (QByteArray) arrives
93 incrementally (as in QSocket and filter case above).
94
95 I tried using QBuffer, but QBuffer does not trim bytes from the front of
96 the buffer in cases like:
97
98 QBuffer buf;
99 buf.open( IO_ReadOnly );
100 QDataStream ds( &buf );
101 Q_INT32 x;
102 ds >> x;
103 buf.close();
104
105 In the above case, buf.size() will be identical before and after the
106 operation with QDataStream. Based on the implementation of QBuffer, it
107 does not appear well suited for this kind of operation.
108*/
109
110// Private class for QSocket
111
112class QSocketPrivate {
113public:
114 QSocketPrivate();
115 ~QSocketPrivate();
116 void closeSocket();
117 void close();
118 void connectionClosed();
119 void setSocketDevice( QSocket *q, QSocketDevice *device );
120
121 QSocket::State state; // connection state
122 QString host; // host name
123 Q_UINT16 port; // host port
124 QSocketDevice *socket; // connection socket
125 QSocketNotifier *rsn, *wsn; // socket notifiers
126 QMembuf rba; // read buffer
127 Q_ULONG readBufferSize; // limit for the read buffer size
128 QPtrList<QByteArray> wba; // list of write bufs
129 QHostAddress addr; // connection address
130 QValueList<QHostAddress> addresses; // alternatives looked up
131 QIODevice::Offset wsize; // write total buf size
132 QIODevice::Offset windex; // write index
133#ifndef QT_NO_DNS
134 QDns *dns4;
135 QDns *dns6;
136#endif
137 static QPtrList<QSocket> sn_read_alreadyCalled; // used to avoid unwanted recursion
138};
139
140QPtrList<QSocket> QSocketPrivate::sn_read_alreadyCalled;
141
142QSocketPrivate::QSocketPrivate()
143 : state(QSocket::Idle), host(QString::fromLatin1("")), port(0),
144 socket(0), rsn(0), wsn(0), readBufferSize(0), wsize(0), windex(0)
145{
146#ifndef QT_NO_DNS
147 dns4 = 0;
148 dns6 = 0;
149#endif
150 wba.setAutoDelete( TRUE );
151}
152
153QSocketPrivate::~QSocketPrivate()
154{
155 close();
156 delete socket;
157#ifndef QT_NO_DNS
158 delete dns4;
159 delete dns6;
160#endif
161}
162
163void QSocketPrivate::closeSocket()
164{
165 // Order is important here - the socket notifiers must go away
166 // before the socket does, otherwise libc or the kernel will
167 // become unhappy.
168 delete rsn;
169 rsn = 0;
170 delete wsn;
171 wsn = 0;
172 if ( socket )
173 socket->close();
174}
175
176void QSocketPrivate::close()
177{
178 closeSocket();
179 wsize = 0;
180 rba.clear(); wba.clear();
181 windex = 0;
182}
183
184void QSocketPrivate::connectionClosed()
185{
186 // We keep the open state in case there's unread incoming data
187 state = QSocket::Idle;
188 closeSocket();
189 wba.clear();
190 windex = wsize = 0;
191}
192
193void QSocketPrivate::setSocketDevice( QSocket *q, QSocketDevice *device )
194{
195 delete socket;
196 delete rsn;
197 delete wsn;
198
199 if ( device ) {
200 socket = device;
201 } else {
202 socket = new QSocketDevice( QSocketDevice::Stream,
203 ( addr.isIPv4Address() ?
204 QSocketDevice::IPv4 :
205 QSocketDevice::IPv6 ), 0 );
206 socket->setBlocking( FALSE );
207 socket->setAddressReusable( TRUE );
208 }
209
210 rsn = new QSocketNotifier( socket->socket(),
211 QSocketNotifier::Read, q, "read" );
212 wsn = new QSocketNotifier( socket->socket(),
213 QSocketNotifier::Write, q, "write" );
214
215 QObject::connect( rsn, SIGNAL(activated(int)), q, SLOT(sn_read()) );
216 rsn->setEnabled( FALSE );
217 QObject::connect( wsn, SIGNAL(activated(int)), q, SLOT(sn_write()) );
218 wsn->setEnabled( FALSE );
219}
220
221/*!
222 \class QSocket qsocket.h
223 \brief The QSocket class provides a buffered TCP connection.
224\if defined(commercial)
225 It is part of the <a href="commercialeditions.html">Qt Enterprise Edition</a>.
226\endif
227
228 \ingroup io
229 \module network
230
231 It provides a totally non-blocking QIODevice, and modifies and
232 extends the API of QIODevice with socket-specific code.
233
234 The functions you're likely to call most are connectToHost(),
235 bytesAvailable(), canReadLine() and the ones it inherits from
236 QIODevice.
237
238 connectToHost() is the most-used function. As its name implies,
239 it opens a connection to a named host.
240
241 Most network protocols are either packet-oriented or
242 line-oriented. canReadLine() indicates whether a connection
243 contains an entire unread line or not, and bytesAvailable()
244 returns the number of bytes available for reading.
245
246 The signals error(), connected(), readyRead() and
247 connectionClosed() inform you of the progress of the connection.
248 There are also some less commonly used signals. hostFound() is
249 emitted when connectToHost() has finished its DNS lookup and is
250 starting its TCP connection. delayedCloseFinished() is emitted
251 when close() succeeds. bytesWritten() is emitted when QSocket
252 moves data from its "to be written" queue into the TCP
253 implementation.
254
255 There are several access functions for the socket: state() returns
256 whether the object is idle, is doing a DNS lookup, is connecting,
257 has an operational connection, etc. address() and port() return
258 the IP address and port used for the connection. The peerAddress()
259 and peerPort() functions return the IP address and port used by
260 the peer, and peerName() returns the name of the peer (normally
261 the name that was passed to connectToHost()). socket() returns a
262 pointer to the QSocketDevice used for this socket.
263
264 QSocket inherits QIODevice, and reimplements some functions. In
265 general, you can treat it as a QIODevice for writing, and mostly
266 also for reading. The match isn't perfect, since the QIODevice
267 API is designed for devices that are controlled by the same
268 machine, and an asynchronous peer-to-peer network connection isn't
269 quite like that. For example, there is nothing that matches
270 QIODevice::size() exactly. The documentation for open(), close(),
271 flush(), size(), at(), atEnd(), readBlock(), writeBlock(),
272 getch(), putch(), ungetch() and readLine() describes the
273 differences in detail.
274
275 \warning QSocket is not suitable for use in threads. If you need
276 to uses sockets in threads use the lower-level QSocketDevice class.
277
278 \sa QSocketDevice, QHostAddress, QSocketNotifier
279*/
280
281
282/*!
283 Creates a QSocket object in \c QSocket::Idle state.
284
285 The \a parent and \a name arguments are passed on to the QObject
286 constructor.
287*/
288
289QSocket::QSocket( QObject *parent, const char *name )
290 : QObject( parent, name )
291{
292 d = new QSocketPrivate;
293 setSocketDevice( 0 );
294 setFlags( IO_Direct );
295 resetStatus();
296}
297
298
299/*!
300 Destroys the socket. Closes the connection if necessary.
301
302 \sa close()
303*/
304
305QSocket::~QSocket()
306{
307#if defined(QSOCKET_DEBUG)
308 qDebug( "QSocket (%s): Destroy", name() );
309#endif
310 if ( state() != Idle )
311 close();
312 Q_ASSERT( d != 0 );
313 delete d;
314}
315
316
317/*!
318 Returns a pointer to the internal socket device.
319
320 There is normally no need to manipulate the socket device directly
321 since this class does the necessary setup for most applications.
322*/
323
324QSocketDevice *QSocket::socketDevice()
325{
326 return d->socket;
327}
328
329/*!
330 Sets the internal socket device to \a device. Passing a \a device
331 of 0 will cause the internal socket device to be used. Any
332 existing connection will be disconnected before using the new \a
333 device.
334
335 The new device should not be connected before being associated
336 with a QSocket; after setting the socket call connectToHost() to
337 make the connection.
338
339 This function is useful if you need to subclass QSocketDevice and
340 want to use the QSocket API, for example, to implement Unix domain
341 sockets.
342*/
343
344void QSocket::setSocketDevice( QSocketDevice *device )
345{
346 if ( state() != Idle )
347 close();
348 d->setSocketDevice( this, device );
349}
350
351/*!
352 \enum QSocket::State
353
354 This enum defines the connection states:
355
356 \value Idle if there is no connection
357 \value HostLookup during a DNS lookup
358 \value Connecting during TCP connection establishment
359 \value Connected when there is an operational connection
360 \value Closing if the socket is closing down, but is not yet closed.
361*/
362
363/*!
364 Returns the current state of the socket connection.
365
366 \sa QSocket::State
367*/
368
369QSocket::State QSocket::state() const
370{
371 return d->state;
372}
373
374
375#ifndef QT_NO_DNS
376
377/*!
378 Attempts to make a connection to \a host on the specified \a port
379 and return immediately.
380
381 Any connection or pending connection is closed immediately, and
382 QSocket goes into the \c HostLookup state. When the lookup
383 succeeds, it emits hostFound(), starts a TCP connection and goes
384 into the \c Connecting state. Finally, when the connection
385 succeeds, it emits connected() and goes into the \c Connected
386 state. If there is an error at any point, it emits error().
387
388 \a host may be an IP address in string form, or it may be a DNS
389 name. QSocket will do a normal DNS lookup if required. Note that
390 \a port is in native byte order, unlike some other libraries.
391
392 \sa state()
393*/
394
395void QSocket::connectToHost( const QString &host, Q_UINT16 port )
396{
397#if defined(QSOCKET_DEBUG)
398 qDebug( "QSocket (%s)::connectToHost: host %s, port %d",
399 name(), host.ascii(), port );
400#endif
401 setSocketIntern( -1 );
402 d->state = HostLookup;
403 d->host = host;
404 d->port = port;
405 d->dns4 = new QDns( host, QDns::A );
406 d->dns6 = new QDns( host, QDns::Aaaa );
407
408 // try if the address is already available (for faster connecting...)
409 tryConnecting();
410 if ( d->state == HostLookup ) {
411 connect( d->dns4, SIGNAL(resultsReady()),
412 this, SLOT(tryConnecting()) );
413 connect( d->dns6, SIGNAL(resultsReady()),
414 this, SLOT(tryConnecting()) );
415 }
416}
417
418#endif
419
420
421/*!
422 This private slots continues the connection process where
423 connectToHost() leaves off.
424*/
425
426void QSocket::tryConnecting()
427{
428#if defined(QSOCKET_DEBUG)
429 qDebug( "QSocket (%s)::tryConnecting()", name() );
430#endif
431 // ### this ifdef isn't correct - addresses() also does /etc/hosts and
432 // numeric-address-as-string handling.
433#ifndef QT_NO_DNS
434 static QValueList<QHostAddress> l4;
435 static QValueList<QHostAddress> l6;
436
437 if ( d->dns4 ) {
438 l4 = d->dns4->addresses();
439 if ( !l4.isEmpty() || !d->dns4->isWorking() ) {
440#if defined(QSOCKET_DEBUG)
441 qDebug( "QSocket (%s)::tryConnecting: host %s, port %d: "
442 "%d IPv4 addresses",
443 name(), d->host.ascii(), d->port, l4.count() );
444#endif
445 delete d->dns4;
446 d->dns4 = 0;
447 }
448 }
449
450 if ( d->dns6 ) {
451 l6 = d->dns6->addresses();
452 if ( !l6.isEmpty() || !d->dns6->isWorking() ) {
453#if defined(QSOCKET_DEBUG)
454 qDebug( "QSocket (%s)::tryConnecting: host %s, port %d: "
455 "%d IPv6 addresses",
456 name(), d->host.ascii(), d->port, l6.count() );
457#endif
458 delete d->dns6;
459 d->dns6 = 0;
460 }
461 }
462
463 if ( d->state == HostLookup ) {
464 if ( l4.isEmpty() && l6.isEmpty() &&
465 !d->dns4 && !d->dns6 ) {
466 // no results and we're not still looking: give up
467 d->state = Idle;
468 emit error( ErrHostNotFound );
469 return;
470 }
471 if ( l4.isEmpty() && l6.isEmpty() ) {
472 // no results (yet): try again later
473 return;
474 }
475
476 // we've found something. press on with that. if we later find
477 // more, fine.
478 emit hostFound();
479 d->state = Connecting;
480 }
481
482 if ( d->state == Connecting ) {
483 d->addresses += l4;
484 d->addresses += l6;
485
486 // try one address at a time, falling back to the next one if
487 // there is a connection failure. (should also support a timeout,
488 // or do multiple TCP-level connects at a time, with staggered
489 // starts to avoid bandwidth waste and cause fewer
490 // "connect-and-abort" errors. but that later.)
491 bool stuck = TRUE;
492 while( stuck ) {
493 stuck = FALSE;
494 if ( d->socket &&
495 d->socket->connect( d->addr, d->port ) == FALSE ) {
496 if ( d->socket->error() == QSocketDevice::NoError ) {
497 if ( d->wsn )
498 d->wsn->setEnabled( TRUE );
499 return; // not serious, try again later
500 }
501
502#if defined(QSOCKET_DEBUG)
503 qDebug( "QSocket (%s)::tryConnecting: "
504 "Gave up on IP address %s",
505 name(), d->socket->peerAddress().toString().ascii() );
506#endif
507 delete d->wsn;
508 d->wsn = 0;
509 delete d->rsn;
510 d->rsn = 0;
511 delete d->socket;
512 d->socket = 0;
513 }
514 // if the host has more addresses, try another some.
515 if ( d->socket == 0 && !d->addresses.isEmpty() ) {
516 d->addr = *d->addresses.begin();
517 d->addresses.remove( d->addresses.begin() );
518 d->setSocketDevice( this, 0 );
519 stuck = TRUE;
520#if defined(QSOCKET_DEBUG)
521 qDebug( "QSocket (%s)::tryConnecting: Trying IP address %s",
522 name(), d->addr.toString().ascii() );
523#endif
524 }
525 };
526
527 // The socket write notifier will fire when the connection succeeds
528 if ( d->wsn )
529 d->wsn->setEnabled( TRUE );
530 }
531#endif
532}
533
534/*!
535 \enum QSocket::Error
536
537 This enum specifies the possible errors:
538 \value ErrConnectionRefused if the connection was refused
539 \value ErrHostNotFound if the host was not found
540 \value ErrSocketRead if a read from the socket failed
541*/
542
543/*!
544 \fn void QSocket::error( int )
545
546 This signal is emitted after an error occurred. The parameter is
547 the \l Error value.
548*/
549
550/*!
551 \fn void QSocket::hostFound()
552
553 This signal is emitted after connectToHost() has been called and
554 the host lookup has succeeded.
555
556 \sa connected()
557*/
558
559
560/*!
561 \fn void QSocket::connected()
562
563 This signal is emitted after connectToHost() has been called and a
564 connection has been successfully established.
565
566 \sa connectToHost(), connectionClosed()
567*/
568
569
570/*!
571 \fn void QSocket::connectionClosed()
572
573 This signal is emitted when the other end has closed the
574 connection. The read buffers may contain buffered input data which
575 you can read after the connection was closed.
576
577 \sa connectToHost(), close()
578*/
579
580
581/*!
582 \fn void QSocket::delayedCloseFinished()
583
584 This signal is emitted when a delayed close is finished.
585
586 If you call close() and there is buffered output data to be
587 written, QSocket goes into the \c QSocket::Closing state and
588 returns immediately. It will then keep writing to the socket until
589 all the data has been written. Then, the delayedCloseFinished()
590 signal is emitted.
591
592 \sa close()
593*/
594
595
596/*!
597 \fn void QSocket::readyRead()
598
599 This signal is emitted every time there is new incoming data.
600
601 Bear in mind that new incoming data is only reported once; if you do not
602 read all the data, this class buffers the data and you can read it later,
603 but no signal is emitted unless new data arrives. A good practice is to
604 read all data in the slot connected to this signal unless you are sure that
605 you need to receive more data to be able to process it.
606
607 \sa readBlock(), readLine(), bytesAvailable()
608*/
609
610
611/*!
612 \fn void QSocket::bytesWritten( int nbytes )
613
614 This signal is emitted when data has been written to the network.
615 The \a nbytes parameter specifies how many bytes were written.
616
617 The bytesToWrite() function is often used in the same context; it
618 indicates how many buffered bytes there are left to write.
619
620 \sa writeBlock(), bytesToWrite()
621*/
622
623
624/*!
625 Opens the socket using the specified QIODevice file mode \a m.
626 This function is called automatically when needed and you should
627 not call it yourself.
628
629 \sa close()
630*/
631
632bool QSocket::open( int m )
633{
634 if ( isOpen() ) {
635#if defined(QT_CHECK_STATE)
636 qWarning( "QSocket::open: Already open" );
637#endif
638 return FALSE;
639 }
640 QIODevice::setMode( m & IO_ReadWrite );
641 setState( IO_Open );
642 return TRUE;
643}
644
645
646/*!
647 Closes the socket.
648
649 The read buffer is cleared.
650
651 If the output buffer is empty, the state is set to \c
652 QSocket::Idle and the connection is terminated immediately. If the
653 output buffer still contains data to be written, QSocket goes into
654 the \c QSocket::Closing state and the rest of the data will be
655 written. When all of the outgoing data have been written, the
656 state is set to \c QSocket::Idle and the connection is terminated.
657 At this point, the delayedCloseFinished() signal is emitted.
658
659 If you don't want that the data of the output buffer is written, call
660 clearPendingData() before you call close().
661
662 \sa state(), bytesToWrite() clearPendingData()
663*/
664
665void QSocket::close()
666{
667 if ( !isOpen() || d->state == Idle ) // already closed
668 return;
669 if ( d->state == Closing )
670 return;
671 if ( !d->rsn || !d->wsn )
672 return;
673#if defined(QSOCKET_DEBUG)
674 qDebug( "QSocket (%s): close socket", name() );
675#endif
676 if ( d->socket && d->wsize ) { // there's data to be written
677 d->state = Closing;
678 if ( d->rsn )
679 d->rsn->setEnabled( FALSE );
680 if ( d->wsn )
681 d->wsn->setEnabled( TRUE );
682 d->rba.clear(); // clear incoming data
683 return;
684 }
685 setFlags( IO_Sequential );
686 resetStatus();
687 setState( 0 );
688 d->close();
689 d->state = Idle;
690}
691
692
693/*!
694 This function consumes \a nbytes bytes of data from the write
695 buffer.
696*/
697
698bool QSocket::consumeWriteBuf( Q_ULONG nbytes )
699{
700 if ( nbytes <= 0 || nbytes > d->wsize )
701 return FALSE;
702#if defined(QSOCKET_DEBUG)
703 qDebug( "QSocket (%s): skipWriteBuf %d bytes", name(), (int)nbytes );
704#endif
705 d->wsize -= nbytes;
706 for ( ;; ) {
707 QByteArray *a = d->wba.first();
708 if ( d->windex + nbytes >= a->size() ) {
709 nbytes -= a->size() - d->windex;
710 d->wba.remove();
711 d->windex = 0;
712 if ( nbytes == 0 )
713 break;
714 } else {
715 d->windex += nbytes;
716 break;
717 }
718 }
719 return TRUE;
720}
721
722
723
724/*!
725 Implementation of the abstract virtual QIODevice::flush() function.
726*/
727
728void QSocket::flush()
729{
730 bool osBufferFull = FALSE;
731 int consumed = 0;
732 while ( !osBufferFull && d->state >= Connecting && d->wsize > 0 ) {
733#if defined(QSOCKET_DEBUG)
734 qDebug( "QSocket (%s): flush: Write data to the socket", name() );
735#endif
736 QByteArray *a = d->wba.first();
737 int nwritten;
738 int i = 0;
739 if ( (int)a->size() - d->windex < 1460 ) {
740 // Concatenate many smaller blocks. the first may be
741 // partial, but each subsequent block is copied entirely
742 // or not at all. the sizes here are picked so that we
743 // generally won't trigger nagle's algorithm in the tcp
744 // implementation: we concatenate if we'd otherwise send
745 // less than PMTU bytes (we assume PMTU is 1460 bytes),
746 // and concatenate up to the largest payload TCP/IP can
747 // carry. with these precautions, nagle's algorithm
748 // should apply only when really appropriate.
749 QByteArray out( 65536 );
750 int j = d->windex;
751 int s = a->size() - j;
752 while ( a && i+s < (int)out.size() ) {
753 memcpy( out.data()+i, a->data()+j, s );
754 j = 0;
755 i += s;
756 a = d->wba.next();
757 s = a ? a->size() : 0;
758 }
759 nwritten = d->socket->writeBlock( out.data(), i );
760 if ( d->wsn )
761 d->wsn->setEnabled( FALSE ); // the QSocketNotifier documentation says so
762 } else {
763 // Big block, write it immediately
764 i = a->size() - d->windex;
765 nwritten = d->socket->writeBlock( a->data() + d->windex, i );
766 if ( d->wsn )
767 d->wsn->setEnabled( FALSE ); // the QSocketNotifier documentation says so
768 }
769 if ( nwritten > 0 ) {
770 if ( consumeWriteBuf( nwritten ) )
771 consumed += nwritten;
772 }
773 if ( nwritten < i )
774 osBufferFull = TRUE;
775 }
776 if ( consumed > 0 ) {
777#if defined(QSOCKET_DEBUG)
778 qDebug( "QSocket (%s): flush: wrote %d bytes, %d left",
779 name(), consumed, (int)d->wsize );
780#endif
781 emit bytesWritten( consumed );
782 }
783 if ( d->state == Closing && d->wsize == 0 ) {
784#if defined(QSOCKET_DEBUG)
785 qDebug( "QSocket (%s): flush: Delayed close done. Terminating.",
786 name() );
787#endif
788 setFlags( IO_Sequential );
789 resetStatus();
790 setState( 0 );
791 d->close();
792 d->state = Idle;
793 emit delayedCloseFinished();
794 return;
795 }
796 if ( !d->socket->isOpen() ) {
797 d->connectionClosed();
798 emit connectionClosed();
799 return;
800 }
801 if ( d->wsn )
802 d->wsn->setEnabled( d->wsize > 0 ); // write if there's data
803}
804
805
806/*!
807 Returns the number of incoming bytes that can be read right now
808 (like bytesAvailable()).
809*/
810
811QIODevice::Offset QSocket::size() const
812{
813 return (Offset)bytesAvailable();
814}
815
816
817/*!
818 Returns the current read index. Since QSocket is a sequential
819 device, the current read index is always zero.
820*/
821
822QIODevice::Offset QSocket::at() const
823{
824 return 0;
825}
826
827
828/*!
829 \overload
830
831 Moves the read index forward to \a index and returns TRUE if the
832 operation was successful; otherwise returns FALSE. Moving the
833 index forward means skipping incoming data.
834*/
835
836bool QSocket::at( Offset index )
837{
838 if ( index > d->rba.size() )
839 return FALSE;
840 d->rba.consumeBytes( (Q_ULONG)index, 0 ); // throw away data 0..index-1
841 // After we read data from our internal buffer, if we use the
842 // setReadBufferSize() to limit our buffer, we might now be able to
843 // read more data in our buffer. So enable the read socket notifier,
844 // but do this only if we are not in a slot connected to the
845 // readyRead() signal since this might cause a bad recursive behavior.
846 // We can test for this condition by looking at the
847 // sn_read_alreadyCalled flag.
848 if ( d->rsn && QSocketPrivate::sn_read_alreadyCalled.findRef(this) == -1 )
849 d->rsn->setEnabled( TRUE );
850 return TRUE;
851}
852
853
854/*!
855 Returns TRUE if there is no more data to read; otherwise returns FALSE.
856*/
857
858bool QSocket::atEnd() const
859{
860 if ( d->socket == 0 )
861 return TRUE;
862 QSocket * that = (QSocket *)this;
863 if ( that->d->socket->bytesAvailable() ) // a little slow, perhaps...
864 that->sn_read();
865 return that->d->rba.size() == 0;
866}
867
868
869/*!
870 Returns the number of incoming bytes that can be read, i.e. the
871 size of the input buffer. Equivalent to size().
872
873 \sa bytesToWrite()
874*/
875
876Q_ULONG QSocket::bytesAvailable() const
877{
878 if ( d->socket == 0 )
879 return 0;
880 QSocket * that = (QSocket *)this;
881 if ( that->d->socket->bytesAvailable() ) // a little slow, perhaps...
882 (void)that->sn_read();
883 return that->d->rba.size();
884}
885
886
887/*!
888 Wait up to \a msecs milliseconds for more data to be available.
889
890 If \a msecs is -1 the call will block indefinitely.
891
892 Returns the number of bytes available.
893
894 If \a timeout is non-null and no error occurred (i.e. it does not
895 return -1): this function sets \a *timeout to TRUE, if the reason
896 for returning was that the timeout was reached; otherwise it sets
897 \a *timeout to FALSE. This is useful to find out if the peer
898 closed the connection.
899
900 \warning This is a blocking call and should be avoided in event
901 driven applications.
902
903 \sa bytesAvailable()
904*/
905
906Q_ULONG QSocket::waitForMore( int msecs, bool *timeout ) const
907{
908 if ( d->socket == 0 )
909 return 0;
910 QSocket * that = (QSocket *)this;
911 if ( that->d->socket->waitForMore( msecs, timeout ) > 0 )
912 (void)that->sn_read( TRUE );
913 return that->d->rba.size();
914}
915
916/*! \overload
917*/
918
919Q_ULONG QSocket::waitForMore( int msecs ) const
920{
921 return waitForMore( msecs, 0 );
922}
923
924/*!
925 Returns the number of bytes that are waiting to be written, i.e.
926 the size of the output buffer.
927
928 \sa bytesAvailable() clearPendingData()
929*/
930
931Q_ULONG QSocket::bytesToWrite() const
932{
933 return d->wsize;
934}
935
936/*!
937 Deletes the data that is waiting to be written. This is useful if you want
938 to close the socket without waiting for all the data to be written.
939
940 \sa bytesToWrite() close() delayedCloseFinished()
941*/
942
943void QSocket::clearPendingData()
944{
945 d->wba.clear();
946 d->windex = d->wsize = 0;
947}
948
949/*!
950 Reads \a maxlen bytes from the socket into \a data and returns the
951 number of bytes read. Returns -1 if an error occurred.
952*/
953
954Q_LONG QSocket::readBlock( char *data, Q_ULONG maxlen )
955{
956 if ( data == 0 && maxlen != 0 ) {
957#if defined(QT_CHECK_NULL)
958 qWarning( "QSocket::readBlock: Null pointer error" );
959#endif
960 return -1;
961 }
962 if ( !isOpen() ) {
963#if defined(QT_CHECK_STATE)
964 qWarning( "QSocket::readBlock: Socket is not open" );
965#endif
966 return -1;
967 }
968 if ( maxlen >= d->rba.size() )
969 maxlen = d->rba.size();
970#if defined(QSOCKET_DEBUG)
971 qDebug( "QSocket (%s): readBlock %d bytes", name(), (int)maxlen );
972#endif
973 d->rba.consumeBytes( maxlen, data );
974 // After we read data from our internal buffer, if we use the
975 // setReadBufferSize() to limit our buffer, we might now be able to
976 // read more data in our buffer. So enable the read socket notifier,
977 // but do this only if we are not in a slot connected to the
978 // readyRead() signal since this might cause a bad recursive behavior.
979 // We can test for this condition by looking at the
980 // sn_read_alreadyCalled flag.
981 if ( d->rsn && QSocketPrivate::sn_read_alreadyCalled.findRef(this) == -1 )
982 d->rsn->setEnabled( TRUE );
983 return maxlen;
984}
985
986
987/*!
988 Writes \a len bytes to the socket from \a data and returns the
989 number of bytes written. Returns -1 if an error occurred.
990*/
991
992Q_LONG QSocket::writeBlock( const char *data, Q_ULONG len )
993{
994#if defined(QT_CHECK_NULL)
995 if ( data == 0 && len != 0 ) {
996 qWarning( "QSocket::writeBlock: Null pointer error" );
997 }
998#endif
999#if defined(QT_CHECK_STATE)
1000 if ( !isOpen() ) {
1001 qWarning( "QSocket::writeBlock: Socket is not open" );
1002 return -1;
1003 }
1004#endif
1005#if defined(QT_CHECK_STATE)
1006 if ( d->state == Closing ) {
1007 qWarning( "QSocket::writeBlock: Cannot write, socket is closing" );
1008 }
1009#endif
1010 if ( len == 0 || d->state == Closing || d->state == Idle )
1011 return 0;
1012 QByteArray *a = d->wba.last();
1013
1014 // next bit is sensitive. if we're writing really small chunks,
1015 // try to buffer up since system calls are expensive, and nagle's
1016 // algorithm is even more expensive. but if anything even
1017 // remotely large is being written, try to issue a write at once.
1018
1019 bool writeNow = ( d->wsize + len >= 1400 || len > 512 );
1020
1021 if ( a && a->size() + len < 128 ) {
1022 // small buffer, resize
1023 int i = a->size();
1024 a->resize( i+len );
1025 memcpy( a->data()+i, data, len );
1026 } else {
1027 // append new buffer
1028 a = new QByteArray( len );
1029 memcpy( a->data(), data, len );
1030 d->wba.append( a );
1031 }
1032 d->wsize += len;
1033 if ( writeNow )
1034 flush();
1035 else if ( d->wsn )
1036 d->wsn->setEnabled( TRUE );
1037#if defined(QSOCKET_DEBUG)
1038 qDebug( "QSocket (%s): writeBlock %d bytes", name(), (int)len );
1039#endif
1040 return len;
1041}
1042
1043
1044/*!
1045 Reads a single byte/character from the internal read buffer.
1046 Returns the byte/character read, or -1 if there is nothing to be
1047 read.
1048
1049 \sa bytesAvailable(), putch()
1050*/
1051
1052int QSocket::getch()
1053{
1054 if ( isOpen() && d->rba.size() > 0 ) {
1055 uchar c;
1056 d->rba.consumeBytes( 1, (char*)&c );
1057 // After we read data from our internal buffer, if we use the
1058 // setReadBufferSize() to limit our buffer, we might now be able to
1059 // read more data in our buffer. So enable the read socket notifier,
1060 // but do this only if we are not in a slot connected to the
1061 // readyRead() signal since this might cause a bad recursive behavior.
1062 // We can test for this condition by looking at the
1063 // sn_read_alreadyCalled flag.
1064 if ( d->rsn && QSocketPrivate::sn_read_alreadyCalled.findRef(this) == -1 )
1065 d->rsn->setEnabled( TRUE );
1066 return c;
1067 }
1068 return -1;
1069}
1070
1071
1072/*!
1073 Writes the character \a ch to the output buffer.
1074
1075 Returns \a ch, or -1 if an error occurred.
1076
1077 \sa getch()
1078*/
1079
1080int QSocket::putch( int ch )
1081{
1082 char buf[2];
1083 buf[0] = ch;
1084 return writeBlock(buf, 1) == 1 ? ch : -1;
1085}
1086
1087
1088/*!
1089 This implementation of the virtual function QIODevice::ungetch()
1090 prepends the character \a ch to the read buffer so that the next
1091 read returns this character as the first character of the output.
1092*/
1093
1094int QSocket::ungetch( int ch )
1095{
1096#if defined(QT_CHECK_STATE)
1097 if ( !isOpen() ) {
1098 qWarning( "QSocket::ungetch: Socket not open" );
1099 return -1;
1100 }
1101#endif
1102 return d->rba.ungetch( ch );
1103}
1104
1105
1106/*!
1107 Returns TRUE if it's possible to read an entire line of text from
1108 this socket at this time; otherwise returns FALSE.
1109
1110 Note that if the peer closes the connection unexpectedly, this
1111 function returns FALSE. This means that loops such as this won't
1112 work:
1113
1114 \code
1115 while( !socket->canReadLine() ) // WRONG
1116 ;
1117 \endcode
1118
1119 \sa readLine()
1120*/
1121
1122bool QSocket::canReadLine() const
1123{
1124 if ( ((QSocket*)this)->d->rba.scanNewline( 0 ) )
1125 return TRUE;
1126 return ( bytesAvailable() > 0 &&
1127 ((QSocket*)this)->d->rba.scanNewline( 0 ) );
1128}
1129
1130/*!
1131 \reimp
1132 \internal
1133 So that it's not hidden by our other readLine().
1134*/
1135Q_LONG QSocket::readLine( char *data, Q_ULONG maxlen )
1136{
1137 return QIODevice::readLine(data,maxlen);
1138}
1139
1140/*!
1141 Returns a line of text including a terminating newline character
1142 (\n). Returns "" if canReadLine() returns FALSE.
1143
1144 \sa canReadLine()
1145*/
1146
1147QString QSocket::readLine()
1148{
1149 QByteArray a(256);
1150 bool nl = d->rba.scanNewline( &a );
1151 QString s;
1152 if ( nl ) {
1153 at( a.size() ); // skips the data read
1154 s = QString( a );
1155 }
1156 return s;
1157}
1158
1159/*!
1160 \internal
1161 Internal slot for handling socket read notifications.
1162
1163 This function has can usually only be entered once (i.e. no
1164 recursive calls). If the argument \a force is TRUE, the function
1165 is executed, but no readyRead() signals are emitted. This
1166 behaviour is useful for the waitForMore() function, so that it is
1167 possible to call waitForMore() in a slot connected to the
1168 readyRead() signal.
1169*/
1170
1171void QSocket::sn_read( bool force )
1172{
1173 Q_LONG maxToRead = 0;
1174 if ( d->readBufferSize > 0 ) {
1175 maxToRead = d->readBufferSize - d->rba.size();
1176 if ( maxToRead <= 0 ) {
1177 if ( d->rsn )
1178 d->rsn->setEnabled( FALSE );
1179 return;
1180 }
1181 }
1182
1183 // Use QSocketPrivate::sn_read_alreadyCalled to avoid recursive calls of
1184 // sn_read() (and as a result avoid emitting the readyRead() signal in a
1185 // slot for readyRead(), if you use bytesAvailable()).
1186 if ( !force && QSocketPrivate::sn_read_alreadyCalled.findRef(this) != -1 )
1187 return;
1188 QSocketPrivate::sn_read_alreadyCalled.append( this );
1189
1190 char buf[4096];
1191 Q_LONG nbytes = d->socket->bytesAvailable();
1192 Q_LONG nread;
1193 QByteArray *a = 0;
1194
1195 if ( state() == Connecting ) {
1196 if ( nbytes > 0 ) {
1197 tryConnection();
1198 } else {
1199 // nothing to do, nothing to care about
1200 QSocketPrivate::sn_read_alreadyCalled.removeRef( this );
1201 return;
1202 }
1203 }
1204 if ( state() == Idle ) {
1205 QSocketPrivate::sn_read_alreadyCalled.removeRef( this );
1206 return;
1207 }
1208
1209 if ( nbytes <= 0 ) { // connection closed?
1210 // On Windows this may happen when the connection is still open.
1211 // This happens when the system is heavily loaded and we have
1212 // read all the data on the socket before a new WSAAsyncSelect
1213 // event is processed. A new read operation would then block.
1214 // This code is also useful when QSocket is used without an
1215 // event loop.
1216 nread = d->socket->readBlock( buf, maxToRead ? QMIN((Q_LONG)sizeof(buf),maxToRead) : sizeof(buf) );
1217 if ( nread == 0 ) { // really closed
1218#if defined(QSOCKET_DEBUG)
1219 qDebug( "QSocket (%s): sn_read: Connection closed", name() );
1220#endif
1221 // ### we should rather ask the socket device if it is closed
1222 d->connectionClosed();
1223 emit connectionClosed();
1224 QSocketPrivate::sn_read_alreadyCalled.removeRef( this );
1225 return;
1226 } else {
1227 if ( nread < 0 ) {
1228 if ( d->socket->error() == QSocketDevice::NoError ) {
1229 // all is fine
1230 QSocketPrivate::sn_read_alreadyCalled.removeRef( this );
1231 return;
1232 }
1233#if defined(QSOCKET_DEBUG)
1234 qWarning( "QSocket::sn_read (%s): Close error", name() );
1235#endif
1236 if ( d->rsn )
1237 d->rsn->setEnabled( FALSE );
1238 emit error( ErrSocketRead );
1239 QSocketPrivate::sn_read_alreadyCalled.removeRef( this );
1240 return;
1241 }
1242 a = new QByteArray( nread );
1243 memcpy( a->data(), buf, nread );
1244 }
1245
1246 } else { // data to be read
1247#if defined(QSOCKET_DEBUG)
1248 qDebug( "QSocket (%s): sn_read: %ld incoming bytes", name(), nbytes );
1249#endif
1250 if ( nbytes > (int)sizeof(buf) ) {
1251 // big
1252 a = new QByteArray( nbytes );
1253 nread = d->socket->readBlock( a->data(), maxToRead ? QMIN(nbytes,maxToRead) : nbytes );
1254 } else {
1255 a = 0;
1256 nread = d->socket->readBlock( buf, maxToRead ? QMIN((Q_LONG)sizeof(buf),maxToRead) : sizeof(buf) );
1257 if ( nread > 0 ) {
1258 // ##### could setRawData
1259 a = new QByteArray( nread );
1260 memcpy( a->data(), buf, nread );
1261 }
1262 }
1263 if ( nread == 0 ) {
1264#if defined(QSOCKET_DEBUG)
1265 qDebug( "QSocket (%s): sn_read: Connection closed", name() );
1266#endif
1267 // ### we should rather ask the socket device if it is closed
1268 d->connectionClosed();
1269 emit connectionClosed();
1270 QSocketPrivate::sn_read_alreadyCalled.removeRef( this );
1271 return;
1272 } else if ( nread < 0 ) {
1273 if ( d->socket->error() == QSocketDevice::NoError ) {
1274 // all is fine
1275 QSocketPrivate::sn_read_alreadyCalled.removeRef( this );
1276 return;
1277 }
1278#if defined(QT_CHECK_RANGE)
1279 qWarning( "QSocket::sn_read: Read error" );
1280#endif
1281 delete a;
1282 if ( d->rsn )
1283 d->rsn->setEnabled( FALSE );
1284 emit error( ErrSocketRead );
1285 QSocketPrivate::sn_read_alreadyCalled.removeRef( this );
1286 return;
1287 }
1288 if ( nread != (int)a->size() ) { // unexpected
1289#if defined(CHECK_RANGE) && !defined(Q_OS_WIN32)
1290 qWarning( "QSocket::sn_read: Unexpected short read" );
1291#endif
1292 a->resize( nread );
1293 }
1294 }
1295 d->rba.append( a );
1296 if ( !force ) {
1297 if ( d->rsn )
1298 d->rsn->setEnabled( FALSE );
1299 emit readyRead();
1300 if ( d->rsn )
1301 d->rsn->setEnabled( TRUE );
1302 }
1303
1304 QSocketPrivate::sn_read_alreadyCalled.removeRef( this );
1305}
1306
1307
1308/*!
1309 \internal
1310 Internal slot for handling socket write notifications.
1311*/
1312
1313void QSocket::sn_write()
1314{
1315 if ( d->state == Connecting ) // connection established?
1316 tryConnection();
1317 flush();
1318}
1319
1320void QSocket::emitErrorConnectionRefused()
1321{
1322 emit error( ErrConnectionRefused );
1323}
1324
1325void QSocket::tryConnection()
1326{
1327 if ( d->socket->connect( d->addr, d->port ) ) {
1328 d->state = Connected;
1329#if defined(QSOCKET_DEBUG)
1330 qDebug( "QSocket (%s): sn_write: Got connection to %s",
1331 name(), peerName().ascii() );
1332#endif
1333 if ( d->rsn )
1334 d->rsn->setEnabled( TRUE );
1335 emit connected();
1336 } else {
1337 d->state = Idle;
1338 QTimer::singleShot( 0, this, SLOT(emitErrorConnectionRefused()) );
1339 return;
1340 }
1341}
1342
1343
1344/*!
1345 Returns the socket number, or -1 if there is no socket at the moment.
1346*/
1347
1348int QSocket::socket() const
1349{
1350 if ( d->socket == 0 )
1351 return -1;
1352 return d->socket->socket();
1353}
1354
1355/*!
1356 Sets the socket to use \a socket and the state() to \c Connected.
1357 The socket must already be connected.
1358
1359 This allows us to use the QSocket class as a wrapper for other
1360 socket types (e.g. Unix Domain Sockets).
1361*/
1362
1363void QSocket::setSocket( int socket )
1364{
1365 setSocketIntern( socket );
1366 d->state = Connection;
1367 d->rsn->setEnabled( TRUE );
1368}
1369
1370
1371/*!
1372 Sets the socket to \a socket. This is used by both setSocket() and
1373 connectToHost() and can also be used on unconnected sockets.
1374*/
1375
1376void QSocket::setSocketIntern( int socket )
1377{
1378 if ( state() != Idle ) {
1379 clearPendingData();
1380 close();
1381 }
1382 delete d;
1383
1384 d = new QSocketPrivate;
1385 if ( socket >= 0 ) {
1386 QSocketDevice *sd = new QSocketDevice( socket, QSocketDevice::Stream );
1387 sd->setBlocking( FALSE );
1388 sd->setAddressReusable( TRUE );
1389 d->setSocketDevice( this, sd );
1390 }
1391 d->state = Idle;
1392
1393 // Initialize the IO device flags
1394 setFlags( IO_Direct );
1395 resetStatus();
1396 open( IO_ReadWrite );
1397
1398 // hm... this is not very nice.
1399 d->host = QString::null;
1400 d->port = 0;
1401#ifndef QT_NO_DNS
1402 delete d->dns4;
1403 d->dns4 = 0;
1404 delete d->dns6;
1405 d->dns6 = 0;
1406#endif
1407}
1408
1409
1410/*!
1411 Returns the host port number of this socket, in native byte order.
1412*/
1413
1414Q_UINT16 QSocket::port() const
1415{
1416 if ( d->socket == 0 )
1417 return 0;
1418 return d->socket->port();
1419}
1420
1421
1422/*!
1423 Returns the peer's host port number, normally as specified to the
1424 connectToHost() function. If none has been set, this function
1425 returns 0.
1426
1427 Note that Qt always uses native byte order, i.e. 67 is 67 in Qt;
1428 there is no need to call htons().
1429*/
1430
1431Q_UINT16 QSocket::peerPort() const
1432{
1433 if ( d->socket == 0 )
1434 return 0;
1435 return d->socket->peerPort();
1436}
1437
1438
1439/*!
1440 Returns the host address of this socket. (This is normally the
1441 main IP address of the host, but can be e.g. 127.0.0.1 for
1442 connections to localhost.)
1443*/
1444
1445QHostAddress QSocket::address() const
1446{
1447 if ( d->socket == 0 ) {
1448 QHostAddress tmp;
1449 return tmp;
1450 }
1451 return d->socket->address();
1452}
1453
1454
1455/*!
1456 Returns the host address as resolved from the name specified to
1457 the connectToHost() function.
1458*/
1459
1460QHostAddress QSocket::peerAddress() const
1461{
1462 if ( d->socket == 0 ) {
1463 QHostAddress tmp;
1464 return tmp;
1465 }
1466 return d->socket->peerAddress();
1467}
1468
1469
1470/*!
1471 Returns the host name as specified to the connectToHost()
1472 function. An empty string is returned if none has been set.
1473*/
1474
1475QString QSocket::peerName() const
1476{
1477 return d->host;
1478}
1479
1480/*!
1481 Sets the size of the QSocket's internal read buffer to \a bufSize.
1482
1483 Usually QSocket reads all data that is available from the operating
1484 system's socket. If the buffer size is limited to a certain size, this
1485 means that the QSocket class doesn't buffer more than this size of data.
1486
1487 If the size of the read buffer is 0, the read buffer is unlimited and all
1488 incoming data is buffered. This is the default.
1489
1490 If you read the data in the readyRead() signal, you shouldn't use this
1491 option since it might slow down your program unnecessary. This option is
1492 useful if you only need to read the data at certain points in time, like in
1493 a realtime streaming application.
1494
1495 \sa readBufferSize()
1496*/
1497
1498void QSocket::setReadBufferSize( Q_ULONG bufSize )
1499{
1500 d->readBufferSize = bufSize;
1501}
1502
1503/*!
1504 Returns the size of the read buffer.
1505
1506 \sa setReadBufferSize()
1507*/
1508
1509Q_ULONG QSocket::readBufferSize() const
1510{
1511 return d->readBufferSize;
1512}
1513
1514#endif //QT_NO_NETWORK
Note: See TracBrowser for help on using the repository browser.