2 * Copyright (c) 2010 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 Copyright (c) 1999-2009, Apple Inc. All rights reserved.
26 Responsibility: Christopher Kane
29 #include "CFInternal.h"
30 #include <CoreFoundation/CFPriv.h>
31 #if DEPLOYMENT_TARGET_WINDOWS
43 #define mkdir(a,b) _NS_mkdir(a)
44 #define rmdir _NS_rmdir
45 #define unlink _NS_unlink
47 #define statinfo _stat
54 #include <sys/types.h>
65 CF_INLINE
int openAutoFSNoWait() {
66 #if DEPLOYMENT_TARGET_WINDOWS
69 return (__CFProphylacticAutofsAccess
? open("/dev/autofs_nowait", 0) : -1);
73 CF_INLINE
void closeAutoFSNoWait(int fd
) {
74 #if DEPLOYMENT_TARGET_WINDOWS
76 if (-1 != fd
) close(fd
);
80 __private_extern__ CFStringRef
_CFCopyExtensionForAbstractType(CFStringRef abstractType
) {
81 return (abstractType
? (CFStringRef
)CFRetain(abstractType
) : NULL
);
85 __private_extern__ Boolean
_CFCreateDirectory(const char *path
) {
86 int no_hang_fd
= openAutoFSNoWait();
87 int ret
= ((mkdir(path
, 0777) == 0) ? true : false);
88 closeAutoFSNoWait(no_hang_fd
);
92 #if DEPLOYMENT_TARGET_WINDOWS
93 // todo: remove this function and make callers use _CFCreateDirectory
94 __private_extern__ Boolean
_CFCreateDirectoryWide(const wchar_t *path
) {
95 return CreateDirectoryW(path
, 0);
99 __private_extern__ Boolean
_CFRemoveDirectory(const char *path
) {
100 int no_hang_fd
= openAutoFSNoWait();
101 int ret
= ((rmdir(path
) == 0) ? true : false);
102 closeAutoFSNoWait(no_hang_fd
);
106 __private_extern__ Boolean
_CFDeleteFile(const char *path
) {
107 int no_hang_fd
= openAutoFSNoWait();
108 int ret
= unlink(path
) == 0;
109 closeAutoFSNoWait(no_hang_fd
);
113 __private_extern__ Boolean
_CFReadBytesFromFile(CFAllocatorRef alloc
, CFURLRef url
, void **bytes
, CFIndex
*length
, CFIndex maxLength
) {
114 // maxLength is the number of bytes desired, or 0 if the whole file is desired regardless of length.
116 struct statinfo statBuf
;
117 char path
[CFMaxPathSize
];
118 if (!CFURLGetFileSystemRepresentation(url
, true, (uint8_t *)path
, CFMaxPathSize
)) {
125 int no_hang_fd
= openAutoFSNoWait();
126 fd
= open(path
, O_RDONLY
|CF_OPENFLGS
, 0666);
129 closeAutoFSNoWait(no_hang_fd
);
132 if (fstat(fd
, &statBuf
) < 0) {
133 int saveerr
= thread_errno();
135 closeAutoFSNoWait(no_hang_fd
);
136 thread_set_errno(saveerr
);
139 if ((statBuf
.st_mode
& S_IFMT
) != S_IFREG
) {
141 closeAutoFSNoWait(no_hang_fd
);
142 thread_set_errno(EACCES
);
145 if (statBuf
.st_size
== 0) {
146 *bytes
= CFAllocatorAllocate(alloc
, 4, 0); // don't return constant string -- it's freed!
147 if (__CFOASafe
) __CFSetLastAllocationEventName(*bytes
, "CFUtilities (file-bytes)");
150 CFIndex desiredLength
;
151 if ((maxLength
>= statBuf
.st_size
) || (maxLength
== 0)) {
152 desiredLength
= statBuf
.st_size
;
154 desiredLength
= maxLength
;
156 *bytes
= CFAllocatorAllocate(alloc
, desiredLength
, 0);
157 if (__CFOASafe
) __CFSetLastAllocationEventName(*bytes
, "CFUtilities (file-bytes)");
158 // fcntl(fd, F_NOCACHE, 1);
159 if (read(fd
, *bytes
, desiredLength
) < 0) {
160 CFAllocatorDeallocate(alloc
, *bytes
);
162 closeAutoFSNoWait(no_hang_fd
);
165 *length
= desiredLength
;
168 closeAutoFSNoWait(no_hang_fd
);
172 __private_extern__ Boolean
_CFWriteBytesToFile(CFURLRef url
, const void *bytes
, CFIndex length
) {
175 struct statinfo statBuf
;
176 char path
[CFMaxPathSize
];
177 if (!CFURLGetFileSystemRepresentation(url
, true, (uint8_t *)path
, CFMaxPathSize
)) {
181 int no_hang_fd
= openAutoFSNoWait();
183 if (0 == stat(path
, &statBuf
)) {
184 mode
= statBuf
.st_mode
;
185 } else if (thread_errno() != ENOENT
) {
186 closeAutoFSNoWait(no_hang_fd
);
189 fd
= open(path
, O_WRONLY
|O_CREAT
|O_TRUNC
|CF_OPENFLGS
, 0666);
191 closeAutoFSNoWait(no_hang_fd
);
194 if (length
&& write(fd
, bytes
, length
) != length
) {
195 int saveerr
= thread_errno();
197 closeAutoFSNoWait(no_hang_fd
);
198 thread_set_errno(saveerr
);
201 #if DEPLOYMENT_TARGET_WINDOWS
202 FlushFileBuffers((HANDLE
)_get_osfhandle(fd
));
207 closeAutoFSNoWait(no_hang_fd
);
212 /* On Mac OS 8/9, one of dirSpec and dirURL must be non-NULL. On all other platforms, one of path and dirURL must be non-NULL
213 If both are present, they are assumed to be in-synch; that is, they both refer to the same directory. */
214 /* Lately, dirSpec appears to be (rightfully) unused. */
215 __private_extern__ CFMutableArrayRef
_CFContentsOfDirectory(CFAllocatorRef alloc
, char *dirPath
, void *dirSpec
, CFURLRef dirURL
, CFStringRef matchingAbstractType
) {
216 CFMutableArrayRef files
= NULL
;
217 Boolean releaseBase
= false;
218 CFIndex pathLength
= dirPath
? strlen(dirPath
) : 0;
219 // MF:!!! Need to use four-letter type codes where appropriate.
220 CFStringRef extension
= (matchingAbstractType
? _CFCopyExtensionForAbstractType(matchingAbstractType
) : NULL
);
221 CFIndex extLen
= (extension
? CFStringGetLength(extension
) : 0);
224 #if DEPLOYMENT_TARGET_WINDOWS
225 // This is a replacement for 'dirent' below, and also uses wchar_t to support unicode paths
226 wchar_t extBuff
[CFMaxPathSize
];
229 CFStringGetBytes(extension
, CFRangeMake(0, extLen
), kCFStringEncodingUTF16
, 0, false, (uint8_t *)extBuff
, CFMaxPathLength
, &extLen
);
230 extBuff
[extLen
] = '\0';
233 wchar_t pathBuf
[CFMaxPathSize
];
236 if (!_CFURLGetWideFileSystemRepresentation(dirURL
, true, pathBuf
, CFMaxPathLength
)) {
237 if (extension
) CFRelease(extension
);
241 pathLength
= wcslen(pathBuf
);
244 // Convert dirPath to a wide representation and put it into our pathBuf
245 // Get the real length of the string in UTF16 characters
246 CFStringRef dirPathStr
= CFStringCreateWithCString(kCFAllocatorSystemDefault
, dirPath
, kCFStringEncodingUTF8
);
247 CFIndex strLen
= CFStringGetLength(dirPathStr
);
249 // Copy the string into the buffer and terminate
250 CFStringGetCharacters(dirPathStr
, CFRangeMake(0, strLen
), (UniChar
*)pathBuf
);
253 CFRelease(dirPathStr
);
256 WIN32_FIND_DATAW file
;
259 if (pathLength
+ 2 >= CFMaxPathLength
) {
261 CFRelease(extension
);
266 pathBuf
[pathLength
] = '\\';
267 pathBuf
[pathLength
+ 1] = '*';
268 pathBuf
[pathLength
+ 2] = '\0';
269 handle
= FindFirstFileW(pathBuf
, (LPWIN32_FIND_DATAW
)&file
);
270 if (INVALID_HANDLE_VALUE
== handle
) {
271 pathBuf
[pathLength
] = '\0';
273 CFRelease(extension
);
278 files
= CFArrayCreateMutable(alloc
, 0, &kCFTypeArrayCallBacks
);
282 CFIndex namelen
= wcslen(file
.cFileName
);
283 if (file
.cFileName
[0] == '.' && (namelen
== 1 || (namelen
== 2 && file
.cFileName
[1] == '.'))) {
287 if (extLen
> namelen
) continue; // if the extension is the same length or longer than the name, it can't possibly match.
290 // Check to see if it matches the extension we're looking for.
291 if (_wcsicmp(&(file
.cFileName
[namelen
- extLen
]), (const wchar_t *)extBuff
) != 0) {
295 if (dirURL
== NULL
) {
296 CFStringRef dirURLStr
= CFStringCreateWithBytes(alloc
, (const uint8_t *)pathBuf
, pathLength
, kCFStringEncodingUTF16
, NO
);
297 dirURL
= CFURLCreateWithFileSystemPath(alloc
, dirURLStr
, kCFURLWindowsPathStyle
, true);
298 CFRelease(dirURLStr
);
301 // MF:!!! What about the trailing slash?
302 CFStringRef fileURLStr
= CFStringCreateWithBytes(alloc
, (const uint8_t *)file
.cFileName
, namelen
, kCFStringEncodingUTF16
, NO
);
303 fileURL
= CFURLCreateWithFileSystemPathRelativeToBase(alloc
, fileURLStr
, kCFURLWindowsPathStyle
, (file
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) ? true : false, dirURL
);
304 CFArrayAppendValue(files
, fileURL
);
306 CFRelease(fileURLStr
);
307 } while (FindNextFileW(handle
, &file
));
309 pathBuf
[pathLength
] = '\0';
311 #elif DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
312 uint8_t extBuff
[CFMaxPathSize
];
315 CFStringGetBytes(extension
, CFRangeMake(0, extLen
), CFStringFileSystemEncoding(), 0, false, extBuff
, CFMaxPathLength
, &extLen
);
316 extBuff
[extLen
] = '\0';
319 uint8_t pathBuf
[CFMaxPathSize
];
322 if (!CFURLGetFileSystemRepresentation(dirURL
, true, pathBuf
, CFMaxPathLength
)) {
323 if (extension
) CFRelease(extension
);
326 dirPath
= (char *)pathBuf
;
327 pathLength
= strlen(dirPath
);
331 struct dirent buffer
;
335 int no_hang_fd
= __CFProphylacticAutofsAccess
? open("/dev/autofs_nowait", 0) : -1;
337 DIR *dirp
= opendir(dirPath
);
340 CFRelease(extension
);
342 if (-1 != no_hang_fd
) close(no_hang_fd
);
344 // raiseErrno("opendir", path);
346 files
= CFArrayCreateMutable(alloc
, 0, & kCFTypeArrayCallBacks
);
348 while((0 == readdir_r(dirp
, &buffer
, &dp
)) && dp
) {
350 unsigned namelen
= strlen(dp
->d_name
);
352 // skip . & ..; they cause descenders to go berserk
353 if (dp
->d_name
[0] == '.' && (namelen
== 1 || (namelen
== 2 && dp
->d_name
[1] == '.'))) {
357 if (extLen
> namelen
) continue; // if the extension is the same length or longer than the name, it can't possibly match.
360 // Check to see if it matches the extension we're looking for.
361 if (strncmp(&(dp
->d_name
[namelen
- extLen
]), (char *)extBuff
, extLen
) != 0) {
365 if (dirURL
== NULL
) {
366 dirURL
= CFURLCreateFromFileSystemRepresentation(alloc
, (uint8_t *)dirPath
, pathLength
, true);
369 if (dp
->d_type
== DT_DIR
|| dp
->d_type
== DT_UNKNOWN
) {
370 Boolean isDir
= (dp
->d_type
== DT_DIR
);
373 char subdirPath
[CFMaxPathLength
];
374 struct statinfo statBuf
;
375 strlcpy(subdirPath
, dirPath
, sizeof(subdirPath
));
376 strlcat(subdirPath
, "/", sizeof(subdirPath
));
377 strlcat(subdirPath
, dp
->d_name
, sizeof(subdirPath
));
378 if (stat(subdirPath
, &statBuf
) == 0) {
379 isDir
= ((statBuf
.st_mode
& S_IFMT
) == S_IFDIR
);
382 fileURL
= CFURLCreateFromFileSystemRepresentationRelativeToBase(alloc
, (uint8_t *)dp
->d_name
, dp
->d_namlen
, isDir
, dirURL
);
384 fileURL
= CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc
, (uint8_t *)dp
->d_name
, dp
->d_namlen
, false, dirURL
);
386 CFArrayAppendValue(files
, fileURL
);
389 err
= closedir(dirp
);
390 if (-1 != no_hang_fd
) close(no_hang_fd
);
397 CFRelease(extension
);
404 #error _CFContentsOfDirectory() unknown architecture, not implemented
409 CFRelease(extension
);
417 __private_extern__ SInt32
_CFGetFileProperties(CFAllocatorRef alloc
, CFURLRef pathURL
, Boolean
*exists
, SInt32
*posixMode
, int64_t *size
, CFDateRef
*modTime
, SInt32
*ownerID
, CFArrayRef
*dirContents
) {
419 Boolean isDirectory
= false;
421 if ((exists
== NULL
) && (posixMode
== NULL
) && (size
== NULL
) && (modTime
== NULL
) && (ownerID
== NULL
) && (dirContents
== NULL
)) {
426 struct statinfo statBuf
;
427 char path
[CFMaxPathSize
];
429 if (!CFURLGetFileSystemRepresentation(pathURL
, true, (uint8_t *)path
, CFMaxPathLength
)) {
433 if (stat(path
, &statBuf
) != 0) {
434 // stat failed, but why?
435 if (thread_errno() == ENOENT
) {
438 return thread_errno();
442 isDirectory
= ((statBuf
.st_mode
& S_IFMT
) == S_IFDIR
);
446 if (exists
!= NULL
) {
447 *exists
= fileExists
;
450 if (posixMode
!= NULL
) {
453 *posixMode
= statBuf
.st_mode
;
463 *size
= statBuf
.st_size
;
470 if (modTime
!= NULL
) {
472 #if DEPLOYMENT_TARGET_WINDOWS
473 struct timespec ts
= {statBuf
.st_mtime
, 0};
475 struct timespec ts
= statBuf
.st_mtimespec
;
477 *modTime
= CFDateCreate(alloc
, _CFAbsoluteTimeFromFileTimeSpec(ts
));
483 if (ownerID
!= NULL
) {
486 *ownerID
= statBuf
.st_uid
;
493 if (dirContents
!= NULL
) {
494 if (fileExists
&& isDirectory
) {
496 CFMutableArrayRef contents
= _CFContentsOfDirectory(alloc
, (char *)path
, NULL
, pathURL
, NULL
);
499 *dirContents
= contents
;
511 // MF:!!! Should pull in the rest of the UniChar based path utils from Foundation.
512 #if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_LINUX || DEPLOYMENT_TARGET_FREEBSD
513 #define UNIX_PATH_SEMANTICS
514 #elif DEPLOYMENT_TARGET_WINDOWS
515 #define WINDOWS_PATH_SEMANTICS
517 #error Unknown platform
520 #if defined(WINDOWS_PATH_SEMANTICS)
521 #define CFPreferredSlash ((UniChar)'\\')
522 #elif defined(UNIX_PATH_SEMANTICS)
523 #define CFPreferredSlash ((UniChar)'/')
524 #elif defined(HFS_PATH_SEMANTICS)
525 #define CFPreferredSlash ((UniChar)':')
527 #error Cannot define NSPreferredSlash on this platform
530 #if defined(HFS_PATH_SEMANTICS)
531 #define HAS_DRIVE(S) (false)
532 #define HAS_NET(S) (false)
534 #define HAS_DRIVE(S) ((S)[1] == ':' && (('A' <= (S)[0] && (S)[0] <= 'Z') || ('a' <= (S)[0] && (S)[0] <= 'z')))
535 #define HAS_NET(S) ((S)[0] == '\\' && (S)[1] == '\\')
538 #if defined(WINDOWS_PATH_SEMANTICS)
539 #define IS_SLASH(C) ((C) == '\\' || (C) == '/')
540 #elif defined(UNIX_PATH_SEMANTICS)
541 #define IS_SLASH(C) ((C) == '/')
542 #elif defined(HFS_PATH_SEMANTICS)
543 #define IS_SLASH(C) ((C) == ':')
546 __private_extern__ Boolean
_CFIsAbsolutePath(UniChar
*unichars
, CFIndex length
) {
550 #if defined(WINDOWS_PATH_SEMANTICS)
551 if (unichars
[0] == '~') {
557 if (HAS_NET(unichars
)) {
563 if (IS_SLASH(unichars
[2]) && HAS_DRIVE(unichars
)) {
566 #elif defined(HFS_PATH_SEMANTICS)
567 return !IS_SLASH(unichars
[0]);
569 if (unichars
[0] == '~') {
572 if (IS_SLASH(unichars
[0])) {
579 __private_extern__ Boolean
_CFStripTrailingPathSlashes(UniChar
*unichars
, CFIndex
*length
) {
580 Boolean destHasDrive
= (1 < *length
) && HAS_DRIVE(unichars
);
581 CFIndex oldLength
= *length
;
582 while (((destHasDrive
&& 3 < *length
) || (!destHasDrive
&& 1 < *length
)) && IS_SLASH(unichars
[*length
- 1])) {
585 return (oldLength
!= *length
);
588 __private_extern__ Boolean
_CFAppendPathComponent(UniChar
*unichars
, CFIndex
*length
, CFIndex maxLength
, UniChar
*component
, CFIndex componentLength
) {
589 if (0 == componentLength
) {
592 if (maxLength
< *length
+ 1 + componentLength
) {
599 if (!IS_SLASH(unichars
[0])) {
600 unichars
[(*length
)++] = CFPreferredSlash
;
604 if (!HAS_DRIVE(unichars
) && !HAS_NET(unichars
)) {
605 unichars
[(*length
)++] = CFPreferredSlash
;
609 unichars
[(*length
)++] = CFPreferredSlash
;
612 memmove(unichars
+ *length
, component
, componentLength
* sizeof(UniChar
));
613 *length
+= componentLength
;
617 __private_extern__ Boolean
_CFAppendPathExtension(UniChar
*unichars
, CFIndex
*length
, CFIndex maxLength
, UniChar
*extension
, CFIndex extensionLength
) {
618 if (maxLength
< *length
+ 1 + extensionLength
) {
621 if ((0 < extensionLength
&& IS_SLASH(extension
[0])) || (1 < extensionLength
&& HAS_DRIVE(extension
))) {
624 _CFStripTrailingPathSlashes(unichars
, length
);
629 if (IS_SLASH(unichars
[0]) || unichars
[0] == '~') {
634 if (HAS_DRIVE(unichars
) || HAS_NET(unichars
)) {
639 if (IS_SLASH(unichars
[2]) && HAS_DRIVE(unichars
)) {
644 if (0 < *length
&& unichars
[0] == '~') {
646 Boolean hasSlash
= false;
647 for (idx
= 1; idx
< *length
; idx
++) {
648 if (IS_SLASH(unichars
[idx
])) {
657 unichars
[(*length
)++] = '.';
658 memmove(unichars
+ *length
, extension
, extensionLength
* sizeof(UniChar
));
659 *length
+= extensionLength
;
663 __private_extern__ Boolean
_CFTransmutePathSlashes(UniChar
*unichars
, CFIndex
*length
, UniChar replSlash
) {
664 CFIndex didx
, sidx
, scnt
= *length
;
665 sidx
= (1 < *length
&& HAS_NET(unichars
)) ? 2 : 0;
667 while (sidx
< scnt
) {
668 if (IS_SLASH(unichars
[sidx
])) {
669 unichars
[didx
++] = replSlash
;
670 for (sidx
++; sidx
< scnt
&& IS_SLASH(unichars
[sidx
]); sidx
++);
672 unichars
[didx
++] = unichars
[sidx
++];
676 return (scnt
!= didx
);
679 __private_extern__ CFIndex
_CFStartOfLastPathComponent(UniChar
*unichars
, CFIndex length
) {
684 for (idx
= length
- 1; idx
; idx
--) {
685 if (IS_SLASH(unichars
[idx
- 1])) {
689 if ((2 < length
) && HAS_DRIVE(unichars
)) {
695 __private_extern__ CFIndex
_CFLengthAfterDeletingLastPathComponent(UniChar
*unichars
, CFIndex length
) {
700 for (idx
= length
- 1; idx
; idx
--) {
701 if (IS_SLASH(unichars
[idx
- 1])) {
702 if ((idx
!= 1) && (!HAS_DRIVE(unichars
) || idx
!= 3)) {
708 if ((2 < length
) && HAS_DRIVE(unichars
)) {
714 __private_extern__ CFIndex
_CFStartOfPathExtension(UniChar
*unichars
, CFIndex length
) {
719 for (idx
= length
- 1; idx
; idx
--) {
720 if (IS_SLASH(unichars
[idx
- 1])) {
723 if (unichars
[idx
] != '.') {
726 if (idx
== 2 && HAS_DRIVE(unichars
)) {
734 __private_extern__ CFIndex
_CFLengthAfterDeletingPathExtension(UniChar
*unichars
, CFIndex length
) {
735 CFIndex start
= _CFStartOfPathExtension(unichars
, length
);
736 return ((0 < start
) ? start
: length
);
740 #undef UNIX_PATH_SEMANTICS
741 #undef WINDOWS_PATH_SEMANTICS
742 #undef HFS_PATH_SEMANTICS
743 #undef CFPreferredSlash