AcessNative - Fixing bad handling of errors, add run script for ARCH=native
[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");
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 is not a directory");
395                         errno = ENOTDIR;
396                         goto _error;
397                 }
398                 
399                 // Check if path needs extending
400                 if(!TruePath)   continue;
401                 
402                 // Increase buffer space
403                 tmp = realloc( *TruePath, retLength + strlen(pathEle) + 1 + 1 );
404                 // Check if allocation succeeded
405                 if(!tmp) {
406                         Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
407                         errno = ENOMEM;
408                         goto _error;
409                 }
410                 *TruePath = tmp;
411                 // Append to path
412                 (*TruePath)[retLength] = '/';
413                 strcpy(*TruePath+retLength+1, pathEle);
414                 
415                 LOG("*TruePath = '%s'", *TruePath);
416                 
417                 // - Extend Path
418                 retLength += nextSlash + 1;
419         }
420
421         // Check final finddir call     
422         if( !curNode->Type || !curNode->Type->FindDir ) {
423                 Log_Warning("VFS", "VFS_ParsePath - FindDir doesn't exist for element of '%s'", Path);
424                 errno = ENOENT;
425                 goto _error;
426         }
427         
428         // Get last node
429         LOG("FindDir(%p, '%s')", curNode, &Path[ofs]);
430         tmpNode = curNode->Type->FindDir(curNode, &Path[ofs], 0);
431         LOG("tmpNode = %p", tmpNode);
432         // Check if file was found
433         if(!tmpNode) {
434                 LOG("Node '%s' not found in dir '%.*s'", &Path[ofs], ofs, Path);
435                 errno = ENOENT;
436                 goto _error;
437         }
438         _CloseNode( curNode );
439         
440         if(TruePath)
441         {
442                 // Increase buffer space
443                 tmp = realloc(*TruePath, retLength + strlen(&Path[ofs]) + 1 + 1);
444                 // Check if allocation succeeded
445                 if(!tmp) {
446                         Log_Warning("VFS", "VFS_ParsePath -  Unable to reallocate true path buffer");
447                         errno = ENOMEM;
448                         goto _error;
449                 }
450                 *TruePath = tmp;
451                 // Append to path
452                 (*TruePath)[retLength] = '/';
453                 strcpy(*TruePath + retLength + 1, &Path[ofs]);
454                 // - Extend Path
455                 //retLength += strlen(tmpNode->Name) + 1;
456         }
457
458         if( MountPoint ) {
459                 *MountPoint = mnt;
460         }
461         
462         // Leave the mointpoint's count increased
463         
464         LEAVE('p', tmpNode);
465         return tmpNode;
466
467 _error:
468         _CloseNode( curNode );
469         
470         if(TruePath && *TruePath) {
471                 free(*TruePath);
472                 *TruePath = NULL;
473         }
474         // Open failed, so decrement the open handle count
475         _DereferenceMount(mnt, "ParsePath - error");
476         LEAVE('n');
477         return NULL;
478 }
479
480 /**
481  * \brief Create and return a handle number for the given node and mode
482  */
483 int VFS_int_CreateHandle( tVFS_Node *Node, tVFS_Mount *Mount, int Mode )
484 {
485          int    i;
486         
487         ENTER("pNode pMount xMode", Node, Mount, Mode);
488
489         i = 0;
490         i |= (Mode & VFS_OPENFLAG_EXEC) ? VFS_PERM_EXEC : 0;
491         i |= (Mode & VFS_OPENFLAG_READ) ? VFS_PERM_READ : 0;
492         i |= (Mode & VFS_OPENFLAG_WRITE) ? VFS_PERM_WRITE : 0;
493         
494         LOG("i = 0b%b", i);
495         
496         // Permissions Check
497         if( !VFS_CheckACL(Node, i) ) {
498                 _CloseNode( Node );
499                 Log_Log("VFS", "VFS_int_CreateHandle: Permissions Failed");
500                 errno = EACCES;
501                 LEAVE_RET('i', -1);
502         }
503
504         if( MM_GetPhysAddr(Node->Type) == 0 ) {
505                 Log_Error("VFS", "Node %p from mount '%s' (%s) has a bad type (%p)",
506                         Node, Mount->MountPoint, Mount->Filesystem->Name, Node->Type);
507                 errno = EINTERNAL;
508                 LEAVE_RET('i', -1);
509         }
510         
511         i = VFS_AllocHandle( !!(Mode & VFS_OPENFLAG_USER), Node, Mode );
512         if( i < 0 ) {
513                 Log_Notice("VFS", "VFS_int_CreateHandle: Out of handles");
514                 errno = ENFILE;
515                 LEAVE_RET('i', -1);
516         }
517
518         VFS_GetHandle(i)->Mount = Mount;
519
520         LEAVE_RET('x', i);
521 }
522
523 /**
524  * \fn int VFS_Open(const char *Path, Uint Mode)
525  * \brief Open a file
526  */
527 int VFS_Open(const char *Path, Uint Flags)
528 {
529         return VFS_OpenEx(Path, Flags, 0);
530 }
531
532 int VFS_OpenEx(const char *Path, Uint Flags, Uint Mode)
533 {
534         tVFS_Node       *node;
535         tVFS_Mount      *mnt;
536         char    *absPath;
537         
538         ENTER("sPath xFlags oMode", Path, Flags);
539         
540         // Get absolute path
541         absPath = VFS_GetAbsPath(Path);
542         if(absPath == NULL) {
543                 Log_Warning("VFS", "VFS_Open: Path expansion failed '%s'", Path);
544                 LEAVE_RET('i', -1);
545         }
546         LOG("absPath = \"%s\"", absPath);
547         
548         // Parse path and get mount point
549         node = VFS_ParsePath(absPath, NULL, &mnt);
550         
551         // Create file if requested and it doesn't exist
552         if( !node && (Flags & VFS_OPENFLAG_CREATE) )
553         {
554                 // TODO: Translate `Mode` into ACL and node flags
555                 Uint    new_flags = 0;
556                 
557                 // Split path at final separator
558                 char *file = strrchr(absPath, '/');
559                 *file = '\0';
560                 file ++;
561
562                 // Get parent node
563                 tVFS_Mount      *pmnt;
564                 tVFS_Node *pnode = VFS_ParsePath(absPath, NULL, &pmnt);
565                 if(!pnode) {
566                         LOG("Unable to open parent '%s'", absPath);
567                         free(absPath);
568                         errno = ENOENT;
569                         LEAVE_RET('i', -1);
570                 }
571
572                 // Check ACLs on the parent
573                 if( !VFS_CheckACL(pnode, VFS_PERM_EXEC|VFS_PERM_WRITE) ) {
574                         errno = EACCES;
575                         goto _pnode_err;
576                 }
577
578                 // Check that there's a MkNod method
579                 if( !pnode->Type || !pnode->Type->MkNod ) {
580                         Log_Warning("VFS", "VFS_Open - Directory has no MkNod method");
581                         errno = EINVAL;
582                         goto _pnode_err;
583                 }
584                 
585                 node = pnode->Type->MkNod(pnode, file, new_flags);
586                 if( !node ) {
587                         LOG("Cannot create node '%s' in '%s'", file, absPath);
588                         errno = ENOENT;
589                         goto _pnode_err;
590                 }
591                 // Set mountpoint (and increment open handle count)
592                 mnt = pmnt;
593                 _ReferenceMount(mnt, "Open - create");
594                 // Fall through on error check
595                 
596                 _CloseNode(pnode);
597                 _DereferenceMount(pmnt, "Open - create");
598                 goto _pnode_ok;
599
600         _pnode_err:
601                 if( pnode ) {
602                         _CloseNode(pnode);
603                         _DereferenceMount(pmnt, "Open - create,fail");
604                         free(absPath);
605                 }
606                 LEAVE('i', -1);
607                 return -1;
608         }
609         _pnode_ok:
610         
611         // Free generated path
612         free(absPath);
613         
614         // Check for error
615         if(!node)
616         {
617                 LOG("Cannot find node");
618                 errno = ENOENT;
619                 goto _error;
620         }
621         
622         // Check for symlinks
623         if( !(Flags & VFS_OPENFLAG_NOLINK) && (node->Flags & VFS_FFLAG_SYMLINK) )
624         {
625                 char    tmppath[node->Size+1];
626                 if( node->Size > MAX_PATH_LEN ) {
627                         Log_Warning("VFS", "VFS_Open - Symlink is too long (%i)", node->Size);
628                         goto _error;
629                 }
630                 if( !node->Type || !node->Type->Read ) {
631                         Log_Warning("VFS", "VFS_Open - No read method on symlink");
632                         goto _error;
633                 }
634                 // Read symlink's path
635                 node->Type->Read( node, 0, node->Size, tmppath, 0 );
636                 tmppath[ node->Size ] = '\0';
637                 _CloseNode( node );
638                 _DereferenceMount(mnt, "Open - symlink");
639                 // Open the target
640                 node = VFS_ParsePath(tmppath, NULL, &mnt);
641                 if(!node) {
642                         LOG("Cannot find symlink target node (%s)", tmppath);
643                         errno = ENOENT;
644                         goto _error;
645                 }
646         }
647
648          int    ret = VFS_int_CreateHandle(node, mnt, Flags);
649         LEAVE_RET('x', ret);
650 _error:
651         if( node )
652         {
653                 _DereferenceMount(mnt, "Open - error");
654                 _CloseNode(node);
655         }
656         LEAVE_RET('i', -1);
657 }
658
659
660 /**
661  * \brief Open a file from an open directory
662  */
663 int VFS_OpenChild(int FD, const char *Name, Uint Mode)
664 {
665         tVFS_Handle     *h;
666         tVFS_Node       *node;
667         
668         ENTER("xFD sName xMode", FD, Name, Mode);
669
670         // Get handle
671         h = VFS_GetHandle(FD);
672         if(h == NULL) {
673                 Log_Warning("VFS", "VFS_OpenChild - Invalid file handle 0x%x", FD);
674                 errno = EINVAL;
675                 LEAVE_RET('i', -1);
676         }
677         
678         // Check for directory
679         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
680                 Log_Warning("VFS", "VFS_OpenChild - Passed handle is not a directory");
681                 errno = ENOTDIR;
682                 LEAVE_RET('i', -1);
683         }
684
685         // Sanity check
686         if( !h->Node->Type || !h->Node->Type->FindDir ) {
687                 Log_Error("VFS", "VFS_OpenChild - Node does not have a type/is missing FindDir");
688                 errno = ENOTDIR;
689                 LEAVE_RET('i', -1);
690         }
691         
692         // Find Child
693         node = h->Node->Type->FindDir(h->Node, Name, 0);
694         if(!node) {
695                 errno = ENOENT;
696                 LEAVE_RET('i', -1);
697         }
698
699         // Increment open handle count, no problems with the mount going away as `h` is already open on it
700         _ReferenceMount(h->Mount, "OpenChild");
701
702         LEAVE_RET('x', VFS_int_CreateHandle(node, h->Mount, Mode));
703 }
704
705 int VFS_OpenInode(Uint32 Mount, Uint64 Inode, int Mode)
706 {
707         tVFS_Mount      *mnt;
708         tVFS_Node       *node;
709
710         ENTER("iMount XInode xMode", Mount, Inode, Mode);
711         
712         // Get mount point
713         mnt = VFS_GetMountByIdent(Mount);
714         if( !mnt ) {
715                 LOG("Mount point ident invalid");
716                 errno = ENOENT;
717                 LEAVE_RET('i', -1);
718         }
719         
720         // Does the filesystem support this?
721         if( !mnt->Filesystem->GetNodeFromINode ) {
722                 Log_Notice("VFS", "Filesystem '%s' does not support inode accesses",
723                         mnt->Filesystem->Name);
724                 errno = ENOENT;
725                 LEAVE_RET('i', -1);
726         }
727
728         // Get node
729         node = mnt->Filesystem->GetNodeFromINode(mnt->RootNode, Inode);
730         if( !node ) {
731                 LOG("Unable to find inode");
732                 errno = ENOENT;
733                 LEAVE_RET('i', -1);
734         }
735         
736         LEAVE_RET('x', VFS_int_CreateHandle(node, mnt, Mode));
737 }
738
739 int VFS_Reopen(int FD, const char *Path, int Flags)
740 {
741         tVFS_Handle     *h = VFS_GetHandle(FD);
742         if(!h) {
743                 errno = EBADF;
744                 return -1;
745         }
746
747         int newf = VFS_Open(Path, Flags);
748         if( newf == -1 ) {
749                 // errno = set by VFS_Open
750                 return -1;
751         }
752         
753         _CloseNode(h->Node);
754         _DereferenceMount(h->Mount, "Reopen");
755         memcpy(h, VFS_GetHandle(newf), sizeof(*h));
756         _ReferenceNode(h->Node);
757         _ReferenceMount(h->Mount, "Reopen");
758         
759         VFS_Close(newf);        
760
761         return FD;
762 }
763
764 /**
765  * \fn void VFS_Close(int FD)
766  * \brief Closes an open file handle
767  */
768 void VFS_Close(int FD)
769 {
770         tVFS_Handle     *h;
771         
772         // Get handle
773         h = VFS_GetHandle(FD);
774         if(h == NULL) {
775                 Log_Warning("VFS", "Invalid file handle passed to VFS_Close, 0x%x", FD);
776                 errno = EINVAL;
777                 return;
778         }
779
780         if( h->Node == NULL ) {
781                 Log_Warning("VFS", "Non-open handle passed to VFS_Close, 0x%x", FD);
782                 errno = EINVAL;
783                 return ;
784         }       
785
786         #if VALIDATE_VFS_FUNCTIPONS
787         if(h->Node->Close && !MM_GetPhysAddr(h->Node->Close)) {
788                 Log_Warning("VFS", "Node %p's ->Close method is invalid (%p)",
789                         h->Node, h->Node->Close);
790                 errno = EINTERNAL;
791                 return ;
792         }
793         #endif
794         
795         LOG("Handle %x", FD);
796         _CloseNode(h->Node);
797
798         if( h->Mount ) {
799                 _DereferenceMount(h->Mount, "Close");
800         }
801
802         h->Node = NULL;
803 }
804
805 int VFS_DuplicateFD(int SrcFD, int DstFD)
806 {
807          int    isUser = !(SrcFD & VFS_KERNEL_FLAG);
808         tVFS_Handle     *src = VFS_GetHandle(SrcFD);
809         if( !src )      return -1;
810         if( DstFD == -1 ) {
811                 DstFD = VFS_AllocHandle(isUser, src->Node, src->Mode);
812         }
813         else {
814                 // Can't overwrite
815                 if( VFS_GetHandle(DstFD) )
816                         return -1;
817                 VFS_SetHandle(DstFD, src->Node, src->Mode);
818         }
819         _ReferenceMount(src->Mount, "DuplicateFD");
820         _ReferenceNode(src->Node);
821         memcpy(VFS_GetHandle(DstFD), src, sizeof(tVFS_Handle));
822         return DstFD;
823 }
824
825 /*
826  * Update flags on a FD
827  */
828 int VFS_SetFDFlags(int FD, int Mask, int Value)
829 {
830         tVFS_Handle     *h = VFS_GetHandle(FD);
831         if(!h) {
832                 errno = EBADF;
833                 return -1;
834         }
835          int    ret = h->Mode;
836         
837         Value &= Mask;
838         h->Mode &= ~Mask;
839         h->Mode |= Value;
840         return ret;
841 }
842
843 /**
844  * \brief Change current working directory
845  */
846 int VFS_ChDir(const char *Dest)
847 {
848         char    *buf;
849          int    fd;
850         tVFS_Handle     *h;
851         
852         // Create Absolute
853         buf = VFS_GetAbsPath(Dest);
854         if(buf == NULL) {
855                 Log_Notice("VFS", "VFS_ChDir: Path expansion failed");
856                 return -1;
857         }
858         
859         // Check if path exists
860         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
861         if(fd == -1) {
862                 Log_Notice("VFS", "VFS_ChDir: Path is invalid");
863                 return -1;
864         }
865         
866         // Get node so we can check for directory
867         h = VFS_GetHandle(fd);
868         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
869                 Log("VFS_ChDir: Path is not a directory");
870                 VFS_Close(fd);
871                 return -1;
872         }
873         
874         // Close file
875         VFS_Close(fd);
876         
877         {
878                 char    **cwdptr = Threads_GetCWD(NULL);
879                 // Free old working directory
880                 if( *cwdptr )   free( *cwdptr );
881                 // Set new
882                 *cwdptr = buf;
883         }
884         
885         Log_Debug("VFS", "Updated CWD to '%s'", buf);
886         
887         return 1;
888 }
889
890 /**
891  * \fn int VFS_ChRoot(char *New)
892  * \brief Change current root directory
893  */
894 int VFS_ChRoot(const char *New)
895 {
896         char    *buf;
897          int    fd;
898         tVFS_Handle     *h;
899         
900         if(New[0] == '/' && New[1] == '\0')
901                 return 1;       // What a useless thing to ask!
902         
903         // Create Absolute
904         buf = VFS_GetAbsPath(New);
905         if(buf == NULL) {
906                 LOG("Path expansion failed");
907                 return -1;
908         }
909         
910         // Check if path exists
911         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
912         if(fd == -1) {
913                 LOG("Path is invalid");
914                 return -1;
915         }
916         
917         // Get node so we can check for directory
918         h = VFS_GetHandle(fd);
919         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
920                 LOG("Path is not a directory");
921                 VFS_Close(fd);
922                 return -1;
923         }
924         
925         // Close file
926         VFS_Close(fd);
927
928         // Update       
929         {
930                 char    **chroot_ptr = Threads_GetChroot(NULL);
931                 if( *chroot_ptr )       free( *chroot_ptr );
932                 *chroot_ptr = buf;
933         }
934         
935         LOG("Updated Root to '%s'", buf);
936         
937         return 1;
938 }
939
940 /*
941  * Marshal a handle so that it can be transferred between processes
942  */
943 Uint64 VFS_MarshalHandle(int FD)
944 {
945         tVFS_Handle     *h = VFS_GetHandle(FD);
946         if(!h || !h->Node) {
947                 errno = EBADF;
948                 return -1;
949         }
950         
951         // Allocate marshal location
952          int    ret = -1;
953         Mutex_Acquire(&glVFS_MarshalledHandles);
954         for( int i = 0; i < MAX_MARSHALLED_HANDLES; i ++ )
955         {
956                 tVFS_MarshalledHandle*  mh = &gaVFS_MarshalledHandles[i];
957                 if( mh->Handle.Node == NULL ) {
958                         mh->Handle.Node = h->Node;
959                         mh->AllocTime = now();
960                         ret = i;
961                 }
962                 if( now() - mh->AllocTime > 2000 ) {
963                         Log_Notice("VFS", "TODO: Expire marshalled handle");
964                 }
965         }
966         Mutex_Release(&glVFS_MarshalledHandles);
967         if( ret < 0 ) {
968                 // TODO: Need to clean up lost handles to avoid DOS
969                 Log_Warning("VFS", "Out of marshaled handle slots");
970                 errno = EAGAIN;
971                 return -1;
972         }
973         
974         // Populate
975         tVFS_MarshalledHandle*  mh = &gaVFS_MarshalledHandles[ret];
976         mh->Handle = *h;
977         _ReferenceMount(h->Mount, "MarshalHandle");
978         _ReferenceNode(h->Node);
979         mh->Magic = rand();
980         
981         return (Uint64)mh->Magic << 32 | ret;
982 }
983
984 /*
985  * Un-marshal a handle into the current process
986  * NOTE: Does not support unmarshalling into kernel handle list
987  */
988 int VFS_UnmarshalHandle(Uint64 Handle)
989 {
990         Uint32  magic = Handle >> 32;
991          int    id = Handle & 0xFFFFFFFF;
992         
993         // Range check
994         if( id >= MAX_MARSHALLED_HANDLES ) {
995                 LOG("ID too high (%i > %i)", id, MAX_MARSHALLED_HANDLES);
996                 errno = EINVAL;
997                 return -1;
998         }
999         
1000         
1001         // Check validity
1002         tVFS_MarshalledHandle   *mh = &gaVFS_MarshalledHandles[id];
1003         if( mh->Handle.Node == NULL ) {
1004                 LOG("Target node is NULL");
1005                 errno = EINVAL;
1006                 return -1;
1007         }
1008         if( mh->Magic != magic ) {
1009                 LOG("Magic mismatch (0x%08x != 0x%08x)", magic, mh->Magic);
1010                 errno = EACCES;
1011                 return -1;
1012         }
1013         
1014         Mutex_Acquire(&glVFS_MarshalledHandles);
1015         // - Create destination handle
1016          int    ret = VFS_AllocHandle(true, mh->Handle.Node, mh->Handle.Mode);
1017         // - Clear allocation
1018         mh->Handle.Node = NULL;
1019         Mutex_Release(&glVFS_MarshalledHandles);
1020         if( ret == -1 ) {
1021                 errno = ENFILE;
1022                 return -1;
1023         }
1024         
1025         // No need to reference node/mount, new handle takes marshalled reference
1026         
1027         return ret;
1028 }
1029
1030 // === EXPORTS ===
1031 EXPORT(VFS_Open);
1032 EXPORT(VFS_Close);

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