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

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