File indexing completed on 2024-09-29 09:25:05

0001 /*  -*- C++ -*-
0002  *  Copyright (C) 2003,2005 Thiago Macieira <thiago@kde.org>
0003  *
0004  *
0005  *  Permission is hereby granted, free of charge, to any person obtaining
0006  *  a copy of this software and associated documentation files (the
0007  *  "Software"), to deal in the Software without restriction, including
0008  *  without limitation the rights to use, copy, modify, merge, publish,
0009  *  distribute, sublicense, and/or sell copies of the Software, and to
0010  *  permit persons to whom the Software is furnished to do so, subject to
0011  *  the following conditions:
0012  *
0013  *  The above copyright notice and this permission notice shall be included
0014  *  in all copies or substantial portions of the Software.
0015  *
0016  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
0017  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
0018  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
0019  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
0020  *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
0021  *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
0022  *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0023  */
0024 
0025 #ifndef KCLIENTSOCKETBASE_H
0026 #define KCLIENTSOCKETBASE_H
0027 
0028 #include <QObject>
0029 #include <QString>
0030 
0031 #include <kdelibs4support_export.h>
0032 #include "k3socketbase.h"
0033 #include "k3resolver.h"
0034 
0035 namespace KNetwork
0036 {
0037 
0038 class KClientSocketBasePrivate;
0039 /** @class KClientSocketBase k3clientsocketbase.h k3clientsocketbase.h
0040  *  @brief Abstract client socket class.
0041  *
0042  * This class provides the base functionality for client sockets,
0043  * such as, and especially, name resolution and signals.
0044  *
0045  * @note This class is abstract. If you're looking for a normal,
0046  *       client socket class, see KStreamSocket and KBufferedSocket
0047  *
0048  * @author Thiago Macieira <thiago@kde.org>
0049  * @deprecated Use KSocketFactory or KLocalSocket instead
0050  */
0051 class KDELIBS4SUPPORT_DEPRECATED_EXPORT KClientSocketBase : public KActiveSocketBase
0052 {
0053     Q_OBJECT
0054 
0055 public:
0056     /**
0057      * Socket states.
0058      *
0059      * These are the possible states for a KClientSocketBase:
0060      * - Idle: socket is not connected
0061      * - HostLookup: socket is doing host lookup prior to connecting
0062      * - HostFound: name lookup is complete
0063      * - Bound: the socket is locally bound
0064      * - Connecting: socket is attempting connection
0065      * - Open: socket is open
0066      * - Connected (=Open): socket is connected
0067      * - Connection (=Open): yet another name for a connected socket
0068      * - Closing: socket is shutting down
0069      *
0070      * Whenever the socket state changes, the stateChanged(int) signal
0071      * will be emitted.
0072      */
0073     enum SocketState {
0074         Idle,
0075         HostLookup,
0076         HostFound,
0077         Bound,
0078         Connecting,
0079         Open,
0080         Closing,
0081 
0082         Unconnected = Bound,
0083         Connected = Open,
0084         Connection = Open
0085     };
0086 
0087 public:
0088     /**
0089      * Default constructor.
0090      *
0091      * @param parent  the parent QObject object
0092      */
0093     KClientSocketBase(QObject *parent);
0094 
0095     /**
0096      * Destructor.
0097      */
0098     ~KClientSocketBase() override;
0099 
0100     /**
0101      * Returns the current state for this socket.
0102      * @see SocketState
0103      */
0104     SocketState state() const;
0105 
0106 protected:
0107     /**
0108      * Sets the socket options. Reimplemented from KSocketBase.
0109      */
0110     bool setSocketOptions(int opts) override;
0111 
0112 public:
0113     /**
0114      * Returns the internal KResolver object used for
0115      * looking up the peer host name and service.
0116      *
0117      * This can be used to set extra options to the
0118      * lookup process other than the default values, as well
0119      * as obtaining the error codes in case of lookup failure.
0120      */
0121     KResolver &peerResolver() const;
0122 
0123     /**
0124      * Returns the internal list of resolved results for the peer address.
0125      */
0126     const KResolverResults &peerResults() const;
0127 
0128     /**
0129      * Returns the internal KResolver object used for
0130      * looking up the local host name and service.
0131      *
0132      * This can be used to set extra options to the
0133      * lookup process other than the default values, as well
0134      * as obtaining the error codes in case of lookup failure.
0135      */
0136     KResolver &localResolver() const;
0137 
0138     /**
0139      * Returns the internal list of resolved results for the local address.
0140      */
0141     const KResolverResults &localResults() const;
0142 
0143     /**
0144      * Enables or disables name resolution. If this flag is set to true,
0145      * bind() and connect() operations will trigger name lookup
0146      * operations (i.e., converting a hostname into its binary form).
0147      * If the flag is set to false, those operations will instead
0148      * try to convert a string representation of an address without
0149      * attempting name resolution.
0150      *
0151      * This is useful, for instance, when IP addresses are in
0152      * their string representation (such as "1.2.3.4") or come
0153      * from other sources like KSocketAddress.
0154      *
0155      * @param enable  whether to enable
0156      */
0157     void setResolutionEnabled(bool enable);
0158 
0159     /**
0160      * Sets the allowed families for the resolutions.
0161      *
0162      * @param families        the families that we want/accept
0163      * @see KResolver::SocketFamilies for possible values
0164      */
0165     void setFamily(int families);
0166 
0167     /**
0168      * Starts the lookup for peer and local hostnames as
0169      * well as their services.
0170      *
0171      * If the blocking mode for this object is on, this function will
0172      * wait for the lookup results to be available (by calling the
0173      * KResolver::wait() method on the resolver objects).
0174      *
0175      * When the lookup is done, the signal hostFound() will be
0176      * emitted (only once, even if we're doing a double lookup).
0177      * If the lookup failed (for any of the two lookups) the
0178      * gotError() signal will be emitted with the appropriate
0179      * error condition (see KSocketBase::SocketError).
0180      *
0181      * This function returns true on success and false on error. Note that
0182      * this is not the lookup result!
0183      */
0184     virtual bool lookup();
0185 
0186     /**
0187      * Binds this socket to the given nodename and service,
0188      * or use the default ones if none are given.
0189      *
0190      * Upon successful binding, the bound() signal will be
0191      * emitted. If an error is found, the gotError()
0192      * signal will be emitted.
0193      *
0194      * @note Due to the internals of the name lookup and binding
0195      *       mechanism, some (if not most) implementations of this function
0196      *       do not actually bind the socket until the connection
0197      *       is requested (see connect()). They only set the values
0198      *       for future reference.
0199      *
0200      * This function returns true on success.
0201      *
0202      * @param node    the nodename
0203      * @param service the service
0204      */
0205     virtual bool bind(const QString &node = QString(),
0206                       const QString &service = QString()) = 0;
0207 
0208     /**
0209      * Reimplemented from KSocketBase. Connect this socket to this
0210      * specific address.
0211      *
0212      * Unlike bind(const QString&, const QString&) above, this function
0213      * really does bind the socket. No lookup is performed. The bound()
0214      * signal will be emitted.
0215      */
0216     bool bind(const KResolverEntry &address) override;
0217 
0218     /**
0219      * Attempts to connect to a given hostname and service,
0220      * or use the default ones if none are given. If a connection attempt
0221      * is already in progress, check on its state and set the error status
0222      * (NoError or InProgress).
0223      *
0224      * If the blocking mode for this object is on, this function will only
0225      * return when all the resolved peer addresses have been tried or when
0226      * a connection is established.
0227      *
0228      * Upon successfully connecting, the connected() signal
0229      * will be emitted. If an error is found, the gotError()
0230      * signal will be emitted.
0231      *
0232      * @par Note for derived classes:
0233      *      Derived classes must implement this function. The implementation
0234      *      will set the parameters for the lookup (using the peer KResolver
0235      *      object) and call lookup() to start it.
0236      *
0237      * @par
0238      *      The implementation should use the hostFound()
0239      *      signal to be notified of the completion of the lookup process and
0240      *      then proceed to start the connection itself. Care should be taken
0241      *      regarding the value of blocking() flag.
0242      *
0243      * @param node    the nodename (host to connect to)
0244      * @param service the service to connect to
0245      * @param mode        the mode to open the connection in
0246      */
0247     virtual bool connect(const QString &node = QString(),
0248                          const QString &service = QString(),
0249                          OpenMode mode = ReadWrite) = 0;
0250 
0251     /**
0252      * @overload
0253      * Reimplemented from KSocketBase.
0254      */
0255     bool connect(const KResolverEntry &address,
0256                          OpenMode mode = ReadWrite) override;
0257 
0258     /**
0259      * Disconnects the socket.
0260      * Note that not all socket types can disconnect.
0261      */
0262     bool disconnect() override;
0263 
0264     /**
0265      * Opens the socket. Reimplemented from QIODevice.
0266      *
0267      * You should not call this function; instead, use connect()
0268      */
0269     bool open(OpenMode mode) override;
0270 
0271     /**
0272      * Closes the socket. Reimplemented from QIODevice.
0273      *
0274      * The closing of the socket causes the emission of the
0275      * signal closed().
0276      */
0277     void close() override;
0278 
0279     /**
0280      * This call is not supported on unbuffered sockets.
0281      * Reimplemented from QIODevice.
0282      */
0283     virtual bool flush();
0284 
0285     /**
0286      * Returns the number of bytes available on this socket.
0287      * Reimplemented from KSocketBase.
0288      */
0289     qint64 bytesAvailable() const override;
0290 
0291     /**
0292      * Waits for more data. Reimplemented from KSocketBase.
0293      */
0294     qint64 waitForMore(int msecs, bool *timeout = nullptr) override;
0295 
0296     /**
0297      * Returns the local socket address. Reimplemented from KSocketBase.
0298      */
0299     KSocketAddress localAddress() const override;
0300 
0301     /**
0302      * Returns the peer socket address. Reimplemented from KSocketBase.
0303      */
0304     KSocketAddress peerAddress() const override;
0305 
0306     /**
0307      * Returns true if the readyRead signal is set to be emitted.
0308      */
0309     bool emitsReadyRead() const;
0310 
0311     /**
0312      * Enables the emission of the readyRead signal.
0313      * By default, this signal is enabled.
0314      *
0315      * @param enable  whether to enable the signal
0316      */
0317     virtual void enableRead(bool enable);
0318 
0319     /**
0320      * Returns true if the readyWrite signal is set to be emitted.
0321      */
0322     bool emitsReadyWrite() const;
0323 
0324     /**
0325      * Enables the emission of the readyWrite signal.
0326      * By default, this signal is disabled.
0327      *
0328      * @param enable  whether to enable the signal
0329      */
0330     virtual void enableWrite(bool enable);
0331 
0332 protected Q_SLOTS:
0333     // protected slots
0334 
0335     /**
0336      * This slot is connected to the read notifier's signal meaning
0337      * the socket can read more data.
0338      *
0339      * The default implementation only emits the readyRead signal.
0340      *
0341      * Override if your class requires processing of incoming
0342      * data.
0343      */
0344     virtual void slotReadActivity();
0345 
0346     /**
0347      * This slot is connected to the write notifier's signal
0348      * meaning the socket can write more data.
0349      *
0350      * The default implementation only emits the readyWrite signal.
0351      *
0352      * Override if your class writes data from another source
0353      * (like a buffer).
0354      */
0355     virtual void slotWriteActivity();
0356 
0357 private Q_SLOTS:
0358     void lookupFinishedSlot();
0359 
0360 Q_SIGNALS:
0361     /**
0362      * This signal is emitted whenever the socket state changes.
0363      *
0364      * Note: do not delete this object inside the slot called by this
0365      * signal.
0366      *
0367      * @param newstate    the new state of the socket object
0368      */
0369     void stateChanged(int newstate);
0370 
0371     /**
0372      * This signal is emitted when this object finds an error.
0373      * The @p code parameter contains the error code that can
0374      * also be found by calling error().
0375      */
0376     void gotError(int code);
0377 
0378     /**
0379      * This signal is emitted when the lookup is successfully completed.
0380      */
0381     void hostFound();
0382 
0383     /**
0384      * This signal is emitted when the socket successfully binds
0385      * to an address.
0386      *
0387      * @param local   the local address we bound to
0388      */
0389     void bound(const KNetwork::KResolverEntry &local);
0390 
0391     /**
0392      * This signal is emitted when the socket is about to connect
0393      * to an address (but before doing so).
0394      *
0395      * The @p skip parameter can be used to make the loop skip this address.
0396      * Its value is initially false: change it to true if you want to
0397      * skip the current address (as given by @p remote).
0398      *
0399      * This function is also useful if one wants to reset the timeout.
0400      *
0401      * @param remote  the address we're about to connect to
0402      * @param skip    set to true if you want to skip this address
0403      * @note if the connection is successful, the connected() signal will be
0404      *       emitted.
0405      */
0406     void aboutToConnect(const KNetwork::KResolverEntry &remote, bool &skip);
0407 
0408     /**
0409      * This socket is emitted when the socket successfully connects
0410      * to a remote address.
0411      *
0412      * @param remote  the remote address we did connect to
0413      */
0414     void connected(const KNetwork::KResolverEntry &remote);
0415 
0416     /**
0417      * This signal is emitted when the socket completes the
0418      * closing/shut down process.
0419      */
0420     void closed();
0421 
0422 #if 0
0423     // QIODevice already has this
0424     /**
0425      * This signal is emitted whenever the socket is ready for
0426      * reading -- i.e., there is data to be read in the buffers.
0427      * The subsequent read operation is guaranteed to be non-blocking.
0428      *
0429      * You can toggle the emission of this signal with the enableRead()
0430      * function. This signal is by default enabled.
0431      */
0432     void readyRead();
0433 #endif
0434 
0435     /**
0436      * This signal is emitted whenever the socket is ready for
0437      * writing -- i.e., whenever there's space available in the buffers
0438      * to receive more data. The subsequent write operation is
0439      * guaranteed to be non-blocking.
0440      *
0441      * You can toggle the emission of this signal with the enableWrite()
0442      * function. This signal is by default disabled. You will
0443      * want to disable this signal after the first reception, since
0444      * it'll probably fire at every event loop.
0445      */
0446     void readyWrite();
0447 
0448 protected:
0449     /**
0450      * Reads data from a socket. Reimplemented from KSocketBase.
0451      */
0452     qint64 readData(char *data, qint64 maxlen, KSocketAddress *from) override;
0453 
0454     /**
0455      * Peeks data from the socket. Reimplemented from KSocketBase.
0456      */
0457     qint64 peekData(char *data, qint64 maxlen, KSocketAddress *from) override;
0458 
0459     /**
0460      * @overload
0461      * Writes data to the socket. Reimplemented from KSocketBase.
0462      */
0463     qint64 writeData(const char *data, qint64 len, const KSocketAddress *to) override;
0464 
0465     /**
0466      * Sets the socket state to @p state. This function does not
0467      * emit the stateChanged() signal.
0468      */
0469     void setState(SocketState state);
0470 
0471     /**
0472      * This function is called by setState() whenever the state
0473      * changes. You should override it if you need to specify any
0474      * actions to be done when the state changes.
0475      *
0476      * The default implementation acts for these states only:
0477      *  - Connected: it sets up the socket notifiers to fire readyRead and
0478      *               readyWrite signals.
0479      */
0480     virtual void stateChanging(SocketState newState);
0481 
0482     /**
0483      * Convenience function to set this object's error code to match
0484      * that of the socket device.
0485      */
0486     void copyError();
0487 
0488 private:
0489     KClientSocketBase(const KClientSocketBase &);
0490     KClientSocketBase &operator=(const KClientSocketBase &);
0491 
0492     KClientSocketBasePrivate *const d;
0493 };
0494 
0495 }               // namespace KNetwork
0496 
0497 #endif