Line data Source code
1 : // Copyright (c) 2012-2022 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 along
17 : // with this program; if not, write to the Free Software Foundation, Inc.,
18 : // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 :
20 : /** \file
21 : * \brief Implementation of the Snap Communicator class.
22 : *
23 : * This class wraps the C poll() interface in a C++ object with many types
24 : * of objects:
25 : *
26 : * \li Server Connections; for software that want to offer a port to
27 : * which clients can connect to; the server will call accept()
28 : * once a new client connection is ready; this results in a
29 : * Server/Client connection object
30 : * \li Client Connections; for software that want to connect to
31 : * a server; these expect the IP address and port to connect to
32 : * \li Server/Client Connections; for the server when it accepts a new
33 : * connection; in this case the server gets a socket from accept()
34 : * and creates one of these objects to handle the connection
35 : *
36 : * Using the poll() function is the easiest and allows us to listen
37 : * on pretty much any number of sockets (on my server it is limited
38 : * at 16,768 and frankly over 1,000 we probably will start to have
39 : * real slowness issues on small VPN servers.)
40 : */
41 :
42 : // to get the POLLRDHUP definition
43 : #ifndef _GNU_SOURCE
44 : #define _GNU_SOURCE
45 : #endif
46 :
47 :
48 : // self
49 : //
50 : #include "eventdispatcher/local_stream_blocking_client_message_connection.h"
51 :
52 : #include "eventdispatcher/exception.h"
53 :
54 :
55 : // snaplogger lib
56 : //
57 : #include <snaplogger/message.h>
58 :
59 :
60 : // snapdev lib
61 : //
62 : #include <snapdev/not_used.h>
63 :
64 :
65 : // C++ lib
66 : //
67 : #include <cstring>
68 :
69 :
70 : // C lib
71 : //
72 : #include <poll.h>
73 : #include <sys/resource.h>
74 :
75 :
76 : // last include
77 : //
78 : #include <snapdev/poison.h>
79 :
80 :
81 :
82 : namespace ed
83 : {
84 :
85 :
86 :
87 : /** \brief Blocking client message connection.
88 : *
89 : * This object allows you to create a blocking, generally temporary
90 : * one message connection client. This is specifically used with
91 : * the snaplock daemon, but it can be used for other things too as
92 : * required.
93 : *
94 : * The connection is expected to be used as shown in the following
95 : * example which is how it is used to implement the LOCK through
96 : * our snaplock daemons.
97 : *
98 : * \code
99 : * class my_blocking_connection
100 : * : public ed::local_stream_blocking_client_message_connection
101 : * {
102 : * public:
103 : * my_blocking_connection(std::string const & addr, int port, mode_t mode)
104 : * : local_stream_blocking_client_message_connection(addr, port, mode)
105 : * {
106 : * // need to register with communicator
107 : * message register_message;
108 : * register_message.set_command("REGISTER");
109 : * ...
110 : * blocking_connection.send_message(register_message);
111 : *
112 : * run();
113 : * }
114 : *
115 : * ~my_blocking_connection()
116 : * {
117 : * // done, send UNLOCK and then make sure to unregister
118 : * message unlock_message;
119 : * unlock_message.set_command("UNLOCK");
120 : * ...
121 : * blocking_connection.send_message(unlock_message);
122 : *
123 : * message unregister_message;
124 : * unregister_message.set_command("UNREGISTER");
125 : * ...
126 : * blocking_connection.send_message(unregister_message);
127 : * }
128 : *
129 : * // now that we have a dispatcher, this would probably use
130 : * // that mechanism instead of a list of if()/else if()
131 : * //
132 : * // Please, consider using the dispatcher instead
133 : * //
134 : * virtual void process_message(message const & message)
135 : * {
136 : * QString const command(message.get_command());
137 : * if(command == "LOCKED")
138 : * {
139 : * // the lock worked, release hand back to the user
140 : * done();
141 : * }
142 : * else if(command == "READY")
143 : * {
144 : * // the REGISTER worked
145 : * // send the LOCK now
146 : * message lock_message;
147 : * lock_message.set_command("LOCK");
148 : * ...
149 : * blocking_connection.send_message(lock_message);
150 : * }
151 : * else if(command == "HELP")
152 : * {
153 : * // snapcommunicator wants us to tell it what commands
154 : * // we accept
155 : * message commands_message;
156 : * commands_message.set_command("COMMANDS");
157 : * ...
158 : * blocking_connection.send_message(commands_message);
159 : * }
160 : * }
161 : * };
162 : * my_blocking_connection blocking_connection("127.0.0.1", 4040);
163 : *
164 : * // then we can send a message to the service we are interested in
165 : * my_blocking_connection.send_message(my_message);
166 : *
167 : * // now we call run() waiting for a reply
168 : * my_blocking_connection.run();
169 : * \endcode
170 : *
171 : * \param[in] address The address to connect to.
172 : * \param[in] blocking Whether the connection is blocking or not.
173 : * \param[in] close_on_exec Whether to force close this connection on an
174 : * exec() call.
175 : */
176 0 : local_stream_blocking_client_message_connection::local_stream_blocking_client_message_connection(
177 : addr::unix const & address
178 : , bool const blocking
179 0 : , bool const close_on_exec)
180 : : local_stream_client_message_connection(
181 : address
182 : , blocking
183 0 : , close_on_exec)
184 : {
185 0 : }
186 :
187 :
188 : /** \brief Blocking run on the connection.
189 : *
190 : * This function reads the incoming messages and calls process_message()
191 : * on each one of them, in a blocking manner.
192 : *
193 : * If you called mark_done() before, the done flag is reset back to false.
194 : * You will have to call mark_done() again if you again receive a message
195 : * that is expected to end the loop.
196 : *
197 : * \note
198 : * Internally, the function actually calls process_line() which transforms
199 : * the line in a message and in turn calls process_message().
200 : */
201 0 : void local_stream_blocking_client_message_connection::run()
202 : {
203 0 : mark_not_done();
204 :
205 0 : do
206 : {
207 : for(;;)
208 : {
209 : // TBD: can the socket become -1 within the read() loop?
210 : // (i.e. should not that be just outside of the for(;;)?)
211 : //
212 0 : struct pollfd fd;
213 0 : fd.events = POLLIN | POLLPRI | POLLRDHUP;
214 0 : fd.fd = get_socket();
215 0 : if(fd.fd < 0
216 0 : || !is_enabled())
217 : {
218 : // invalid socket
219 0 : process_error();
220 0 : return;
221 : }
222 :
223 : // at this time, this class is used with the lock and
224 : // the lock has a timeout so we need to block at most
225 : // for that amount of time and not forever (presumably
226 : // the snaplock would send us a LOCKFAILED marked with
227 : // a "timeout" parameter, but we cannot rely on the
228 : // snaplock being there and responding as expected.)
229 : //
230 : // calculate the number of microseconds and then convert
231 : // them to milliseconds for poll()
232 : //
233 0 : std::int64_t const next_timeout_timestamp(save_timeout_timestamp());
234 0 : std::int64_t const now(get_current_date());
235 0 : std::int64_t const timeout((next_timeout_timestamp - now) / 1000);
236 0 : if(timeout <= 0)
237 : {
238 : // timed out
239 : //
240 0 : process_timeout();
241 0 : if(is_done())
242 : {
243 0 : return;
244 : }
245 0 : SNAP_LOG_FATAL
246 : << "blocking connection timed out."
247 : << SNAP_LOG_SEND;
248 : throw event_dispatcher_runtime_error(
249 : "local_stream_blocking_client_message_connection::run(): blocking"
250 0 : " connection timed out.");
251 : }
252 0 : errno = 0;
253 0 : fd.revents = 0; // probably useless... (kernel should clear those)
254 0 : int const r(::poll(&fd, 1, timeout));
255 0 : if(r < 0)
256 : {
257 : // r < 0 means an error occurred
258 : //
259 0 : if(errno == EINTR)
260 : {
261 : // Note: if the user wants to prevent this error, he should
262 : // use the signal with the Unix signals that may
263 : // happen while calling poll().
264 : //
265 : throw event_dispatcher_runtime_error(
266 : "local_stream_blocking_client_message_connection::run():"
267 : " EINTR occurred while in poll() -- interrupts"
268 0 : " are not supported yet though.");
269 : }
270 0 : if(errno == EFAULT)
271 : {
272 : throw event_dispatcher_runtime_error(
273 : "local_stream_blocking_client_message_connection::run():"
274 0 : " buffer was moved out of our address space?");
275 : }
276 0 : if(errno == EINVAL)
277 : {
278 : // if this is really because nfds is too large then it may be
279 : // a "soft" error that can be fixed; that being said, my
280 : // current version is 16K files which frankly when we reach
281 : // that level we have a problem...
282 : //
283 0 : rlimit rl;
284 0 : getrlimit(RLIMIT_NOFILE, &rl);
285 : throw event_dispatcher_invalid_parameter(
286 : "local_stream_blocking_client_message_connection::run():"
287 : " too many file fds for poll, limit is"
288 : " currently "
289 0 : + std::to_string(rl.rlim_cur)
290 0 : + ", your kernel top limit is "
291 0 : + std::to_string(rl.rlim_max)
292 0 : + ".");
293 : }
294 0 : if(errno == ENOMEM)
295 : {
296 : throw event_dispatcher_runtime_error(
297 : "local_stream_blocking_client_message_connection::run():"
298 0 : " poll() failed because of memory.");
299 : }
300 0 : int const e(errno);
301 : throw event_dispatcher_invalid_parameter(
302 : "local_stream_blocking_client_message_connection::run():"
303 : " poll() failed with error "
304 0 : + std::to_string(e)
305 0 : + " -- "
306 0 : + strerror(e));
307 : }
308 :
309 0 : if((fd.revents & (POLLIN | POLLPRI)) != 0)
310 : {
311 : // read one character at a time otherwise we would be
312 : // blocked forever
313 : //
314 0 : char buf[2];
315 0 : int const size(::read(fd.fd, buf, 1));
316 0 : if(size != 1)
317 : {
318 : // invalid read
319 : //
320 0 : process_error();
321 : throw event_dispatcher_invalid_parameter(
322 : "local_stream_blocking_client_message_connection::run():"
323 : " read() failed reading data from socket"
324 : " (return value = "
325 0 : + std::to_string(size)
326 0 : + ").");
327 : }
328 0 : if(buf[0] == '\n')
329 : {
330 : // end of a line, we got a whole message in our buffer
331 : // notice that we do not add the '\n' to line
332 : //
333 0 : break;
334 : }
335 0 : buf[1] = '\0';
336 0 : f_line += buf;
337 : }
338 0 : if((fd.revents & POLLERR) != 0)
339 : {
340 0 : process_error();
341 0 : return;
342 : }
343 0 : if((fd.revents & (POLLHUP | POLLRDHUP)) != 0)
344 : {
345 0 : process_hup();
346 0 : return;
347 : }
348 0 : if((fd.revents & POLLNVAL) != 0)
349 : {
350 0 : process_invalid();
351 0 : return;
352 : }
353 0 : }
354 0 : process_line(f_line);
355 0 : f_line.clear();
356 : }
357 0 : while(!is_done());
358 : }
359 :
360 :
361 : /** \brief Quick peek on the connection.
362 : *
363 : * This function checks for incoming messages and calls process_message()
364 : * on each one of them. If no messages are found on the pipe, then the
365 : * function returns immediately.
366 : *
367 : * \note
368 : * Internally, the function actually calls process_line() which transforms
369 : * the line in a message and in turn calls process_message().
370 : */
371 0 : void local_stream_blocking_client_message_connection::peek()
372 : {
373 0 : do
374 : {
375 : for(;;)
376 : {
377 0 : pollfd fd;
378 0 : fd.events = POLLIN | POLLPRI | POLLRDHUP;
379 0 : fd.fd = get_socket();
380 0 : if(fd.fd < 0
381 0 : || !is_enabled())
382 : {
383 : // invalid socket
384 0 : process_error();
385 0 : return;
386 : }
387 :
388 0 : errno = 0;
389 0 : fd.revents = 0; // probably useless... (kernel should clear those)
390 0 : int const r(::poll(&fd, 1, 0));
391 0 : if(r < 0)
392 : {
393 : // r < 0 means an error occurred
394 : //
395 0 : if(errno == EINTR)
396 : {
397 : // Note: if the user wants to prevent this error, he should
398 : // use the signal with the Unix signals that may
399 : // happen while calling poll().
400 : //
401 : throw event_dispatcher_runtime_error(
402 : "local_stream_blocking_client_message_connection::run():"
403 : " EINTR occurred while in poll() -- interrupts"
404 0 : " are not supported yet though");
405 : }
406 0 : if(errno == EFAULT)
407 : {
408 : throw event_dispatcher_invalid_parameter(
409 : "local_stream_blocking_client_message_connection::run():"
410 0 : " buffer was moved out of our address space?");
411 : }
412 0 : if(errno == EINVAL)
413 : {
414 : // if this is really because nfds is too large then it may be
415 : // a "soft" error that can be fixed; that being said, my
416 : // current version is 16K files which frankly when we reach
417 : // that level we have a problem...
418 : //
419 0 : struct rlimit rl;
420 0 : getrlimit(RLIMIT_NOFILE, &rl);
421 : throw event_dispatcher_invalid_parameter(
422 : "local_stream_blocking_client_message_connection::run():"
423 : " too many file fds for poll, limit is currently "
424 0 : + std::to_string(rl.rlim_cur)
425 0 : + ", your kernel top limit is "
426 0 : + std::to_string(rl.rlim_max));
427 : }
428 0 : if(errno == ENOMEM)
429 : {
430 : throw event_dispatcher_runtime_error(
431 : "local_stream_blocking_client_message_connection::run():"
432 0 : " poll() failed because of memory");
433 : }
434 0 : int const e(errno);
435 : throw event_dispatcher_runtime_error(
436 : "local_stream_blocking_client_message_connection::run():"
437 : " poll() failed with error "
438 0 : + std::to_string(e)
439 0 : + " -- "
440 0 : + strerror(e));
441 : }
442 :
443 0 : if(r == 0)
444 : {
445 0 : return;
446 : }
447 :
448 0 : if((fd.revents & (POLLIN | POLLPRI)) != 0)
449 : {
450 : // read one character at a time otherwise we would be
451 : // blocked forever
452 : //
453 0 : char buf[2];
454 0 : int const size(::read(fd.fd, buf, 1));
455 0 : if(size != 1)
456 : {
457 : // invalid read
458 0 : process_error();
459 : throw event_dispatcher_runtime_error(
460 : "local_stream_blocking_client_message_connection::run():"
461 : " read() failed reading data from socket (return"
462 : " value = "
463 0 : + std::to_string(size)
464 0 : + ")");
465 : }
466 0 : if(buf[0] == '\n')
467 : {
468 : // end of a line, we got a whole message in our buffer
469 : // notice that we do not add the '\n' to line
470 0 : break;
471 : }
472 0 : buf[1] = '\0';
473 0 : f_line += buf;
474 : }
475 0 : if((fd.revents & POLLERR) != 0)
476 : {
477 0 : process_error();
478 0 : return;
479 : }
480 0 : if((fd.revents & (POLLHUP | POLLRDHUP)) != 0)
481 : {
482 0 : process_hup();
483 0 : return;
484 : }
485 0 : if((fd.revents & POLLNVAL) != 0)
486 : {
487 0 : process_invalid();
488 0 : return;
489 : }
490 0 : }
491 0 : process_line(f_line);
492 0 : f_line.clear();
493 : }
494 0 : while(!is_done());
495 : }
496 :
497 :
498 : /** \brief Send the specified message to the connection on the other end.
499 : *
500 : * This function sends the specified message to the other side of the
501 : * socket connection. If the write somehow fails, then the function
502 : * returns false.
503 : *
504 : * The function blocks until the entire message was written to the
505 : * socket.
506 : *
507 : * \param[in] msg The message to send to the connection.
508 : * \param[in] cache Whether to cache the message if it cannot be sent
509 : * immediately (ignored at the moment.)
510 : *
511 : * \return true if the message was sent successfully, false otherwise.
512 : */
513 0 : bool local_stream_blocking_client_message_connection::send_message(message const & msg, bool cache)
514 : {
515 0 : snapdev::NOT_USED(cache);
516 :
517 0 : int const s(get_socket());
518 0 : if(s >= 0)
519 : {
520 : // transform the message to a string and write to the socket
521 : // the writing is blocking and thus fully synchronous so the
522 : // function blocks until the message gets fully sent
523 : //
524 : // WARNING: we cannot use f_connection.write() because that one
525 : // is asynchronous (at least, it writes to a buffer
526 : // and not directly to the socket!)
527 : //
528 0 : std::string buf(msg.to_message());
529 0 : buf += '\n';
530 0 : return ::write(s, buf.c_str(), buf.length()) == static_cast<ssize_t>(buf.length());
531 : }
532 :
533 0 : return false;
534 : }
535 :
536 :
537 :
538 :
539 :
540 6 : } // namespace ed
541 : // vim: ts=4 sw=4 et
|