Skip to content

Commit

Permalink
dlt_client:Block in connect()
Browse files Browse the repository at this point in the history
Connect TCP socket with non-blocking socket

Check errno and getsockopt to guarantee that the socket connection is established successfully

Signed-off-by: Le Tin <[email protected]>
  • Loading branch information
thanhbnq committed Sep 27, 2022
1 parent 6170416 commit 3c6fdb9
Showing 1 changed file with 60 additions and 6 deletions.
66 changes: 60 additions & 6 deletions src/lib/dlt_client.c
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
#include <string.h> /* for strlen(), memcmp(), memmove() */
#include <errno.h>
#include <limits.h>
#include <poll.h>

#include "dlt_types.h"
#include "dlt_client.h"
Expand Down Expand Up @@ -171,7 +172,7 @@ DltReturnValue dlt_client_init(DltClient *client, int verbose)
DltReturnValue dlt_client_connect(DltClient *client, int verbose)
{
const int yes = 1;
char portnumbuffer[33];
char portnumbuffer[33] = {0};
struct addrinfo hints, *servinfo, *p;
struct sockaddr_un addr;
int rv;
Expand Down Expand Up @@ -205,27 +206,80 @@ DltReturnValue dlt_client_connect(DltClient *client, int verbose)
continue;
}

if (connect(client->sock, p->ai_addr, p->ai_addrlen) < 0) {
/* Set socket to Non-blocking mode */
if(fcntl(client->sock, F_SETFL, fcntl(client->sock,F_GETFL,0) | O_NONBLOCK) < 0)
{
dlt_vlog(LOG_WARNING,
"%s: Socket cannot be changed to NON BLOCK: %s\n",
__func__, strerror(errno));
close(client->sock);
continue;
}

if (connect(client->sock, p->ai_addr, p->ai_addrlen) < 0) {
if (errno == EINPROGRESS) {
pfds[0].fd = client->sock;
pfds[0].events = POLLOUT;
ret = poll(pfds, 1, 500);
if (ret < 0) {
dlt_vlog(LOG_ERR, "%s: Failed to poll with err [%s]\n",
__func__, strerror(errno));
close(client->sock);
continue;
}
else if ((pfds[0].revents & POLLOUT) &&
getsockopt(client->sock, SOL_SOCKET,
SO_ERROR, (void*)&n, &m) == 0) {
if (n == 0) {
dlt_vlog(LOG_DEBUG, "%s: Already connect\n", __func__);
if(fcntl(client->sock, F_SETFL,
fcntl(client->sock,F_GETFL,0) & ~O_NONBLOCK) < 0) {
dlt_vlog(LOG_WARNING,
"%s: Socket cannot be changed to BLOCK with err [%s]\n",
__func__, strerror(errno));
close(client->sock);
continue;
}
}
else {
connect_errno = n;
close(client->sock);
continue;
}
}
else {
connect_errno = errno;
close(client->sock);
continue;
}
}
else {
connect_errno = errno;
close(client->sock);
continue;
}
}

break;
}

freeaddrinfo(servinfo);

if (p == NULL) {
dlt_vlog(LOG_ERR,
"%s: ERROR: failed to connect! %s\n",
__func__,
strerror(connect_errno));
return DLT_RETURN_ERROR;
}

if (verbose) {
dlt_vlog(LOG_INFO,
"%s: Connected to DLT daemon (%s)\n",
__func__,
client->servIP);
return DLT_RETURN_ERROR;
}

if (verbose)
printf("Connected to DLT daemon (%s)\n", client->servIP);

receiver_type = DLT_RECEIVE_SOCKET;

break;
Expand Down

0 comments on commit 3c6fdb9

Please sign in to comment.