BUY THIS BOOK
Add to Cart

PDF $27.99

Safari Books Online

What is this?

Looking to Reprint or License this content?


Mac OS X Tiger for Unix Geeks
Mac OS X Tiger for Unix Geeks, Third Edition By Brian Jepson, Ernest E. Rothman
June 2005
Pages: 415

Cover | Table of Contents


Table of Contents

Chapter 1: Inside the Terminal
The Terminal application (/Applications/Utilities) is Mac OS X's graphical terminal emulator. Inside the Terminal, Unix users will find a familiar command-line environment. In this chapter we describe Terminal's capabilities and compare them to the corresponding xterm functionality when appropriate. We also highlight key features of another Aqua-native terminal application, iTerm. The chapter concludes with a synopsis of the open command, which you can use to launch Aqua applications from the Terminal.
Mac OS X comes with the Bourne-Again shell (bash) as the default user shell and also includes the TENEX C shell (tcsh), the Korn shell (ksh), and the Z shell (zsh). The bash, ksh, and zsh are sh-compatible. When tcsh is invoked through the csh link, it behaves much like csh. Similarly, /bin/sh is a hard link to bash, which also reverts to traditional behavior when invoked through this link (see the bash manpage for more information).
The version of bash that ships with Tiger has improved POSIX support over bash implementations that shipped with earlier releases of Mac OS X. Invoking bash with the -posix command-line option changes the default behavior of bash to comply with the POSIX 1003.2 standard in cases where the default behavior differs from this standard.
If you install additional shells , you should add them to /etc/shells. To change the Terminal's default shell, see "Customizing the Terminal," later in this chapter. To change a user's default shell (used for both the Terminal and remote console logins), see "Modifying a User" in Chapter 5.
There are several differences between Mac OS X's Terminal application and the xterm and xterm-like applications common to Unix systems running X Windows:
  • You cannot customize the characteristics of the Terminal with command-line switches such as -fn, -fg, and -bg. Instead, you must use the Terminal Inspector.
  • Unlike xterm, in which each window corresponds to a separate process, a single master process controls the Terminal. However, each shell session is run as a separate child process of the Terminal.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Mac OS X Shells
Mac OS X comes with the Bourne-Again shell (bash) as the default user shell and also includes the TENEX C shell (tcsh), the Korn shell (ksh), and the Z shell (zsh). The bash, ksh, and zsh are sh-compatible. When tcsh is invoked through the csh link, it behaves much like csh. Similarly, /bin/sh is a hard link to bash, which also reverts to traditional behavior when invoked through this link (see the bash manpage for more information).
The version of bash that ships with Tiger has improved POSIX support over bash implementations that shipped with earlier releases of Mac OS X. Invoking bash with the -posix command-line option changes the default behavior of bash to comply with the POSIX 1003.2 standard in cases where the default behavior differs from this standard.
If you install additional shells , you should add them to /etc/shells. To change the Terminal's default shell, see "Customizing the Terminal," later in this chapter. To change a user's default shell (used for both the Terminal and remote console logins), see "Modifying a User" in Chapter 5.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Terminal and xterm Compared
There are several differences between Mac OS X's Terminal application and the xterm and xterm-like applications common to Unix systems running X Windows:
  • You cannot customize the characteristics of the Terminal with command-line switches such as -fn, -fg, and -bg. Instead, you must use the Terminal Inspector.
  • Unlike xterm, in which each window corresponds to a separate process, a single master process controls the Terminal. However, each shell session is run as a separate child process of the Terminal.
  • The Terminal selection is not automatically put into the clipboard. Use ⌘-C to copy, and ⌘-V to paste. Even before you press ⌘-C, the current text selection is contained in a selection called the pasteboard . One similarity between Terminal and xterm is that selected text can be pasted in the same window with the middle button of a three-button mouse. If you want to paste selected text into another window, you must drag and drop it with the mouse or use copy and paste. The operations described in "The Services Menu" section of this chapter also use the pasteboard.
  • The value of $TERM is xterm-color when running under Terminal (it's set to xterm under xterm by default).
  • Pressing ⌘-Page Up or ⌘-Page Down scrolls the Terminal window, rather than letting the running program handle it.
  • On compatible systems (generally, a system with at least an ATI Radeon or NVidia GeForce AGP graphics adapter ), the Terminal (and all of the Aqua user interface) uses Quartz Extreme acceleration to make everything faster and smoother.
If you need an xterm, you can have it; however, you must first install Apple's X11 package, which is bundled with Mac OS X Tiger as an optional installation. See Chapter 7 for more information about the X Window System.
There are also Aqua-native applications that offer an alternative to Apple's Terminal, such as the freeware iTerm . We'll have more to say about iTerm later in this chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using the Terminal
The first order of business when exploring a new flavor of Unix is to find the command prompt. In Mac OS X, you won't find the command prompt in the Dock or on a Finder menu. Instead, you'll need to use the Terminal application, located in /Applications/Utilities. Don't open it just yet, though. First, drag Terminal's application icon to the Dock so you'll have quick access to it when you need to access the command line. To launch the Terminal, click its icon in the Dock once, or double-click on its icon in the Finder.
The full path to the Terminal is /Applications/Utilities/Terminal.app, although the Finder hides the .app extension. Terminal.app is not a binary file. Instead, it's a Mac OS X bundle, which contains a collection of files, including the binary and support files for the Terminal's user interface.
You can Control-click (or right-click) on the Terminal in the Finder and select Show Package Contents to see what's inside. You can also use the Unix commands ls and cd to explore the directory /Applications/Utilities/Terminal.app.
After the Terminal starts, you are greeted by the banner message from /etc/motd and a bash prompt, as shown in Figure 1-1.
Figure 1-1: The Terminal window
One difference xterm users will notice is that there is no obvious way to launch a new Terminal window from the command line. For example, the Mac OS X Terminal has no equivalent to the following commands:
    xterm &
    xterm -e -fg green -bg black -e pine -name pine -title pine &
Instead, you create a new Terminal window by pressing ⌘-N or selecting File → New Shell from the menu bar.
To cycle between open Terminal windows, you can use the same keystroke that most other Mac OS X applications use: ⌘-". You can also switch between windows by pressing ⌘-Right Arrow or ⌘-Left Arrow, using the Window menu, or by using the Terminal's Dock menu. You can also jump to a particular Terminal window with ⌘-
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Customizing the Terminal
To customize the shell used by the Terminal, start by changing the Terminal's Preferences (Terminal → Preferences). In the Preferences pane, you can tell the Terminal to execute the default shell or a specific command (such as an alternative shell) at startup. You can also declare the terminal type ($TERM), which is set as xterm-color by default. The other choices for the environment variable TERM are ansi, dtterm, rxvt, vt52, vt100, vt102, and xterm. Among other things, the default setting for TERM allows you to take advantage of the support for color output in ls (via the -G option) and color syntax highlighting in the vim editor. Although color is enabled by the default xterm-color, dtterm provides some additional capabilities. For example, the visual bell in vi works with dtterm, but not with xterm-color.
You can also adjust the Terminal's characteristics using Terminal → Window Settings (or ⌘-I), which brings up the Terminal Inspector, shown in Figure 1-3. Table 1-1 lists the available window settings . Changing these settings affects only the topmost Terminal window. If you want to change the default settings for all future Terminal windows, click the Use Settings As Defaults button at the bottom of the Terminal Inspector window.
Figure 1-3: The Terminal Inspector
Table 1-1: Window settings
Pane
Description
Shell
Displays the shell used by the Terminal and lets you choose whether to close the Terminal window when the shell exits.
Processes
Displays the processes running under the frontmost window. You can also control whether Terminal will warn you if you try to close the window while you are running a program. You can disable this by choosing Never under "Prompt before closing window." You can also supply a list of commands that should be ignored, so if you're running a program (such as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Services Menu
Mac OS X's Services menu (Terminal → Services) exposes a collection of services that can work with the currently running application. In the case of the Terminal, the services operate on text that you have selected (the pasteboard). To use a service, select a region of text in the Terminal and choose one of the following items from the Services menu:
ChineseTextConverter
This service can be used to convert selected text either to simplified Chinese or Traditional Chinese.
Disk Utility
This service invokes Disk Utility to calculate either a CRC-32 or an MD-5 image checksum of a selected disk.
Finder
The Finder Services menu allows you to open a file (Finder → Open), show its enclosing directory (Finder → Reveal), or show its information (Finder → Show Info).
Font Book
This can be used either to create a font collection or a font library from text.
Grab
Not supported by the Terminal.
Import Image
Not supported by the Terminal.
Mail
The Mail → Send To service allows you to compose a new message to an email address, once you have selected that address in the Terminal. You can also select a region of text and choose Mail → Send Selection to send a message containing the selected text.
Make New Sticky Note (Shift-⌘-Y)
This service creates a new Sticky (/Applications/Stickies) containing the selected text.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Bonjour
Bonjour (http://developer.apple.com/networking/bonjour), formerly known as Rendezvous, is a networking technology that allows Bonjour-enabled devices on a local network to automatically discover each other. As are many Mac OS X applications, Terminal is Bonjour-enabled. For example, you can select File → Connect to Server to make an SSH connection to any other Mac OS X system on the LAN, provided it allows such connections. The other Macs on the LAN are identified by their computer names, as specified in their Sharing System Preferences.
Announced in 2002 as Rendezvous, Bonjour is Apple's implementation of the Zero Configuration Networking open source project , also known as Zeroconf (http://www.zeroconf.org), which was initiated by the Internet Engineering Task Force (http://www.ietf.org) in 1999.
You can learn more about Bonjour by reading Apple's Bonjour Technology Brief at http://images.apple.com/macosx/pdf/MacOSX_Bonjour_TB.pdf.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Alternative Terminal Applications
As noted earlier, other Aqua-native terminal applications are available, and the freeware iTerm (http://iterm.sourceforge.net), developed by Fabian and Ujwal S. Sathyam, is a particularly attractive one. Although Mac OS X's Terminal is rich with useful features, iTerm offers some interesting extras that make it worthy of consideration. We won't cover iTerm in great detail, but will touch on a few of its more attractive aspects.
Before getting into what makes iTerm distinct, here are some similarities between iTerm and Terminal:
  • One feature that each of these terminal applications share is that they use the same Services menu.
  • Both iTerm and Terminal support transparency, language encodings, and AppleScript, and have contextual menus that can be accessed by Control-clicking or right-clicking (if you have a two- or three-button mouse) in a window.
iTerm supports several language encodings, vt100/ANSI/xterm/xterm-color/rxvt emulations, and many GUI features. Particularly interesting features of iTerm include support for multiple tabbed terminal sessions within each window, bookmarks that allow you to open new iTerm sessions with preset terminal settings, and bookmarks for launching non-shell commands. The default value for TERM is vt100, but this can be changed either on the fly with a bash shell command, such as TERM=xterm-color, in the Configure menu, or, if you want a global change, in iTerm's Preferences dialog. Like the Terminal application, iTerm is also Bonjour-enabled.
iTerm's tabbed view should be familiar to GNOME users, since the gnome-terminal also supports this feature. Tabs in iTerm are designed to make efficient use of desktop space, much as they do in Safari and other popular web browsers. Figure 1-4 shows an iTerm window with two tabs.
The same bash (or tcsh) shell commands that can be used to customize the Terminal's titlebar work just as well with iTerm's titlebar. When used in iTerm, these commands also set the tab labels as shown in Figure 1-5.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The open Command
The open shell command lets you open Finder windows and launch Aqua applications. To open a directory in the Finder, use open, followed by the name of the directory. For example, to open a Finder window containing the current directory, enter the following command:
    open .
Figure 1-8: Defining a bookmark to a new profile in iTerm
To open your Public folder (~ /Public) in a Finder window, use the following:
    open ~/Public
To open the /Applications folder in a Finder window, use the following:
    open /Applications
To open an application, you need only its name. To open Xcode (/Developer/Applications), you would use the following:
    open -a Xcode
You are not required to enter the path for the application, only its name, even if it is a Classic application. The only time you are required to enter the path is if you have two different versions of an application with similar names on your system.
You can use the -a option to open a file with something other than the application with which it's associated. For example, to open an XML file in Xcode instead of the default XML editor, the Property List Editor, enter this command:
    open -a Xcode data.xml
To open multiple files, you can use wildcards:
    open *.c
To force a file to be opened with TextEdit, use -e:
    open -e *.c
The -e option directs the file to be opened in TextEdit; it cannot be used to open a file in another text editor, such as BBEdit (though BBEdit includes its own command-line application for this purpose). However, if you want to open a file using BBEdit, use the following:
    open -a BBEdit filename
If you want to use TextEdit on a file that is owned by an administrator (or root), sudo open -e won't work. You'll need to specify the full path to the TextEdit executable, as in:
    $ sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit 
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Searching and Metadata
If a Unix Geek needs to find something, she'll probably use locate or find, depending on what she's looking for. Because locate is based on a static database that's only regenerated periodically (see "Scheduling Tasks in Chapter 4), it would be the choice for things that don't change a lot (virtually anything in /usr). It's also much faster because it has that database to consult. And trusty old find, slow as molasses, is what you need when you need more control over the search or when you're looking for something that locate doesn't know about, such as files that have been created recently.
But Tiger introduces a new search capability, Spotlight , which stores and sifts through file metadata faster than a herd of sheep can clear a field. Spotlight comes in two forms: a GUI interface accessible from the menubar, and a suite of command-line utilities. This chapter introduces you to Spotlight and shows you how to take advantage of all it has to offer.
Remember the relentless disk grinding you heard after you first installed the operating system? That was Spotlight creating its initial database. Spotlight is a repository of metadata for certain types of files—Spotlight gathers information about any file (or data record, such as an iCal event) for which it has an importer (an operating system plug-in that extracts metadata from a document). To see all the importers on your system, look in /System/Library/Spotlight and /Library/Spotlight.
By default, Spotlight has importers for the following files and data:
  • Address Book records
  • AppleWorks files
  • Applications
  • Audio files
  • Safari bookmarks
  • iChat transcripts
  • Fonts
  • iCal events
  • Images
  • Keynote presentations
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Spotlight
Remember the relentless disk grinding you heard after you first installed the operating system? That was Spotlight creating its initial database. Spotlight is a repository of metadata for certain types of files—Spotlight gathers information about any file (or data record, such as an iCal event) for which it has an importer (an operating system plug-in that extracts metadata from a document). To see all the importers on your system, look in /System/Library/Spotlight and /Library/Spotlight.
By default, Spotlight has importers for the following files and data:
  • Address Book records
  • AppleWorks files
  • Applications
  • Audio files
  • Safari bookmarks
  • iChat transcripts
  • Fonts
  • iCal events
  • Images
  • Keynote presentations
  • Mail messages
  • Microsoft Office documents
  • Pages documents
  • PDF and PostScript files
  • QuickTime movies
  • RTF documents
  • Source code
  • System preferences
To perform a spotlight query, simply click the magnifying glass icon in the upper right of the menu bar or press ⌘-Space. A Spotlight search field drops down, in which you enter a search term, as shown in Figure 2-1.
You can get a more detailed Spotlight search window by pressing Option-⌘-Space. This window, shown in Figure 2-2, lets you configure a number of aspects of your search, such as location, date, and result grouping.
Unix geeks might never use Spotlight if Mac OS X didn't include some command-line goodies for performing searches . You can perform a simple Spotlight search from the shell with the following syntax:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Resource Forks and HFS+ Metadata
Apple's HFS+ filesystem has been stashing metadata away since its introduction in Mac OS 8.1. Resource forks are generally invisible portions of files used for stashing additional information (the primary portion of the file—indeed the only part of a file most Unix Geeks are used to thinking about—is called the data fork ). Before Mac OS X, resource forks contained application resources. These are now contained in the application bundle itself, although resource forks are still used in classic applications and a few odd places (such as text clippings, which you can create by dragging and dropping text selections to the Finder).
You can inspect a resource fork by appending /rsrc to a file name, as in:
    $ ls -l Sample.textClipping
    -rw-r--r--   1 bjepson  bjepson  0 Feb 27 11:05 Sample.textClipping
    $ ls -l Sample.textClipping/rsrc
    -rw-r--r--   1 bjepson  bjepson  1770 Feb 27 11:05 Sample.textClipping/rsrc
The contents of a resource fork, even for something simple like a text clipping, are not necessarily human-readable, but there's usually something you can dig out:
    $ file Sample.textClipping/rsrc
    Sample.textClipping/rsrc: ms-windows icon resource
    $ strings Sample.textClipping/rsrc
    KApple's HFS+ filesystem has been stashing metadata away since its
    introduction in Mac OS X 8.1. Resource forks are generally invisible
    portionsof files used for stashing additional information (the primary
    portion of the...
Mac OS X Tiger also makes use of HFS+ metadata, which consists of extended attributes that are associated with files. For example, if you look at the root of your Mac's hard drive in the Finder, you'll only see a small subset of the files (at the very least, Library, System, Applications, Users). But if you drop down into the Terminal, there are plenty more. The files that don't appear have an attribute (I) that makes them invisible to the Finder.
You can inspect this metadata with GetFileInfo and set it with SetFile, both of which are located in
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: The Mac OS X Filesystem
HFS+ has a lot going for it. Although its case-insensitivity caused problems back in the very early days of Mac OS X, is hasn't proved to be a problem in the long run. Its transparent support of the metadata that is so crucial to Mac OS X, coupled with its excellent support for journaling, make it the filesystem of choice for Mac OS X. But even if your hard disk, iPods, and external drives are all happily formatted with HFS+, you'll have to exchange files with something other than a Mac one of these days.
Mac OS X files are complicated constructs. Chapter 2 introduced you to the metadata that can lurk on the HFS+ filesystem and also discussed how it's stored on other types of filesystems using the Apple Double format . With much more than the usual contents of files to worry about, it's very easy to drop bits of your files all over the place, especially on foreign filesystems. This chapter talks a bit more about these details, explains what you need to consider when you move files from HFS+ to other filesystems, and ends with a description of how files are laid out on a Mac.
If you're going to move files between your Mac and another operating system, there are some things you need to watch out for. As we discussed in Chapter 2, the Apple Double format will sprinkle some files with odd names across the filesystem, such as ._filename. You'll also find a few files created in the root, such as Temporary Items and .Trashes (see Table 3-1).
The most significant problem you'll run into is moving large files around: if you're not using a third-party utility, the only common filesystem that Mac OS X, Windows, and Linux can read and write is the ancient FAT32, which has a limit of 2 GB per file.
If at all possible, we suggest that you use the network to transfer large files. If you're using an AirPort (or even a 100BaseT) network, it's worth running a cable between your Mac and the other system and setting up a TCP/IP connection for large file transfers. If you can get Gigabit Ethernet or even IP over FireWire, you'll be pleased with the zippy file transfer speeds. Even if you're not moving large files, the network is often the best way to exchange information. The are several solutions you can use for exchanging files across the network:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with Foreign Filesystems
If you're going to move files between your Mac and another operating system, there are some things you need to watch out for. As we discussed in Chapter 2, the Apple Double format will sprinkle some files with odd names across the filesystem, such as ._filename. You'll also find a few files created in the root, such as Temporary Items and .Trashes (see Table 3-1).
The most significant problem you'll run into is moving large files around: if you're not using a third-party utility, the only common filesystem that Mac OS X, Windows, and Linux can read and write is the ancient FAT32, which has a limit of 2 GB per file.
If at all possible, we suggest that you use the network to transfer large files. If you're using an AirPort (or even a 100BaseT) network, it's worth running a cable between your Mac and the other system and setting up a TCP/IP connection for large file transfers. If you can get Gigabit Ethernet or even IP over FireWire, you'll be pleased with the zippy file transfer speeds. Even if you're not moving large files, the network is often the best way to exchange information. The are several solutions you can use for exchanging files across the network:
Netatalk
Netatalk (http://netatalk.sourceforge.net) is best known as a suite for introducing Unix servers to AppleTalk networks. However, it has a daemon, afpd, which can share files over TCP/IP using the native Apple sharing protocol, AFP (Apple Filing Protocol) . Early versions (and often the versions that are bundled with many Linux distributions) only supported an earlier version of AFP, and were limited in the length of file names. The most recent version of Netatalk works great with Mac OS X, with the exception of its non-standard Apple Double implementation, described later in this section.
Unison
Unison (http://www.cis.upenn.edu/~bcpierce/unison) is a powerful file synchronizer that lets you keep Windows, Mac OS X, Linux, and Unix files in sync. It does so by maintaining a replica on each side of the synchronization, comparing the state of the filesystem against the last-known replica, and making intelligent decisions about which files are the most recent. In cases where it can't figure something out (perhaps you changed the file in both places), it prompts you to tell it what to do.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Files and Directories
If you do an ls -a / on your Tiger system, you'll see some familiar things, such as /etc and /var, but you'll also notice some unfamiliar things, such as /TheVolumeSettingsFolder, /Library, and /Documents. Mac OS X's filesystem contains traces of Unix, NeXTSTEP, and Mac OS 9. The tables in the rest of this chapter list directory entries and provide a description of each file or directory.
Table 3-1 describes the files and directories (indicated with a trailing slash) you may find in your / (the root) directory. The remaining tables in this chapter describe significant subdirectories.
Table 3-1: Mac OS X's root directory
File or directory
Description
.DS_Store
Contains Finder settings, such as icon location and window size. The file will appear in any directory that you've viewed with the Finder.
.Spotlight-V100/
Contains metadata used by Spotlight. For more information, see Chapter 2.
.Trashes/
Contains files that have been dragged to the Trash. On a boot volume, such files are stored in ~/.Trash. On a non-boot volume, these files are in /.Trashes/uid/.
.vol/
Maps HFS+ file IDs to files. If you know a file's ID, you can open it using /.vol/id.
Applications/
Holds all your Mac OS X applications. Its Utilities subdirectory includes lots of useful things, such as the Terminal, Console, and the Activity Monitor.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Startup
The most striking difference between Mac OS X and other flavors of Unix is in how Mac OS X handles the boot process. Gone are /etc/inittab, /etc/init.d, and /etc/rc.local from traditional Unix systems. In their place is a BSD-like startup sequence sandwiched between a Mach foundation and the Aqua user interface.
This chapter describes Mac OS X Tiger's startup sequence, beginning with the BootX loader and progressing to full multiuser mode, at which time the system is ready to accept logins from normal users. The chapter also covers custom startup items, network interface configuration, and Mac OS X's default periodic jobs.
When the computer is powered up, the firmware is in complete control. After the firmware initializes the hardware, it hands off control to the BootX loader, which bootstraps the kernel. After a trip into Mach, the control bubbles up into the BSD subsystem, and eventually into the Aqua user interface.
By default, Mac OS X boots graphically. If you'd like to see console messages as you boot, hold down ⌘-V (the "V" stands for "verbose") as you start the computer. If you'd like to always boot in verbose mode , you can specify a flag in the boot arguments that are stored in your system's firmware. First, use the command nvram boot-args to make sure there aren't any flags already set (if there are, and you didn't set them, you probably should not change this setting). Set your boot arguments to -v with this command:
    sudo /usr/sbin/nvram boot-args="-v"
The next time you boot your Mac, it boots in verbose mode. To turn this setting off, use the command:
    sudo /usr/sbin/nvram boot-args=
To boot in single-user mode , hold down ⌘-S as you start the computer. In single-user mode, your filesystem is mounted as read-only, which limits what you can do. Single-user mode should generally be used only to repair a system that has been damaged (for example, see "Restoring the Directory Services Database" in Chapter 5). Unlike with other Unix systems, we do not suggest that you use single-user mode to perform
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Booting Mac OS X
When the computer is powered up, the firmware is in complete control. After the firmware initializes the hardware, it hands off control to the BootX loader, which bootstraps the kernel. After a trip into Mach, the control bubbles up into the BSD subsystem, and eventually into the Aqua user interface.
By default, Mac OS X boots graphically. If you'd like to see console messages as you boot, hold down ⌘-V (the "V" stands for "verbose") as you start the computer. If you'd like to always boot in verbose mode , you can specify a flag in the boot arguments that are stored in your system's firmware. First, use the command nvram boot-args to make sure there aren't any flags already set (if there are, and you didn't set them, you probably should not change this setting). Set your boot arguments to -v with this command:
    sudo /usr/sbin/nvram boot-args="-v"
The next time you boot your Mac, it boots in verbose mode. To turn this setting off, use the command:
    sudo /usr/sbin/nvram boot-args=
To boot in single-user mode , hold down ⌘-S as you start the computer. In single-user mode, your filesystem is mounted as read-only, which limits what you can do. Single-user mode should generally be used only to repair a system that has been damaged (for example, see "Restoring the Directory Services Database" in Chapter 5). Unlike with other Unix systems, we do not suggest that you use single-user mode to perform fsck repairs manually. Instead, restart your Mac and boot from Tiger's install DVD (hold down the C key as your Mac starts up), and then run the Disk Utility (Installer → Open Disk Utility) to repair a problem disk volume.
BootX is located in /System/Library/CoreServices. It draws the Apple logo on the screen and proceeds to set up the kernel environment. BootX first looks for kernel extensions (drivers , also known as kexts) that are cached in the mkext cache. If this cache does not exist, BootX loads only those extensions in /System/Library/Extensions that have the OSBundleRequired
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding Startup Items
To automatically start applications, you have two choices: start them when a user logs in, or start them when the system boots up. On most Unix systems, startup applications either reside in the /etc/rc.local script or the /etc/init.d directory. Under Mac OS 9, you could add a startup item by putting its alias in System Folder/Startup Items. Mac OS X has a different approach, described in the following sections.
To start an application each time you log in, use the Accounts panel of System Preferences and select the Login Items tab. This is good for user applications, such as Stickies or an instant messenger program. For system daemons, you should set up a directory in /Library/StartupItems, as described in the next section.
If you compile and install a daemon, you'll probably want it to start at boot time. For example, MySQL will build out of the box on Mac OS X (you can download it from http://www.mysql.com).
In some cases, you can start a daemon by creating a launch daemon property list in /Library/LaunchDaemons. However, there are many restrictions on launch daemons—for example, they are not allowed to change the user or group id. Also, launch daemons do not have a facility for shutting down. For complete details on these restrictions, see the launchd.plist manpage. If you are setting up a daemon that either cannot abide by the launchd restrictions, or one that needs to be shutdown gracefully, you should create a Startup Item as described in this section.
A startup item is controlled by three things: a folder (such as /Library/StartupItems/MyItem), a shell script with the same name as the directory (such as MyItem), and a property list named StartupParameters.plist . The shell script and the property list must appear at the top level of the startup item's folder. You can also create a Resources directory to hold localized resources, but this is not mandatory.
To set up the MySQL startup item, create the directory
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Scheduling Tasks
Like other flavors of Unix, Mac OS X uses cron to schedule tasks for periodic execution. Each user's cron jobs are controlled by configuration files that you can edit with crontab -e. (To list the contents of the file, use crontab -l.)
In Mac OS X Tiger, the global crontab (/etc/crontab) has been replaced with three launch daemons. The original crontab looked like this:
    15 3 * * *       root    periodic daily
    30 4 * * 6       root    periodic weekly
    30 5 1 * *       root    periodic monthly
But now, each line is replaced by a file in /System/Library/LaunchDaemons (com.apple.periodic-daily.plist, com.apple.periodic-weekly.plist, and com.apple.periodic-monthly.plist) that uses the StartCalendar tag to specify when it is to be run. For example, here is the com.apple.periodic-daily.plist file:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.
    com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
            <key>Label</key>
            <string>com.apple.periodic-daily</string>
            <key>ProgramArguments</key>
            <array>
                    <string>/usr/sbin/periodic</string>
                    <string>daily</string>
            </array>
            <key>LowPriorityIO</key>
            <true/>
            <key>Nice</key>
            <integer>1</integer>
            <key>StartCalendarInterval</key>
            <dict>
                    <key>Hour</key>
                    <integer>3</integer>
                    <key>Minute</key>
                    <integer>15</integer>
            </dict>
    </dict>
    </plist>
These three launch daemons run the scripts contained in subdirectories of the /etc/periodic directory: /etc/periodic/daily, /etc/periodic/weekly, and /etc/periodic/monthly. Each of these directories contains one or more scripts:
    /etc/periodic/daily/100.clean-logs
    /etc/periodic/daily/500.daily
    /etc/periodic/monthly/500.monthly
    /etc/periodic/weekly/500.weekly
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Directory Services
A directory service manages information about users and resources such as printers and servers. It can manage this information for anything from a single machine to an entire corporate network. The Directory Service architecture in Mac OS X is called Open Directory . Open Directory encompasses flat files (such as /etc/hosts), NetInfo (the legacy directory service brought over from earlier versions of Mac OS X and NeXTSTEP), LDAPv3, and other services through third-party plug-ins.
This chapter describes how to perform common configuration tasks, such as adding a user or host on Mac OS X with the default configuration. If your system administrator has configured your Macintosh to consult an external directory server, some of these instructions may not work. If that's the case, you should ask your system administrator to make these kinds of changes anyhow.
In Mac OS X 10.1.x and earlier, the system was configured to consult the NetInfo database for all directory information. If you needed to do something simple, such as adding a host, you couldn't just add it to /etc/hosts and be done with it. Instead, you had to use the NetInfo Manager (or NetInfo's command-line utilities) to add the host to the system.
However, as of Mac OS X 10.2 (Jaguar), NetInfo functions started to become more of a legacy protocol and were reduced to handling the local directory database for machines that did not participate in a network-wide directory, such as Active Directory or OpenLDAP. NetInfo is still present in Mac OS X 10.3 and 10.4, but you can perform many configuration tasks by editing the standard Unix flat files. By default, Mac OS X is now configured to consult the local directory (also known as the NetInfo database) for authentication, which corresponds to /etc/passwd and /etc/group on other Unix systems. You can override this setting with the Directory Access application . For more information, see "Configuring Directory Services," later in this chapter.
For users whose network configuration consists of an IP address, a default gateway, and some DNS addresses, this default configuration should be fine. You'll need to tap into Open Directory 's features for more advanced configurations, such as determining how a user can log into a workstation and find his home directory, even when that directory is hosted on a shared server.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding Directory Services
In Mac OS X 10.1.x and earlier, the system was configured to consult the NetInfo database for all directory information. If you needed to do something simple, such as adding a host, you couldn't just add it to /etc/hosts and be done with it. Instead, you had to use the NetInfo Manager (or NetInfo's command-line utilities) to add the host to the system.
However, as of Mac OS X 10.2 (Jaguar), NetInfo functions started to become more of a legacy protocol and were reduced to handling the local directory database for machines that did not participate in a network-wide directory, such as Active Directory or OpenLDAP. NetInfo is still present in Mac OS X 10.3 and 10.4, but you can perform many configuration tasks by editing the standard Unix flat files. By default, Mac OS X is now configured to consult the local directory (also known as the NetInfo database) for authentication, which corresponds to /etc/passwd and /etc/group on other Unix systems. You can override this setting with the Directory Access application . For more information, see "Configuring Directory Services," later in this chapter.
For users whose network configuration consists of an IP address, a default gateway, and some DNS addresses, this default configuration should be fine. You'll need to tap into Open Directory 's features for more advanced configurations, such as determining how a user can log into a workstation and find his home directory, even when that directory is hosted on a shared server.
In order to work with Mac OS X's Directory Services, you must first understand the overall architecture, which is known as Open Directory. Directory Services is the part of Mac OS X (and the open source Darwin operating system) that implements this architecture. Figure 5-1 shows the relationship of Directory Services to the rest of the operating system. On the top, server processes, as well as the user's desktop and applications, act as clients to Directory Services, which delegates requests to a directory service plug-in (see "Configuring Directory Services," later in this chapter, for a description of each plug-in).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Programming with Directory Services
As a programmer, you frequently need to deal with directory information, whether you realize it or not. Your application uses Directory Services each time it looks up a host entry or authenticates a password. The Open Directory architecture unifies what used to be a random collection of flat files in /etc. The good news is that the flat files still work. The other good news is that there is a brave new world just beyond those flat files. So, while all your old Unix code should work with the Open Directory architecture, you should look for new ways to accomplish old tasks, especially if you can continue writing portable code.
To get at directory information, Unix applications typically go through the C library using such functions as gethostent( ). The C library connects to lookupd, a thin shim that is the doorway to the DirectoryService daemon. The DirectoryService daemon consults the available plug-ins until it finds the one that can answer the directory query.
One traditional route to user and password information was through the getpw* family of functions. However, those functions are not ideal for working with systems that support multiple directories (flat files, NetInfo, LDAP, etc.). Also, in the interest of thwarting dictionary attacks against password files , many operating systems have stopped returning encrypted passwords through those APIs. Many Unix and Linux systems simply return an "x" when you invoke a function like getpwnam( ). However, those systems can return an encrypted password through functions like getspnam( ), which consult shadow password entries and can generally be invoked by the root user only. Example 5-1 shows the typical usage of such an API, where the user enters her plaintext password, and the program encrypts it and then compares it against the encrypted password stored in the system.
Example 5-1. Using getpwnam( ) to retrieve an encrypted password
    /*
     * getpw* no longer returns a crypted password.
     *
     * Compile with gcc checkpass.c -o checkpass
     * Run with: ./checkpass
     */

    #include <pwd.h>
    #include <stdio.h>
    #include <stdlib.h>

    int main(int argc, char *argv[])
    {
      const char *user = NULL;
      struct passwd *pwd;

      /* Set the user name if it was supplied on the command
       * line.  Bail out if we don't end up with a user name.
       */
      if (argc == 2)
        user = argv[1];
      if(!user)
      {
        fprintf(stderr, "Usage: checkpass <username>\n");
        exit(1);
      }

      /* Fetch the password entry. */
      if (pwd = getpwnam(user))
      {
        char *password = (char *) getpass("Enter your password: ");

        /* Encrypt the password using the encrypted password as salt.
         * See crypt(3) for complete details.
         */
        char *crypted  = (char *) crypt(password, pwd->pw_passwd);

        /* Are the two encrypted passwords identical? */
        if (strcmp(pwd->pw_passwd, crypted) == 0)
          printf("Success.\n");
        else
        {
          printf("Bad password: %s != %s\n", pwd->pw_passwd, crypted);
          return 1;
        }
      }
      else
      {
        fprintf(stderr, "Could not find password for %s.\n", user);
        return 1;
      }
      return 0;

    }
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Configuring Directory Services
In order to configure Directory Services, use the Directory Access application (/Applications/Utilities), shown in Figure 5-2. You can enable or disable various directory service plug-ins , or change their configuration.
Directory Access supports the following plug-ins:
Active Directory
This plug-in lets Mac OS X consult an Active Directory domain on a server running Windows 2000 or Windows 2003.
AppleTalk
This is the ultimate Mac OS legacy protocol. AppleTalk was the original networking protocol supported by Mac OS versions prior to Mac OS X. Linux and the server editions of Windows also support AppleTalk.
Bonjour
Formerly known as Rendezvous, Bonjour is Apple's zero-configuration protocol for discovering file sharing, printers, and other network services. It uses a peer-to-peer approach to announce and discover services automatically as devices join a network.
BSD Flat File and NIS
This includes the Network Information Service (NIS) and the flat files located in the /etc directory, such as hosts, exports, and services. By default, this option is switched off. After you enable it, click Apply, switch to the Authentication tab, choose Custom Path from the search menu, click the Add button, choose /BSD/Local, and click Apply again.
Figure 5-2: The Directory Access application shows the available plug-ins
LDAPv3
This is the same version of LDAP used by Microsoft's Active Directory and Novell's NDS. In addition to the client components, Mac OS X includes
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
NetInfo Manager
The local directory is organized hierarchically, starting from the root, which, like a filesystem's root, is called /. However, this is not meant to suggest that there is a corresponding directory or file for each entry. Instead, the data is stored in a collection of files under /var/db/netinfo.
You can browse or modify the local directory using NetInfo Manager, which is located in /Applications/Utilities. Figure 5-4 shows NetInfo Manager displaying the properties of the mysql user.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Directory Services Utilities
This chapter demonstrates four Directory Services utilities : dscl, nireport, nidump, and niload. Table 5-1 describes these and other NetInfo utilities.
Figure 5-4: Browsing the local directory
Table 5-1: NetInfo tools
Tool
Description
dscl
Provides a command-line interface to Directory Services.
nicl
Provides a command-line interface to NetInfo.
nidump
Extracts flat file format data (such as /etc/passwd) from NetInfo.
nifind
Finds a NetInfo directory.
nigrep
Performs a regular expression search on NetInfo.
niload
Loads flat file format data (such as /etc/passwd) into NetInfo.
nireport
Prints tables from NetInfo.
niutil
NetInfo utility for manipulating the database.
The nidump and nireport utilities display the contents of the local directory. niload loads the contents of flat files (such as /etc/passwd or /etc/hosts) into Directory Services. niutil directly manipulates the Directory Services database; it's the command-line equivalent of NetInfo Manager. To make changes, use
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Managing Groups