Kernel - Implimented VFS_Reopen
[tpg/acess2.git] / KernelLand / Kernel / vfs / open.c
1 /*
2  * Acess2 VFS
3  * - Open, Close and ChDir
4  */
5 #define SANITY  1
6 #define DEBUG   0
7 #include <acess.h>
8 #include "vfs.h"
9 #include "vfs_int.h"
10 #include "vfs_ext.h"
11 #include <threads.h>
12
13 // === CONSTANTS ===
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
19 // === IMPORTS ===
20 extern tVFS_Mount       *gVFS_RootMount;
21 extern tVFS_Node        *VFS_MemFile_Create(const char *Path);
22
23 // === PROTOTYPES ===
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);
27
28 // === CODE ===
29 void _ReferenceMount(tVFS_Mount *Mount, const char *DebugTag)
30 {
31 //      Log_Debug("VFS", "%s: inc. mntpt '%s' to %i", DebugTag, Mount->MountPoint, Mount->OpenHandleCount+1);
32         Mount->OpenHandleCount ++;
33 }
34 void _DereferenceMount(tVFS_Mount *Mount, const char *DebugTag)
35 {
36 //      Log_Debug("VFS", "%s: dec. mntpt '%s' to %i", DebugTag, Mount->MountPoint, Mount->OpenHandleCount-1);
37         ASSERT(Mount->OpenHandleCount > 0);
38         Mount->OpenHandleCount --;
39 }
40 /**
41  * \fn char *VFS_GetAbsPath(const char *Path)
42  * \brief Create an absolute path from a relative one
43  */
44 char *VFS_GetAbsPath(const char *Path)
45 {
46         char    *ret;
47          int    pathLen = strlen(Path);
48         char    *pathComps[MAX_PATH_SLASHES];
49         char    *tmpStr;
50         int             iPos = 0;
51         int             iPos2 = 0;
52         const char      *chroot = *Threads_GetChroot();
53          int    chrootLen;
54         const char      *cwd = *Threads_GetCWD();
55          int    cwdLen;
56         
57         ENTER("sPath", Path);
58         
59         // Memory File
60         if(Path[0] == '$') {
61                 ret = malloc(strlen(Path)+1);
62                 if(!ret) {
63                         Log_Warning("VFS", "VFS_GetAbsPath: malloc() returned NULL");
64                         return NULL;
65                 }
66                 strcpy(ret, Path);
67                 LEAVE('p', ret);
68                 return ret;
69         }
70         
71         // - Fetch ChRoot
72         if( chroot == NULL )
73                 chroot = "";
74         chrootLen = strlen(chroot);
75         // Trim trailing slash off chroot
76         if( chrootLen && chroot[chrootLen - 1] == '/' )
77                 chrootLen -= 1;
78         
79         // Check if the path is already absolute
80         if(Path[0] == '/') {
81                 ret = malloc(chrootLen + pathLen + 1);
82                 if(!ret) {
83                         Log_Warning("VFS", "VFS_GetAbsPath: malloc() returned NULL");
84                         return NULL;
85                 }
86                 strcpy(ret + chrootLen, Path);
87         }
88         else {
89                 if(cwd == NULL) {
90                         cwd = "/";
91                         cwdLen = 1;
92                 }
93                 else {
94                         cwdLen = strlen(cwd);
95                 }
96                 // Prepend the current directory
97                 ret = malloc(chrootLen + cwdLen + 1 + pathLen + 1 );
98                 strcpy(ret+chrootLen, cwd);
99                 ret[cwdLen] = '/';
100                 strcpy(ret+chrootLen+cwdLen+1, Path);
101                 //Log("ret = '%s'", ret);
102         }
103         
104         // Parse Path
105         pathComps[iPos++] = tmpStr = ret+chrootLen+1;
106         while(*tmpStr)
107         {
108                 if(*tmpStr++ == '/')
109                 {
110                         pathComps[iPos++] = tmpStr;
111                         if(iPos == MAX_PATH_SLASHES) {
112                                 LOG("Path '%s' has too many elements", Path);
113                                 free(ret);
114                                 LEAVE('n');
115                                 return NULL;
116                         }
117                 }
118         }
119         pathComps[iPos] = NULL;
120         
121         // Cleanup
122         iPos2 = iPos = 0;
123         while(pathComps[iPos])
124         {
125                 tmpStr = pathComps[iPos];
126                 // Always Increment iPos
127                 iPos++;
128                 // ..
129                 if(tmpStr[0] == '.' && tmpStr[1] == '.' && (tmpStr[2] == '/' || tmpStr[2] == '\0') )
130                 {
131                         if(iPos2 != 0)
132                                 iPos2 --;
133                         continue;
134                 }
135                 // .
136                 if(tmpStr[0] == '.' && (tmpStr[1] == '/' || tmpStr[1] == '\0') )
137                 {
138                         continue;
139                 }
140                 // Empty
141                 if(tmpStr[0] == '/' || tmpStr[0] == '\0')
142                 {
143                         continue;
144                 }
145                 
146                 // Set New Position
147                 pathComps[iPos2] = tmpStr;
148                 iPos2++;
149         }
150         pathComps[iPos2] = NULL;
151         
152         // Build New Path
153         iPos2 = chrootLen + 1;  iPos = 0;
154         ret[0] = '/';
155         while(pathComps[iPos])
156         {
157                 tmpStr = pathComps[iPos];
158                 while(*tmpStr && *tmpStr != '/')
159                 {
160                         ret[iPos2++] = *tmpStr;
161                         tmpStr++;
162                 }
163                 ret[iPos2++] = '/';
164                 iPos++;
165         }
166         if(iPos2 > 1)
167                 ret[iPos2-1] = 0;
168         else
169                 ret[iPos2] = 0;
170
171         // Prepend the chroot
172         if(chrootLen)
173                 memcpy( ret, chroot, chrootLen );
174         
175         LEAVE('s', ret);
176 //      Log_Debug("VFS", "VFS_GetAbsPath: RETURN '%s'", ret);
177         return ret;
178 }
179
180 /**
181  * \fn char *VFS_ParsePath(const char *Path, char **TruePath)
182  * \brief Parses a path, resolving sysmlinks and applying permissions
183  */
184 tVFS_Node *VFS_ParsePath(const char *Path, char **TruePath, tVFS_Mount **MountPoint)
185 {
186         tVFS_Mount      *mnt, *longestMount;
187          int    cmp, retLength = 0;
188          int    ofs, nextSlash;
189          int    iNestedLinks = 0;
190         tVFS_Node       *curNode, *tmpNode;
191         char    *tmp;
192         char    path_buffer[MAX_PATH_LEN+1];
193         
194         ENTER("sPath pTruePath", Path, TruePath);
195         
196         // HACK: Memory File
197         if(Threads_GetUID() == 0 && Path[0] == '$') {
198                 if(TruePath) {
199                         *TruePath = malloc(strlen(Path)+1);
200                         strcpy(*TruePath, Path);
201                 }
202                 curNode = VFS_MemFile_Create(Path);
203                 if(MountPoint) {
204                         *MountPoint = NULL;
205                 }
206                 LEAVE('p', curNode);
207                 return curNode;
208         }
209
210 restart_parse:  
211         // For root we always fast return
212         if(Path[0] == '/' && Path[1] == '\0') {
213                 if(TruePath) {
214                         *TruePath = malloc( gVFS_RootMount->MountPointLen+1 );
215                         strcpy(*TruePath, gVFS_RootMount->MountPoint);
216                 }
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;
221         }
222         
223         // Check if there is anything mounted
224         if(!gVFS_Mounts) {
225                 Log_Error("VFS", "VFS_ParsePath - No filesystems mounted");
226                 return NULL;
227         }
228         
229         // Find Mountpoint
230         longestMount = gVFS_RootMount;
231         RWLock_AcquireRead( &glVFS_MountList );
232         for(mnt = gVFS_Mounts; mnt; mnt = mnt->Next)
233         {
234                 // Quick Check
235                 if( Path[mnt->MountPointLen] != '/' && Path[mnt->MountPointLen] != '\0')
236                         continue;
237                 // Length Check - If the length is smaller than the longest match sofar
238                 if(mnt->MountPointLen < longestMount->MountPointLen)    continue;
239                 // String Compare
240                 cmp = strncmp(Path, mnt->MountPoint, mnt->MountPointLen);
241                 // Not a match, continue
242                 if(cmp != 0)    continue;
243                 
244                 #if OPEN_MOUNT_ROOT
245                 // Fast Break - Request Mount Root
246                 if(Path[mnt->MountPointLen] == '\0') {
247                         if(TruePath) {
248                                 *TruePath = malloc( mnt->MountPointLen+1 );
249                                 strcpy(*TruePath, mnt->MountPoint);
250                         }
251                         if(MountPoint)
252                                 *MountPoint = mnt;
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;
258                 }
259                 #endif
260                 longestMount = mnt;
261         }
262         if(!longestMount) {
263                 Log_Panic("VFS", "VFS_ParsePath - No mount for '%s'", Path);
264                 return NULL;
265         }
266         
267         _ReferenceMount(longestMount, "ParsePath");
268         RWLock_Release( &glVFS_MountList );
269         
270         // Save to shorter variable
271         mnt = longestMount;
272         
273         LOG("mnt = {MountPoint:\"%s\"}", mnt->MountPoint);
274         
275         // Initialise String
276         if(TruePath)
277         {
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;
282         }
283         
284         curNode = mnt->RootNode;
285         curNode->ReferenceCount ++;     
286         // Parse Path
287         ofs = mnt->MountPointLen+1;
288         for(; (nextSlash = strpos(&Path[ofs], '/')) != -1; ofs += nextSlash + 1)
289         {
290                 char    pathEle[nextSlash+1];
291                 
292                 // Empty String
293                 if(nextSlash == 0)      continue;
294                 
295                 memcpy(pathEle, &Path[ofs], nextSlash);
296                 pathEle[nextSlash] = 0;
297         
298                 // Check permissions on root of filesystem
299                 if( !VFS_CheckACL(curNode, VFS_PERM_EXECUTE) ) {
300                         LOG("Permissions failure on '%s'", Path);
301                         errno = EPERM;
302                         goto _error;
303                 }
304                 
305                 // Check if the node has a FindDir method
306                 if( !curNode->Type )
307                 {
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);
311                         goto _error;
312                 }
313                 if( !curNode->Type->FindDir )
314                 {
315                         LOG("Finddir failure on '%s' - No FindDir method in %s", Path, curNode->Type->TypeName);
316                         goto _error;
317                 }
318                 LOG("FindDir{=%p}(%p, '%s')", curNode->Type->FindDir, curNode, pathEle);
319                 // Get Child Node
320                 tmpNode = curNode->Type->FindDir(curNode, pathEle, 0);
321                 LOG("tmpNode = %p", tmpNode);
322                 _CloseNode( curNode );
323                 curNode = tmpNode;
324                 
325                 // Error Check
326                 if(!curNode) {
327                         LOG("Node '%s' not found in dir '%s'", pathEle, Path);
328                         errno = ENOENT;
329                         goto _error;
330                 }
331                 
332                 // Handle Symbolic Links
333                 if(curNode->Flags & VFS_FFLAG_SYMLINK) {
334                         if(TruePath) {
335                                 free(*TruePath);
336                                 *TruePath = NULL;
337                         }
338                         if(!curNode->Type || !curNode->Type->Read) {
339                                 Log_Warning("VFS", "VFS_ParsePath - Read of symlink node %p'%s' is NULL",
340                                         curNode, Path);
341                                 errno = EINTERNAL;
342                                 goto _error;
343                         }
344                         
345                         if(iNestedLinks > MAX_NESTED_LINKS) {
346                                 Log_Notice("VFS", "VFS_ParsePath - Nested link limit exceeded");
347                                 errno = ENOENT;
348                                 goto _error;
349                         }
350                         
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)
354                         {
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");
358                                         errno = ENOENT;
359                                         goto _error;
360                                 }
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
366                                 
367                                 Path = path_buffer;
368 //                              Log_Debug("VFS", "VFS_ParsePath: Symlink translated to '%s'", Path);
369                                 iNestedLinks ++;
370                         }
371
372                         // EVIL: Goto :)
373                         LOG("Symlink -> '%s', restart", Path);
374                         _DereferenceMount(mnt, "ParsePath - sym");
375                         goto restart_parse;
376                 }
377                 
378                 // Handle Non-Directories
379                 if( !(curNode->Flags & VFS_FFLAG_DIRECTORY) )
380                 {
381                         Log_Warning("VFS", "VFS_ParsePath - Path segment is not a directory");
382                         errno = ENOTDIR;
383                         goto _error;
384                 }
385                 
386                 // Check if path needs extending
387                 if(!TruePath)   continue;
388                 
389                 // Increase buffer space
390                 tmp = realloc( *TruePath, retLength + strlen(pathEle) + 1 + 1 );
391                 // Check if allocation succeeded
392                 if(!tmp) {
393                         Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
394                         errno = ENOMEM;
395                         goto _error;
396                 }
397                 *TruePath = tmp;
398                 // Append to path
399                 (*TruePath)[retLength] = '/';
400                 strcpy(*TruePath+retLength+1, pathEle);
401                 
402                 LOG("*TruePath = '%s'", *TruePath);
403                 
404                 // - Extend Path
405                 retLength += nextSlash + 1;
406         }
407
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);
411                 errno = ENOENT;
412                 goto _error;
413         }
414         
415         // Get last node
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
420         if(!tmpNode) {
421                 LOG("Node '%s' not found in dir '%.*s'", &Path[ofs], ofs, Path);
422                 errno = ENOENT;
423                 goto _error;
424         }
425         _CloseNode( curNode );
426         
427         if(TruePath)
428         {
429                 // Increase buffer space
430                 tmp = realloc(*TruePath, retLength + strlen(&Path[ofs]) + 1 + 1);
431                 // Check if allocation succeeded
432                 if(!tmp) {
433                         Log_Warning("VFS", "VFS_ParsePath -  Unable to reallocate true path buffer");
434                         errno = ENOMEM;
435                         goto _error;
436                 }
437                 *TruePath = tmp;
438                 // Append to path
439                 (*TruePath)[retLength] = '/';
440                 strcpy(*TruePath + retLength + 1, &Path[ofs]);
441                 // - Extend Path
442                 //retLength += strlen(tmpNode->Name) + 1;
443         }
444
445         if( MountPoint ) {
446                 *MountPoint = mnt;
447         }
448         
449         // Leave the mointpoint's count increased
450         
451         LEAVE('p', tmpNode);
452         return tmpNode;
453
454 _error:
455         _CloseNode( curNode );
456         
457         if(TruePath && *TruePath) {
458                 free(*TruePath);
459                 *TruePath = NULL;
460         }
461         // Open failed, so decrement the open handle count
462         _DereferenceMount(mnt, "ParsePath - error");
463         LEAVE('n');
464         return NULL;
465 }
466
467 /**
468  * \brief Create and return a handle number for the given node and mode
469  */
470 int VFS_int_CreateHandle( tVFS_Node *Node, tVFS_Mount *Mount, int Mode )
471 {
472          int    i;
473         
474         ENTER("pNode pMount xMode", Node, Mount, Mode);
475
476         i = 0;
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;
480         
481         LOG("i = 0b%b", i);
482         
483         // Permissions Check
484         if( !VFS_CheckACL(Node, i) ) {
485                 _CloseNode( Node );
486                 Log_Log("VFS", "VFS_int_CreateHandle: Permissions Failed");
487                 errno = EACCES;
488                 LEAVE_RET('i', -1);
489         }
490
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);
494                 errno = EINTERNAL;
495                 LEAVE_RET('i', -1);
496         }
497         
498         i = VFS_AllocHandle( !!(Mode & VFS_OPENFLAG_USER), Node, Mode );
499         if( i < 0 ) {
500                 Log_Notice("VFS", "VFS_int_CreateHandle: Out of handles");
501                 errno = ENFILE;
502                 LEAVE_RET('i', -1);
503         }
504
505         VFS_GetHandle(i)->Mount = Mount;
506
507         LEAVE_RET('x', i);
508 }
509
510 /**
511  * \fn int VFS_Open(const char *Path, Uint Mode)
512  * \brief Open a file
513  */
514 int VFS_Open(const char *Path, Uint Flags)
515 {
516         return VFS_OpenEx(Path, Flags, 0);
517 }
518
519 int VFS_OpenEx(const char *Path, Uint Flags, Uint Mode)
520 {
521         tVFS_Node       *node;
522         tVFS_Mount      *mnt;
523         char    *absPath;
524         
525         ENTER("sPath xFlags oMode", Path, Flags);
526         
527         // Get absolute path
528         absPath = VFS_GetAbsPath(Path);
529         if(absPath == NULL) {
530                 Log_Warning("VFS", "VFS_Open: Path expansion failed '%s'", Path);
531                 LEAVE_RET('i', -1);
532         }
533         LOG("absPath = \"%s\"", absPath);
534         
535         // Parse path and get mount point
536         node = VFS_ParsePath(absPath, NULL, &mnt);
537         
538         // Create file if requested and it doesn't exist
539         if( !node && (Flags & VFS_OPENFLAG_CREATE) )
540         {
541                 // TODO: Translate `Mode` into ACL and node flags
542                 Uint    new_flags = 0;
543                 
544                 // Split path at final separator
545                 char *file = strrchr(absPath, '/');
546                 *file = '\0';
547                 file ++;
548
549                 // Get parent node
550                 tVFS_Mount      *pmnt;
551                 tVFS_Node *pnode = VFS_ParsePath(absPath, NULL, &pmnt);
552                 if(!pnode) {
553                         LOG("Unable to open parent '%s'", absPath);
554                         free(absPath);
555                         errno = ENOENT;
556                         LEAVE_RET('i', -1);
557                 }
558
559                 // Check ACLs on the parent
560                 if( !VFS_CheckACL(pnode, VFS_PERM_EXECUTE|VFS_PERM_WRITE) ) {
561                         errno = EACCES;
562                         goto _pnode_err;
563                 }
564
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");
568                         errno = EINVAL;
569                         goto _pnode_err;
570                 }
571                 
572                 node = pnode->Type->MkNod(pnode, file, new_flags);
573                 if( !node ) {
574                         LOG("Cannot create node '%s' in '%s'", file, absPath);
575                         errno = ENOENT;
576                         goto _pnode_err;
577                 }
578                 // Set mountpoint (and increment open handle count)
579                 mnt = pmnt;
580                 _ReferenceMount(mnt, "Open - create");
581                 // Fall through on error check
582                 
583                 _CloseNode(pnode);
584                 _DereferenceMount(pmnt, "Open - create");
585                 goto _pnode_ok;
586
587         _pnode_err:
588                 if( pnode ) {
589                         _CloseNode(pnode);
590                         _DereferenceMount(pmnt, "Open - create,fail");
591                         free(absPath);
592                 }
593                 LEAVE('i', -1);
594                 return -1;
595         }
596         _pnode_ok:
597         
598         // Free generated path
599         free(absPath);
600         
601         // Check for error
602         if(!node)
603         {
604                 LOG("Cannot find node");
605                 errno = ENOENT;
606                 goto _error;
607         }
608         
609         // Check for symlinks
610         if( !(Flags & VFS_OPENFLAG_NOLINK) && (node->Flags & VFS_FFLAG_SYMLINK) )
611         {
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);
615                         goto _error;
616                 }
617                 if( !node->Type || !node->Type->Read ) {
618                         Log_Warning("VFS", "VFS_Open - No read method on symlink");
619                         goto _error;
620                 }
621                 // Read symlink's path
622                 node->Type->Read( node, 0, node->Size, tmppath, 0 );
623                 tmppath[ node->Size ] = '\0';
624                 _CloseNode( node );
625                 _DereferenceMount(mnt, "Open - symlink");
626                 // Open the target
627                 node = VFS_ParsePath(tmppath, NULL, &mnt);
628                 if(!node) {
629                         LOG("Cannot find symlink target node (%s)", tmppath);
630                         errno = ENOENT;
631                         goto _error;
632                 }
633         }
634
635          int    ret = VFS_int_CreateHandle(node, mnt, Flags);
636         LEAVE_RET('x', ret);
637 _error:
638         if( node )
639         {
640                 _DereferenceMount(mnt, "Open - error");
641                 _CloseNode(node);
642         }
643         LEAVE_RET('i', -1);
644 }
645
646
647 /**
648  * \brief Open a file from an open directory
649  */
650 int VFS_OpenChild(int FD, const char *Name, Uint Mode)
651 {
652         tVFS_Handle     *h;
653         tVFS_Node       *node;
654         
655         ENTER("xFD sName xMode", FD, Name, Mode);
656
657         // Get handle
658         h = VFS_GetHandle(FD);
659         if(h == NULL) {
660                 Log_Warning("VFS", "VFS_OpenChild - Invalid file handle 0x%x", FD);
661                 errno = EINVAL;
662                 LEAVE_RET('i', -1);
663         }
664         
665         // Check for directory
666         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
667                 Log_Warning("VFS", "VFS_OpenChild - Passed handle is not a directory");
668                 errno = ENOTDIR;
669                 LEAVE_RET('i', -1);
670         }
671
672         // Sanity check
673         if( !h->Node->Type || !h->Node->Type->FindDir ) {
674                 Log_Error("VFS", "VFS_OpenChild - Node does not have a type/is missing FindDir");
675                 errno = ENOTDIR;
676                 LEAVE_RET('i', -1);
677         }
678         
679         // Find Child
680         node = h->Node->Type->FindDir(h->Node, Name, 0);
681         if(!node) {
682                 errno = ENOENT;
683                 LEAVE_RET('i', -1);
684         }
685
686         // Increment open handle count, no problems with the mount going away as `h` is already open on it
687         _ReferenceMount(h->Mount, "OpenChild");
688
689         LEAVE_RET('x', VFS_int_CreateHandle(node, h->Mount, Mode));
690 }
691
692 int VFS_OpenInode(Uint32 Mount, Uint64 Inode, int Mode)
693 {
694         tVFS_Mount      *mnt;
695         tVFS_Node       *node;
696
697         ENTER("iMount XInode xMode", Mount, Inode, Mode);
698         
699         // Get mount point
700         mnt = VFS_GetMountByIdent(Mount);
701         if( !mnt ) {
702                 LOG("Mount point ident invalid");
703                 errno = ENOENT;
704                 LEAVE_RET('i', -1);
705         }
706         
707         // Does the filesystem support this?
708         if( !mnt->Filesystem->GetNodeFromINode ) {
709                 LOG("Filesystem does not support inode accesses");
710                 errno = ENOENT;
711                 LEAVE_RET('i', -1);
712         }
713
714         // Get node
715         node = mnt->Filesystem->GetNodeFromINode(mnt->RootNode, Inode);
716         if( !node ) {
717                 LOG("Unable to find inode");
718                 errno = ENOENT;
719                 LEAVE_RET('i', -1);
720         }
721         
722         LEAVE_RET('x', VFS_int_CreateHandle(node, mnt, Mode));
723 }
724
725 int VFS_Reopen(int FD, const char *Path, int Flags)
726 {
727         tVFS_Handle     *h = VFS_GetHandle(FD);
728         if(!h) {
729                 errno = EBADF;
730                 return -1;
731         }
732
733         int newf = VFS_Open(Path, Flags);
734         if( newf == -1 ) {
735                 return -1;
736         }
737         
738         _CloseNode(h->Node);
739         _DereferenceMount(h->Mount, "Reopen");
740         memcpy(h, VFS_GetHandle(newf), sizeof(*h));
741         _ReferenceNode(h->Node);
742         _ReferenceMount(h->Mount, "Reopen");
743         
744         VFS_Close(newf);        
745
746         return FD;
747 }
748
749 /**
750  * \fn void VFS_Close(int FD)
751  * \brief Closes an open file handle
752  */
753 void VFS_Close(int FD)
754 {
755         tVFS_Handle     *h;
756         
757         // Get handle
758         h = VFS_GetHandle(FD);
759         if(h == NULL) {
760                 Log_Warning("VFS", "Invalid file handle passed to VFS_Close, 0x%x", FD);
761                 return;
762         }
763
764         if( h->Node == NULL ) {
765                 Log_Warning("VFS", "Non-open handle passed to VFS_Close, 0x%x", FD);
766                 return ;
767         }       
768
769         #if VALIDATE_VFS_FUNCTIPONS
770         if(h->Node->Close && !MM_GetPhysAddr(h->Node->Close)) {
771                 Log_Warning("VFS", "Node %p's ->Close method is invalid (%p)",
772                         h->Node, h->Node->Close);
773                 return ;
774         }
775         #endif
776         
777         LOG("Handle %x", FD);
778         _CloseNode(h->Node);
779
780         if( h->Mount ) {
781                 _DereferenceMount(h->Mount, "Close");
782         }
783
784         h->Node = NULL;
785 }
786
787 int VFS_DuplicateFD(int SrcFD, int DstFD)
788 {
789          int    isUser = !(SrcFD & VFS_KERNEL_FLAG);
790         tVFS_Handle     *src = VFS_GetHandle(SrcFD);
791         if( !src )      return -1;
792         if( DstFD == -1 ) {
793                 DstFD = VFS_AllocHandle(isUser, src->Node, src->Mode);
794         }
795         else {
796                 // Can't overwrite
797                 if( VFS_GetHandle(DstFD) )
798                         return -1;
799                 VFS_SetHandle(DstFD, src->Node, src->Mode);
800         }
801         _ReferenceMount(src->Mount, "DuplicateFD");
802         _ReferenceNode(src->Node);
803         memcpy(VFS_GetHandle(DstFD), src, sizeof(tVFS_Handle));
804         return DstFD;
805 }
806
807 /*
808  * Update flags on a FD
809  */
810 int VFS_SetFDFlags(int FD, int Mask, int Value)
811 {
812         tVFS_Handle     *h = VFS_GetHandle(FD);
813         if(!FD) return -1;
814          int    ret = h->Mode;
815         
816         Value &= Mask;
817         h->Mode &= ~Mask;
818         h->Mode |= Value;
819         return ret;
820 }
821
822 /**
823  * \brief Change current working directory
824  */
825 int VFS_ChDir(const char *Dest)
826 {
827         char    *buf;
828          int    fd;
829         tVFS_Handle     *h;
830         
831         // Create Absolute
832         buf = VFS_GetAbsPath(Dest);
833         if(buf == NULL) {
834                 Log_Notice("VFS", "VFS_ChDir: Path expansion failed");
835                 return -1;
836         }
837         
838         // Check if path exists
839         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
840         if(fd == -1) {
841                 Log_Notice("VFS", "VFS_ChDir: Path is invalid");
842                 return -1;
843         }
844         
845         // Get node so we can check for directory
846         h = VFS_GetHandle(fd);
847         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
848                 Log("VFS_ChDir: Path is not a directory");
849                 VFS_Close(fd);
850                 return -1;
851         }
852         
853         // Close file
854         VFS_Close(fd);
855         
856         {
857                 char    **cwdptr = Threads_GetCWD();
858                 // Free old working directory
859                 if( *cwdptr )   free( *cwdptr );
860                 // Set new
861                 *cwdptr = buf;
862         }
863         
864         Log_Debug("VFS", "Updated CWD to '%s'", buf);
865         
866         return 1;
867 }
868
869 /**
870  * \fn int VFS_ChRoot(char *New)
871  * \brief Change current root directory
872  */
873 int VFS_ChRoot(const char *New)
874 {
875         char    *buf;
876          int    fd;
877         tVFS_Handle     *h;
878         
879         if(New[0] == '/' && New[1] == '\0')
880                 return 1;       // What a useless thing to ask!
881         
882         // Create Absolute
883         buf = VFS_GetAbsPath(New);
884         if(buf == NULL) {
885                 LOG("Path expansion failed");
886                 return -1;
887         }
888         
889         // Check if path exists
890         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
891         if(fd == -1) {
892                 LOG("Path is invalid");
893                 return -1;
894         }
895         
896         // Get node so we can check for directory
897         h = VFS_GetHandle(fd);
898         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
899                 LOG("Path is not a directory");
900                 VFS_Close(fd);
901                 return -1;
902         }
903         
904         // Close file
905         VFS_Close(fd);
906
907         // Update       
908         {
909                 char    **chroot_ptr = Threads_GetChroot();
910                 if( *chroot_ptr )       free( *chroot_ptr );
911                 *chroot_ptr = buf;
912         }
913         
914         LOG("Updated Root to '%s'", buf);
915         
916         return 1;
917 }
918
919 // === EXPORTS ===
920 EXPORT(VFS_Open);
921 EXPORT(VFS_Close);

UCC git Repository :: git.ucc.asn.au