Search code examples
clibwebsockets

libwebsockets client fails to connect


I'm using libwebsockets 2.0 and I'm having a few issues trying to connect to a server using it as a client.

According to the libwebsockets log, this is what happens when my fairly simple client tries to connect to echo.websocket.org:

[2016/09/25 19:22:56:9033] INFO: lws_header_table_attach: wsi 0x7fe32402a680: ah (nil) (tsi 0, count = 0) in
[2016/09/25 19:22:56:9034] INFO: lws_header_table_attach: wsi 0x7fe32402a680: ah 0x7fe3240078f0: count 1 (on exit)
[2016/09/25 19:22:56:9034] CLIENT: lws_client_connect: direct conn
[2016/09/25 19:22:56:9034] CLIENT: lws_client_connect_2
[2016/09/25 19:22:56:9034] CLIENT: lws_client_connect_2: address 
[2016/09/25 19:22:56:9044] ERR: getaddrinfo failed
Callback LWS_CALLBACK_CLIENT_CONNECTION_ERROR (1)
Connection error: (25) getaddrinfo (ipv4) failed

According to this log, it appears to say that getaddrinfo failed, but the line above it (which is supposed to output the address which libwebsockets is connecting to) is returning an empty string.

Even weirder, when I run my test code through Valgrind, everything appears to work fine:

[2016/09/25 19:46:17:7566] INFO: lws_header_table_attach: wsi 0x6714970: ah (nil) (tsi 0, count = 0) in
[2016/09/25 19:46:17:7598] INFO: lws_header_table_attach: wsi 0x6714970: ah 0x65b35c0: count 1 (on exit)
[2016/09/25 19:46:17:7665] CLIENT: lws_client_connect: direct conn
[2016/09/25 19:46:17:7670] CLIENT: lws_client_connect_2
[2016/09/25 19:46:17:7680] CLIENT: lws_client_connect_2: address echo.websocket.org
[2016/09/25 19:46:17:9511] DEBUG: insert_wsi_socket_into_fds: 0x6714970: tsi=0, sock=6, pos-in-fds=1

All of the included examples/tests work just fine, so I'm really not sure where my problem is.

The code at fault is here - I'm not sure whether the issue is within my code or whether it's a library issue.


Solution

  • I was pondering over my code today, trying random things to see if it would fix the issue. Turns out a free in my code was causing issues with libwebsockets:

    char* address_internal = malloc(strlen(address) + 1);
    memcpy(address_internal, address, strlen(address));
    
    /*...*/
    
    free(address_internal);
    

    Removing free(address_internal); allows the code to work correctly outside of Valgrind.

    I'm guessing the problem is that lws_parse_uri doesn't create its own internal copy, which the docs don't clearly mention. What's weird is that Valgrind didn't pick up on this, and somehow allowed the memory to still be used.