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);
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, 0);
321 LOG("tmpNode = %p", tmpNode);
322 _CloseNode( curNode );
327 LOG("Node '%s' not found in dir '%s'", pathEle, Path);
332 // Handle Symbolic Links
333 if(curNode->Flags & VFS_FFLAG_SYMLINK) {
338 if(!curNode->Type || !curNode->Type->Read) {
339 Log_Warning("VFS", "VFS_ParsePath - Read of symlink node %p'%s' is NULL",
345 if(iNestedLinks > MAX_NESTED_LINKS) {
346 Log_Notice("VFS", "VFS_ParsePath - Nested link limit exceeded");
351 // Parse Symlink Path
352 // - Just update the path variable and restart the function
353 // > Count nested symlinks and limit to some value (counteracts loops)
355 int remlen = strlen(Path) - (ofs + nextSlash);
356 if( curNode->Size + remlen > MAX_PATH_LEN ) {
357 Log_Warning("VFS", "VFS_ParsePath - Symlinked path too long");
361 curNode->Type->Read( curNode, 0, curNode->Size, path_buffer, 0 );
362 path_buffer[ curNode->Size ] = '\0';
363 LOG("path_buffer = '%s'", path_buffer);
364 strcat(path_buffer, Path + ofs+nextSlash);
365 // TODO: Pass to VFS_GetAbsPath to handle ../. in the symlink
368 // Log_Debug("VFS", "VFS_ParsePath: Symlink translated to '%s'", Path);
373 LOG("Symlink -> '%s', restart", Path);
374 _DereferenceMount(mnt, "ParsePath - sym");
378 // Handle Non-Directories
379 if( !(curNode->Flags & VFS_FFLAG_DIRECTORY) )
381 Log_Warning("VFS", "VFS_ParsePath - Path segment is not a directory");
386 // Check if path needs extending
387 if(!TruePath) continue;
389 // Increase buffer space
390 tmp = realloc( *TruePath, retLength + strlen(pathEle) + 1 + 1 );
391 // Check if allocation succeeded
393 Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
399 (*TruePath)[retLength] = '/';
400 strcpy(*TruePath+retLength+1, pathEle);
402 LOG("*TruePath = '%s'", *TruePath);
405 retLength += nextSlash + 1;
408 // Check final finddir call
409 if( !curNode->Type || !curNode->Type->FindDir ) {
410 Log_Warning("VFS", "VFS_ParsePath - FindDir doesn't exist for element of '%s'", Path);
416 LOG("FindDir(%p, '%s')", curNode, &Path[ofs]);
417 tmpNode = curNode->Type->FindDir(curNode, &Path[ofs], 0);
418 LOG("tmpNode = %p", tmpNode);
419 // Check if file was found
421 LOG("Node '%s' not found in dir '%.*s'", &Path[ofs], ofs, Path);
425 _CloseNode( curNode );
429 // Increase buffer space
430 tmp = realloc(*TruePath, retLength + strlen(&Path[ofs]) + 1 + 1);
431 // Check if allocation succeeded
433 Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
439 (*TruePath)[retLength] = '/';
440 strcpy(*TruePath + retLength + 1, &Path[ofs]);
442 //retLength += strlen(tmpNode->Name) + 1;
449 // Leave the mointpoint's count increased
455 _CloseNode( curNode );
457 if(TruePath && *TruePath) {
461 // Open failed, so decrement the open handle count
462 _DereferenceMount(mnt, "ParsePath - error");
468 * \brief Create and return a handle number for the given node and mode
470 int VFS_int_CreateHandle( tVFS_Node *Node, tVFS_Mount *Mount, int Mode )
474 ENTER("pNode pMount xMode", Node, Mount, Mode);
477 i |= (Mode & VFS_OPENFLAG_EXEC) ? VFS_PERM_EXECUTE : 0;
478 i |= (Mode & VFS_OPENFLAG_READ) ? VFS_PERM_READ : 0;
479 i |= (Mode & VFS_OPENFLAG_WRITE) ? VFS_PERM_WRITE : 0;
484 if( !VFS_CheckACL(Node, i) ) {
486 Log_Log("VFS", "VFS_int_CreateHandle: Permissions Failed");
491 if( MM_GetPhysAddr(Node->Type) == 0 ) {
492 Log_Error("VFS", "Node %p from mount '%s' (%s) has a bad type (%p)",
493 Node, Mount->MountPoint, Mount->Filesystem->Name, Node->Type);
498 i = VFS_AllocHandle( !!(Mode & VFS_OPENFLAG_USER), Node, Mode );
500 Log_Notice("VFS", "VFS_int_CreateHandle: Out of handles");
505 VFS_GetHandle(i)->Mount = Mount;
511 * \fn int VFS_Open(const char *Path, Uint Mode)
514 int VFS_Open(const char *Path, Uint Flags)
516 return VFS_OpenEx(Path, Flags, 0);
519 int VFS_OpenEx(const char *Path, Uint Flags, Uint Mode)
525 ENTER("sPath xFlags oMode", Path, Flags);
528 absPath = VFS_GetAbsPath(Path);
529 if(absPath == NULL) {
530 Log_Warning("VFS", "VFS_Open: Path expansion failed '%s'", Path);
533 LOG("absPath = \"%s\"", absPath);
535 // Parse path and get mount point
536 node = VFS_ParsePath(absPath, NULL, &mnt);
538 // Create file if requested and it doesn't exist
539 if( !node && (Flags & VFS_OPENFLAG_CREATE) )
541 // TODO: Translate `Mode` into ACL and node flags
544 // Split path at final separator
545 char *file = strrchr(absPath, '/');
551 tVFS_Node *pnode = VFS_ParsePath(absPath, NULL, &pmnt);
553 LOG("Unable to open parent '%s'", absPath);
559 // Check ACLs on the parent
560 if( !VFS_CheckACL(pnode, VFS_PERM_EXECUTE|VFS_PERM_WRITE) ) {
565 // Check that there's a MkNod method
566 if( !pnode->Type || !pnode->Type->MkNod ) {
567 Log_Warning("VFS", "VFS_Open - Directory has no MkNod method");
572 node = pnode->Type->MkNod(pnode, file, new_flags);
574 LOG("Cannot create node '%s' in '%s'", file, absPath);
578 // Set mountpoint (and increment open handle count)
580 _ReferenceMount(mnt, "Open - create");
581 // Fall through on error check
584 _DereferenceMount(pmnt, "Open - create");
590 _DereferenceMount(pmnt, "Open - create,fail");
598 // Free generated path
604 LOG("Cannot find node");
609 // Check for symlinks
610 if( !(Flags & VFS_OPENFLAG_NOLINK) && (node->Flags & VFS_FFLAG_SYMLINK) )
612 char tmppath[node->Size+1];
613 if( node->Size > MAX_PATH_LEN ) {
614 Log_Warning("VFS", "VFS_Open - Symlink is too long (%i)", node->Size);
617 if( !node->Type || !node->Type->Read ) {
618 Log_Warning("VFS", "VFS_Open - No read method on symlink");
621 // Read symlink's path
622 node->Type->Read( node, 0, node->Size, tmppath, 0 );
623 tmppath[ node->Size ] = '\0';
625 _DereferenceMount(mnt, "Open - symlink");
627 node = VFS_ParsePath(tmppath, NULL, &mnt);
629 LOG("Cannot find symlink target node (%s)", tmppath);
635 int ret = VFS_int_CreateHandle(node, mnt, Flags);
640 _DereferenceMount(mnt, "Open - error");
648 * \brief Open a file from an open directory
650 int VFS_OpenChild(int FD, const char *Name, Uint Mode)
655 ENTER("xFD sName xMode", FD, Name, Mode);
658 h = VFS_GetHandle(FD);
660 Log_Warning("VFS", "VFS_OpenChild - Invalid file handle 0x%x", FD);
665 // Check for directory
666 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
667 Log_Warning("VFS", "VFS_OpenChild - Passed handle is not a directory");
673 if( !h->Node->Type || !h->Node->Type->FindDir ) {
674 Log_Error("VFS", "VFS_OpenChild - Node does not have a type/is missing FindDir");
680 node = h->Node->Type->FindDir(h->Node, Name, 0);
686 // Increment open handle count, no problems with the mount going away as `h` is already open on it
687 _ReferenceMount(h->Mount, "OpenChild");
689 LEAVE_RET('x', VFS_int_CreateHandle(node, h->Mount, Mode));
692 int VFS_OpenInode(Uint32 Mount, Uint64 Inode, int Mode)
697 ENTER("iMount XInode xMode", Mount, Inode, Mode);
700 mnt = VFS_GetMountByIdent(Mount);
702 LOG("Mount point ident invalid");
707 // Does the filesystem support this?
708 if( !mnt->Filesystem->GetNodeFromINode ) {
709 Log_Notice("VFS", "Filesystem '%s' does not support inode accesses",
710 mnt->Filesystem->Name);
716 node = mnt->Filesystem->GetNodeFromINode(mnt->RootNode, Inode);
718 LOG("Unable to find inode");
723 LEAVE_RET('x', VFS_int_CreateHandle(node, mnt, Mode));
726 int VFS_Reopen(int FD, const char *Path, int Flags)
728 tVFS_Handle *h = VFS_GetHandle(FD);
734 int newf = VFS_Open(Path, Flags);
740 _DereferenceMount(h->Mount, "Reopen");
741 memcpy(h, VFS_GetHandle(newf), sizeof(*h));
742 _ReferenceNode(h->Node);
743 _ReferenceMount(h->Mount, "Reopen");
751 * \fn void VFS_Close(int FD)
752 * \brief Closes an open file handle
754 void VFS_Close(int FD)
759 h = VFS_GetHandle(FD);
761 Log_Warning("VFS", "Invalid file handle passed to VFS_Close, 0x%x", FD);
765 if( h->Node == NULL ) {
766 Log_Warning("VFS", "Non-open handle passed to VFS_Close, 0x%x", FD);
770 #if VALIDATE_VFS_FUNCTIPONS
771 if(h->Node->Close && !MM_GetPhysAddr(h->Node->Close)) {
772 Log_Warning("VFS", "Node %p's ->Close method is invalid (%p)",
773 h->Node, h->Node->Close);
778 LOG("Handle %x", FD);
782 _DereferenceMount(h->Mount, "Close");
788 int VFS_DuplicateFD(int SrcFD, int DstFD)
790 int isUser = !(SrcFD & VFS_KERNEL_FLAG);
791 tVFS_Handle *src = VFS_GetHandle(SrcFD);
792 if( !src ) return -1;
794 DstFD = VFS_AllocHandle(isUser, src->Node, src->Mode);
798 if( VFS_GetHandle(DstFD) )
800 VFS_SetHandle(DstFD, src->Node, src->Mode);
802 _ReferenceMount(src->Mount, "DuplicateFD");
803 _ReferenceNode(src->Node);
804 memcpy(VFS_GetHandle(DstFD), src, sizeof(tVFS_Handle));
809 * Update flags on a FD
811 int VFS_SetFDFlags(int FD, int Mask, int Value)
813 tVFS_Handle *h = VFS_GetHandle(FD);
827 * \brief Change current working directory
829 int VFS_ChDir(const char *Dest)
836 buf = VFS_GetAbsPath(Dest);
838 Log_Notice("VFS", "VFS_ChDir: Path expansion failed");
842 // Check if path exists
843 fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
845 Log_Notice("VFS", "VFS_ChDir: Path is invalid");
849 // Get node so we can check for directory
850 h = VFS_GetHandle(fd);
851 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
852 Log("VFS_ChDir: Path is not a directory");
861 char **cwdptr = Threads_GetCWD();
862 // Free old working directory
863 if( *cwdptr ) free( *cwdptr );
868 Log_Debug("VFS", "Updated CWD to '%s'", buf);
874 * \fn int VFS_ChRoot(char *New)
875 * \brief Change current root directory
877 int VFS_ChRoot(const char *New)
883 if(New[0] == '/' && New[1] == '\0')
884 return 1; // What a useless thing to ask!
887 buf = VFS_GetAbsPath(New);
889 LOG("Path expansion failed");
893 // Check if path exists
894 fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
896 LOG("Path is invalid");
900 // Get node so we can check for directory
901 h = VFS_GetHandle(fd);
902 if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
903 LOG("Path is not a directory");
913 char **chroot_ptr = Threads_GetChroot();
914 if( *chroot_ptr ) free( *chroot_ptr );
918 LOG("Updated Root to '%s'", buf);