ac47683f0631bf201991aae00531cdc19dd7fba2
[tpg/acess2.git] / Kernel / vfs / open.c
1 /*
2  * AcessMicro 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_KERNEL_FILES        128
14 #define MAX_PATH_SLASHES        256
15
16 // === IMPORTS ===
17 extern tVFS_Node        gVFS_MemRoot;
18 extern tVFS_Mount       *gVFS_RootMount;
19
20 // === GLOBALS ===
21 tVFS_Handle     *gaUserHandles = (void*)MM_PPD_VFS;
22 tVFS_Handle     *gaKernelHandles = (void*)MM_KERNEL_VFS;
23
24 // === CODE ===
25 /**
26  * \fn char *VFS_GetAbsPath(char *Path)
27  * \brief Create an absolute path from a relative one
28  */
29 char *VFS_GetAbsPath(char *Path)
30 {
31         char    *ret;
32          int    pathLen = strlen(Path);
33         char    *pathComps[MAX_PATH_SLASHES];
34         char    *tmpStr;
35         int             iPos = 0;
36         int             iPos2 = 0;
37         char    *chroot = CFGPTR(CFG_VFS_CHROOT);
38          int    chrootLen;
39         char    *cwd = CFGPTR(CFG_VFS_CWD);
40          int    cwdLen;
41         
42         ENTER("sPath", Path);
43         
44         // Memory File
45         if(Path[0] == '$') {
46                 ret = malloc(strlen(Path)+1);
47                 if(!ret) {
48                         Warning("VFS_GetAbsPath - malloc() returned NULL");
49                         return NULL;
50                 }
51                 strcpy(ret, Path);
52                 LEAVE('p', ret);
53                 return ret;
54         }
55         
56         // - Fetch ChRoot
57         if( chroot == NULL ) {
58                 chroot = "";
59                 chrootLen = 0;
60         } else {
61                 chrootLen = strlen(chroot);
62         }
63         
64         // Check if the path is already absolute
65         if(Path[0] == '/') {
66                 ret = malloc(pathLen + 1);
67                 if(!ret) {
68                         Warning("VFS_GetAbsPath - malloc() returned NULL");
69                         return NULL;
70                 }
71                 strcpy(ret, Path);
72         } else {
73                 if(cwd == NULL) {
74                         cwd = "/";
75                         cwdLen = 1;
76                 }
77                 else {
78                         cwdLen = strlen(cwd);
79                 }
80                 // Prepend the current directory
81                 ret = malloc( cwdLen + 1 + pathLen + 1 );
82                 strcpy(ret, cwd);
83                 ret[cwdLen] = '/';
84                 strcpy(&ret[cwdLen+1], Path);
85                 //Log("ret = '%s'\n", ret);
86         }
87         
88         // Parse Path
89         pathComps[iPos++] = tmpStr = ret+1;
90         while(*tmpStr)
91         {
92                 if(*tmpStr++ == '/')
93                 {
94                         pathComps[iPos++] = tmpStr;
95                         if(iPos == MAX_PATH_SLASHES) {
96                                 LOG("Path '%s' has too many elements", Path);
97                                 free(ret);
98                                 LEAVE('n');
99                                 return NULL;
100                         }
101                 }
102         }
103         pathComps[iPos] = NULL;
104         
105         // Cleanup
106         iPos2 = iPos = 0;
107         while(pathComps[iPos])
108         {
109                 tmpStr = pathComps[iPos];
110                 // Always Increment iPos
111                 iPos++;
112                 // ..
113                 if(tmpStr[0] == '.' && tmpStr[1] == '.' && (tmpStr[2] == '/' || tmpStr[2] == '\0') )
114                 {
115                         if(iPos2 != 0)
116                                 iPos2 --;
117                         continue;
118                 }
119                 // .
120                 if(tmpStr[0] == '.' && (tmpStr[1] == '/' || tmpStr[1] == '\0') )
121                 {
122                         continue;
123                 }
124                 // Empty
125                 if(tmpStr[0] == '/' || tmpStr[0] == '\0')
126                 {
127                         continue;
128                 }
129                 
130                 // Set New Position
131                 pathComps[iPos2] = tmpStr;
132                 iPos2++;
133         }
134         pathComps[iPos2] = NULL;
135         
136         // Build New Path
137         iPos2 = 1;      iPos = 0;
138         ret[0] = '/';
139         while(pathComps[iPos])
140         {
141                 tmpStr = pathComps[iPos];
142                 while(*tmpStr && *tmpStr != '/')
143                 {
144                         ret[iPos2++] = *tmpStr;
145                         tmpStr++;
146                 }
147                 ret[iPos2++] = '/';
148                 iPos++;
149         }
150         if(iPos2 > 1)
151                 ret[iPos2-1] = 0;
152         else
153                 ret[iPos2] = 0;
154         
155         
156         // Prepend the chroot
157         tmpStr = malloc(chrootLen + strlen(ret) + 1);
158         strcpy( tmpStr, chroot );
159         strcpy( tmpStr+chrootLen, ret );
160         free(ret);
161         ret = tmpStr;
162         
163         LEAVE('s', ret);
164         //Log("VFS_GetAbsPath: RETURN '%s'", ret);
165         return ret;
166 }
167
168 /**
169  * \fn char *VFS_ParsePath(char *Path, char **TruePath)
170  * \brief Parses a path, resolving sysmlinks and applying permissions
171  */
172 tVFS_Node *VFS_ParsePath(char *Path, char **TruePath)
173 {
174         tVFS_Mount      *mnt;
175         tVFS_Mount      *longestMount = gVFS_RootMount; // Root is first
176          int    cmp, retLength = 0;
177          int    ofs, nextSlash;
178         tVFS_Node       *curNode, *tmpNode;
179         char    *tmp;
180         
181         ENTER("sPath pTruePath", Path, TruePath);
182         
183         // Memory File
184         if(Path[0] == '$') {
185                 if(TruePath) {
186                         *TruePath = malloc(strlen(Path)+1);
187                         strcpy(*TruePath, Path);
188                 }
189                 curNode = gVFS_MemRoot.FindDir(&gVFS_MemRoot, Path);
190                 LEAVE('p', curNode);
191                 return curNode;
192         }
193         // For root we always fast return
194         
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                 LEAVE('p', gVFS_RootMount->RootNode);
201                 return gVFS_RootMount->RootNode;
202         }
203         
204         // Check if there is anything mounted
205         if(!gVFS_Mounts) {
206                 Warning("WTF! There's nothing mounted?");
207                 return NULL;
208         }
209         
210         // Find Mountpoint
211         for(mnt = gVFS_Mounts;
212                 mnt;
213                 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                         LEAVE('p', mnt->RootNode);
231                         return mnt->RootNode;
232                 }
233                 #endif
234                 // Not a match, continue
235                 if(cmp != '/')  continue;
236                 longestMount = mnt;
237         }
238         
239         // Sanity Check
240         /*if(!longestMount) {
241                 Log("VFS_ParsePath - ERROR: No Root Node\n");
242                 return NULL;
243         }*/
244         
245         // Save to shorter variable
246         mnt = longestMount;
247         
248         LOG("mnt = {MountPoint:\"%s\"}", mnt->MountPoint);
249         
250         // Initialise String
251         if(TruePath)
252         {
253                 *TruePath = malloc( mnt->MountPointLen+1 );
254                 strcpy(*TruePath, mnt->MountPoint);
255                 retLength = mnt->MountPointLen;
256         }
257         
258         curNode = mnt->RootNode;
259         curNode->ReferenceCount ++;     
260         // Parse Path
261         ofs = mnt->MountPointLen+1;
262         for(; (nextSlash = strpos(&Path[ofs], '/')) != -1; Path[nextSlash]='/',ofs = nextSlash + 1)
263         {
264                 nextSlash += ofs;
265                 Path[nextSlash] = '\0';
266         
267                 // Check for empty string
268                 if( Path[ofs] == '\0' ) continue;
269         
270                 // Check permissions on root of filesystem
271                 if( !VFS_CheckACL(curNode, VFS_PERM_EXECUTE) ) {
272                         if(curNode->Close)      curNode->Close( curNode );
273                         if(TruePath) {
274                                 free(*TruePath);
275                                 *TruePath = NULL;
276                         }
277                         //Log("Permissions fail on '%s'", Path);
278                         LEAVE('n');
279                         return NULL;
280                 }
281                 
282                 // Check if the node has a FindDir method
283                 if( !curNode->FindDir )
284                 {
285                         if(curNode->Close)      curNode->Close(curNode);
286                         if(TruePath) {
287                                 free(*TruePath);
288                                 *TruePath = NULL;
289                         }
290                         Path[nextSlash] = '/';
291                         //Log("FindDir fail on '%s'", Path);
292                         LEAVE('n');
293                         return NULL;
294                 }
295                 LOG("FindDir(%p, '%s')", curNode, &Path[ofs]);
296                 // Get Child Node
297                 tmpNode = curNode->FindDir(curNode, &Path[ofs]);
298                 LOG("tmpNode = %p", tmpNode);
299                 if(curNode->Close)      curNode->Close(curNode);
300                 curNode = tmpNode;
301                 
302                 // Error Check
303                 if(!curNode) {
304                         LOG("Node '%s' not found in dir '%s'", &Path[ofs], Path);
305                         if(TruePath) {
306                                 free(*TruePath);
307                                 *TruePath = NULL;
308                         }
309                         //Log("Child fail on '%s' ('%s)", Path, &Path[ofs]);
310                         Path[nextSlash] = '/';
311                         LEAVE('n');
312                         return NULL;
313                 }
314                 
315                 // Handle Symbolic Links
316                 if(curNode->Flags & VFS_FFLAG_SYMLINK) {
317                         if(TruePath) {
318                                 free(*TruePath);
319                                 *TruePath = NULL;
320                         }
321                         tmp = malloc( curNode->Size + 1 );
322                         if(!curNode->Read) {
323                                 Warning("VFS_ParsePath - Read of node %p is NULL (%s)",
324                                         curNode, Path);
325                                 if(curNode->Close)      curNode->Close(curNode);
326                                 LEAVE('n');
327                                 return NULL;
328                         }
329                         curNode->Read( curNode, 0, curNode->Size, tmp );
330                         tmp[ curNode->Size ] = '\0';
331                         
332                         // Parse Symlink Path
333                         curNode = VFS_ParsePath(tmp, TruePath);
334                         
335                         // Error Check
336                         if(!curNode) {
337                                 Log("Symlink fail '%s'", tmp);
338                                 free(tmp);      // Free temp string
339                                 LEAVE('n');
340                                 return NULL;
341                         }
342                         
343                         // Set Path Variable
344                         if(TruePath) {
345                                 *TruePath = tmp;
346                                 retLength = strlen(tmp);
347                         } else {
348                                 free(tmp);      // Free temp string
349                         }
350                         
351                         continue;
352                 }
353                 
354                 // Handle Non-Directories
355                 if( !(curNode->Flags & VFS_FFLAG_DIRECTORY) )
356                 {
357                         Warning("VFS_ParsePath - File in directory context");
358                         if(TruePath)    free(*TruePath);
359                         LEAVE('n');
360                         return NULL;
361                 }
362                 
363                 // Check if path needs extending
364                 if(!TruePath)   continue;
365                 
366                 // Increase buffer space
367                 tmp = realloc( *TruePath, retLength + strlen(&Path[ofs]) + 1 + 1 );
368                 // Check if allocation succeeded
369                 if(!tmp) {
370                         Warning("VFS_ParsePath -  Unable to reallocate true path buffer");
371                         free(*TruePath);
372                         if(curNode->Close)      curNode->Close(curNode);
373                         LEAVE('n');
374                         return NULL;
375                 }
376                 *TruePath = tmp;
377                 // Append to path
378                 (*TruePath)[retLength] = '/';
379                 strcpy(*TruePath+retLength+1, &Path[ofs]);
380                 // - Extend Path
381                 retLength += strlen(&Path[ofs])+1;
382         }
383         
384         // Get last node
385         LOG("VFS_ParsePath: FindDir(%p, '%s')", curNode, &Path[ofs]);
386         tmpNode = curNode->FindDir(curNode, &Path[ofs]);
387         LOG("tmpNode = %p", tmpNode);
388         if(curNode->Close)      curNode->Close(curNode);
389         // Check if file was found
390         if(!tmpNode) {
391                 LOG("Node '%s' not found in dir '%s'", &Path[ofs], Path);
392                 //Log("Child fail '%s' ('%s')", Path, &Path[ofs]);
393                 if(TruePath)    free(*TruePath);
394                 if(curNode->Close)      curNode->Close(curNode);
395                 LEAVE('n');
396                 return NULL;
397         }
398         
399         if(TruePath)
400         {
401                 // Increase buffer space
402                 tmp = realloc(*TruePath, retLength + strlen(&Path[ofs]) + 1 + 1);
403                 // Check if allocation succeeded
404                 if(!tmp) {
405                         Warning("VFS_ParsePath -  Unable to reallocate true path buffer");
406                         free(*TruePath);
407                         if(tmpNode->Close)      tmpNode->Close(curNode);
408                         LEAVE('n');
409                         return NULL;
410                 }
411                 *TruePath = tmp;
412                 // Append to path
413                 (*TruePath)[retLength] = '/';
414                 strcpy(*TruePath + retLength + 1, &Path[ofs]);
415                 // - Extend Path
416                 //retLength += strlen(tmpNode->Name) + 1;
417         }
418         
419         LEAVE('p', tmpNode);
420         return tmpNode;
421 }
422
423 /**
424  * \fn int VFS_Open(char *Path, Uint Mode)
425  * \brief Open a file
426  */
427 int VFS_Open(char *Path, Uint Mode)
428 {
429         tVFS_Node       *node;
430         char    *absPath;
431          int    i;
432         
433         ENTER("sPath xMode", Path, Mode);
434         
435         // Get absolute path
436         absPath = VFS_GetAbsPath(Path);
437         LOG("absPath = \"%s\"", absPath);
438         // Parse path and get mount point
439         node = VFS_ParsePath(absPath, NULL);
440         // Free generated path
441         free(absPath);
442         
443         if(!node) {
444                 LOG("Cannot find node");
445                 LEAVE('i', -1);
446                 return -1;
447         }
448         
449         // Check for symlinks
450         if( !(Mode & VFS_OPENFLAG_NOLINK) && (node->Flags & VFS_FFLAG_SYMLINK) )
451         {
452                 if( !node->Read ) {
453                         Warning("No read method on symlink");
454                         LEAVE('i', -1);
455                         return -1;
456                 }
457                 absPath = malloc(node->Size+1); // Allocate Buffer
458                 node->Read( node, 0, node->Size, absPath );     // Read Path
459                 
460                 absPath[ node->Size ] = '\0';   // End String
461                 if(node->Close) node->Close( node );    // Close old node
462                 node = VFS_ParsePath(absPath, NULL);    // Get new node
463                 free( absPath );        // Free allocated path
464         }
465         
466         if(!node) {
467                 LOG("Cannot find node");
468                 LEAVE('i', -1);
469                 return -1;
470         }
471         
472         i = 0;
473         i |= (Mode & VFS_OPENFLAG_EXEC) ? VFS_PERM_EXECUTE : 0;
474         i |= (Mode & VFS_OPENFLAG_READ) ? VFS_PERM_READ : 0;
475         i |= (Mode & VFS_OPENFLAG_WRITE) ? VFS_PERM_WRITE : 0;
476         
477         LOG("i = 0b%b", i);
478         
479         // Permissions Check
480         if( !VFS_CheckACL(node, i) ) {
481                 if(node->Close) node->Close( node );
482                 Log("VFS_Open: Permissions Failed");
483                 LEAVE('i', -1);
484                 return -1;
485         }
486         
487         // Check for a user open
488         if(Mode & VFS_OPENFLAG_USER)
489         {
490                 // Allocate Buffer
491                 if( MM_GetPhysAddr( (Uint)gaUserHandles ) == 0 )
492                 {
493                         Uint    addr, size;
494                         size = CFGINT(CFG_VFS_MAXFILES) * sizeof(tVFS_Handle);
495                         for(addr = 0; addr < size; addr += 0x1000)
496                                 MM_Allocate( (Uint)gaUserHandles + addr );
497                         memset( gaUserHandles, 0, size );
498                 }
499                 // Get a handle
500                 for(i=0;i<CFGINT(CFG_VFS_MAXFILES);i++)
501                 {
502                         if(gaUserHandles[i].Node)       continue;
503                         gaUserHandles[i].Node = node;
504                         gaUserHandles[i].Position = 0;
505                         gaUserHandles[i].Mode = Mode;
506                         LEAVE('i', i);
507                         return i;
508                 }
509         }
510         else
511         {
512                 // Allocate space if not already
513                 if( MM_GetPhysAddr( (Uint)gaKernelHandles ) == 0 )
514                 {
515                         Uint    addr, size;
516                         size = MAX_KERNEL_FILES * sizeof(tVFS_Handle);
517                         for(addr = 0; addr < size; addr += 0x1000)
518                                 MM_Allocate( (Uint)gaKernelHandles + addr );
519                         memset( gaKernelHandles, 0, size );
520                 }
521                 // Get a handle
522                 for(i=0;i<MAX_KERNEL_FILES;i++)
523                 {
524                         if(gaKernelHandles[i].Node)     continue;
525                         gaKernelHandles[i].Node = node;
526                         gaKernelHandles[i].Position = 0;
527                         gaKernelHandles[i].Mode = Mode;
528                         LEAVE('x', i|VFS_KERNEL_FLAG);
529                         return i|VFS_KERNEL_FLAG;
530                 }
531         }
532         
533         Log("VFS_Open: Out of handles");
534         LEAVE('i', -1);
535         return -1;
536 }
537
538 /**
539  * \fn void VFS_Close(int FD)
540  * \brief Closes an open file handle
541  */
542 void VFS_Close(int FD)
543 {
544         tVFS_Handle     *h;
545         
546         // Get handle
547         h = VFS_GetHandle(FD);
548         if(h == NULL) {
549                 Warning("Invalid file handle passed to VFS_Close, 0x%x\n", FD);
550                 return;
551         }
552         
553         if(h->Node->Close)
554                 h->Node->Close( h->Node );
555         
556         h->Node = NULL;
557 }
558
559 /**
560  * \brief Change current working directory
561  */
562 int VFS_ChDir(char *Dest)
563 {
564         char    *buf;
565          int    fd;
566         tVFS_Handle     *h;
567         
568         // Create Absolute
569         buf = VFS_GetAbsPath(Dest);
570         if(buf == NULL) {
571                 Log("VFS_ChDir: Path expansion failed");
572                 return -1;
573         }
574         
575         // Check if path exists
576         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
577         if(fd == -1) {
578                 Log("VFS_ChDir: Path is invalid");
579                 return -1;
580         }
581         
582         // Get node so we can check for directory
583         h = VFS_GetHandle(fd);
584         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
585                 Log("VFS_ChDir: Path is not a directory");
586                 VFS_Close(fd);
587                 return -1;
588         }
589         
590         // Close file
591         VFS_Close(fd);
592         
593         // Free old working directory
594         if( CFGPTR(CFG_VFS_CWD) )
595                 free( CFGPTR(CFG_VFS_CWD) );
596         // Set new
597         CFGPTR(CFG_VFS_CWD) = buf;
598         
599         Log("Updated CWD to '%s'", buf);
600         
601         return 1;
602 }
603
604 /**
605  * \fn int VFS_ChRoot(char *New)
606  * \brief Change current root directory
607  */
608 int VFS_ChRoot(char *New)
609 {
610         char    *buf;
611          int    fd;
612         tVFS_Handle     *h;
613         
614         if(New[0] == '/' && New[1] == '\0')
615                 return 1;       // What a useless thing to ask!
616         
617         // Create Absolute
618         buf = VFS_GetAbsPath(New);
619         if(buf == NULL) {
620                 LOG("Path expansion failed");
621                 return -1;
622         }
623         
624         // Check if path exists
625         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
626         if(fd == -1) {
627                 LOG("Path is invalid");
628                 return -1;
629         }
630         
631         // Get node so we can check for directory
632         h = VFS_GetHandle(fd);
633         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
634                 LOG("Path is not a directory");
635                 VFS_Close(fd);
636                 return -1;
637         }
638         
639         // Close file
640         VFS_Close(fd);
641         
642         // Free old working directory
643         if( CFGPTR(CFG_VFS_CHROOT) )
644                 free( CFGPTR(CFG_VFS_CHROOT) );
645         // Set new
646         CFGPTR(CFG_VFS_CHROOT) = buf;
647         
648         LOG("Updated Root to '%s'", buf);
649         
650         return 1;
651 }
652
653 /**
654  * \fn tVFS_Handle *VFS_GetHandle(int FD)
655  * \brief Gets a pointer to the handle information structure
656  */
657 tVFS_Handle *VFS_GetHandle(int FD)
658 {
659         tVFS_Handle     *h;
660         
661         if(FD < 0)      return NULL;
662         
663         if(FD & VFS_KERNEL_FLAG) {
664                 FD &= (VFS_KERNEL_FLAG - 1);
665                 if(FD >= MAX_KERNEL_FILES)      return NULL;
666                 h = &gaKernelHandles[ FD ];
667         } else {
668                 if(FD >= CFGINT(CFG_VFS_MAXFILES))      return NULL;
669                 h = &gaUserHandles[ FD ];
670         }
671         
672         if(h->Node == NULL)     return NULL;
673         return h;
674 }
675
676 // === EXPORTS ===
677 EXPORT(VFS_Open);
678 EXPORT(VFS_Close);

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