VirtualBox

source: vbox/trunk/src/libs/xpcom18a4/xpcom/obsolete/nsFileSpecUnix.cpp@ 86262

Last change on this file since 86262 was 39926, checked in by vboxsync, 13 years ago

be more restrictive

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 21.8 KB
Line 
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
4 *
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/
9 *
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
13 * License.
14 *
15 * The Original Code is mozilla.org code.
16 *
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.
21 *
22 * Contributor(s):
23 * Henry Sobotka <[email protected]>
24 *
25 * Alternatively, the contents of this file may be used under the terms of
26 * either of the GNU General Public License Version 2 or later (the "GPL"),
27 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
36 *
37 * ***** END LICENSE BLOCK ***** */
38
39// This file is included by nsFileSpec.cpp, and includes the Unix-specific
40// implementations.
41
42#include <sys/stat.h>
43#include <sys/param.h>
44#include <errno.h>
45#include <dirent.h>
46#include <unistd.h>
47#include <stdlib.h>
48#include <limits.h>
49#include "xpcom-private.h"
50#include "nsError.h"
51#include "prio.h" /* for PR_Rename */
52#include "nsAutoBuffer.h"
53
54#if defined(_SCO_DS)
55#define _SVID3 /* for statvfs.h */
56#endif
57
58#ifdef HAVE_SYS_STATVFS_H
59#include <sys/statvfs.h>
60#endif
61
62#ifdef HAVE_SYS_VFS_H
63#include <sys/vfs.h>
64#endif
65
66#ifdef HAVE_SYS_STATFS_H
67#include <sys/statfs.h>
68#endif
69
70#ifdef HAVE_SYS_MOUNT_H
71#include <sys/mount.h>
72#undef Free
73#endif
74
75#ifdef HAVE_STATVFS
76#define STATFS statvfs
77#else
78#define STATFS statfs
79#endif
80
81#ifndef MAXPATHLEN
82#define MAXPATHLEN 1024 /* Guessing this is okay. Works for SCO. */
83#endif
84
85#if defined(__QNX__)
86#include <unix.h> /* for realpath */
87#define f_bavail f_bfree
88extern "C" int truncate(const char *, off_t);
89#endif
90
91#if defined(SUNOS4)
92extern "C" int statfs(char *, struct statfs *);
93#endif
94
95#if defined(OSF1)
96extern "C" int statvfs(const char *, struct statvfs *);
97#endif
98
99#ifdef XP_MACOSX
100static void CopyUTF8toUTF16NFC(const nsACString& aSrc, nsAString& aResult);
101#endif
102
103//----------------------------------------------------------------------------------------
104void nsFileSpecHelpers::Canonify(nsSimpleCharString& ioPath, PRBool inMakeDirs)
105// Canonify, make absolute, and check whether directories exist
106//----------------------------------------------------------------------------------------
107{
108 if (ioPath.IsEmpty())
109 return;
110 if (inMakeDirs)
111 {
112 const mode_t mode = 0700;
113 nsFileSpecHelpers::MakeAllDirectories((const char*)ioPath, mode);
114 }
115
116 errno = 0; // needed?
117
118 if (ioPath[0] != '/')
119 {
120 // the ioPath that was passed in is relative. We must cat it to the cwd.
121 char buffer[MAXPATHLEN];
122
123 (void) getcwd(buffer, MAXPATHLEN);
124
125 strcat(buffer, "/");
126 strcat(buffer, ioPath);
127
128 ioPath = buffer;
129 }
130} // nsFileSpecHelpers::Canonify
131
132//----------------------------------------------------------------------------------------
133void nsFileSpec::SetLeafName(const char* inLeafName)
134//----------------------------------------------------------------------------------------
135{
136 mPath.LeafReplace('/', inLeafName);
137} // nsFileSpec::SetLeafName
138
139//----------------------------------------------------------------------------------------
140char* nsFileSpec::GetLeafName() const
141//----------------------------------------------------------------------------------------
142{
143#ifndef XP_MACOSX
144 return mPath.GetLeaf('/');
145#else
146 char *name = mPath.GetLeaf('/');
147 if (!name || !*name)
148 return name;
149 nsAutoString nameInNFC;
150 CopyUTF8toUTF16NFC(nsDependentCString(name), nameInNFC);
151 nsCRT::free(name);
152 return nsCRT::strdup(NS_ConvertUTF16toUTF8(nameInNFC).get());
153#endif
154} // nsFileSpec::GetLeafName
155
156//----------------------------------------------------------------------------------------
157PRBool nsFileSpec::Exists() const
158//----------------------------------------------------------------------------------------
159{
160 struct stat st;
161 return !mPath.IsEmpty() && 0 == stat(mPath, &st);
162} // nsFileSpec::Exists
163
164//----------------------------------------------------------------------------------------
165void nsFileSpec::GetModDate(TimeStamp& outStamp) const
166//----------------------------------------------------------------------------------------
167{
168 struct stat st;
169 if (!mPath.IsEmpty() && stat(mPath, &st) == 0)
170 outStamp = st.st_mtime;
171 else
172 outStamp = 0;
173} // nsFileSpec::GetModDate
174
175//----------------------------------------------------------------------------------------
176PRUint32 nsFileSpec::GetFileSize() const
177//----------------------------------------------------------------------------------------
178{
179 struct stat st;
180 if (!mPath.IsEmpty() && stat(mPath, &st) == 0)
181 return (PRUint32)st.st_size;
182 return 0;
183} // nsFileSpec::GetFileSize
184
185//----------------------------------------------------------------------------------------
186PRBool nsFileSpec::IsFile() const
187//----------------------------------------------------------------------------------------
188{
189 struct stat st;
190 return !mPath.IsEmpty() && stat(mPath, &st) == 0 && S_ISREG(st.st_mode);
191} // nsFileSpec::IsFile
192
193//----------------------------------------------------------------------------------------
194PRBool nsFileSpec::IsDirectory() const
195//----------------------------------------------------------------------------------------
196{
197 struct stat st;
198 return !mPath.IsEmpty() && 0 == stat(mPath, &st) && S_ISDIR(st.st_mode);
199} // nsFileSpec::IsDirectory
200
201//----------------------------------------------------------------------------------------
202PRBool nsFileSpec::IsHidden() const
203//----------------------------------------------------------------------------------------
204{
205 PRBool hidden = PR_FALSE;
206 char *leafname = GetLeafName();
207 if (nsnull != leafname)
208 {
209 // rjc: don't return ".", "..", or any file/directory that begins with a "."
210
211 /* if ((!strcmp(leafname, ".")) || (!strcmp(leafname, ".."))) */
212 if (leafname[0] == '.')
213 {
214 hidden = PR_TRUE;
215 }
216 nsCRT::free(leafname);
217 }
218 return hidden;
219} // nsFileSpec::IsHidden
220
221//----------------------------------------------------------------------------------------
222PRBool nsFileSpec::IsSymlink() const
223//----------------------------------------------------------------------------------------
224{
225 struct stat st;
226 if (!mPath.IsEmpty() && stat(mPath, &st) == 0 && S_ISLNK(st.st_mode))
227 return PR_TRUE;
228
229 return PR_FALSE;
230} // nsFileSpec::IsSymlink
231
232//----------------------------------------------------------------------------------------
233nsresult nsFileSpec::ResolveSymlink(PRBool& wasAliased)
234//----------------------------------------------------------------------------------------
235{
236 wasAliased = PR_FALSE;
237
238 char resolvedPath[MAXPATHLEN];
239 int charCount = readlink(mPath, (char*)&resolvedPath, MAXPATHLEN);
240 if (0 < charCount)
241 {
242 if (MAXPATHLEN > charCount)
243 resolvedPath[charCount] = '\0';
244
245 wasAliased = PR_TRUE;
246
247 /* if it's not an absolute path,
248 replace the leaf with what got resolved */
249 if (resolvedPath[0] != '/') {
250 SetLeafName(resolvedPath);
251 }
252 else {
253 mPath = (char*)&resolvedPath;
254 }
255
256 char* canonicalPath = realpath((const char *)mPath, resolvedPath);
257 NS_ASSERTION(canonicalPath, "realpath failed");
258 if (canonicalPath) {
259 mPath = (char*)&resolvedPath;
260 }
261 else {
262 return NS_ERROR_FAILURE;
263 }
264 }
265
266 return NS_OK;
267} // nsFileSpec::ResolveSymlink
268
269
270//----------------------------------------------------------------------------------------
271void nsFileSpec::GetParent(nsFileSpec& outSpec) const
272//----------------------------------------------------------------------------------------
273{
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, '/');
278 if (cp++)
279 outSpec.mPath.SetLength(cp - chars); // truncate.
280} // nsFileSpec::GetParent
281
282//----------------------------------------------------------------------------------------
283void nsFileSpec::operator += (const char* inRelativePath)
284//----------------------------------------------------------------------------------------
285{
286 NS_ASSERTION(inRelativePath, "Attempt to do += with a null string");
287
288 if (!inRelativePath || mPath.IsEmpty())
289 return;
290
291 char endChar = mPath[(int)(strlen(mPath) - 1)];
292 if (endChar == '/')
293 mPath += "x";
294 else
295 mPath += "/x";
296 SetLeafName(inRelativePath);
297} // nsFileSpec::operator +=
298
299//----------------------------------------------------------------------------------------
300void nsFileSpec::CreateDirectory(int mode)
301//----------------------------------------------------------------------------------------
302{
303 // Note that mPath is canonical!
304 if (mPath.IsEmpty())
305 return;
306 mkdir(mPath, mode);
307} // nsFileSpec::CreateDirectory
308
309//----------------------------------------------------------------------------------------
310void nsFileSpec::Delete(PRBool inRecursive) const
311// To check if this worked, call Exists() afterwards, see?
312//----------------------------------------------------------------------------------------
313{
314 if (IsDirectory())
315 {
316 if (inRecursive)
317 {
318 for (nsDirectoryIterator i(*this, PR_FALSE); i.Exists(); i++)
319 {
320 nsFileSpec& child = (nsFileSpec&)i;
321 child.Delete(inRecursive);
322 }
323 }
324 rmdir(mPath);
325 }
326 else if (!mPath.IsEmpty())
327 remove(mPath);
328} // nsFileSpec::Delete
329
330//----------------------------------------------------------------------------------------
331void nsFileSpec::RecursiveCopy(nsFileSpec newDir) const
332//----------------------------------------------------------------------------------------
333{
334 if (IsDirectory())
335 {
336 if (!(newDir.Exists()))
337 {
338 newDir.CreateDirectory();
339 }
340
341 for (nsDirectoryIterator i(*this, PR_FALSE); i.Exists(); i++)
342 {
343 nsFileSpec& child = (nsFileSpec&)i;
344
345 if (child.IsDirectory())
346 {
347 nsFileSpec tmpDirSpec(newDir);
348
349 char *leafname = child.GetLeafName();
350 tmpDirSpec += leafname;
351 nsCRT::free(leafname);
352
353 child.RecursiveCopy(tmpDirSpec);
354 }
355 else
356 {
357 child.RecursiveCopy(newDir);
358 }
359 }
360 }
361 else if (!mPath.IsEmpty())
362 {
363 nsFileSpec& filePath = (nsFileSpec&) *this;
364
365 if (!(newDir.Exists()))
366 {
367 newDir.CreateDirectory();
368 }
369
370 filePath.CopyToDir(newDir);
371 }
372} // nsFileSpec::RecursiveCopy
373
374
375//----------------------------------------------------------------------------------------
376nsresult nsFileSpec::Truncate(PRInt32 offset) const
377//----------------------------------------------------------------------------------------
378{
379 char* Path = nsCRT::strdup(mPath);
380
381 int rv = truncate(Path, offset) ;
382
383 nsCRT::free(Path) ;
384
385 if(!rv)
386 return NS_OK ;
387 else
388 return NS_ERROR_FAILURE ;
389} // nsFileSpec::Truncate
390
391//----------------------------------------------------------------------------------------
392nsresult nsFileSpec::Rename(const char* inNewName)
393//----------------------------------------------------------------------------------------
394{
395 NS_ASSERTION(inNewName, "Attempt to Rename with a null string");
396
397 // This function should not be used to move a file on disk.
398 if (mPath.IsEmpty() || strchr(inNewName, '/'))
399 return NS_FILE_FAILURE;
400
401 char* oldPath = nsCRT::strdup(mPath);
402
403 SetLeafName(inNewName);
404
405 if (PR_Rename(oldPath, mPath) != NS_OK)
406 {
407 // Could not rename, set back to the original.
408 mPath = oldPath;
409 return NS_FILE_FAILURE;
410 }
411
412 nsCRT::free(oldPath);
413
414 return NS_OK;
415} // nsFileSpec::Rename
416
417//----------------------------------------------------------------------------------------
418static int CrudeFileCopy(const char* in, const char* out)
419//----------------------------------------------------------------------------------------
420{
421 struct stat in_stat;
422 int stat_result = -1;
423
424 char buf [1024];
425 FILE *ifp, *ofp;
426 int rbytes, wbytes;
427
428 if (!in || !out)
429 return -1;
430
431 stat_result = stat (in, &in_stat);
432
433 ifp = fopen (in, "r");
434 if (!ifp)
435 {
436 return -1;
437 }
438
439 ofp = fopen (out, "w");
440 if (!ofp)
441 {
442 fclose (ifp);
443 return -1;
444 }
445
446 while ((rbytes = fread (buf, 1, sizeof(buf), ifp)) > 0)
447 {
448 while (rbytes > 0)
449 {
450 if ( (wbytes = fwrite (buf, 1, rbytes, ofp)) < 0 )
451 {
452 fclose (ofp);
453 fclose (ifp);
454 unlink(out);
455 return -1;
456 }
457 rbytes -= wbytes;
458 }
459 }
460 fclose (ofp);
461 fclose (ifp);
462
463 if (stat_result == 0)
464 chmod (out, in_stat.st_mode & 0777);
465
466 return 0;
467} // nsFileSpec::Rename
468
469//----------------------------------------------------------------------------------------
470nsresult nsFileSpec::CopyToDir(const nsFileSpec& inParentDirectory) const
471//----------------------------------------------------------------------------------------
472{
473 // We can only copy into a directory, and (for now) can not copy entire directories
474 nsresult result = NS_FILE_FAILURE;
475
476 if (inParentDirectory.IsDirectory() && (! IsDirectory() ) )
477 {
478 char *leafname = GetLeafName();
479 nsSimpleCharString destPath(inParentDirectory.GetCString());
480 destPath += "/";
481 destPath += leafname;
482 nsCRT::free(leafname);
483 result = NS_FILE_RESULT(CrudeFileCopy(GetCString(), destPath));
484 }
485 return result;
486} // nsFileSpec::CopyToDir
487
488//----------------------------------------------------------------------------------------
489nsresult nsFileSpec::MoveToDir(const nsFileSpec& inNewParentDirectory)
490//----------------------------------------------------------------------------------------
491{
492 // We can only copy into a directory, and (for now) can not copy entire directories
493 nsresult result = NS_FILE_FAILURE;
494
495 if (inNewParentDirectory.IsDirectory() && !IsDirectory())
496 {
497 char *leafname = GetLeafName();
498 nsSimpleCharString destPath(inNewParentDirectory.GetCString());
499 destPath += "/";
500 destPath += leafname;
501 nsCRT::free(leafname);
502
503 result = NS_FILE_RESULT(CrudeFileCopy(GetCString(), (const char*)destPath));
504 if (result == NS_OK)
505 {
506 // cast to fix const-ness
507 ((nsFileSpec*)this)->Delete(PR_FALSE);
508
509 *this = inNewParentDirectory + GetLeafName();
510 }
511 }
512 return result;
513}
514
515//----------------------------------------------------------------------------------------
516nsresult nsFileSpec::Execute(const char* inArgs ) const
517//----------------------------------------------------------------------------------------
518{
519 nsresult result = NS_FILE_FAILURE;
520
521 if (!mPath.IsEmpty() && !IsDirectory())
522 {
523 nsSimpleCharString fileNameWithArgs = mPath + " " + inArgs;
524 result = NS_FILE_RESULT(system(fileNameWithArgs));
525 }
526
527 return result;
528
529} // nsFileSpec::Execute
530
531//----------------------------------------------------------------------------------------
532PRInt64 nsFileSpec::GetDiskSpaceAvailable() const
533//----------------------------------------------------------------------------------------
534{
535 PRInt64 bytes; /* XXX dougt needs to fix this */
536 LL_I2L(bytes , LONG_MAX); // initialize to all the space in the world?
537
538
539#if defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_STATVFS_H)
540
541 char curdir [MAXPATHLEN];
542 if (mPath.IsEmpty())
543 {
544 (void) getcwd(curdir, MAXPATHLEN);
545 if (!curdir)
546 return bytes; /* hope for the best as we did in cheddar */
547 }
548 else
549 sprintf(curdir, "%.200s", (const char*)mPath);
550
551 struct STATFS fs_buf;
552#if defined(__QNX__) && !defined(HAVE_STATVFS) /* Maybe this should be handled differently? */
553 if (STATFS(curdir, &fs_buf, 0, 0) < 0)
554#else
555 if (STATFS(curdir, &fs_buf) < 0)
556#endif
557 return bytes; /* hope for the best as we did in cheddar */
558
559#ifdef DEBUG_DISK_SPACE
560 printf("DiskSpaceAvailable: %d bytes\n",
561 fs_buf.f_bsize * (fs_buf.f_bavail - 1));
562#endif
563
564 PRInt64 bsize,bavail;
565 LL_I2L( bsize, fs_buf.f_bsize );
566 LL_I2L( bavail, fs_buf.f_bavail - 1 );
567 LL_MUL( bytes, bsize, bavail );
568 return bytes;
569
570#else
571 /*
572 ** This platform doesn't have statfs or statvfs, so we don't have much
573 ** choice but to "hope for the best as we did in cheddar".
574 */
575 return bytes;
576#endif /* HAVE_SYS_STATFS_H or HAVE_SYS_STATVFS_H */
577
578} // nsFileSpec::GetDiskSpace()
579
580//========================================================================================
581// nsDirectoryIterator
582//========================================================================================
583
584//----------------------------------------------------------------------------------------
585nsDirectoryIterator::nsDirectoryIterator(const nsFileSpec& inDirectory, PRBool resolveSymLinks)
586//----------------------------------------------------------------------------------------
587 : mCurrent(inDirectory)
588 , mExists(PR_FALSE)
589 , mResoveSymLinks(resolveSymLinks)
590 , mStarting(inDirectory)
591 , mDir(nsnull)
592
593{
594 mStarting += "sysygy"; // save off the starting directory
595 mCurrent += "sysygy"; // prepare the path for SetLeafName
596 mDir = opendir((const char*)nsFilePath(inDirectory));
597 ++(*this);
598} // nsDirectoryIterator::nsDirectoryIterator
599
600//----------------------------------------------------------------------------------------
601nsDirectoryIterator::~nsDirectoryIterator()
602//----------------------------------------------------------------------------------------
603{
604 if (mDir)
605 closedir(mDir);
606} // nsDirectoryIterator::nsDirectoryIterator
607
608//----------------------------------------------------------------------------------------
609nsDirectoryIterator& nsDirectoryIterator::operator ++ ()
610//----------------------------------------------------------------------------------------
611{
612 mExists = PR_FALSE;
613 if (!mDir)
614 return *this;
615 const char dot[] = ".";
616 const char dotdot[] = "..";
617 struct dirent* entry = readdir(mDir);
618 if (entry && strcmp(entry->d_name, dot) == 0)
619 entry = readdir(mDir);
620 if (entry && strcmp(entry->d_name, dotdot) == 0)
621 entry = readdir(mDir);
622 if (entry)
623 {
624 mExists = PR_TRUE;
625 mCurrent = mStarting; // restore mCurrent to be the starting directory. ResolveSymlink() may have taken us to another directory
626 mCurrent.SetLeafName(entry->d_name);
627 if (mResoveSymLinks)
628 {
629 PRBool ignore;
630 mCurrent.ResolveSymlink(ignore);
631 }
632 }
633 return *this;
634} // nsDirectoryIterator::operator ++
635
636//----------------------------------------------------------------------------------------
637nsDirectoryIterator& nsDirectoryIterator::operator -- ()
638//----------------------------------------------------------------------------------------
639{
640 return ++(*this); // can't do it backwards.
641} // nsDirectoryIterator::operator --
642
643// Convert a UTF-8 string to a UTF-16 string while normalizing to
644// Normalization Form C (composed Unicode). We need this because
645// Mac OS X file system uses NFD (Normalization Form D : decomposed Unicode)
646// while most other OS', server-side programs usually expect NFC.
647
648#ifdef XP_MACOSX
649typedef void (*UnicodeNormalizer) (CFMutableStringRef, CFStringNormalizationForm);
650static void CopyUTF8toUTF16NFC(const nsACString& aSrc, nsAString& aResult)
651{
652 static PRBool sChecked = PR_FALSE;
653 static UnicodeNormalizer sUnicodeNormalizer = NULL;
654
655 // CFStringNormalize was not introduced until Mac OS 10.2
656 if (!sChecked) {
657 CFBundleRef carbonBundle =
658 CFBundleGetBundleWithIdentifier(CFSTR("com.apple.Carbon"));
659 if (carbonBundle)
660 sUnicodeNormalizer = (UnicodeNormalizer)
661 ::CFBundleGetFunctionPointerForName(carbonBundle,
662 CFSTR("CFStringNormalize"));
663 sChecked = PR_TRUE;
664 }
665
666 if (!sUnicodeNormalizer) { // OS X 10.1 or earlier
667 CopyUTF8toUTF16(aSrc, aResult);
668 return;
669 }
670
671 const nsAFlatCString &inFlatSrc = PromiseFlatCString(aSrc);
672
673 // The number of 16bit code units in a UTF-16 string will never be
674 // larger than the number of bytes in the corresponding UTF-8 string.
675 CFMutableStringRef inStr =
676 ::CFStringCreateMutable(NULL, inFlatSrc.Length());
677
678 if (!inStr) {
679 CopyUTF8toUTF16(aSrc, aResult);
680 return;
681 }
682
683 ::CFStringAppendCString(inStr, inFlatSrc.get(), kCFStringEncodingUTF8);
684
685 sUnicodeNormalizer(inStr, kCFStringNormalizationFormC);
686
687 CFIndex length = CFStringGetLength(inStr);
688 const UniChar* chars = CFStringGetCharactersPtr(inStr);
689
690 if (chars)
691 aResult.Assign(chars, length);
692 else {
693 nsAutoBuffer<UniChar, 512> buffer;
694 if (buffer.EnsureElemCapacity(length)) {
695 CFStringGetCharacters(inStr, CFRangeMake(0, length), buffer.get());
696 aResult.Assign(buffer.get(), length);
697 }
698 else
699 CopyUTF8toUTF16(aSrc, aResult);
700 }
701 CFRelease(inStr);
702}
703#endif
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