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

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