sqlitecloud / sdk

Official SDK repository for SQLite Cloud databases and nodes.
https://sqlitecloud.io
29 stars 2 forks source link

C SDK / Error in internal_socket_read when processing chunked responses #9

Closed andinux closed 2 months ago

andinux commented 2 months ago

I found an error on the C cli when processing a chunked response from the server. I'm able to reproduce the issue only when the server runs in insecure mode. Minimal environment to make it happen:

The server send the following buffers

/43 1:1 2 1
+4 name+10 db1.sqlite+10 db2.sqlite
/6 0 0 0

If the client reads from the socket each one of the 3 packets individually or the first 2 in a single read and the third in a following read (like it seems to always happpen with TLS), the sdk/cli works fine. Otherwise, if the sdk/cli reads all the received data in a single read (like it frequently happens without TLS) then it fires an error in internal_socket_read. The issue is in sqcloud.c lines 1470-1480:

           if (clen + cstart + 1 != tread) {
                // check buffer allocation and continue reading
                if (clen + cstart - tread > blen) {
                ...
                blen = (clen + cstart + 1) - tread;

because in this case tread includes the end chunk (it's value is 56) but clen + cstart + 1 only consider the real content (43+3+1 = 47) and the following blen = (clen + cstart + 1) - tread; is lower than 0 but the value is uint64 so it's value is represented as 4294967287 and the following read will fail with error code 22 Invalid argument because of this blen value.

marcobambini commented 2 months ago

Related to https://github.com/sqlitecloud/core/issues/18

marcobambini commented 2 months ago

Fixed by https://github.com/sqlitecloud/sdk/commit/a4835577ab84292d924dd636839d4fb391138ce6