VFS - Rework to remove function pointers from tVFS_Node
[tpg/acess2.git] / Kernel / vfs / open.c
1 /*
2  * Acess2 VFS
3  * - Open, Close and ChDir
4  */
5 #define DEBUG   0
6 #include <acess.h>
7 #include "vfs.h"
8 #include "vfs_int.h"
9 #include "vfs_ext.h"
10
11 // === CONSTANTS ===
12 #define OPEN_MOUNT_ROOT 1
13 #define MAX_PATH_SLASHES        256
14 #define MAX_NESTED_LINKS        4
15 #define MAX_PATH_LEN    255
16
17 // === IMPORTS ===
18 extern tVFS_Mount       *gVFS_RootMount;
19 extern int      VFS_AllocHandle(int bIsUser, tVFS_Node *Node, int Mode);
20 extern tVFS_Node        *VFS_MemFile_Create(const char *Path);
21
22 // === PROTOTYPES ===
23  int    VFS_int_CreateHandle( tVFS_Node *Node, tVFS_Mount *Mount, int Mode );
24
25 // === CODE ===
26 /**
27  * \fn char *VFS_GetAbsPath(const char *Path)
28  * \brief Create an absolute path from a relative one
29  */
30 char *VFS_GetAbsPath(const char *Path)
31 {
32         char    *ret;
33          int    pathLen = strlen(Path);
34         char    *pathComps[MAX_PATH_SLASHES];
35         char    *tmpStr;
36         int             iPos = 0;
37         int             iPos2 = 0;
38         const char      *chroot = CFGPTR(CFG_VFS_CHROOT);
39          int    chrootLen;
40         const char      *cwd = CFGPTR(CFG_VFS_CWD);
41          int    cwdLen;
42         
43         ENTER("sPath", Path);
44         
45         // Memory File
46         if(Path[0] == '$') {
47                 ret = malloc(strlen(Path)+1);
48                 if(!ret) {
49                         Log_Warning("VFS", "VFS_GetAbsPath: malloc() returned NULL");
50                         return NULL;
51                 }
52                 strcpy(ret, Path);
53                 LEAVE('p', ret);
54                 return ret;
55         }
56         
57         // - Fetch ChRoot
58         if( chroot == NULL )
59                 chroot = "";
60         chrootLen = strlen(chroot);
61         
62         // Check if the path is already absolute
63         if(Path[0] == '/') {
64                 ret = malloc(chrootLen + pathLen + 1);
65                 if(!ret) {
66                         Log_Warning("VFS", "VFS_GetAbsPath: malloc() returned NULL");
67                         return NULL;
68                 }
69                 strcpy(ret + chrootLen, Path);
70         }
71         else {
72                 if(cwd == NULL) {
73                         cwd = "/";
74                         cwdLen = 1;
75                 }
76                 else {
77                         cwdLen = strlen(cwd);
78                 }
79                 // Prepend the current directory
80                 ret = malloc(chrootLen + cwdLen + 1 + pathLen + 1 );
81                 strcpy(ret+chrootLen, cwd);
82                 ret[cwdLen] = '/';
83                 strcpy(ret+chrootLen+cwdLen+1, Path);
84                 //Log("ret = '%s'", ret);
85         }
86         
87         // Parse Path
88         pathComps[iPos++] = tmpStr = ret+chrootLen+1;
89         while(*tmpStr)
90         {
91                 if(*tmpStr++ == '/')
92                 {
93                         pathComps[iPos++] = tmpStr;
94                         if(iPos == MAX_PATH_SLASHES) {
95                                 LOG("Path '%s' has too many elements", Path);
96                                 free(ret);
97                                 LEAVE('n');
98                                 return NULL;
99                         }
100                 }
101         }
102         pathComps[iPos] = NULL;
103         
104         // Cleanup
105         iPos2 = iPos = 0;
106         while(pathComps[iPos])
107         {
108                 tmpStr = pathComps[iPos];
109                 // Always Increment iPos
110                 iPos++;
111                 // ..
112                 if(tmpStr[0] == '.' && tmpStr[1] == '.' && (tmpStr[2] == '/' || tmpStr[2] == '\0') )
113                 {
114                         if(iPos2 != 0)
115                                 iPos2 --;
116                         continue;
117                 }
118                 // .
119                 if(tmpStr[0] == '.' && (tmpStr[1] == '/' || tmpStr[1] == '\0') )
120                 {
121                         continue;
122                 }
123                 // Empty
124                 if(tmpStr[0] == '/' || tmpStr[0] == '\0')
125                 {
126                         continue;
127                 }
128                 
129                 // Set New Position
130                 pathComps[iPos2] = tmpStr;
131                 iPos2++;
132         }
133         pathComps[iPos2] = NULL;
134         
135         // Build New Path
136         iPos2 = chrootLen + 1;  iPos = 0;
137         ret[0] = '/';
138         while(pathComps[iPos])
139         {
140                 tmpStr = pathComps[iPos];
141                 while(*tmpStr && *tmpStr != '/')
142                 {
143                         ret[iPos2++] = *tmpStr;
144                         tmpStr++;
145                 }
146                 ret[iPos2++] = '/';
147                 iPos++;
148         }
149         if(iPos2 > 1)
150                 ret[iPos2-1] = 0;
151         else
152                 ret[iPos2] = 0;
153
154         // Prepend the chroot
155         if(chrootLen)
156                 memcpy( ret, chroot, chrootLen );
157         
158         LEAVE('s', ret);
159 //      Log_Debug("VFS", "VFS_GetAbsPath: RETURN '%s'", ret);
160         return ret;
161 }
162
163 /**
164  * \fn char *VFS_ParsePath(const char *Path, char **TruePath)
165  * \brief Parses a path, resolving sysmlinks and applying permissions
166  */
167 tVFS_Node *VFS_ParsePath(const char *Path, char **TruePath, tVFS_Mount **MountPoint)
168 {
169         tVFS_Mount      *mnt, *longestMount;
170          int    cmp, retLength = 0;
171          int    ofs, nextSlash;
172          int    iNestedLinks = 0;
173         tVFS_Node       *curNode, *tmpNode;
174         char    *tmp;
175         char    path_buffer[MAX_PATH_LEN+1];
176         
177         ENTER("sPath pTruePath", Path, TruePath);
178         
179         // HACK: Memory File
180         if(Threads_GetUID() == 0 && Path[0] == '$') {
181                 if(TruePath) {
182                         *TruePath = malloc(strlen(Path)+1);
183                         strcpy(*TruePath, Path);
184                 }
185                 curNode = VFS_MemFile_Create(Path);
186                 if(MountPoint) {
187                         *MountPoint = NULL;
188                 }
189                 LEAVE('p', curNode);
190                 return curNode;
191         }
192
193 restart_parse:  
194         // For root we always fast return
195         if(Path[0] == '/' && Path[1] == '\0') {
196                 if(TruePath) {
197                         *TruePath = malloc( gVFS_RootMount->MountPointLen+1 );
198                         strcpy(*TruePath, gVFS_RootMount->MountPoint);
199                 }
200                 if(MountPoint)  *MountPoint = gVFS_RootMount;
201                 LEAVE('p', gVFS_RootMount->RootNode);
202                 return gVFS_RootMount->RootNode;
203         }
204         
205         // Check if there is anything mounted
206         if(!gVFS_Mounts) {
207                 Log_Error("VFS", "VFS_ParsePath - No filesystems mounted");
208                 return NULL;
209         }
210         
211         // Find Mountpoint
212         longestMount = gVFS_RootMount;
213         for(mnt = gVFS_Mounts; mnt; mnt = mnt->Next)
214         {
215                 // Quick Check
216                 if( Path[mnt->MountPointLen] != '/' && Path[mnt->MountPointLen] != '\0')
217                         continue;
218                 // Length Check - If the length is smaller than the longest match sofar
219                 if(mnt->MountPointLen < longestMount->MountPointLen)    continue;
220                 // String Compare
221                 cmp = strcmp(Path, mnt->MountPoint);
222                 
223                 #if OPEN_MOUNT_ROOT
224                 // Fast Break - Request Mount Root
225                 if(cmp == 0) {
226                         if(TruePath) {
227                                 *TruePath = malloc( mnt->MountPointLen+1 );
228                                 strcpy(*TruePath, mnt->MountPoint);
229                         }
230                         if(MountPoint)
231                                 *MountPoint = mnt;
232                         LEAVE('p', mnt->RootNode);
233                         return mnt->RootNode;
234                 }
235                 #endif
236                 // Not a match, continue
237                 if(cmp != '/')  continue;
238                 longestMount = mnt;
239         }
240         
241         // Save to shorter variable
242         mnt = longestMount;
243         
244         LOG("mnt = {MountPoint:\"%s\"}", mnt->MountPoint);
245         
246         // Initialise String
247         if(TruePath)
248         {
249                 // Assumes that the resultant path (here) will not be > strlen(Path) + 1
250                 *TruePath = malloc( strlen(Path) + 1 );
251                 strcpy(*TruePath, mnt->MountPoint);
252                 retLength = mnt->MountPointLen;
253         }
254         
255         curNode = mnt->RootNode;
256         curNode->ReferenceCount ++;     
257         // Parse Path
258         ofs = mnt->MountPointLen+1;
259         for(; (nextSlash = strpos(&Path[ofs], '/')) != -1; ofs += nextSlash + 1)
260         {
261                 char    pathEle[nextSlash+1];
262                 
263                 // Empty String
264                 if(nextSlash == 0)      continue;
265                 
266                 memcpy(pathEle, &Path[ofs], nextSlash);
267                 pathEle[nextSlash] = 0;
268         
269                 // Check permissions on root of filesystem
270                 if( !VFS_CheckACL(curNode, VFS_PERM_EXECUTE) ) {
271                         //Log("Permissions fail on '%s'", Path);
272                         goto _error;
273                 }
274                 
275                 // Check if the node has a FindDir method
276                 if( !curNode->Type->FindDir )
277                 {
278                         //Log("FindDir fail on '%s'", Path);
279                         goto _error;
280                 }
281                 LOG("FindDir{=%p}(%p, '%s')", curNode->Type->FindDir, curNode, pathEle);
282                 // Get Child Node
283                 tmpNode = curNode->Type->FindDir(curNode, pathEle);
284                 LOG("tmpNode = %p", tmpNode);
285                 _CloseNode( curNode );
286                 curNode = tmpNode;
287                 
288                 // Error Check
289                 if(!curNode) {
290                         LOG("Node '%s' not found in dir '%s'", pathEle, Path);
291                         goto _error;
292                 }
293                 
294                 // Handle Symbolic Links
295                 if(curNode->Flags & VFS_FFLAG_SYMLINK) {
296                         if(TruePath) {
297                                 free(*TruePath);
298                                 *TruePath = NULL;
299                         }
300                         if(!curNode->Type || !curNode->Type->Read) {
301                                 Log_Warning("VFS", "VFS_ParsePath - Read of symlink node %p'%s' is NULL",
302                                         curNode, Path);
303                                 goto _error;
304                         }
305                         
306                         if(iNestedLinks > MAX_NESTED_LINKS) {
307                                 Log_Notice("VFS", "VFS_ParsePath - Nested link limit exceeded");
308                                 goto _error;
309                         }
310                         
311                         // Parse Symlink Path
312                         // - Just update the path variable and restart the function
313                         // > Count nested symlinks and limit to some value (counteracts loops)
314                         {
315                                  int    remlen = strlen(Path) - (ofs + nextSlash);
316                                 if( curNode->Size + remlen > MAX_PATH_LEN ) {
317                                         Log_Warning("VFS", "VFS_ParsePath - Symlinked path too long");
318                                         goto _error;
319                                 }
320                                 curNode->Type->Read( curNode, 0, curNode->Size, path_buffer );
321                                 path_buffer[ curNode->Size ] = '\0';
322                                 LOG("path_buffer = '%s'", path_buffer);
323                                 strcat(path_buffer, Path + ofs+nextSlash);
324                                 
325                                 Path = path_buffer;
326 //                              Log_Debug("VFS", "VFS_ParsePath: Symlink translated to '%s'", Path);
327                                 iNestedLinks ++;
328                         }
329
330                         // EVIL: Goto :)
331                         LOG("Symlink -> '%s', restart", Path);
332                         goto restart_parse;
333                 }
334                 
335                 // Handle Non-Directories
336                 if( !(curNode->Flags & VFS_FFLAG_DIRECTORY) )
337                 {
338                         Log_Warning("VFS", "VFS_ParsePath - Path segment is not a directory");
339                         goto _error;
340                 }
341                 
342                 // Check if path needs extending
343                 if(!TruePath)   continue;
344                 
345                 // Increase buffer space
346                 tmp = realloc( *TruePath, retLength + strlen(pathEle) + 1 + 1 );
347                 // Check if allocation succeeded
348                 if(!tmp) {
349                         Log_Warning("VFS", "VFS_ParsePath - Unable to reallocate true path buffer");
350                         goto _error;
351                 }
352                 *TruePath = tmp;
353                 // Append to path
354                 (*TruePath)[retLength] = '/';
355                 strcpy(*TruePath+retLength+1, pathEle);
356                 
357                 LOG("*TruePath = '%s'", *TruePath);
358                 
359                 // - Extend Path
360                 retLength += nextSlash + 1;
361         }
362
363         // Check final finddir call     
364         if( !curNode->Type || !curNode->Type->FindDir ) {
365                 Log_Warning("VFS", "VFS_ParsePath - FindDir doesn't exist for element of '%s'", Path);
366                 goto _error;
367         }
368         
369         // Get last node
370         LOG("FindDir(%p, '%s')", curNode, &Path[ofs]);
371         tmpNode = curNode->Type->FindDir(curNode, &Path[ofs]);
372         LOG("tmpNode = %p", tmpNode);
373         // Check if file was found
374         if(!tmpNode) {
375                 LOG("Node '%s' not found in dir '%s'", &Path[ofs], Path);
376                 goto _error;
377         }
378         _CloseNode( curNode );
379         
380         if(TruePath)
381         {
382                 // Increase buffer space
383                 tmp = realloc(*TruePath, retLength + strlen(&Path[ofs]) + 1 + 1);
384                 // Check if allocation succeeded
385                 if(!tmp) {
386                         Log_Warning("VFS", "VFS_ParsePath -  Unable to reallocate true path buffer");
387                         goto _error;
388                 }
389                 *TruePath = tmp;
390                 // Append to path
391                 (*TruePath)[retLength] = '/';
392                 strcpy(*TruePath + retLength + 1, &Path[ofs]);
393                 // - Extend Path
394                 //retLength += strlen(tmpNode->Name) + 1;
395         }
396
397         if( MountPoint ) {
398                 *MountPoint = mnt;
399         }
400         
401         LEAVE('p', tmpNode);
402         return tmpNode;
403
404 _error:
405         _CloseNode( curNode );
406         
407         if(TruePath && *TruePath) {
408                 free(*TruePath);
409                 *TruePath = NULL;
410         }
411         LEAVE('n');
412         return NULL;
413 }
414
415 /**
416  * \brief Create and return a handle number for the given node and mode
417  */
418 int VFS_int_CreateHandle( tVFS_Node *Node, tVFS_Mount *Mount, int Mode )
419 {
420          int    i;
421         
422         ENTER("pNode pMount xMode", Node, Mount, Mode);
423
424         i = 0;
425         i |= (Mode & VFS_OPENFLAG_EXEC) ? VFS_PERM_EXECUTE : 0;
426         i |= (Mode & VFS_OPENFLAG_READ) ? VFS_PERM_READ : 0;
427         i |= (Mode & VFS_OPENFLAG_WRITE) ? VFS_PERM_WRITE : 0;
428         
429         LOG("i = 0b%b", i);
430         
431         // Permissions Check
432         if( !VFS_CheckACL(Node, i) ) {
433                 _CloseNode( Node );
434                 Log_Log("VFS", "VFS_int_CreateHandle: Permissions Failed");
435                 errno = EACCES;
436                 LEAVE_RET('i', -1);
437         }
438         
439         i = VFS_AllocHandle( !!(Mode & VFS_OPENFLAG_USER), Node, Mode );
440         if( i < 0 ) {
441                 Log_Notice("VFS", "VFS_int_CreateHandle: Out of handles");
442                 errno = ENFILE;
443                 LEAVE_RET('i', -1);
444         }
445
446         VFS_GetHandle(i)->Mount = Mount;
447
448         LEAVE_RET('x', i);
449 }
450
451 /**
452  * \fn int VFS_Open(const char *Path, Uint Mode)
453  * \brief Open a file
454  */
455 int VFS_Open(const char *Path, Uint Mode)
456 {
457         tVFS_Node       *node;
458         tVFS_Mount      *mnt;
459         char    *absPath;
460         
461         ENTER("sPath xMode", Path, Mode);
462         
463         // Get absolute path
464         absPath = VFS_GetAbsPath(Path);
465         if(absPath == NULL) {
466                 Log_Warning("VFS", "VFS_Open: Path expansion failed '%s'", Path);
467                 LEAVE_RET('i', -1);
468         }
469         LOG("absPath = \"%s\"", absPath);
470         // Parse path and get mount point
471         node = VFS_ParsePath(absPath, NULL, &mnt);
472         // Free generated path
473         free(absPath);
474         
475         if(!node) {
476                 LOG("Cannot find node");
477                 errno = ENOENT;
478                 LEAVE_RET('i', -1);
479         }
480         
481         // Check for symlinks
482         if( !(Mode & VFS_OPENFLAG_NOLINK) && (node->Flags & VFS_FFLAG_SYMLINK) )
483         {
484                 char    tmppath[node->Size+1];
485                 if( node->Size > MAX_PATH_LEN ) {
486                         Log_Warning("VFS", "VFS_Open - Symlink is too long (%i)", node->Size);
487                         LEAVE_RET('i', -1);
488                 }
489                 if( !node->Type || !node->Type->Read ) {
490                         Log_Warning("VFS", "VFS_Open - No read method on symlink");
491                         LEAVE_RET('i', -1);
492                 }
493                 // Read symlink's path
494                 node->Type->Read( node, 0, node->Size, tmppath );
495                 tmppath[ node->Size ] = '\0';
496                 _CloseNode( node );
497                 // Open the target
498                 node = VFS_ParsePath(tmppath, NULL, &mnt);
499                 if(!node) {
500                         LOG("Cannot find symlink target node (%s)", tmppath);
501                         errno = ENOENT;
502                         LEAVE_RET('i', -1);
503                 }
504         }
505
506         LEAVE_RET('x', VFS_int_CreateHandle(node, mnt, Mode));
507 }
508
509
510 /**
511  * \brief Open a file from an open directory
512  */
513 int VFS_OpenChild(int FD, const char *Name, Uint Mode)
514 {
515         tVFS_Handle     *h;
516         tVFS_Node       *node;
517         
518         ENTER("xFD sName xMode", FD, Name, Mode);
519
520         // Get handle
521         h = VFS_GetHandle(FD);
522         if(h == NULL) {
523                 Log_Warning("VFS", "VFS_OpenChild - Invalid file handle 0x%x", FD);
524                 errno = EINVAL;
525                 LEAVE_RET('i', -1);
526         }
527         
528         // Check for directory
529         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
530                 Log_Warning("VFS", "VFS_OpenChild - Passed handle is not a directory");
531                 errno = ENOTDIR;
532                 LEAVE_RET('i', -1);
533         }
534
535         // Sanity check
536         if( !h->Node->Type || !h->Node->Type->FindDir ) {
537                 Log_Error("VFS", "VFS_OpenChild - Node does not have a type/is missing FindDir");
538                 errno = ENOTDIR;
539                 LEAVE_RET('i', -1);
540         }
541         
542         // Find Child
543         node = h->Node->Type->FindDir(h->Node, Name);
544         if(!node) {
545                 errno = ENOENT;
546                 LEAVE_RET('i', -1);
547         }
548
549         LEAVE_RET('x', VFS_int_CreateHandle(node, h->Mount, Mode));
550 }
551
552 int VFS_OpenInode(Uint32 Mount, Uint64 Inode, int Mode)
553 {
554         tVFS_Mount      *mnt;
555         tVFS_Node       *node;
556
557         ENTER("iMount XInode xMode", Mount, Inode, Mode);
558         
559         // Get mount point
560         mnt = VFS_GetMountByIdent(Mount);
561         if( !mnt ) {
562                 LOG("Mount point ident invalid");
563                 errno = ENOENT;
564                 LEAVE_RET('i', -1);
565         }
566         
567         // Does the filesystem support this?
568         if( !mnt->Filesystem->GetNodeFromINode ) {
569                 LOG("Filesystem does not support inode accesses");
570                 errno = ENOENT;
571                 LEAVE_RET('i', -1);
572         }
573
574         // Get node
575         node = mnt->Filesystem->GetNodeFromINode(mnt->RootNode, Inode);
576         if( !node ) {
577                 LOG("Unable to find inode");
578                 errno = ENOENT;
579                 LEAVE_RET('i', -1);
580         }
581         
582         LEAVE_RET('x', VFS_int_CreateHandle(node, mnt, Mode));
583 }
584
585 /**
586  * \fn void VFS_Close(int FD)
587  * \brief Closes an open file handle
588  */
589 void VFS_Close(int FD)
590 {
591         tVFS_Handle     *h;
592         
593         // Get handle
594         h = VFS_GetHandle(FD);
595         if(h == NULL) {
596                 Log_Warning("VFS", "Invalid file handle passed to VFS_Close, 0x%x", FD);
597                 return;
598         }
599         
600         #if VALIDATE_VFS_FUNCTIPONS
601         if(h->Node->Close && !MM_GetPhysAddr(h->Node->Close)) {
602                 Log_Warning("VFS", "Node %p's ->Close method is invalid (%p)",
603                         h->Node, h->Node->Close);
604                 return ;
605         }
606         #endif
607         
608         _CloseNode(h->Node);
609         
610         h->Node = NULL;
611 }
612
613 /**
614  * \brief Change current working directory
615  */
616 int VFS_ChDir(const char *Dest)
617 {
618         char    *buf;
619          int    fd;
620         tVFS_Handle     *h;
621         
622         // Create Absolute
623         buf = VFS_GetAbsPath(Dest);
624         if(buf == NULL) {
625                 Log_Notice("VFS", "VFS_ChDir: Path expansion failed");
626                 return -1;
627         }
628         
629         // Check if path exists
630         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
631         if(fd == -1) {
632                 Log_Notice("VFS", "VFS_ChDir: Path is invalid");
633                 return -1;
634         }
635         
636         // Get node so we can check for directory
637         h = VFS_GetHandle(fd);
638         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
639                 Log("VFS_ChDir: Path is not a directory");
640                 VFS_Close(fd);
641                 return -1;
642         }
643         
644         // Close file
645         VFS_Close(fd);
646         
647         // Free old working directory
648         if( CFGPTR(CFG_VFS_CWD) )
649                 free( CFGPTR(CFG_VFS_CWD) );
650         // Set new
651         CFGPTR(CFG_VFS_CWD) = buf;
652         
653         Log("Updated CWD to '%s'", buf);
654         
655         return 1;
656 }
657
658 /**
659  * \fn int VFS_ChRoot(char *New)
660  * \brief Change current root directory
661  */
662 int VFS_ChRoot(const char *New)
663 {
664         char    *buf;
665          int    fd;
666         tVFS_Handle     *h;
667         
668         if(New[0] == '/' && New[1] == '\0')
669                 return 1;       // What a useless thing to ask!
670         
671         // Create Absolute
672         buf = VFS_GetAbsPath(New);
673         if(buf == NULL) {
674                 LOG("Path expansion failed");
675                 return -1;
676         }
677         
678         // Check if path exists
679         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
680         if(fd == -1) {
681                 LOG("Path is invalid");
682                 return -1;
683         }
684         
685         // Get node so we can check for directory
686         h = VFS_GetHandle(fd);
687         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
688                 LOG("Path is not a directory");
689                 VFS_Close(fd);
690                 return -1;
691         }
692         
693         // Close file
694         VFS_Close(fd);
695         
696         // Free old working directory
697         if( CFGPTR(CFG_VFS_CHROOT) )
698                 free( CFGPTR(CFG_VFS_CHROOT) );
699         // Set new
700         CFGPTR(CFG_VFS_CHROOT) = buf;
701         
702         LOG("Updated Root to '%s'", buf);
703         
704         return 1;
705 }
706
707 // === EXPORTS ===
708 EXPORT(VFS_Open);
709 EXPORT(VFS_Close);

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