* Igor Gavriloff <igor@nupes.cefetpr.br> [001016 15:16] wrote:
> Hi,
>
> I'm trying to write a function in C that I can load into postgres,
> that basically removes a file from the system (quite unsafe thought, but
> it'll be suitable for me here):
>
> #include <postgres.h>
> #include <stdio.h>
>
> bool file_remove(text *this)
> {
> if (remove((char *)this) == 0) return (true);
> else return (false);
> }
>
> I compile it and link as instructed for Solaris (where the backend
> runs), and load it with:
>
> CREATE FUNCTION file_remove(text) RETURNS bool AS '/path/file_remove.so'
> LANGUAGE 'c';
>
> But it always returns false when I try to remove something. I'm sure
> that I'm trying to remove files that the the backend's user owns (have
> write access). If I try to make any changes on this code (eg.: the
> casts...), when I try to use it the backends terminates abnormally.
> Does someone can give me a clue?
from pgsql/src/includes/c.h:
* BTW: when you need to copy a non-null-terminated string (like a text* datum) and add a null, do not do it
withStrNCpy(..., len+1). That* might seem to work, but it fetches one byte more than there is in the* text
object. One fine day you'll have a SIGSEGV because there isn't* another byte before the end of memory. Don't
laugh,we've had real* live bug reports from real live users over exactly this mistake.* Do it honestly with
"memcpy(dst,src,len);dst[len] = '\0';", instead.
from postgres.h:
struct varlena
{ int32 vl_len; char vl_dat[1];
};
typedef struct varlena text;
so it seems that 'text' is not a char *, you'll probably want to
use malloc and a memcpy to make a proper C string from a 'text'
object.
had you thought of running a debugger or looking at the struct
definitions before doing such a dangerous cast?
--
-Alfred Perlstein - [bright@wintelcom.net|alfred@freebsd.org]
"I have the heart of a child; I keep it in a jar on my desk."