The readlink() function reads where a link points to.
the function with its arguments is:
readlink(link, buf, len);
Non-Compliant Solution
readlink() never 0-terminates by itself, so you have to do it by yourself. People often seem to forget this, leading to infoleaks or sometimes memory corruption.
another thing people like to do is:
len = readlink(link, buf, sizeof(buf)); buf[len] = '\0';
There are two problems here, readlink() can return -1 if it fails and hence causing an off-by-one underflow, so always check the readlink return value. The other problem that can occur is that readlink returns how many byted got written to the buffer, in this case it can write up to sizeof(buf) bytes. if it does you basicly end up doing:
bufsizeof(buf) = '\0'; which is an off-by-one overflow.
Compliant Solution
#include <unistd.h> char buf[1024]; ssizet_t len; ... if ((len = readlink("/modules/pass1", buf, sizeof(buf)-1)) != -1) buf[len] = '\0';
References
- ilja's blog readlink abuse. http://blogs.23.nu/ilja/stories/12551/
- The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004 Edition http://www.opengroup.org/onlinepubs/000095399/functions/readlink.html
- The Single UNIX ® Specification, Version 2 http://www.opengroup.org/pubs/online/7908799/xsh/readlink.html