VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/posix/dir-posix.cpp@ 70760

Last change on this file since 70760 was 69753, checked in by vboxsync, 7 years ago

iprt/dir: Morphing PRTDIR into a handle named RTDIR. (Been wanting to correct this for years. Don't know why I makde it a pointer rather than an abstrct handle like everything else.)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 18.8 KB
Line 
1/* $Id: dir-posix.cpp 69753 2017-11-19 14:27:58Z vboxsync $ */
2/** @file
3 * IPRT - Directory manipulation, POSIX.
4 */
5
6/*
7 * Copyright (C) 2006-2017 Oracle Corporation
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
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#define LOG_GROUP RTLOGGROUP_DIR
32#include <errno.h>
33#include <unistd.h>
34#include <sys/types.h>
35#include <sys/stat.h>
36#include <fcntl.h>
37#include <dirent.h>
38#include <stdio.h>
39
40#include <iprt/dir.h>
41#include "internal/iprt.h"
42
43#include <iprt/alloca.h>
44#include <iprt/assert.h>
45#include <iprt/err.h>
46#include <iprt/log.h>
47#include <iprt/mem.h>
48#include <iprt/param.h>
49#include <iprt/path.h>
50#include <iprt/string.h>
51#include "internal/dir.h"
52#include "internal/fs.h"
53#include "internal/path.h"
54
55#if !defined(RT_OS_SOLARIS) && !defined(RT_OS_HAIKU)
56# define HAVE_DIRENT_D_TYPE 1
57#endif
58
59
60RTDECL(bool) RTDirExists(const char *pszPath)
61{
62 bool fRc = false;
63 char const *pszNativePath;
64 int rc = rtPathToNative(&pszNativePath, pszPath, NULL);
65 if (RT_SUCCESS(rc))
66 {
67 struct stat s;
68 fRc = !stat(pszNativePath, &s)
69 && S_ISDIR(s.st_mode);
70
71 rtPathFreeNative(pszNativePath, pszPath);
72 }
73
74 LogFlow(("RTDirExists(%p={%s}): returns %RTbool\n", pszPath, pszPath, fRc));
75 return fRc;
76}
77
78
79RTDECL(int) RTDirCreate(const char *pszPath, RTFMODE fMode, uint32_t fCreate)
80{
81 RT_NOREF_PV(fCreate);
82
83 int rc;
84 fMode = rtFsModeNormalize(fMode, pszPath, 0);
85 if (rtFsModeIsValidPermissions(fMode))
86 {
87 char const *pszNativePath;
88 rc = rtPathToNative(&pszNativePath, pszPath, NULL);
89 if (RT_SUCCESS(rc))
90 {
91 if (mkdir(pszNativePath, fMode & RTFS_UNIX_MASK))
92 {
93 rc = errno;
94 bool fVerifyIsDir = true;
95#ifdef RT_OS_SOLARIS
96 /*
97 * mkdir on nfs mount points has been/is busted in various
98 * during the Nevada development cycle. We've observed:
99 * - Build 111b (2009.06) returns EACCES.
100 * - Build ca. 70-80 returns ENOSYS.
101 */
102 if ( rc == ENOSYS
103 || rc == EACCES)
104 {
105 rc = RTErrConvertFromErrno(rc);
106 fVerifyIsDir = false; /* We'll check if it's a dir ourselves since we're going to stat() anyway. */
107 struct stat st;
108 if (!stat(pszNativePath, &st))
109 {
110 rc = VERR_ALREADY_EXISTS;
111 if (!S_ISDIR(st.st_mode))
112 rc = VERR_IS_A_FILE;
113 }
114 }
115 else
116 rc = RTErrConvertFromErrno(rc);
117#else
118 rc = RTErrConvertFromErrno(rc);
119#endif
120 if ( rc == VERR_ALREADY_EXISTS
121 && fVerifyIsDir == true)
122 {
123 /*
124 * Verify that it really exists as a directory.
125 */
126 struct stat st;
127 if (!stat(pszNativePath, &st) && !S_ISDIR(st.st_mode))
128 rc = VERR_IS_A_FILE;
129 }
130 }
131 }
132
133 rtPathFreeNative(pszNativePath, pszPath);
134 }
135 else
136 {
137 AssertMsgFailed(("Invalid file mode! %RTfmode\n", fMode));
138 rc = VERR_INVALID_FMODE;
139 }
140 LogFlow(("RTDirCreate(%p={%s}, %RTfmode): returns %Rrc\n", pszPath, pszPath, fMode, rc));
141 return rc;
142}
143
144
145RTDECL(int) RTDirRemove(const char *pszPath)
146{
147 char const *pszNativePath;
148 int rc = rtPathToNative(&pszNativePath, pszPath, NULL);
149 if (RT_SUCCESS(rc))
150 {
151 if (rmdir(pszNativePath))
152 rc = RTErrConvertFromErrno(errno);
153
154 rtPathFreeNative(pszNativePath, pszPath);
155 }
156
157 LogFlow(("RTDirRemove(%p={%s}): returns %Rrc\n", pszPath, pszPath, rc));
158 return rc;
159}
160
161
162RTDECL(int) RTDirFlush(const char *pszPath)
163{
164 /*
165 * Linux: The fsync() man page hints at this being required for ensuring
166 * consistency between directory and file in case of a crash.
167 *
168 * Solaris: No mentioned is made of directories on the fsync man page.
169 * While rename+fsync will do what we want on ZFS, the code needs more
170 * careful studying wrt whether the directory entry of a new file is
171 * implicitly synced when the file is synced (it's very likely for ZFS).
172 *
173 * FreeBSD: The FFS fsync code seems to flush the directory entry as well
174 * in some cases. Don't know exactly what's up with rename, but from the
175 * look of things fsync(dir) should work.
176 */
177 int rc;
178#ifdef O_DIRECTORY
179 int fd = open(pszPath, O_RDONLY | O_DIRECTORY, 0);
180#else
181 int fd = open(pszPath, O_RDONLY, 0);
182#endif
183 if (fd >= 0)
184 {
185 if (fsync(fd) == 0)
186 rc = VINF_SUCCESS;
187 else
188 {
189 /* Linux fsync(2) man page documents both errors as an indication
190 * that the file descriptor can't be flushed (seen EINVAL for usual
191 * directories on CIFS). BSD (OS X) fsync(2) documents only the
192 * latter, and Solaris fsync(3C) pretends there is no problem. */
193 if (errno == EROFS || errno == EINVAL)
194 rc = VERR_NOT_SUPPORTED;
195 else
196 rc = RTErrConvertFromErrno(errno);
197 }
198 close(fd);
199 }
200 else
201 rc = RTErrConvertFromErrno(errno);
202 return rc;
203}
204
205
206size_t rtDirNativeGetStructSize(const char *pszPath)
207{
208 long cbNameMax = pathconf(pszPath, _PC_NAME_MAX);
209# ifdef NAME_MAX
210 if (cbNameMax < NAME_MAX) /* This is plain paranoia, but it doesn't hurt. */
211 cbNameMax = NAME_MAX;
212# endif
213# ifdef _XOPEN_NAME_MAX
214 if (cbNameMax < _XOPEN_NAME_MAX) /* Ditto. */
215 cbNameMax = _XOPEN_NAME_MAX;
216# endif
217 size_t cbDir = RT_OFFSETOF(RTDIRINTERNAL, Data.d_name[cbNameMax + 1]);
218 if (cbDir < sizeof(RTDIRINTERNAL)) /* Ditto. */
219 cbDir = sizeof(RTDIRINTERNAL);
220 cbDir = RT_ALIGN_Z(cbDir, 8);
221
222 return cbDir;
223}
224
225
226int rtDirNativeOpen(PRTDIRINTERNAL pDir, char *pszPathBuf, uintptr_t hRelativeDir, void *pvNativeRelative)
227{
228 NOREF(pszPathBuf); /* only used on windows */
229 NOREF(hRelativeDir);
230 NOREF(pvNativeRelative);
231
232 /*
233 * Convert to a native path and try opendir.
234 */
235 char const *pszNativePath;
236 int rc = rtPathToNative(&pszNativePath, pDir->pszPath, NULL);
237 if (RT_SUCCESS(rc))
238 {
239 pDir->pDir = opendir(pszNativePath);
240 if (pDir->pDir)
241 {
242 /*
243 * Init data (allocated as all zeros).
244 */
245 pDir->fDataUnread = false; /* spelling it out */
246 }
247 else
248 rc = RTErrConvertFromErrno(errno);
249
250 rtPathFreeNative(pszNativePath, pDir->pszPath);
251 }
252
253 return rc;
254}
255
256
257RTDECL(int) RTDirClose(RTDIR hDir)
258{
259 PRTDIRINTERNAL pDir = hDir;
260
261 /*
262 * Validate input.
263 */
264 if (!pDir)
265 return VERR_INVALID_PARAMETER;
266 if (pDir->u32Magic != RTDIR_MAGIC)
267 {
268 AssertMsgFailed(("Invalid pDir=%p\n", pDir));
269 return VERR_INVALID_PARAMETER;
270 }
271
272 /*
273 * Close the handle.
274 */
275 int rc = VINF_SUCCESS;
276 pDir->u32Magic = RTDIR_MAGIC_DEAD;
277 if (closedir(pDir->pDir))
278 {
279 rc = RTErrConvertFromErrno(errno);
280 AssertMsgFailed(("closedir(%p) -> errno=%d (%Rrc)\n", pDir->pDir, errno, rc));
281 }
282
283 RTMemFree(pDir);
284 return rc;
285}
286
287
288/**
289 * Ensure that there is unread data in the buffer
290 * and that there is a converted filename hanging around.
291 *
292 * @returns IPRT status code.
293 * @param pDir the open directory. Fully validated.
294 */
295static int rtDirReadMore(PRTDIRINTERNAL pDir)
296{
297 /** @todo try avoid the rematching on buffer overflow errors. */
298 for (;;)
299 {
300 /*
301 * Fetch data?
302 */
303 if (!pDir->fDataUnread)
304 {
305 struct dirent *pResult = NULL;
306#if RT_GNUC_PREREQ(4, 6)
307# pragma GCC diagnostic push
308# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
309#endif
310 int rc = readdir_r(pDir->pDir, &pDir->Data, &pResult);
311#if RT_GNUC_PREREQ(4, 6)
312# pragma GCC diagnostic pop
313#endif
314 if (rc)
315 {
316 rc = RTErrConvertFromErrno(rc);
317 /** @todo Consider translating ENOENT (The current
318 * position of the directory stream is invalid)
319 * differently. */
320 AssertMsg(rc == VERR_FILE_NOT_FOUND, ("%Rrc\n", rc));
321 return rc;
322 }
323 if (!pResult)
324 return VERR_NO_MORE_FILES;
325 }
326
327 /*
328 * Convert the filename to UTF-8.
329 */
330 if (!pDir->pszName)
331 {
332 int rc = rtPathFromNative(&pDir->pszName, pDir->Data.d_name, pDir->pszPath);
333 if (RT_FAILURE(rc))
334 {
335 pDir->pszName = NULL;
336 return rc;
337 }
338 pDir->cchName = strlen(pDir->pszName);
339 }
340 if ( !pDir->pfnFilter
341 || pDir->pfnFilter(pDir, pDir->pszName))
342 break;
343 rtPathFreeIprt(pDir->pszName, pDir->Data.d_name);
344 pDir->pszName = NULL;
345 pDir->fDataUnread = false;
346 }
347
348 pDir->fDataUnread = true;
349 return VINF_SUCCESS;
350}
351
352
353#ifdef HAVE_DIRENT_D_TYPE
354/**
355 * Converts the d_type field to IPRT directory entry type.
356 *
357 * @returns IPRT directory entry type.
358 * @param Unix
359 */
360static RTDIRENTRYTYPE rtDirType(int iType)
361{
362 switch (iType)
363 {
364 case DT_UNKNOWN: return RTDIRENTRYTYPE_UNKNOWN;
365 case DT_FIFO: return RTDIRENTRYTYPE_FIFO;
366 case DT_CHR: return RTDIRENTRYTYPE_DEV_CHAR;
367 case DT_DIR: return RTDIRENTRYTYPE_DIRECTORY;
368 case DT_BLK: return RTDIRENTRYTYPE_DEV_BLOCK;
369 case DT_REG: return RTDIRENTRYTYPE_FILE;
370 case DT_LNK: return RTDIRENTRYTYPE_SYMLINK;
371 case DT_SOCK: return RTDIRENTRYTYPE_SOCKET;
372 case DT_WHT: return RTDIRENTRYTYPE_WHITEOUT;
373 default:
374 AssertMsgFailed(("iType=%d\n", iType));
375 return RTDIRENTRYTYPE_UNKNOWN;
376 }
377}
378#endif /*HAVE_DIRENT_D_TYPE */
379
380
381RTDECL(int) RTDirRead(RTDIR hDir, PRTDIRENTRY pDirEntry, size_t *pcbDirEntry)
382{
383 PRTDIRINTERNAL pDir = hDir;
384
385 /*
386 * Validate and digest input.
387 */
388 if (!rtDirValidHandle(pDir))
389 return VERR_INVALID_PARAMETER;
390 AssertMsgReturn(VALID_PTR(pDirEntry), ("%p\n", pDirEntry), VERR_INVALID_POINTER);
391
392 size_t cbDirEntry = sizeof(*pDirEntry);
393 if (pcbDirEntry)
394 {
395 AssertMsgReturn(VALID_PTR(pcbDirEntry), ("%p\n", pcbDirEntry), VERR_INVALID_POINTER);
396 cbDirEntry = *pcbDirEntry;
397 AssertMsgReturn(cbDirEntry >= RT_UOFFSETOF(RTDIRENTRY, szName[2]),
398 ("Invalid *pcbDirEntry=%d (min %d)\n", *pcbDirEntry, RT_OFFSETOF(RTDIRENTRYEX, szName[2])),
399 VERR_INVALID_PARAMETER);
400 }
401
402 /*
403 * Fetch more data if necessary and/or convert the name.
404 */
405 int rc = rtDirReadMore(pDir);
406 if (RT_SUCCESS(rc))
407 {
408 /*
409 * Check if we've got enough space to return the data.
410 */
411 const char *pszName = pDir->pszName;
412 const size_t cchName = pDir->cchName;
413 const size_t cbRequired = RT_OFFSETOF(RTDIRENTRY, szName[1]) + cchName;
414 if (pcbDirEntry)
415 *pcbDirEntry = cbRequired;
416 if (cbRequired <= cbDirEntry)
417 {
418 /*
419 * Setup the returned data.
420 */
421 pDirEntry->INodeId = pDir->Data.d_ino; /* may need #ifdefing later */
422#ifdef HAVE_DIRENT_D_TYPE
423 pDirEntry->enmType = rtDirType(pDir->Data.d_type);
424#else
425 pDirEntry->enmType = RTDIRENTRYTYPE_UNKNOWN;
426#endif
427 pDirEntry->cbName = (uint16_t)cchName;
428 Assert(pDirEntry->cbName == cchName);
429 memcpy(pDirEntry->szName, pszName, cchName + 1);
430
431 /* free cached data */
432 pDir->fDataUnread = false;
433 rtPathFreeIprt(pDir->pszName, pDir->Data.d_name);
434 pDir->pszName = NULL;
435 }
436 else
437 rc = VERR_BUFFER_OVERFLOW;
438 }
439
440 LogFlow(("RTDirRead(%p:{%s}, %p:{%s}, %p:{%u}): returns %Rrc\n",
441 pDir, pDir->pszPath, pDirEntry, RT_SUCCESS(rc) ? pDirEntry->szName : "<failed>",
442 pcbDirEntry, pcbDirEntry ? *pcbDirEntry : 0, rc));
443 return rc;
444}
445
446
447/**
448 * Fills dummy info into the info structure.
449 * This function is called if we cannot stat the file.
450 *
451 * @param pInfo The struct in question.
452 * @param
453 */
454static void rtDirSetDummyInfo(PRTFSOBJINFO pInfo, RTDIRENTRYTYPE enmType)
455{
456 pInfo->cbObject = 0;
457 pInfo->cbAllocated = 0;
458 RTTimeSpecSetNano(&pInfo->AccessTime, 0);
459 RTTimeSpecSetNano(&pInfo->ModificationTime, 0);
460 RTTimeSpecSetNano(&pInfo->ChangeTime, 0);
461 RTTimeSpecSetNano(&pInfo->BirthTime, 0);
462 memset(&pInfo->Attr, 0, sizeof(pInfo->Attr));
463 pInfo->Attr.enmAdditional = RTFSOBJATTRADD_NOTHING;
464 switch (enmType)
465 {
466 default:
467 case RTDIRENTRYTYPE_UNKNOWN: pInfo->Attr.fMode = RTFS_DOS_NT_NORMAL; break;
468 case RTDIRENTRYTYPE_FIFO: pInfo->Attr.fMode = RTFS_DOS_NT_NORMAL | RTFS_TYPE_FIFO; break;
469 case RTDIRENTRYTYPE_DEV_CHAR: pInfo->Attr.fMode = RTFS_DOS_NT_NORMAL | RTFS_TYPE_DEV_CHAR; break;
470 case RTDIRENTRYTYPE_DIRECTORY: pInfo->Attr.fMode = RTFS_DOS_DIRECTORY | RTFS_TYPE_DIRECTORY; break;
471 case RTDIRENTRYTYPE_DEV_BLOCK: pInfo->Attr.fMode = RTFS_DOS_NT_NORMAL | RTFS_TYPE_DEV_BLOCK; break;
472 case RTDIRENTRYTYPE_FILE: pInfo->Attr.fMode = RTFS_DOS_NT_NORMAL | RTFS_TYPE_FILE; break;
473 case RTDIRENTRYTYPE_SYMLINK: pInfo->Attr.fMode = RTFS_DOS_NT_NORMAL | RTFS_TYPE_SYMLINK; break;
474 case RTDIRENTRYTYPE_SOCKET: pInfo->Attr.fMode = RTFS_DOS_NT_NORMAL | RTFS_TYPE_SOCKET; break;
475 case RTDIRENTRYTYPE_WHITEOUT: pInfo->Attr.fMode = RTFS_DOS_NT_NORMAL | RTFS_TYPE_WHITEOUT; break;
476 }
477}
478
479
480RTDECL(int) RTDirReadEx(RTDIR hDir, PRTDIRENTRYEX pDirEntry, size_t *pcbDirEntry,
481 RTFSOBJATTRADD enmAdditionalAttribs, uint32_t fFlags)
482{
483 PRTDIRINTERNAL pDir = hDir;
484
485 /*
486 * Validate and digest input.
487 */
488 if (!rtDirValidHandle(pDir))
489 return VERR_INVALID_PARAMETER;
490 AssertMsgReturn(VALID_PTR(pDirEntry), ("%p\n", pDirEntry), VERR_INVALID_POINTER);
491 AssertMsgReturn( enmAdditionalAttribs >= RTFSOBJATTRADD_NOTHING
492 && enmAdditionalAttribs <= RTFSOBJATTRADD_LAST,
493 ("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs),
494 VERR_INVALID_PARAMETER);
495 AssertMsgReturn(RTPATH_F_IS_VALID(fFlags, 0), ("%#x\n", fFlags), VERR_INVALID_PARAMETER);
496 size_t cbDirEntry = sizeof(*pDirEntry);
497 if (pcbDirEntry)
498 {
499 AssertMsgReturn(VALID_PTR(pcbDirEntry), ("%p\n", pcbDirEntry), VERR_INVALID_POINTER);
500 cbDirEntry = *pcbDirEntry;
501 AssertMsgReturn(cbDirEntry >= (unsigned)RT_OFFSETOF(RTDIRENTRYEX, szName[2]),
502 ("Invalid *pcbDirEntry=%d (min %d)\n", *pcbDirEntry, RT_OFFSETOF(RTDIRENTRYEX, szName[2])),
503 VERR_INVALID_PARAMETER);
504 }
505
506 /*
507 * Fetch more data if necessary and/or convert the name.
508 */
509 int rc = rtDirReadMore(pDir);
510 if (RT_SUCCESS(rc))
511 {
512 /*
513 * Check if we've got enough space to return the data.
514 */
515 const char *pszName = pDir->pszName;
516 const size_t cchName = pDir->cchName;
517 const size_t cbRequired = RT_OFFSETOF(RTDIRENTRYEX, szName[1]) + cchName;
518 if (pcbDirEntry)
519 *pcbDirEntry = cbRequired;
520 if (cbRequired <= cbDirEntry)
521 {
522 /*
523 * Setup the returned data.
524 */
525 pDirEntry->cwcShortName = 0;
526 pDirEntry->wszShortName[0] = 0;
527 pDirEntry->cbName = (uint16_t)cchName;
528 Assert(pDirEntry->cbName == cchName);
529 memcpy(pDirEntry->szName, pszName, cchName + 1);
530
531 /* get the info data */
532 size_t cch = cchName + pDir->cchPath + 1;
533 char *pszNamePath = (char *)alloca(cch);
534 if (pszNamePath)
535 {
536 memcpy(pszNamePath, pDir->pszPath, pDir->cchPath);
537 memcpy(pszNamePath + pDir->cchPath, pszName, cchName + 1);
538 rc = RTPathQueryInfoEx(pszNamePath, &pDirEntry->Info, enmAdditionalAttribs, fFlags);
539 }
540 else
541 rc = VERR_NO_MEMORY;
542 if (RT_FAILURE(rc))
543 {
544#ifdef HAVE_DIRENT_D_TYPE
545 rtDirSetDummyInfo(&pDirEntry->Info, rtDirType(pDir->Data.d_type));
546#else
547 rtDirSetDummyInfo(&pDirEntry->Info, RTDIRENTRYTYPE_UNKNOWN);
548#endif
549 rc = VWRN_NO_DIRENT_INFO;
550 }
551
552 /* free cached data */
553 pDir->fDataUnread = false;
554 rtPathFreeIprt(pDir->pszName, pDir->Data.d_name);
555 pDir->pszName = NULL;
556 }
557 else
558 rc = VERR_BUFFER_OVERFLOW;
559 }
560
561 return rc;
562}
563
564
565RTDECL(int) RTDirRename(const char *pszSrc, const char *pszDst, unsigned fRename)
566{
567 /*
568 * Validate input.
569 */
570 AssertMsgReturn(VALID_PTR(pszSrc), ("%p\n", pszSrc), VERR_INVALID_POINTER);
571 AssertMsgReturn(VALID_PTR(pszDst), ("%p\n", pszDst), VERR_INVALID_POINTER);
572 AssertMsgReturn(*pszSrc, ("%p\n", pszSrc), VERR_INVALID_PARAMETER);
573 AssertMsgReturn(*pszDst, ("%p\n", pszDst), VERR_INVALID_PARAMETER);
574 AssertMsgReturn(!(fRename & ~RTPATHRENAME_FLAGS_REPLACE), ("%#x\n", fRename), VERR_INVALID_PARAMETER);
575
576 /*
577 * Take common cause with RTPathRename.
578 */
579 int rc = rtPathPosixRename(pszSrc, pszDst, fRename, RTFS_TYPE_DIRECTORY);
580
581 LogFlow(("RTDirRename(%p:{%s}, %p:{%s}): returns %Rrc\n",
582 pszSrc, pszSrc, pszDst, pszDst, rc));
583 return rc;
584}
585
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