fix memory leaks and shutdown connection on close