Don't use O_DIRECTORY flag, which is Linux specific.

Directories will fail when we try to chdir into them anyway, so all
we lose is the early warning.
Switch back to test folder after each test.

Otherwise the test framework may try to write into the wrong
directory.
Merge pull request #1123 from kacfengine/safe_open

Some fixes to the safe_open() function.