Map pathnames containing ".." component to prefix path.
authorRalph Ronnquist <rrq@rrq.au>
Thu, 28 Aug 2025 06:44:31 +0000 (16:44 +1000)
committerRalph Ronnquist <rrq@rrq.au>
Thu, 28 Aug 2025 06:44:31 +0000 (16:44 +1000)
libpathmap-0.c

index f7dea491de8c065aa82f0117e05624645f26decc..e1d9a94a0c82e9c95e25246bee4220317db9c705 100644 (file)
@@ -134,25 +134,38 @@ static void load_prefixes() {
     prefix.root_index = binsearch( prefix.root );
 }
 
+static char *add_prefix(const char *path) {
+    char *p = (char*)malloc( strlen( path ) + prefix.root_length + 1 );
+    memcpy( p, prefix.root, prefix.root_length );
+    strcpy( p + prefix.root_length, path );
+    //fprintf( stderr, "libpathmap: [%s] %s\n", prefix.root, path );
+    return p;
+}
+
 // Utility function to lookup a matching prefix for the given path. If
 // none is found, then 0 is returned. Otherwise memory is allocated
 // (malloc) for a new string that consists of the root path followed
 // by the given path. Note that prefixing only applies to absolute
 // paths.
 static char *maybe_add_prefix(const char *path) {
-    if ( prefix.count > 0 && *path == '/' ) {
-       //fprintf( stderr, "libpathmap: check %s\n", path );
+    if ( prefix.count == 0 ) {
+       return 0;
+    }
+    //fprintf( stderr, "libpathmap: check %s\n", path );
+    int n = strlen( path );
+    // Return only prefix for any pathname that includes a ".."
+    // component.
+    if ( ( strcmp( path, ".." ) == 0 ) ||
+        ( strstr( path, "/../" ) != 0 ) ||
+        ( n > 2 && ( ( strncmp( path, "../", 3 ) == 0 ) ||
+                     ( strcmp( path + n -3, "/.." ) == 0 ) ) ) ) {
+        return add_prefix( "" );
+    }
+    // Add prefix to absolut paths, except where it should not
+    if ( *path == '/' ) {
        int x = prefixsearch( path );
        //fprintf( stderr, "libpathmap: %d %s\n", x, path );
-       if ( x < 0 ) {
-           char *p = (char*)malloc( strlen( path ) + prefix.root_length + 1 );
-           memcpy( p, prefix.root, prefix.root_length );
-           strcpy( p + prefix.root_length, path );
-           //fprintf( stderr, "libpathmap: [%s] %s\n", prefix.root, path );
-           return p;
-       } else {
-           //fprintf( stderr, "libpathmap: [] %s\n", path );
-       }
+       return ( x < 0 )? add_prefix( path ) : 0;
     }
     return 0;
 }