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

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