Backport fixes to race conditions and file permissions in file editing.

One squashed commit with the these three cherry-picks from master:

(cherry picked from commit a3f1a964ad5e079f8abc419bb9e0489aa8c62f7a)
(cherry picked from commit 908fb187191b41df44bdfb7d092a429cded06436)
(cherry picked from commit 76d895609ea7dee55502139acf52b1b141ca9b10)

as well as compile fixes (esp for Log() -> CfOut and cfPS).

Was hoping that this would make it easier to backport to 3.3.x as well, but that needs more work.

Needs testing.