User: Password:
|
|
Subscribe / Log in / New account

No easy solution with fopen()

No easy solution with fopen()

Posted Sep 20, 2007 14:19 UTC (Thu) by dwheeler (guest, #1216)
In reply to: Exploiting symlinks and tmpfiles by intgr
Parent article: Exploiting symlinks and tmpfiles

You're correct, there is NO easy solution with fopen(). I believe that there should be work to modify the standards to create an additional option character (just as "b" is a flag for "binary" on some systems), but it'd be a fair amount of work to get it through the standards process.


(Log in to post comments)

Actually, there is an easy solution with fopen()

Posted Sep 20, 2007 16:29 UTC (Thu) by hummassa (subscriber, #307) [Link]

I tested it on linux, works ok -- except for the fact that it WILL clobber an empty file:
  
FILE* open_only_if_does_not_exist(const char *filename) {   
  FILE* f = fopen(filename, "a");   
  if( ftell(f) ) {   
    fclose(f);   
    return 0;   
  }   
  return f;   
}   

Actually, there is an easy solution with fopen()

Posted Sep 20, 2007 18:45 UTC (Thu) by vmole (guest, #111) [Link]

...except for the fact that it WILL clobber an empty file

So, in other words, it doesn't do what the function name claims. Not to mention no error checking on the fopen() call. Yeah, I know, it's just psuedo-code in a comment. But since the whole article is about correct code without security holes, I'm being a dick about it.

Anyway, it pointless to try to do this within the C standard. If you don't have POSIX calls (open(), fdopen()), then you don't have POSIX file system semantics, so you've got no guarantees anyway. For temporary files, use tmpfile(). If your OS/library doesn't have tmpfile() (which means it's not even C89), implement it using whatever OS specific tools are necessary. For non-temporary but unique files, the most general technique looks to be mkstemp() and rename(), but I'd guess plain old open()/fdopen() is just as well supported.


Copyright © 2017, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds