VirtualBox

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

Last change on this file since 6749 was 5999, checked in by vboxsync, 17 years ago

The Giant CDDL Dual-License Header Change.

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