Interarchy IconInterarchy

Complex Transfers Simplified - Only With A Mac

Reference

FTP

The FTP protocol was created in 1985 and remains a primary way of transferring files on the Internet and supports both anonymous and authenticated logins.

Although FTP is a solid protocol that has stood the test of time, it has several drawbacks.

Like the telnet protocol, the FTP protocol’s authentication takes place in clear text and so can be viewed by anyone with access to any point on the network between you and the server. This security limitation has led to the introduction of SSH, which in turn produced SFTP and FTP over SSH.

Also, the FTP protocol was never very well standardized and such things as the listing format and directory paths can vary from server to server. This can lead to compatibility problems and although Interarchy makes a valiant effort to be compatible with most unix-like servers, compatibility with all servers is not feasible.

Another issue with the FTP protocol is that it uses a new TCP connection for each listing or file transfer while retaining the original control connection to specify the action. This can lead to problems from two directions. When creating a data connection, Interarchy must connect to the server or vice versa (see the Passive Mode/Port Mode section), and this connection takes place from a random port to a random port which requires a wide firewall hole (see the Firewalls section) and which can have problems related to dynamic IP addresses or Network Address Translation (NAT) if the connection cannot be made. Also, during a long transfer the control connection sits idle while the data is transferred on the data connection. When the transfer is finished, a final message is sent on the control connection to confirm the valid completion. Unfortunately on some networks, the routers may have since ‘forgotten’ the route the control connection packets take and this can lead to the transfer failing right at the end. Usually just canceling and resuming the transfer will resolve the problem. For a solution to this problem if it afflicts you, see the Long transfers timeout at the end of the transfer, what’s wrong? section.

See also the FTP over SSH, SSH and Passive Mode/Port Mode sections.

FTP over SSH

The FTP protocol was created in 1985, when security was less of a concern on the Internet. As with the telnet protocol, the FTP protocol specifies a login sequence which involves sending the username and password in plain text between client and server. In recent years, as security has become more of a concern, this has become a problem for users who do not want intermediate parties to record their usernames and passwords.

FTP over SSH resolves this problem by putting the FTP control connection through an SSH tunnel. Because FTP commands go over the control connection, and data is transmitted over a separate, independent data connection, FTP over SSH encrypts usernames and passwords (the control connection), but not the actual files transmitted. Files are transferred over an unencrypted data connection, which is faster and less demanding of the processor than encrypted data transfers would be.

Tunneling is generally complicated and difficult to set up, but Interarchy makes it simple. To use FTP over SSH, simply add “;ssh” to the host name when making an FTP connection. Assuming the server supports FTP over SSH, you should notice no other changes except that your username and password will now be securely encrypted. You can also try SFTP if FTP over SSH is not supported on your server.

See also the FTP, SSH and FTP over SSL-TLS sections.

FTP over SSL-TLS

The FTP protocol was created in 1985, when security was less of a concern on the Internet. As with the telnet protocol, the FTP protocol specifies a login sequence which involves sending the username and password in plain text between client and server. In recent years, as security has become more of a concern, this has become a problem for users who do not want intermediate parties to record their usernames and passwords.

FTP over SSL-TLS resolves this problem by putting the FTP control connection, and optionally the data connection, through an SSL tunnel. The username and password are transmitted over the control connection, while the files (and listings) are transmitted over separate data connections.

Interarchy is set to use FTP over SSL-TLS (AUTH TLS) by default for all non-anonymous FTP connections, if the server supports it. It will encrypt the control connection and data connection if possible. It will allow any certificates, including those that do not verify, so it will not provide security against spoofing servers, but generally this is less of a concern than clear text passwords. You can control these settings using in the SSL-TLS panel of the Preferences window.

Assuming the server supports FTP over SSL-TLS (AUTH TLS), you should notice no other changes except that your username and password will now be securely encrypted, however you may find problems with some servers that support SSL, but then fail to handle the data connection, in which case you should either disable FTP over SSL-TLS (in the SSL-TLS panel of the Preferences window) or try SFTP.

See also the FTP, SSH, SSL and FTP over SSH sections.

SFTP

The FTP protocol was created in 1985, when security was less of a concern on the Internet. As with the telnet protocol, the FTP protocol specifies a login sequence which involves sending the username and password in plain text between client and server. In recent years, as security has become more of a concern, this has become a problem for users who do not want intermediate parties to record their usernames and passwords or see the files they transfer.

SFTP resolves this problem by providing a new protocol, quite similar in many ways to FTP, which uses a single connection entirely encrypted in an SSH tunnel.

Because SFTP uses a single connection, there are no problems related to creating a data connection. And because the entire connection is encrypted, your username and password, as well as all transferred files are reasonably safe from view by intermediate parties.

SFTP supports only binary mode transfers, but Interarchy will still honor your text mode setting and transfer files in text mode as appropriate, including line ending encoding and ISO-8859-1 translation. Note that since the server will not support any concept of text mode, it is important that you configure your “SFTP remote text file line endings” preference in the Translation panel of the Preferences window appropriately for the server you are uploading to. Alternatively, you can ensure you use the appropriate encodings on your local file and transfer files in Binary mode.

See also the FTP over SSH and SSH sections.

SSH

The SSH protocol was designed to provide an easy modern replacement for telnet, FTP, and some related protocols (the “r* protocols”). Mac OS X includes OpenSSH, a free implementation of the SSH protocol suite.

The SSH suite provides an interactive session interface like telnet but encrypts the connection, so passwords are never transmitted in a readable format over the Internet. In addition, SSH can create an encrypted ‘tunnel’, through which arbitrary data can be forwarded. In this scenario, the SSH client and server bring up a tunnel connecting the two across the Internet, and all data transmitted through this tunnel is encrypted by the SSH software. A program on the client system, like an FTP client, can send data to the local end of the tunnel; the SSH client encrypts it and forwards it to the SSH server, and the SSH server decrypts the data and passes it along to the FTP server. Because the SSH tunnel is ‘transparent’ to the other client and server, this works even with a client and/or server that does not support SSH directly. The same process happens in reverse to transmit data from the server back to the client.

See also the FTP over SSH section.

SSL

The SSL protocol was designed to provide a secure layer on top of normal TCP sockets, allowing easy encryption of existing protocols with minimal changes to servers and clients.

SSL encryption is most commonly used in HTTPS (Secure HTTP) where it provides a secure layer for HTTP Web clients and servers.

SSL relies in part on signed certificates, however certificates are often generated ad hoc, so for many sites, the certificates fail to verify. Generally this is not a series issue, since the transferred data is still encrypted, however it does mean that unless the certificate is carefully verified, the site you are communicating with is not guaranteed to be who they say they are. Interarchy does not verify certificates by default (since encrypted passwords is deemed a more important goal), but you can configure it to verify certificates in the SSL-TLS panel of the Preferences window.

See also the FTP over SSL-TLS, SSH and HTTPS sections.

HTTP

The HTTP protocol is used to communicate between web clients and web servers, and typically involves a client making a request for a resource based on a URL, and the server responds with the data for that resource (typically a web page).

HTTP includes several forms of authentication, the basic form of which is essentially plain text usernames and passwords (the username and password is actually encoded, but can be easily decoded to retrieve the password).

See also the HTTPS section.

HTTPS

The HTTP protocol does not include any encryption, so data is sent in clear text. This is fine for public web pages, but not desirable for communications such as back transactions. The SSL protocol provides a way to encrypt a normal TCP socket, so HTTPS was born. HTTPS is simply the HTTP protocol over an SSL encryption layer.

See also the SSL and HTTP sections.

WebDAV

The WebDAV (Web-based Distributed Authoring and Versioning) protocol is an extension to the HTTP protocol to provide for distributed authoring and versioning. Typically it is used to provide raw disk space, an upload facility for websites, or a version control system for files.

Apple’s iDisks are implemented using WebDAV.

Amazon S3

Amazon S3 is a web service that can be used to store and retrieve any amount of data which gives developers access to the same highly scalable, reliable, fast, inexpensive data storage infrastructure that Amazon uses to run its own global network of web sites.

Interarchy provides direct access to this service, allowing you to upload or download files just as if you were accessing an FTP or SFTP site. You simply select the Amazon S3 protocol and use your AWS Access Key ID and AWS Secret Access Key just as you would your FTP username and password.

You must create an Amazon Web Services account, and Amazon S3 bandwidth and storage costs will apply.

Interarchy allows you to create buckets and directories, upload or download files, and set permissions (Private, Public Read, Public Read/Write, and Authenticated Read). You can even use a mirror or Net Disk directly to Amazon S3.

The following are some technical notes on Interarchy’s implementation of Amazon S3 access. For normal use, you probably never need to know any of this, Interarchy makes your Amazon S3 storage look just like nay other file system.

Amazon S3 file paths can be anything at all, there is no requirement for any kind of directory structure. For example, a valid Amazon S3 file might be found at “http://s3.amazonaws.com/stairways//./..//”. The Key would be “/./..//”. However, Interarchy simulates a directory structure based on slash (/) delimited paths. Interarchy does not support such unusual keys.

The top level (root) directory in Amazon S3 is a global name space of "buckets" which is shared by all Amazon S3 users, so you cannot create a top level folder that is not unique to you, nor any files in the root directory. Also bucket names must be 3 to 255 characters long and can contain only ASCII letters, numbers, underscores and dashes. Further, you are limited to 100 buckets. So you should generally create a top level directory named after your name or domain name (eg “stairways.com”) or containing your Amazon Access Key ID and then do your work in there.

Amazon S3 has no concept of directories, so Interarchy simulates them. If a file like “http://s3.amazonaws.com/stairways/folder/files/file.txt” exists, then Interarchy simulates directories for /stairways, /stairways/folder and /stairways/folder/files. If you create a directory in Interarchy, it actually creates a zero length file with a name ending in a slash. For example, if you create directory “http://s3.amazonaws.com/stairways/folder”, Interarchy actually creates a zero length file with bucket “stairways” and key “folder/”.

If you create a directory in the root, Interarchy creates a bucket for you, if available. Buckets are world-global, so they disappear almost as fast as .com domain names.

Amazon S3 only supports listing all files with a given prefix. So if you list a directory like /stairways/folder, Interarchy asks for all files starting with the prefix “/stairways/folder/”. This could be a very large listing, only to result in one subfolder being displayed. Note: Amazon S3 recently added support for Delimiter specification in listing requests which would resolve this problem, we will add support for it in the future.

Amazon S3 does not support renaming. Because of this, if you duplicate a folder, Interarchy will prompt you for the new name.

Interarchy supports Amazon S3’s “Canned Access Policies” (Private, Public Read, Public Read/Write, and Authenticated Read). You can configure the permissions for uploaded files using the Set Upload Permissions command in the Listing menu, or set them afterwards using the Get Info command in the Listing menu.

Passive Mode/Port Mode

The FTP protocol uses two connections, one control connection contains all the commands sent between Interarchy and the server (you can see these displayed in the Transcript window), and another data connection for each listing or file transferred.

Every time Interarchy gets a directory listing or uploads or downloads a file, a new data connection is created. The connection can be opened by Interarchy to the server (Passive Mode) or the connection can be opened by the server and connect back to Interarchy (Port Mode). This method of operation is probably responsible for more FTP failures than any other feature of the protocol.

In passive mode, Interarchy send the command “PASV”, the server opens a new listener on a new random port on the remote server, and sends back the response line that indicates the IP address and port number to connect to. Interarchy connects from a new random local port to the remote server as specified.

This will fail if:

In port mode, Interarchy opens a new listener on a new random local port, and sends your IP address and the new port number to the server with the “PORT” command. The server then connects back from a remote random port to Interarchy on the IP address and port specified.

This will fail if:

Note that some firewalls and some NAT routers are ‘smart’ enough to look in the FTP control connection and ‘make it work’, although as often as not this causes as many problems as it fixes.

Note also that using FTP over SSH or SSL-TLS may affect the behavior of the server, causing one or other of Port or Passive mode to succeed or fail.

So it is possible both passive mode and port mode can fail in may ways, and it is all too possible for passive mode to fail in one way and port mode to fail in another way leaving you without any options except to try to use SFTP instead, or possibly to try FTP over SSH or FTP over SSL-TLS.

See also the FTP and Firewalls sections.

Firewalls

A firewall is a program or device designed to block certain network connections. The idea is to limit the access that remote machines have to a local ‘protected’ network. While this is a worthwhile goal, the net result may not be helpful to you if you are one of those remote machines being blocked from access to a ‘local’ machine you should have access to. To this end, firewalls generally have holes in them that allow certain connections through.

Every time you connect, there may be many firewalls you have to pass through:

To connect to an HTTP server, you would typically connect from a local random port (random ports are normally 5000 or larger) to the HTTP port (port 80) or the HTTPS port (443). All the firewalls have to allow that to happen for the connection to take place.

To connect to an FTP server, you connect from a local random port to the FTP port (port 21). However to actually list a directory or upload or download a file, a second data connection needs to be made (see the Passive Mode/Port Mode section) and this requires a either a connection from a random local port to the FTP data port (port 20), or a connection from a random local or remote port to a random remote or local port. The latter case requires a very large hole in the firewall.

To connect to an FTP over SSH server, you connect from a local random port to the SSH port (port 22). However, the same data connection requirements as for FTP apply (see above).

To connect to an SFTP server, you connect from a local random port to the SSH port (port 22). Since data (listing and files) is transferred on the same connection, there are no other requirements.

Transfer Mode

Files can generally be transferred either as Text of Binary.

In Text mode, Interarchy will convert between local line endings and network line endings. This is generally good for text files, but will destroy binary files like disk images.

In Binary mode, Interarchy will transfer the bytes of the file unmodified. This is good for binary files, but not necessarily good for text files (eg scripts) as the line endings may not match the destination.

You can also ask Interarchy to choose the Transfer Mode based on the File Mapping for the transferred file. In this automatic mode, Interarchy uses the file extension, file creator/type (for local files) and/or MIME Type (for HTTP files) to select the appropriate transfer mode. To ensure consistency, mirroring always uses this automatic selection of Transfer Mode.

To change the Transfer Mode for a particular file extension, select the file in a Listing window and choose Get Info from the Listing menu and select the desired Encoding.

See also the File Mappings section.

File Mappings

Interarchy uses its internal File Mappings to determine information about files. The information is keyed off the file extension, file creator/type (for local files) and/or MIME Type (for HTTP files).

A File Mapping contains the following information:

To change the file mappings for a particular file extension, select a file with that extension in a Listing window and choose Get Info from the Listing menu.

File Converters

Interarchy can automatically convert files to and from specific formats using File Converter tools. We include several, or you can write your own. The File Converter is called to encode the file before it is uploaded, and called to decode the file after it is downloaded. If the File Converter returns without error (exit status 0), then the translated file is used, otherwise the original file is used.

File Converters are called by Interarchy as unix tools, either:

convert -U source dest

for uploading (encoding) or:

convert -D source dest

for downloading (decoding).

The source file will always exist and must not be modified in any way. The destination file may (probably will) exist and should be overwritten. For downloading, Interarchy will already have set the file creator, type and moddates which you may want to preserve.

Currently, we provide these File Converters:

gzip
a simple script (shown below) to use /usr/bin/gzip to encode the file, and /usr/bin/ungzip to decode it.
MacBinary
MacBinary encoding and decoding. MacBinary supports some meta data and date and resource forks, but has numerous limitations including 2GB file length limits and limited meta data support. See the MacBinary 3 Specification for details of the format.
Backup
Interarchy Backup encodes or decodes to an open format we have defined which includes all meta data (>4GB data and resource forks; Finder meta data; all file dates; owner, group and permissions; BSD flags; extended HFS attributes; ACLs). See the Interarchy Backup Specification for details of the format. Note that the Backup tool does not run with root permissions so it will not necessarily be able to restore all meta data.

Please note that there is much more to backups than just including all the file meta data. See the The Tao of Backups for more information. Interarchy can help with Coverage (at least your data anyway), Frequency (using Scheduling), Separation (using Amazon S3 or other remote service), Testing, and Security (using an encrypting tool (not provided)), but is less able to help with things like History, and Integrity. History, in particular is an important facility.

An example File Converter tool (which uses gzip/ungzip) follows. This could be used as a template to handle encryption or other conversions.

#!/bin/sh

# This Interarchy file converter is released in the Public Domain by Stairways Software
# Comments or bug reports can be sent to <support@stairways.com>

# usage:
# converter -U readonlyfile tempfile
# display "OK" or display an error message
# converter -D readonlyfile newfile
# display "OK" or display an error message

function usage () { 
  echo "Usage: convert-gz [-U|-D] source dest" > /dev/stderr
  exit 1
}

if [[ "$2" == "" || "$3" == "" ]]; then
  usage
fi
if [[ "$1" != "-U" && "$1" != "-D" ]]; then
  usage
fi

if [[ ! -r "$2" || ! -f "$2" ]]; then
  echo "Source file '$2' not readable" > /dev/stderr
  exit 2
fi

if [ "$1" == "-U" ]; then

  if gzip --quiet --stdout "$2" > "$3"; then
    exit 0
  else
    e=$?
    echo "gzip failed" > /dev/stderr
    exit $e
  fi

elif [ "$1" == "-D" ]; then

  if gunzip --quiet --stdout "$2" > "$3"; then
    exit 0
  else
    e=$?
    echo "gunzip failed" > /dev/stderr
    exit $e
  fi

else
  usage
fi

Bonjour

Interarchy can locate servers via Bonjour, Apple’s automatic network configuration protocol. If a server broadcasts its presence via Bonjour, as is the case with the Apache web server in Mac OS X 10.2, then the server will appear in the Bonjour collection as well as in Bonjour command in the Bookmarks menu and it will act the same as if you had bookmarked the site previously.

Bookmarks

Interarchy’s Bookmark implementation is powerful and flexible. Bookmarks can trigger most actions, individually or in sequence, and can be triggered within Interarchy, from the Finder, from the Dashboard, via AppleScript or from unix scripting. Interarchy offers a full hierarchical Bookmarks window to organize your Bookmarks. You can usually use the Add Bookmark command in the Bookmarks menu to create a new bookmark with the current window or selected item.

To edit a saved bookmark, select it in the Bookmarks window and click the toolbar Edit button. This will bring up an editing window to adjust the bookmark. Bookmark files can be saved and triggered anywhere, but typically they live in Interarchy’s preferences folder and are organized within the Bookmarks window.

Passwords are not saved in Bookmarks, but are generally read from the Keychain instead.

Scheduling

You can schedule any action to happen at a later time or periodically.

In the Connect to Server window, you can choose Schedule from the action pop-up menu. In a Queue window, you can click the toolbar Schedule button. In the Scheduled Bookmarks collection in the Bookmarks window, you can click the toolbar Edit button and then choose Schedule from the action pop-up menu.

You can choose to schedule a bookmark to execute:

Scheduled bookmarks appear in the Scheduled Bookmarks collection in the Bookmarks window, and you can enable, disable or delete them there.

See also the Bookmarks Window and How do I schedule a bookmark to run later? sections.

Mirroring

Mirroring is the process of making two distinct directories (including sub-directories) exactly identical. This is done by uploading, downloading or deleting files.

Warning: Mirroring (including Net Disks) in either direction can destroy a large number of files, so make sure you are mirroring the remote directory you expect, the local folder you expect, and always ensure you have good backups before commencing any mirroring.

Mirroring works by walking the local and remote directory tree simultaneously and checking each file or folder found there. Several different changes are possible:

For each difference, Interarchy determines which side is ‘correct’ and updates the other side.

Interarchy has three forms of mirrors:

Mirror Both Ways
use this if files may change both locally and remotely.
Mirror Download
use this if your remote files are always definitive and you never make any local changes that you want sent to the server.
Mirror Upload
use this if you local files are always definitive and you never make any remote changes that you want copied down to your Mac.

For example, say a new file named “new-file” has been created on the remote server, and a file named “old-file” has been changed on the local Mac, and now you mirror the two directories.

If you modify a file both locally and remotely and you are using Mirror Both Ways, then Interarchy will have to guess which file is more up to date. It will do this using the modification times of the files (this is the only case where modification times are compared for anything other than changes). Since its guess may be wrong, it will ensure no files are deleted by renaming the remote file with the extension “.bak”. If you later find that the wrong file was saved, simply rename the file back and modify it to force a resync. However in general, if you are editing the same file both locally and remotely, you will lose changes, so you should not do this.

For example, say you wanted to maintain your website. You have all the files on your Mac, all ready to be uploaded to your server. All you need to do is choose Connect to Server from the File menu, select the desired protocol (FTP, SFTP or WebDAV), and the Mirror action, then enter your server, path to your remote web directory (eg “/home/peter/Sites”), the username and password, select the local folder, and click the toolbar Mirror button. Of course, you probably are going to make some changes in the future, so you might want to save the mirror as a bookmark (choose Add Bookmark from the Bookmarks menu or choose Add to Bookmarks from the action pop-up menu) and then you can run the mirror from the Bookmarks window any time you make a change.

Normally mirroring will make the two directories exactly the same. This is often good, but occasionally you want to restrict the mirror to exclude certain files or folders, for example you might want to Mirror Upload your website from your local Mac files, but you might want to leave the log directory alone.

Files or folders are excluded if:

So in the example above, you could make an alias or symbolic link (it does not matter what it points to) or Mirror Place Holder file, name it “log” and place it in your Web folder.

Mirroring works by storing the local and remote modification date and local and remote file size for each file in the mirror folder. This cache is stored in the .InterarchyMirrorCacheData folder in the locate mirror folder, with a file name like Current Cache.1. Interarchy will then detect a file as being changed locally if the local modification date or file size changes, or changed remotely if the remote modification date or file size changes. It is imporortant to note that the local modification date is not compared to the remote modification date (except as described above for Mirror Both Ways when both local and remote files have changed). For Mirrors, if you delete the Current Cache file, the next run will (like the very first run) sync based solely on the file size and ignore (but remember) the modification dates.

One issue it is possible to run in to is if you have two very similar bookmarks, it is possible to end up with two different mirrors folder the same local and remote folder, which can proceed to ‘fight’ for control. If so, delete the extransous offending mirror bookmark and one or both of the Current Cache.N files and rerun the mirror.

Warning: If you delete the Current Cache file for a Net Disk, you will permanently disable the Net Disk as it cannot be regenerated.

See also the Net Disks, How do I set up a mirror? and How do I avoid mirroring certain files or folders? sections.

Net Disks

A Net Disk acts as a virtual disk which you can manipulate locally on your harddisk just like any other local folder on your harddisk. While the disk is mounted, Interarchy will automatically synchronize it with your remote directory.

Net Disks are simple and easy to use, and are a good way to maintain your personal website. They are suitable when you do not need strict control over updates, but are not suitable when you need to always keep your website self-consistent (such as a heavily used online shop for example). If you need more control, use a mirror instead (see the Mirroring section).

Warning: Mirroring (including Net Disks) in either direction can destroy a large number of files, so make sure you are mirroring the remote directory you expect, the local folder you expect, and always ensure you have good backups before commencing any mirroring.

Net Disks can use FTP, SFTP or WebDAV. SFTP is preferable since it is secure.

You create a new Net Disk by specifying the remote server, path, username and password. Interarchy will then perform the initial mirror in whichever direction you have chosen, making the local and remote site identical (probably both empty), and then mount the Net Disk on your desktop.

After that, you can make any local changes you want and Interarchy will periodically synchronize the local and remote files. The disk will appear in the Net Disks collection in the Bookmarks window, and when you are done with the disk, you can unmount it. When you next want to work with the Net Disk, just mount it again.

For more details on how to create a Net Disk, see the How do I set up a Net Disk? section, and for more details on the mirroring process, see the Mirroring section.

For maintaining a website, Mirror Upload is often the best choice. Try to avoid Mirror Both Ways if possible, since at some point you could have an unexpected change or a change on both sides and Interarchy may not do what you expect.

Also, do not forget about things like log files, forums and such, which may change frequently or unexpectedly. If you need to hide certain files from the mirroring process, there are ways to do that, see the How do I avoid mirroring certain files or folders? section.

Initially the mounted disk will be on your desktop and the unmounted disk will live in Interarchy’s preferences folder, however Interarchy will remember both locations if you move the disk, so if you prefer it to live somewhere else, move it while it is mounted or unmounted as desired (both locations can be the same in which case the disk will not move when mounted or unmounted).

You can operate on the files in the unmounted disk and, when you next mount the disk, Interarchy will synchronize the files.

Remember, for Mirror Download, any local changes you make will be lost the next time you mirror and, for Mirror Upload, any remote changes you make will be lost the next time you mirror.

See also the Mirroring, How do I set up a Net Disk? and How do I avoid mirroring certain files or folders? sections.

Mirror Mode

Mirroring (including both manual and Net Disks) operate in one of three modes: Mirror Both Ways, Mirror Download and Mirror Upload.

Mirror Both Ways transfers any changes on the local files to the remote server, and any changes on the remote server to the local folder.

Mirror Download transfers any changes on the remote server to the local folder. Any changes made to the local folder will be destroyed. The remote server is definitive and is never modified.

Mirror Upload transfers any changes in the local folder to the remote server. Any changes made to the remote server will be destoryed (keep in mind changes like log files). The local folder is definitive and is never modified. Typically you use this mode for maintaining your web site, make local changes and sending them to the server.

You can also specify exclusions which apply equally to any Mirror Mode.

See also the Mirroring, Net Disks, How do I set up a mirror? and How do I avoid mirroring certain files or folders? sections.

Auto Uploads

An Auto Upload is a mapping associating a local folder with a remote directory. When you drop a file or folder on to Interarchy (that is, on to the Interarchy application icon of the Interarchy Dock icon), if the file is inside an Auto Upload local folder, it will automatically be uploaded to the appropriate location inside the remote directory.

To create an Auto Upload, enter the location of the remote directory and select the corresponding local folder. Make sure the path specified exactly corresponds to the local folder (although the contents do not need to be identical as would be the case for a mirror).

When you drop a file (or folder) on to Interarchy, it will check whether the file is inside an Auto Upload. If so, it will find the relative location within the Auto Upload folder, and then upload the folder to the correct location within the remote destination as specified by the Auto Upload.

The uploaded file or folder is merged on to the remote site, so nothing is ever deleted, although remote files may be overwritten with new data. All files in an uploaded folder are uploaded, no mirroring happens.

You can view or edit your Auto Uploads in the Auto Uploads collection.

Note that since any changes you make and any Auto Upload that happens will not be noted by any existing mirror or FTP Disk, when you next sync a disk or run a mirror it will appear as if both the local and remote files have changed, so depending on the type of mirror, the local files will be uploaded again, or the remote files will be downloaded, or (for Mirror Both Ways) Interarchy will try to guess which of the two is more up to date and transfer. As such it would be best to only use an Auto Upload together with Mirror Upload.

Check Website

Interarchy can check the links on a website, either a local one on your harddisk, or a remote one on the web. Checking a website involves connecting to the HTTP (Web) server and scan the server looking for links and validating that they work.

To check a website, choose Connect to Server from the File menu and select the HTTP protocol (or File protocol) and Check Website action. Enter the URL of the starting web page you wish to scan from. To scan a local website, click the Choose button or drag the starting file or folder to the text field or button.

Normally Interarchy will read all pages referenced (directly or indirectly) from the starting page that are on the same server and in the same directory (or a sub-directory) as the starting page, and it will check all links referenced from any of those pages.

If you turn on the “Scan Just This Page” checkbox, only the starting page will be read, and all links referenced from it will be checked.

If you turn on the “Check Just Links On This Server” checkbox, only links on the same server as the starting page will be checked.

In the action pop-up menu (labeled with a gear and a down arrow), you can choose whether to take the action immediately, bookmark the action for later, schedule the action to happen at some later time or a repeating interval, or add the action to a Queue window.

Typically you will want to bookmark this action so that you can recheck the website at a later time, in which case you should choose Add Bookmark from the Bookmarks menu or choose Add to Bookmarks from the action pop-up menu to add the check to your bookmarks.

Once you start checking the site links, Interarchy will show a Check Website Report window which will display the errors as they are found.

Toolbars

At the top of many windows in Interarchy is a standard Mac OS X toolbar which you can customize by choosing Customize Toolbar from the View menu and which you can show or hide by using the View menu.

We have set up the default toolbars to give a reasonably well rounded experience, but you may want to configure the toolbars depending on your particular needs.

Action Menu

Near the bottom of several windows (for example, the Connect to Server window) there is an action pop-up menu which lets you choose between different actions, such as Add to Bookmarks or Schedule.

In the Connect to Server window, you can choose from these options:

Add to Bookmarks
this saves the action as a Bookmark in the Bookmarks collection in the Bookmarks window.
Schedule
perform the action at a scheduled time or repeating interval.
Once at
perform the action once at a particular time.
Add to Queue
add to a specific queue.
Add to New Queue
add to a new queue.

You do not really need to worry about this menu until you want to start getting the most out of Interarchy.

Internet Config

In 1994, several developers (including the Interarchy developers) created a shared preference system, for sharing Internet information among multiple programs. This system was called Internet Config. It stored two main types of information: user identification, including username, email server, signature, etc.; and preferred ‘helper’ applications to provide various services, identified by schemes , which formed the first part of URLs. The goal was to provide a single consistent database so multiple programs could share information, rather than requiring each Internet application to store the same information. Then, when a user received an email message containing the URL ftp://ftp.interarchy.com/ and clicked on it, their client could look up the preferred helper for “ftp” in Internet Config, and find Interarchy. It would then pass the URL on to Interarchy, which would do something useful with it. Similarly, the user might click a “mailto” URL in their web browser, and the browser could use Internet Config to find an email program to handle the URL.

After a few years, Apple built Internet Config into the Classic Mac OS as the Internet control panel, and Mac OS X uses it as the basis for the Internet section of System Preferences. Note: Mac OS X stores more information than is visible in System Preferences, and Apple provides no direct access to the other settings. Per convention, Interarchy uses the email address as a password when making anonymous FTP connections.

When Interarchy is run for the first time, it looks at the Internet Config database. If it is not already the preferred helper for the ftp: scheme, Interarchy will offer to handle it. Interarchy always registers itself for the interarchy: scheme, which it uses for various internal functions. For each of the bbftp:, traceroute: etc schemes, Interarchy will automatically register itself if it does not find a preexisting registration. In addition to these, Interarchy can handle http:, although this scheme is normally registered to a web browser, rather than Interarchy. Also, Interarchy uses the Internet Config Download Folder as the default download directory, and uses Internet Config for various proxy / firewall settings.

Interarchy no longer uses the Passive setting from Internet Config.

Interarchy also no longer uses the File Mappings from Internet Config due to the fact that many programs erroneously (or maliciously) modify the users settings for file mappings, often in ways that cause data corruption or user confusion. By using our own file mappings, we can also support more information such as double click action and viewer application.

Dashboard Widgets

In Mac OS X 10.4 Tiger, Apple introduced Dashboard, home to widgets (mini-applications) that let you perform common tasks and provide you with fast access to information.

Interarchy includes two widgets:

Interarchy Bookmark
a small widget that can contain an Interarchy Bookmark. Install the widget, then drag an Interarchy Bookmark, and while dragging enable Dashboard and drop the bookmark on the widget. After that, the widget acts as a bookmark, you can click it or drop files on it as appropriate.
Network Status
a widget showing a graph of the network usage for a specified interface. Interarchy must be running to collect the information.

To install a widget, choose Preferences from the Interarchy menu and display the Advanced panel of the Preferences window, then click the Install Dashboard Widgets button, which will open a disk image. Double click any widget you want installed, and then eject the disk image.

Automator Actions

In Mac OS X 10.4 Tiger, Apple introduced Automator, a graphical system for sequencing actions, intended to enable a wider number of users to script their systems.

Applications can provide Automator Actions to Automator, and Interarchy provides three such actions:

List URLs
takes an input list of URLs and lists the directory of each URL, returning a (usually longer) list of URLs. You can also recursively list the URLs.
Download URLs
takes an input list of URLs and downloads each URL, returning a list of files. You specify the download location and whether to automatically replace the files.
Upload Files
takes an input list of files and uploads each one, returning a list of URLs. You specify the remote directory and how to handle existing files and folders.

AppleScripting

Interarchy was one of the first AppleScriptable applications when System 7 was released over a decade ago and remains extensively scriptable and recordable.

To use Interarchy from AppleScript, open the Script Editor and open the Interarchy dictionary. You can:

You can use Interarchy to perform FTP or SFTP actions using list, fetch, view, edit, store, remove, mkdir, rename, sendcommand, setpermissions, setuploadpermissions, duplicate, and create commands.

You can perform HTTP actions using weblist, webfetch, webview, getwebsite, and checkwebsite commands.

You can perform actions on the local harddisk using filelist, filemkdir, filecreate, fileremove, filesetpermissions, filerename, fileview, and fileedit commands.

You can show almost any window in Interarchy using the show command.

You can perform mirrors (use extreme caution!) using mirror, mirrorupload and mirrordownload commands.

You can create and control Net Disks (use caution!) using newftpdisk, findftpdisk, mount/unmountftpdisk, revealftpdisk, deleteftpdisk and syncftpdisk commands.

You can also set and view Interarchy’s preferences.

There are several example AppleScripts in the Extras folder that comes with Interarchy.

Some examples include:

tell application "Interarchy"
  show wFTP
  list url "ftp://user:pass@host.com/somewhere/" with window
  get contents of front window
  set url of front window to "ftp://ftp.interarchy.com/"
  set bounds of front window to {30, 30, 400, 400}
  set contents of preference "UsePassive" to true
  set contents of preference "UsePassive:*:porthost.com:*" to false
end tell

See also the Preferences section.

Unix Scripting

You can script Interarchy from the terminal or a unix shell script in any one of a number of ways:

To use the interarchy tool, first ensure the tool is installed by clicking the Install “interarchy” tool button in the Advanced panel of the Preferences window. You will need Administrative Permissions to install the tool. Then make sure /usr/bin is in your path (or specify the path to the tool directly). If you do not have Administrative Permissions, but you know what you are doing, you can get the tool from inside the Interarchy application bundle.

Use man interarchy to read the help on the tool. A nice alias to use is:

getint  (/usr/bin/interarchy --background --output .)

which you can use to download a URL with Interarchy, keeping Interarchy in the background and saving the file to the current directory.

Interarchy Command Line Tool

To use the interarchy tool, first ensure the tool is installed by clicking the Install “interarchy” tool button in the Advanced panel of the Preferences window. You will need Administrative Permissions to install the tool. Then make sure /usr/bin is in your path (or specify the path to the tool directly). If you do not have Administrative Permissions, but you know what you are doing, you can get the tool from inside the Interarchy application bundle.

NAME
       interarchy - ask Interarchy to get a file by URL.


SYNOPSIS
       interarchy [options] [URL]


DESCRIPTION
       interarchy is a unix tool to interface to the Interarchy application.
       It generally runs without further user interaction.


URL
       The URL syntax is protocol dependent. You'll find a detailed
       description in RFC 2396.


OPTIONS
       -b, --background
       Launch Interarchy in the background if it's not already running,
       or keep it in the background if it is.


       -d, --debug, --verbose
       Makes the tool more verbose when working.  Mostly usable for
       debugging.


       -f, --foreground
       Launch Interarchy and/or bring it to the foreground.


       -h, --help
       Usage help.


       -m, --max-time seconds
       Maximum time in seconds the whole operation may take.  This is
       useful for preventing batch jobs from hanging for hours due to
       slow networks or links going down.


       -M, --manual
       Manual. Display the full help text.


       -o, --output file
       Write output to file instead of a local file named like the
       remote file we get.


       -s, --silent
       Silent mode.  Do not show error messages.  Makes interarchy
       silent.


       -v, --version
       Displays the full version of the command-line tool.


       -V, --short-version
       Display the short-form version number of the interarchy command-
       line tool.

       Although Interarchy will be found by its Bundle ID if it needs
       launching, you can specify the Interarchy application to ensure
       the right version is launched using the INTERARCHY APPLICATION PATH
       environment variable, which you can set with:

       setenv INTERARCHY APPLICATION PATH '/Applications/Interarchy'

Translations

Interarchy includes English, French, Japanese and German translations.

The French translation of Interarchy was done by Jean-Pierre Kuypers of Universite catholique de Louvain.

The Japanese translation of Interarchy was done by Pautha.

The German translation of Interarchy was done by Dragon Art.

Character Sets

When transferring files between computers, or when dealing with multiple languages, it is often necessary to consider character sets that are used to encode the actual characters into computer files.

Historically, character sets have been 8-bit, with lots of difference characters sets, one for each language (and often different for each operating system).

Eventually, Unicode was promulgated as a solution to this, by defining a 32-bit character set that encompasses pretty much all languages, together with the UTF-8 character encoding, which compactly represents ASCII and other popular 8-bit character sets while allowing the inclusion of all character sets.

Originally, the Mac used MacRoman (for English, and other character sets for other languages), Windows used Windows Latin 1, a superset of ISO-8859-1 (ISO Latin 1) as used by many unix systems. Since the Mac is now a unix system, things are even further confused.

Interarchy has traditionally supported MacRoman and ISO-8859-1. As of Interarchy 8, Interarchy internally handles all text as UTF-8. For listings, Interarchy assumes all FTP servers speak UTF-8 (although it is possible to configure specific servers as other character sets), and translated between UTF-8 and whatever encodings are specified for HTTP files. SFTP is defined to be UTF-8.

Interarchy no longer applies any character translations when transferring files in Text mode - you must ensure the character encoding of any file is correct.

See the glossary entries for ASCII, ISO-8859-1, UTF-8 and Unicode.

Administrative Permissions

Interarchy asks for Administrative Permissions in order to perform certain tasks, including:

Also, network administrators can configure the system so that Interarchy requires inside the Interarchy application bundle before watching traffic (see the Network Traffic Window section).

Uninstall

To uninstall Interarchy, you can just remove the Interarchy application folder and InterarchyCMPlugIn, and widgets, but if you want to remove all the parts of Interarchy, you can remove these:

The “~” means within your home folder.

Note that you may also want to specify a new FTP handler in Internet Config if Interarchy was configured as your FTP handler. A tool like MisFox will allow you to configure your Internet Config helpers.

PCAP Packet Filter Logic

You can specify a packet filter in the Network Traffic window using the BPF/PCAP packet filter logic which is very powerful, although a little cryptic.

The best documentation we have found for this logic is by Jordan Ritter for his ngrep tool, and he kindly allowed us to reproduce that documentation here. Most of this section is a paraphrase or direct quote of that documentation.

The filter logic selects which packets will be dumped. Only packets for which PCAP filter logic is “true” will be dumped.

The PCAP filter logic consists of one or more primitives. Primitives usually consist of an id (name or number) preceded by one or more qualifiers. There are three different kinds of qualifier:

type qualifiers
say what kind of thing the id name or number refers to. Possible types are host, net and port. For example, “host foo”, “net 128.3”, “port 20”. If there is no type qualifier, host is assumed.
dir qualifiers
specify a particular transfer direction to and/or from id. Possible directions are src, dst, src or dst and src and dst. For example, “src foo”, “dst net 128.3”, “src or dst port ftp-data”. If there is no dir qualifier, src or dst is assumed. For “null” link layers (i.e. point to point protocols such as PPP) the inbound and outbound qualifiers can be used to specify a desired direction.
proto qualifiers
are restricted to ip-only protocols. Possible protos are: tcp, udp and icmp. For example, “udp src foo” or “tcp port 21”. If there is no proto qualifier, all protocols consistent with the type are assumed. For example “src foo” means “ip and ((tcp or udp) src foo)”, “net bar” means “ip and (net bar)”, and “port 53” means “ip and ((tcp or udp) port 53)”.

In addition to the above, there are some special ‘primitive’ keywords that do not follow the pattern: gateway, broadcast, less, greater and arithmetic expressions. All of these are described below.

More complex filter expressions are built up by using the words and, or and not to combine primitives. For example, “host foo and not port ftp and not port ftp-data”. To save typing, identical qualifier lists can be omitted. For example, “tcp dst port ftp or ftp-data or domain” is exactly the same as “tcp dst port ftp or tcp dst port ftp-data or tcp dst port domain”.

Allowable primitives are:

dst host host
True if the IP destination field of the packet is host, which may be either an address or a name.
src host host
True if the IP source field of the packet is host.
host host
True if either the IP source or destination of the packet is host. Any of the above host expressions can be prepended with the keywords: ip, arp, or rarp. For example, “ip host foo”
ether dst ehost
True if the ethernet destination address is ehost which may be either a name from /etc/ethers or a number.
ether src ehost
True if the ethernet source address is ehost.
ether host ehost
True if either the ethernet source or destination address is ehost.
gateway host
True if the packet used host as a gateway, that is, the ethernet source or destination address was host but neither the IP source nor the IP destination was host. Host must be a name and must be found in both /etc/hosts and /etc/ethers. An equivalent expression is “ether host ehost and not host host which can be used with either names or numbers for host and ehost.
dst net net
True if the IP destination address of the packet has a network number of net which may be either a name from /etc/networks or a network number.
src net net
True if the IP source address of the packet has a network number of net.
net net
True if either the IP source or destination address of the packet has a network number of net.
net net mask mask
True if the IP address matches net with the specific mask. May be qualified with src or dst.
net net/len
True if the IP address matches net a netmask len bits wide. May be qualified with src or dst.
dst port port
True if the packet is ip/tcp or ip/udp and has a destination port value of port which can be a number or a name from /etc/services. If a name is used, both the port number and protocol are checked. If a number or ambiguous name is used, only the port number is checked. For example, “dst port 513” will display both tcp/login traffic and udp/who traffic, and “port domain” will display both tcp/domain and udp/domain traffic.
src port port
True if the packet has a source port value of port.
port port
True if either the source or destination port of the packet is port. Any of the above port expressions can be prepended with the keywords tcp or udp. For example, “tcp src port port” matches only tcp packets whose source port is port.
less length
True if the packet has a length less than or equal to length. This is equivalent to “len <= length”.
greater length
True if the packet has a length greater than or equal to length. This is equivalent to “len >= length”.
ip proto protocol
True if the packet is an ip packet of protocol type protocol. Protocol can be a number or one of the names tcp, udp or icmp. Note that the identifiers tcp and udp are also keywords and must be escaped via backslash (\).
ip broadcast
True if the packet is an IP broadcast packet. It checks for both the all-zeroes and all-ones broadcast conventions, and looks up the local subnet mask.
ip multicast
True if the packet is an IP multicast packet.
ip
Abbreviation for “ether proto ip”
tcp
Abbreviation for “ip proto tcp”
udp
Abbreviation for “ip proto udp”
icmp
Abbreviation for “ip proto icmp”
expr relop expr
True if the relation holds, where relop is one of >, <, >=, <=, =, !=, and expr is an arithmetic expression composed of integer constants (expressed in standard C syntax), the normal binary operators [+, -, *, /, &, |], a length operator, and special packet data accessors.

The length operator, len, gives the length of the packet.

To access data inside the packet, use the syntax “proto[expr:size]” where proto is one of ether, ip, tcp, udp, icmp and indicates the protocol layer for the index operation. The byte offset, relative to the indicated protocol layer, is given by expr. Size is optional and indicates the number of bytes in the field of interest - it can be either one, two, or four, and defaults to one. For example:

Primitives may be combined using:

Negation has highest precedence. Alternation and concatenation have equal precedence and associate left to right. Note that explicit and tokens, not juxtaposition, are required for concatenation.

If an identifier is given without a keyword, the most recent keyword is assumed. For example, “not host vs and ace” is short for “not host vs and host ace” which should not be confused with “not ( host vs or ace )”.

FTP List Specification

This section is a quote of a document written in 1994 describing the FTP Listing which is otherwise not specified or standardized anywhere.

FTP LIST Specification - Peter N Lewis, Feb 1994.

Target Audience:

FTP server authors and FTP client authors who wish to parse the LIST command to display information in a local (non-English or graphical) manner.

Premise:

There is no way to change existing servers in a reasonable amount of time.

For a long time the FTP LIST output has been unspecified and yet there are more and more programs each year that rely on this format in one way or another. To try to combat this problem I am proposing a specification of a LIST format that is easily decoded and very close to the current common format.

Please note that I am offering up this specification in the hope of increasing compatibility amongst servers and clients but no one is under any obligation to pay any attention to this document.

It is necessary to distinguish between the output format and the method of decoding the format since we wish to allow all decoders to interpret as many of the current versions of the LIST format, while trying to reduce the variation in the output.

The output should be something like this:

-rw-------  1 peter         848 Dec 14 11:22 00README.txt
or
- whatever you feel like 848 Dec 14 11:22 00README.txt

This specification only defines the first character, and the information (size/date/name) at the end of the line. The information between is at the discretion of the server author, although you need to be careful to avoid displaying something that will match the date format.

The first character should be one of [-dl]. “-” means a file, “d” means a directory and “l” means a link. In many cases it may be preferable to resolve the link and display it simply as a file or directory, since the client otherwise has no way to tell which it is except by trying to change directory into it (or by using the -p switch, see later). Currently the only way I have been able to find to determine if a link is a file or directory is to check if it has an extension (ie terminates in a dot followed by 1 to 3 characters) (this is obviously less than an ideal solution)

The rest of the line should be found by matching <space><3-letter-month-code><space><any><digit><space><digit|space><digit> (regexp: / ([A-Za-z][A-Za-z][A-Za-z]) .[0-9] [0-9 ][0-9]/ where $1 is a valid English month) and using the earliest such match (since that string may be part of the file name. The month name match should be case insensitive, and should match one of the twelve English three-letter month abbreviations: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec. Servers should always use the English version. Clients should of course display the date in the local language and format where possible. Some servers may currently use French month names, so you might like to also accept them (though it would be better to have the servers change to English).

Once you have found that, you can determine the file size by looking at the number immediately before that match location. This number may be missing or invalid for directories, links, or other ‘file types’ (and thus should be ignored except for files).

The date format is either:

  MMM DD hh:mm
OR
  MMM DD  YYYY
OR
  MMM DD YYYY

In the first case, the year is taken to be the most recent past occurrence of the date. Servers should choose to switch over well before this becomes close to allow for variations in the local time (not to mention user confusion).

And the file name follows the date and continues to the end of the line. If the file name is a link, it may include a pointer to the original, in which case it is in the form “name -> link”. This is really very bad, since that is also a perfectly valid file name under unix and other systems (especially the Macintosh). Servers should not do this where possible (resolve the link, correct the filesize and display as a file or directory is in general a better plan).

The information between the first character and the size (for files) or date (for other types) should be ignored. Servers may put any system dependent information here (although as noted about, you should avoid displaying anything that looks like a date).

When decoding, it is important to note that many implementations include a line at the start like “total <number>”. Clients should ignore any lines that do not match the described format. If no matches are found, and more than a few lines are read, then the server is probably non-conformant, so you might consider using the NLST command. Also, listings may include the special files “.” and “..”. I have no idea what you do with them or how you tell if they are special. Servers should not display them where possible.

Servers should try to support the important unix ls switches:

-p - add / on the end of directories, especially important for links.
-F - add /, *, @, = to the end of various files.
-l - in the long format described above (ie LIST should ignore it)
-R - recursive listing (some mirroring software relies on this)

Site maintainers should consider the problem of determining the type of a link and try to maintain the original name or at least the original extensions (this will also help users as well as client software).

Caveats:

A better solution would be to implement a structured list command, but this is not practical (even if this were done, it would be years before a reasonable percentage of servers were converted, and thus this document remains necessary).

Although it looks unix-centric, and English-centric, the intention is the exact opposite. By standardizing the list display, we allow clients to display dates in the local language, and listings in a local and/or graphical format.

BNF:

<list> ::= <line> <list>
         | <comment> <list>
         | <null>
<line> ::= <type-char> <stuff> <size> SPC <date> SPC <longname> <crlf>
<type-char> ::= "-" | "d" | "l"
<stuff> ::= <ascii-char> <stuff>
          | <null>
<size> ::= <digit> <size>
         | <null>
<date> ::= <month> SPC <day> SPC <time>
         | <month> SPC <day> SPC SPC <year>
         | <month> SPC <day> SPC <year> SPC
<month> ::= "Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun" | "Jul"
          | "Aug" | "Sep" | "Oct" | "Nov" | "Dec"
<day> ::= <digit> <digit>
        |   SPC   <digit>
<time> ::= <digit> <digit> ":" <digit> <digit>
         |   SPC   <digit> ":" <digit> <digit>
<year> ::= <digit> <digit> <digit> <digit>
<longname> ::= <name> SPC "->" SPC <name>
             | <name>
<name> ::= <ascii-char> <name>
         | <ascii-char>
<comment> ::= <stuff> <crlf>
<crlf> ::= CR LF
<null> ::=

Notes:

Month names are case insensitive.

<ascii-char> is any character from 1 to 255 of ISO 8859-1, excluding CR and LF.

Names in capital letters and without angle bracket (“<>”) quotes are names of ASCII control characters.

The ambiguity between <comment> and <line> must always be resolved in favor of <line>.

There is also an ambiguity between the first and second forms of <longname>. Resolution of this ambiguity is up to the programmer, but always preferring the first form is likely to give reasonable results. It may be possible to use the FTP NLST command to obtain disambiguating information.

More ambiguity: Should <stuff> ever contain a legal <date>, all bets are off!

Author:

Peter N Lewis peter@stairways.com.au

Contributors:

Quinn quinn@quinn.echidna.id.au

James W. Matthews James.W.Matthews@Dartmouth.EDU

Stephen Trier trier@ins.cwru.edu

Obviously, any errors in this document are my own!

How Trace Route Works

TTL stands for Time To Live. When an IP packet is sent, its TTL is set, which is the number of routers (hops) it can pass through before the packet is discarded. As the packet passes through a router, the TTL is decremented until, when the TTL reaches zero, the packet is destroyed and an ICMP “time exceeded” message is returned. The return message’s TTL is set by the terminating router when it creates the packet, and decremented normally.

Trace Route works by setting the TTL for a packet to 1, sending it towards the requested destination host, and listening for the reply. When the initiating machine receives a “time exceeded” response, it examines the packet to determine where the packet came from -- this identifies the machine one hop away. Then the tracing machine generates a new packet with TTL 2, and uses the response to determine the machine 2 hops away, and so on.

Unfortunately not all TCP stacks behave correctly. Some TCP stacks set the TTL for the ICMP “time exceeded” message to that of the message being killed. So if the TTL is 0, the packet will be killed by the next machine to which it is passed. This can have two effects on a trace. If the computer is an intermediate machine in the trace, the entry will remain blank. No information is returned to the machine conducting the trace because the “time exceeded” message never makes it back. If the machine you are doing a trace to has this bug in its TCP stack, return packets will not reach the originating machine unless the TTL is high enough to cover the round trip. So Trace Route will show a number of failed connections equal to n (the number of hops to the destination machine) minus 1. For example:

1  3/3  0.003 0.004 0.007 203.8.112.1  guppy.peter.com.au
2  3/3  0.184 0.193 0.198 139.130.177.2 iinet.gw.au
3  2/3  0.195 0.237 0.279 203.14.168.3  swing.iinet.net.au
4  3/3  0.183 0.297 0.370 130.95.97.1  muchacho.connections.uwa.edu.au
5  3/3  0.179 0.274 0.322 130.95.128.16 hacienda.uwa.edu.au
6  0/3
7  0/3
8  0/3
9  0/3
10 0/3
11 !TTL 0.194 0.218 0.261 130.95.1.150  redback.cs.uwa.oz.au 

Entries 6-10 are blank because redback.cs.uwa.oz.au has set the TTL incorrectly. redback.cs.uwa.oz.au is actually 6 hops away, but it shows n-1 (5, in this case) extra entries when traced.

Machines running MacTCP display this bug (redback.cs.uwa.oz.au , listed above, runs MacTCP). Open Transport handles TTLs correctly. The original distributions of 4.3 BSD had this error, so some UNIX machines display the problem.

The times in Trace Route are total round trip times in seconds. The Min/Avg/Max should increase from machine to machine n+1 , but they may not, for a variety of reasons. To start with, the times are based on the number of tests listed in the results column (generally 3 for a completed trace). Response times vary depending on network usage. So if the network is under heavy load when you are testing a machine 4 hops away but less when you start testing a machine 5 hops away, the time for machine #5 may be lower than the time for machine #4.

Additionally, returning a “time exceeded” message requires more computational time than routing a packet onwards. So if machine #4 is under heavy load when it is being probed by Trace Route , while machine #5 is not, the times for machine #4 may be higher than the times for machine #5. This is probably the case in the above example: machine #4 ( muchacho.connections.uwa.edu.au ) is heavily loaded, while machines #5 and #11 ( hacienda.uwa.edu.au and redback.cs.uwa.oz.au ) are less loaded, so they return the “time exceeded” message more quickly.

Finally, packet paths may not be the same coming and going. If the return path from machine #5 does not trace back through machine #4, the return time for machine #5 is independent of machine #4.

PCRE Regular Expression Syntax

This documentation comes from the PCRE documentation on the pattern syntax, see http://www.pcre.org/ for more details.

PCRE REGULAR EXPRESSION DETAILS

The syntax and semantics of the regular expressions supported by PCRE are described below. Regular expressions are also described in the Perl documentation and in a number of books, some of which have copious examples. Jeffrey Friedl’s “Mastering Regular Expressions”, published by O’Reilly, covers regular expressions in great detail. This description of PCRE’s regular expressions is intended as reference material.

A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern

  The quick brown fox

matches a portion of a subject string that is identical to itself. The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of metacharacters, which do not stand for themselves but instead are interpreted in some special way.

There are two different sets of metacharacters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the metacharacters are as follows:

  \      general escape character with several uses
  ^      assert start of string (or line, in multiline mode)
  $      assert end of string (or line, in multiline mode)
  .      match any character except newline (by default)
  [      start character class definition
  |      start of alternative branch
  (      start subpattern
  )      end subpattern
  ?      extends the meaning of (
         also 0 or 1 quantifier
         also quantifier minimizer
  *      0 or more quantifier
  +      1 or more quantifier
         also “possessive quantifier”
  {      start min/max quantifier

Part of a pattern that is in square brackets is called a “character class”. In a character class the only metacharacters are:

  \      general escape character
  ^      negate the class, but only if the first character
  -      indicates character range
  [      POSIX character class (only if followed by POSIX syntax)
  ]      terminates the character class

The following sections describe the use of each of the metacharacters.

BACKSLASH

The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.

For example, if you want to match a * character, you write \* in the pattern. This escaping action applies whether or not the following character would otherwise be interpreted as a metacharacter, so it is always safe to precede a non-alphanumeric with backslash to specify that it stands for itself. In particular, if you want to match a backslash, you write \\.

If a pattern is compiled with the PCRE EXTENDED option, whitespace in the pattern (other than in a character class) and characters between a # outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or # character as part of the pattern.

If you want to remove the special meaning from a sequence of characters, you can do so by putting them between \Q and \E. This is different from Perl in that $ and @ are handled as literals in \Q...\E sequences in PCRE, whereas in Perl, $ and @ cause variable interpolation. Note the following examples:

  Pattern            PCRE matches   Perl matches

  \Qabc$xyz\E        abc$xyz        abc followed by the contents of $xyz
  \Qabc\$xyz\E       abc\$xyz       abc\$xyz
  \Qabc\E\$\Qxyz\E   abc$xyz        abc$xyz

The \Q...\E sequence is recognized both inside and outside character classes.

Non-printing characters

A second use of backslash provides a way of encoding non-printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:

  \a        alarm, that is, the BEL character (hex 07)
  \cx       “control-x”, where x is any character
  \e        escape (hex 1B)
  \f        formfeed (hex 0C)
  \n        newline (hex 0A)
  \r        carriage return (hex 0D)
  \t        tab (hex 09)
  \ddd      character with octal code ddd, or backreference
  \xhh      character with hex code hh
  \x{hhh..} character with hex code hhh... (UTF-8 mode only)

The precise effect of \cx is as follows: if x is a lower case letter, it is converted to upper case. Then bit 6 of the character (hex 40) is inverted. Thus \cz becomes hex 1A, but \c{ becomes hex 3B, while \c; becomes hex 7B.

After \x, from zero to two hexadecimal digits are read (letters can be in upper or lower case). In UTF-8 mode, any number of hexadecimal digits may appear between \x{ and }, but the value of the character code must be less than 2**31 (that is, the maximum hexadecimal value is 7FFFFFFF). If characters other than hexadecimal digits appear between \x{ and }, or if there is no terminating }, this form of escape is not recognized. Instead, the initial \x will be interpreted as a basic hexadecimal escape, with no following digits, giving a character whose value is zero.

Characters whose value is less than 256 can be defined by either of the two syntaxes for \x when PCRE is in UTF-8 mode. There is no difference in the way they are handled. For example, \xdc is exactly the same as \x{dc}.

After \0 up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence \0\x\07 specifies two binary zeros followed by a BEL character (code value 7). Make sure you supply two digits after the initial zero if the pattern character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:

  \040   is another way of writing a space
  \40    is the same, provided there are fewer than 40 previous capturing subpatterns
  \7     is always a back reference
  \11    might be a back reference, or another way of writing a tab
  \011   is always a tab
  \0113  is a tab followed by the character “3”
  \113   might be a back reference, otherwise the character with octal code 113
  \377   might be a back reference, otherwise the byte consisting entirely of 1 bits
  \81    is either a back reference, or a binary zero followed by the two characters “8” and “1”

Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value or a single UTF-8 character (in UTF-8 mode) can be used both inside and outside character classes. In addition, inside a character class, the sequence \b is interpreted as the backspace character (hex 08), and the sequence \X is interpreted as the character “X”. Outside a character class, these sequences have different meanings (see below).

Generic character types

The third use of backslash is for specifying generic character types. The following are always recognized:

  \d     any decimal digit
  \D     any character that is not a decimal digit
  \s     any whitespace character
  \S     any character that is not a whitespace character
  \w     any “word” character
  \W     any “non-word” character

Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.

These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.

For compatibility with Perl, \s does not match the VT character (code 11). This makes it different from the the POSIX “space” class. The \s characters are HT (9), LF (10), FF (12), CR (13), and space (32).

A “word” character is an underscore or any character less than 256 that is a letter or digit. The definition of letters and digits is controlled by PCRE’s low-valued character tables, and may vary if locale-specific matching is taking place. For example, in the “fr FR” (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

In UTF-8 mode, characters with values greater than 128 never match \d, \s, or \w, and always match \D, \S, and \W. This is true even when Unicode character property support is available.

Unicode character properties

When PCRE is built with Unicode character property support, three additional escape sequences to match generic character types are available when UTF-8 mode is selected. They are:

 \p{xx}   a character with the xx property
 \P{xx}   a character without the xx property
 \X       an extended Unicode sequence

The property names represented by xx above are limited to the Unicode general category properties. Each character has exactly one such property, specified by a two-letter abbreviation. For compatibility with Perl, negation can be specified by including a circumflex between the opening brace and the property name. For example, \p{^Lu} is the same as \P{Lu}.

If only one letter is specified with \p or \P, it includes all the properties that start with that letter. In this case, in the absence of negation, the curly brackets in the escape sequence are optional; these two examples have the same effect:

  \p{L}
  \pL

The following property codes are supported:

  C     Other
  Cc    Control
  Cf    Format
  Cn    Unassigned
  Co    Private use
  Cs    Surrogate

  L     Letter
  Ll    Lower case letter
  Lm    Modifier letter
  Lo    Other letter
  Lt    Title case letter
  Lu    Upper case letter

  M     Mark
  Mc    Spacing mark
  Me    Enclosing mark
  Mn    Non-spacing mark

  N     Number
  Nd    Decimal number
  Nl    Letter number
  No    Other number

  P     Punctuation
  Pc    Connector punctuation
  Pd    Dash punctuation
  Pe    Close punctuation
  Pf    Final punctuation
  Pi    Initial punctuation
  Po    Other punctuation
  Ps    Open punctuation

  S     Symbol
  Sc    Currency symbol
  Sk    Modifier symbol
  Sm    Mathematical symbol
  So    Other symbol

  Z     Separator
  Zl    Line separator
  Zp    Paragraph separator
  Zs    Space separator

Extended properties such as “Greek” or “InMusicalSymbols” are not supported by PCRE.

Specifying caseless matching does not affect these escape sequences. For example, \p{Lu} always matches only upper case letters.

The \X escape matches any number of Unicode characters that form an extended Unicode sequence. \X is equivalent to

  (?>\PM\pM*)

That is, it matches a character without the “mark” property, followed by zero or more characters with the “mark” property, and treats the sequence as an atomic group (see below). Characters with the “mark” property are typically accents that affect the preceding character.

Matching characters by Unicode property is not fast, because PCRE has to search a structure that contains data for over fifteen thousand characters. That is why the traditional escape sequences such as \d and \w do not use Unicode properties in PCRE.

Simple assertions

The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below.

The backslashed assertions are:

  \b     matches at a word boundary
  \B     matches when not at a word boundary
  \A     matches at start of subject
  \Z     matches at end of subject or before newline at end
  \z     matches at end of subject
  \G     matches at first matching position in subject

These assertions may not appear in character classes (but note that \b has a different meaning, namely the backspace character, inside a character class).

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.

The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described in the next section) in that they only ever match at the very start and end of the subject string, whatever options are set. Thus, they are independent of multiline mode. These three assertions are not affected by the PCRE NOTBOL or PCRE NOTEOL options, which affect only the behavior of the circumflex and dollar metacharacters. The difference between \Z and \z is that \Z matches before a newline that is the last character of the string as well as at the end of the string, whereas \z matches only at the end.

CIRCUMFLEX AND DOLLAR

Outside a character class, in the default matching mode, the circumflex character is an assertion that is true only if the current matching point is at the start of the subject string. Inside a character class, circumflex has an entirely different meaning (see below).

Circumflex need not be the first character of the pattern if a number of alternatives are involved, but it should be the first thing in each alternative in which it appears if the pattern is ever to match that branch. If all possible alternatives start with a circumflex, that is, if the pattern is constrained to match only at the start of the subject, it is said to be an “anchored” pattern. (There are also other constructs that can cause a pattern to be anchored.)

A dollar character is an assertion that is true only if the current matching point is at the end of the subject string, or immediately before a newline character that is the last character in the string (by default). Dollar need not be the last character of the pattern if a number of alternatives are involved, but it should be the last item in any branch in which it appears. Dollar has no special meaning in a character class.

The meaning of dollar can be changed so that it matches only at the very end of the string, by setting the PCRE DOLLAR ENDONLY option at compile time. This does not affect the \Z assertion.

The meanings of the circumflex and dollar characters are changed if the PCRE MULTILINE option is set. When this is the case, they match immediately after and immediately before an internal newline character, respectively, in addition to matching at the start and end of the subject string. For example, the pattern /^abc$/ matches the subject string “def\nabc” (where \n represents a newline character) in multiline mode, but not otherwise. Consequently, patterns that are anchored in single line mode because all branches start with ^ are not anchored in multiline mode. The PCRE DOLLAR ENDONLY option is ignored if PCRE MULTILINE is set.

Note that the sequences \A, \Z, and \z can be used to match the start and end of the subject in both modes, and if all branches of a pattern start with \A it is always anchored, whether PCRE MULTILINE is set or not.

FULL STOP (PERIOD, DOT)

Outside a character class, a dot in the pattern matches any one character in the subject, including a non-printing character, but not (by default) newline. In UTF-8 mode, a dot matches any UTF-8 character, which might be more than one byte long, except (by default) newline. If the PCRE DOTALL option is set, dots match newlines as well. The handling of dot is entirely independent of the handling of circumflex and dollar, the only relationship being that they both involve newline characters. Dot has no special meaning in a character class.

MATCHING A SINGLE BYTE

Outside a character class, the escape sequence \C matches any one byte, both in and out of UTF-8 mode. Unlike a dot, it can match a newline. The feature is provided in Perl in order to match individual bytes in UTF-8 mode. Because it breaks up UTF-8 characters into individual bytes, what remains in the string may be a malformed UTF-8 string. For this reason, the \C escape sequence is best avoided.

PCRE does not allow \C to appear in lookbehind assertions (described below), because in UTF-8 mode this would make it impossible to calculate the length of the lookbehind.

SQUARE BRACKETS AND CHARACTER CLASSES

An opening square bracket introduces a character class, terminated by a closing square bracket. A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class, it should be the first data character in the class (after an initial circumflex, if present) or escaped with a backslash.

A character class matches a single character in the subject. In UTF-8 mode, the character may occupy more than one byte. A matched character must be in the set of characters defined by the class, unless the first character in the class definition is a circumflex, in which case the subject character must not be in the set defined by the class. If a circumflex is actually required as a member of the class, ensure it is not the first character, or escape it with a backslash.

For example, the character class [aeiou] matches any lower case vowel, while [^aeiou] matches any character that is not a lower case vowel. Note that a circumflex is just a convenient notation for specifying the characters that are in the class by enumerating those that are not. A class that starts with a circumflex is not an assertion: it still consumes a character from the subject string, and therefore it fails if the current pointer is at the end of the string.

In UTF-8 mode, characters with values greater than 255 can be included in a class as a literal string of bytes, or by using the \x{ escaping mechanism.

When caseless matching is set, any letters in a class represent both their upper case and lower case versions, so for example, a caseless [aeiou] matches “A” as well as “a”, and a caseless [^aeiou] does not match “A”, whereas a caseful version would. When running in UTF-8 mode, PCRE supports the concept of case for characters with values greater than 128 only when it is compiled with Unicode property support.

The newline character is never treated in any special way in character classes, whatever the setting of the PCRE DOTALL or PCRE MULTILINE options is. A class such as [^a] will always match a newline.

The minus (hyphen) character can be used to specify a range of characters in a character class. For example, [d-m] matches any letter between d and m, inclusive. If a minus character is required in a class, it must be escaped with a backslash or appear in a position where it cannot be interpreted as indicating a range, typically as the first or last character in the class.

It is not possible to have the literal character “]” as the end character of a range. A pattern such as [W-]46] is interpreted as a class of two characters (“W” and “-”) followed by a literal string “46]”, so it would match “W46]” or “-46]”. However, if the “]” is escaped with a backslash it is interpreted as the end of range, so [W-\]46] is interpreted as a class containing a range followed by two other characters. The octal or hexadecimal representation of “]” can also be used to end a range.

Ranges operate in the collating sequence of character values. They can also be used for characters specified numerically, for example [\000-\037]. In UTF-8 mode, ranges can include characters whose values are greater than 255, for example [\x{100}-\x{2ff}].

If a range that includes letters is used when caseless matching is set, it matches the letters in either case. For example, [W-c] is equivalent to [][\\^ `wxyzabc], matched caselessly, and in non-UTF-8 mode, if character tables for the “fr FR” locale are in use, [\xc8-\xcb] matches accented E characters in both cases. In UTF-8 mode, PCRE supports the concept of case for characters with values greater than 128 only when it is compiled with Unicode property support.

The character types \d, \D, \p, \P, \s, \S, \w, and \W may also appear in a character class, and add the characters that they match to the class. For example, [\dABCDEF] matches any hexadecimal digit. A circumflex can conveniently be used with the upper case character types to specify a more restricted set of characters than the matching lower case type. For example, the class [^\W] matches any letter or digit, but not underscore.

The only metacharacters that are recognized in character classes are backslash, hyphen (only where it can be interpreted as specifying a range), circumflex (only at the start), opening square bracket (only when it can be interpreted as introducing a POSIX class name - see the next section), and the terminating closing square bracket. However, escaping other non-alphanumeric characters does no harm.

POSIX CHARACTER CLASSES

Perl supports the POSIX notation for character classes. This uses names enclosed by [: and :] within the enclosing square brackets. PCRE also supports this notation. For example,

  [01[:alpha:]%]

matches “0”, “1”, any alphabetic character, or “%”. The supported class names are

  alnum    letters and digits
  alpha    letters
  ascii    character codes 0 - 127
  blank    space or tab only
  cntrl    control characters
  digit    decimal digits (same as \d)
  graph    printing characters, excluding space
  lower    lower case letters
  print    printing characters, including space
  punct    printing characters, excluding letters and digits
  space    white space (not quite the same as \s)
  upper    upper case letters
  word     “word” characters (same as \w)
  xdigit   hexadecimal digits

The “space” characters are HT (9), LF (10), VT (11), FF (12), CR (13), and space (32). Notice that this list includes the VT character (code 11). This makes “space” different to \s, which does not include VT (for Perl compatibility).

The name “word” is a Perl extension, and “blank” is a GNU extension from Perl 5.8. Another Perl extension is negation, which is indicated by a ^ character after the colon. For example,

  [12[:^digit:]]

matches “1”, “2”, or any non-digit. PCRE (and Perl) also recognize the POSIX syntax [.ch.] and [=ch=] where “ch” is a “collating element”, but these are not supported, and an error is given if they are encountered.

In UTF-8 mode, characters with values greater than 128 do not match any of the POSIX character classes.

VERTICAL BAR

Vertical bar characters are used to separate alternative patterns. For example, the pattern

  gilbert|sullivan

matches either “gilbert” or “sullivan”. Any number of alternatives may appear, and an empty alternative is permitted (matching the empty string). The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. If the alternatives are within a subpattern (defined below), “succeeds” means matching the rest of the main pattern as well as the alternative in the subpattern.

INTERNAL OPTION SETTING

The settings of the PCRE CASELESS, PCRE MULTILINE, PCRE DOTALL, and PCRE EXTENDED options can be changed from within the pattern by a sequence of Perl option letters enclosed between “(?” and “)”. The option letters are

  i  for PCRE CASELESS
  m  for PCRE MULTILINE
  s  for PCRE DOTALL
  x  for PCRE EXTENDED

For example, (?im) sets caseless, multiline matching. It is also possible to unset these options by preceding the letter with a hyphen, and a combined setting and unsetting such as (?im-sx), which sets PCRE CASELESS and PCRE MULTILINE while unsetting PCRE DOTALL and PCRE EXTENDED, is also permitted. If a letter appears both before and after the hyphen, the option is unset.

When an option change occurs at top level (that is, not inside subpattern parentheses), the change applies to the remainder of the pattern that follows.

An option change within a subpattern affects only that part of the current pattern that follows it, so

  (a(?i)b)c

matches abc and aBc and no other strings (assuming PCRE CASELESS is not used). By this means, options can be made to have different settings in different parts of the pattern. Any changes made in one alternative do carry on into subsequent branches within the same subpattern. For example,

  (a(?i)b|c)

matches “ab”, “aB”, “c”, and “C”, even though when matching “C” the first branch is abandoned before the option setting. This is because the effects of option settings happen at compile time. There would be some very weird behavior otherwise.

The PCRE-specific options PCRE UNGREEDY and PCRE EXTRA can be changed in the same way as the Perl-compatible options by using the characters U and X respectively. The (?X) flag setting is special in that it must always occur earlier in the pattern than any of the additional features it turns on, even when it is at top level. It is best to put it at the start.

SUBPATTERNS

Subpatterns are delimited by parentheses (round brackets), which can be nested. Turning part of a pattern into a subpattern does two things:

1. It localizes a set of alternatives. For example, the pattern

  cat(aract|erpillar|)

matches one of the words “cat”, “cataract”, or “caterpillar”. Without the parentheses, it would match “cataract”, “erpillar” or the empty string.

2. It sets up the subpattern as a capturing subpattern. This means that, when the whole pattern matches, that portion of the subject string that matched the subpattern is passed back to the caller. Opening parentheses are counted from left to right (starting from 1) to obtain numbers for the capturing subpatterns.

For example, if the string “the red king” is matched against the pattern

  the ((red|white) (king|queen))

the captured substrings are “red king”, “red”, and “king”, and are numbered 1, 2, and 3, respectively.

The fact that plain parentheses fulfill two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by a question mark and a colon, the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. For example, if the string “the white queen” is matched against the pattern

  the ((?:red|white) (king|queen))

the captured substrings are “white queen” and “queen”, and are numbered 1 and 2.

As a convenient shorthand, if any option settings are required at the start of a non-capturing subpattern, the option letters may appear between the “?” and the “:”. Thus the two patterns

  (?i:saturday|sunday)
  (?:(?i)saturday|sunday)

match exactly the same set of strings. Because alternative branches are tried from left to right, and options are not reset until the end of the subpattern is reached, an option setting in one branch does affect subsequent branches, so the above patterns match “SUNDAY” as well as “Saturday”.

REPETITION

Repetition is specified by quantifiers, which can follow any of the following items:

  a literal data character
  the . metacharacter
  the \C escape sequence
  the \X escape sequence (in UTF-8 mode with Unicode properties)
  an escape such as \d that matches a single character
  a character class
  a back reference (see next section)
  a parenthesized subpattern (unless it is an assertion)

The general repetition quantifier specifies a minimum and maximum number of permitted matches, by giving the two numbers in curly brackets (braces), separated by a comma. The numbers must be less than 65536, and the first must be less than or equal to the second. For example:

  z{2,4}

matches “zz”, “zzz”, or “zzzz”. A closing brace on its own is not a special character. If the second number is omitted, but the comma is present, there is no upper limit; if the second number and the comma are both omitted, the quantifier specifies an exact number of required matches. Thus

  [aeiou]{3,}

matches at least 3 successive vowels, but may match many more, while

  \d{8}

matches exactly 8 digits. An opening curly bracket that appears in a position where a quantifier is not allowed, or one that does not match the syntax of a quantifier, is taken as a literal character. For example, {,6} is not a quantifier, but a literal string of four characters.

In UTF-8 mode, quantifiers apply to UTF-8 characters rather than to individual bytes. Thus, for example, \x{100}{2} matches two UTF-8 characters, each of which is represented by a two-byte sequence. Similarly, when Unicode property support is available, \X{3} matches three Unicode extended sequences, each of which may be several bytes long (and they may be of different lengths).

The quantifier {0} is permitted, causing the expression to behave as if the previous item and the quantifier were not present.

For convenience (and historical compatibility) the three most common quantifiers have single-character abbreviations:

  *    is equivalent to {0,}
  +    is equivalent to {1,}
  ?    is equivalent to {0,1}

It is possible to construct infinite loops by following a subpattern that can match no characters with a quantifier that has no upper limit, for example:

  (a?)*

Earlier versions of Perl and PCRE used to give an error at compile time for such patterns. However, because there are cases where this can be useful, such patterns are now accepted, but if any repetition of the subpattern does in fact match no characters, the loop is forcibly broken.

By default, the quantifiers are “greedy”, that is, they match as much as possible (up to the maximum number of permitted times), without causing the rest of the pattern to fail. The classic example of where this gives problems is in trying to match comments in C programs. These appear between /* and */ and within the comment, individual * and / characters may appear. An attempt to match C comments by applying the pattern

  /\*.*\*/

to the string

  /* first comment */  not comment  /* second comment */

fails, because it matches the entire string owing to the greediness of the .* item.

However, if a quantifier is followed by a question mark, it ceases to be greedy, and instead matches the minimum number of times possible, so the pattern

  /\*.*?\*/

does the right thing with the C comments. The meaning of the various quantifiers is not otherwise changed, just the preferred number of matches. Do not confuse this use of question mark with its use as a quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in

  \d??\d

which matches one digit by preference, but can match two if that is the only way the rest of the pattern matches.

When a capturing subpattern is repeated, the value captured is the substring that matched the final iteration. For example, after

  (tweedle[dume]{3}\s*)+

has matched “tweedledum tweedledee” the value of the captured substring is “tweedledee”. However, if there are nested capturing subpatterns, the corresponding captured values may have been set in previous iterations. For example, after

  /(a|(b))+/

matches “aba” the value of the second captured substring is “b”.

ATOMIC GROUPING AND POSSESSIVE QUANTIFIERS

With both maximizing and minimizing repetition, failure of what follows normally causes the repeated item to be re-evaluated to see if a different number of repeats allows the rest of the pattern to match. Sometimes it is useful to prevent this, either to change the nature of the match, or to cause it fail earlier than it otherwise might, when the author of the pattern knows there is no point in carrying on.

Consider, for example, the pattern \d+foo when applied to the subject line

  123456bar

After matching all 6 digits and then failing to match “foo”, the normal action of the matcher is to try again with only 5 digits matching the \d+ item, and then with 4, and so on, before ultimately failing. “Atomic grouping” (a term taken from Jeffrey Friedl’s book) provides the means for specifying that once a subpattern has matched, it is not to be re-evaluated in this way.

If we use atomic grouping for the previous example, the matcher would give up immediately on failing to match “foo” the first time. The notation is a kind of special parenthesis, starting with (?> as in this example:

  (?>\d+)foo

This kind of parenthesis “locks up” the part of the pattern it contains once it has matched, and a failure further into the pattern is prevented from backtracking into it. Backtracking past it to previous items, however, works as normal.

An alternative description is that a subpattern of this type matches the string of characters that an identical standalone pattern would match, if anchored at the current point in the subject string.

Atomic grouping subpatterns are not capturing subpatterns. Simple cases such as the above example can be thought of as a maximizing repeat that must swallow everything it can. So, while both \d+ and \d+? are prepared to adjust the number of digits they match in order to make the rest of the pattern match, (?>\d+) can only match an entire sequence of digits.

Atomic groups in general can of course contain arbitrarily complicated subpatterns, and can be nested. However, when the subpattern for an atomic group is just a single repeated item, as in the example above, a simpler notation, called a “possessive quantifier” can be used. This consists of an additional + character following a quantifier. Using this notation, the previous example can be rewritten as

  \d++foo

Possessive quantifiers are always greedy; the setting of the PCRE UNGREEDY option is ignored. They are a convenient notation for the simpler forms of atomic group. However, there is no difference in the meaning or processing of a possessive quantifier and the equivalent atomic group.

The possessive quantifier syntax is an extension to the Perl syntax. It originates in Sun’s Java package.

When a pattern contains an unlimited repeat inside a subpattern that can itself be repeated an unlimited number of times, the use of an atomic group is the only way to avoid some failing matches taking a very long time indeed. The pattern

  (\D+|<\d+>)*[!?]

matches an unlimited number of substrings that either consist of non-digits, or digits enclosed in <>, followed by either ! or ?. When it matches, it runs quickly. However, if it is applied to

  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

it takes a long time before reporting failure. This is because the string can be divided between the internal \D+ repeat and the external * repeat in a large number of ways, and all have to be tried. (The example uses [!?] rather than a single character at the end, because both PCRE and Perl have an optimization that allows for fast failure when a single character is used. They remember the last single character that is required for a match, and fail early if it is not present in the string.) If the pattern is changed so that it uses an atomic group, like this:

  ((?>\D+)|<\d+>)*[!?]

sequences of non-digits cannot be broken, and failure happens quickly.

BACK REFERENCES

Outside a character class, a backslash followed by a digit greater than 0 (and possibly further digits) is a back reference to a capturing subpattern earlier (that is, to its left) in the pattern, provided there have been that many previous capturing left parentheses.

However, if the decimal number following the backslash is less than 10, it is always taken as a back reference, and causes an error only if there are not that many capturing left parentheses in the entire pattern. In other words, the parentheses that are referenced need not be to the left of the reference for numbers less than 10. See the subsection entitled “Non-printing characters” above for further details of the handling of digits following a backslash.

A back reference matches whatever actually matched the capturing subpattern in the current subject string, rather than anything matching the subpattern itself (see “Subpatterns as subroutines” below for a way of doing that). So the pattern

  (sens|respons)e and \1ibility

matches “sense and sensibility” and “response and responsibility”, but not “sense and responsibility”. If caseful matching is in force at the time of the back reference, the case of letters is relevant. For example,

  ((?i)rah)\s+\1

matches “rah rah” and “RAH RAH”, but not “RAH rah”, even though the original capturing subpattern is matched caselessly.

There may be more than one back reference to the same subpattern. If a subpattern has not actually been used in a particular match, any back references to it always fail. For example, the pattern

  (a|(bc))\2

always fails if it starts to match “a” rather than “bc”. Because there may be many capturing parentheses in a pattern, all digits following the backslash are taken as part of a potential back reference number. If the pattern continues with a digit character, some delimiter must be used to terminate the back reference. If the PCRE EXTENDED option is set, this can be whitespace. Otherwise an empty comment (see “Comments” below) can be used.

A back reference that occurs inside the parentheses to which it refers fails when the subpattern is first used, so, for example, (a\1) never matches. However, such references can be useful inside repeated subpatterns. For example, the pattern

  (a|b\1)+

matches any number of “a”s and also “aba”, “ababbaa” etc. At each iteration of the subpattern, the back reference matches the character string corresponding to the previous iteration. In order for this to work, the pattern must be such that the first iteration does not need to match the back reference. This can be done using alternation, as in the example above, or by a quantifier with a minimum of zero.

ASSERTIONS

An assertion is a test on the characters following or preceding the current matching point that does not actually consume any characters. The simple assertions coded as \b, \B, \A, \G, \Z, \z, ^ and $ are described above.

More complicated assertions are coded as subpatterns. There are two kinds: those that look ahead of the current position in the subject string, and those that look behind it. An assertion subpattern is matched in the normal way, except that it does not cause the current matching position to be changed.

Assertion subpatterns are not capturing subpatterns, and may not be repeated, because it makes no sense to assert the same thing several times. If any kind of assertion contains capturing subpatterns within it, these are counted for the purposes of numbering the capturing subpatterns in the whole pattern. However, substring capturing is carried out only for positive assertions, because it does not make sense for negative assertions.

Lookahead assertions

Lookahead assertions start with (?= for positive assertions and (?! for negative assertions. For example,

  \w+(?=;)

matches a word followed by a semicolon, but does not include the semicolon in the match, and

  foo(?!bar)

matches any occurrence of “foo” that is not followed by “bar”. Note that the apparently similar pattern

  (?!foo)bar

does not find an occurrence of “bar” that is preceded by something other than “foo”; it finds any occurrence of “bar” whatsoever, because the assertion (?!foo) is always true when the next three characters are “bar”. A lookbehind assertion is needed to achieve the other effect.

If you want to force a matching failure at some point in a pattern, the most convenient way to do it is with (?!) because an empty string always matches, so an assertion that requires there not to be an empty string must always fail.

Lookbehind assertions

Lookbehind assertions start with (?<= for positive assertions and (?<! for negative assertions. For example,

  (?<!foo)bar

does find an occurrence of “bar” that is not preceded by “foo”. The contents of a lookbehind assertion are restricted such that all the strings it matches must have a fixed length. However, if there are several alternatives, they do not all have to have the same fixed length. Thus

  (?<=bullock|donkey)

is permitted, but

  (?<!dogs?|cats?)

causes an error at compile time. Branches that match different length strings are permitted only at the top level of a lookbehind assertion. This is an extension compared with Perl (at least for 5.8), which requires all branches to match the same length of string. An assertion such as

  (?<=ab(c|de))

is not permitted, because its single top-level branch can match two different lengths, but it is acceptable if rewritten to use two top-level branches:

  (?<=abc|abde)

The implementation of lookbehind assertions is, for each alternative, to temporarily move the current position back by the fixed width and then try to match. If there are insufficient characters before the current position, the match is deemed to fail.

PCRE does not allow the \C escape (which matches a single byte in UTF-8 mode) to appear in lookbehind assertions, because it makes it impossible to calculate the length of the lookbehind. The \X escape, which can match different numbers of bytes, is also not permitted.

Atomic groups can be used in conjunction with lookbehind assertions to specify efficient matching at the end of the subject string. Consider a simple pattern such as

  abcd$

when applied to a long string that does not match. Because matching proceeds from left to right, PCRE will look for each “a” in the subject and then see if what follows matches the rest of the pattern. If the pattern is specified as

  ^.*abcd$

the initial .* matches the entire string at first, but when this fails (because there is no following “a”), it backtracks to match all but the last character, then all but the last two characters, and so on. Once again the search for “a” covers the entire string, from right to left, so we are no better off. However, if the pattern is written as

  ^(?>.*)(?<=abcd)

or, equivalently, using the possessive quantifier syntax,

  ^.*+(?<=abcd)

there can be no backtracking for the .* item; it can match only the entire string. The subsequent lookbehind assertion does a single test on the last four characters. If it fails, the match fails immediately. For long strings, this approach makes a significant difference to the processing time.

Using multiple assertions

Several assertions (of any sort) may occur in succession. For example,

  (?<=\d{3})(?<!999)foo

matches “foo” preceded by three digits that are not “999”. Notice that each of the assertions is applied independently at the same point in the subject string. First there is a check that the previous three characters are all digits, and then there is a check that the same three characters are not “999”. This pattern does not match “foo” preceded by six characters, the first of which are digits and the last three of which are not “999”. For example, it doesn’t match “123abcfoo”. A pattern to do that is

  (?<=\d{3}...)(?<!999)foo

This time the first assertion looks at the preceding six characters, checking that the first three are digits, and then the second assertion checks that the preceding three characters are not “999”.

Assertions can be nested in any combination. For example,

  (?<=(?<!foo)bar)baz

matches an occurrence of “baz” that is preceded by “bar” which in turn is not preceded by “foo”, while

  (?<=\d{3}(?!999)...)foo

is another pattern that matches “foo” preceded by three digits and any three characters that are not “999”.

CONDITIONAL SUBPATTERNS

It is possible to cause the matching process to obey a subpattern conditionally or to choose between two alternative subpatterns, depending on the result of an assertion, or whether a previous capturing subpattern matched or not. The two possible forms of conditional subpattern are

  (?(condition)yes-pattern)
  (?(condition)yes-pattern|no-pattern)

If the condition is satisfied, the yes-pattern is used; otherwise the no-pattern (if present) is used. If there are more than two alternatives in the subpattern, a compile-time error occurs.

There are three kinds of condition. If the text between the parentheses consists of a sequence of digits, the condition is satisfied if the capturing subpattern of that number has previously matched. The number must be greater than zero. Consider the following pattern, which contains non-significant white space to make it more readable (assume the PCRE EXTENDED option) and to divide it into three parts for ease of discussion:

  ( \( )?    [^()]+    (?(1) \) )

The first part matches an optional opening parenthesis, and if that character is present, sets it as the first captured substring. The second part matches one or more characters that are not parentheses. The third part is a conditional subpattern that tests whether the first set of parentheses matched or not. If they did, that is, if subject started with an opening parenthesis, the condition is true, and so the yes-pattern is executed and a closing parenthesis is required. Otherwise, since no-pattern is not present, the subpattern matches nothing. In other words, this pattern matches a sequence of non-parentheses, optionally enclosed in parentheses.

If the condition is the string (R), it is satisfied if a recursive call to the pattern or subpattern has been made. At “top level”, the condition is false. This is a PCRE extension. Recursive patterns are described in the next section.

If the condition is not a sequence of digits or (R), it must be an assertion. This may be a positive or negative lookahead or lookbehind assertion. Consider this pattern, again containing non-significant white space, and with the two alternatives on the second line:

  (?(?=[^a-z]*[a-z])
  \d{2}-[a-z]{3}-\d{2}  |  \d{2}-\d{2}-\d{2} )

The condition is a positive lookahead assertion that matches an optional sequence of non-letters followed by a letter. In other words, it tests for the presence of at least one letter in the subject. If a letter is found, the subject is matched against the first alternative; otherwise it is matched against the second. This pattern matches strings in one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.

COMMENTS

The sequence (?# marks the start of a comment that continues up to the next closing parenthesis. Nested parentheses are not permitted. The characters that make up a comment play no part in the pattern matching at all.

If the PCRE EXTENDED option is set, an unescaped # character outside a character class introduces a comment that continues up to the next newline character in the pattern.

RECURSIVE PATTERNS

Consider the problem of matching a string in parentheses, allowing for unlimited nested parentheses. Without the use of recursion, the best that can be done is to use a pattern that matches up to some fixed depth of nesting. It is not possible to handle an arbitrary nesting depth. Perl provides a facility that allows regular expressions to recurse (amongst other things). It does this by interpolating Perl code in the expression at run time, and the code can refer to the expression itself. A Perl pattern to solve the parentheses problem can be created like this:

  $re = qr{\( (?: (?>[^()]+) | (?p{$re}) )* \)}x;

The (?p{...}) item interpolates Perl code at run time, and in this case refers recursively to the pattern in which it appears. Obviously, PCRE cannot support the interpolation of Perl code. Instead, it supports some special syntax for recursion of the entire pattern, and also for individual subpattern recursion.

The special item that consists of (? followed by a number greater than zero and a closing parenthesis is a recursive call of the subpattern of the given number, provided that it occurs inside that subpattern. (If not, it is a “subroutine” call, which is described in the next section.) The special item (?R) is a recursive call of the entire regular expression.

For example, this PCRE pattern solves the nested parentheses problem (assume the PCRE EXTENDED option is set so that white space is ignored):

  \( ( (?>[^()]+) | (?R) )* \)

First it matches an opening parenthesis. Then it matches any number of substrings which can either be a sequence of non-parentheses, or a recursive match of the pattern itself (that is a correctly parenthesized substring). Finally there is a closing parenthesis.

If this were part of a larger pattern, you would not want to recurse the entire pattern, so instead you could use this:

  ( \( ( (?>[^()]+) | (?1) )* \) )

We have put the pattern into parentheses, and caused the recursion to refer to them instead of the whole pattern. In a larger pattern, keeping track of parenthesis numbers can be tricky. It may be more convenient to use named parentheses instead. For this, PCRE uses (?P>name), which is an extension to the Python syntax that PCRE uses for named parentheses (Perl does not provide named parentheses). We could rewrite the above example as follows:

  (?P<pn> \( ( (?>[^()]+) | (?P>pn) )* \) )

This particular example pattern contains nested unlimited repeats, and so the use of atomic grouping for matching strings of non-parentheses is important when applying the pattern to strings that do not match. For example, when this pattern is applied to

  (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()

it yields “no match” quickly. However, if atomic grouping is not used, the match runs for a very long time indeed because there are so many different ways the + and * repeats can carve up the subject, and all have to be tested before failure can be reported.

At the end of a match, the values set for any capturing subpatterns are those from the outermost level of the recursion at which the subpattern value is set. If the pattern above is matched against

  (ab(cd)ef)

the value for the capturing parentheses is “ef”, which is the last value taken on at the top level. If additional parentheses are added, giving

  \( ( ( (?>[^()]+) | (?R) )* ) \)
     ^                        ^
     ^                        ^

Do not confuse the (?R) item with the condition (R), which tests for recursion. Consider this pattern, which matches text in angle brackets, allowing for arbitrary nesting. Only digits are allowed in nested brackets (that is, when recursing), whereas any characters are permitted at the outer level.

  < (?: (?(R) \d++  | [^<>]*+) | (?R)) * >

In this pattern, (?(R) is the start of a conditional subpattern, with two different alternatives for the recursive and non-recursive cases. The (?R) item is the actual recursive call.

SUBPATTERNS AS SUBROUTINES

If the syntax for a recursive subpattern reference is used outside the parentheses to which it refers, it operates like a subroutine in a programming language. An earlier example pointed out that the pattern

  (sens|respons)e and \1ibility

matches “sense and sensibility” and “response and responsibility”, but not “sense and responsibility”. If instead the pattern

  (sens|respons)e and (?1)ibility

is used, it does match “sense and responsibility” as well as the other two strings. Such references must, however, follow the subpattern to which they refer.

Continue on to Administrative Details

Feedback Form

Please provide any feedback you may have


Email Address:
Subject:
Feedback:


Your email address is appreciated but is not required and will not be saved.
It will be used only for responding to or clarifying this feedback.

Documentation

Interarchy

Old Documentation

Powered By Interarchy