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
18 #define MAX_MARSHALLED_HANDLES 16 // Max outstanding
21 extern tVFS_Mount *gVFS_RootMount;
22 extern tVFS_Node *VFS_MemFile_Create(const char *Path);
25 typedef struct sVFS_MarshaledHandle
30 } tVFS_MarshalledHandle;
33 void _ReferenceMount(tVFS_Mount *Mount, const char *DebugTag);
34 void _DereferenceMount(tVFS_Mount *Mount, const char *DebugTag);
35 int VFS_int_CreateHandle(tVFS_Node *Node, tVFS_Mount *Mount, int Mode);
38 tMutex glVFS_MarshalledHandles;
39 tVFS_MarshalledHandle gaVFS_MarshalledHandles[MAX_MARSHALLED_HANDLES];
42 void _ReferenceMount(tVFS_Mount *Mount, const char *DebugTag)
44 // Log_Debug("VFS", "%s: inc. mntpt '%s' to %i", DebugTag, Mount->MountPoint, Mount->OpenHandleCount+1);
45 Mount->OpenHandleCount ++;
47 void _DereferenceMount(tVFS_Mount *Mount, const char *DebugTag)
49 // Log_Debug("VFS", "%s: dec. mntpt '%s' to %i", DebugTag, Mount->MountPoint, Mount->OpenHandleCount-1);
50 ASSERT(Mount->OpenHandleCount > 0);
51 Mount->OpenHandleCount --;
54 * \fn char *VFS_GetAbsPath(const char *Path)
55 * \brief Create an absolute path from a relative one
57 char *VFS_GetAbsPath(const char *Path)
60 int pathLen = strlen(Path);
61 char *pathComps[MAX_PATH_SLASHES];
65 const char *chroot = *Threads_GetChroot(NULL);
67 const char *cwd = *Threads_GetCWD(NULL);
74 ret = malloc(strlen(Path)+1);
76 Log_Warning("VFS", "VFS_GetAbsPath: malloc() returned NULL");
87 chrootLen = strlen(chroot);
88 // Trim trailing slash off chroot
89 if( chrootLen && chroot[chrootLen - 1] == '/' )
92 // Check if the path is already absolute
94 ret = malloc(chrootLen + pathLen + 1);
96 Log_Warning("VFS", "VFS_GetAbsPath: malloc() returned NULL");
99 strcpy(ret + chrootLen, Path);
107 cwdLen = strlen(cwd);
109 // Prepend the current directory
110 ret = malloc(chrootLen + cwdLen + 1 + pathLen + 1 );
111 strcpy(ret+chrootLen, cwd);
113 strcpy(ret+chrootLen+cwdLen+1, Path);
114 //Log("ret = '%s'", ret);
118 pathComps[iPos++] = tmpStr = ret+chrootLen+1;
123 pathComps[iPos++] = tmpStr;
124 if(iPos == MAX_PATH_SLASHES) {
125 LOG("Path '%s' has too many elements", Path);
132 pathComps[iPos] = NULL;
136 while(pathComps[iPos])
138 tmpStr = pathComps[iPos];
139 // Always Increment iPos
142 if(tmpStr[0] == '.' && tmpStr[1] == '.' && (tmpStr[2] == '/' || tmpStr[2] == '\0') )
149 if(tmpStr[0] == '.' && (tmpStr[1] == '/' || tmpStr[1] == '\0') )
154 if(tmpStr[0] == '/' || tmpStr[0] == '\0')
160 pathComps[iPos2] = tmpStr;
163 pathComps[iPos2] = NULL;
166 iPos2 = chrootLen + 1; iPos = 0;
168 while(pathComps[iPos])
170 tmpStr = pathComps[iPos];
171 while(*tmpStr && *tmpStr != '/')
173 ret[iPos2++] = *tmpStr;
184 // Prepend the chroot
186 memcpy( ret, chroot, chrootLen );
189 // Log_Debug("VFS", "VFS_GetAbsPath: RETURN '%s'", ret);
194 * \fn char *VFS_ParsePath(const char *Path, char **TruePath)
195 * \brief Parses a path, resolving sysmlinks and applying permissions
197 tVFS_Node *VFS_ParsePath(const char *Path, char **TruePath, tVFS_Mount **MountPoint)
199 tVFS_Mount *mnt, *longestMount;
200 int cmp, retLength = 0;
202 int iNestedLinks = 0;
203 tVFS_Node *curNode, *tmpNode;
205 char path_buffer[MAX_PATH_LEN+1];
207 ENTER("sPath pTruePath", Path, TruePath);
210 if(Threads_GetUID() == 0 && Path[0] == '$') {
212 *TruePath = malloc(strlen(Path)+1);
213 strcpy(*TruePath, Path);
215 curNode = VFS_MemFile_Create(Path);
224 // For root we always fast return
225 if(Path[0] == '/' && Path[1] == '\0') {
227 *TruePath = malloc( gVFS_RootMount->MountPointLen+1 );
228 strcpy(*TruePath, gVFS_RootMount->MountPoint);
230 _ReferenceMount(gVFS_RootMount, "ParsePath - Fast Tree Root");
231 if(MountPoint) *MountPoint = gVFS_RootMount;
232 LEAVE('p', gVFS_RootMount->RootNode);
233 return gVFS_RootMount->RootNode;
236 // Check if there is anything mounted
238 Log_Error("VFS", "VFS_ParsePath - No filesystems mounted");
243 longestMount = gVFS_RootMount;
244 RWLock_AcquireRead( &glVFS_MountList );
245 for(mnt = gVFS_Mounts; mnt; mnt = mnt->Next)
248 if( Path[mnt->MountPointLen] != '/' && Path[mnt->MountPointLen] != '\0')
250 // Length Check - If the length is smaller than the longest match sofar
251 if(mnt->MountPointLen < longestMount->MountPointLen) continue;
253 cmp = strncmp(Path, mnt->MountPoint, mnt->MountPointLen);
254 // Not a match, continue
255 if(cmp != 0) continue;
258 // Fast Break - Request Mount Root
259 if(Path[mnt->MountPointLen] == '\0') {
261 *TruePath = malloc( mnt->MountPointLen+1 );
262 strcpy(*TruePath, mnt->MountPoint);
266 RWLock_Release( &glVFS_MountList );
267 LOG("Mount %p root", mnt);
268 _ReferenceMount(mnt, "ParsePath - Mount Root");
269 LEAVE('p', mnt->RootNode);
270 return mnt->RootNode;
276 Log_Panic("VFS", "VFS_ParsePath - No mount for '%s'", Path);
280 _ReferenceMount(longestMount, "ParsePath");
281 RWLock_Release( &glVFS_MountList );
283 // Save to shorter variable
286 LOG("mnt = {MountPoint:\"%s\"}", mnt->MountPoint);
291 // Assumes that the resultant path (here) will not be > strlen(Path) + 1
292 *TruePath = malloc( strlen(Path) + 1 );
293 strcpy(*TruePath, mnt->MountPoint);
294 retLength = mnt->MountPointLen;
297 curNode = mnt->RootNode;
298 curNode->ReferenceCount ++;
300 ofs = mnt->MountPointLen+1;
301 for(; (nextSlash = strpos(&Path[ofs], '/')) != -1; ofs += nextSlash + 1)
303 char pathEle[nextSlash+1];
306 if(nextSlash == 0) continue;
308 memcpy(pathEle, &Path[ofs], nextSlash);
309 pathEle[nextSlash] = 0;
311 // Check permissions on root of filesystem
312 if( !VFS_CheckACL(curNode, VFS_PERM_EXEC) ) {
313 LOG("Permissions failure on '%s'", Path);
318 // Check if the node has a FindDir method
321 LOG("Finddir failure on '%s' - No type", Path);
322 Log_Error("VFS", "Node at '%s' has no type (mount %s:%s)",
323 Path, mnt->Filesystem->Name, mnt->MountPoint);
326 if( !curNode->Type->FindDir )
328 LOG("Finddir failure on '%s' - No FindDir method in %s", Path, curNode->Type->TypeName);
331 LOG("FindDir{=%p}(%p, '%s')", curNode->Type->FindDir, curNode, pathEle);
333 tmpNode = curNode->Type->FindDir(curNode, pathEle, 0);
334 LOG("tmpNode = %p", tmpNode);
335 _CloseNode( curNode );
340 LOG("Node '%s' not found in dir '%s'", pathEle, Path);
345 // Handle Symbolic Links
346 if(curNode->Flags & VFS_FFLAG_SYMLINK) {
351 if(!curNode->Type || !curNode->Type->Read) {
352 Log_Warning("VFS", "VFS_ParsePath - Read of symlink node %p'%s' is NULL",
358 if(iNestedLinks > MAX_NESTED_LINKS) {
359 Log_Notice("VFS", "VFS_ParsePath - Nested link limit exceeded on '%.*s'", ofs, Path);
364 // Parse Symlink Path
365 // - Just update the path variable and restart the function
366 // > Count nested symlinks and limit to some value (counteracts loops)
368 int remlen = strlen(Path) - (ofs + nextSlash);
369 if( curNode->Size + remlen > MAX_PATH_LEN ) {
370 Log_Warning("VFS", "VFS_ParsePath - Symlinked path too long");
374 curNode->Type->Read( curNode, 0, curNode->Size, path_buffer, 0 );
375 path_buffer[ curNode->Size ] = '\0';
376 LOG("path_buffer = '%s'", path_buffer);
377 strcat(path_buffer, Path + ofs+nextSlash);
378 // TODO: Pass to VFS_GetAbsPath to handle ../. in the symlink
381 // Log_Debug("VFS", "VFS_ParsePath: Symlink translated to '%s'", Path);
386 LOG("Symlink -> '%s', restart", Path);
387 _DereferenceMount(mnt, "ParsePath - sym");
391 // Handle Non-Directories
392 if( !(curNode->Flags & VFS_FFLAG_DIRECTORY) )
394 Log_Warning("VFS", "VFS_ParsePath - Path segment '%.*s' is not a directory (curNode{%p}->Flags = 0x%x)",
395 ofs+nextSlash, Path, curNode, curNode->Flags);
400 // Check if path needs extending
401 if(!TruePath) continue;
403 // Increase buffer space
404 tmp = realloc( *TruePath, retLength + strlen(pathEle) + 1 + 1 );
405 // Check if allocation succeeded
407 Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
413 (*TruePath)[retLength] = '/';
414 strcpy(*TruePath+retLength+1, pathEle);
416 LOG("*TruePath = '%s'", *TruePath);
419 retLength += nextSlash + 1;
422 // Check final finddir call
423 if( !curNode->Type || !curNode->Type->FindDir ) {
424 Log_Warning("VFS", "VFS_ParsePath - FindDir doesn't exist for leaf of '%s' (dir '%.*s')", Path, ofs, Path);
430 LOG("FindDir(%p, '%s')", curNode, &Path[ofs]);
431 tmpNode = curNode->Type->FindDir(curNode, &Path[ofs], 0);
432 LOG("tmpNode = %p", tmpNode);
433 // Check if file was found
435 LOG("Node '%s' not found in dir '%.*s'", &Path[ofs], ofs, Path);
439 _CloseNode( curNode );
443 // Increase buffer space
444 tmp = realloc(*TruePath, retLength + strlen(&Path[ofs]) + 1 + 1);
445 // Check if allocation succeeded
447 Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
453 (*TruePath)[retLength] = '/';
454 strcpy(*TruePath + retLength + 1, &Path[ofs]);
456 //retLength += strlen(tmpNode->Name) + 1;
463 // Leave the mointpoint's count increased
469 _CloseNode( curNode );
471 if(TruePath && *TruePath) {
475 // Open failed, so decrement the open handle count
476 _DereferenceMount(mnt, "ParsePath - error");
482 * \brief Create and return a handle number for the given node and mode
484 int VFS_int_CreateHandle( tVFS_Node *Node, tVFS_Mount *Mount, int Mode )
488 ENTER("pNode pMount xMode", Node, Mount, Mode);
491 i |= (Mode & VFS_OPENFLAG_EXEC) ? VFS_PERM_EXEC : 0;
492 i |= (Mode & VFS_OPENFLAG_READ) ? VFS_PERM_READ : 0;
493 i |= (Mode & VFS_OPENFLAG_WRITE) ? VFS_PERM_WRITE : 0;
498 if( !VFS_CheckACL(Node, i) ) {
500 Log_Log("VFS", "VFS_int_CreateHandle: Permissions Failed");
505 if( MM_GetPhysAddr(Node->Type) == 0 ) {
506 Log_Error("VFS", "Node %p from mount '%s' (%s) has a bad type (%p)",
507 Node, Mount->MountPoint, Mount->Filesystem->Name, Node->Type);
512 i = VFS_AllocHandle( !!(Mode & VFS_OPENFLAG_USER), Node, Mode );
514 Log_Notice("VFS", "VFS_int_CreateHandle: Out of handles");
519 VFS_GetHandle(i)->Mount = Mount;
525 * \fn int VFS_Open(const char *Path, Uint Mode)
528 int VFS_Open(const char *Path, Uint Flags)
530 return VFS_OpenEx(Path, Flags, 0);
533 int VFS_OpenEx(const char *Path, Uint Flags, Uint Mode)
539 ENTER("sPath xFlags oMode", Path, Flags);
542 absPath = VFS_GetAbsPath(Path);
543 if(absPath == NULL) {
544 Log_Warning("VFS", "VFS_Open: Path expansion failed '%s'", Path);
547 LOG("absPath = \"%s\"", absPath);
549 // Parse path and get mount point
550 node = VFS_ParsePath(absPath, NULL, &mnt);
552 // Create file if requested and it doesn't exist
553 if( !node && (Flags & VFS_OPENFLAG_CREATE) )
555 // TODO: Translate `Mode` into ACL and node flags
558 // Split path at final separator
559 char *file = strrchr(absPath, '/');
565 tVFS_Node *pnode = VFS_ParsePath(absPath, NULL, &pmnt);
567 LOG("Unable to open parent '%s'", absPath);
573 // Check ACLs on the parent
574 if( !VFS_CheckACL(pnode, VFS_PERM_EXEC|VFS_PERM_WRITE) ) {
579 // Check that there's a MkNod method
580 if( !pnode->Type || !pnode->Type->MkNod ) {
581 Log_Warning("VFS", "VFS_Open - Directory has no MkNod method");
586 node = pnode->Type->MkNod(pnode, file, new_flags);
588 LOG("Cannot create node '%s' in '%s'", file, absPath);
592 // Set mountpoint (and increment open handle count)
594 _ReferenceMount(mnt, "Open - create");
595 // Fall through on error check
598 _DereferenceMount(pmnt, "Open - create");
604 _DereferenceMount(pmnt, "Open - create,fail");
612 // Free generated path
618 LOG("Cannot find node");
623 // Check for symlinks
624 if( !(Flags & VFS_OPENFLAG_NOLINK) && (node->Flags & VFS_FFLAG_SYMLINK) )
626 char tmppath[node->Size+1];
627 if( node->Size > MAX_PATH_LEN ) {
628 Log_Warning("VFS", "VFS_Open - Symlink is too long (%i)", node->Size);
631 if( !node->Type || !node->Type->Read ) {
632 Log_Warning("VFS", "VFS_Open - No read method on symlink");
635 // Read symlink's path
636 node->Type->Read( node, 0, node->Size, tmppath, 0 );
637 tmppath[ node->Size ] = '\0';
639 _DereferenceMount(mnt, "Open - symlink");
641 node = VFS_ParsePath(tmppath, NULL, &mnt);
643 LOG("Cannot find symlink target node (%s)", tmppath);
649 int ret = VFS_int_CreateHandle(node, mnt, Flags);
654 _DereferenceMount(mnt, "Open - error");
662 * \brief Open a file from an open directory
664 int VFS_OpenChild(int FD, const char *Name, Uint Mode)
669 ENTER("xFD sName xMode", FD, Name, Mode);
672 h = VFS_GetHandle(FD);
674 Log_Warning("VFS", "VFS_OpenChild - Invalid file handle 0x%x", FD);
679 // Check for directory
680 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
681 Log_Warning("VFS", "VFS_OpenChild - Passed handle is not a directory");
687 if( !h->Node->Type || !h->Node->Type->FindDir ) {
688 Log_Error("VFS", "VFS_OpenChild - Node does not have a type/is missing FindDir");
694 node = h->Node->Type->FindDir(h->Node, Name, 0);
700 // Increment open handle count, no problems with the mount going away as `h` is already open on it
701 _ReferenceMount(h->Mount, "OpenChild");
703 LEAVE_RET('x', VFS_int_CreateHandle(node, h->Mount, Mode));
706 int VFS_OpenInode(Uint32 Mount, Uint64 Inode, int Mode)
711 ENTER("iMount XInode xMode", Mount, Inode, Mode);
714 mnt = VFS_GetMountByIdent(Mount);
716 LOG("Mount point ident invalid");
721 // Does the filesystem support this?
722 if( !mnt->Filesystem->GetNodeFromINode ) {
723 Log_Notice("VFS", "Filesystem '%s' does not support inode accesses",
724 mnt->Filesystem->Name);
730 node = mnt->Filesystem->GetNodeFromINode(mnt->RootNode, Inode);
732 LOG("Unable to find inode");
737 LEAVE_RET('x', VFS_int_CreateHandle(node, mnt, Mode));
740 int VFS_Reopen(int FD, const char *Path, int Flags)
742 tVFS_Handle *h = VFS_GetHandle(FD);
748 int newf = VFS_Open(Path, Flags);
750 // errno = set by VFS_Open
755 _DereferenceMount(h->Mount, "Reopen");
756 memcpy(h, VFS_GetHandle(newf), sizeof(*h));
757 _ReferenceNode(h->Node);
758 _ReferenceMount(h->Mount, "Reopen");
766 * \fn void VFS_Close(int FD)
767 * \brief Closes an open file handle
769 void VFS_Close(int FD)
774 h = VFS_GetHandle(FD);
776 Log_Warning("VFS", "Invalid file handle passed to VFS_Close, 0x%x", FD);
781 if( h->Node == NULL ) {
782 Log_Warning("VFS", "Non-open handle passed to VFS_Close, 0x%x", FD);
787 #if VALIDATE_VFS_FUNCTIPONS
788 if(h->Node->Close && !MM_GetPhysAddr(h->Node->Close)) {
789 Log_Warning("VFS", "Node %p's ->Close method is invalid (%p)",
790 h->Node, h->Node->Close);
796 LOG("Handle %x", FD);
800 _DereferenceMount(h->Mount, "Close");
806 int VFS_DuplicateFD(int SrcFD, int DstFD)
808 int isUser = !(SrcFD & VFS_KERNEL_FLAG);
809 tVFS_Handle *src = VFS_GetHandle(SrcFD);
810 if( !src ) return -1;
812 DstFD = VFS_AllocHandle(isUser, src->Node, src->Mode);
816 if( VFS_GetHandle(DstFD) )
818 VFS_SetHandle(DstFD, src->Node, src->Mode);
820 _ReferenceMount(src->Mount, "DuplicateFD");
821 _ReferenceNode(src->Node);
822 memcpy(VFS_GetHandle(DstFD), src, sizeof(tVFS_Handle));
827 * Update flags on a FD
829 int VFS_SetFDFlags(int FD, int Mask, int Value)
831 tVFS_Handle *h = VFS_GetHandle(FD);
845 * \brief Change current working directory
847 int VFS_ChDir(const char *Dest)
854 buf = VFS_GetAbsPath(Dest);
856 Log_Notice("VFS", "VFS_ChDir: Path expansion failed");
860 // Check if path exists
861 fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
863 Log_Notice("VFS", "VFS_ChDir: Path is invalid");
867 // Get node so we can check for directory
868 h = VFS_GetHandle(fd);
869 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
870 Log("VFS_ChDir: Path is not a directory");
879 char **cwdptr = Threads_GetCWD(NULL);
880 // Free old working directory
881 if( *cwdptr ) free( *cwdptr );
886 Log_Debug("VFS", "Updated CWD to '%s'", buf);
892 * \fn int VFS_ChRoot(char *New)
893 * \brief Change current root directory
895 int VFS_ChRoot(const char *New)
901 if(New[0] == '/' && New[1] == '\0')
902 return 1; // What a useless thing to ask!
905 buf = VFS_GetAbsPath(New);
907 LOG("Path expansion failed");
911 // Check if path exists
912 fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
914 LOG("Path is invalid");
918 // Get node so we can check for directory
919 h = VFS_GetHandle(fd);
920 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
921 LOG("Path is not a directory");
931 char **chroot_ptr = Threads_GetChroot(NULL);
932 if( *chroot_ptr ) free( *chroot_ptr );
936 LOG("Updated Root to '%s'", buf);
942 * Marshal a handle so that it can be transferred between processes
944 Uint64 VFS_MarshalHandle(int FD)
946 tVFS_Handle *h = VFS_GetHandle(FD);
952 // Allocate marshal location
954 Mutex_Acquire(&glVFS_MarshalledHandles);
955 for( int i = 0; i < MAX_MARSHALLED_HANDLES; i ++ )
957 tVFS_MarshalledHandle* mh = &gaVFS_MarshalledHandles[i];
958 if( mh->Handle.Node == NULL ) {
959 mh->Handle.Node = h->Node;
960 mh->AllocTime = now();
963 if( now() - mh->AllocTime > 2000 ) {
964 Log_Notice("VFS", "TODO: Expire marshalled handle");
967 Mutex_Release(&glVFS_MarshalledHandles);
969 // TODO: Need to clean up lost handles to avoid DOS
970 Log_Warning("VFS", "Out of marshaled handle slots");
976 tVFS_MarshalledHandle* mh = &gaVFS_MarshalledHandles[ret];
978 _ReferenceMount(h->Mount, "MarshalHandle");
979 _ReferenceNode(h->Node);
982 return (Uint64)mh->Magic << 32 | ret;
986 * Un-marshal a handle into the current process
987 * NOTE: Does not support unmarshalling into kernel handle list
989 int VFS_UnmarshalHandle(Uint64 Handle)
991 Uint32 magic = Handle >> 32;
992 int id = Handle & 0xFFFFFFFF;
995 if( id >= MAX_MARSHALLED_HANDLES ) {
996 LOG("ID too high (%i > %i)", id, MAX_MARSHALLED_HANDLES);
1003 tVFS_MarshalledHandle *mh = &gaVFS_MarshalledHandles[id];
1004 if( mh->Handle.Node == NULL ) {
1005 LOG("Target node is NULL");
1009 if( mh->Magic != magic ) {
1010 LOG("Magic mismatch (0x%08x != 0x%08x)", magic, mh->Magic);
1015 Mutex_Acquire(&glVFS_MarshalledHandles);
1016 // - Create destination handle
1017 int ret = VFS_AllocHandle(true, mh->Handle.Node, mh->Handle.Mode);
1018 // - Clear allocation
1019 mh->Handle.Node = NULL;
1020 Mutex_Release(&glVFS_MarshalledHandles);
1026 // No need to reference node/mount, new handle takes marshalled reference