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

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