Added wxFile::write_excl and use it from wxTempFile to securely open the
[wxWidgets.git] / src / common / file.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: file.cpp
3 // Purpose: wxFile - encapsulates low-level "file descriptor"
4 // wxTempFile
5 // Author: Vadim Zeitlin
6 // Modified by:
7 // Created: 29/01/98
8 // RCS-ID: $Id$
9 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
12
13 // ----------------------------------------------------------------------------
14 // headers
15 // ----------------------------------------------------------------------------
16
17 #ifdef __GNUG__
18 #pragma implementation "file.h"
19 #endif
20
21 // For compilers that support precompilation, includes "wx.h".
22 #include "wx/wxprec.h"
23
24 #ifdef __BORLANDC__
25 #pragma hdrstop
26 #endif
27
28 #if wxUSE_FILE
29
30 // standard
31 #if defined(__WXMSW__) && !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__WXMICROWIN__)
32 #include <io.h>
33
34 #ifndef __SALFORDC__
35 #define WIN32_LEAN_AND_MEAN
36 #define NOSERVICE
37 #define NOIME
38 #define NOATOM
39 #define NOGDI
40 #define NOGDICAPMASKS
41 #define NOMETAFILE
42 #define NOMINMAX
43 #define NOMSG
44 #define NOOPENFILE
45 #define NORASTEROPS
46 #define NOSCROLL
47 #define NOSOUND
48 #define NOSYSMETRICS
49 #define NOTEXTMETRIC
50 #define NOWH
51 #define NOCOMM
52 #define NOKANJI
53 #define NOCRYPT
54 #define NOMCX
55 #endif
56
57 #include <windows.h> // for GetTempFileName
58 #elif (defined(__UNIX__) || defined(__GNUWIN32__))
59 #include <unistd.h>
60 #ifdef __GNUWIN32__
61 #include <windows.h>
62 #endif
63 #elif (defined(__WXPM__))
64 #include <io.h>
65 #define W_OK 2
66 #define R_OK 4
67 #elif (defined(__WXSTUBS__))
68 // Have to ifdef this for different environments
69 #include <io.h>
70 #elif (defined(__WXMAC__))
71 #if __MSL__ < 0x6000
72 int access( const char *path, int mode ) { return 0 ; }
73 #else
74 int _access( const char *path, int mode ) { return 0 ; }
75 #endif
76 char* mktemp( char * path ) { return path ;}
77 #include <stat.h>
78 #define W_OK 2
79 #define R_OK 4
80 #include <unistd.h>
81 #else
82 #error "Please specify the header with file functions declarations."
83 #endif //Win/UNIX
84
85 #include <stdio.h> // SEEK_xxx constants
86 #include <fcntl.h> // O_RDONLY &c
87
88 #ifndef __MWERKS__
89 #include <sys/types.h> // needed for stat
90 #include <sys/stat.h> // stat
91 #elif ( defined(__MWERKS__) && defined(__WXMSW__) )
92 #include <sys/types.h> // needed for stat
93 #include <sys/stat.h> // stat
94 #endif
95
96 #if defined(__BORLANDC__) || defined(_MSC_VER)
97 #define W_OK 2
98 #define R_OK 4
99 #endif
100
101 // there is no distinction between text and binary files under Unix, so define
102 // O_BINARY as 0 if the system headers don't do it already
103 #if defined(__UNIX__) && !defined(O_BINARY)
104 #define O_BINARY (0)
105 #endif //__UNIX__
106
107 #ifdef __SALFORDC__
108 #include <unix.h>
109 #endif
110
111 #ifndef MAX_PATH
112 #define MAX_PATH 512
113 #endif
114
115 // some broken compilers don't have 3rd argument in open() and creat()
116 #ifdef __SALFORDC__
117 #define ACCESS(access)
118 #define stat _stat
119 #else // normal compiler
120 #define ACCESS(access) , (access)
121 #endif // Salford C
122
123 // wxWindows
124 #include "wx/string.h"
125 #include "wx/intl.h"
126 #include "wx/file.h"
127 #include "wx/log.h"
128
129 // ============================================================================
130 // implementation of wxFile
131 // ============================================================================
132
133 // ----------------------------------------------------------------------------
134 // static functions
135 // ----------------------------------------------------------------------------
136 bool wxFile::Exists(const wxChar *name)
137 {
138 wxStructStat st;
139 #if wxUSE_UNICODE && wxMBFILES
140 wxCharBuffer fname = wxConvFile.cWC2MB(name);
141
142 return !wxAccess(fname, 0) &&
143 !wxStat(wxMBSTRINGCAST fname, &st) &&
144 (st.st_mode & S_IFREG);
145
146 #else
147 return !wxAccess(name, 0) &&
148 !wxStat(name, &st) &&
149 (st.st_mode & S_IFREG);
150 #endif
151 }
152
153 bool wxFile::Access(const wxChar *name, OpenMode mode)
154 {
155 int how = 0;
156
157 switch ( mode ) {
158 case read:
159 how = R_OK;
160 break;
161
162 case write:
163 how = W_OK;
164 break;
165
166 default:
167 wxFAIL_MSG(wxT("bad wxFile::Access mode parameter."));
168 }
169
170 return wxAccess(wxFNCONV(name), how) == 0;
171 }
172
173 // ----------------------------------------------------------------------------
174 // opening/closing
175 // ----------------------------------------------------------------------------
176
177 // ctors
178 wxFile::wxFile(const wxChar *szFileName, OpenMode mode)
179 {
180 m_fd = fd_invalid;
181 m_error = FALSE;
182
183 Open(szFileName, mode);
184 }
185
186 // create the file, fail if it already exists and bOverwrite
187 bool wxFile::Create(const wxChar *szFileName, bool bOverwrite, int accessMode)
188 {
189 // if bOverwrite we create a new file or truncate the existing one,
190 // otherwise we only create the new file and fail if it already exists
191 #if defined(__WXMAC__) && !defined(__UNIX__)
192 // Dominic Mazzoni [dmazzoni+@cs.cmu.edu] reports that open is still broken on the mac, so we replace
193 // int fd = open(wxUnix2MacFilename( szFileName ), O_CREAT | (bOverwrite ? O_TRUNC : O_EXCL), access);
194 int fd = creat( szFileName , accessMode);
195 #else
196 int fd = wxOpen(wxFNCONV(szFileName),
197 O_BINARY | O_WRONLY | O_CREAT |
198 (bOverwrite ? O_TRUNC : O_EXCL)
199 ACCESS(accessMode));
200 #endif
201 if ( fd == -1 ) {
202 wxLogSysError(_("can't create file '%s'"), szFileName);
203 return FALSE;
204 }
205 else {
206 Attach(fd);
207 return TRUE;
208 }
209 }
210
211 // open the file
212 bool wxFile::Open(const wxChar *szFileName, OpenMode mode, int accessMode)
213 {
214 int flags = O_BINARY;
215
216 switch ( mode ) {
217 case read:
218 flags |= O_RDONLY;
219 break;
220
221 case write_append:
222 if ( wxFile::Exists(szFileName) )
223 {
224 flags |= O_WRONLY | O_APPEND;
225 break;
226 }
227 //else: fall through as write_append is the same as write if the
228 // file doesn't exist
229
230 case write:
231 flags |= O_WRONLY | O_CREAT | O_TRUNC;
232 break;
233
234 case write_excl:
235 flags |= O_WRONLY | O_CREAT | O_EXCL;
236 break;
237
238 case read_write:
239 flags |= O_RDWR;
240 break;
241 }
242
243 int fd = wxOpen(wxFNCONV(szFileName), flags ACCESS(accessMode));
244 if ( fd == -1 ) {
245 wxLogSysError(_("can't open file '%s'"), szFileName);
246 return FALSE;
247 }
248 else {
249 Attach(fd);
250 return TRUE;
251 }
252 }
253
254 // close
255 bool wxFile::Close()
256 {
257 if ( IsOpened() ) {
258 if ( close(m_fd) == -1 ) {
259 wxLogSysError(_("can't close file descriptor %d"), m_fd);
260 m_fd = fd_invalid;
261 return FALSE;
262 }
263 else
264 m_fd = fd_invalid;
265 }
266
267 return TRUE;
268 }
269
270 // ----------------------------------------------------------------------------
271 // read/write
272 // ----------------------------------------------------------------------------
273
274 // read
275 off_t wxFile::Read(void *pBuf, off_t nCount)
276 {
277 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
278
279 #ifdef __MWERKS__
280 int iRc = ::read(m_fd, (char*) pBuf, nCount);
281 #else
282 int iRc = ::read(m_fd, pBuf, nCount);
283 #endif
284 if ( iRc == -1 ) {
285 wxLogSysError(_("can't read from file descriptor %d"), m_fd);
286 return wxInvalidOffset;
287 }
288 else
289 return (size_t)iRc;
290 }
291
292 // write
293 size_t wxFile::Write(const void *pBuf, size_t nCount)
294 {
295 wxCHECK( (pBuf != NULL) && IsOpened(), 0 );
296
297 #ifdef __MWERKS__
298 #if __MSL__ >= 0x6000
299 int iRc = ::write(m_fd, (void*) pBuf, nCount);
300 #else
301 int iRc = ::write(m_fd, (const char*) pBuf, nCount);
302 #endif
303 #else
304 int iRc = ::write(m_fd, pBuf, nCount);
305 #endif
306 if ( iRc == -1 ) {
307 wxLogSysError(_("can't write to file descriptor %d"), m_fd);
308 m_error = TRUE;
309 return 0;
310 }
311 else
312 return iRc;
313 }
314
315 // flush
316 bool wxFile::Flush()
317 {
318 if ( IsOpened() ) {
319 #if defined(__VISUALC__) || wxHAVE_FSYNC
320 if ( wxFsync(m_fd) == -1 )
321 {
322 wxLogSysError(_("can't flush file descriptor %d"), m_fd);
323 return FALSE;
324 }
325 #else // no fsync
326 // just do nothing
327 #endif // fsync
328 }
329
330 return TRUE;
331 }
332
333 // ----------------------------------------------------------------------------
334 // seek
335 // ----------------------------------------------------------------------------
336
337 // seek
338 off_t wxFile::Seek(off_t ofs, wxSeekMode mode)
339 {
340 wxASSERT( IsOpened() );
341
342 int origin;
343 switch ( mode ) {
344 default:
345 wxFAIL_MSG(_("unknown seek origin"));
346
347 case wxFromStart:
348 origin = SEEK_SET;
349 break;
350
351 case wxFromCurrent:
352 origin = SEEK_CUR;
353 break;
354
355 case wxFromEnd:
356 origin = SEEK_END;
357 break;
358 }
359
360 int iRc = lseek(m_fd, ofs, origin);
361 if ( iRc == -1 ) {
362 wxLogSysError(_("can't seek on file descriptor %d"), m_fd);
363 return wxInvalidOffset;
364 }
365 else
366 return (off_t)iRc;
367 }
368
369 // get current off_t
370 off_t wxFile::Tell() const
371 {
372 wxASSERT( IsOpened() );
373
374 int iRc = wxTell(m_fd);
375 if ( iRc == -1 ) {
376 wxLogSysError(_("can't get seek position on file descriptor %d"), m_fd);
377 return wxInvalidOffset;
378 }
379 else
380 return (off_t)iRc;
381 }
382
383 // get current file length
384 off_t wxFile::Length() const
385 {
386 wxASSERT( IsOpened() );
387
388 #ifdef __VISUALC__
389 int iRc = _filelength(m_fd);
390 #else // !VC++
391 int iRc = wxTell(m_fd);
392 if ( iRc != -1 ) {
393 // @ have to use const_cast :-(
394 int iLen = ((wxFile *)this)->SeekEnd();
395 if ( iLen != -1 ) {
396 // restore old position
397 if ( ((wxFile *)this)->Seek(iRc) == -1 ) {
398 // error
399 iLen = -1;
400 }
401 }
402
403 iRc = iLen;
404 }
405 #endif // VC++
406
407 if ( iRc == -1 ) {
408 wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
409 return wxInvalidOffset;
410 }
411 else
412 return (off_t)iRc;
413 }
414
415 // is end of file reached?
416 bool wxFile::Eof() const
417 {
418 wxASSERT( IsOpened() );
419
420 int iRc;
421
422 #if defined(__UNIX__) || defined(__GNUWIN32__) || defined( __MWERKS__ ) || defined(__SALFORDC__)
423 // @@ this doesn't work, of course, on unseekable file descriptors
424 off_t ofsCur = Tell(),
425 ofsMax = Length();
426 if ( ofsCur == wxInvalidOffset || ofsMax == wxInvalidOffset )
427 iRc = -1;
428 else
429 iRc = ofsCur == ofsMax;
430 #else // Windows and "native" compiler
431 iRc = eof(m_fd);
432 #endif // Windows/Unix
433
434 switch ( iRc ) {
435 case 1:
436 break;
437
438 case 0:
439 return FALSE;
440
441 case -1:
442 wxLogSysError(_("can't determine if the end of file is reached on descriptor %d"), m_fd);
443 break;
444
445 default:
446 wxFAIL_MSG(_("invalid eof() return value."));
447 }
448
449 return TRUE;
450 }
451
452 // ============================================================================
453 // implementation of wxTempFile
454 // ============================================================================
455
456 // ----------------------------------------------------------------------------
457 // construction
458 // ----------------------------------------------------------------------------
459 wxTempFile::wxTempFile(const wxString& strName)
460 {
461 Open(strName);
462 }
463
464 bool wxTempFile::Open(const wxString& strName)
465 {
466 m_strName = strName;
467
468 // we want to create the file in the same directory as strName because
469 // otherwise rename() in Commit() might not work (if the files are on
470 // different partitions for example). Unfortunately, the only standard
471 // (POSIX) temp file creation function tmpnam() can't do it.
472 #if defined(__UNIX__) || defined(__WXSTUBS__)|| defined( __WXMAC__ )
473 static const wxChar *szMktempSuffix = wxT("XXXXXX");
474 m_strTemp << strName << szMktempSuffix;
475 // can use the cast because length doesn't change
476 mktemp(wxMBSTRINGCAST m_strTemp.mb_str());
477 #elif defined(__WXPM__)
478 // for now just create a file
479 // future enhancements can be to set some extended attributes for file systems
480 // OS/2 supports that have them (HPFS, FAT32) and security (HPFS386)
481 static const wxChar *szMktempSuffix = wxT("XXX");
482 m_strTemp << strName << szMktempSuffix;
483 // Temporarily remove - MN
484 #ifndef __WATCOMC__
485 ::DosCreateDir(m_strTemp.GetWriteBuf(MAX_PATH), NULL);
486 #endif
487 #else // Windows
488 wxString strPath;
489 wxSplitPath(strName, &strPath, NULL, NULL);
490 if ( strPath.IsEmpty() )
491 strPath = wxT('.'); // GetTempFileName will fail if we give it empty string
492 #ifdef __WIN32__
493 if ( !GetTempFileName(strPath, wxT("wx_"),0, m_strTemp.GetWriteBuf(MAX_PATH)) )
494 #else
495 // Not sure why MSVC++ 1.5 header defines first param as BYTE - bug?
496 if ( !GetTempFileName((BYTE) (DWORD)(const wxChar*) strPath, wxT("wx_"),0, m_strTemp.GetWriteBuf(MAX_PATH)) )
497 #endif
498 wxLogLastError(wxT("GetTempFileName"));
499 m_strTemp.UngetWriteBuf();
500 #endif // Windows/Unix
501
502 int access = wxS_DEFAULT;
503 #ifdef __UNIX__
504 // create the file with the same mode as the original one under Unix
505 mode_t umaskOld = 0; // just to suppress compiler warning
506 bool changedUmask;
507
508 wxStructStat st;
509 if ( stat(strName.fn_str(), &st) == 0 )
510 {
511 // this assumes that only lower bits of st_mode contain the access
512 // rights, but it's true for at least all Unices which have S_IXXXX()
513 // macros, so should not be less portable than using (not POSIX)
514 // S_IFREG &c
515 access = st.st_mode & 0777;
516
517 // we want to create the file with exactly the same access rights as
518 // the original one, so disable the user's umask for the moment
519 umaskOld = umask(0);
520 changedUmask = TRUE;
521 }
522 else
523 {
524 // file probably didn't exist, just create with default mode _using_
525 // user's umask (new files creation should respect umask)
526 changedUmask = FALSE;
527 }
528 #endif // Unix
529
530 // Open this file securely, since it surely should not exist unless
531 // nefarious activities (or other random bad things) are at play.
532
533 bool ok = m_file.Open(m_strTemp, wxFile::write_excl, access);
534
535 // FIXME: If !ok here should we loop and try again with another file
536 // name? That is the standard recourse if open(O_EXCL) fails,
537 // though of course it should be protected against possible
538 // infinite looping too.
539
540 #ifdef __UNIX__
541 if ( changedUmask )
542 {
543 // restore umask now that the file is created
544 (void)umask(umaskOld);
545 }
546 #endif // Unix
547
548 return ok;
549 }
550
551 // ----------------------------------------------------------------------------
552 // destruction
553 // ----------------------------------------------------------------------------
554
555 wxTempFile::~wxTempFile()
556 {
557 if ( IsOpened() )
558 Discard();
559 }
560
561 bool wxTempFile::Commit()
562 {
563 m_file.Close();
564
565 if ( wxFile::Exists(m_strName) && wxRemove(m_strName) != 0 ) {
566 wxLogSysError(_("can't remove file '%s'"), m_strName.c_str());
567 return FALSE;
568 }
569
570 if ( wxRename(m_strTemp, m_strName) != 0 ) {
571 wxLogSysError(_("can't commit changes to file '%s'"), m_strName.c_str());
572 return FALSE;
573 }
574
575 return TRUE;
576 }
577
578 void wxTempFile::Discard()
579 {
580 m_file.Close();
581 if ( wxRemove(m_strTemp) != 0 )
582 wxLogSysError(_("can't remove temporary file '%s'"), m_strTemp.c_str());
583 }
584
585 #endif
586