Line data Source code
1 : // Copyright (c) 2012-2019 Made to Order Software Corp. All Rights Reserved
2 : //
3 : // https://snapwebsites.org/project/eventdispatcher
4 : // contact@m2osw.com
5 : //
6 : // This program is free software; you can redistribute it and/or modify
7 : // it under the terms of the GNU General Public License as published by
8 : // the Free Software Foundation; either version 2 of the License, or
9 : // (at your option) any later version.
10 : //
11 : // This program is distributed in the hope that it will be useful,
12 : // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 : // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 : // GNU General Public License for more details.
15 : //
16 : // You should have received a copy of the GNU General Public License
17 : // along with this program; if not, write to the Free Software
18 : // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 :
20 : /** \file
21 : * \brief Event dispatch class.
22 : *
23 : * Class used to handle events.
24 : */
25 :
26 : // to get the POLLRDHUP definition
27 : #ifndef _GNU_SOURCE
28 : #define _GNU_SOURCE
29 : #endif
30 :
31 :
32 : // self
33 : //
34 : #include "eventdispatcher/udp_server.h"
35 :
36 : #include "eventdispatcher/exception.h"
37 :
38 :
39 : // snapwebsites lib
40 : //
41 : #include <snaplogger/message.h>
42 :
43 :
44 : // C lib
45 : //
46 : #include <arpa/inet.h>
47 : #include <poll.h>
48 : #include <string.h>
49 :
50 :
51 : // last include
52 : //
53 : #include <snapdev/poison.h>
54 :
55 :
56 :
57 :
58 : namespace ed
59 : {
60 :
61 :
62 :
63 : /** \brief Initialize a UDP server object.
64 : *
65 : * This function initializes a UDP server object making it ready to
66 : * receive messages.
67 : *
68 : * The server address and port are specified in the constructor so
69 : * if you need to receive messages from several different addresses
70 : * and/or port, you'll have to create a server for each.
71 : *
72 : * The address is a string and it can represent an IPv4 or IPv6
73 : * address.
74 : *
75 : * Note that this function calls bind() to listen to the socket
76 : * at the specified address. To accept data on different UDP addresses
77 : * and ports, multiple UDP servers must be created.
78 : *
79 : * \note
80 : * The socket is open in this process. If you fork() or exec() then the
81 : * socket will be closed by the operating system.
82 : *
83 : * \warning
84 : * We only make use of the first address found by getaddrinfo(). All
85 : * the other addresses are ignored.
86 : *
87 : * \warning
88 : * Remember that the multicast feature under Linux is shared by all
89 : * processes running on that server. Any one process can listen for
90 : * any and all multicast messages from any other process. Our
91 : * implementation limits the multicast from a specific IP. However.
92 : * other processes can also receive you packets and there is nothing
93 : * you can do to prevent that.
94 : *
95 : * \exception udp_client_server_runtime_error
96 : * The udp_client_server_runtime_error exception is raised when the address
97 : * and port combinaison cannot be resolved or if the socket cannot be
98 : * opened.
99 : *
100 : * \param[in] addr The address we receive on.
101 : * \param[in] port The port we receive from.
102 : * \param[in] family The family used to search for 'addr'.
103 : * \param[in] multicast_addr A multicast address.
104 : */
105 0 : udp_server::udp_server(std::string const & addr, int port, int family, std::string const * multicast_addr)
106 0 : : udp_base(addr, port, family)
107 : {
108 : // bind to the very first address
109 : //
110 0 : int r(bind(f_socket.get(), f_addrinfo->ai_addr, f_addrinfo->ai_addrlen));
111 0 : if(r != 0)
112 : {
113 0 : int const e(errno);
114 :
115 : // reverse the address from the f_addrinfo so we know exactly
116 : // which one was picked
117 : //
118 : char addr_buf[256];
119 0 : switch(f_addrinfo->ai_family)
120 : {
121 : case AF_INET:
122 0 : inet_ntop(AF_INET
123 0 : , &reinterpret_cast<struct sockaddr_in *>(f_addrinfo->ai_addr)->sin_addr
124 : , addr_buf
125 0 : , sizeof(addr_buf));
126 0 : break;
127 :
128 : case AF_INET6:
129 0 : inet_ntop(AF_INET6
130 0 : , &reinterpret_cast<struct sockaddr_in6 *>(f_addrinfo->ai_addr)->sin6_addr
131 : , addr_buf
132 0 : , sizeof(addr_buf));
133 0 : break;
134 :
135 : default:
136 0 : strncpy(addr_buf, "Unknown Adress Family", sizeof(addr_buf));
137 0 : break;
138 :
139 : }
140 :
141 : SNAP_LOG_ERROR
142 0 : << "the bind() function failed with errno: "
143 0 : << e
144 0 : << " ("
145 0 : << strerror(e)
146 0 : << "); address length "
147 0 : << f_addrinfo->ai_addrlen
148 0 : << " and address is \""
149 0 : << addr_buf
150 0 : << "\"";
151 0 : throw event_dispatcher_runtime_error("could not bind UDP socket to \"" + f_addr + ":" + std::to_string(port) + "\"");
152 : }
153 :
154 : // are we creating a server to listen to multicast packets?
155 : //
156 0 : if(multicast_addr != nullptr)
157 : {
158 : struct ip_mreqn mreq;
159 :
160 0 : std::stringstream decimal_port;
161 0 : decimal_port << f_port;
162 0 : std::string port_str(decimal_port.str());
163 :
164 0 : struct addrinfo hints = addrinfo();
165 0 : hints.ai_family = AF_UNSPEC;
166 0 : hints.ai_socktype = SOCK_DGRAM;
167 0 : hints.ai_protocol = IPPROTO_UDP;
168 :
169 : // we use the multicast address, but the same port as for
170 : // the other address
171 : //
172 0 : addrinfo * a(nullptr);
173 0 : r = getaddrinfo(multicast_addr->c_str(), port_str.c_str(), &hints, &a);
174 0 : if(r != 0 || a == nullptr)
175 : {
176 0 : throw event_dispatcher_runtime_error("invalid address or port for UDP socket: \"" + addr + ":" + port_str + "\"");
177 : }
178 :
179 : // both addresses must have the right size
180 : //
181 0 : if(a->ai_addrlen != sizeof(mreq.imr_multiaddr)
182 0 : || f_addrinfo->ai_addrlen != sizeof(mreq.imr_address))
183 : {
184 0 : throw event_dispatcher_runtime_error("invalid address type for UDP multicast: \"" + addr + ":" + port_str
185 0 : + "\" or \"" + *multicast_addr + ":" + port_str + "\"");
186 : }
187 :
188 0 : memcpy(&mreq.imr_multiaddr, a->ai_addr->sa_data, sizeof(mreq.imr_multiaddr));
189 0 : memcpy(&mreq.imr_address, f_addrinfo->ai_addr->sa_data, sizeof(mreq.imr_address));
190 0 : mreq.imr_ifindex = 0; // no specific interface
191 :
192 0 : r = setsockopt(f_socket.get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
193 0 : if(r < 0)
194 : {
195 0 : int const e(errno);
196 0 : throw event_dispatcher_runtime_error("IP_ADD_MEMBERSHIP failed for: \"" + addr + ":" + port_str
197 0 : + "\" or \"" + *multicast_addr + ":" + port_str + "\", "
198 0 : + std::to_string(e) + strerror(e));
199 : }
200 :
201 : // setup the multicast to 0 so we don't receive other's
202 : // messages; apparently the default would be 1
203 : //
204 0 : int multicast_all(0);
205 0 : r = setsockopt(f_socket.get(), IPPROTO_IP, IP_MULTICAST_ALL, &multicast_all, sizeof(multicast_all));
206 0 : if(r < 0)
207 : {
208 : // things should still work if the IP_MULTICAST_ALL is not
209 : // set as we want it
210 : //
211 0 : int const e(errno);
212 : SNAP_LOG_WARNING
213 0 : << "could not set IP_MULTICAST_ALL to zero, e = "
214 0 : << e
215 0 : << " -- "
216 0 : << strerror(e);
217 : }
218 : }
219 0 : }
220 :
221 :
222 : /** \brief Clean up the UDP server.
223 : *
224 : * This function frees the address info structures and close the socket.
225 : */
226 0 : udp_server::~udp_server()
227 : {
228 0 : }
229 :
230 :
231 : /** \brief Wait on a message.
232 : *
233 : * This function waits until a message is received on this UDP server.
234 : * There are no means to return from this function except by receiving
235 : * a message. Remember that UDP does not have a connect state so whether
236 : * another process quits does not change the status of this UDP server
237 : * and thus it continues to wait forever.
238 : *
239 : * Note that you may change the type of socket by making it non-blocking
240 : * (use the get_socket() to retrieve the socket identifier) in which
241 : * case this function will not block if no message is available. Instead
242 : * it returns immediately.
243 : *
244 : * \param[in] msg The buffer where the message is saved.
245 : * \param[in] max_size The maximum size the message (i.e. size of the \p msg buffer.)
246 : *
247 : * \return The number of bytes read or -1 if an error occurs.
248 : */
249 0 : int udp_server::recv(char * msg, size_t max_size)
250 : {
251 0 : return static_cast<int>(::recv(f_socket.get(), msg, max_size, 0));
252 : }
253 :
254 :
255 : /** \brief Wait for data to come in.
256 : *
257 : * This function waits for a given amount of time for data to come in. If
258 : * no data comes in after max_wait_ms, the function returns with -1 and
259 : * errno set to EAGAIN.
260 : *
261 : * The socket is expected to be a blocking socket (the default,) although
262 : * it is possible to setup the socket as non-blocking if necessary for
263 : * some other reason.
264 : *
265 : * This function blocks for a maximum amount of time as defined by
266 : * max_wait_ms. It may return sooner with an error or a message.
267 : *
268 : * \param[in] msg The buffer where the message will be saved.
269 : * \param[in] max_size The size of the \p msg buffer in bytes.
270 : * \param[in] max_wait_ms The maximum number of milliseconds to wait for a message.
271 : *
272 : * \return -1 if an error occurs or the function timed out, the number of bytes received otherwise.
273 : */
274 0 : int udp_server::timed_recv(char * msg, size_t const max_size, int const max_wait_ms)
275 : {
276 : pollfd fd;
277 0 : fd.events = POLLIN | POLLPRI | POLLRDHUP;
278 0 : fd.fd = f_socket.get();
279 0 : int const retval(poll(&fd, 1, max_wait_ms));
280 :
281 : // fd_set s;
282 : // FD_ZERO(&s);
283 : //#pragma GCC diagnostic push
284 : //#pragma GCC diagnostic ignored "-Wold-style-cast"
285 : // FD_SET(f_socket.get(), &s);
286 : //#pragma GCC diagnostic pop
287 : // struct timeval timeout;
288 : // timeout.tv_sec = max_wait_ms / 1000;
289 : // timeout.tv_usec = (max_wait_ms % 1000) * 1000;
290 : // int const retval(select(f_socket.get() + 1, &s, nullptr, &s, &timeout));
291 0 : if(retval == -1)
292 : {
293 : // poll() sets errno accordingly
294 0 : return -1;
295 : }
296 0 : if(retval > 0)
297 : {
298 : // our socket has data
299 0 : return static_cast<int>(::recv(f_socket.get(), msg, max_size, 0));
300 : }
301 :
302 : // our socket has no data
303 0 : errno = EAGAIN;
304 0 : return -1;
305 : }
306 :
307 :
308 : /** \brief Wait for data to come in, but return a std::string.
309 : *
310 : * This function waits for a given amount of time for data to come in. If
311 : * no data comes in after max_wait_ms, the function returns with -1 and
312 : * errno set to EAGAIN.
313 : *
314 : * The socket is expected to be a blocking socket (the default,) although
315 : * it is possible to setup the socket as non-blocking if necessary for
316 : * some other reason.
317 : *
318 : * This function blocks for a maximum amount of time as defined by
319 : * max_wait_ms. It may return sooner with an error or a message.
320 : *
321 : * \param[in] bufsize The maximum size of the returned string in bytes.
322 : * \param[in] max_wait_ms The maximum number of milliseconds to wait for a message.
323 : *
324 : * \return received string. nullptr if error.
325 : *
326 : * \sa timed_recv()
327 : */
328 0 : std::string udp_server::timed_recv( int const bufsize, int const max_wait_ms )
329 : {
330 0 : std::vector<char> buf;
331 0 : buf.resize( bufsize + 1, '\0' ); // +1 for ending \0
332 0 : int const r(timed_recv( &buf[0], bufsize, max_wait_ms ));
333 0 : if( r <= -1 )
334 : {
335 : // Timed out, so return empty string.
336 : // TBD: could std::string() smash errno?
337 : //
338 0 : return std::string();
339 : }
340 :
341 : // Resize the buffer, then convert to std string
342 : //
343 0 : buf.resize( r + 1, '\0' );
344 :
345 0 : std::string word;
346 0 : word.resize( r );
347 0 : std::copy( buf.begin(), buf.end(), word.begin() );
348 :
349 0 : return word;
350 : }
351 :
352 :
353 :
354 :
355 6 : } // namespace ed
356 : // vim: ts=4 sw=4 et
|