From 34a4541114318a7eda1c96ed58f83cdcd2622207 Mon Sep 17 00:00:00 2001 From: Dirk Engling Date: Tue, 17 May 2022 15:23:33 +0200 Subject: Move packet handler and line splitting to vchat-connection.c --- vchat-connection.c | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 64 insertions(+), 5 deletions(-) (limited to 'vchat-connection.c') diff --git a/vchat-connection.c b/vchat-connection.c index 6b38168..06ea187 100644 --- a/vchat-connection.c +++ b/vchat-connection.c @@ -35,6 +35,10 @@ static int serverfd = -1; unsigned int want_tcp_keepalive = 0; +/* TODO: NEEDS TO GO. status-variable from vchat-client.c + * eventloop is done as long as this is true */ +extern int status; + /* Generic tcp connector, blocking */ static int connect_tcp_socket( const char *server, const char *port ) { struct addrinfo hints, *res, *res0; @@ -213,10 +217,65 @@ vc_sendmessage (const char *msg) } } -ssize_t -vc_receivemessage (char *buffer, size_t size) { - if (getintoption(CF_USESSL)) - return vc_tls_receivemessage (buffer, size); +/* offset in buffer (for linebreaks at packet borders) */ +#define BUFSIZE 4096 +static char _buf[BUFSIZE]; +static size_t _buf_fill; + +/* get data from servers connection */ +void +vc_receive (void) +{ + char *endmsg; + size_t freebytes = BUFSIZE - _buf_fill; + ssize_t bytes; + + if (!getintoption(CF_USESSL)) + bytes = read(serverfd, _buf + _buf_fill, freebytes); else - return read(serverfd, buffer, size); + bytes = vc_tls_receivemessage(_buf + _buf_fill, freebytes); + + /* Our tls functions may require retries with handshakes etc, this is signalled by -2 */ + if (bytes == -2) + return; + + /* Error on the socket read? raise error message, bail out */ + if (bytes == -1) { + snprintf (tmpstr, TMPSTRSIZE, "Receive fails, %s.", strerror(errno)); + snprintf (errstr, ERRSTRSIZE, "Receive fails, %s.\n", strerror(errno)); + writecf (FS_ERR,tmpstr); + status = 0; + return; + } + + /* end of file from server? */ + if (bytes == 0) { + /* inform user, bail out */ + writecf (FS_SERV, "* EOF from server."); + snprintf (errstr, ERRSTRSIZE, "* EOF from server.\n"); + status = 0; + return; + } + + _buf_fill += bytes; + + /* as long as there are lines .. */ + while ((endmsg = memchr(_buf, '\n', _buf_fill)) != NULL) { + if (endmsg > _buf) { + /* Zero terminate message, optionally chomp CR */ + endmsg[0] = 0; + if (endmsg[-1] == '\r') + endmsg[-1] = 0; + /* If terminating and chomping left us with a message, give it to line handler */ + if (_buf[0]) { +#ifdef DEBUG + /* debugging? log network input! */ + fprintf (stderr, "<| %s\n", _buf); +#endif + protocol_parsemsg (_buf); + } + } + _buf_fill -= 1 + endmsg - _buf; + memmove(_buf, endmsg + 1, _buf_fill); + } } -- cgit v1.2.3