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

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