[io-layer] Properly check write permission of a file. Fixes #3501.

The existing check only verified if owner had write privileges.
Which returns the wrong value when the file is not owned by the user.

And doesn't work when the file is globally writeable or the user
belongs to the user of the file.

We check flags for when euid/egid matches file's. Otherwise we fallback
to access(2), which sucks, but it's the only thing close to working
that exists on unix and has a reasonably portable behavior.