flightaware / Pgtcl

Tcl client side interface to PostgreSQL (libpgtcl)
https://flightaware.github.io/Pgtcl/
BSD 3-Clause "New" or "Revised" License
31 stars 10 forks source link

Fix use-after-free when disconnecting inside pg_select body #26

Closed agbrooks closed 5 years ago

agbrooks commented 5 years ago

In Pgtcl 2.6.1, making apg_select query on multiple rows containing nulls, and disconnecting inside the pg_select body, can cause the reuse of already-freed memory, potentially leading to a segfault. Note that if -withoutnulls is supplied, this does not happen, since the reuse occurs here.

Something like

pg_select $::db "SELECT (some multi-row query with nulls)" row {
    pg_disconnect $::db
    set ::db [pg_connect -connlist [array get ::dbSettings]]
}

should trigger the bug. (If you're interested, I have a more FlightAware-specific test case that causes this reliably on one of our servers.)

This PR modifies Pg_select() so that it registers/unregisters on the channel associated with the database connection, preventing PgDelConnectionId() from freeing the connection ID in use until Pg_select() completes.

I saw this bug on FreeBSD 11.2-RELEASE-p4, using Tcl 8.6.8.

resuna commented 5 years ago

Looks good to me.