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

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