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 tVFS_Node *VFS_MemFile_Create(const char *Path);
24 void _ReferenceMount(tVFS_Mount *Mount, const char *DebugTag);
25 void _DereferenceMount(tVFS_Mount *Mount, const char *DebugTag);
26 int VFS_int_CreateHandle(tVFS_Node *Node, tVFS_Mount *Mount, int Mode);
29 void _ReferenceMount(tVFS_Mount *Mount, const char *DebugTag)
31 // Log_Debug("VFS", "%s: inc. mntpt '%s' to %i", DebugTag, Mount->MountPoint, Mount->OpenHandleCount+1);
32 Mount->OpenHandleCount ++;
34 void _DereferenceMount(tVFS_Mount *Mount, const char *DebugTag)
36 // Log_Debug("VFS", "%s: dec. mntpt '%s' to %i", DebugTag, Mount->MountPoint, Mount->OpenHandleCount-1);
37 ASSERT(Mount->OpenHandleCount > 0);
38 Mount->OpenHandleCount --;
41 * \fn char *VFS_GetAbsPath(const char *Path)
42 * \brief Create an absolute path from a relative one
44 char *VFS_GetAbsPath(const char *Path)
47 int pathLen = strlen(Path);
48 char *pathComps[MAX_PATH_SLASHES];
52 const char *chroot = *Threads_GetChroot();
54 const char *cwd = *Threads_GetCWD();
61 ret = malloc(strlen(Path)+1);
63 Log_Warning("VFS", "VFS_GetAbsPath: malloc() returned NULL");
74 chrootLen = strlen(chroot);
75 // Trim trailing slash off chroot
76 if( chrootLen && chroot[chrootLen - 1] == '/' )
79 // Check if the path is already absolute
81 ret = malloc(chrootLen + pathLen + 1);
83 Log_Warning("VFS", "VFS_GetAbsPath: malloc() returned NULL");
86 strcpy(ret + chrootLen, Path);
96 // Prepend the current directory
97 ret = malloc(chrootLen + cwdLen + 1 + pathLen + 1 );
98 strcpy(ret+chrootLen, cwd);
100 strcpy(ret+chrootLen+cwdLen+1, Path);
101 //Log("ret = '%s'", ret);
105 pathComps[iPos++] = tmpStr = ret+chrootLen+1;
110 pathComps[iPos++] = tmpStr;
111 if(iPos == MAX_PATH_SLASHES) {
112 LOG("Path '%s' has too many elements", Path);
119 pathComps[iPos] = NULL;
123 while(pathComps[iPos])
125 tmpStr = pathComps[iPos];
126 // Always Increment iPos
129 if(tmpStr[0] == '.' && tmpStr[1] == '.' && (tmpStr[2] == '/' || tmpStr[2] == '\0') )
136 if(tmpStr[0] == '.' && (tmpStr[1] == '/' || tmpStr[1] == '\0') )
141 if(tmpStr[0] == '/' || tmpStr[0] == '\0')
147 pathComps[iPos2] = tmpStr;
150 pathComps[iPos2] = NULL;
153 iPos2 = chrootLen + 1; iPos = 0;
155 while(pathComps[iPos])
157 tmpStr = pathComps[iPos];
158 while(*tmpStr && *tmpStr != '/')
160 ret[iPos2++] = *tmpStr;
171 // Prepend the chroot
173 memcpy( ret, chroot, chrootLen );
176 // Log_Debug("VFS", "VFS_GetAbsPath: RETURN '%s'", ret);
181 * \fn char *VFS_ParsePath(const char *Path, char **TruePath)
182 * \brief Parses a path, resolving sysmlinks and applying permissions
184 tVFS_Node *VFS_ParsePath(const char *Path, char **TruePath, tVFS_Mount **MountPoint)
186 tVFS_Mount *mnt, *longestMount;
187 int cmp, retLength = 0;
189 int iNestedLinks = 0;
190 tVFS_Node *curNode, *tmpNode;
192 char path_buffer[MAX_PATH_LEN+1];
194 ENTER("sPath pTruePath", Path, TruePath);
197 if(Threads_GetUID() == 0 && Path[0] == '$') {
199 *TruePath = malloc(strlen(Path)+1);
200 strcpy(*TruePath, Path);
202 curNode = VFS_MemFile_Create(Path);
211 // For root we always fast return
212 if(Path[0] == '/' && Path[1] == '\0') {
214 *TruePath = malloc( gVFS_RootMount->MountPointLen+1 );
215 strcpy(*TruePath, gVFS_RootMount->MountPoint);
217 _ReferenceMount(gVFS_RootMount, "ParsePath - Fast Tree Root");
218 if(MountPoint) *MountPoint = gVFS_RootMount;
219 LEAVE('p', gVFS_RootMount->RootNode);
220 return gVFS_RootMount->RootNode;
223 // Check if there is anything mounted
225 Log_Error("VFS", "VFS_ParsePath - No filesystems mounted");
230 longestMount = gVFS_RootMount;
231 RWLock_AcquireRead( &glVFS_MountList );
232 for(mnt = gVFS_Mounts; mnt; mnt = mnt->Next)
235 if( Path[mnt->MountPointLen] != '/' && Path[mnt->MountPointLen] != '\0')
237 // Length Check - If the length is smaller than the longest match sofar
238 if(mnt->MountPointLen < longestMount->MountPointLen) continue;
240 cmp = strncmp(Path, mnt->MountPoint, mnt->MountPointLen);
241 // Not a match, continue
242 if(cmp != 0) continue;
245 // Fast Break - Request Mount Root
246 if(Path[mnt->MountPointLen] == '\0') {
248 *TruePath = malloc( mnt->MountPointLen+1 );
249 strcpy(*TruePath, mnt->MountPoint);
253 RWLock_Release( &glVFS_MountList );
254 LOG("Mount %p root", mnt);
255 _ReferenceMount(mnt, "ParsePath - Mount Root");
256 LEAVE('p', mnt->RootNode);
257 return mnt->RootNode;
263 Log_Panic("VFS", "VFS_ParsePath - No mount for '%s'", Path);
267 _ReferenceMount(longestMount, "ParsePath");
268 RWLock_Release( &glVFS_MountList );
270 // Save to shorter variable
273 LOG("mnt = {MountPoint:\"%s\"}", mnt->MountPoint);
278 // Assumes that the resultant path (here) will not be > strlen(Path) + 1
279 *TruePath = malloc( strlen(Path) + 1 );
280 strcpy(*TruePath, mnt->MountPoint);
281 retLength = mnt->MountPointLen;
284 curNode = mnt->RootNode;
285 curNode->ReferenceCount ++;
287 ofs = mnt->MountPointLen+1;
288 for(; (nextSlash = strpos(&Path[ofs], '/')) != -1; ofs += nextSlash + 1)
290 char pathEle[nextSlash+1];
293 if(nextSlash == 0) continue;
295 memcpy(pathEle, &Path[ofs], nextSlash);
296 pathEle[nextSlash] = 0;
298 // Check permissions on root of filesystem
299 if( !VFS_CheckACL(curNode, VFS_PERM_EXECUTE) ) {
300 LOG("Permissions failure on '%s'", Path);
304 // Check if the node has a FindDir method
307 LOG("Finddir failure on '%s' - No type", Path);
308 Log_Error("VFS", "Node at '%s' has no type (mount %s:%s)",
309 Path, mnt->Filesystem->Name, mnt->MountPoint);
312 if( !curNode->Type->FindDir )
314 LOG("Finddir failure on '%s' - No FindDir method in %s", Path, curNode->Type->TypeName);
317 LOG("FindDir{=%p}(%p, '%s')", curNode->Type->FindDir, curNode, pathEle);
319 tmpNode = curNode->Type->FindDir(curNode, pathEle);
320 LOG("tmpNode = %p", tmpNode);
321 _CloseNode( curNode );
326 LOG("Node '%s' not found in dir '%s'", pathEle, Path);
330 // Handle Symbolic Links
331 if(curNode->Flags & VFS_FFLAG_SYMLINK) {
336 if(!curNode->Type || !curNode->Type->Read) {
337 Log_Warning("VFS", "VFS_ParsePath - Read of symlink node %p'%s' is NULL",
342 if(iNestedLinks > MAX_NESTED_LINKS) {
343 Log_Notice("VFS", "VFS_ParsePath - Nested link limit exceeded");
347 // Parse Symlink Path
348 // - Just update the path variable and restart the function
349 // > Count nested symlinks and limit to some value (counteracts loops)
351 int remlen = strlen(Path) - (ofs + nextSlash);
352 if( curNode->Size + remlen > MAX_PATH_LEN ) {
353 Log_Warning("VFS", "VFS_ParsePath - Symlinked path too long");
356 curNode->Type->Read( curNode, 0, curNode->Size, path_buffer );
357 path_buffer[ curNode->Size ] = '\0';
358 LOG("path_buffer = '%s'", path_buffer);
359 strcat(path_buffer, Path + ofs+nextSlash);
360 // TODO: Pass to VFS_GetAbsPath to handle ../. in the symlink
363 // Log_Debug("VFS", "VFS_ParsePath: Symlink translated to '%s'", Path);
368 LOG("Symlink -> '%s', restart", Path);
369 _DereferenceMount(mnt, "ParsePath - sym");
373 // Handle Non-Directories
374 if( !(curNode->Flags & VFS_FFLAG_DIRECTORY) )
376 Log_Warning("VFS", "VFS_ParsePath - Path segment is not a directory");
380 // Check if path needs extending
381 if(!TruePath) continue;
383 // Increase buffer space
384 tmp = realloc( *TruePath, retLength + strlen(pathEle) + 1 + 1 );
385 // Check if allocation succeeded
387 Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
392 (*TruePath)[retLength] = '/';
393 strcpy(*TruePath+retLength+1, pathEle);
395 LOG("*TruePath = '%s'", *TruePath);
398 retLength += nextSlash + 1;
401 // Check final finddir call
402 if( !curNode->Type || !curNode->Type->FindDir ) {
403 Log_Warning("VFS", "VFS_ParsePath - FindDir doesn't exist for element of '%s'", Path);
408 LOG("FindDir(%p, '%s')", curNode, &Path[ofs]);
409 tmpNode = curNode->Type->FindDir(curNode, &Path[ofs]);
410 LOG("tmpNode = %p", tmpNode);
411 // Check if file was found
413 LOG("Node '%s' not found in dir '%.*s'", &Path[ofs], ofs, Path);
416 _CloseNode( curNode );
420 // Increase buffer space
421 tmp = realloc(*TruePath, retLength + strlen(&Path[ofs]) + 1 + 1);
422 // Check if allocation succeeded
424 Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
429 (*TruePath)[retLength] = '/';
430 strcpy(*TruePath + retLength + 1, &Path[ofs]);
432 //retLength += strlen(tmpNode->Name) + 1;
439 // Leave the mointpoint's count increased
445 _CloseNode( curNode );
447 if(TruePath && *TruePath) {
451 // Open failed, so decrement the open handle count
452 _DereferenceMount(mnt, "ParsePath - error");
459 * \brief Create and return a handle number for the given node and mode
461 int VFS_int_CreateHandle( tVFS_Node *Node, tVFS_Mount *Mount, int Mode )
465 ENTER("pNode pMount xMode", Node, Mount, Mode);
468 i |= (Mode & VFS_OPENFLAG_EXEC) ? VFS_PERM_EXECUTE : 0;
469 i |= (Mode & VFS_OPENFLAG_READ) ? VFS_PERM_READ : 0;
470 i |= (Mode & VFS_OPENFLAG_WRITE) ? VFS_PERM_WRITE : 0;
475 if( !VFS_CheckACL(Node, i) ) {
477 Log_Log("VFS", "VFS_int_CreateHandle: Permissions Failed");
482 if( MM_GetPhysAddr(Node->Type) == 0 ) {
483 Log_Error("VFS", "Node %p from mount '%s' (%s) has a bad type (%p)",
484 Node, Mount->MountPoint, Mount->Filesystem->Name, Node->Type);
489 i = VFS_AllocHandle( !!(Mode & VFS_OPENFLAG_USER), Node, Mode );
491 Log_Notice("VFS", "VFS_int_CreateHandle: Out of handles");
496 VFS_GetHandle(i)->Mount = Mount;
502 * \fn int VFS_Open(const char *Path, Uint Mode)
505 int VFS_Open(const char *Path, Uint Flags)
507 return VFS_OpenEx(Path, Flags, 0);
510 int VFS_OpenEx(const char *Path, Uint Flags, Uint Mode)
516 ENTER("sPath xFlags oMode", Path, Flags);
519 absPath = VFS_GetAbsPath(Path);
520 if(absPath == NULL) {
521 Log_Warning("VFS", "VFS_Open: Path expansion failed '%s'", Path);
524 LOG("absPath = \"%s\"", absPath);
526 // Parse path and get mount point
527 node = VFS_ParsePath(absPath, NULL, &mnt);
529 // Create file if requested and it doesn't exist
530 if( !node && (Flags & VFS_OPENFLAG_CREATE) )
532 // TODO: Translate `Mode` into ACL and node flags
535 // Split path at final separator
536 char *file = strrchr(absPath, '/');
542 tVFS_Node *pnode = VFS_ParsePath(absPath, NULL, &pmnt);
544 LOG("Unable to open parent '%s'", absPath);
550 // Check ACLs on the parent
551 if( !VFS_CheckACL(pnode, VFS_PERM_EXECUTE|VFS_PERM_WRITE) ) {
556 // Check that there's a MkNod method
557 if( !pnode->Type || !pnode->Type->MkNod ) {
558 Log_Warning("VFS", "VFS_Open - Directory has no MkNod method");
563 node = pnode->Type->MkNod(pnode, file, new_flags);
565 LOG("Cannot create node '%s' in '%s'", file, absPath);
569 // Set mountpoint (and increment open handle count)
571 _ReferenceMount(mnt, "Open - create");
572 // Fall through on error check
575 _DereferenceMount(pmnt, "Open - create");
581 _DereferenceMount(pmnt, "Open - create,fail");
589 // Free generated path
595 LOG("Cannot find node");
600 // Check for symlinks
601 if( !(Flags & VFS_OPENFLAG_NOLINK) && (node->Flags & VFS_FFLAG_SYMLINK) )
603 char tmppath[node->Size+1];
604 if( node->Size > MAX_PATH_LEN ) {
605 Log_Warning("VFS", "VFS_Open - Symlink is too long (%i)", node->Size);
608 if( !node->Type || !node->Type->Read ) {
609 Log_Warning("VFS", "VFS_Open - No read method on symlink");
612 // Read symlink's path
613 node->Type->Read( node, 0, node->Size, tmppath );
614 tmppath[ node->Size ] = '\0';
616 _DereferenceMount(mnt, "Open - symlink");
618 node = VFS_ParsePath(tmppath, NULL, &mnt);
620 LOG("Cannot find symlink target node (%s)", tmppath);
626 int ret = VFS_int_CreateHandle(node, mnt, Flags);
631 _DereferenceMount(mnt, "Open - error");
639 * \brief Open a file from an open directory
641 int VFS_OpenChild(int FD, const char *Name, Uint Mode)
646 ENTER("xFD sName xMode", FD, Name, Mode);
649 h = VFS_GetHandle(FD);
651 Log_Warning("VFS", "VFS_OpenChild - Invalid file handle 0x%x", FD);
656 // Check for directory
657 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
658 Log_Warning("VFS", "VFS_OpenChild - Passed handle is not a directory");
664 if( !h->Node->Type || !h->Node->Type->FindDir ) {
665 Log_Error("VFS", "VFS_OpenChild - Node does not have a type/is missing FindDir");
671 node = h->Node->Type->FindDir(h->Node, Name);
677 // Increment open handle count, no problems with the mount going away as `h` is already open on it
678 _ReferenceMount(h->Mount, "OpenChild");
680 LEAVE_RET('x', VFS_int_CreateHandle(node, h->Mount, Mode));
683 int VFS_OpenInode(Uint32 Mount, Uint64 Inode, int Mode)
688 ENTER("iMount XInode xMode", Mount, Inode, Mode);
691 mnt = VFS_GetMountByIdent(Mount);
693 LOG("Mount point ident invalid");
698 // Does the filesystem support this?
699 if( !mnt->Filesystem->GetNodeFromINode ) {
700 LOG("Filesystem does not support inode accesses");
706 node = mnt->Filesystem->GetNodeFromINode(mnt->RootNode, Inode);
708 LOG("Unable to find inode");
713 LEAVE_RET('x', VFS_int_CreateHandle(node, mnt, Mode));
717 * \fn void VFS_Close(int FD)
718 * \brief Closes an open file handle
720 void VFS_Close(int FD)
725 h = VFS_GetHandle(FD);
727 Log_Warning("VFS", "Invalid file handle passed to VFS_Close, 0x%x", FD);
731 if( h->Node == NULL ) {
732 Log_Warning("VFS", "Non-open handle passed to VFS_Close, 0x%x", FD);
736 #if VALIDATE_VFS_FUNCTIPONS
737 if(h->Node->Close && !MM_GetPhysAddr(h->Node->Close)) {
738 Log_Warning("VFS", "Node %p's ->Close method is invalid (%p)",
739 h->Node, h->Node->Close);
744 LOG("Handle %x", FD);
748 _DereferenceMount(h->Mount, "Close");
754 int VFS_DuplicateFD(int SrcFD, int DstFD)
756 int isUser = !(SrcFD & VFS_KERNEL_FLAG);
757 tVFS_Handle *src = VFS_GetHandle(SrcFD);
758 if( !src ) return -1;
760 DstFD = VFS_AllocHandle(isUser, src->Node, src->Mode);
764 if( VFS_GetHandle(DstFD) )
766 VFS_SetHandle(DstFD, src->Node, src->Mode);
768 memcpy(VFS_GetHandle(DstFD), src, sizeof(tVFS_Handle));
773 * Update flags on a FD
775 int VFS_SetFDFlags(int FD, int Mask, int Value)
777 tVFS_Handle *h = VFS_GetHandle(FD);
788 * \brief Change current working directory
790 int VFS_ChDir(const char *Dest)
797 buf = VFS_GetAbsPath(Dest);
799 Log_Notice("VFS", "VFS_ChDir: Path expansion failed");
803 // Check if path exists
804 fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
806 Log_Notice("VFS", "VFS_ChDir: Path is invalid");
810 // Get node so we can check for directory
811 h = VFS_GetHandle(fd);
812 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
813 Log("VFS_ChDir: Path is not a directory");
822 char **cwdptr = Threads_GetCWD();
823 // Free old working directory
824 if( *cwdptr ) free( *cwdptr );
829 Log_Debug("VFS", "Updated CWD to '%s'", buf);
835 * \fn int VFS_ChRoot(char *New)
836 * \brief Change current root directory
838 int VFS_ChRoot(const char *New)
844 if(New[0] == '/' && New[1] == '\0')
845 return 1; // What a useless thing to ask!
848 buf = VFS_GetAbsPath(New);
850 LOG("Path expansion failed");
854 // Check if path exists
855 fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
857 LOG("Path is invalid");
861 // Get node so we can check for directory
862 h = VFS_GetHandle(fd);
863 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
864 LOG("Path is not a directory");
874 char **chroot_ptr = Threads_GetChroot();
875 if( *chroot_ptr ) free( *chroot_ptr );
879 LOG("Updated Root to '%s'", buf);