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 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 :
43 : // self
44 : //
45 : #include "eventdispatcher/tcp_client_buffer_connection.h"
46 :
47 : #include "eventdispatcher/utils.h"
48 :
49 :
50 : // snaplogger lib
51 : //
52 : #include <snaplogger/message.h>
53 :
54 :
55 : // last include
56 : //
57 : #include <snapdev/poison.h>
58 :
59 :
60 :
61 : namespace ed
62 : {
63 :
64 :
65 :
66 : /** \brief Initialize a client socket.
67 : *
68 : * The client socket gets initialized with the specified 'socket'
69 : * parameter.
70 : *
71 : * This constructor creates a writer connection too. This gives you
72 : * a read/write connection. You can get the writer with the writer()
73 : * function. So you may write data with:
74 : *
75 : * \code
76 : * my_reader.writer().write(buf, buf_size);
77 : * \endcode
78 : *
79 : * \param[in] addr The address to connect to.
80 : * \param[in] port The port to connect to.
81 : * \param[in] mode The mode to connect as (PLAIN or SECURE).
82 : * \param[in] blocking If true, keep a blocking socket, other non-blocking.
83 : */
84 0 : tcp_client_buffer_connection::tcp_client_buffer_connection(
85 : std::string const & addr
86 : , int const port
87 : , mode_t const mode
88 : , bool const blocking)
89 0 : : tcp_client_connection(addr, port, mode)
90 : {
91 0 : if(!blocking)
92 : {
93 0 : non_blocking();
94 : }
95 0 : }
96 :
97 :
98 : /** \brief Check whether this connection still has some input in its buffer.
99 : *
100 : * This function returns true if there is partial incoming data in this
101 : * object's buffer.
102 : *
103 : * \return true if some buffered input is waiting for completion.
104 : */
105 0 : bool tcp_client_buffer_connection::has_input() const
106 : {
107 0 : return !f_line.empty();
108 : }
109 :
110 :
111 :
112 : /** \brief Check whether this connection still has some output in its buffer.
113 : *
114 : * This function returns true if there is still some output in the client
115 : * buffer. Output is added by the write() function, which is called by
116 : * the send_message() function.
117 : *
118 : * \return true if some buffered output is waiting to be sent out.
119 : */
120 0 : bool tcp_client_buffer_connection::has_output() const
121 : {
122 0 : return !f_output.empty();
123 : }
124 :
125 :
126 :
127 : /** \brief Write data to the connection.
128 : *
129 : * This function can be used to send data to this TCP/IP connection.
130 : * The data is bufferized and as soon as the connection can WRITE
131 : * to the socket, it will wake up and send the data. In other words,
132 : * we cannot just sleep and wait for an answer. The transfer will
133 : * be asynchroneous.
134 : *
135 : * \todo
136 : * Optimization: look into writing the \p data buffer directly in
137 : * the socket if the f_output cache is empty. If that works then
138 : * we can completely bypass our intermediate cache. This works only
139 : * if we make sure that the socket is non-blocking, though.
140 : *
141 : * \todo
142 : * Determine whether we may end up with really large buffers that
143 : * grow for a long time. This function only inserts and the
144 : * process_signal() function only reads some of the bytes but it
145 : * does not reduce the size of the buffer until all the data was
146 : * sent.
147 : *
148 : * \param[in] data The pointer to the buffer of data to be sent.
149 : * \param[out] length The number of bytes to send.
150 : *
151 : * \return The number of bytes that were saved in our buffer, 0 if
152 : * no data was written to the buffer (i.e. the socket is
153 : * closed, length is zero, or data is a null pointer.)
154 : */
155 0 : ssize_t tcp_client_buffer_connection::write(void const * data, size_t length)
156 : {
157 0 : if(get_socket() == -1)
158 : {
159 0 : errno = EBADF;
160 0 : return -1;
161 : }
162 :
163 0 : if(data != nullptr && length > 0)
164 : {
165 0 : char const * d(reinterpret_cast<char const *>(data));
166 0 : f_output.insert(f_output.end(), d, d + length);
167 0 : return length;
168 : }
169 :
170 0 : return 0;
171 : }
172 :
173 :
174 : /** \brief The buffer is a writer when the output buffer is not empty.
175 : *
176 : * This function returns true as long as the output buffer of this
177 : * client connection is not empty.
178 : *
179 : * \return true if the output buffer is not empty, false otherwise.
180 : */
181 0 : bool tcp_client_buffer_connection::is_writer() const
182 : {
183 0 : return get_socket() != -1 && !f_output.empty();
184 : }
185 :
186 :
187 : /** \brief Instantiation of process_read().
188 : *
189 : * This function reads incoming data from a socket.
190 : *
191 : * The function is what manages our low level TCP/IP connection protocol
192 : * which is to read one line of data (i.e. bytes up to the next '\n'
193 : * character; note that '\r' are not understood.)
194 : *
195 : * Once a complete line of data was read, it is converted to UTF-8 and
196 : * sent to the next layer using the process_line() function passing
197 : * the line it just read (without the '\n') to that callback.
198 : *
199 : * \sa process_write()
200 : * \sa process_line()
201 : */
202 0 : void tcp_client_buffer_connection::process_read()
203 : {
204 : // we read one character at a time until we get a '\n'
205 : // since we have a non-blocking socket we can read as
206 : // much as possible and then check for a '\n' and keep
207 : // any extra data in a cache.
208 : //
209 0 : if(get_socket() != -1)
210 : {
211 0 : int count_lines(0);
212 0 : std::int64_t const date_limit(get_current_date() + get_processing_time_limit());
213 0 : std::vector<char> buffer;
214 0 : buffer.resize(1024);
215 0 : for(;;)
216 : {
217 0 : errno = 0;
218 0 : ssize_t const r(read(&buffer[0], buffer.size()));
219 0 : if(r > 0)
220 : {
221 0 : for(ssize_t position(0); position < r; )
222 : {
223 0 : std::vector<char>::const_iterator it(std::find(buffer.begin() + position, buffer.begin() + r, '\n'));
224 0 : if(it == buffer.begin() + r)
225 : {
226 : // no newline, just add the whole thing
227 0 : f_line += std::string(&buffer[position], r - position);
228 0 : break; // do not waste time, we know we are done
229 : }
230 :
231 : // retrieve the characters up to the newline
232 : // character and process the line
233 : //
234 0 : f_line += std::string(&buffer[position], it - buffer.begin() - position);
235 0 : process_line(f_line);
236 0 : ++count_lines;
237 :
238 : // done with that line
239 : //
240 0 : f_line.clear();
241 :
242 : // we had a newline, we may still have some data
243 : // in that buffer; (+1 to skip the '\n' itself)
244 : //
245 0 : position = it - buffer.begin() + 1;
246 : }
247 :
248 : // when we reach here all the data read in `buffer` is
249 : // now either fully processed or in f_line
250 : //
251 : // TODO: change the way this works so we can test the
252 : // limit after each process_line() call
253 : //
254 0 : if(count_lines >= get_event_limit()
255 0 : || get_current_date() >= date_limit)
256 : {
257 : // we reach one or both limits, stop processing so
258 : // the other events have a chance to run
259 : //
260 0 : break;
261 : }
262 : }
263 0 : else if(r == 0 || errno == 0 || errno == EAGAIN || errno == EWOULDBLOCK)
264 : {
265 : // no more data available at this time
266 : break;
267 : }
268 : else //if(r < 0)
269 : {
270 : // TODO: do something about the error
271 0 : int const e(errno);
272 : SNAP_LOG_ERROR
273 0 : << "an error occurred while reading from socket (errno: "
274 0 : << e
275 0 : << " -- "
276 0 : << strerror(e)
277 0 : << ").";
278 0 : process_error();
279 0 : return;
280 : }
281 : }
282 : }
283 :
284 : // process next level too
285 0 : tcp_client_connection::process_read();
286 : }
287 :
288 :
289 : /** \brief Instantiation of process_write().
290 : *
291 : * This function writes outgoing data to a socket.
292 : *
293 : * This function manages our own internal cache, which we use to allow
294 : * for out of synchronization (non-blocking) output.
295 : *
296 : * When the output buffer goes empty, this function calls the
297 : * process_empty_buffer() callback.
298 : *
299 : * \sa write()
300 : * \sa process_read()
301 : * \sa process_empty_buffer()
302 : */
303 0 : void tcp_client_buffer_connection::process_write()
304 : {
305 0 : if(get_socket() != -1)
306 : {
307 0 : errno = 0;
308 0 : ssize_t const r(tcp_client_connection::write(&f_output[f_position], f_output.size() - f_position));
309 0 : if(r > 0)
310 : {
311 : // some data was written
312 0 : f_position += r;
313 0 : if(f_position >= f_output.size())
314 : {
315 0 : f_output.clear();
316 0 : f_position = 0;
317 0 : process_empty_buffer();
318 : }
319 : }
320 0 : else if(r < 0 && errno != 0 && errno != EAGAIN && errno != EWOULDBLOCK)
321 : {
322 : // connection is considered bad, generate an error
323 : //
324 0 : int const e(errno);
325 : SNAP_LOG_ERROR
326 0 : << "an error occurred while writing to socket of \""
327 0 : << get_name()
328 0 : << "\" (errno: "
329 0 : << e
330 0 : << " -- "
331 0 : << strerror(e)
332 0 : << ").";
333 0 : process_error();
334 0 : return;
335 : }
336 : }
337 :
338 : // process next level too
339 0 : tcp_client_connection::process_write();
340 : }
341 :
342 :
343 : /** \brief The hang up event occurred.
344 : *
345 : * This function closes the socket and then calls the previous level
346 : * hang up code which removes this connection from the snap_communicator
347 : * object it was last added in.
348 : */
349 0 : void tcp_client_buffer_connection::process_hup()
350 : {
351 : // this connection is dead...
352 : //
353 0 : close();
354 :
355 : // process next level too
356 0 : tcp_client_connection::process_hup();
357 0 : }
358 :
359 :
360 : /** \fn tcp_client_buffer_connection::process_line(std::string const & line);
361 : * \brief Process a line of data.
362 : *
363 : * This is the default virtual class that can be overridden to implement
364 : * your own processing. By default this function does nothing.
365 : *
366 : * \note
367 : * At this point I implemented this function so one can instantiate
368 : * a snap_tcp_server_client_buffer_connection without having to
369 : * derive it, although I do not think that is 100% proper.
370 : *
371 : * \param[in] line The line of data that was just read from the input
372 : * socket.
373 : */
374 :
375 :
376 :
377 6 : } // namespace ed
378 : // vim: ts=4 sw=4 et
|