VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/posix/fileio-posix.cpp@ 10634

Last change on this file since 10634 was 10634, checked in by vboxsync, 16 years ago

Runtime: implement Unix access permissions in RTFileOpen

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 17.1 KB
Line 
1/* $Id: fileio-posix.cpp 10634 2008-07-15 09:34:28Z vboxsync $ */
2/** @file
3 * IPRT - File I/O, POSIX.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 *
26 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31
32/*******************************************************************************
33* Header Files *
34*******************************************************************************/
35#define LOG_GROUP RTLOGGROUP_FILE
36
37#include <errno.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40#include <sys/ioctl.h>
41#include <sys/fcntl.h>
42#include <fcntl.h>
43#ifdef _MSC_VER
44# include <io.h>
45# include <stdio.h>
46#else
47# include <unistd.h>
48# include <sys/time.h>
49#endif
50#if defined(RT_OS_OS2) && (!defined(__INNOTEK_LIBC__) || __INNOTEK_LIBC__ < 0x006)
51# include <io.h>
52#endif
53#ifdef RT_OS_L4
54/* This is currently ifdef'ed out in the relevant L4 header file */
55/* Same as `utimes', but takes an open file descriptor instead of a name. */
56extern int futimes(int __fd, __const struct timeval __tvp[2]) __THROW;
57#endif
58
59#ifdef RT_OS_SOLARIS
60# define futimes(filedes, timeval) futimesat(filedes, NULL, timeval)
61#endif
62
63#include <iprt/file.h>
64#include <iprt/path.h>
65#include <iprt/assert.h>
66#include <iprt/string.h>
67#include <iprt/err.h>
68#include <iprt/log.h>
69#include "internal/file.h"
70#include "internal/fs.h"
71#include "internal/path.h"
72
73
74
75/*******************************************************************************
76* Defined Constants And Macros *
77*******************************************************************************/
78/** @def RT_DONT_CONVERT_FILENAMES
79 * Define this to pass UTF-8 unconverted to the kernel. */
80#ifdef __DOXYGEN__
81#define RT_DONT_CONVERT_FILENAMES 1
82#endif
83
84/** Default file permissions for newly created files. */
85#if defined(S_IRUSR) && defined(S_IWUSR)
86# define RT_FILE_PERMISSION (S_IRUSR | S_IWUSR)
87#else
88# define RT_FILE_PERMISSION (00600)
89#endif
90
91
92RTR3DECL(int) RTFileOpen(PRTFILE pFile, const char *pszFilename, unsigned fOpen)
93{
94 /*
95 * Validate input.
96 */
97 if (!VALID_PTR(pFile))
98 {
99 AssertMsgFailed(("Invalid pFile %p\n", pFile));
100 return VERR_INVALID_PARAMETER;
101 }
102 *pFile = NIL_RTFILE;
103 if (!VALID_PTR(pszFilename))
104 {
105 AssertMsgFailed(("Invalid pszFilename %p\n", pszFilename));
106 return VERR_INVALID_PARAMETER;
107 }
108
109 /*
110 * Merge forced open flags and validate them.
111 */
112 int rc = rtFileRecalcAndValidateFlags(&fOpen);
113 if (RT_FAILURE(rc))
114 return rc;
115#ifndef O_NONBLOCK
116 if (fOpen & RTFILE_O_NON_BLOCK)
117 {
118 AssertMsgFailed(("Invalid parameters! fOpen=%#x\n", fOpen));
119 return VERR_INVALID_PARAMETER;
120 }
121#endif
122
123 /*
124 * Calculate open mode flags.
125 */
126 int fOpenMode = 0;
127#ifdef O_BINARY
128 fOpenMode |= O_BINARY; /* (pc) */
129#endif
130#ifdef O_LARGEFILE
131 fOpenMode |= O_LARGEFILE; /* (linux) */
132#endif
133#ifdef O_NOINHERIT
134 if (!(fOpen & RTFILE_O_INHERIT))
135 fOpenMode |= O_NOINHERIT;
136#endif
137#ifdef O_NONBLOCK
138 if (fOpen & RTFILE_O_NON_BLOCK)
139 fOpenMode |= O_NONBLOCK;
140#endif
141#ifdef O_SYNC
142 if (fOpen & RTFILE_O_WRITE_THROUGH)
143 fOpenMode |= O_SYNC;
144#endif
145
146 /* create/truncate file */
147 switch (fOpen & RTFILE_O_ACTION_MASK)
148 {
149 case RTFILE_O_OPEN: break;
150 case RTFILE_O_OPEN_CREATE: fOpenMode |= O_CREAT; break;
151 case RTFILE_O_CREATE: fOpenMode |= O_CREAT | O_EXCL; break;
152 case RTFILE_O_CREATE_REPLACE: fOpenMode |= O_CREAT | O_TRUNC; break; /** @todo replacing needs fixing, this is *not* a 1:1 mapping! */
153 }
154 if (fOpen & RTFILE_O_TRUNCATE)
155 fOpenMode |= O_TRUNC;
156
157 switch (fOpen & RTFILE_O_ACCESS_MASK)
158 {
159 case RTFILE_O_READ: fOpenMode |= O_RDONLY; break;
160 case RTFILE_O_WRITE: fOpenMode |= O_WRONLY; break;
161 case RTFILE_O_READWRITE: fOpenMode |= O_RDWR; break;
162 default:
163 AssertMsgFailed(("RTFileOpen received an invalid RW value, fOpen=%#x\n", fOpen));
164 return VERR_INVALID_PARAMETER;
165 }
166 /* Unix permissions */
167 fOpenMode |= (fOpen & RTFILE_O_CREATE_MODE_MASK) >> RTFILE_O_CREATE_MODE_SHIFT;
168
169 /** @todo sharing! */
170
171 /*
172 * Open/create the file.
173 */
174#ifdef RT_DONT_CONVERT_FILENAMES
175 int fh = open(pszFilename, fOpenMode, RT_FILE_PERMISSION);
176 int iErr = errno;
177#else
178 char *pszNativeFilename;
179 rc = rtPathToNative(&pszNativeFilename, pszFilename);
180 if (RT_FAILURE(rc))
181 return (rc);
182
183 int fh = open(pszNativeFilename, fOpenMode, RT_FILE_PERMISSION);
184 int iErr = errno;
185 rtPathFreeNative(pszNativeFilename);
186#endif
187 if (fh >= 0)
188 {
189 /*
190 * Mark the file handle close on exec, unless inherit is specified.
191 */
192 if ( !(fOpen & RTFILE_O_INHERIT)
193#ifdef O_NOINHERIT
194 || (fOpenMode & O_NOINHERIT) /* careful since it could be a dummy. */
195#endif
196 || fcntl(fh, F_SETFD, FD_CLOEXEC) >= 0)
197 {
198 *pFile = (RTFILE)fh;
199 Assert((int)*pFile == fh);
200 LogFlow(("RTFileOpen(%p:{%RTfile}, %p:{%s}, %#x): returns %Rrc\n",
201 pFile, *pFile, pszFilename, pszFilename, fOpen, rc));
202 return VINF_SUCCESS;
203 }
204 iErr = errno;
205 close(fh);
206 }
207 return RTErrConvertFromErrno(iErr);
208}
209
210
211RTR3DECL(int) RTFileClose(RTFILE File)
212{
213 if (close((int)File) == 0)
214 return VINF_SUCCESS;
215 return RTErrConvertFromErrno(errno);
216}
217
218
219RTR3DECL(int) RTFileFromNative(PRTFILE pFile, RTHCINTPTR uNative)
220{
221 if ( uNative < 0
222 || (RTFILE)uNative != (RTUINTPTR)uNative)
223 {
224 AssertMsgFailed(("%p\n", uNative));
225 *pFile = NIL_RTFILE;
226 return VERR_INVALID_HANDLE;
227 }
228 *pFile = (RTFILE)uNative;
229 return VINF_SUCCESS;
230}
231
232
233RTR3DECL(RTHCINTPTR) RTFileToNative(RTFILE File)
234{
235 AssertReturn(File != NIL_RTFILE, -1);
236 return (RTHCINTPTR)File;
237}
238
239
240RTR3DECL(int) RTFileDelete(const char *pszFilename)
241{
242 char *pszNativeFilename;
243 int rc = rtPathToNative(&pszNativeFilename, pszFilename);
244 if (RT_SUCCESS(rc))
245 {
246 if (unlink(pszNativeFilename) != 0)
247 rc = RTErrConvertFromErrno(errno);
248 rtPathFreeNative(pszNativeFilename);
249 }
250 return rc;
251}
252
253
254RTR3DECL(int) RTFileSeek(RTFILE File, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
255{
256 static const unsigned aSeekRecode[] =
257 {
258 SEEK_SET,
259 SEEK_CUR,
260 SEEK_END,
261 };
262
263 /*
264 * Validate input.
265 */
266 if (uMethod > RTFILE_SEEK_END)
267 {
268 AssertMsgFailed(("Invalid uMethod=%d\n", uMethod));
269 return VERR_INVALID_PARAMETER;
270 }
271
272 /* check that within off_t range. */
273 if ( sizeof(off_t) < sizeof(offSeek)
274 && ( (offSeek > 0 && (unsigned)(offSeek >> 32) != 0)
275 || (offSeek < 0 && (unsigned)(-offSeek >> 32) != 0)))
276 {
277 AssertMsgFailed(("64-bit search not supported\n"));
278 return VERR_NOT_SUPPORTED;
279 }
280
281 off_t offCurrent = lseek((int)File, (off_t)offSeek, aSeekRecode[uMethod]);
282 if (offCurrent != ~0)
283 {
284 if (poffActual)
285 *poffActual = (uint64_t)offCurrent;
286 return VINF_SUCCESS;
287 }
288 return RTErrConvertFromErrno(errno);
289}
290
291
292RTR3DECL(int) RTFileRead(RTFILE File, void *pvBuf, size_t cbToRead, size_t *pcbRead)
293{
294 if (cbToRead <= 0)
295 return VINF_SUCCESS;
296
297 /*
298 * Attempt read.
299 */
300 ssize_t cbRead = read((int)File, pvBuf, cbToRead);
301 if (cbRead >= 0)
302 {
303 if (pcbRead)
304 /* caller can handle partial read. */
305 *pcbRead = cbRead;
306 else
307 {
308 /* Caller expects all to be read. */
309 while ((ssize_t)cbToRead > cbRead)
310 {
311 ssize_t cbReadPart = read((int)File, (char*)pvBuf + cbRead, cbToRead - cbRead);
312 if (cbReadPart <= 0)
313 {
314 if (cbReadPart == 0)
315 return VERR_EOF;
316 return RTErrConvertFromErrno(errno);
317 }
318 cbRead += cbReadPart;
319 }
320 }
321 return VINF_SUCCESS;
322 }
323
324 return RTErrConvertFromErrno(errno);
325}
326
327
328RTR3DECL(int) RTFileWrite(RTFILE File, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
329{
330 if (cbToWrite <= 0)
331 return VINF_SUCCESS;
332
333 /*
334 * Attempt write.
335 */
336 ssize_t cbWritten = write((int)File, pvBuf, cbToWrite);
337 if (cbWritten >= 0)
338 {
339 if (pcbWritten)
340 /* caller can handle partial write. */
341 *pcbWritten = cbWritten;
342 else
343 {
344 /* Caller expects all to be write. */
345 while ((ssize_t)cbToWrite > cbWritten)
346 {
347 ssize_t cbWrittenPart = write((int)File, (const char *)pvBuf + cbWritten, cbToWrite - cbWritten);
348 if (cbWrittenPart <= 0)
349 return RTErrConvertFromErrno(errno);
350 cbWritten += cbWrittenPart;
351 }
352 }
353 return VINF_SUCCESS;
354 }
355 return RTErrConvertFromErrno(errno);
356}
357
358
359RTR3DECL(int) RTFileSetSize(RTFILE File, uint64_t cbSize)
360{
361 /*
362 * Validate offset.
363 */
364 if ( sizeof(off_t) < sizeof(cbSize)
365 && (cbSize >> 32) != 0)
366 {
367 AssertMsgFailed(("64-bit filesize not supported! cbSize=%lld\n", cbSize));
368 return VERR_NOT_SUPPORTED;
369 }
370
371#if defined(_MSC_VER) || (defined(RT_OS_OS2) && (!defined(__INNOTEK_LIBC__) || __INNOTEK_LIBC__ < 0x006))
372 if (chsize((int)File, (off_t)cbSize) == 0)
373#else
374 /* This relies on a non-standard feature of FreeBSD, Linux, and OS/2
375 * LIBC v0.6 and higher. (SuS doesn't define ftruncate() and size bigger
376 * than the file.)
377 */
378 if (ftruncate((int)File, (off_t)cbSize) == 0)
379#endif
380 return VINF_SUCCESS;
381 return RTErrConvertFromErrno(errno);
382}
383
384
385RTR3DECL(int) RTFileGetSize(RTFILE File, uint64_t *pcbSize)
386{
387 struct stat st;
388 if (!fstat((int)File, &st))
389 {
390 *pcbSize = st.st_size;
391 return VINF_SUCCESS;
392 }
393 return RTErrConvertFromErrno(errno);
394}
395
396
397/**
398 * Determine the maximum file size.
399 *
400 * @returns IPRT status code.
401 * @param File Handle to the file.
402 * @param pcbMax Where to store the max file size.
403 * @see RTFileGetMaxSize.
404 */
405RTR3DECL(int) RTFileGetMaxSizeEx(RTFILE File, PRTFOFF pcbMax)
406{
407 /*
408 * Save the current location
409 */
410 uint64_t offOld;
411 int rc = RTFileSeek(File, 0, RTFILE_SEEK_CURRENT, &offOld);
412 if (RT_FAILURE(rc))
413 return rc;
414
415 /*
416 * Perform a binary search for the max file size.
417 */
418 uint64_t offLow = 0;
419 uint64_t offHigh = 8 * _1T; /* we don't need bigger files */
420 /** @todo Unfortunately this does not work for certain file system types,
421 * for instance cifs mounts. Even worse, statvfs.f_fsid returns 0 for such
422 * file systems. */
423 //uint64_t offHigh = INT64_MAX;
424 for (;;)
425 {
426 uint64_t cbInterval = (offHigh - offLow) >> 1;
427 if (cbInterval == 0)
428 {
429 if (pcbMax)
430 *pcbMax = offLow;
431 return RTFileSeek(File, offOld, RTFILE_SEEK_BEGIN, NULL);
432 }
433
434 rc = RTFileSeek(File, offLow + cbInterval, RTFILE_SEEK_BEGIN, NULL);
435 if (RT_FAILURE(rc))
436 offHigh = offLow + cbInterval;
437 else
438 offLow = offLow + cbInterval;
439 }
440}
441
442
443RTR3DECL(bool) RTFileIsValid(RTFILE File)
444{
445 if (File != NIL_RTFILE)
446 {
447 int fFlags = fcntl(File, F_GETFD);
448 if (fFlags >= 0)
449 return true;
450 }
451 return false;
452}
453
454
455RTR3DECL(int) RTFileFlush(RTFILE File)
456{
457 if (fsync((int)File))
458 return RTErrConvertFromErrno(errno);
459 return VINF_SUCCESS;
460}
461
462
463RTR3DECL(int) RTFileIoCtl(RTFILE File, int iRequest, void *pvData, unsigned cbData, int *piRet)
464{
465 int rc = ioctl((int)File, iRequest, pvData);
466 if (piRet)
467 *piRet = rc;
468 return rc >= 0 ? VINF_SUCCESS : RTErrConvertFromErrno(errno);
469}
470
471
472RTR3DECL(int) RTFileQueryInfo(RTFILE File, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAdditionalAttribs)
473{
474 /*
475 * Validate input.
476 */
477 if (File == NIL_RTFILE)
478 {
479 AssertMsgFailed(("Invalid File=%RTfile\n", File));
480 return VERR_INVALID_PARAMETER;
481 }
482 if (!pObjInfo)
483 {
484 AssertMsgFailed(("Invalid pObjInfo=%p\n", pObjInfo));
485 return VERR_INVALID_PARAMETER;
486 }
487 if ( enmAdditionalAttribs < RTFSOBJATTRADD_NOTHING
488 || enmAdditionalAttribs > RTFSOBJATTRADD_LAST)
489 {
490 AssertMsgFailed(("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs));
491 return VERR_INVALID_PARAMETER;
492 }
493
494 /*
495 * Query file info.
496 */
497 struct stat Stat;
498 if (fstat((int)File, &Stat))
499 {
500 int rc = RTErrConvertFromErrno(errno);
501 Log(("RTFileQueryInfo(%RTfile,,%d): returns %Rrc\n", File, enmAdditionalAttribs, rc));
502 return rc;
503 }
504
505 /*
506 * Setup the returned data.
507 */
508 rtFsConvertStatToObjInfo(pObjInfo, &Stat, NULL, 0);
509
510 /*
511 * Requested attributes (we cannot provide anything actually).
512 */
513 switch (enmAdditionalAttribs)
514 {
515 case RTFSOBJATTRADD_EASIZE:
516 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_EASIZE;
517 pObjInfo->Attr.u.EASize.cb = 0;
518 break;
519
520 case RTFSOBJATTRADD_NOTHING:
521 case RTFSOBJATTRADD_UNIX:
522 /* done */
523 break;
524
525 default:
526 AssertMsgFailed(("Impossible!\n"));
527 return VERR_INTERNAL_ERROR;
528 }
529
530 LogFlow(("RTFileQueryInfo(%RTfile,,%d): returns VINF_SUCCESS\n", File, enmAdditionalAttribs));
531 return VINF_SUCCESS;
532}
533
534
535RTR3DECL(int) RTFileSetTimes(RTFILE File, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
536 PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
537{
538 /*
539 * We can only set AccessTime and ModificationTime, so if neither
540 * are specified we can return immediately.
541 */
542 if (!pAccessTime && !pModificationTime)
543 return VINF_SUCCESS;
544
545 /*
546 * Convert the input to timeval, getting the missing one if necessary,
547 * and call the API which does the change.
548 */
549 struct timeval aTimevals[2];
550 if (pAccessTime && pModificationTime)
551 {
552 RTTimeSpecGetTimeval(pAccessTime, &aTimevals[0]);
553 RTTimeSpecGetTimeval(pModificationTime, &aTimevals[1]);
554 }
555 else
556 {
557 RTFSOBJINFO ObjInfo;
558 int rc = RTFileQueryInfo(File, &ObjInfo, RTFSOBJATTRADD_UNIX);
559 if (RT_FAILURE(rc))
560 return rc;
561 RTTimeSpecGetTimeval(pAccessTime ? pAccessTime : &ObjInfo.AccessTime, &aTimevals[0]);
562 RTTimeSpecGetTimeval(pModificationTime ? pModificationTime : &ObjInfo.ModificationTime, &aTimevals[1]);
563 }
564
565 if (futimes((int)File, aTimevals))
566 {
567 int rc = RTErrConvertFromErrno(errno);
568 Log(("RTFileSetTimes(%RTfile,%p,%p,,): returns %Rrc\n", File, pAccessTime, pModificationTime, rc));
569 return rc;
570 }
571 return VINF_SUCCESS;
572}
573
574
575RTR3DECL(int) RTFileSetMode(RTFILE File, RTFMODE fMode)
576{
577 /*
578 * Normalize the mode and call the API.
579 */
580 fMode = rtFsModeNormalize(fMode, NULL, 0);
581 if (!rtFsModeIsValid(fMode))
582 return VERR_INVALID_PARAMETER;
583
584 if (fchmod((int)File, fMode & RTFS_UNIX_MASK))
585 {
586 int rc = RTErrConvertFromErrno(errno);
587 Log(("RTFileSetMode(%RTfile,%RTfmode): returns %Rrc\n", File, fMode));
588 return rc;
589 }
590 return VINF_SUCCESS;
591}
592
593
594RTR3DECL(int) RTFileRename(const char *pszSrc, const char *pszDst, unsigned fRename)
595{
596 /*
597 * Validate input.
598 */
599 AssertMsgReturn(VALID_PTR(pszSrc), ("%p\n", pszSrc), VERR_INVALID_POINTER);
600 AssertMsgReturn(VALID_PTR(pszDst), ("%p\n", pszDst), VERR_INVALID_POINTER);
601 AssertMsgReturn(*pszSrc, ("%p\n", pszSrc), VERR_INVALID_PARAMETER);
602 AssertMsgReturn(*pszDst, ("%p\n", pszDst), VERR_INVALID_PARAMETER);
603 AssertMsgReturn(!(fRename & ~RTPATHRENAME_FLAGS_REPLACE), ("%#x\n", fRename), VERR_INVALID_PARAMETER);
604
605 /*
606 * Take common cause with RTPathRename.
607 */
608 int rc = rtPathPosixRename(pszSrc, pszDst, fRename, RTFS_TYPE_FILE);
609
610 LogFlow(("RTDirRename(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n",
611 pszSrc, pszSrc, pszDst, pszDst, fRename, rc));
612 return rc;
613}
614
615
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette