3 * - Open, Close and ChDir
14 #define OPEN_MOUNT_ROOT 1
15 #define MAX_PATH_SLASHES 256
16 #define MAX_NESTED_LINKS 4
17 #define MAX_PATH_LEN 255
20 extern tVFS_Mount *gVFS_RootMount;
21 extern int VFS_AllocHandle(int bIsUser, tVFS_Node *Node, int Mode);
22 extern tVFS_Node *VFS_MemFile_Create(const char *Path);
25 void _ReferenceMount(tVFS_Mount *Mount, const char *DebugTag);
26 void _DereferenceMount(tVFS_Mount *Mount, const char *DebugTag);
27 int VFS_int_CreateHandle( tVFS_Node *Node, tVFS_Mount *Mount, int Mode );
30 void _ReferenceMount(tVFS_Mount *Mount, const char *DebugTag)
32 // Log_Debug("VFS", "%s: inc. mntpt '%s' to %i", DebugTag, Mount->MountPoint, Mount->OpenHandleCount+1);
33 Mount->OpenHandleCount ++;
35 void _DereferenceMount(tVFS_Mount *Mount, const char *DebugTag)
37 // Log_Debug("VFS", "%s: dec. mntpt '%s' to %i", DebugTag, Mount->MountPoint, Mount->OpenHandleCount-1);
38 ASSERT(Mount->OpenHandleCount > 0);
39 Mount->OpenHandleCount --;
42 * \fn char *VFS_GetAbsPath(const char *Path)
43 * \brief Create an absolute path from a relative one
45 char *VFS_GetAbsPath(const char *Path)
48 int pathLen = strlen(Path);
49 char *pathComps[MAX_PATH_SLASHES];
53 const char *chroot = *Threads_GetChroot();
55 const char *cwd = *Threads_GetCWD();
62 ret = malloc(strlen(Path)+1);
64 Log_Warning("VFS", "VFS_GetAbsPath: malloc() returned NULL");
75 chrootLen = strlen(chroot);
76 // Trim trailing slash off chroot
77 if( chrootLen && chroot[chrootLen - 1] == '/' )
80 // Check if the path is already absolute
82 ret = malloc(chrootLen + pathLen + 1);
84 Log_Warning("VFS", "VFS_GetAbsPath: malloc() returned NULL");
87 strcpy(ret + chrootLen, Path);
97 // Prepend the current directory
98 ret = malloc(chrootLen + cwdLen + 1 + pathLen + 1 );
99 strcpy(ret+chrootLen, cwd);
101 strcpy(ret+chrootLen+cwdLen+1, Path);
102 //Log("ret = '%s'", ret);
106 pathComps[iPos++] = tmpStr = ret+chrootLen+1;
111 pathComps[iPos++] = tmpStr;
112 if(iPos == MAX_PATH_SLASHES) {
113 LOG("Path '%s' has too many elements", Path);
120 pathComps[iPos] = NULL;
124 while(pathComps[iPos])
126 tmpStr = pathComps[iPos];
127 // Always Increment iPos
130 if(tmpStr[0] == '.' && tmpStr[1] == '.' && (tmpStr[2] == '/' || tmpStr[2] == '\0') )
137 if(tmpStr[0] == '.' && (tmpStr[1] == '/' || tmpStr[1] == '\0') )
142 if(tmpStr[0] == '/' || tmpStr[0] == '\0')
148 pathComps[iPos2] = tmpStr;
151 pathComps[iPos2] = NULL;
154 iPos2 = chrootLen + 1; iPos = 0;
156 while(pathComps[iPos])
158 tmpStr = pathComps[iPos];
159 while(*tmpStr && *tmpStr != '/')
161 ret[iPos2++] = *tmpStr;
172 // Prepend the chroot
174 memcpy( ret, chroot, chrootLen );
177 // Log_Debug("VFS", "VFS_GetAbsPath: RETURN '%s'", ret);
182 * \fn char *VFS_ParsePath(const char *Path, char **TruePath)
183 * \brief Parses a path, resolving sysmlinks and applying permissions
185 tVFS_Node *VFS_ParsePath(const char *Path, char **TruePath, tVFS_Mount **MountPoint)
187 tVFS_Mount *mnt, *longestMount;
188 int cmp, retLength = 0;
190 int iNestedLinks = 0;
191 tVFS_Node *curNode, *tmpNode;
193 char path_buffer[MAX_PATH_LEN+1];
195 ENTER("sPath pTruePath", Path, TruePath);
198 if(Threads_GetUID() == 0 && Path[0] == '$') {
200 *TruePath = malloc(strlen(Path)+1);
201 strcpy(*TruePath, Path);
203 curNode = VFS_MemFile_Create(Path);
212 // For root we always fast return
213 if(Path[0] == '/' && Path[1] == '\0') {
215 *TruePath = malloc( gVFS_RootMount->MountPointLen+1 );
216 strcpy(*TruePath, gVFS_RootMount->MountPoint);
218 _ReferenceMount(gVFS_RootMount, "ParsePath - Fast Tree Root");
219 if(MountPoint) *MountPoint = gVFS_RootMount;
220 LEAVE('p', gVFS_RootMount->RootNode);
221 return gVFS_RootMount->RootNode;
224 // Check if there is anything mounted
226 Log_Error("VFS", "VFS_ParsePath - No filesystems mounted");
231 longestMount = gVFS_RootMount;
232 RWLock_AcquireRead( &glVFS_MountList );
233 for(mnt = gVFS_Mounts; mnt; mnt = mnt->Next)
236 if( Path[mnt->MountPointLen] != '/' && Path[mnt->MountPointLen] != '\0')
238 // Length Check - If the length is smaller than the longest match sofar
239 if(mnt->MountPointLen < longestMount->MountPointLen) continue;
241 cmp = strncmp(Path, mnt->MountPoint, mnt->MountPointLen);
242 // Not a match, continue
243 if(cmp != 0) continue;
246 // Fast Break - Request Mount Root
247 if(Path[mnt->MountPointLen] == '\0') {
249 *TruePath = malloc( mnt->MountPointLen+1 );
250 strcpy(*TruePath, mnt->MountPoint);
254 RWLock_Release( &glVFS_MountList );
255 LOG("Mount %p root", mnt);
256 _ReferenceMount(mnt, "ParsePath - Mount Root");
257 LEAVE('p', mnt->RootNode);
258 return mnt->RootNode;
264 Log_Panic("VFS", "VFS_ParsePath - No mount for '%s'", Path);
268 _ReferenceMount(longestMount, "ParsePath");
269 RWLock_Release( &glVFS_MountList );
271 // Save to shorter variable
274 LOG("mnt = {MountPoint:\"%s\"}", mnt->MountPoint);
279 // Assumes that the resultant path (here) will not be > strlen(Path) + 1
280 *TruePath = malloc( strlen(Path) + 1 );
281 strcpy(*TruePath, mnt->MountPoint);
282 retLength = mnt->MountPointLen;
285 curNode = mnt->RootNode;
286 curNode->ReferenceCount ++;
288 ofs = mnt->MountPointLen+1;
289 for(; (nextSlash = strpos(&Path[ofs], '/')) != -1; ofs += nextSlash + 1)
291 char pathEle[nextSlash+1];
294 if(nextSlash == 0) continue;
296 memcpy(pathEle, &Path[ofs], nextSlash);
297 pathEle[nextSlash] = 0;
299 // Check permissions on root of filesystem
300 if( !VFS_CheckACL(curNode, VFS_PERM_EXECUTE) ) {
301 LOG("Permissions failure on '%s'", Path);
305 // Check if the node has a FindDir method
308 LOG("Finddir failure on '%s' - No type", Path);
309 Log_Error("VFS", "Node at '%s' has no type (mount %s:%s)",
310 Path, mnt->Filesystem->Name, mnt->MountPoint);
313 if( !curNode->Type->FindDir )
315 LOG("Finddir failure on '%s' - No FindDir method in %s", Path, curNode->Type->TypeName);
318 LOG("FindDir{=%p}(%p, '%s')", curNode->Type->FindDir, curNode, pathEle);
320 tmpNode = curNode->Type->FindDir(curNode, pathEle);
321 LOG("tmpNode = %p", tmpNode);
322 _CloseNode( curNode );
327 LOG("Node '%s' not found in dir '%s'", pathEle, Path);
331 // Handle Symbolic Links
332 if(curNode->Flags & VFS_FFLAG_SYMLINK) {
337 if(!curNode->Type || !curNode->Type->Read) {
338 Log_Warning("VFS", "VFS_ParsePath - Read of symlink node %p'%s' is NULL",
343 if(iNestedLinks > MAX_NESTED_LINKS) {
344 Log_Notice("VFS", "VFS_ParsePath - Nested link limit exceeded");
348 // Parse Symlink Path
349 // - Just update the path variable and restart the function
350 // > Count nested symlinks and limit to some value (counteracts loops)
352 int remlen = strlen(Path) - (ofs + nextSlash);
353 if( curNode->Size + remlen > MAX_PATH_LEN ) {
354 Log_Warning("VFS", "VFS_ParsePath - Symlinked path too long");
357 curNode->Type->Read( curNode, 0, curNode->Size, path_buffer );
358 path_buffer[ curNode->Size ] = '\0';
359 LOG("path_buffer = '%s'", path_buffer);
360 strcat(path_buffer, Path + ofs+nextSlash);
361 // TODO: Pass to VFS_GetAbsPath to handle ../. in the symlink
364 // Log_Debug("VFS", "VFS_ParsePath: Symlink translated to '%s'", Path);
369 LOG("Symlink -> '%s', restart", Path);
370 _DereferenceMount(mnt, "ParsePath - sym");
374 // Handle Non-Directories
375 if( !(curNode->Flags & VFS_FFLAG_DIRECTORY) )
377 Log_Warning("VFS", "VFS_ParsePath - Path segment is not a directory");
381 // Check if path needs extending
382 if(!TruePath) continue;
384 // Increase buffer space
385 tmp = realloc( *TruePath, retLength + strlen(pathEle) + 1 + 1 );
386 // Check if allocation succeeded
388 Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
393 (*TruePath)[retLength] = '/';
394 strcpy(*TruePath+retLength+1, pathEle);
396 LOG("*TruePath = '%s'", *TruePath);
399 retLength += nextSlash + 1;
402 // Check final finddir call
403 if( !curNode->Type || !curNode->Type->FindDir ) {
404 Log_Warning("VFS", "VFS_ParsePath - FindDir doesn't exist for element of '%s'", Path);
409 LOG("FindDir(%p, '%s')", curNode, &Path[ofs]);
410 tmpNode = curNode->Type->FindDir(curNode, &Path[ofs]);
411 LOG("tmpNode = %p", tmpNode);
412 // Check if file was found
414 LOG("Node '%s' not found in dir '%.*s'", &Path[ofs], ofs, Path);
417 _CloseNode( curNode );
421 // Increase buffer space
422 tmp = realloc(*TruePath, retLength + strlen(&Path[ofs]) + 1 + 1);
423 // Check if allocation succeeded
425 Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
430 (*TruePath)[retLength] = '/';
431 strcpy(*TruePath + retLength + 1, &Path[ofs]);
433 //retLength += strlen(tmpNode->Name) + 1;
440 // Leave the mointpoint's count increased
446 _CloseNode( curNode );
448 if(TruePath && *TruePath) {
452 // Open failed, so decrement the open handle count
453 _DereferenceMount(mnt, "ParsePath - error");
460 * \brief Create and return a handle number for the given node and mode
462 int VFS_int_CreateHandle( tVFS_Node *Node, tVFS_Mount *Mount, int Mode )
466 ENTER("pNode pMount xMode", Node, Mount, Mode);
469 i |= (Mode & VFS_OPENFLAG_EXEC) ? VFS_PERM_EXECUTE : 0;
470 i |= (Mode & VFS_OPENFLAG_READ) ? VFS_PERM_READ : 0;
471 i |= (Mode & VFS_OPENFLAG_WRITE) ? VFS_PERM_WRITE : 0;
476 if( !VFS_CheckACL(Node, i) ) {
478 Log_Log("VFS", "VFS_int_CreateHandle: Permissions Failed");
483 if( MM_GetPhysAddr(Node->Type) == 0 ) {
484 Log_Error("VFS", "Node %p from mount '%s' (%s) has a bad type (%p)",
485 Node, Mount->MountPoint, Mount->Filesystem->Name, Node->Type);
490 i = VFS_AllocHandle( !!(Mode & VFS_OPENFLAG_USER), Node, Mode );
492 Log_Notice("VFS", "VFS_int_CreateHandle: Out of handles");
497 VFS_GetHandle(i)->Mount = Mount;
503 * \fn int VFS_Open(const char *Path, Uint Mode)
506 int VFS_Open(const char *Path, Uint Flags)
508 return VFS_OpenEx(Path, Flags, 0);
511 int VFS_OpenEx(const char *Path, Uint Flags, Uint Mode)
517 ENTER("sPath xFlags oMode", Path, Flags);
520 absPath = VFS_GetAbsPath(Path);
521 if(absPath == NULL) {
522 Log_Warning("VFS", "VFS_Open: Path expansion failed '%s'", Path);
525 LOG("absPath = \"%s\"", absPath);
527 // Parse path and get mount point
528 node = VFS_ParsePath(absPath, NULL, &mnt);
530 // Create file if requested and it doesn't exist
531 if( !node && (Flags & VFS_OPENFLAG_CREATE) )
533 // TODO: Translate `Mode` into ACL and node flags
536 // Split path at final separator
537 char *file = strrchr(absPath, '/');
543 tVFS_Node *pnode = VFS_ParsePath(absPath, NULL, &pmnt);
545 LOG("Unable to open parent '%s'", absPath);
551 // Check ACLs on the parent
552 if( !VFS_CheckACL(pnode, VFS_PERM_EXECUTE|VFS_PERM_WRITE) ) {
557 // Check that there's a MkNod method
558 if( !pnode->Type || !pnode->Type->MkNod ) {
559 Log_Warning("VFS", "VFS_Open - Directory has no MkNod method");
564 node = pnode->Type->MkNod(pnode, file, new_flags);
566 LOG("Cannot create node '%s' in '%s'", file, absPath);
570 // Set mountpoint (and increment open handle count)
572 _ReferenceMount(mnt, "Open - create");
573 // Fall through on error check
576 _DereferenceMount(pmnt, "Open - create");
582 _DereferenceMount(pmnt, "Open - create,fail");
590 // Free generated path
596 LOG("Cannot find node");
601 // Check for symlinks
602 if( !(Flags & VFS_OPENFLAG_NOLINK) && (node->Flags & VFS_FFLAG_SYMLINK) )
604 char tmppath[node->Size+1];
605 if( node->Size > MAX_PATH_LEN ) {
606 Log_Warning("VFS", "VFS_Open - Symlink is too long (%i)", node->Size);
609 if( !node->Type || !node->Type->Read ) {
610 Log_Warning("VFS", "VFS_Open - No read method on symlink");
613 // Read symlink's path
614 node->Type->Read( node, 0, node->Size, tmppath );
615 tmppath[ node->Size ] = '\0';
617 _DereferenceMount(mnt, "Open - symlink");
619 node = VFS_ParsePath(tmppath, NULL, &mnt);
621 LOG("Cannot find symlink target node (%s)", tmppath);
627 int ret = VFS_int_CreateHandle(node, mnt, Flags);
632 _DereferenceMount(mnt, "Open - error");
640 * \brief Open a file from an open directory
642 int VFS_OpenChild(int FD, const char *Name, Uint Mode)
647 ENTER("xFD sName xMode", FD, Name, Mode);
650 h = VFS_GetHandle(FD);
652 Log_Warning("VFS", "VFS_OpenChild - Invalid file handle 0x%x", FD);
657 // Check for directory
658 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
659 Log_Warning("VFS", "VFS_OpenChild - Passed handle is not a directory");
665 if( !h->Node->Type || !h->Node->Type->FindDir ) {
666 Log_Error("VFS", "VFS_OpenChild - Node does not have a type/is missing FindDir");
672 node = h->Node->Type->FindDir(h->Node, Name);
678 // Increment open handle count, no problems with the mount going away as `h` is already open on it
679 _ReferenceMount(h->Mount, "OpenChild");
681 LEAVE_RET('x', VFS_int_CreateHandle(node, h->Mount, Mode));
684 int VFS_OpenInode(Uint32 Mount, Uint64 Inode, int Mode)
689 ENTER("iMount XInode xMode", Mount, Inode, Mode);
692 mnt = VFS_GetMountByIdent(Mount);
694 LOG("Mount point ident invalid");
699 // Does the filesystem support this?
700 if( !mnt->Filesystem->GetNodeFromINode ) {
701 LOG("Filesystem does not support inode accesses");
707 node = mnt->Filesystem->GetNodeFromINode(mnt->RootNode, Inode);
709 LOG("Unable to find inode");
714 LEAVE_RET('x', VFS_int_CreateHandle(node, mnt, Mode));
718 * \fn void VFS_Close(int FD)
719 * \brief Closes an open file handle
721 void VFS_Close(int FD)
726 h = VFS_GetHandle(FD);
728 Log_Warning("VFS", "Invalid file handle passed to VFS_Close, 0x%x", FD);
732 if( h->Node == NULL ) {
733 Log_Warning("VFS", "Non-open handle passed to VFS_Close, 0x%x", FD);
737 #if VALIDATE_VFS_FUNCTIPONS
738 if(h->Node->Close && !MM_GetPhysAddr(h->Node->Close)) {
739 Log_Warning("VFS", "Node %p's ->Close method is invalid (%p)",
740 h->Node, h->Node->Close);
745 LOG("Handle %x", FD);
749 _DereferenceMount(h->Mount, "Close");
756 * \brief Change current working directory
758 int VFS_ChDir(const char *Dest)
765 buf = VFS_GetAbsPath(Dest);
767 Log_Notice("VFS", "VFS_ChDir: Path expansion failed");
771 // Check if path exists
772 fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
774 Log_Notice("VFS", "VFS_ChDir: Path is invalid");
778 // Get node so we can check for directory
779 h = VFS_GetHandle(fd);
780 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
781 Log("VFS_ChDir: Path is not a directory");
790 char **cwdptr = Threads_GetCWD();
791 // Free old working directory
792 if( *cwdptr ) free( *cwdptr );
797 Log_Debug("VFS", "Updated CWD to '%s'", buf);
803 * \fn int VFS_ChRoot(char *New)
804 * \brief Change current root directory
806 int VFS_ChRoot(const char *New)
812 if(New[0] == '/' && New[1] == '\0')
813 return 1; // What a useless thing to ask!
816 buf = VFS_GetAbsPath(New);
818 LOG("Path expansion failed");
822 // Check if path exists
823 fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
825 LOG("Path is invalid");
829 // Get node so we can check for directory
830 h = VFS_GetHandle(fd);
831 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
832 LOG("Path is not a directory");
842 char **chroot_ptr = Threads_GetChroot();
843 if( *chroot_ptr ) free( *chroot_ptr );
847 LOG("Updated Root to '%s'", buf);