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");
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 is not a directory");
399 // Check if path needs extending
400 if(!TruePath) continue;
402 // Increase buffer space
403 tmp = realloc( *TruePath, retLength + strlen(pathEle) + 1 + 1 );
404 // Check if allocation succeeded
406 Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
412 (*TruePath)[retLength] = '/';
413 strcpy(*TruePath+retLength+1, pathEle);
415 LOG("*TruePath = '%s'", *TruePath);
418 retLength += nextSlash + 1;
421 // Check final finddir call
422 if( !curNode->Type || !curNode->Type->FindDir ) {
423 Log_Warning("VFS", "VFS_ParsePath - FindDir doesn't exist for element of '%s'", Path);
429 LOG("FindDir(%p, '%s')", curNode, &Path[ofs]);
430 tmpNode = curNode->Type->FindDir(curNode, &Path[ofs], 0);
431 LOG("tmpNode = %p", tmpNode);
432 // Check if file was found
434 LOG("Node '%s' not found in dir '%.*s'", &Path[ofs], ofs, Path);
438 _CloseNode( curNode );
442 // Increase buffer space
443 tmp = realloc(*TruePath, retLength + strlen(&Path[ofs]) + 1 + 1);
444 // Check if allocation succeeded
446 Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
452 (*TruePath)[retLength] = '/';
453 strcpy(*TruePath + retLength + 1, &Path[ofs]);
455 //retLength += strlen(tmpNode->Name) + 1;
462 // Leave the mointpoint's count increased
468 _CloseNode( curNode );
470 if(TruePath && *TruePath) {
474 // Open failed, so decrement the open handle count
475 _DereferenceMount(mnt, "ParsePath - error");
481 * \brief Create and return a handle number for the given node and mode
483 int VFS_int_CreateHandle( tVFS_Node *Node, tVFS_Mount *Mount, int Mode )
487 ENTER("pNode pMount xMode", Node, Mount, Mode);
490 i |= (Mode & VFS_OPENFLAG_EXEC) ? VFS_PERM_EXEC : 0;
491 i |= (Mode & VFS_OPENFLAG_READ) ? VFS_PERM_READ : 0;
492 i |= (Mode & VFS_OPENFLAG_WRITE) ? VFS_PERM_WRITE : 0;
497 if( !VFS_CheckACL(Node, i) ) {
499 Log_Log("VFS", "VFS_int_CreateHandle: Permissions Failed");
504 if( MM_GetPhysAddr(Node->Type) == 0 ) {
505 Log_Error("VFS", "Node %p from mount '%s' (%s) has a bad type (%p)",
506 Node, Mount->MountPoint, Mount->Filesystem->Name, Node->Type);
511 i = VFS_AllocHandle( !!(Mode & VFS_OPENFLAG_USER), Node, Mode );
513 Log_Notice("VFS", "VFS_int_CreateHandle: Out of handles");
518 VFS_GetHandle(i)->Mount = Mount;
524 * \fn int VFS_Open(const char *Path, Uint Mode)
527 int VFS_Open(const char *Path, Uint Flags)
529 return VFS_OpenEx(Path, Flags, 0);
532 int VFS_OpenEx(const char *Path, Uint Flags, Uint Mode)
538 ENTER("sPath xFlags oMode", Path, Flags);
541 absPath = VFS_GetAbsPath(Path);
542 if(absPath == NULL) {
543 Log_Warning("VFS", "VFS_Open: Path expansion failed '%s'", Path);
546 LOG("absPath = \"%s\"", absPath);
548 // Parse path and get mount point
549 node = VFS_ParsePath(absPath, NULL, &mnt);
551 // Create file if requested and it doesn't exist
552 if( !node && (Flags & VFS_OPENFLAG_CREATE) )
554 // TODO: Translate `Mode` into ACL and node flags
557 // Split path at final separator
558 char *file = strrchr(absPath, '/');
564 tVFS_Node *pnode = VFS_ParsePath(absPath, NULL, &pmnt);
566 LOG("Unable to open parent '%s'", absPath);
572 // Check ACLs on the parent
573 if( !VFS_CheckACL(pnode, VFS_PERM_EXEC|VFS_PERM_WRITE) ) {
578 // Check that there's a MkNod method
579 if( !pnode->Type || !pnode->Type->MkNod ) {
580 Log_Warning("VFS", "VFS_Open - Directory has no MkNod method");
585 node = pnode->Type->MkNod(pnode, file, new_flags);
587 LOG("Cannot create node '%s' in '%s'", file, absPath);
591 // Set mountpoint (and increment open handle count)
593 _ReferenceMount(mnt, "Open - create");
594 // Fall through on error check
597 _DereferenceMount(pmnt, "Open - create");
603 _DereferenceMount(pmnt, "Open - create,fail");
611 // Free generated path
617 LOG("Cannot find node");
622 // Check for symlinks
623 if( !(Flags & VFS_OPENFLAG_NOLINK) && (node->Flags & VFS_FFLAG_SYMLINK) )
625 char tmppath[node->Size+1];
626 if( node->Size > MAX_PATH_LEN ) {
627 Log_Warning("VFS", "VFS_Open - Symlink is too long (%i)", node->Size);
630 if( !node->Type || !node->Type->Read ) {
631 Log_Warning("VFS", "VFS_Open - No read method on symlink");
634 // Read symlink's path
635 node->Type->Read( node, 0, node->Size, tmppath, 0 );
636 tmppath[ node->Size ] = '\0';
638 _DereferenceMount(mnt, "Open - symlink");
640 node = VFS_ParsePath(tmppath, NULL, &mnt);
642 LOG("Cannot find symlink target node (%s)", tmppath);
648 int ret = VFS_int_CreateHandle(node, mnt, Flags);
653 _DereferenceMount(mnt, "Open - error");
661 * \brief Open a file from an open directory
663 int VFS_OpenChild(int FD, const char *Name, Uint Mode)
668 ENTER("xFD sName xMode", FD, Name, Mode);
671 h = VFS_GetHandle(FD);
673 Log_Warning("VFS", "VFS_OpenChild - Invalid file handle 0x%x", FD);
678 // Check for directory
679 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
680 Log_Warning("VFS", "VFS_OpenChild - Passed handle is not a directory");
686 if( !h->Node->Type || !h->Node->Type->FindDir ) {
687 Log_Error("VFS", "VFS_OpenChild - Node does not have a type/is missing FindDir");
693 node = h->Node->Type->FindDir(h->Node, Name, 0);
699 // Increment open handle count, no problems with the mount going away as `h` is already open on it
700 _ReferenceMount(h->Mount, "OpenChild");
702 LEAVE_RET('x', VFS_int_CreateHandle(node, h->Mount, Mode));
705 int VFS_OpenInode(Uint32 Mount, Uint64 Inode, int Mode)
710 ENTER("iMount XInode xMode", Mount, Inode, Mode);
713 mnt = VFS_GetMountByIdent(Mount);
715 LOG("Mount point ident invalid");
720 // Does the filesystem support this?
721 if( !mnt->Filesystem->GetNodeFromINode ) {
722 Log_Notice("VFS", "Filesystem '%s' does not support inode accesses",
723 mnt->Filesystem->Name);
729 node = mnt->Filesystem->GetNodeFromINode(mnt->RootNode, Inode);
731 LOG("Unable to find inode");
736 LEAVE_RET('x', VFS_int_CreateHandle(node, mnt, Mode));
739 int VFS_Reopen(int FD, const char *Path, int Flags)
741 tVFS_Handle *h = VFS_GetHandle(FD);
747 int newf = VFS_Open(Path, Flags);
749 // errno = set by VFS_Open
754 _DereferenceMount(h->Mount, "Reopen");
755 memcpy(h, VFS_GetHandle(newf), sizeof(*h));
756 _ReferenceNode(h->Node);
757 _ReferenceMount(h->Mount, "Reopen");
765 * \fn void VFS_Close(int FD)
766 * \brief Closes an open file handle
768 void VFS_Close(int FD)
773 h = VFS_GetHandle(FD);
775 Log_Warning("VFS", "Invalid file handle passed to VFS_Close, 0x%x", FD);
780 if( h->Node == NULL ) {
781 Log_Warning("VFS", "Non-open handle passed to VFS_Close, 0x%x", FD);
786 #if VALIDATE_VFS_FUNCTIPONS
787 if(h->Node->Close && !MM_GetPhysAddr(h->Node->Close)) {
788 Log_Warning("VFS", "Node %p's ->Close method is invalid (%p)",
789 h->Node, h->Node->Close);
795 LOG("Handle %x", FD);
799 _DereferenceMount(h->Mount, "Close");
805 int VFS_DuplicateFD(int SrcFD, int DstFD)
807 int isUser = !(SrcFD & VFS_KERNEL_FLAG);
808 tVFS_Handle *src = VFS_GetHandle(SrcFD);
809 if( !src ) return -1;
811 DstFD = VFS_AllocHandle(isUser, src->Node, src->Mode);
815 if( VFS_GetHandle(DstFD) )
817 VFS_SetHandle(DstFD, src->Node, src->Mode);
819 _ReferenceMount(src->Mount, "DuplicateFD");
820 _ReferenceNode(src->Node);
821 memcpy(VFS_GetHandle(DstFD), src, sizeof(tVFS_Handle));
826 * Update flags on a FD
828 int VFS_SetFDFlags(int FD, int Mask, int Value)
830 tVFS_Handle *h = VFS_GetHandle(FD);
844 * \brief Change current working directory
846 int VFS_ChDir(const char *Dest)
853 buf = VFS_GetAbsPath(Dest);
855 Log_Notice("VFS", "VFS_ChDir: Path expansion failed");
859 // Check if path exists
860 fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
862 Log_Notice("VFS", "VFS_ChDir: Path is invalid");
866 // Get node so we can check for directory
867 h = VFS_GetHandle(fd);
868 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
869 Log("VFS_ChDir: Path is not a directory");
878 char **cwdptr = Threads_GetCWD(NULL);
879 // Free old working directory
880 if( *cwdptr ) free( *cwdptr );
885 Log_Debug("VFS", "Updated CWD to '%s'", buf);
891 * \fn int VFS_ChRoot(char *New)
892 * \brief Change current root directory
894 int VFS_ChRoot(const char *New)
900 if(New[0] == '/' && New[1] == '\0')
901 return 1; // What a useless thing to ask!
904 buf = VFS_GetAbsPath(New);
906 LOG("Path expansion failed");
910 // Check if path exists
911 fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
913 LOG("Path is invalid");
917 // Get node so we can check for directory
918 h = VFS_GetHandle(fd);
919 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
920 LOG("Path is not a directory");
930 char **chroot_ptr = Threads_GetChroot(NULL);
931 if( *chroot_ptr ) free( *chroot_ptr );
935 LOG("Updated Root to '%s'", buf);
941 * Marshal a handle so that it can be transferred between processes
943 Uint64 VFS_MarshalHandle(int FD)
945 tVFS_Handle *h = VFS_GetHandle(FD);
951 // Allocate marshal location
953 Mutex_Acquire(&glVFS_MarshalledHandles);
954 for( int i = 0; i < MAX_MARSHALLED_HANDLES; i ++ )
956 tVFS_MarshalledHandle* mh = &gaVFS_MarshalledHandles[i];
957 if( mh->Handle.Node == NULL ) {
958 mh->Handle.Node = h->Node;
959 mh->AllocTime = now();
962 if( now() - mh->AllocTime > 2000 ) {
963 Log_Notice("VFS", "TODO: Expire marshalled handle");
966 Mutex_Release(&glVFS_MarshalledHandles);
968 // TODO: Need to clean up lost handles to avoid DOS
969 Log_Warning("VFS", "Out of marshaled handle slots");
975 tVFS_MarshalledHandle* mh = &gaVFS_MarshalledHandles[ret];
977 _ReferenceMount(h->Mount, "MarshalHandle");
978 _ReferenceNode(h->Node);
981 return (Uint64)mh->Magic << 32 | ret;
985 * Un-marshal a handle into the current process
986 * NOTE: Does not support unmarshalling into kernel handle list
988 int VFS_UnmarshalHandle(Uint64 Handle)
990 Uint32 magic = Handle >> 32;
991 int id = Handle & 0xFFFFFFFF;
994 if( id >= MAX_MARSHALLED_HANDLES ) {
995 LOG("ID too high (%i > %i)", id, MAX_MARSHALLED_HANDLES);
1002 tVFS_MarshalledHandle *mh = &gaVFS_MarshalledHandles[id];
1003 if( mh->Handle.Node == NULL ) {
1004 LOG("Target node is NULL");
1008 if( mh->Magic != magic ) {
1009 LOG("Magic mismatch (0x%08x != 0x%08x)", magic, mh->Magic);
1014 Mutex_Acquire(&glVFS_MarshalledHandles);
1015 // - Create destination handle
1016 int ret = VFS_AllocHandle(true, mh->Handle.Node, mh->Handle.Mode);
1017 // - Clear allocation
1018 mh->Handle.Node = NULL;
1019 Mutex_Release(&glVFS_MarshalledHandles);
1025 // No need to reference node/mount, new handle takes marshalled reference