TweetFollow Us on Twitter

ckpath

Volume Number: 18 (2002)
Issue Number: 9
Column Tag: Mac OS X

ckpath

Analyze a file's permissions, using Perl

by Rich Morin

In order to know who can do what to a file, you have to understand the permissions on the file itself and on each directory leading to it. Locking down write permission on a file, for instance, keeps miscreants from writing into the file, but it doesn't keep them from removing and replacing it. To prevent that, you have to set the right permissions on the enclosing directory.

Or, let's say that your file path contains some symbolic links. In order to reach the file, a program must traverse the path up to the symlink, then backtrack and traverse the path up to the symlink's target. If the path is /A/B/C and B is a symlink to /X/Y, the program will need access to /, /A, /A/B, / (again), /X, /X/Y, and /X/Y/C.

The BSD command "ls -dl" will show the permissions on a specified file or directory, but typing in a long sequence of commands is both tedious and error-prone. Consider:

% ls -ld /
drwxrwxr-t  49 root  admin  1622 Jul 29 11:11 /
% ls -ld /Applications
drwxrwxr-x  36 root  admin  1180 Jul 28 10:34 /Applications
...

Fortunately, it's quite possible to automate this procedure. My ckpath script examines each element in the requested file path, back-tracking as necessary to handle symbolic links. It handles "white space" in file names (uncommon in BSD, but common in Mac OS X) and fiddles a bit with the output format.. Here's some sample output:

% ckpath "/Applications/AppleScript/Example Scripts"
"/Applications/AppleScript/Example Scripts"
1775 drwxrwxr-t  49 root  admin  2002.07.29 /
0775 drwxrwxr-x  36 root  admin  2002.07.28 Applications
0775 drwxrwxr-x   5 root  admin  2002.02.14 AppleScript
0775 lrwxrwxr-x   1 root  admin  2002.02.14
    "Example Scripts" -> /Library/Scripts
/Library/Scripts
1775 drwxrwxr-t  49 root  admin  2002.07.29 /
0775 drwxrwxr-x  28 root  admin  2002.07.16 Library
0775 drwxrwxr-x  12 root  admin  2001.09.14 Scripts

The first two output fields (e.g., 0775 and drwxrwxr-x) contain the octal and symbolic representations of the node's permissions. For a complete explanation of BSD permission codes, see the ls(1) manual page. Briefly, however, the story is that each entity in the file system has a type (e.g., directory, file, symlink) and three sets of permissions bits (for user, group, and other). Some ancillary bits control special features such as set[ug]id execution.

A string such as drwxrwxr-x indicates that this is a directory and that anyone can read and execute (pass through) it. Any "other" user (not the owner, nor in the directory's group) cannot write (i.e., create, remove, or rename files) in the directory.

The following three fields (links, owner, and group) are taken directly from the ls output. The date has been normalized into YY.MM.DD format, improving line-to-line consistency and easing date calculations. The remainder of the line contains the node name, quoted if it contains spaces. As in ls output, symlinks are listed with their targets.

Code Walkthrough

This walkthrough is neither an attempt to teach Perl in one sitting, nor a truly detailed explanation of the intricacies of ckpath. Instead, it touches on both language and design issues, trying to hit some of the high points of each. The references listed in this month's "Section 7" column can help you with the Perl issues; I hope to explain the program's general flow in the following text.

The first line of ckpath allows for the possibility that we may have installed a copy of the Perl interpreter in a non-standard location. /usr/bin/env walks down our search path, finding the same copy of Perl that the shell would.

If ckpath is run with no argument, it examines the current working directory. Otherwise, it uses the argument as a path name, prepending the current working directory unless the path begins with a slash. This is fairly traditional behavior for a BSD command.

Some advocates of structured programming entirely refuse to use gotos. I avoid them in general, but use them (as in this case) when the alternative would be even uglier. Interested readers are invited to attempt a goto-free formulation.

After tidying up the incoming path name, we print it out for the user (in quotes, if it contains any white space). We then create a "todo" list, containing the full path names for each node in the input path name. This is the putative task list, but it may be abandoned if we encounter a symlink or an error.

After formatting the node name and determining that the node actually exists, we examine it in two ways. First, we run "ls -ald", discarding everything but the symbolic permission information. We then use lstat to retrieve the rest of the information we want.

This isn't particularly elegant or efficient, but it's a lot easier than generating the symbolic permission codes ourselves or, worse, trying to parse the output of ls. Interested readers, again, are welcome to try coding alternative approaches.

Using getpwuid and getgrgid, we try for symbolic versions of the user and group names, falling back to numeric forms if need be. localtime gives us a printable list of time values, from which we grab the year, month, and day.

If the node is a symlink, we add the target to the output line, fudge the path name to reflect the symlink's target, and jump back to REDO. Otherwise, we simply print a closing newline and go back for the next node.

Observations

Perl is particularly facile at handling this sort of problem. It has good string-handling capabilities, powerful and convenient data structures, and access to assorted system calls and library functions. I can't see doing this program as a shell script; the shell isn't powerful enough. Nor would I want to try writing it in C (no string-handling, regular expressions, etc.).

The strict and warnings pragmas are a bit like using lint(1) on C code. They tell Perl to look for all sorts of incipient problems, such as variables which are only used once. I've started using these more frequently than I once did, partly as a consequence of writing larger scripts where the scope of variables can become a real issue. The extra typing (and, occasionally, redesign) that the pragmas require seems to be more than compensated by the problems they uncover.

CKPATH SOURCE CODE
#!/usr/bin/env perl
#
# Usage: ckpath [file node]             # defaults to .
#
# Rationale:
#
# Let's say that you have a file which is having permissions
# problems.  In order to find out ALL the relevant
# permissions, you will have to run "ls -ld" on each element
# of the path, then back-track for each symbolic link you
# encounter.  Not fun.  This script automates the process,
# allowing you to see the entire path's permissions at once.
# It also tweaks the output format a bit (e.g., printing the
# octal modes and making the date format consistent).
#
# Written by Rich Morin, CFCL, 2002.06
use strict;
use warnings;
{
  my(@stat, @todo,
     $cwd, $grp, $mday, $mode, $mon, $name, $node,
     $save, $sm, $tgt, $tmp, $todo, $usr, $year
  );
  $cwd = `pwd`; chomp($cwd);
  if ($#ARGV == -1) {             # Get path, if any.
    $todo =  $cwd;
  } else {
    $todo = $ARGV[0];
    $todo = "$cwd/$todo" if ($todo !~ m|^/|);
  }
REDO:
  $todo =~ s|/[^/]+/\.\./|/|g;    # "/foo/../" -> "/"
  $todo =~ s|/\./|/|g;            # "/./"      -> "/"
  $todo =~ s|//+|/|g;             # "//"       -> "/"
  $todo =~ s|/$||;                # ".../foo/" -> ".../foo"
  $save = $tmp = $todo;           # Print current task.
  $tmp = "\"$tmp\"" if ($tmp =~ m|\s|);
  print "\n$tmp\n";
  undef @todo;                    # Get list of nodes.
  while ($todo ne '') {
    push(@todo, $todo);
    $todo =~ s|/[^/]+$||;
  }
  push(@todo, '/');
  while ($name = pop(@todo)) {    # Print info on node.
                                  # Format node name.
    ($node = $name) =~ s|^.*/([^/]+)$|$1|;
    $node = "\"$node\"" if ($node =~ m|\s|);
    if (! -e $name) {
      printf("%-48s %s\n",
        'Warning!  No such file or directory:', $node);
      last;
    }
                                  # Protect white space.
    ($tmp = $name) =~ s|(\s)|\\$1|g;
                                  # Get symbolic mode info.
    $sm   = substr(`ls -ald $tmp`, 0, 10);
                                  # Get info on node.
    @stat = lstat($name);
                                  # Get numeric mode info.
    $mode = $stat[2] &  07777;
                                  # Get user name.
    $usr  = (getpwuid($stat[4]))[0];
    $usr  = $stat[4] if ($usr eq '');
                                  # Get group name.
    $grp  = (getgrgid($stat[5]))[0];
    $grp  = $stat[5] if ($grp eq '');
                                  # Get modification time.
    (undef, undef, undef, $mday, $mon, $year,
     undef, undef, undef) = localtime($stat[9]);
    printf("%04o %10s %3d %-8s %-8s %s.%02d.%02d %s",
      $mode, $sm, $stat[3], $usr, $grp,
      $year+1900, $mon+1, $mday, $node);
    if ($sm =~ m|^l|) {           # Eeek, a symbolic link!
      $tmp = $tgt = readlink($name);
      $tmp = "\"$tmp\"" if ($tmp =~ m|\s|);
      printf(" -> %s\n", $tmp);
      ($todo = $save) =~ s|^$name|$tgt|;
      if ($tmp !~ m|^/|) {
        ($tmp  = $name) =~ s|^(.*/)[^/]+$|$1|;
        $todo  = "$tmp$todo";
      }
      goto REDO;
    }
    print("\n");
} }

Rich Morin has been using computers since 1970, Unix since 1983, and Mac-based Unix since 1986 (when he helped Apple create A/UX 1.0). When he isn't writing this column, Rich runs Prime Time Freeware (www.ptf.com), a publisher of books and CD-ROMs for the Free and Open Source software community. Feel free to write to Rich at rdm@ptf.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.