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.

 
AAPL
$116.47
Apple Inc.
+0.16
MSFT
$47.98
Microsoft Corpora
-0.72
GOOG
$537.50
Google Inc.
+2.67

MacTech Search:
Community Search:

Software Updates via MacUpdate

Cobook 3.0.7 - Intelligent address book....
Cobook Contacts is an intuitive, engaging address book. Solve the problem of contact management with Cobook Contacts and its simple interface and powerful syncing and integration possibilities.... Read more
StatsBar 1.9 - Monitor system processes...
StatsBar gives you a comprehensive and detailed analysis of the following areas of your Mac: CPU usage Memory usage Disk usage Network and bandwidth usage Battery power and health (MacBooks only)... Read more
Cyberduck 4.6 - FTP and SFTP browser. (F...
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Evernote 6.0.1 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
calibre 2.11 - Complete e-library manage...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital... Read more
Herald 5.0.1 - Notification plugin for M...
Note: Versions 2.1.3 (for OS X 10.7), 3.0.6 (for OS X 10.8), and 4.0.8 (for OS X 10.9) are no longer supported by the developer. Herald is a notification plugin for Mail.app, Apple's Mac OS X email... Read more
Firetask 3.7 - Innovative task managemen...
Firetask uniquely combines the advantages of classical priority-and-due-date-based task management with GTD. Stay focused and on top of your commitments - Firetask's "Today" view shows all relevant... Read more
TechTool Pro 7.0.6 - Hard drive and syst...
TechTool Pro is now 7, and this is the most advanced version of the acclaimed Macintosh troubleshooting utility created in its 20-year history. Micromat has redeveloped TechTool Pro 7 to be fully 64... Read more
PhotoDesk 3.0.1 - Instagram client for p...
PhotoDesk lets you view, like, comment, and download Instagram pictures/videos! (NO Uploads! / Image Posting! Instagram forbids that! AND you *need* an *existing* Instagram account). But you can do... Read more

Latest Forum Discussions

See All

Ubisoft Gives Everyone Two New Ways to E...
Ubisoft Gives Everyone Two New Ways to Earn In-Game Stuff for Far Cry 4 Posted by Jessica Fisher on November 21st, 2014 [ permalink ] | Read more »
Golfinity – Tips, Tricks, Strategies, an...
Dig this: Would you like to know what we thought of being an infinite golfer? Check out our Golfinity review! Golfinity offers unlimited ways to test your skills at golf. Here are a few ways to make sure your score doesn’t get too high and your... | Read more »
Dark Hearts, The Sequel to Haunting Meli...
Dark Hearts, The Sequel to Haunting Melissa, is Available Now Posted by Jessica Fisher on November 21st, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Meowza! Toyze Brings Talking Tom to Life...
Meowza! | Read more »
Square Enix Announces New Tactical RPG f...
Square Enix Announces New Tactical RPG for Mobile, Heavenstrike Rivals. Posted by Jessica Fisher on November 21st, 2014 [ permalink ] With their epic stories and gorgeous graphics, | Read more »
Quest for Revenge (Games)
Quest for Revenge 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: The great Kingdom of the west has fallen. The gods ignore the prayers of the desperate. A dark warlord has extinguished... | Read more »
Threadz is a New Writing Adventure for Y...
Threadz is a New Writing Adventure for You and Your Friends Posted by Jessica Fisher on November 21st, 2014 [ permalink ] In the tradition of round-robin storytelling, | Read more »
SteelSeries Stratus XL Hardware Review
Made by: SteelSeries Price: $59.99 Hardware/iOS Integration Rating: 4 out of 5 stars Usability Rating: 4.5 out of 5 stars Reuse Value Rating: 4.25 out of 5 stars Build Quality Rating: 4.5 out of 5 stars Overall Rating: 4.31 out of 5 stars | Read more »
ACDSee (Photography)
ACDSee 1.0.0 Device: iOS iPhone Category: Photography Price: $1.99, Version: 1.0.0 (iTunes) Description: Capture, perfect, and share your photos with ACDSee. The ACDSee iPhone app combines an innovative camera, a powerful photo... | Read more »
ProTube for YouTube (Entertainment)
ProTube for YouTube 2.0.2 Device: iOS Universal Category: Entertainment Price: $1.99, Version: 2.0.2 (iTunes) Description: ProTube is the ultimate, fully featured YouTube app. With it's highly polished design, ProTube offers ad-free... | Read more »

Price Scanner via MacPrices.net

Save up to $400 with Apple refurbished 2014 1...
The Apple Store has restocked Apple Certified Refurbished 2014 15″ Retina MacBook Pros for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and shipping... Read more
New 13-inch 1.4GHz MacBook Air on sale for $8...
 Adorama has the 2014 13″ 1.4GHz/128GB MacBook Air on sale for $899.99 including free shipping plus NY & NJ tax only. Their price is $100 off MSRP. B&H Photo has the 13″ 1.4GHz/128GB MacBook... Read more
Apple Expected to Reverse Nine-Month Tablet S...
Apple and Samsung combined accounted for 62 percent of the nearly 36 million branded tablets shipped in 3Q 2014, according to early vendor shipment share estimates from market intelligence firm ABI... Read more
Stratos: 30 Percent of US Smartphone Owners t...
Stratos, Inc., creator of the Bluetooth Connected Card Platform, has announced results from its 2014 Holiday Mobile Payments Survey. The consumer survey found that nearly one out of three (30 percent... Read more
2014 1.4GHz Mac mini on sale for $449, save $...
 B&H Photo has lowered their price on the new 1.4GHz Mac mini to $449.99 including free shipping plus NY tax only. Their price is $50 off MSRP, and it’s the lowest price available for this new... Read more
Check Apple prices on any device with the iTr...
MacPrices is proud to offer readers a free iOS app (iPhones, iPads, & iPod touch) and Android app (Google Play and Amazon App Store) called iTracx, which allows you to glance at today’s lowest... Read more
64GB iPod touch on sale for $249, save $50
Best Buy has the 64GB iPod touch on sale for $249 on their online store for a limited time. Their price is $50 off MSRP. Choose free shipping or free local store pickup (if available). Sale price for... Read more
15″ 2.2GHz Retina MacBook Pro on sale for $17...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale for $1799.99 for a limited time. Shipping is free, and B&H charges NY sales tax only. B&H will also include free copies of... Read more
New Logitech AnyAngle Case/Stand Brings Flexi...
Logitec has announced the newest addition to its suite of tablet products — the Logitech AnyAngle. A protective case with an any-angle stand for iPad Air 2 and all iPad mini models, AnyAngle is the... Read more
Notebook PC Shipments Rise Year-Over-Year as...
According to preliminary results from the upcoming DisplaySearch Quarterly Mobile PC Shipment and Forecast Report, the global notebook PC market grew 10 percent year-over-year in Q3’14 to 49.4... Read more

Jobs Board

*Apple* Solutions Consultant (ASC)- Retail S...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Store Leader Program - College Gradu...
Job Description: Job Summary As an Apple Store Leader Program agent, you can continue your education as you major in the art of leadership at the Apple Store. You'll Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.