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

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