Merge branch 'master' of ssh.ucc.asn.au:tpg/acess2
[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                         goto _error;
302                 }
303                 
304                 // Check if the node has a FindDir method
305                 if( !curNode->Type )
306                 {
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);
310                         goto _error;
311                 }
312                 if( !curNode->Type->FindDir )
313                 {
314                         LOG("Finddir failure on '%s' - No FindDir method in %s", Path, curNode->Type->TypeName);
315                         goto _error;
316                 }
317                 LOG("FindDir{=%p}(%p, '%s')", curNode->Type->FindDir, curNode, pathEle);
318                 // Get Child Node
319                 tmpNode = curNode->Type->FindDir(curNode, pathEle);
320                 LOG("tmpNode = %p", tmpNode);
321                 _CloseNode( curNode );
322                 curNode = tmpNode;
323                 
324                 // Error Check
325                 if(!curNode) {
326                         LOG("Node '%s' not found in dir '%s'", pathEle, Path);
327                         goto _error;
328                 }
329                 
330                 // Handle Symbolic Links
331                 if(curNode->Flags & VFS_FFLAG_SYMLINK) {
332                         if(TruePath) {
333                                 free(*TruePath);
334                                 *TruePath = NULL;
335                         }
336                         if(!curNode->Type || !curNode->Type->Read) {
337                                 Log_Warning("VFS", "VFS_ParsePath - Read of symlink node %p'%s' is NULL",
338                                         curNode, Path);
339                                 goto _error;
340                         }
341                         
342                         if(iNestedLinks > MAX_NESTED_LINKS) {
343                                 Log_Notice("VFS", "VFS_ParsePath - Nested link limit exceeded");
344                                 goto _error;
345                         }
346                         
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)
350                         {
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");
354                                         goto _error;
355                                 }
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
361                                 
362                                 Path = path_buffer;
363 //                              Log_Debug("VFS", "VFS_ParsePath: Symlink translated to '%s'", Path);
364                                 iNestedLinks ++;
365                         }
366
367                         // EVIL: Goto :)
368                         LOG("Symlink -> '%s', restart", Path);
369                         _DereferenceMount(mnt, "ParsePath - sym");
370                         goto restart_parse;
371                 }
372                 
373                 // Handle Non-Directories
374                 if( !(curNode->Flags & VFS_FFLAG_DIRECTORY) )
375                 {
376                         Log_Warning("VFS", "VFS_ParsePath - Path segment is not a directory");
377                         goto _error;
378                 }
379                 
380                 // Check if path needs extending
381                 if(!TruePath)   continue;
382                 
383                 // Increase buffer space
384                 tmp = realloc( *TruePath, retLength + strlen(pathEle) + 1 + 1 );
385                 // Check if allocation succeeded
386                 if(!tmp) {
387                         Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
388                         goto _error;
389                 }
390                 *TruePath = tmp;
391                 // Append to path
392                 (*TruePath)[retLength] = '/';
393                 strcpy(*TruePath+retLength+1, pathEle);
394                 
395                 LOG("*TruePath = '%s'", *TruePath);
396                 
397                 // - Extend Path
398                 retLength += nextSlash + 1;
399         }
400
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);
404                 goto _error;
405         }
406         
407         // Get last node
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
412         if(!tmpNode) {
413                 LOG("Node '%s' not found in dir '%.*s'", &Path[ofs], ofs, Path);
414                 goto _error;
415         }
416         _CloseNode( curNode );
417         
418         if(TruePath)
419         {
420                 // Increase buffer space
421                 tmp = realloc(*TruePath, retLength + strlen(&Path[ofs]) + 1 + 1);
422                 // Check if allocation succeeded
423                 if(!tmp) {
424                         Log_Warning("VFS", "VFS_ParsePath -  Unable to reallocate true path buffer");
425                         goto _error;
426                 }
427                 *TruePath = tmp;
428                 // Append to path
429                 (*TruePath)[retLength] = '/';
430                 strcpy(*TruePath + retLength + 1, &Path[ofs]);
431                 // - Extend Path
432                 //retLength += strlen(tmpNode->Name) + 1;
433         }
434
435         if( MountPoint ) {
436                 *MountPoint = mnt;
437         }
438         
439         // Leave the mointpoint's count increased
440         
441         LEAVE('p', tmpNode);
442         return tmpNode;
443
444 _error:
445         _CloseNode( curNode );
446         
447         if(TruePath && *TruePath) {
448                 free(*TruePath);
449                 *TruePath = NULL;
450         }
451         // Open failed, so decrement the open handle count
452         _DereferenceMount(mnt, "ParsePath - error");
453         
454         LEAVE('n');
455         return NULL;
456 }
457
458 /**
459  * \brief Create and return a handle number for the given node and mode
460  */
461 int VFS_int_CreateHandle( tVFS_Node *Node, tVFS_Mount *Mount, int Mode )
462 {
463          int    i;
464         
465         ENTER("pNode pMount xMode", Node, Mount, Mode);
466
467         i = 0;
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;
471         
472         LOG("i = 0b%b", i);
473         
474         // Permissions Check
475         if( !VFS_CheckACL(Node, i) ) {
476                 _CloseNode( Node );
477                 Log_Log("VFS", "VFS_int_CreateHandle: Permissions Failed");
478                 errno = EACCES;
479                 LEAVE_RET('i', -1);
480         }
481
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);
485                 errno = EINTERNAL;
486                 LEAVE_RET('i', -1);
487         }
488         
489         i = VFS_AllocHandle( !!(Mode & VFS_OPENFLAG_USER), Node, Mode );
490         if( i < 0 ) {
491                 Log_Notice("VFS", "VFS_int_CreateHandle: Out of handles");
492                 errno = ENFILE;
493                 LEAVE_RET('i', -1);
494         }
495
496         VFS_GetHandle(i)->Mount = Mount;
497
498         LEAVE_RET('x', i);
499 }
500
501 /**
502  * \fn int VFS_Open(const char *Path, Uint Mode)
503  * \brief Open a file
504  */
505 int VFS_Open(const char *Path, Uint Flags)
506 {
507         return VFS_OpenEx(Path, Flags, 0);
508 }
509
510 int VFS_OpenEx(const char *Path, Uint Flags, Uint Mode)
511 {
512         tVFS_Node       *node;
513         tVFS_Mount      *mnt;
514         char    *absPath;
515         
516         ENTER("sPath xFlags oMode", Path, Flags);
517         
518         // Get absolute path
519         absPath = VFS_GetAbsPath(Path);
520         if(absPath == NULL) {
521                 Log_Warning("VFS", "VFS_Open: Path expansion failed '%s'", Path);
522                 LEAVE_RET('i', -1);
523         }
524         LOG("absPath = \"%s\"", absPath);
525         
526         // Parse path and get mount point
527         node = VFS_ParsePath(absPath, NULL, &mnt);
528         
529         // Create file if requested and it doesn't exist
530         if( !node && (Flags & VFS_OPENFLAG_CREATE) )
531         {
532                 // TODO: Translate `Mode` into ACL and node flags
533                 Uint    new_flags = 0;
534                 
535                 // Split path at final separator
536                 char *file = strrchr(absPath, '/');
537                 *file = '\0';
538                 file ++;
539
540                 // Get parent node
541                 tVFS_Mount      *pmnt;
542                 tVFS_Node *pnode = VFS_ParsePath(absPath, NULL, &pmnt);
543                 if(!pnode) {
544                         LOG("Unable to open parent '%s'", absPath);
545                         free(absPath);
546                         errno = ENOENT;
547                         LEAVE_RET('i', -1);
548                 }
549
550                 // Check ACLs on the parent
551                 if( !VFS_CheckACL(pnode, VFS_PERM_EXECUTE|VFS_PERM_WRITE) ) {
552                         errno = EACCES;
553                         goto _pnode_err;
554                 }
555
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");
559                         errno = EINVAL;
560                         goto _pnode_err;
561                 }
562                 
563                 node = pnode->Type->MkNod(pnode, file, new_flags);
564                 if( !node ) {
565                         LOG("Cannot create node '%s' in '%s'", file, absPath);
566                         errno = ENOENT;
567                         goto _pnode_err;
568                 }
569                 // Set mountpoint (and increment open handle count)
570                 mnt = pmnt;
571                 _ReferenceMount(mnt, "Open - create");
572                 // Fall through on error check
573                 
574                 _CloseNode(pnode);
575                 _DereferenceMount(pmnt, "Open - create");
576                 goto _pnode_ok;
577
578         _pnode_err:
579                 if( pnode ) {
580                         _CloseNode(pnode);
581                         _DereferenceMount(pmnt, "Open - create,fail");
582                         free(absPath);
583                 }
584                 LEAVE('i', -1);
585                 return -1;
586         }
587         _pnode_ok:
588         
589         // Free generated path
590         free(absPath);
591         
592         // Check for error
593         if(!node)
594         {
595                 LOG("Cannot find node");
596                 errno = ENOENT;
597                 goto _error;
598         }
599         
600         // Check for symlinks
601         if( !(Flags & VFS_OPENFLAG_NOLINK) && (node->Flags & VFS_FFLAG_SYMLINK) )
602         {
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);
606                         goto _error;
607                 }
608                 if( !node->Type || !node->Type->Read ) {
609                         Log_Warning("VFS", "VFS_Open - No read method on symlink");
610                         goto _error;
611                 }
612                 // Read symlink's path
613                 node->Type->Read( node, 0, node->Size, tmppath );
614                 tmppath[ node->Size ] = '\0';
615                 _CloseNode( node );
616                 _DereferenceMount(mnt, "Open - symlink");
617                 // Open the target
618                 node = VFS_ParsePath(tmppath, NULL, &mnt);
619                 if(!node) {
620                         LOG("Cannot find symlink target node (%s)", tmppath);
621                         errno = ENOENT;
622                         goto _error;
623                 }
624         }
625
626          int    ret = VFS_int_CreateHandle(node, mnt, Flags);
627         LEAVE_RET('x', ret);
628 _error:
629         if( node )
630         {
631                 _DereferenceMount(mnt, "Open - error");
632                 _CloseNode(node);
633         }
634         LEAVE_RET('i', -1);
635 }
636
637
638 /**
639  * \brief Open a file from an open directory
640  */
641 int VFS_OpenChild(int FD, const char *Name, Uint Mode)
642 {
643         tVFS_Handle     *h;
644         tVFS_Node       *node;
645         
646         ENTER("xFD sName xMode", FD, Name, Mode);
647
648         // Get handle
649         h = VFS_GetHandle(FD);
650         if(h == NULL) {
651                 Log_Warning("VFS", "VFS_OpenChild - Invalid file handle 0x%x", FD);
652                 errno = EINVAL;
653                 LEAVE_RET('i', -1);
654         }
655         
656         // Check for directory
657         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
658                 Log_Warning("VFS", "VFS_OpenChild - Passed handle is not a directory");
659                 errno = ENOTDIR;
660                 LEAVE_RET('i', -1);
661         }
662
663         // Sanity check
664         if( !h->Node->Type || !h->Node->Type->FindDir ) {
665                 Log_Error("VFS", "VFS_OpenChild - Node does not have a type/is missing FindDir");
666                 errno = ENOTDIR;
667                 LEAVE_RET('i', -1);
668         }
669         
670         // Find Child
671         node = h->Node->Type->FindDir(h->Node, Name);
672         if(!node) {
673                 errno = ENOENT;
674                 LEAVE_RET('i', -1);
675         }
676
677         // Increment open handle count, no problems with the mount going away as `h` is already open on it
678         _ReferenceMount(h->Mount, "OpenChild");
679
680         LEAVE_RET('x', VFS_int_CreateHandle(node, h->Mount, Mode));
681 }
682
683 int VFS_OpenInode(Uint32 Mount, Uint64 Inode, int Mode)
684 {
685         tVFS_Mount      *mnt;
686         tVFS_Node       *node;
687
688         ENTER("iMount XInode xMode", Mount, Inode, Mode);
689         
690         // Get mount point
691         mnt = VFS_GetMountByIdent(Mount);
692         if( !mnt ) {
693                 LOG("Mount point ident invalid");
694                 errno = ENOENT;
695                 LEAVE_RET('i', -1);
696         }
697         
698         // Does the filesystem support this?
699         if( !mnt->Filesystem->GetNodeFromINode ) {
700                 LOG("Filesystem does not support inode accesses");
701                 errno = ENOENT;
702                 LEAVE_RET('i', -1);
703         }
704
705         // Get node
706         node = mnt->Filesystem->GetNodeFromINode(mnt->RootNode, Inode);
707         if( !node ) {
708                 LOG("Unable to find inode");
709                 errno = ENOENT;
710                 LEAVE_RET('i', -1);
711         }
712         
713         LEAVE_RET('x', VFS_int_CreateHandle(node, mnt, Mode));
714 }
715
716 /**
717  * \fn void VFS_Close(int FD)
718  * \brief Closes an open file handle
719  */
720 void VFS_Close(int FD)
721 {
722         tVFS_Handle     *h;
723         
724         // Get handle
725         h = VFS_GetHandle(FD);
726         if(h == NULL) {
727                 Log_Warning("VFS", "Invalid file handle passed to VFS_Close, 0x%x", FD);
728                 return;
729         }
730
731         if( h->Node == NULL ) {
732                 Log_Warning("VFS", "Non-open handle passed to VFS_Close, 0x%x", FD);
733                 return ;
734         }       
735
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);
740                 return ;
741         }
742         #endif
743         
744         LOG("Handle %x", FD);
745         _CloseNode(h->Node);
746
747         if( h->Mount ) {
748                 _DereferenceMount(h->Mount, "Close");
749         }
750
751         h->Node = NULL;
752 }
753
754 int VFS_DuplicateFD(int SrcFD, int DstFD)
755 {
756          int    isUser = !(SrcFD & VFS_KERNEL_FLAG);
757         tVFS_Handle     *src = VFS_GetHandle(SrcFD);
758         if( !src )      return -1;
759         if( DstFD == -1 ) {
760                 DstFD = VFS_AllocHandle(isUser, src->Node, src->Mode);
761         }
762         else {
763                 // Can't overwrite
764                 if( VFS_GetHandle(DstFD) )
765                         return -1;
766                 VFS_SetHandle(DstFD, src->Node, src->Mode);
767         }
768         memcpy(VFS_GetHandle(DstFD), src, sizeof(tVFS_Handle));
769         return DstFD;
770 }
771
772 /**
773  * \brief Change current working directory
774  */
775 int VFS_ChDir(const char *Dest)
776 {
777         char    *buf;
778          int    fd;
779         tVFS_Handle     *h;
780         
781         // Create Absolute
782         buf = VFS_GetAbsPath(Dest);
783         if(buf == NULL) {
784                 Log_Notice("VFS", "VFS_ChDir: Path expansion failed");
785                 return -1;
786         }
787         
788         // Check if path exists
789         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
790         if(fd == -1) {
791                 Log_Notice("VFS", "VFS_ChDir: Path is invalid");
792                 return -1;
793         }
794         
795         // Get node so we can check for directory
796         h = VFS_GetHandle(fd);
797         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
798                 Log("VFS_ChDir: Path is not a directory");
799                 VFS_Close(fd);
800                 return -1;
801         }
802         
803         // Close file
804         VFS_Close(fd);
805         
806         {
807                 char    **cwdptr = Threads_GetCWD();
808                 // Free old working directory
809                 if( *cwdptr )   free( *cwdptr );
810                 // Set new
811                 *cwdptr = buf;
812         }
813         
814         Log_Debug("VFS", "Updated CWD to '%s'", buf);
815         
816         return 1;
817 }
818
819 /**
820  * \fn int VFS_ChRoot(char *New)
821  * \brief Change current root directory
822  */
823 int VFS_ChRoot(const char *New)
824 {
825         char    *buf;
826          int    fd;
827         tVFS_Handle     *h;
828         
829         if(New[0] == '/' && New[1] == '\0')
830                 return 1;       // What a useless thing to ask!
831         
832         // Create Absolute
833         buf = VFS_GetAbsPath(New);
834         if(buf == NULL) {
835                 LOG("Path expansion failed");
836                 return -1;
837         }
838         
839         // Check if path exists
840         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
841         if(fd == -1) {
842                 LOG("Path is invalid");
843                 return -1;
844         }
845         
846         // Get node so we can check for directory
847         h = VFS_GetHandle(fd);
848         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
849                 LOG("Path is not a directory");
850                 VFS_Close(fd);
851                 return -1;
852         }
853         
854         // Close file
855         VFS_Close(fd);
856
857         // Update       
858         {
859                 char    **chroot_ptr = Threads_GetChroot();
860                 if( *chroot_ptr )       free( *chroot_ptr );
861                 *chroot_ptr = buf;
862         }
863         
864         LOG("Updated Root to '%s'", buf);
865         
866         return 1;
867 }
868
869 // === EXPORTS ===
870 EXPORT(VFS_Open);
871 EXPORT(VFS_Close);

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