Back to index

lightning-sunbird  0.9+nobinonly
nsFileSpecBeOS.cpp
Go to the documentation of this file.
00001 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
00002 /* ***** BEGIN LICENSE BLOCK *****
00003  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00004  *
00005  * The contents of this file are subject to the Mozilla Public License Version
00006  * 1.1 (the "License"); you may not use this file except in compliance with
00007  * the License. You may obtain a copy of the License at
00008  * http://www.mozilla.org/MPL/
00009  *
00010  * Software distributed under the License is distributed on an "AS IS" basis,
00011  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00012  * for the specific language governing rights and limitations under the
00013  * License.
00014  *
00015  * The Original Code is mozilla.org code.
00016  *
00017  * The Initial Developer of the Original Code is
00018  * Netscape Communications Corporation.
00019  * Portions created by the Initial Developer are Copyright (C) 1998
00020  * the Initial Developer. All Rights Reserved.
00021  *
00022  * Contributor(s):
00023  *
00024  * Alternatively, the contents of this file may be used under the terms of
00025  * either of the GNU General Public License Version 2 or later (the "GPL"),
00026  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00027  * in which case the provisions of the GPL or the LGPL are applicable instead
00028  * of those above. If you wish to allow use of your version of this file only
00029  * under the terms of either the GPL or the LGPL, and not to allow others to
00030  * use your version of this file under the terms of the MPL, indicate your
00031  * decision by deleting the provisions above and replace them with the notice
00032  * and other provisions required by the GPL or the LGPL. If you do not delete
00033  * the provisions above, a recipient may use your version of this file under
00034  * the terms of any one of the MPL, the GPL or the LGPL.
00035  *
00036  * ***** END LICENSE BLOCK ***** */
00037  
00038 //    This file is included by nsFileSpec.cpp, and includes the Unix-specific
00039 //    implementations.
00040 
00041 #include <sys/stat.h>
00042 #include <sys/param.h>
00043 #include <errno.h>
00044 #include <dirent.h>
00045 #include <unistd.h>
00046 #include <stdlib.h>
00047 #include <limits.h>
00048 #include "nsError.h"
00049 #include "prio.h"   /* for PR_Rename */
00050 
00051 // BeOS specific headers
00052 #include <Entry.h>
00053 #include <Path.h>
00054 #include <Volume.h>
00055 
00056 //----------------------------------------------------------------------------------------
00057 void nsFileSpecHelpers::Canonify(nsSimpleCharString& ioPath, PRBool inMakeDirs)
00058 // Canonify, make absolute, and check whether directories exist
00059 //----------------------------------------------------------------------------------------
00060 {
00061     if (ioPath.IsEmpty())
00062         return;
00063     if (inMakeDirs)
00064     {
00065         const mode_t mode = 0700;
00066         nsFileSpecHelpers::MakeAllDirectories((const char*)ioPath, mode);
00067     }
00068     char buffer[MAXPATHLEN];
00069     errno = 0;
00070     *buffer = '\0';
00071     BEntry e((const char *)ioPath, true);
00072     BPath p;
00073     e.GetPath(&p);
00074     ioPath = p.Path();
00075 } // nsFileSpecHelpers::Canonify
00076 
00077 //----------------------------------------------------------------------------------------
00078 void nsFileSpec::SetLeafName(const char* inLeafName)
00079 //----------------------------------------------------------------------------------------
00080 {
00081     mPath.LeafReplace('/', inLeafName);
00082 } // nsFileSpec::SetLeafName
00083 
00084 //----------------------------------------------------------------------------------------
00085 char* nsFileSpec::GetLeafName() const
00086 //----------------------------------------------------------------------------------------
00087 {
00088     return mPath.GetLeaf('/');
00089 } // nsFileSpec::GetLeafName
00090 
00091 //----------------------------------------------------------------------------------------
00092 PRBool nsFileSpec::Exists() const
00093 //----------------------------------------------------------------------------------------
00094 {
00095     struct stat st;
00096     return !mPath.IsEmpty() && 0 == stat(mPath, &st); 
00097 } // nsFileSpec::Exists
00098 
00099 //----------------------------------------------------------------------------------------
00100 void nsFileSpec::GetModDate(TimeStamp& outStamp) const
00101 //----------------------------------------------------------------------------------------
00102 {
00103        struct stat st;
00104     if (!mPath.IsEmpty() && stat(mPath, &st) == 0) 
00105         outStamp = st.st_mtime; 
00106     else
00107         outStamp = 0;
00108 } // nsFileSpec::GetModDate
00109 
00110 //----------------------------------------------------------------------------------------
00111 PRUint32 nsFileSpec::GetFileSize() const
00112 //----------------------------------------------------------------------------------------
00113 {
00114        struct stat st;
00115     if (!mPath.IsEmpty() && stat(mPath, &st) == 0) 
00116         return (PRUint32)st.st_size; 
00117     return 0;
00118 } // nsFileSpec::GetFileSize
00119 
00120 //----------------------------------------------------------------------------------------
00121 PRBool nsFileSpec::IsFile() const
00122 //----------------------------------------------------------------------------------------
00123 {
00124     struct stat st;
00125     return !mPath.IsEmpty() && stat(mPath, &st) == 0 && S_ISREG(st.st_mode); 
00126 } // nsFileSpec::IsFile
00127 
00128 //----------------------------------------------------------------------------------------
00129 PRBool nsFileSpec::IsDirectory() const
00130 //----------------------------------------------------------------------------------------
00131 {
00132     struct stat st;
00133     return !mPath.IsEmpty() && 0 == stat(mPath, &st) && S_ISDIR(st.st_mode); 
00134 } // nsFileSpec::IsDirectory
00135 
00136 //----------------------------------------------------------------------------------------
00137 PRBool nsFileSpec::IsHidden() const
00138 //----------------------------------------------------------------------------------------
00139 {
00140     PRBool hidden = PR_TRUE;
00141     char *leafname = GetLeafName();
00142     if (nsnull != leafname)
00143     {
00144         if ((!strcmp(leafname, ".")) || (!strcmp(leafname, "..")))
00145         {
00146             hidden = PR_FALSE;
00147         }
00148         nsCRT::free(leafname);
00149     }
00150     return hidden;
00151 } // nsFileSpec::IsHidden
00152 
00153 //----------------------------------------------------------------------------------------
00154 PRBool nsFileSpec::IsSymlink() const
00155 //----------------------------------------------------------------------------------------
00156 {
00157     struct stat st;
00158     if (!mPath.IsEmpty() && stat(mPath, &st) == 0 && S_ISLNK(st.st_mode))
00159         return PR_TRUE;
00160 
00161     return PR_FALSE;
00162 } // nsFileSpec::IsSymlink
00163 
00164 //----------------------------------------------------------------------------------------
00165 nsresult nsFileSpec::ResolveSymlink(PRBool& wasAliased)
00166 //----------------------------------------------------------------------------------------
00167 {
00168     wasAliased = PR_FALSE;
00169 
00170     char resolvedPath[MAXPATHLEN];
00171     int charCount = readlink(mPath, (char*)&resolvedPath, MAXPATHLEN);
00172     if (0 < charCount)
00173     {
00174         if (MAXPATHLEN > charCount)
00175             resolvedPath[charCount] = '\0';
00176         
00177         wasAliased = PR_TRUE;
00178               /* if it's not an absolute path, 
00179                  replace the leaf with what got resolved */
00180               if (resolvedPath[0] != '/') {
00181                      SetLeafName(resolvedPath);
00182               }
00183               else {
00184                      mPath = (char*)resolvedPath;
00185               } 
00186 
00187               BEntry e((const char *)mPath, true);      // traverse symlink
00188               BPath p;
00189               status_t err;
00190               err = e.GetPath(&p);
00191               NS_ASSERTION(err == B_OK, "realpath failed");
00192 
00193               const char* canonicalPath = p.Path();
00194               if(err == B_OK)
00195                      mPath = (char*)canonicalPath;
00196               else
00197                      return NS_ERROR_FAILURE;
00198     }
00199     return NS_OK;
00200 } // nsFileSpec::ResolveSymlink
00201 
00202 //----------------------------------------------------------------------------------------
00203 void nsFileSpec::GetParent(nsFileSpec& outSpec) const
00204 //----------------------------------------------------------------------------------------
00205 {
00206     outSpec.mPath = mPath;
00207        char* chars = (char*)outSpec.mPath;
00208        chars[outSpec.mPath.Length() - 1] = '\0'; // avoid trailing separator, if any
00209     char* cp = strrchr(chars, '/');
00210     if (cp++)
00211            outSpec.mPath.SetLength(cp - chars); // truncate.
00212 } // nsFileSpec::GetParent
00213 
00214 //----------------------------------------------------------------------------------------
00215 void nsFileSpec::operator += (const char* inRelativePath)
00216 //----------------------------------------------------------------------------------------
00217 {
00218     if (!inRelativePath || mPath.IsEmpty())
00219         return;
00220     
00221     char endChar = mPath[(int)(strlen(mPath) - 1)];
00222     if (endChar == '/')
00223         mPath += "x";
00224     else
00225         mPath += "/x";
00226     SetLeafName(inRelativePath);
00227 } // nsFileSpec::operator +=
00228 
00229 //----------------------------------------------------------------------------------------
00230 void nsFileSpec::CreateDirectory(int mode)
00231 //----------------------------------------------------------------------------------------
00232 {
00233     // Note that mPath is canonical!
00234     if (mPath.IsEmpty())
00235         return;
00236     mkdir(mPath, mode);
00237 } // nsFileSpec::CreateDirectory
00238 
00239 //----------------------------------------------------------------------------------------
00240 void nsFileSpec::Delete(PRBool inRecursive) const
00241 // To check if this worked, call Exists() afterwards, see?
00242 //----------------------------------------------------------------------------------------
00243 {
00244     if (IsDirectory())
00245     {
00246         if (inRecursive)
00247         {
00248             for (nsDirectoryIterator i(*this, PR_FALSE); i.Exists(); i++)
00249             {
00250                 nsFileSpec& child = (nsFileSpec&)i;
00251                 child.Delete(inRecursive);
00252             }        
00253         }
00254         rmdir(mPath);
00255     }
00256     else if (!mPath.IsEmpty())
00257         remove(mPath);
00258 } // nsFileSpec::Delete
00259 
00260 //----------------------------------------------------------------------------------------
00261 void nsFileSpec::RecursiveCopy(nsFileSpec newDir) const
00262 //----------------------------------------------------------------------------------------
00263 {
00264     if (IsDirectory())
00265     {
00266               if (!(newDir.Exists()))
00267               {
00268                      newDir.CreateDirectory();
00269               }
00270 
00271               for (nsDirectoryIterator i(*this, PR_FALSE); i.Exists(); i++)
00272               {
00273                      nsFileSpec& child = (nsFileSpec&)i;
00274 
00275                      if (child.IsDirectory())
00276                      {
00277                             nsFileSpec tmpDirSpec(newDir);
00278 
00279                             char *leafname = child.GetLeafName();
00280                             tmpDirSpec += leafname;
00281                             nsCRT::free(leafname);
00282 
00283                             child.RecursiveCopy(tmpDirSpec);
00284                      }
00285                      else
00286                      {
00287                             child.RecursiveCopy(newDir);
00288                      }
00289               }
00290     }
00291     else if (!mPath.IsEmpty())
00292     {
00293               nsFileSpec& filePath = (nsFileSpec&) *this;
00294 
00295               if (!(newDir.Exists()))
00296               {
00297                      newDir.CreateDirectory();
00298               }
00299 
00300         filePath.CopyToDir(newDir);
00301     }
00302 } // nsFileSpec::RecursiveCopy
00303 
00304 //----------------------------------------------------------------------------------------
00305 nsresult nsFileSpec::Truncate(PRInt32 offset) const
00306 //----------------------------------------------------------------------------------------
00307 {
00308     char* Path = nsCRT::strdup(mPath);
00309 
00310     int rv = truncate(Path, offset) ;
00311 
00312     nsCRT::free(Path) ;
00313 
00314     if(!rv) 
00315         return NS_OK ;
00316     else
00317         return NS_ERROR_FAILURE ;
00318 } // nsFileSpec::Truncate
00319 
00320 //----------------------------------------------------------------------------------------
00321 nsresult nsFileSpec::Rename(const char* inNewName)
00322 //----------------------------------------------------------------------------------------
00323 {
00324     // This function should not be used to move a file on disk. 
00325     if (mPath.IsEmpty() || strchr(inNewName, '/')) 
00326         return NS_FILE_FAILURE;
00327 
00328     char* oldPath = nsCRT::strdup(mPath);
00329     
00330     SetLeafName(inNewName); 
00331 
00332     if (PR_Rename(oldPath, mPath) != NS_OK)
00333     {
00334         // Could not rename, set back to the original.
00335         mPath = oldPath;
00336         return NS_FILE_FAILURE;
00337     }
00338     
00339     nsCRT::free(oldPath);
00340 
00341     return NS_OK;
00342 } // nsFileSpec::Rename
00343 
00344 //----------------------------------------------------------------------------------------
00345 static int CrudeFileCopy(const char* in, const char* out)
00346 //----------------------------------------------------------------------------------------
00347 {
00348        struct stat in_stat;
00349        int stat_result = -1;
00350 
00351        char   buf [1024];
00352        FILE   *ifp, *ofp;
00353        int    rbytes, wbytes;
00354 
00355        if (!in || !out)
00356               return -1;
00357 
00358        stat_result = stat (in, &in_stat);
00359 
00360        ifp = fopen (in, "r");
00361        if (!ifp) 
00362        {
00363               return -1;
00364        }
00365 
00366        ofp = fopen (out, "w");
00367        if (!ofp)
00368        {
00369               fclose (ifp);
00370               return -1;
00371        }
00372 
00373        while ((rbytes = fread (buf, 1, sizeof(buf), ifp)) > 0)
00374        {
00375               while (rbytes > 0)
00376               {
00377                      if ( (wbytes = fwrite (buf, 1, rbytes, ofp)) < 0 )
00378                      {
00379                             fclose (ofp);
00380                             fclose (ifp);
00381                             unlink(out);
00382                             return -1;
00383                      }
00384                      rbytes -= wbytes;
00385               }
00386        }
00387        fclose (ofp);
00388        fclose (ifp);
00389 
00390        if (stat_result == 0)
00391               chmod (out, in_stat.st_mode & 0777);
00392 
00393        return 0;
00394 } // nsFileSpec::Rename
00395 
00396 //----------------------------------------------------------------------------------------
00397 nsresult nsFileSpec::CopyToDir(const nsFileSpec& inParentDirectory) const
00398 //----------------------------------------------------------------------------------------
00399 {
00400     // We can only copy into a directory, and (for now) can not copy entire directories
00401     nsresult result = NS_FILE_FAILURE;
00402 
00403     if (inParentDirectory.IsDirectory() && (! IsDirectory() ) )
00404     {
00405         char *leafname = GetLeafName();
00406         nsSimpleCharString destPath(inParentDirectory.GetCString());
00407         destPath += "/";
00408         destPath += leafname;
00409         nsCRT::free(leafname);
00410         result = NS_FILE_RESULT(CrudeFileCopy(GetCString(), destPath));
00411     }
00412     return result;
00413 } // nsFileSpec::CopyToDir
00414 
00415 //----------------------------------------------------------------------------------------
00416 nsresult nsFileSpec::MoveToDir(const nsFileSpec& inNewParentDirectory)
00417 //----------------------------------------------------------------------------------------
00418 {
00419     // We can only copy into a directory, and (for now) can not copy entire directories
00420     nsresult result = NS_FILE_FAILURE;
00421 
00422     if (inNewParentDirectory.IsDirectory() && !IsDirectory())
00423     {
00424         char *leafname = GetLeafName();
00425         nsSimpleCharString destPath(inNewParentDirectory.GetCString());
00426         destPath += "/";
00427         destPath += leafname;
00428         nsCRT::free(leafname);
00429 
00430         result = NS_FILE_RESULT(CrudeFileCopy(GetCString(), (const char*)destPath));
00431         if (result == NS_OK)
00432         {
00433             // cast to fix const-ness
00434                   ((nsFileSpec*)this)->Delete(PR_FALSE);
00435         
00436             *this = inNewParentDirectory + GetLeafName(); 
00437        }
00438     }
00439     return result;
00440 } 
00441 
00442 //----------------------------------------------------------------------------------------
00443 nsresult nsFileSpec::Execute(const char* inArgs ) const
00444 //----------------------------------------------------------------------------------------
00445 {
00446     nsresult result = NS_FILE_FAILURE;
00447     
00448     if (!mPath.IsEmpty() && !IsDirectory())
00449     {
00450         nsSimpleCharString fileNameWithArgs = mPath + " " + inArgs;
00451         result = NS_FILE_RESULT(system(fileNameWithArgs));
00452     } 
00453 
00454     return result;
00455 
00456 } // nsFileSpec::Execute
00457 
00458 //----------------------------------------------------------------------------------------
00459 PRInt64 nsFileSpec::GetDiskSpaceAvailable() const
00460 //----------------------------------------------------------------------------------------
00461 {
00462     char curdir [MAXPATHLEN];
00463     if (!mPath || !*mPath)
00464     {
00465         (void) getcwd(curdir, MAXPATHLEN);
00466         if (!curdir)
00467             return ULONGLONG_MAX;  /* hope for the best as we did in cheddar */
00468     }
00469     else
00470         sprintf(curdir, "%.200s", (const char*)mPath);
00471 
00472     BEntry e(curdir);
00473     if(e.InitCheck() != B_OK)
00474         return ULONGLONG_MAX; /* hope for the best as we did in cheddar */
00475     entry_ref ref;
00476     e.GetRef(&ref);
00477     BVolume v(ref.device);
00478 
00479 #ifdef DEBUG_DISK_SPACE
00480     printf("DiskSpaceAvailable: %d bytes\n", space);
00481 #endif
00482     return v.FreeBytes();
00483 } // nsFileSpec::GetDiskSpace()
00484 
00485 //========================================================================================
00486 //                                nsDirectoryIterator
00487 //========================================================================================
00488 
00489 //----------------------------------------------------------------------------------------
00490 nsDirectoryIterator::nsDirectoryIterator(
00491     const nsFileSpec& inDirectory
00492 ,   PRBool resolveSymlinks)
00493 //----------------------------------------------------------------------------------------
00494     : mCurrent(inDirectory)
00495     , mStarting(inDirectory)
00496     , mExists(PR_FALSE)
00497     , mDir(nsnull)
00498     , mResoveSymLinks(resolveSymlinks)
00499 {
00500     mStarting += "sysygy"; // save off the starting directory
00501     mCurrent += "sysygy"; // prepare the path for SetLeafName
00502     mDir = opendir((const char*)nsFilePath(inDirectory));
00503     ++(*this);
00504 } // nsDirectoryIterator::nsDirectoryIterator
00505 
00506 //----------------------------------------------------------------------------------------
00507 nsDirectoryIterator::~nsDirectoryIterator()
00508 //----------------------------------------------------------------------------------------
00509 {
00510     if (mDir)
00511         closedir(mDir);
00512 } // nsDirectoryIterator::nsDirectoryIterator
00513 
00514 //----------------------------------------------------------------------------------------
00515 nsDirectoryIterator& nsDirectoryIterator::operator ++ ()
00516 //----------------------------------------------------------------------------------------
00517 {
00518     mExists = PR_FALSE;
00519     if (!mDir)
00520         return *this;
00521     char* dot    = ".";
00522     char* dotdot = "..";
00523     struct dirent* entry = readdir(mDir);
00524     if (entry && strcmp(entry->d_name, dot) == 0)
00525         entry = readdir(mDir);
00526     if (entry && strcmp(entry->d_name, dotdot) == 0)
00527         entry = readdir(mDir);
00528     if (entry)
00529     {
00530         mExists = PR_TRUE;
00531        mCurrent = mStarting;              // restore mCurrent to be the starting directory.  ResolveSymlink() may have taken us to another directory
00532         mCurrent.SetLeafName(entry->d_name);
00533         if (mResoveSymLinks)
00534         {   
00535           PRBool ignore;
00536           mCurrent.ResolveSymlink(ignore);
00537         }
00538     }
00539     return *this;
00540 } // nsDirectoryIterator::operator ++
00541 
00542 //----------------------------------------------------------------------------------------
00543 nsDirectoryIterator& nsDirectoryIterator::operator -- ()
00544 //----------------------------------------------------------------------------------------
00545 {
00546     return ++(*this); // can't do it backwards.
00547 } // nsDirectoryIterator::operator --