Fix redmine #2561, "Bad file descriptor" in cf_closesocket(), plus some minor cleanups