Ok, this was embarrassing... Added core include file that was renamed
[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                         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                         if(curNode->Close)      curNode->Close(curNode);
285                         if(TruePath) {
286                                 free(*TruePath);
287                                 *TruePath = NULL;
288                         }
289                         Path[nextSlash] = '/';
290                         //Log("FindDir fail on '%s'", Path);
291                         LEAVE('n');
292                         return NULL;
293                 }
294                 LOG("FindDir(%p, '%s')", curNode, &Path[ofs]);
295                 // Get Child Node
296                 tmpNode = curNode->FindDir(curNode, &Path[ofs]);
297                 LOG("tmpNode = %p", tmpNode);
298                 if(curNode->Close)
299                         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                         curNode->Read( curNode, 0, curNode->Size, tmp );
323                         tmp[ curNode->Size ] = '\0';
324                         
325                         // Parse Symlink Path
326                         curNode = VFS_ParsePath(tmp, TruePath);
327                         
328                         // Error Check
329                         if(!curNode) {
330                                 Log("Symlink fail '%s'", tmp);
331                                 free(tmp);      // Free temp string
332                                 LEAVE('n');
333                                 return NULL;
334                         }
335                         
336                         // Set Path Variable
337                         if(TruePath) {
338                                 *TruePath = tmp;
339                                 retLength = strlen(tmp);
340                         } else {
341                                 free(tmp);      // Free temp string
342                         }
343                         
344                         continue;
345                 }
346                 
347                 // Handle Non-Directories
348                 if( !(curNode->Flags & VFS_FFLAG_DIRECTORY) )
349                 {
350                         Warning("VFS_ParsePath - File in directory context");
351                         if(TruePath)    free(*TruePath);
352                         LEAVE('n');
353                         return NULL;
354                 }
355                 
356                 // Check if path needs extending
357                 if(!TruePath)   continue;
358                 
359                 // Increase buffer space
360                 tmp = realloc( *TruePath, retLength + strlen(&Path[ofs]) + 1 + 1 );
361                 // Check if allocation succeeded
362                 if(!tmp) {
363                         Warning("VFS_ParsePath -  Unable to reallocate true path buffer");
364                         free(*TruePath);
365                         if(curNode->Close)      curNode->Close(curNode);
366                         LEAVE('n');
367                         return NULL;
368                 }
369                 *TruePath = tmp;
370                 // Append to path
371                 (*TruePath)[retLength] = '/';
372                 strcpy(*TruePath+retLength+1, &Path[ofs]);
373                 // - Extend Path
374                 retLength += strlen(&Path[ofs])+1;
375         }
376         
377         // Get last node
378         LOG("VFS_ParsePath: FindDir(%p, '%s')", curNode, &Path[ofs]);
379         tmpNode = curNode->FindDir(curNode, &Path[ofs]);
380         LOG("tmpNode = %p", tmpNode);
381         if(curNode->Close)      curNode->Close(curNode);
382         // Check if file was found
383         if(!tmpNode) {
384                 LOG("Node '%s' not found in dir '%s'", &Path[ofs], Path);
385                 //Log("Child fail '%s' ('%s')", Path, &Path[ofs]);
386                 if(TruePath)    free(*TruePath);
387                 if(curNode->Close)      curNode->Close(curNode);
388                 LEAVE('n');
389                 return NULL;
390         }
391         
392         if(TruePath)
393         {
394                 // Increase buffer space
395                 tmp = realloc(*TruePath, retLength + strlen(&Path[ofs]) + 1 + 1);
396                 // Check if allocation succeeded
397                 if(!tmp) {
398                         Warning("VFS_ParsePath -  Unable to reallocate true path buffer");
399                         free(*TruePath);
400                         if(tmpNode->Close)      tmpNode->Close(curNode);
401                         LEAVE('n');
402                         return NULL;
403                 }
404                 *TruePath = tmp;
405                 // Append to path
406                 (*TruePath)[retLength] = '/';
407                 strcpy(*TruePath + retLength + 1, &Path[ofs]);
408                 // - Extend Path
409                 //retLength += strlen(tmpNode->Name) + 1;
410         }
411         
412         LEAVE('p', tmpNode);
413         return tmpNode;
414 }
415
416 /**
417  * \fn int VFS_Open(char *Path, Uint Mode)
418  * \brief Open a file
419  */
420 int VFS_Open(char *Path, Uint Mode)
421 {
422         tVFS_Node       *node;
423         char    *absPath;
424          int    i;
425         
426         ENTER("sPath xMode", Path, Mode);
427         
428         // Get absolute path
429         absPath = VFS_GetAbsPath(Path);
430         LOG("absPath = \"%s\"", absPath);
431         // Parse path and get mount point
432         node = VFS_ParsePath(absPath, NULL);
433         // Free generated path
434         free(absPath);
435         
436         if(!node) {
437                 LOG("Cannot find node");
438                 LEAVE('i', -1);
439                 return -1;
440         }
441         
442         // Check for symlinks
443         if( !(Mode & VFS_OPENFLAG_NOLINK) && (node->Flags & VFS_FFLAG_SYMLINK) )
444         {
445                 if( !node->Read ) {
446                         Warning("No read method on symlink");
447                         LEAVE('i', -1);
448                         return -1;
449                 }
450                 absPath = malloc(node->Size+1); // Allocate Buffer
451                 node->Read( node, 0, node->Size, absPath );     // Read Path
452                 
453                 absPath[ node->Size ] = '\0';   // End String
454                 if(node->Close) node->Close( node );    // Close old node
455                 node = VFS_ParsePath(absPath, NULL);    // Get new node
456                 free( absPath );        // Free allocated path
457         }
458         
459         if(!node) {
460                 LOG("Cannot find node");
461                 LEAVE('i', -1);
462                 return -1;
463         }
464         
465         i = 0;
466         i |= (Mode & VFS_OPENFLAG_EXEC) ? VFS_PERM_EXECUTE : 0;
467         i |= (Mode & VFS_OPENFLAG_READ) ? VFS_PERM_READ : 0;
468         i |= (Mode & VFS_OPENFLAG_WRITE) ? VFS_PERM_WRITE : 0;
469         
470         LOG("i = 0b%b", i);
471         
472         // Permissions Check
473         if( !VFS_CheckACL(node, i) ) {
474                 node->Close( node );
475                 Log("VFS_Open: Permissions Failed");
476                 LEAVE('i', -1);
477                 return -1;
478         }
479         
480         // Check for a user open
481         if(Mode & VFS_OPENFLAG_USER)
482         {
483                 // Allocate Buffer
484                 if( MM_GetPhysAddr( (Uint)gaUserHandles ) == 0 )
485                 {
486                         Uint    addr, size;
487                         size = CFGINT(CFG_VFS_MAXFILES) * sizeof(tVFS_Handle);
488                         for(addr = 0; addr < size; addr += 0x1000)
489                                 MM_Allocate( (Uint)gaUserHandles + addr );
490                         memset( gaUserHandles, 0, size );
491                 }
492                 // Get a handle
493                 for(i=0;i<CFGINT(CFG_VFS_MAXFILES);i++)
494                 {
495                         if(gaUserHandles[i].Node)       continue;
496                         gaUserHandles[i].Node = node;
497                         gaUserHandles[i].Position = 0;
498                         gaUserHandles[i].Mode = Mode;
499                         LEAVE('i', i);
500                         return i;
501                 }
502         }
503         else
504         {
505                 // Allocate space if not already
506                 if( MM_GetPhysAddr( (Uint)gaKernelHandles ) == 0 )
507                 {
508                         Uint    addr, size;
509                         size = MAX_KERNEL_FILES * sizeof(tVFS_Handle);
510                         for(addr = 0; addr < size; addr += 0x1000)
511                                 MM_Allocate( (Uint)gaKernelHandles + addr );
512                         memset( gaKernelHandles, 0, size );
513                 }
514                 // Get a handle
515                 for(i=0;i<MAX_KERNEL_FILES;i++)
516                 {
517                         if(gaKernelHandles[i].Node)     continue;
518                         gaKernelHandles[i].Node = node;
519                         gaKernelHandles[i].Position = 0;
520                         gaKernelHandles[i].Mode = Mode;
521                         LEAVE('x', i|VFS_KERNEL_FLAG);
522                         return i|VFS_KERNEL_FLAG;
523                 }
524         }
525         
526         Log("VFS_Open: Out of handles");
527         LEAVE('i', -1);
528         return -1;
529 }
530
531 /**
532  * \fn void VFS_Close(int FD)
533  * \brief Closes an open file handle
534  */
535 void VFS_Close(int FD)
536 {
537         tVFS_Handle     *h;
538         
539         // Get handle
540         h = VFS_GetHandle(FD);
541         if(h == NULL) {
542                 Warning("Invalid file handle passed to VFS_Close, 0x%x\n", FD);
543                 return;
544         }
545         
546         if(h->Node->Close)
547                 h->Node->Close( h->Node );
548         
549         h->Node = NULL;
550 }
551
552 /**
553  * \brief Change current working directory
554  */
555 int VFS_ChDir(char *Dest)
556 {
557         char    *buf;
558          int    fd;
559         tVFS_Handle     *h;
560         
561         // Create Absolute
562         buf = VFS_GetAbsPath(Dest);
563         if(buf == NULL) {
564                 Log("VFS_ChDir: Path expansion failed");
565                 return -1;
566         }
567         
568         // Check if path exists
569         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
570         if(fd == -1) {
571                 Log("VFS_ChDir: Path is invalid");
572                 return -1;
573         }
574         
575         // Get node so we can check for directory
576         h = VFS_GetHandle(fd);
577         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
578                 Log("VFS_ChDir: Path is not a directory");
579                 VFS_Close(fd);
580                 return -1;
581         }
582         
583         // Close file
584         VFS_Close(fd);
585         
586         // Free old working directory
587         if( CFGPTR(CFG_VFS_CWD) )
588                 free( CFGPTR(CFG_VFS_CWD) );
589         // Set new
590         CFGPTR(CFG_VFS_CWD) = buf;
591         
592         Log("Updated CWD to '%s'", buf);
593         
594         return 1;
595 }
596
597 /**
598  * \fn int VFS_ChRoot(char *New)
599  * \brief Change current root directory
600  */
601 int VFS_ChRoot(char *New)
602 {
603         char    *buf;
604          int    fd;
605         tVFS_Handle     *h;
606         
607         if(New[0] == '/' && New[1] == '\0')
608                 return 1;       // What a useless thing to ask!
609         
610         // Create Absolute
611         buf = VFS_GetAbsPath(New);
612         if(buf == NULL) {
613                 LOG("Path expansion failed");
614                 return -1;
615         }
616         
617         // Check if path exists
618         fd = VFS_Open(buf, VFS_OPENFLAG_EXEC);
619         if(fd == -1) {
620                 LOG("Path is invalid");
621                 return -1;
622         }
623         
624         // Get node so we can check for directory
625         h = VFS_GetHandle(fd);
626         if( !(h->Node->Flags & VFS_FFLAG_DIRECTORY) ) {
627                 LOG("Path is not a directory");
628                 VFS_Close(fd);
629                 return -1;
630         }
631         
632         // Close file
633         VFS_Close(fd);
634         
635         // Free old working directory
636         if( CFGPTR(CFG_VFS_CHROOT) )
637                 free( CFGPTR(CFG_VFS_CHROOT) );
638         // Set new
639         CFGPTR(CFG_VFS_CHROOT) = buf;
640         
641         LOG("Updated Root to '%s'", buf);
642         
643         return 1;
644 }
645
646 /**
647  * \fn tVFS_Handle *VFS_GetHandle(int FD)
648  * \brief Gets a pointer to the handle information structure
649  */
650 tVFS_Handle *VFS_GetHandle(int FD)
651 {
652         tVFS_Handle     *h;
653         
654         if(FD < 0)      return NULL;
655         
656         if(FD & VFS_KERNEL_FLAG) {
657                 FD &= (VFS_KERNEL_FLAG - 1);
658                 if(FD >= MAX_KERNEL_FILES)      return NULL;
659                 h = &gaKernelHandles[ FD ];
660         } else {
661                 if(FD >= CFGINT(CFG_VFS_MAXFILES))      return NULL;
662                 h = &gaUserHandles[ FD ];
663         }
664         
665         if(h->Node == NULL)     return NULL;
666         return h;
667 }
668
669 // === EXPORTS ===
670 EXPORT(VFS_Open);
671 EXPORT(VFS_Close);

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