1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
15 * The Original Code is mozilla.org code.
17 * The Initial Developer of the Original Code is
18 * Netscape Communications Corporation.
19 * Portions created by the Initial Developer are Copyright (C) 1998
20 * the Initial Developer. All Rights Reserved.
23 * Henry Sobotka <sobotka@axess.com>
24 * William Bonnet <wbonnet@on-x.com>
26 * Alternatively, the contents of this file may be used under the terms of
27 * either of the GNU General Public License Version 2 or later (the "GPL"),
28 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29 * in which case the provisions of the GPL or the LGPL are applicable instead
30 * of those above. If you wish to allow use of your version of this file only
31 * under the terms of either the GPL or the LGPL, and not to allow others to
32 * use your version of this file under the terms of the MPL, indicate your
33 * decision by deleting the provisions above and replace them with the notice
34 * and other provisions required by the GPL or the LGPL. If you do not delete
35 * the provisions above, a recipient may use your version of this file under
36 * the terms of any one of the MPL, the GPL or the LGPL.
38 * ***** END LICENSE BLOCK ***** */
40 // This file is included by nsFileSpec.cpp, and includes the Unix-specific
44 #include <sys/param.h>
50 #include "xpcom-private.h"
52 #include "prio.h" /* for PR_Rename */
56 #define _SVID3 /* for statvfs.h */
59 #ifdef HAVE_SYS_STATVFS_H
60 #include <sys/statvfs.h>
67 #ifdef HAVE_SYS_STATFS_H
68 #include <sys/statfs.h>
71 #ifdef HAVE_SYS_MOUNT_H
72 #include <sys/mount.h>
77 #define STATFS statvfs
83 #define MAXPATHLEN 1024 /* Guessing this is okay. Works for SCO. */
87 #include <unix.h> /* for realpath */
88 #define f_bavail f_bfree
89 extern "C" int truncate(const char *, off_t
);
93 extern "C" int statfs(char *, struct statfs
*);
97 extern "C" int statvfs(const char *, struct statvfs
*);
101 static void CopyUTF8toUTF16NFC(const nsACString
& aSrc
, nsAString
& aResult
);
104 //----------------------------------------------------------------------------------------
105 void nsFileSpecHelpers::Canonify(nsSimpleCharString
& ioPath
, PRBool inMakeDirs
)
106 // Canonify, make absolute, and check whether directories exist
107 //----------------------------------------------------------------------------------------
109 if (ioPath
.IsEmpty())
113 const mode_t mode
= 0755;
114 nsFileSpecHelpers::MakeAllDirectories((const char*)ioPath
, mode
);
117 errno
= 0; // needed?
119 if (ioPath
[0] != '/')
121 // the ioPath that was passed in is relative. We must cat it to the cwd.
122 char buffer
[MAXPATHLEN
];
124 (void) getcwd(buffer
, MAXPATHLEN
);
127 strcat(buffer
, ioPath
);
131 } // nsFileSpecHelpers::Canonify
133 //----------------------------------------------------------------------------------------
134 void nsFileSpec::SetLeafName(const char* inLeafName
)
135 //----------------------------------------------------------------------------------------
137 mPath
.LeafReplace('/', inLeafName
);
138 } // nsFileSpec::SetLeafName
140 //----------------------------------------------------------------------------------------
141 char* nsFileSpec::GetLeafName() const
142 //----------------------------------------------------------------------------------------
145 return mPath
.GetLeaf('/');
147 char *name
= mPath
.GetLeaf('/');
150 nsAutoString nameInNFC
;
151 CopyUTF8toUTF16NFC(nsDependentCString(name
), nameInNFC
);
153 return nsCRT::strdup(NS_ConvertUTF16toUTF8(nameInNFC
).get());
155 } // nsFileSpec::GetLeafName
157 //----------------------------------------------------------------------------------------
158 PRBool
nsFileSpec::Exists() const
159 //----------------------------------------------------------------------------------------
161 return !mPath
.IsEmpty() && 0 == access(mPath
, F_OK
);
162 } // nsFileSpec::Exists
164 //----------------------------------------------------------------------------------------
165 void nsFileSpec::GetModDate(TimeStamp
& outStamp
) const
166 //----------------------------------------------------------------------------------------
169 if (!mPath
.IsEmpty() && stat(mPath
, &st
) == 0)
170 outStamp
= st
.st_mtime
;
173 } // nsFileSpec::GetModDate
175 //----------------------------------------------------------------------------------------
176 PRUint32
nsFileSpec::GetFileSize() const
177 //----------------------------------------------------------------------------------------
180 if (!mPath
.IsEmpty() && stat(mPath
, &st
) == 0)
181 return (PRUint32
)st
.st_size
;
183 } // nsFileSpec::GetFileSize
185 //----------------------------------------------------------------------------------------
186 PRBool
nsFileSpec::IsFile() const
187 //----------------------------------------------------------------------------------------
190 return !mPath
.IsEmpty() && stat(mPath
, &st
) == 0 && S_ISREG(st
.st_mode
);
191 } // nsFileSpec::IsFile
193 //----------------------------------------------------------------------------------------
194 PRBool
nsFileSpec::IsDirectory() const
195 //----------------------------------------------------------------------------------------
198 return !mPath
.IsEmpty() && 0 == stat(mPath
, &st
) && S_ISDIR(st
.st_mode
);
199 } // nsFileSpec::IsDirectory
201 //----------------------------------------------------------------------------------------
202 PRBool
nsFileSpec::IsHidden() const
203 //----------------------------------------------------------------------------------------
205 PRBool hidden
= PR_FALSE
;
206 char *leafname
= GetLeafName();
207 if (nsnull
!= leafname
)
209 // rjc: don't return ".", "..", or any file/directory that begins with a "."
211 /* if ((!strcmp(leafname, ".")) || (!strcmp(leafname, ".."))) */
212 if (leafname
[0] == '.')
216 nsCRT::free(leafname
);
219 } // nsFileSpec::IsHidden
221 //----------------------------------------------------------------------------------------
222 PRBool
nsFileSpec::IsSymlink() const
223 //----------------------------------------------------------------------------------------
226 if (!mPath
.IsEmpty() && stat(mPath
, &st
) == 0 && S_ISLNK(st
.st_mode
))
230 } // nsFileSpec::IsSymlink
232 //----------------------------------------------------------------------------------------
233 nsresult
nsFileSpec::ResolveSymlink(PRBool
& wasAliased
)
234 //----------------------------------------------------------------------------------------
236 wasAliased
= PR_FALSE
;
238 char resolvedPath
[MAXPATHLEN
];
239 int charCount
= readlink(mPath
, (char*)&resolvedPath
, MAXPATHLEN
);
242 if (MAXPATHLEN
> charCount
)
243 resolvedPath
[charCount
] = '\0';
245 wasAliased
= PR_TRUE
;
247 /* if it's not an absolute path,
248 replace the leaf with what got resolved */
249 if (resolvedPath
[0] != '/') {
250 SetLeafName(resolvedPath
);
253 mPath
= (char*)&resolvedPath
;
256 char* canonicalPath
= realpath((const char *)mPath
, resolvedPath
);
257 NS_ASSERTION(canonicalPath
, "realpath failed");
259 mPath
= (char*)&resolvedPath
;
262 return NS_ERROR_FAILURE
;
267 } // nsFileSpec::ResolveSymlink
270 //----------------------------------------------------------------------------------------
271 void nsFileSpec::GetParent(nsFileSpec
& outSpec
) const
272 //----------------------------------------------------------------------------------------
274 outSpec
.mPath
= mPath
;
275 char* chars
= (char*)outSpec
.mPath
;
276 chars
[outSpec
.mPath
.Length() - 1] = '\0'; // avoid trailing separator, if any
277 char* cp
= strrchr(chars
, '/');
279 outSpec
.mPath
.SetLength(cp
- chars
); // truncate.
280 } // nsFileSpec::GetParent
282 //----------------------------------------------------------------------------------------
283 void nsFileSpec::operator += (const char* inRelativePath
)
284 //----------------------------------------------------------------------------------------
286 NS_ASSERTION(inRelativePath
, "Attempt to do += with a null string");
288 if (!inRelativePath
|| mPath
.IsEmpty())
291 char endChar
= mPath
[(int)(strlen(mPath
) - 1)];
296 SetLeafName(inRelativePath
);
297 } // nsFileSpec::operator +=
299 //----------------------------------------------------------------------------------------
300 void nsFileSpec::CreateDirectory(int mode
)
301 //----------------------------------------------------------------------------------------
303 // Note that mPath is canonical!
307 } // nsFileSpec::CreateDirectory
309 //----------------------------------------------------------------------------------------
310 void nsFileSpec::Delete(PRBool inRecursive
) const
311 // To check if this worked, call Exists() afterwards, see?
312 //----------------------------------------------------------------------------------------
318 for (nsDirectoryIterator
i(*this, PR_FALSE
); i
.Exists(); i
++)
320 nsFileSpec
& child
= (nsFileSpec
&)i
;
321 child
.Delete(inRecursive
);
326 else if (!mPath
.IsEmpty())
328 } // nsFileSpec::Delete
330 //----------------------------------------------------------------------------------------
331 void nsFileSpec::RecursiveCopy(nsFileSpec newDir
) const
332 //----------------------------------------------------------------------------------------
336 if (!(newDir
.Exists()))
338 newDir
.CreateDirectory();
341 for (nsDirectoryIterator
i(*this, PR_FALSE
); i
.Exists(); i
++)
343 nsFileSpec
& child
= (nsFileSpec
&)i
;
345 if (child
.IsDirectory())
347 nsFileSpec
tmpDirSpec(newDir
);
349 char *leafname
= child
.GetLeafName();
350 tmpDirSpec
+= leafname
;
351 nsCRT::free(leafname
);
353 child
.RecursiveCopy(tmpDirSpec
);
357 child
.RecursiveCopy(newDir
);
361 else if (!mPath
.IsEmpty())
363 nsFileSpec
& filePath
= (nsFileSpec
&) *this;
365 if (!(newDir
.Exists()))
367 newDir
.CreateDirectory();
370 filePath
.CopyToDir(newDir
);
372 } // nsFileSpec::RecursiveCopy
375 //----------------------------------------------------------------------------------------
376 nsresult
nsFileSpec::Truncate(PRInt32 offset
) const
377 //----------------------------------------------------------------------------------------
379 char* Path
= nsCRT::strdup(mPath
);
381 int rv
= truncate(Path
, offset
) ;
388 return NS_ERROR_FAILURE
;
389 } // nsFileSpec::Truncate
391 //----------------------------------------------------------------------------------------
392 nsresult
nsFileSpec::Rename(const char* inNewName
)
393 //----------------------------------------------------------------------------------------
395 NS_ASSERTION(inNewName
, "Attempt to Rename with a null string");
397 // This function should not be used to move a file on disk.
398 if (mPath
.IsEmpty() || strchr(inNewName
, '/'))
399 return NS_FILE_FAILURE
;
401 char* oldPath
= nsCRT::strdup(mPath
);
403 SetLeafName(inNewName
);
405 if (PR_Rename(oldPath
, mPath
) != NS_OK
)
407 // Could not rename, set back to the original.
409 nsCRT::free(oldPath
);
410 return NS_FILE_FAILURE
;
413 nsCRT::free(oldPath
);
416 } // nsFileSpec::Rename
418 //----------------------------------------------------------------------------------------
419 static int CrudeFileCopy_DoCopy(PRFileDesc
* pFileDescIn
, PRFileDesc
* pFileDescOut
, char * pBuf
, long bufferSize
)
420 //----------------------------------------------------------------------------------------
422 PRInt32 rbytes
, wbytes
; // Number of bytes read and written in copy loop
426 // If EOF is reached and no data is available, PR_Read returns 0. A negative
427 // return value means an error occured
428 rbytes
= PR_Read(pFileDescIn
, pBuf
, bufferSize
);
429 if (rbytes
< 0) // Test if read was unsuccessfull
431 return -1; // Return an error
434 while (rbytes
> 0) // While there is data to copy
436 // Data buffer size is only 1K ! fwrite function is able to write it in
437 // one call. According to the man page fwrite returns a number of elements
438 // written if an error occured. Thus there is no need to handle this case
439 // as a normal case. Written data cannot be smaller than rbytes.
440 wbytes
= PR_Write(pFileDescOut
, pBuf
, rbytes
); // Copy data to output file
441 if (wbytes
!= rbytes
) // Test if all data was written
442 { // No this an error
443 return -1; // Return an error
446 // Write is done, we try to get more data
447 rbytes
= PR_Read(pFileDescIn
, pBuf
, bufferSize
);
448 if (rbytes
< 0) // Test if read was unsuccessful
450 return -1; // Return an error
454 return 0; // Still here ? ok so it worked :)
455 } // nsFileSpec::CrudeFileCopy_DoCopy
457 //----------------------------------------------------------------------------------------
458 static int CrudeFileCopy(const char* in
, const char* out
)
459 //----------------------------------------------------------------------------------------
461 char buf
[1024]; // Used as buffer for the copy loop
462 PRInt32 rbytes
, wbytes
; // Number of bytes read and written in copy loop
463 struct stat in_stat
; // Stores informations from the stat syscall
464 int stat_result
= -1, ret
;
465 PRFileDesc
* pFileDescIn
, * pFileDescOut
; // Src and dest pointers
467 // Check if the pointers to filenames are valid
468 NS_ASSERTION(in
&& out
, "CrudeFileCopy should be called with pointers to filenames...");
470 // Check if the pointers are the same, if so, no need to copy A to A
474 // Check if content of the pointers are the sames, if so, no need to copy A to A
475 if (strcmp(in
,out
) == 0)
478 // Retrieve the 'in' file attributes
479 stat_result
= stat(in
, &in_stat
);
482 // test if stat failed, it can happen if the file does not exist, is not
483 // readable or is not available ( can happen with NFS mounts )
484 return -1; // Return an error
487 // Open the input file for binary read
488 pFileDescIn
= PR_Open(in
, PR_RDONLY
, 0444);
489 if (pFileDescIn
== 0)
491 return -1; // Open failed, return an error
494 // Open the output file for binary write
495 pFileDescOut
= PR_Open(out
, PR_WRONLY
| PR_CREATE_FILE
, 0600);
496 if (pFileDescOut
== 0)
498 // Open failed, need to close input file, then return an error
499 PR_Close(pFileDescOut
); // Close the output file
500 return -1; // Open failed, return an error
504 if (CrudeFileCopy_DoCopy(pFileDescIn
, pFileDescOut
, buf
, sizeof(buf
)) != 0)
506 PR_Close(pFileDescOut
); // Close output file
507 PR_Close(pFileDescIn
); // Close input file
508 PR_Delete(out
); // Destroy output file
509 return -1; // Return an error
512 // There is no need for error handling here. This should have worked, but even
513 // if it fails, the data are now copied to destination, thus there is no need
514 // for the function to fail on the input file error
515 PR_Close(pFileDescIn
);
517 // It is better to call fsync and test return code before exiting to be sure
518 // data are actually written on disk. Data loss can happen with NFS mounts
519 if (PR_Sync(pFileDescOut
) != PR_SUCCESS
)
520 { // Test if the fsync function succeeded
521 PR_Close(pFileDescOut
); // Close output file
522 PR_Delete(out
); // Destroy output file
523 return -1; // Return an error
526 // Copy is done, close both file
527 if (PR_Close(pFileDescOut
) != PR_SUCCESS
) // Close output file
528 { // Output file was not closed :(
529 PR_Delete(out
); // Destroy output file
530 return -1; // Return an error
533 ret
= chmod(out
, in_stat
.st_mode
& 0777); // Set the new file file mode
534 if (ret
!= 0) // Test if the chmod function succeeded
536 PR_Delete(out
); // Destroy output file
537 return -1; // Return an error
540 return 0; // Still here ? ok so it worked :)
541 } // nsFileSpec::CrudeFileCopy
543 //----------------------------------------------------------------------------------------
544 nsresult
nsFileSpec::CopyToDir(const nsFileSpec
& inParentDirectory
) const
545 //----------------------------------------------------------------------------------------
547 // We can only copy into a directory, and (for now) can not copy entire directories
548 nsresult result
= NS_FILE_FAILURE
;
550 if (inParentDirectory
.IsDirectory() && (! IsDirectory() ) )
552 char *leafname
= GetLeafName();
553 nsSimpleCharString
destPath(inParentDirectory
.GetCString());
555 destPath
+= leafname
;
556 nsCRT::free(leafname
);
557 result
= NS_FILE_RESULT(CrudeFileCopy(GetCString(), destPath
));
560 } // nsFileSpec::CopyToDir
562 //----------------------------------------------------------------------------------------
563 nsresult
nsFileSpec::MoveToDir(const nsFileSpec
& inNewParentDirectory
)
564 //----------------------------------------------------------------------------------------
566 // We can only copy into a directory, and (for now) can not copy entire directories
567 nsresult result
= NS_FILE_FAILURE
;
569 if (inNewParentDirectory
.IsDirectory() && !IsDirectory())
571 char *leafname
= GetLeafName();
572 nsSimpleCharString
destPath(inNewParentDirectory
.GetCString());
574 destPath
+= leafname
;
575 nsCRT::free(leafname
);
577 result
= NS_FILE_RESULT(CrudeFileCopy(GetCString(), (const char*)destPath
));
580 // cast to fix const-ness
581 ((nsFileSpec
*)this)->Delete(PR_FALSE
);
583 *this = inNewParentDirectory
+ GetLeafName();
589 //----------------------------------------------------------------------------------------
590 nsresult
nsFileSpec::Execute(const char* inArgs
) const
591 //----------------------------------------------------------------------------------------
593 nsresult result
= NS_FILE_FAILURE
;
595 if (!mPath
.IsEmpty() && !IsDirectory())
597 nsSimpleCharString fileNameWithArgs
= mPath
+ " " + inArgs
;
598 result
= NS_FILE_RESULT(system(fileNameWithArgs
));
603 } // nsFileSpec::Execute
605 //----------------------------------------------------------------------------------------
606 PRInt64
nsFileSpec::GetDiskSpaceAvailable() const
607 //----------------------------------------------------------------------------------------
609 PRInt64 bytes
; /* XXX dougt needs to fix this */
610 LL_I2L(bytes
, LONG_MAX
); // initialize to all the space in the world?
613 #if defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_STATVFS_H)
615 char curdir
[MAXPATHLEN
];
618 (void) getcwd(curdir
, MAXPATHLEN
);
620 return bytes
; /* hope for the best as we did in cheddar */
623 sprintf(curdir
, "%.200s", (const char*)mPath
);
625 struct STATFS fs_buf
;
626 #if defined(__QNX__) && !defined(HAVE_STATVFS) /* Maybe this should be handled differently? */
627 if (STATFS(curdir
, &fs_buf
, 0, 0) < 0)
629 if (STATFS(curdir
, &fs_buf
) < 0)
631 return bytes
; /* hope for the best as we did in cheddar */
633 #ifdef DEBUG_DISK_SPACE
634 printf("DiskSpaceAvailable: %d bytes\n",
635 fs_buf
.f_bsize
* (fs_buf
.f_bavail
- 1));
638 PRInt64 bsize
,bavail
;
639 LL_I2L( bsize
, fs_buf
.f_bsize
);
640 LL_I2L( bavail
, fs_buf
.f_bavail
- 1 );
641 LL_MUL( bytes
, bsize
, bavail
);
646 ** This platform doesn't have statfs or statvfs, so we don't have much
647 ** choice but to "hope for the best as we did in cheddar".
650 #endif /* HAVE_SYS_STATFS_H or HAVE_SYS_STATVFS_H */
652 } // nsFileSpec::GetDiskSpace()
654 //========================================================================================
655 // nsDirectoryIterator
656 //========================================================================================
658 //----------------------------------------------------------------------------------------
659 nsDirectoryIterator::nsDirectoryIterator(const nsFileSpec
& inDirectory
, PRBool resolveSymLinks
)
660 //----------------------------------------------------------------------------------------
661 : mCurrent(inDirectory
)
663 , mResoveSymLinks(resolveSymLinks
)
664 , mStarting(inDirectory
)
668 mStarting
+= "sysygy"; // save off the starting directory
669 mCurrent
+= "sysygy"; // prepare the path for SetLeafName
670 mDir
= opendir((const char*)nsFilePath(inDirectory
));
672 } // nsDirectoryIterator::nsDirectoryIterator
674 //----------------------------------------------------------------------------------------
675 nsDirectoryIterator::~nsDirectoryIterator()
676 //----------------------------------------------------------------------------------------
680 } // nsDirectoryIterator::nsDirectoryIterator
682 //----------------------------------------------------------------------------------------
683 nsDirectoryIterator
& nsDirectoryIterator::operator ++ ()
684 //----------------------------------------------------------------------------------------
689 const char dot
[] = ".";
690 const char dotdot
[] = "..";
691 struct dirent
* entry
= readdir(mDir
);
692 if (entry
&& strcmp(entry
->d_name
, dot
) == 0)
693 entry
= readdir(mDir
);
694 if (entry
&& strcmp(entry
->d_name
, dotdot
) == 0)
695 entry
= readdir(mDir
);
699 mCurrent
= mStarting
; // restore mCurrent to be the starting directory. ResolveSymlink() may have taken us to another directory
700 mCurrent
.SetLeafName(entry
->d_name
);
704 mCurrent
.ResolveSymlink(ignore
);
708 } // nsDirectoryIterator::operator ++
710 //----------------------------------------------------------------------------------------
711 nsDirectoryIterator
& nsDirectoryIterator::operator -- ()
712 //----------------------------------------------------------------------------------------
714 return ++(*this); // can't do it backwards.
715 } // nsDirectoryIterator::operator --
717 // Convert a UTF-8 string to a UTF-16 string while normalizing to
718 // Normalization Form C (composed Unicode). We need this because
719 // Mac OS X file system uses NFD (Normalization Form D : decomposed Unicode)
720 // while most other OS', server-side programs usually expect NFC.
723 typedef void (*UnicodeNormalizer
) (CFMutableStringRef
, CFStringNormalizationForm
);
724 static void CopyUTF8toUTF16NFC(const nsACString
& aSrc
, nsAString
& aResult
)
726 static PRBool sChecked
= PR_FALSE
;
727 static UnicodeNormalizer sUnicodeNormalizer
= NULL
;
729 // CFStringNormalize was not introduced until Mac OS 10.2
731 CFBundleRef carbonBundle
=
732 CFBundleGetBundleWithIdentifier(CFSTR("com.apple.Carbon"));
734 sUnicodeNormalizer
= (UnicodeNormalizer
)
735 ::CFBundleGetFunctionPointerForName(carbonBundle
,
736 CFSTR("CFStringNormalize"));
740 if (!sUnicodeNormalizer
) { // OS X 10.1 or earlier
741 CopyUTF8toUTF16(aSrc
, aResult
);
745 const nsAFlatCString
&inFlatSrc
= PromiseFlatCString(aSrc
);
747 // The number of 16bit code units in a UTF-16 string will never be
748 // larger than the number of bytes in the corresponding UTF-8 string.
749 CFMutableStringRef inStr
=
750 ::CFStringCreateMutable(NULL
, inFlatSrc
.Length());
753 CopyUTF8toUTF16(aSrc
, aResult
);
757 ::CFStringAppendCString(inStr
, inFlatSrc
.get(), kCFStringEncodingUTF8
);
759 sUnicodeNormalizer(inStr
, kCFStringNormalizationFormC
);
761 CFIndex length
= CFStringGetLength(inStr
);
762 const UniChar
* chars
= CFStringGetCharactersPtr(inStr
);
765 aResult
.Assign(chars
, length
);
767 nsAutoTArray
<UniChar
, 512> buffer
;
768 if (buffer
.SetLength(length
)) {
769 CFStringGetCharacters(inStr
, CFRangeMake(0, length
), buffer
.Elements());
770 aResult
.Assign(buffer
.Elements(), length
);
773 CopyUTF8toUTF16(aSrc
, aResult
);