[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

When it's safe to free callback userdata for channels and events?


Hi there,

In my server application several channels are handled simultaneously.
Each channel has his individual CB function set with userdata, which is
allocated at runtime (malloc).

The server keeps running for an undefined time, so the allocated memory
should be freed individually per channel after it's been closed.

The question is: When is it safe to free this memory?

struct ssh_channel_callbacks_struct *cb_chan = malloc(sizeof *cb_chan);
struct event_fd_data_struct *event_fd_data = malloc(sizeof *event_fd_data);

event_fd_data->fd = ...
event_fd_data->status = ...
cb_chan->userdata = event_fd_data;
cb_chan->channel_data_function = my_channel_data_function;

ssh_callbacks_init(cb_chan);
ssh_set_channel_callbacks(channel, cb_chan);

After one side has sent a EOF on a channel, I run ssh_channel_close()
and then test in the main event loop for ssh_channel_is_closed(). When
it's considered closed, I run ssh_channel_free().

Now the problem is that my_channel_data_function() is still called after
then channel has been closed and freed. Hence it's not possible to free
the userdata, because this would lead to unpredictable behaviour.

So when exactly the channel callbacks are removed from the poll context?
And how can I check for this, so userdata can be freed safely?

I have the same issue with:

ssh_event_add_fd(mainloop, (socket_t)*pFd, POLLIN, cb_readsock, event_fd_data);

Here as well I can never tell when the callback function can be
considered being unregistered and never called again.
ssh_event_remove_fd() does not guarantee in any way that it's safe to
free userdata.

Like that it's really hard to write a reliable application with
dynamically allocated userdata. And what's the alternative to malloc /
free when the app will run for an undefined time?

Cheers,
Till



Archive administrator: postmaster@lists.cynapses.org