Update action points
[senf.git] / Socket / ClientSocketHandle.hh
1 // $Id$
2 //
3 // Copyright (C) 2006
4 // Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
5 // Kompetenzzentrum fuer Satelitenkommunikation (SatCom)
6 //     Stefan Bund <stefan.bund@fokus.fraunhofer.de>
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 /** \file
24     \brief ClientSocketHandle public header
25  */
26
27 #ifndef HH_ClientSocketHandle_
28 #define HH_ClientSocketHandle_ 1
29
30 // Custom includes
31 #include <boost/call_traits.hpp>
32 #include "SocketHandle.hh"
33
34 //#include "ClientSocketHandle.mpp"
35 ///////////////////////////////hh.p////////////////////////////////////////
36
37 namespace senf {
38
39     /// \addtogroup handle_group
40     /// @{
41
42     template <class Policy> class ServerSocketHandle;
43
44     /** \brief Generic SocketHandle with client interface
45
46         This class provides the client side policy interface of the socket
47         abstraction. ClientSocketHandle defines the complete policy interface. It does not implement
48         any functionality itself however. All calls are forward to the following policy classes:
49
50         <table class="senf">
51         <tr><th>ClientSocketHandle member</th> <th>Policy member</th></tr>
52         <tr><td>read()</td>       <td>ReadPolicy::read (\ref senf::ReadPolicyBase)</td></tr>
53         <tr><td>readfrom()</td>   <td>ReadPolicy::readfrom (\ref senf::ReadPolicyBase)</td></tr>
54         <tr><td>write()</td>      <td>WritePolicy::write (\ref senf::WritePolicyBase)</td></tr>
55         <tr><td>writeto()</td>    <td>WritePolicy::writeto (\ref senf::WritePolicyBase)</td></tr>
56         <tr><td>connect()</td>    <td>AddressingPolicy::connect (\ref senf::AddressingPolicyBase)</td></tr>
57         <tr><td>bind()</td>       <td>AddressingPolicy::bind (\ref senf::AddressingPolicyBase)</td></tr>
58         <tr><td>peer()</td>       <td>AddressingPolicy::peer (\ref senf::AddressingPolicyBase)</td></tr>
59         <tr><td>local()</td>      <td>AddressingPolicy::local (\ref senf::AddressingPolicyBase)</td></tr>
60         <tr><td>rcvbuf()</td>     <td>BufferingPolicy::sndbuf (\ref senf::BufferingPolicyBase)</td></tr>
61         <tr><td>sndbuf()</td>     <td>BufferingPolicy::rcvbuf (\ref senf::BufferingPolicyBase)</td></tr>
62         </table>
63
64         It is important to note, that not all members are always accessible. Which are depends on
65         the \c Policy template argument. If any of the policy axis is left unspecified the
66         corresponding members will not be callable (you will get a compile time error). Even if
67         every policy axis is defined, some members might (and will) not exist if they are
68         meaningless for the protocol of the socket. This depends on the exact policy.
69
70         To find out, which members are available, you have to check the documentation of the policy
71         classes. You can also find a summary of all members available in the leaf protocol class
72         documentation.
73
74         \todo Move all not template-parameter dependent code into a non-template base class
75
76         \idea Give SocketHandle (and therefore ClientSocketHandle and ServerSocketHandle) a \c
77         protocol() template member and an additional template arg \c Policies. This arg should be a
78         typelist of Poclicy classes which can be accessed. You use protocol<ProtocolClass>() to
79         access a protocol class. \c Policies can of course be underspecified or even empty.
80
81         \idea add more flexible read/write members for a) boost::arrays and arrays of other types b)
82         std::vector (which uses contiguous memory ..) c) other random-access containers (we should
83         use some configurable trait class to identify containers with contiguous storage). Probably
84         we should just use a generic Boost.Range interface. Here we again come to the point: make
85         all except the most basic members be non-member algorithms ? this would make the
86         configuration of such extenden members more flexible.
87
88         \see \ref policy_group \n
89              \ref protocol_group
90       */
91     template <class Policy>
92     class ClientSocketHandle
93         : public SocketHandle<Policy>
94     {
95     public:
96         ///////////////////////////////////////////////////////////////////////////
97         // Types
98
99         /// Address type from the addressing policy
100         typedef typename Policy::AddressingPolicy::Address Address;
101         /// 'Best' type for passing address as parameter
102         /** Depending on the type of \c Address, this will be either <tt>Address</tt> or <tt>Address
103             const &</tt>. See <a href="http://www.boost.org/libs/utility/call_traits.htm"
104             class="ext">call_traits documentation in the Boost.Utility library\endlink.</a>
105          */
106         typedef typename boost::call_traits<Address>::param_type AddressParam;
107         /// Corresponding server socket handle with the same policy
108         /** This class will probably only be usable, if the \c CommunicationPolicy is \c
109             ConnectedCommunicationPolicy and the \c AddressingPolicy is not \c
110             NoAddressingPolicy. */
111         typedef ServerSocketHandle<Policy> ServerSocketHandle;
112
113         ///////////////////////////////////////////////////////////////////////////
114         ///\name Structors and default members
115         ///@{
116
117         // no default constructor
118         // default copy constructor
119         // default copy assignment
120         // default destructor
121
122         // conversion constructors
123         template <class OtherPolicy>
124         ClientSocketHandle(ClientSocketHandle<OtherPolicy> other,
125                            typename SocketHandle<Policy>::template IsCompatible<OtherPolicy>::type * = 0);
126
127         template <class OtherPolicy>
128         typename SocketHandle<Policy>::template IsCompatible<OtherPolicy>::type const &
129         operator=(ClientSocketHandle<OtherPolicy> other);
130
131         ///@}
132         ///////////////////////////////////////////////////////////////////////////
133
134         ///////////////////////////////////////////////////////////////////////////
135         ///\name Reading and Writing
136         ///@{
137
138         /** \brief Read data from socket
139
140             If the sockets \c FramingPolicy is \c DatagramFramingPolicy, every read() command will
141             return a single datagram. If the sockets FramingPolicy is StreamFraming, the operation will
142             return as much data as possible from the socket buffer. However it cannot be guaranteed,
143             that the socket buffer will be empty after read() returns.
144
145             \attention If the space available for the data read is limited, the read will return no
146             more than that amount of data. For a datagram socket, a full datagram is still dequed
147             from the socket buffer, the remainder of the datagram will be lost.
148
149             There are three variants of read which differ in how they return the read string.
150
151             \throws senf::SystemException
152
153
154             This variant will read up to \c limit bytes from the
155             socket and return them as a \c std::string object.
156
157             On a blocking socket, this member will \e always return some data (as long as the socket
158             has not been closed at the other end) and will block, if no data is available now. If
159             you do not want to block, you \e must make the socket non-blocking (using
160             FileHandle::blocking()).
161
162             \param[in] limit Maximum number of bytes to read or 0 if unlimited.
163             \returns data read
164
165             \implementation The read() family of members will use standard POSIX \c read calls, not
166             \c recv.
167         */
168         std::string  read         (unsigned limit=0);
169         void         read         (std::string & buffer, unsigned limit=0);
170                                         ///< Read data into string buffer
171                                         /**< On a blocking socket, this member will \e always return
172                                            some data (as long as the socket has not been closed at
173                                            the other end) and will block, if no data is available
174                                            now. If you do not want to block, you \e must make the
175                                            socket non-blocking (using FileHandle::blocking()).
176                                            \param[out] buffer data read
177                                            \param[in] limit Maximum number of buytes to read or 0
178                                            if unlimited
179                                            \see \ref read() */
180         unsigned     read         (char * buffer, unsigned size);
181                                         ///< Read data into memory area
182                                         /**< This variant will read data into the memory area at \c
183                                            buffer of size \c size. This is the most performant
184                                            version of read().
185                                            \param[in] buffer address of buffer to store data at
186                                            \param[in] size size of memory buffer
187                                            \returns Number of bytes read
188                                            \see \ref read() */
189
190         /** \brief Read data from unconnected socket returning address
191
192             This member behaves like read() but should only be available, if the sockets \c
193             CommunicationPolicy is \c UnconnectedCommunicationPolicy and the \c AddressingPolicy is
194             not \c NoAddressingPolicy. The readfrom() family will in addition to the data return the
195             address of the sender.
196
197             \throws senf::SystemException
198
199             This variant will return the data read and the address as a std::pair.
200
201             \returns \c std::pair of data read (a string) and the peers address
202
203             \fixme Add \c limit argument
204
205             \implementation The readfrom() family of members will use \c recvfrom from the BSD
206             socket API.
207          */
208         std::pair<std::string, Address>
209                      readfrom     ();
210         void         readfrom     (std::string & buffer, Address & from);
211                                         ///< Read data into string buffer
212                                         /**< This variant will return the result in the locations
213                                            passed in
214                                            \param[out] buffer data read
215                                            \param[out] from peer address
216                                            \see \ref readfrom() */
217         unsigned     readfrom     (char * buffer, unsigned size, Address & from);
218                                         ///< Read data into memory byffer
219                                         /**< This variant will read data into the memory area at \c
220                                            buffer of size \c size. This is the most performant
221                                            version of readfrom().
222                                            \param[in] buffer address of buffer to store data at
223                                            \param[in] size size of bnuffer
224                                            \param[out] from peer address
225                                            \returns Number of bytes read
226                                            \see \ref readfrom() */
227
228
229         /** \brief Write data to socket
230
231             The write() family of members will write out the data to the socket.  If the sockets \c
232             FramingPolicy is \c DatagramFramingPolicy, every write() call will result in one
233             datagram.
234
235             A single write call might depending on the circumstances write only part of the data.
236
237             There are two variants of thie member
238
239             \throws senf::SystemException
240
241
242             This variant will write out the string \c data.
243
244             \param[in] data Data to write
245             \returns number of bytes written
246             \implementation The write() family of members will use POSIX \c write calls, not \c
247                 send.
248          */
249         unsigned     write        (std::string const & data);
250         unsigned     write        (char const * buffer, unsigned size);
251                                         ///< Write data to socket from memory buffer
252                                         /**< \param[in] buffer address of buffer to write
253                                            \param[in] size amount of data to write
254                                            \returns Number of bytes written
255                                            \see \ref write() */
256
257         /** \brief Write data to unconnected socket
258
259             This member behaves like write() but should only be available, if the sockets \c
260             CommunicationPolicy is \c UnconnectedCommunicationPolicy and the \c AddressingPolicy is
261             not \c NoAddressingPolicy. The writeto() family of members takes the target address as
262             an additional argument.
263
264             There are two variants of this member.
265
266             \throw senf::SystemException
267
268
269             This variant will send the string \c data to the peer \c addr.
270
271             \param[in] addr Address of peer to send data to
272             \param[in] data data to send
273             \returns Number of bytes written
274          */
275         unsigned     writeto      (AddressParam addr, std::string const & data);
276         unsigned     writeto      (AddressParam addr, char const * buffer, unsigned size);
277                                         ///< Write data from memory buffer to unconnected socket
278                                         /**< \param[in] addr Address o fpeer to send data to
279                                            \param[in] buffer address of buffer to write
280                                            \param[in] size amount of data to write
281                                            \returns Number of bytes written
282                                            \see \ref writeto() */
283
284         ///////////////////////////////////////////////////////////////////////////
285         ///\name Addressing
286         ///@{
287
288         /** \brief Connect to remote peer
289
290             This member will establish a connection for addressable connection-oriented protocols
291             (that is, the CommunicationPolicy is ConnectedCommunicationPolicy and the
292             AddressingPolicy is not NoAddressingPolicy).
293
294             \param[in] addr Address to connect to
295
296             \throws senf::SystemException
297          */
298         void         connect      (AddressParam addr);
299
300         /** \brief Set local address
301
302             For addressable protocols (AddressingPolicy is not NoAddressingPolicy), bind() will set
303             the local address of the socket.
304
305             \param[in] addr Local socket address to asign
306
307             \throws senf::SystemException
308          */
309         void         bind         (AddressParam addr);
310
311         /** \brief Query remote address
312
313             This member will return the address of the communication partner in addressable
314             connection-oriented protocols (that is, the CommunicationPolicy is
315             ConnectedCommunicationPolicy and the AddressingPolicy is not NoAddressingPolicy).
316
317             There are two Variants of this member, one will return the address by value, the other
318             takes a reference argument to elide the copy operation.
319
320             \throws senf::SystemException
321          */
322         Address      peer         ();
323         void         peer         (Address & addr);
324                                         ///< Query remote address
325                                         /**< \see \ref peer() */
326
327         /** \brief Query local address
328
329             This member will return the address of the local socket in addressable protocols
330             (AddressingPolicy is not NoAddressingPolicy).
331
332             There are two Variants of this member, one will return the address by value, the other
333             takes a reference argument to elide the copy operation.
334
335             \throws senf::SystemException
336          */
337         Address      local        ();
338         void         local        (Address & addr);
339                                         ///< Query local address
340                                         /**< \see \ref local() */
341
342         ///@}
343
344         ///////////////////////////////////////////////////////////////////////////
345         ///\name Buffering
346         ///@{
347
348         unsigned     rcvbuf      ();    ///< Check size of receive buffer
349                                         /**< \returns size of receive buffer in bytes */
350         void         rcvbuf      (unsigned size);
351                                         ///< Set size of receive buffer
352                                         /**< \param[in] size size of receive buffer in bytes */
353
354         unsigned     sndbuf      ();    ///< Check size of send buffer
355                                         /**< \returns size of send buffer in bytes */
356         void         sndbuf      (unsigned size);
357                                         ///< Set size of send buffer
358                                         /**< \param[in] size size of send buffer in bytes */
359
360         ///@}
361
362         static ClientSocketHandle cast_static(FileHandle handle);
363         static ClientSocketHandle cast_dynamic(FileHandle handle);
364
365         // we need to override both since SocketHandle is *not* polymorphic
366         void state(SocketStateMap & map, unsigned lod=0);
367         std::string dumpState(unsigned lod=0);
368
369     protected:
370         ClientSocketHandle(FileHandle other, bool isChecked);
371         explicit ClientSocketHandle(std::auto_ptr<SocketProtocol> protocol,
372                                     int fd = -1);
373
374     private:
375         unsigned available();
376
377         friend class senf::ServerSocketHandle<Policy>;
378     };
379
380     /// @}
381 }
382
383 ///////////////////////////////hh.e////////////////////////////////////////
384 //#include "ClientSocketHandle.cci"
385 #include "ClientSocketHandle.ct"
386 #include "ClientSocketHandle.cti"
387 #endif
388
389 \f
390 // Local Variables:
391 // mode: c++
392 // fill-column: 100
393 // c-file-style: "senf"
394 // indent-tabs-mode: nil
395 // ispell-local-dictionary: "american"
396 // End: