fix logic
[personal-kdelibs.git] / kdecore / network / k3socketbase.h
blobe2a3d5ee090e58a6cab93b4ca4d101f80911a812
1 /* -*- C++ -*-
2 * Copyright (C) 2003,2005 Thiago Macieira <thiago@kde.org>
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sublicense, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 * Even before our #ifdef, clean up the namespace
28 #ifdef socket
29 #undef socket
30 #endif
32 #ifdef bind
33 #undef bind
34 #endif
36 #ifdef listen
37 #undef listen
38 #endif
40 #ifdef connect
41 #undef connect
42 #endif
44 #ifdef accept
45 #undef accept
46 #endif
48 #ifdef getpeername
49 #undef getpeername
50 #endif
52 #ifdef getsockname
53 #undef getsockname
54 #endif
56 #ifndef KSOCKETBASE_H
57 #define KSOCKETBASE_H
59 #include <QtCore/QIODevice>
60 #include <QtCore/QString>
62 #include <kdecore_export.h>
63 #include "k3socketaddress.h"
65 class QMutex;
67 namespace KNetwork {
69 class KResolverEntry;
70 class KSocketDevice;
72 class KSocketBasePrivate;
73 /** @class KSocketBase k3socketbase.h k3socketbase.h
74 * @brief Basic socket functionality.
76 * This class provides the basic socket functionlity for descended classes.
77 * Socket classes are thread-safe and provide a recursive mutex should it be
78 * needed.
80 * @note This class is abstract.
82 * @author Thiago Macieira <thiago@kde.org>
83 * @deprecated Use KSocketFactory or KLocalSocket instead
85 class KDECORE_EXPORT KSocketBase
87 public:
88 /**
89 * Possible socket options.
91 * These are the options that may be set on a socket:
92 * - Blocking: whether the socket shall operate in blocking
93 * or non-blocking mode. This flag defaults to on.
94 * See setBlocking().
95 * - AddressReusable: whether the address used by this socket will
96 * be available for reuse by other sockets. This flag defaults to off.
97 * See setAddressReuseable().
98 * - IPv6Only: whether an IPv6 socket will accept IPv4 connections
99 * through a mapped address. This flag defaults to off.
100 * See setIPv6Only().
101 * - KeepAlive: whether TCP should send keepalive probes when a connection
102 * has gone idle for far too long.
103 * - Broadcast: whether this socket is allowed to send broadcast packets
104 * and will receive packets sent to broadcast.
105 * - NoDelay: disable the Nagle algorithm for socket types that support
106 * it.
108 enum SocketOptions
110 Blocking = 0x01,
111 AddressReuseable = 0x02,
112 IPv6Only = 0x04,
113 Keepalive = 0x08,
114 Broadcast = 0x10,
115 NoDelay = 0x20
119 * Possible socket error codes.
121 * This is a list of possible error conditions that socket classes may
122 * be expected to find.
124 * - NoError: no error has been detected
125 * - LookupFailure: if a name lookup has failed
126 * - AddressInUse: address is already in use
127 * - AlreadyBound: cannot bind again
128 * - AlreadyCreated: cannot recreate the socket
129 * - NotBound: operation required socket to be bound and it isn't
130 * - NotCreated: operation required socket to exist and it doesn't
131 * - WouldBlock: requested I/O operation would block
132 * - ConnectionRefused: connection actively refused
133 * - ConnectionTimedOut: connection timed out
134 * - InProgress: operation (connection) is already in progress
135 * - NetFailure: a network failure occurred (no route, host down, host unreachable or similar)
136 * - NotSupported: requested operation is not supported
137 * - Timeout: a timed operation timed out
138 * - UnknownError: an unknown/unexpected error has happened
139 * - RemotelyDisconnected: when a connection is disconnected by the other end (since 3.4)
141 * @sa error, errorString
143 enum SocketError
145 NoError = 0,
146 LookupFailure,
147 AddressInUse,
148 AlreadyCreated,
149 AlreadyBound,
150 AlreadyConnected,
151 NotConnected,
152 NotBound,
153 NotCreated,
154 WouldBlock,
155 ConnectionRefused,
156 ConnectionTimedOut,
157 InProgress,
158 NetFailure,
159 NotSupported,
160 Timeout,
161 UnknownError,
162 RemotelyDisconnected
165 public:
167 * Default constructor.
169 KSocketBase();
172 * Destructor.
174 virtual ~KSocketBase();
177 * The following functions are shared by all descended classes and will have
178 * to be reimplemented.
181 protected:
183 * Set the given socket options.
185 * The default implementation does nothing but store the mask internally.
186 * Descended classes must override this function to achieve functionality and
187 * must also call this implementation.
189 * @param opts a mask of SocketOptions or-ed bits of options to set
190 * or unset
191 * @returns true on success
192 * @note this function sets the options corresponding to the bits enabled in @p opts
193 * but will also unset the optiosn corresponding to the bits not set.
195 virtual bool setSocketOptions(int opts);
198 * Retrieves the socket options that have been set.
200 * The default implementation just retrieves the mask from an internal variable.
201 * Descended classes may choose to override this function to read the values
202 * from the operating system.
204 * @returns the mask of the options set
206 virtual int socketOptions() const;
208 public:
210 * Sets this socket's blocking mode.
212 * In blocking operation, all I/O functions are susceptible to blocking --
213 * i.e., will not return unless the I/O can be satisfied. In non-blocking
214 * operation, if the I/O would block, the function will return an error
215 * and set the corresponding error code.
217 * The default implementation toggles the Blocking flag with the current
218 * socket options and calls setSocketOptions().
220 * @param enable whether to set this socket to blocking mode
221 * @returns whether setting this value was successful; it is NOT the
222 * final blocking mode.
224 virtual bool setBlocking(bool enable);
227 * Retrieves this socket's blocking mode.
229 * @returns true if this socket is/will be operated in blocking mode,
230 * false if non-blocking.
232 bool blocking() const;
235 * Sets this socket's address reuseable flag.
237 * When the address reuseable flag is active, the address used by
238 * this socket is left reuseable for other sockets to bind. If
239 * the flag is not active, no other sockets may reuse the same
240 * address.
242 * The default implementation toggles the AddressReuseable flag with the current
243 * socket options and calls setSocketOptions().
245 * @param enable whether to set the flag on or off
246 * @returns true if setting this flag was successful
248 virtual bool setAddressReuseable(bool enable);
251 * Retrieves this socket's address reuseability flag.
253 * @returns true if this socket's address can be reused,
254 * false if it can't.
256 bool addressReuseable() const;
259 * Sets this socket's IPv6 Only flag.
261 * When this flag is on, an IPv6 socket will only accept, connect, send to or
262 * receive from IPv6 addresses. When it is off, it will also talk to
263 * IPv4 addresses through v4-mapped addresses.
265 * This option has no effect on non-IPv6 sockets.
267 * The default implementation toggles the IPv6Only flag with the current
268 * socket options and calls setSocketOptions().
270 * @param enable whether to set the flag on or off
271 * @returns true if setting this flag was successful
273 virtual bool setIPv6Only(bool enable);
276 * Retrieves this socket's IPv6 Only flag.
278 * @returns true if this socket will ignore IPv4-compatible and IPv4-mapped
279 * addresses, false if it will accept them.
281 bool isIPv6Only() const;
284 * Sets this socket Broadcast flag.
286 * Datagram-oriented sockets cannot normally send packets to broadcast
287 * addresses, nor will they receive packets that were sent to a broadcast
288 * address. To do so, you need to enable the Broadcast flag.
290 * This option has no effect on stream-oriented sockets.
292 * @returns true if setting this flag was successful.
294 virtual bool setBroadcast(bool enable);
297 * Retrieves this socket's Broadcast flag.
299 * @returns true if this socket can send and receive broadcast packets,
300 * false if it can't.
302 bool broadcast() const;
305 * Sets this socket's NoDelay flag.
307 * Stream-oriented protocols, like TCP, have an internal algorithm
308 * (called Nagle's algorithm) that collects data in a buffer so that
309 * the transmission doesn't occur after every single write operation.
310 * The side-effect is that the transmission of short messages is
311 * delayed.
313 * Setting NoDelay to 'true' will disable this algorithm.
315 * @returns true if setting this flag was successful.
317 virtual bool setNoDelay(bool enable);
320 * Retrieves this socket's NoDelay flag.
322 * @returns true if this socket's Nagle algorithm is disabled.
324 bool noDelay() const;
327 * Retrieves the socket implementation used on this socket.
329 * This function creates the device if none has been set
330 * using the default factory.
332 KSocketDevice* socketDevice() const;
335 * Sets the socket implementation to be used on this socket.
337 * Note: it is an error to set this if the socket device has
338 * already been set once.
340 * This function is provided virtual so that derived classes can catch
341 * the setting of a device and properly set their own states and internal
342 * variables. The parent class must be called.
344 * This function is called by socketDevice() above when the socket is
345 * first created.
347 virtual void setSocketDevice(KSocketDevice* device);
350 * Sets the internally requested capabilities for a socket device.
352 * Most socket classes can use any back-end implementation. However, a few
353 * may require specific capabilities not provided in the default
354 * implementation. By using this function, derived classes can request
355 * that a backend with those capabilities be created when necessary.
357 * For the possible flags, see KSocketDevice::Capabilities. However, note
358 * that only the Can* flags make sense in this context.
360 * @note Since socketDevice must always return a valid backend object, it
361 * is is possible that the created device does not conform to all
362 * requirements requested. Implementations sensitive to this fact
363 * should test the object returned by socketDevice() (through
364 * KSocketDevice::capabilities(), for instance) the availability.
366 * @param add mask of KSocketDevice::Capabilities to add
367 * @param remove mask of bits to remove from the requirements
368 * @return the current mask of requested capabilities
370 int setRequestedCapabilities(int add, int remove = 0);
372 protected:
374 * Returns true if the socket device has been initialised in this
375 * object, either by calling socketDevice() or setSocketDevice()
377 bool hasDevice() const;
380 * Sets the socket's error code.
382 * @param error the error code
384 void setError(SocketError error);
387 * Resets the socket error code and the I/O Device's status.
389 void resetError();
391 public:
393 * Retrieves the socket error code.
394 * @sa errorString
396 SocketError error() const;
399 * Returns the error string corresponding to this error condition.
401 QString errorString() const;
404 * Returns the internal mutex for this class.
406 * Note on multithreaded use of sockets:
407 * the socket classes are thread-safe by design, but you should be aware of
408 * problems regarding socket creation, connection and destruction in
409 * multi-threaded programs. The classes are guaranteed to work while
410 * the socket exists, but it's not wise to call connect in multiple
411 * threads.
413 * Also, this mutex must be unlocked before the object is destroyed, which
414 * means you cannot use it to guard against other threads accessing the object
415 * while destroying it. You must ensure there are no further references to this
416 * object when deleting it.
418 QMutex* mutex() const;
420 public:
422 * Returns the string describing the given error code, i18n'ed.
424 * @param code the error code
426 static QString errorString(SocketError code);
429 * Returns true if the given error code is a fatal one, false
430 * otherwise. The parameter here is of type int so that
431 * casting isn't necessary when using the parameter to signal
432 * QClientSocketBase::gotError.
434 * @param code the code to test
436 static bool isFatalError(int code);
438 private:
439 /// @internal
440 /// called by KSocketDevice
441 void unsetSocketDevice();
443 KSocketBase(const KSocketBase&);
444 KSocketBase& operator =(const KSocketBase&);
446 KSocketBasePrivate* const d;
448 friend class KSocketDevice;
452 * @class KActiveSocketBase k3socketbase.h k3socketbase.h
453 * @brief Abstract class for active sockets
455 * This class provides the standard interfaces for active sockets, i.e.,
456 * sockets that are used to connect to external addresses.
458 * @author Thiago Macieira <thiago@kde.org>
459 * @deprecated Use KSocketFactory or KLocalSocket instead
461 class KDECORE_EXPORT KActiveSocketBase: public QIODevice, virtual public KSocketBase
463 Q_OBJECT
464 public:
466 * Constructor.
468 KActiveSocketBase(QObject* parent);
471 * Destructor.
473 virtual ~KActiveSocketBase();
476 * Unshadow errorString from QIODevice
478 QString errorString() const;
481 * @reimp
483 virtual void setSocketDevice(KSocketDevice* device);
486 * Reimplemented from QIODevice.
488 virtual bool open(OpenMode mode);
491 * Binds this socket to the given address.
493 * The socket will be constructed with the address family,
494 * socket type and protocol as those given in the
495 * @p address object.
497 * @param address the address to bind to
498 * @returns true if the binding was successful, false otherwise
500 virtual bool bind(const KResolverEntry& address) = 0;
503 * Connect to a remote host.
505 * This will make this socket try to connect to the remote host.
506 * If the socket is not yet created, it will be created using the
507 * address family, socket type and protocol specified in the
508 * @p address object.
510 * If this function returns with error InProgress, calling it
511 * again with the same address after a time will cause it to test
512 * if the connection has succeeded in the mean time.
514 * @param address the address to connect to
515 * @param mode mode for connection, from QIODevice
517 * @returns true if the connection was successful or has been successfully
518 * queued; false if an error occurred.
520 virtual bool connect(const KResolverEntry& address,
521 OpenMode mode = ReadWrite) = 0;
524 * Disconnects this socket from a connection, if possible.
526 * If this socket was connected to an endpoint, the connection
527 * is severed, but the socket is not closed. If the socket wasn't
528 * connected, this function does nothing.
530 * If the socket hadn't yet been created, this function does nothing
531 * either.
533 * Not all socket types can disconnect. Most notably, only
534 * connectionless datagram protocols such as UDP support this operation.
536 * @return true if the socket is now disconnected or false on error.
538 virtual bool disconnect() = 0;
541 * Sockets are sequential
543 virtual bool isSequential() const;
546 * This call is not supported on sockets. Reimplemented from QIODevice.
547 * This will always return 0.
549 virtual qint64 size() const;
552 * This call is not supported on sockets. Reimplemented from QIODevice.
553 * This will always return 0.
555 virtual qint64 pos() const;
558 * This call is not supported on sockets. Reimplemented from QIODevice.
559 * This will always return false.
561 virtual bool seek(qint64);
564 * This call is not supported on sockets. Reimplemented from QIODevice.
565 * This will always return true.
567 virtual bool atEnd() const;
570 * Reads data from the socket.
572 * Reimplemented from QIODevice. See QIODevice::read for
573 * more information.
575 qint64 read(char *data, qint64 maxlen);
578 * Reads data from the socket.
580 * Reimplemented from QIODevice. See QIODevice::read for
581 * more information.
583 QByteArray read(qint64 len);
585 /** @overload
586 * Receives data and the source address.
588 * This call will read data in the socket and will also
589 * place the sender's address in @p from object.
591 * @param data where to write the read data to
592 * @param maxlen the maximum number of bytes to read
593 * @param from the address of the sender will be stored here
594 * @returns the actual number of bytes read
596 qint64 read(char *data, qint64 maxlen, KSocketAddress& from);
599 * Peeks the data in the socket and the source address.
601 * This call will allow you to peek the data to be received without actually
602 * receiving it -- that is, it will be available for further peekings and
603 * for the next read call.
605 * @param data where to write the peeked data to
606 * @param maxlen the maximum number of bytes to peek
607 * @returns the actual number of bytes copied into @p data
609 qint64 peek(char *data, qint64 maxlen);
612 * @overload
613 * Peeks the data in the socket and the source address.
615 * This call will allow you to peek the data to be received without actually
616 * receiving it -- that is, it will be available for further peekings and
617 * for the next read call.
619 * @param data where to write the peeked data to
620 * @param maxlen the maximum number of bytes to peek
621 * @param from the address of the sender will be stored here
622 * @returns the actual number of bytes copied into @p data
624 qint64 peek(char *data, qint64 maxlen, KSocketAddress& from);
627 * Writes the given data to the socket.
629 * Reimplemented from QIODevice. See QIODevice::write for
630 * more information.
632 qint64 write(const char *data, qint64 len);
635 * Writes the given data to the socket.
637 * Reimplemented from QIODevice. See QIODevice::write for
638 * more information.
640 qint64 write(const QByteArray& data);
642 /** @overload
643 * Writes the given data to the destination address.
645 * Note that not all socket connections allow sending data to different
646 * addresses than the one the socket is connected to.
648 * @param data the data to write
649 * @param len the length of the data
650 * @param to the address to send to
651 * @returns the number of bytes actually sent
653 qint64 write(const char *data, qint64 len, const KSocketAddress& to);
656 * Waits up to @p msecs for more data to be available on this socket.
658 * If msecs is -1, this call will block indefinetely until more data
659 * is indeed available; if it's 0, this function returns immediately.
661 * If @p timeout is not NULL, this function will set it to indicate
662 * if a timeout occurred.
664 * @returns the number of bytes available
666 virtual qint64 waitForMore(int msecs, bool *timeout = 0L) = 0;
669 * This call is not supported on sockets. Reimplemented from QIODevice.
671 void ungetChar(char);
674 * Returns this socket's local address.
676 virtual KSocketAddress localAddress() const = 0;
679 * Return this socket's peer address, if we are connected.
680 * If the address cannot be retrieved, the returned object will contain
681 * an invalid address.
683 virtual KSocketAddress peerAddress() const = 0;
685 // FIXME KDE 4.0:
686 // enable this function
687 #if 0
689 * Returns this socket's externally-visible address, if known.
691 virtual KSocketAddress externalAddress() const = 0;
692 #endif
694 protected:
696 * Reads data from the socket.
698 * Reimplemented from QIODevice. See QIODevice::readData for
699 * more information.
701 virtual qint64 readData(char *data, qint64 len);
703 /** @overload
704 * Receives data and the source address.
706 * This call will read data in the socket and will also
707 * place the sender's address in @p from object.
709 * @param data where to write the read data to
710 * @param maxlen the maximum number of bytes to read
711 * @param from the address of the sender will be stored here
712 * @returns the actual number of bytes read
714 virtual qint64 readData(char *data, qint64 maxlen, KSocketAddress* from) = 0;
717 * Peeks the data in the socket and the source address.
719 * This call will allow you to peek the data to be received without actually
720 * receiving it -- that is, it will be available for further peekings and
721 * for the next read call.
723 * @param data where to write the peeked data to
724 * @param maxlen the maximum number of bytes to peek
725 * @param from the address of the sender will be stored here
726 * @returns the actual number of bytes copied into @p data
728 virtual qint64 peekData(char *data, qint64 maxlen, KSocketAddress* from) = 0;
731 * Writes the given data to the socket.
733 * Reimplemented from QIODevice. See QIODevice::writeData for
734 * more information.
736 virtual qint64 writeData(const char *data, qint64 len);
738 /** @overload
739 * Writes the given data to the destination address.
741 * Note that not all socket connections allow sending data to different
742 * addresses than the one the socket is connected to.
744 * @param data the data to write
745 * @param len the length of the data
746 * @param to the address to send to
747 * @returns the number of bytes actually sent
749 virtual qint64 writeData(const char *data, qint64 len, const KSocketAddress* to) = 0;
752 * Sets the socket's error code.
754 * @param error the error code
756 void setError(SocketError error);
759 * Resets the socket error code and the I/O Device's status.
761 void resetError();
765 * @class KPassiveSocketBase k3socketbase.h k3socketbase.h
766 * @brief Abstract base class for passive sockets.
768 * This socket provides the initial functionality for passive sockets,
769 * i.e., sockets that accept incoming connections.
771 * @author Thiago Macieira <thiago@kde.org>
772 * @deprecated Use KSocketFactory or KLocalSocket instead
774 class KDECORE_EXPORT KPassiveSocketBase: virtual public KSocketBase
776 public:
778 * Constructor
780 KPassiveSocketBase();
783 * Destructor
785 virtual ~KPassiveSocketBase();
788 * Binds this socket to the given address.
790 * The socket will be constructed with the address family,
791 * socket type and protocol as those given in the
792 * @p address object.
794 * @param address the address to bind to
795 * @returns true if the binding was successful, false otherwise
797 virtual bool bind(const KResolverEntry& address) = 0;
800 * Puts this socket into listening mode.
802 * Placing a socket in listening mode means that it will
803 * be allowed to receive incoming connections from
804 * remote hosts.
806 * Note that some socket types or protocols cannot be
807 * put in listening mode.
809 * @param backlog the number of accepted connections to
810 * hold before starting to refuse
811 * @returns true if the socket is now in listening mode
813 virtual bool listen(int backlog) = 0;
816 * Closes this socket. All resources used are freed. Note that closing
817 * a passive socket does not close the connections accepted with it.
819 virtual void close() = 0;
822 * Accepts a new incoming connection.
824 * If this socket was in listening mode, you can call this
825 * function to accept an incoming connection.
827 * If this function cannot accept a new connection (either
828 * because it is not listening for one or because the operation
829 * would block), it will return NULL.
831 * Also note that descended classes will override this function
832 * to return specialized socket classes.
834 virtual KActiveSocketBase* accept() = 0;
837 * Returns this socket's local address.
839 virtual KSocketAddress localAddress() const = 0;
842 * Returns this socket's externally-visible address if known.
844 virtual KSocketAddress externalAddress() const = 0;
846 private:
847 KPassiveSocketBase(const KPassiveSocketBase&);
848 KPassiveSocketBase& operator = (const KPassiveSocketBase&);
851 } // namespace KNetwork
853 #endif