VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/win/path-win.cpp@ 15755

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

Runtime/Windows: RTPathAbs: Truncate the trailing slash of a non-root path for compatibility with the POSIX version.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 18.0 KB
Line 
1/* $Id: path-win.cpp 15755 2008-12-25 10:53:52Z vboxsync $ */
2/** @file
3 * IPRT - Path manipulation.
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_PATH
36#include <Windows.h>
37
38#include <iprt/path.h>
39#include <iprt/assert.h>
40#include <iprt/string.h>
41#include <iprt/time.h>
42#include <iprt/mem.h>
43#include <iprt/param.h>
44#include <iprt/log.h>
45#include <iprt/err.h>
46#include "internal/path.h"
47#include "internal/fs.h"
48
49
50/**
51 * Get the real (no symlinks, no . or .. components) path, must exist.
52 *
53 * @returns iprt status code.
54 * @param pszPath The path to resolve.
55 * @param pszRealPath Where to store the real path.
56 * @param cchRealPath Size of the buffer.
57 */
58RTDECL(int) RTPathReal(const char *pszPath, char *pszRealPath, size_t cchRealPath)
59{
60 /*
61 * Convert to UTF-16, call Win32 APIs, convert back.
62 */
63 PRTUTF16 pwszPath;
64 int rc = RTStrToUtf16(pszPath, &pwszPath);
65 if (!RT_SUCCESS(rc))
66 return (rc);
67
68 LPWSTR lpFile;
69 WCHAR wsz[RTPATH_MAX];
70 rc = GetFullPathNameW((LPCWSTR)pwszPath, RT_ELEMENTS(wsz), &wsz[0], &lpFile);
71 if (rc > 0 && rc < RT_ELEMENTS(wsz))
72 {
73 /* Check that it exists. (Use RTPathAbs() to just resolve the name.) */
74 DWORD dwAttr = GetFileAttributesW(wsz);
75 if (dwAttr != INVALID_FILE_ATTRIBUTES)
76 rc = RTUtf16ToUtf8Ex((PRTUTF16)&wsz[0], RTSTR_MAX, &pszRealPath, cchRealPath, NULL);
77 else
78 rc = RTErrConvertFromWin32(GetLastError());
79 }
80 else if (rc <= 0)
81 rc = RTErrConvertFromWin32(GetLastError());
82 else
83 rc = VERR_FILENAME_TOO_LONG;
84
85 RTUtf16Free(pwszPath);
86
87 return rc;
88}
89
90
91/**
92 * Get the absolute path (no symlinks, no . or .. components), doesn't have to exit.
93 *
94 * @returns iprt status code.
95 * @param pszPath The path to resolve.
96 * @param pszAbsPath Where to store the absolute path.
97 * @param cchAbsPath Size of the buffer.
98 */
99RTDECL(int) RTPathAbs(const char *pszPath, char *pszAbsPath, size_t cchAbsPath)
100{
101 /*
102 * Convert to UTF-16, call Win32 API, convert back.
103 */
104 LPWSTR pwszPath;
105 int rc = RTStrToUtf16(pszPath, &pwszPath);
106 if (!RT_SUCCESS(rc))
107 return (rc);
108
109 LPWSTR pwszFile; /* Ignored */
110 RTUTF16 wsz[RTPATH_MAX];
111 rc = GetFullPathNameW(pwszPath, RT_ELEMENTS(wsz), &wsz[0], &pwszFile);
112 if (rc > 0 && rc < RT_ELEMENTS(wsz))
113 rc = RTUtf16ToUtf8Ex(&wsz[0], RTSTR_MAX, &pszAbsPath, cchAbsPath, NULL);
114 else if (rc <= 0)
115 rc = RTErrConvertFromWin32(GetLastError());
116 else
117 rc = VERR_FILENAME_TOO_LONG;
118
119 RTUtf16Free(pwszPath);
120
121 if (RT_SUCCESS(rc))
122 {
123 /*
124 * Remove trailing slash if the path may be pointing to a directory.
125 */
126 size_t cch = strlen(pszAbsPath);
127 if ( cch > 1
128 && RTPATH_IS_SLASH(pszAbsPath[cch - 1])
129 && !RTPATH_IS_VOLSEP(pszAbsPath[cch - 2])
130 && !RTPATH_IS_SLASH(pszAbsPath[cch - 2]))
131 pszAbsPath[cch - 1] = '\0';
132 }
133
134 return rc;
135}
136
137
138/**
139 * Gets the user home directory.
140 *
141 * @returns iprt status code.
142 * @param pszPath Buffer where to store the path.
143 * @param cchPath Buffer size in bytes.
144 */
145RTDECL(int) RTPathUserHome(char *pszPath, size_t cchPath)
146{
147 RTUTF16 wszPath[RTPATH_MAX];
148 DWORD dwAttr;
149
150 /*
151 * There are multiple definitions for what WE think of as user home...
152 */
153 if ( !GetEnvironmentVariableW(L"HOME", &wszPath[0], RTPATH_MAX)
154 || (dwAttr = GetFileAttributesW(&wszPath[0])) == INVALID_FILE_ATTRIBUTES
155 || !(dwAttr & FILE_ATTRIBUTE_DIRECTORY))
156 {
157 if ( !GetEnvironmentVariableW(L"USERPROFILE", &wszPath[0], RTPATH_MAX)
158 || (dwAttr = GetFileAttributesW(&wszPath[0])) == INVALID_FILE_ATTRIBUTES
159 || !(dwAttr & FILE_ATTRIBUTE_DIRECTORY))
160 {
161 /* %HOMEDRIVE%%HOMEPATH% */
162 if (!GetEnvironmentVariableW(L"HOMEDRIVE", &wszPath[0], RTPATH_MAX))
163 return VERR_PATH_NOT_FOUND;
164 size_t const cwc = RTUtf16Len(&wszPath[0]);
165 if ( !GetEnvironmentVariableW(L"HOMEPATH", &wszPath[cwc], RTPATH_MAX - (DWORD)cwc)
166 || (dwAttr = GetFileAttributesW(&wszPath[0])) == INVALID_FILE_ATTRIBUTES
167 || !(dwAttr & FILE_ATTRIBUTE_DIRECTORY))
168 return VERR_PATH_NOT_FOUND;
169 }
170 }
171
172 /*
173 * Convert and return.
174 */
175 return RTUtf16ToUtf8Ex(&wszPath[0], RTSTR_MAX, &pszPath, cchPath, NULL);
176}
177
178
179RTR3DECL(int) RTPathQueryInfo(const char *pszPath, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAdditionalAttribs)
180{
181 /*
182 * Validate input.
183 */
184 if (!pszPath)
185 {
186 AssertMsgFailed(("Invalid pszPath=%p\n", pszPath));
187 return VERR_INVALID_PARAMETER;
188 }
189 if (!pObjInfo)
190 {
191 AssertMsgFailed(("Invalid pObjInfo=%p\n", pObjInfo));
192 return VERR_INVALID_PARAMETER;
193 }
194 if ( enmAdditionalAttribs < RTFSOBJATTRADD_NOTHING
195 || enmAdditionalAttribs > RTFSOBJATTRADD_LAST)
196 {
197 AssertMsgFailed(("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs));
198 return VERR_INVALID_PARAMETER;
199 }
200
201 /*
202 * Query file info.
203 */
204 WIN32_FILE_ATTRIBUTE_DATA Data;
205#ifndef RT_DONT_CONVERT_FILENAMES
206 PRTUTF16 pwszPath;
207 int rc = RTStrToUtf16(pszPath, &pwszPath);
208 if (RT_FAILURE(rc))
209 return rc;
210 if (!GetFileAttributesExW(pwszPath, GetFileExInfoStandard, &Data))
211 {
212 rc = RTErrConvertFromWin32(GetLastError());
213 RTUtf16Free(pwszPath);
214 return rc;
215 }
216 RTUtf16Free(pwszPath);
217#else
218 if (!GetFileAttributesExA(pszPath, GetFileExInfoStandard, &Data))
219 return RTErrConvertFromWin32(GetLastError());
220#endif
221
222 /*
223 * Setup the returned data.
224 */
225 pObjInfo->cbObject = ((uint64_t)Data.nFileSizeHigh << 32)
226 | (uint64_t)Data.nFileSizeLow;
227 pObjInfo->cbAllocated = pObjInfo->cbObject;
228
229 Assert(sizeof(uint64_t) == sizeof(Data.ftCreationTime));
230 RTTimeSpecSetNtTime(&pObjInfo->BirthTime, *(uint64_t *)&Data.ftCreationTime);
231 RTTimeSpecSetNtTime(&pObjInfo->AccessTime, *(uint64_t *)&Data.ftLastAccessTime);
232 RTTimeSpecSetNtTime(&pObjInfo->ModificationTime, *(uint64_t *)&Data.ftLastWriteTime);
233 pObjInfo->ChangeTime = pObjInfo->ModificationTime;
234
235 pObjInfo->Attr.fMode = rtFsModeFromDos((Data.dwFileAttributes << RTFS_DOS_SHIFT) & RTFS_DOS_MASK_NT,
236 pszPath, strlen(pszPath));
237
238 /*
239 * Requested attributes (we cannot provide anything actually).
240 */
241 switch (enmAdditionalAttribs)
242 {
243 case RTFSOBJATTRADD_EASIZE:
244 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_EASIZE;
245 pObjInfo->Attr.u.EASize.cb = 0;
246 break;
247
248 case RTFSOBJATTRADD_UNIX:
249 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX;
250 pObjInfo->Attr.u.Unix.uid = ~0U;
251 pObjInfo->Attr.u.Unix.gid = ~0U;
252 pObjInfo->Attr.u.Unix.cHardlinks = 1;
253 pObjInfo->Attr.u.Unix.INodeIdDevice = 0; /** @todo use volume serial number */
254 pObjInfo->Attr.u.Unix.INodeId = 0; /** @todo use fileid (see GetFileInformationByHandle). */
255 pObjInfo->Attr.u.Unix.fFlags = 0;
256 pObjInfo->Attr.u.Unix.GenerationId = 0;
257 pObjInfo->Attr.u.Unix.Device = 0;
258 break;
259
260 case RTFSOBJATTRADD_NOTHING:
261 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_NOTHING;
262 break;
263
264 default:
265 AssertMsgFailed(("Impossible!\n"));
266 return VERR_INTERNAL_ERROR;
267 }
268
269 return VINF_SUCCESS;
270}
271
272
273RTR3DECL(int) RTPathSetTimes(const char *pszPath, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
274 PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
275{
276 /*
277 * Validate input.
278 */
279 AssertMsgReturn(VALID_PTR(pszPath), ("%p\n", pszPath), VERR_INVALID_POINTER);
280 AssertMsgReturn(*pszPath, ("%p\n", pszPath), VERR_INVALID_PARAMETER);
281 AssertMsgReturn(!pAccessTime || VALID_PTR(pAccessTime), ("%p\n", pAccessTime), VERR_INVALID_POINTER);
282 AssertMsgReturn(!pModificationTime || VALID_PTR(pModificationTime), ("%p\n", pModificationTime), VERR_INVALID_POINTER);
283 AssertMsgReturn(!pChangeTime || VALID_PTR(pChangeTime), ("%p\n", pChangeTime), VERR_INVALID_POINTER);
284 AssertMsgReturn(!pBirthTime || VALID_PTR(pBirthTime), ("%p\n", pBirthTime), VERR_INVALID_POINTER);
285
286 /*
287 * Convert the path.
288 */
289 PRTUTF16 pwszPath;
290 int rc = RTStrToUtf16(pszPath, &pwszPath);
291 if (RT_SUCCESS(rc))
292 {
293 HANDLE hFile = CreateFileW(pwszPath,
294 FILE_WRITE_ATTRIBUTES, /* dwDesiredAccess */
295 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, /* dwShareMode */
296 NULL, /* security attribs */
297 OPEN_EXISTING, /* dwCreationDisposition */
298 FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL,
299 NULL);
300 if (hFile != INVALID_HANDLE_VALUE)
301 {
302 /*
303 * Check if it's a no-op.
304 */
305 if (!pAccessTime && !pModificationTime && !pBirthTime)
306 rc = VINF_SUCCESS; /* NOP */
307 else
308 {
309 /*
310 * Convert the input and call the API.
311 */
312 FILETIME CreationTimeFT;
313 PFILETIME pCreationTimeFT = NULL;
314 if (pBirthTime)
315 pCreationTimeFT = RTTimeSpecGetNtFileTime(pBirthTime, &CreationTimeFT);
316
317 FILETIME LastAccessTimeFT;
318 PFILETIME pLastAccessTimeFT = NULL;
319 if (pAccessTime)
320 pLastAccessTimeFT = RTTimeSpecGetNtFileTime(pAccessTime, &LastAccessTimeFT);
321
322 FILETIME LastWriteTimeFT;
323 PFILETIME pLastWriteTimeFT = NULL;
324 if (pModificationTime)
325 pLastWriteTimeFT = RTTimeSpecGetNtFileTime(pModificationTime, &LastWriteTimeFT);
326
327 if (SetFileTime(hFile, pCreationTimeFT, pLastAccessTimeFT, pLastWriteTimeFT))
328 rc = VINF_SUCCESS;
329 else
330 {
331 DWORD Err = GetLastError();
332 rc = RTErrConvertFromWin32(Err);
333 Log(("RTPathSetTimes('%s', %p, %p, %p, %p): SetFileTime failed with lasterr %d (%Rrc)\n",
334 pszPath, pAccessTime, pModificationTime, pChangeTime, pBirthTime, Err, rc));
335 }
336 }
337 BOOL fRc = CloseHandle(hFile); Assert(fRc); NOREF(fRc);
338 }
339 else
340 {
341 DWORD Err = GetLastError();
342 rc = RTErrConvertFromWin32(Err);
343 Log(("RTPathSetTimes('%s',,,,): failed with %Rrc and lasterr=%u\n", pszPath, rc, Err));
344 }
345
346 RTUtf16Free(pwszPath);
347 }
348
349 LogFlow(("RTPathSetTimes(%p:{%s}, %p:{%RDtimespec}, %p:{%RDtimespec}, %p:{%RDtimespec}, %p:{%RDtimespec}): return %Rrc\n",
350 pszPath, pszPath, pAccessTime, pAccessTime, pModificationTime, pModificationTime,
351 pChangeTime, pChangeTime, pBirthTime, pBirthTime));
352 return rc;
353}
354
355
356
357
358/**
359 * Internal worker for RTFileRename and RTFileMove.
360 *
361 * @returns iprt status code.
362 * @param pszSrc The source filename.
363 * @param pszDst The destination filename.
364 * @param fFlags The windows MoveFileEx flags.
365 * @param fFileType The filetype. We use the RTFMODE filetypes here. If it's 0,
366 * anything goes. If it's RTFS_TYPE_DIRECTORY we'll check that the
367 * source is a directory. If Its RTFS_TYPE_FILE we'll check that it's
368 * not a directory (we are NOT checking whether it's a file).
369 */
370int rtPathWin32MoveRename(const char *pszSrc, const char *pszDst, uint32_t fFlags, RTFMODE fFileType)
371{
372 /*
373 * Convert the strings.
374 */
375 PRTUTF16 pwszSrc;
376 int rc = RTStrToUtf16(pszSrc, &pwszSrc);
377 if (RT_SUCCESS(rc))
378 {
379 PRTUTF16 pwszDst;
380 rc = RTStrToUtf16(pszDst, &pwszDst);
381 if (RT_SUCCESS(rc))
382 {
383 /*
384 * Check object type if requested.
385 * This is open to race conditions.
386 */
387 if (fFileType)
388 {
389 DWORD dwAttr = GetFileAttributesW(pwszSrc);
390 if (dwAttr == INVALID_FILE_ATTRIBUTES)
391 rc = RTErrConvertFromWin32(GetLastError());
392 else if (RTFS_IS_DIRECTORY(fFileType))
393 rc = dwAttr & FILE_ATTRIBUTE_DIRECTORY ? VINF_SUCCESS : VERR_NOT_A_DIRECTORY;
394 else
395 rc = dwAttr & FILE_ATTRIBUTE_DIRECTORY ? VERR_IS_A_DIRECTORY : VINF_SUCCESS;
396 }
397 if (RT_SUCCESS(rc))
398 {
399 if (MoveFileExW(pwszSrc, pwszDst, fFlags))
400 rc = VINF_SUCCESS;
401 else
402 {
403 DWORD Err = GetLastError();
404 rc = RTErrConvertFromWin32(Err);
405 Log(("MoveFileExW('%s', '%s', %#x, %RTfmode): fails with rc=%Rrc & lasterr=%d\n",
406 pszSrc, pszDst, fFlags, fFileType, rc, Err));
407 }
408 }
409 RTUtf16Free(pwszDst);
410 }
411 RTUtf16Free(pwszSrc);
412 }
413 return rc;
414}
415
416
417RTR3DECL(int) RTPathRename(const char *pszSrc, const char *pszDst, unsigned fRename)
418{
419 /*
420 * Validate input.
421 */
422 AssertMsgReturn(VALID_PTR(pszSrc), ("%p\n", pszSrc), VERR_INVALID_POINTER);
423 AssertMsgReturn(VALID_PTR(pszDst), ("%p\n", pszDst), VERR_INVALID_POINTER);
424 AssertMsgReturn(*pszSrc, ("%p\n", pszSrc), VERR_INVALID_PARAMETER);
425 AssertMsgReturn(*pszDst, ("%p\n", pszDst), VERR_INVALID_PARAMETER);
426 AssertMsgReturn(!(fRename & ~RTPATHRENAME_FLAGS_REPLACE), ("%#x\n", fRename), VERR_INVALID_PARAMETER);
427
428 /*
429 * Call the worker.
430 */
431 int rc = rtPathWin32MoveRename(pszSrc, pszDst, fRename & RTPATHRENAME_FLAGS_REPLACE ? MOVEFILE_REPLACE_EXISTING : 0, 0);
432
433 LogFlow(("RTPathRename(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n", pszSrc, pszSrc, pszDst, pszDst, fRename, rc));
434 return rc;
435}
436
437
438/**
439 * Checks if the path exists.
440 *
441 * Symbolic links will all be attempted resolved.
442 *
443 * @returns true if it exists and false if it doesn't
444 * @param pszPath The path to check.
445 */
446RTDECL(bool) RTPathExists(const char *pszPath)
447{
448 /*
449 * Validate input.
450 */
451 AssertPtrReturn(pszPath, false);
452 AssertReturn(*pszPath, false);
453
454 /*
455 * Try query file info.
456 */
457#ifndef RT_DONT_CONVERT_FILENAMES
458 PRTUTF16 pwszPath;
459 int rc = RTStrToUtf16(pszPath, &pwszPath);
460 if (RT_SUCCESS(rc))
461 {
462 if (GetFileAttributesW(pwszPath) == INVALID_FILE_ATTRIBUTES)
463 rc = VERR_GENERAL_FAILURE;
464 RTUtf16Free(pwszPath);
465 }
466#else
467 int rc = VINF_SUCCESS;
468 if (GetFileAttributesExA(pszPath) == INVALID_FILE_ATTRIBUTES)
469 rc = VERR_GENERAL_FAILURE;
470#endif
471
472 return RT_SUCCESS(rc);
473}
474
475
476RTDECL(int) RTPathSetCurrent(const char *pszPath)
477{
478 /*
479 * Validate input.
480 */
481 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
482 AssertReturn(*pszPath, VERR_INVALID_PARAMETER);
483
484 /*
485 * This interface is almost identical to the Windows API.
486 */
487#ifndef RT_DONT_CONVERT_FILENAMES
488 PRTUTF16 pwszPath;
489 int rc = RTStrToUtf16(pszPath, &pwszPath);
490 if (RT_SUCCESS(rc))
491 {
492 /** @todo improove the slash stripping a bit? */
493 size_t cwc = RTUtf16Len(pwszPath);
494 if ( cwc >= 2
495 && ( pwszPath[cwc - 1] == L'/'
496 || pwszPath[cwc - 1] == L'\\')
497 && pwszPath[cwc - 2] != ':')
498 pwszPath[cwc - 1] = L'\0';
499
500 if (!SetCurrentDirectoryW(pwszPath))
501 rc = RTErrConvertFromWin32(GetLastError());
502
503 RTUtf16Free(pwszPath);
504 }
505#else
506 int rc = VINF_SUCCESS;
507 /** @todo improove the slash stripping a bit? */
508 char const *pszEnd = strchr(pszPath, '\0');
509 size_t const cchPath = pszPath - pszEnd;
510 if ( cchPath >= 2
511 && ( pszEnd[-1] == '/'
512 || pszEnd[-1] == '\\')
513 && pszEnd[-2] == ':')
514 {
515 char *pszCopy = (char *)RTMemTmpAlloc(cchPath);
516 if (pszCopy)
517 {
518 memcpy(pszCopy, pszPath, cchPath - 1);
519 pszCopy[cchPath - 1] = '\0';
520 if (!SetCurrentDirectory(pszCopy))
521 rc = RTErrConvertFromWin32(GetLastError());
522 RTMemTmpFree(pszCopy);
523 }
524 else
525 rc = VERR_NO_MEMORY;
526 }
527 else
528 {
529 if (!SetCurrentDirectory(pszPath))
530 rc = RTErrConvertFromWin32(GetLastError());
531 }
532#endif
533 return rc;
534}
535
Note: See TracBrowser for help on using the repository browser.

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