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

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