IPC Advanced
IPC Advanced
Samuel J. Leffler
Robert S. Fabry
William N. Joy
Phil Lapsley
Computer Systems Research Group
Department of Electrical Engineering and Computer Science
University of California, Berkeley
Berkeley, California 94720
Steve Miller
Chris Torek
Heterogeneous Systems Laboratory
Department of Computer Science
University of Maryland, College Park
College Park, Maryland 20742
ABSTRACT
* UNIX is a trademark of UNIX System Laboratories, Inc. in the US and some other countries.
PSD:21-2 Advanced 4.4BSD IPC Tutorial
1. INTRODUCTION
One of the most important additions to UNIX in 4.2BSD was interprocess communication. These facilities
were the result of more than two years of discussion and research. The facilities provided in 4.2BSD incor-
porated many of the ideas from current research, while trying to maintain the UNIX philosophy of simplic-
ity and conciseness. The 4.3BSD release of Berkeley UNIX improved upon some of the IPC facilities
while providing an upward-compatible interface. 4.4BSD adds support for ISO protocols and IP multicast-
ing. The BSD interprocess communication facilities have become a defacto standard for UNIX.
UNIX has previously been very weak in the area of interprocess communication. Prior to the 4BSD
facilities, the only standard mechanism which allowed two processes to communicate were pipes (the mpx
files which were part of Version 7 were experimental). Unfortunately, pipes are very restrictive in that the
two communicating processes must be related through a common ancestor. Further, the semantics of pipes
makes them almost impossible to maintain in a distributed environment.
Earlier attempts at extending the IPC facilities of UNIX have met with mixed reaction. The majority
of the problems have been related to the fact that these facilities have been tied to the UNIX file system,
either through naming or implementation. Consequently, the IPC facilities provided in 4.2BSD were
designed as a totally independent subsystem. The BSD IPC allows processes to rendezvous in many ways.
Processes may rendezvous through a UNIX file system-like name space (a space where all names are path
names) as well as through a network name space. In fact, new name spaces may be added at a future time
with only minor changes visible to users. Further, the communication facilities have been extended to
include more than the simple byte stream provided by a pipe. These extensions have resulted in a com-
pletely new part of the system which users will need time to familiarize themselves with. It is likely that as
more use is made of these facilities they will be refined; only time will tell.
This document provides a high-level description of the IPC facilities in 4.4BSD and their use. It is
designed to complement the manual pages for the IPC primitives by examples of their use. The remainder
of this document is organized in four sections. Section 2 introduces the IPC-related system calls and the
basic model of communication. Section 3 describes some of the supporting library routines users may find
useful in constructing distributed applications. Section 4 is concerned with the client/server model used in
developing applications and includes examples of the two major types of servers. Section 5 delves into
advanced topics which sophisticated users are likely to encounter when using the IPC facilities.
Advanced 4.4BSD IPC Tutorial PSD:21-3
2. BASICS
The basic building block for communication is the socket. A socket is an endpoint of communication
to which a name may be bound. Each socket in use has a type and one or more associated processes. Sock-
ets exist within communication domains. A communication domain is an abstraction introduced to bundle
common properties of processes communicating through sockets. One such property is the scheme used to
name sockets. For example, in the UNIX communication domain sockets are named with UNIX path
names; e.g. a socket may be named ‘‘/dev/foo’’. Sockets normally exchange data only with sockets in the
same domain (it may be possible to cross domain boundaries, but only if some translation process is per-
formed). The 4.4BSD IPC facilities support four separate communication domains: the UNIX domain, for
on-system communication; the Internet domain, which is used by processes which communicate using the
Internet standard communication protocols; the NS domain, which is used by processes which communi-
cate using the Xerox standard communication protocols*; and the ISO OSI protocols, which are not docu-
mented in this tutorial. The underlying communication facilities provided by these domains have a signifi-
cant influence on the internal system implementation as well as the interface to socket facilities available to
a user. An example of the latter is that a socket ‘‘operating’’ in the UNIX domain sees a subset of the error
conditions which are possible when operating in the Internet (or NS) domain.
The default protocol (used when the protocol argument to the socket call is 0) should be correct for
most every situation. However, it is possible to specify a protocol other than the default; this will be cov-
ered in section 5.
There are several reasons a socket call may fail. Aside from the rare occurrence of lack of memory
(ENOBUFS), a socket request may fail due to a request for an unknown protocol (EPROTONOSUPPORT),
or a request for a type of socket for which there is no supporting protocol (EPROTOTYPE).
names contain a path name and a family, which is always AF_UNIX. If one wanted to bind the name
‘‘/tmp/foo’’ to a UNIX domain socket, the following code would be used*:
#include <sys/un.h>
...
struct sockaddr_un addr;
...
strcpy(addr.sun_path, "/tmp/foo");
addr.sun_family = AF_UNIX;
bind(s, (struct sockaddr *) &addr, strlen(addr.sun_path) +
sizeof (addr.sun_len) + sizeof (addr.sun_family));
Note that in determining the size of a UNIX domain address null bytes are not counted, which is why strlen
is used. In the current implementation of UNIX domain IPC, the file name referred to in addr.sun_path is
created as a socket in the system file space. The caller must, therefore, have write permission in the direc-
tory where addr.sun_path is to reside, and this file should be deleted by the caller when it is no longer
needed. Future versions of 4BSD may not create this file.
In binding an Internet address things become more complicated. The actual call is similar,
#include <sys/types.h>
#include <netinet/in.h>
...
struct sockaddr_in sin;
...
bind(s, (struct sockaddr *) &sin, sizeof (sin));
but the selection of what to place in the address sin requires some discussion. We will come back to the
problem of formulating Internet addresses in section 3 when the library routines used in name resolution
are discussed.
Binding an NS address to a socket is even more difficult, especially since the Internet library routines
do not work with NS hostnames. The actual call is again similar:
#include <sys/types.h>
#include <netns/ns.h>
...
struct sockaddr_ns sns;
...
bind(s, (struct sockaddr *) &sns, sizeof (sns));
Again, discussion of what to place in a ‘‘struct sockaddr_ns’’ will be deferred to section 3.
would be declared as a struct sockaddr_ns, but nothing different would need to be done as far as fromlen is
concerned. In the examples which follow, only Internet routines will be discussed.) A new descriptor is
returned on receipt of a connection (along with a new socket). If the server wishes to find out who its client
is, it may supply a buffer for the client socket’s name. The value-result parameter fromlen is initialized by
the server to indicate how much space is associated with from, then modified on return to reflect the true
size of the name. If the client’s name is not of interest, the second parameter may be a null pointer.
Accept normally blocks. That is, accept will not return until a connection is available or the system
call is interrupted by a signal to the process. Further, there is no way for a process to indicate it will accept
connections from only a specific individual, or individuals. It is up to the user process to consider who the
connection is from and close down the connection if it does not wish to speak to the process. If the server
process wants to accept connections on more than one socket, or wants to avoid blocking on the accept call,
there are alternatives; they will be considered in section 5.
Out of band data is a notion specific to stream sockets, and one which we will not immediately consider.
The option to have data sent without routing applied to the outgoing packets is currently used only by the
routing table management process, and is unlikely to be of interest to the casual user. The ability to pre-
view data is, however, of interest. When MSG_PEEK is specified with a recv call, any data present is
returned to the user, but treated as still ‘‘unread’’. That is, the next read or recv call applied to the socket
will return the data previously previewed.
* To be more specific, a return takes place only when a descriptor is selectable, or when a signal is received by
the caller, interrupting the system call.
PSD:21-10 Advanced 4.4BSD IPC Tutorial
#include <sys/time.h>
#include <sys/types.h>
...
fd_set read_template;
struct timeval wait;
...
for (;;) {
wait.tv_sec = 1; /* one second */
wait.tv_usec = 0;
FD_ZERO(&read_template);
FD_SET(s1, &read_template);
FD_SET(s2, &read_template);
if (FD_ISSET(s1, &read_template)) {
Socket #1 is ready to be read from.
}
if (FD_ISSET(s2, &read_template)) {
Socket #2 is ready to be read from.
}
}
In 4.2, the arguments to select were pointers to integers instead of pointers to fd_sets. This type of
call will still work as long as the number of file descriptors being examined is less than the number of bits
in an integer; however, the methods illustrated above should be used in all current programs.
Select provides a synchronous multiplexing scheme. Asynchronous notification of output comple-
tion, input availability, and exceptional conditions is possible through use of the SIGIO and SIGURG sig-
nals described in section 5.
Advanced 4.4BSD IPC Tutorial PSD:21-11
The discussion in section 2 indicated the possible need to locate and construct network addresses
when using the interprocess communication facilities in a distributed environment. To aid in this task a
number of routines have been added to the standard C run-time library. In this section we will consider the
new routines provided to manipulate network addresses. While the 4.4BSD networking facilities support
the Internet protocols and the Xerox NS protocols, most of the routines presented in this section do not
apply to the NS domain. Unless otherwise stated, it should be assumed that the routines presented in this
section do not apply to the NS domain.
Locating a service on a remote host requires many levels of mapping before client and server may
communicate. A service is assigned a name which is intended for human consumption; e.g. ‘‘the login
server on host monet’’. This name, and the name of the peer host, must then be translated into network
addresses which are not necessarily suitable for human consumption. Finally, the address must then used
in locating a physical location and route to the service. The specifics of these three mappings are likely to
vary between network architectures. For instance, it is desirable for a network to not require hosts to be
named in such a way that their physical location is known by the client host. Instead, underlying services
in the network may discover the actual location of the host at the time a client host wishes to communicate.
This ability to have hosts named in a location independent manner may induce overhead in connection
establishment, as a discovery process must take place, but allows a host to be physically mobile without
requiring it to notify its clientele of its current location.
Standard routines are provided for: mapping host names to network addresses, network names to net-
work numbers, protocol names to protocol numbers, and service names to port numbers and the appropriate
protocol to use in communicating with the server process. The file <netdb.h> must be included when using
any of these routines.
names to addresses via a Clearinghouse are rather complicated, and the routines are not part of the standard
libraries. The user-contributed Courier (Xerox remote procedure call protocol) compiler contains routines
to accomplish this mapping; see the documentation and examples provided therein for more information. It
is expected that almost all software that has to communicate using NS will need to use the facilities of the
Courier compiler.
An NS host address is represented by the following:
union ns_host {
u_char c_host[6];
u_short s_host[3];
};
union ns_net {
u_char c_net[4];
u_short s_net[2];
};
struct ns_addr {
union ns_net x_net;
union ns_host x_host;
u_short x_port;
};
The following code fragment inserts a known NS address into a ns_addr:
Advanced 4.4BSD IPC Tutorial PSD:21-13
#include <sys/types.h>
#include <sys/socket.h>
#include <netns/ns.h>
...
u_long netnum;
struct sockaddr_ns dst;
...
bzero((char *)&dst, sizeof(dst));
/*
* There is no convenient way to assign a long
* integer to a ‘‘union ns_net’’ at present; in
* the future, something will hopefully be provided,
* but this is the portable way to go for now.
* The network number below is the one for the NS net
* that the desired host (gyre) is on.
*/
netnum = htonl(2266);
dst.sns_addr.x_net = *(union ns_net *) &netnum;
dst.sns_family = AF_NS;
/*
* host 2.7.1.0.2a.18 == "gyre:Computer Science:UofMaryland"
*/
dst.sns_addr.x_host.c_host[0] = 0x02;
dst.sns_addr.x_host.c_host[1] = 0x07;
dst.sns_addr.x_host.c_host[2] = 0x01;
dst.sns_addr.x_host.c_host[3] = 0x00;
dst.sns_addr.x_host.c_host[4] = 0x2a;
dst.sns_addr.x_host.c_host[5] = 0x18;
dst.sns_addr.x_port = htons(75);
In the NS domain, protocols are indicated by the "client type" field of a IDP header. No protocol
database exists; see section 5 for more information.
3.5. Miscellaneous
With the support routines described above, an Internet application program should rarely have to deal
directly with addresses. This allows services to be developed as much as possible in a network independent
fashion. It is clear, however, that purging all network dependencies is very difficult. So long as the user is
required to supply network addresses when naming services and sockets there will always some network
dependency in a program. For example, the normal code included in client programs, such as the remote
login program, is of the form shown in Figure 1. (This example will be considered in more detail in section
4.)
If we wanted to make the remote login program independent of the Internet protocols and addressing
scheme we would be forced to add a layer of routines which masked the network dependent aspects from
the mainstream login code. For the current facilities available in the system this does not appear to be
worthwhile.
* Courier: The Remote Procedure Call Protocol, XSIS 038112.
Advanced 4.4BSD IPC Tutorial PSD:21-15
Aside from the address-related data base routines, there are several other routines available in the
run-time library which are of interest to users. These are intended mostly to simplify manipulation of
names and addresses. Table 1 summarizes the routines for manipulating variable length byte strings and
handling byte swapping of network addresses and values.
Call Synopsis
bcmp(s1, s2, n) compare byte-strings; 0 if same, not 0 otherwise
bcopy(s1, s2, n) copy n bytes from s1 to s2
bzero(base, n) zero-fill n bytes starting at base
htonl(val) convert 32-bit quantity from host to network byte order
htons(val) convert 16-bit quantity from host to network byte order
ntohl(val) convert 32-bit quantity from network to host byte order
ntohs(val) convert 16-bit quantity from network to host byte order
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <netdb.h>
...
main(argc, argv)
int argc;
char *argv[];
{
struct sockaddr_in server;
struct servent *sp;
struct hostent *hp;
int s;
...
sp = getservbyname("login", "tcp");
if (sp == NULL) {
fprintf(stderr, "rlogin: tcp/login: unknown service\n");
exit(1);
}
hp = gethostbyname(argv[1]);
if (hp == NULL) {
fprintf(stderr, "rlogin: %s: unknown host\n", argv[1]);
exit(2);
}
bzero((char *)&server, sizeof (server));
bcopy(hp->h_addr, (char *)&server.sin_addr, hp->h_length);
server.sin_family = hp->h_addrtype;
server.sin_port = sp->s_port;
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
perror("rlogin: socket");
exit(3);
}
...
/* Connect does the bind() for us */
4. CLIENT/SERVER MODEL
The most commonly used paradigm in constructing distributed applications is the client/server
model. In this scheme client applications request services from a server process. This implies an asymme-
try in establishing communication between the client and server which has been examined in section 2. In
this section we will look more closely at the interactions between client and server, and consider some of
the problems in developing client and server applications.
The client and server require a well known set of conventions before service may be rendered (and
accepted). This set of conventions comprises a protocol which must be implemented at both ends of a con-
nection. Depending on the situation, the protocol may be symmetric or asymmetric. In a symmetric proto-
col, either side may play the master or slave roles. In an asymmetric protocol, one side is immutably recog-
nized as the master, with the other as the slave. An example of a symmetric protocol is the TELNET proto-
col used in the Internet for remote terminal emulation. An example of an asymmetric protocol is the Inter-
net file transfer protocol, FTP. No matter whether the specific protocol used in obtaining a service is sym-
metric or asymmetric, when accessing a service there is a ‘‘client process’’ and a ‘‘server process’’. We
will first consider the properties of server processes, then client processes.
A server process normally listens at a well known address for service requests. That is, the server
process remains dormant until a connection is requested by a client’s connection to the server’s address. At
such a time the server process ‘‘wakes up’’ and services the client, performing whatever appropriate actions
the client requests of it.
Alternative schemes which use a service server may be used to eliminate a flock of server processes
clogging the system while remaining dormant most of the time. For Internet servers in 4.4BSD, this
scheme has been implemented via inetd, the so called ‘‘internet super-server.’’ Inetd listens at a variety of
ports, determined at start-up by reading a configuration file. When a connection is requested to a port on
which inetd is listening, inetd executes the appropriate server program to handle the client. With this
method, clients are unaware that an intermediary such as inetd has played any part in the connection. Inetd
will be described in more detail in section 5.
A similar alternative scheme is used by most Xerox services. In general, the Courier dispatch pro-
cess (if used) accepts connections from processes requesting services of some sort or another. The client
processes request a particular <program number, version number, procedure number> triple. If the dis-
patcher knows of such a program, it is started to handle the request; if not, an error is reported to the client.
In this way, only one port is required to service a large variety of different requests. Again, the Courier
facilities are not available without the use and installation of the Courier compiler. The information pre-
sented in this section applies only to NS clients and services that do not use Courier.
4.1. Servers
In 4.4BSD most servers are accessed at well known Internet addresses or UNIX domain names. For
example, the remote login server’s main loop is of the form shown in Figure 2.
The first step taken by the server is look up its service definition:
sp = getservbyname("login", "tcp");
if (sp == NULL) {
fprintf(stderr, "rlogind: tcp/login: unknown service\n");
exit(1);
}
The result of the getservbyname call is used in later portions of the code to define the Internet port at which
it listens for service requests (indicated by a connection).
PSD:21-18 Advanced 4.4BSD IPC Tutorial
main(argc, argv)
int argc;
char *argv[];
{
int f;
struct sockaddr_in from;
struct servent *sp;
sp = getservbyname("login", "tcp");
if (sp == NULL) {
fprintf(stderr, "rlogind: tcp/login: unknown service\n");
exit(1);
}
...
#ifndef DEBUG
/* Disassociate server from controlling terminal */
...
#endif
Step two is to disassociate the server from the controlling terminal of its invoker:
for (i = 0; i < 3; ++i)
close(i);
open("/", O_RDONLY);
dup2(0, 1);
dup2(0, 2);
i = open("/dev/tty", O_RDWR);
if (i >= 0) {
ioctl(i, TIOCNOTTY, 0);
close(i);
}
This step is important as the server will likely not want to receive signals delivered to the process group of
the controlling terminal. Note, however, that once a server has disassociated itself it can no longer send
reports of errors to a terminal, and must log errors via syslog.
Once a server has established a pristine environment, it creates a socket and begins accepting service
requests. The bind call is required to insure the server listens at its expected location. It should be noted
that the remote login server listens at a restricted port number, and must therefore be run with a user-id of
root. This concept of a ‘‘restricted port number’’ is 4BSD specific, and is covered in section 5.
The main body of the loop is fairly simple:
for (;;) {
int g, len = sizeof (from);
4.2. Clients
The client side of the remote login service was shown earlier in Figure 1. One can see the separate,
asymmetric roles of the client and server clearly in the code. The server is a passive entity, listening for
client connections, while the client process is an active entity, initiating a connection when invoked.
Let us consider more closely the steps taken by the client remote login process. As in the server pro-
cess, the first step is to locate the service definition for a remote login:
PSD:21-20 Advanced 4.4BSD IPC Tutorial
sp = getservbyname("login", "tcp");
if (sp == NULL) {
fprintf(stderr, "rlogin: tcp/login: unknown service\n");
exit(1);
}
Next the destination host is looked up with a gethostbyname call:
hp = gethostbyname(argv[1]);
if (hp == NULL) {
fprintf(stderr, "rlogin: %s: unknown host\n", argv[1]);
exit(2);
}
With this accomplished, all that is required is to establish a connection to the server at the requested host
and start up the remote login protocol. The address buffer is cleared, then filled in with the Internet address
of the foreign host and the port number at which the login process resides on the foreign host:
bzero((char *)&server, sizeof (server));
bcopy(hp->h_addr, (char *) &server.sin_addr, hp->h_length);
server.sin_family = hp->h_addrtype;
server.sin_port = sp->s_port;
A socket is created, and a connection initiated. Note that connect implicitly performs a bind call, since s is
unbound.
s = socket(hp->h_addrtype, SOCK_STREAM, 0);
if (s < 0) {
perror("rlogin: socket");
exit(3);
}
...
if (connect(s, (struct sockaddr *) &server, sizeof (server)) < 0) {
perror("rlogin: connect");
exit(4);
}
The details of the remote login protocol will not be considered here.
The rwho server, in a simplified form, is pictured in Figure 4. There are two separate tasks per-
formed by the server. The first task is to act as a receiver of status information broadcast by other hosts on
the network. This job is carried out in the main loop of the program. Packets received at the rwho port are
interrogated to insure they’ve been sent by another rwho server process, then are time stamped with their
arrival time and used to update a file indicating the status of the host. When a host has not been heard from
for an extended period of time, the database interpretation routines assume the host is down and indicate
such on the status reports. This algorithm is prone to error as a server may be down while a host is actually
up, but serves our current needs.
The second task performed by the server is to supply information regarding the status of its host.
This involves periodically acquiring system status information, packaging it up in a message and broadcast-
ing it on the local network for other rwho servers to hear. The supply function is triggered by a timer and
runs off a signal. Locating the system status information is somewhat involved, but uninteresting. Decid-
ing where to transmit the resultant packet is somewhat problematical, however.
Status information must be broadcast on the local network. For networks which do not support the
notion of broadcast another scheme must be used to simulate or replace broadcasting. One possibility is to
enumerate the known neighbors (based on the status messages received from other rwho servers). This,
unfortunately, requires some bootstrapping information, for a server will have no idea what machines are its
neighbors until it receives status messages from them. Therefore, if all machines on a net are freshly
booted, no machine will have any known neighbors and thus never receive, or send, any status information.
This is the identical problem faced by the routing table management process in propagating routing status
information. The standard solution, unsatisfactory as it may be, is to inform one or more servers of known
neighbors and request that they always communicate with these neighbors. If each server has at least one
neighbor supplied to it, status information may then propagate through a neighbor to hosts which are not
(possibly) directly neighbors. If the server is able to support networks which provide a broadcast capabil-
ity, as well as those which do not, then networks with an arbitrary topology may share status information*.
It is important that software operating in a distributed environment not have any site-dependent infor-
mation compiled into it. This would require a separate copy of the server at each host and make mainte-
nance a severe headache. 4.4BSD attempts to isolate host-specific information from applications by pro-
* One must, however, be concerned about ‘‘loops’’. That is, if a host is connected to multiple networks, it will
receive status information from itself. This can lead to an endless, wasteful, exchange of information.
PSD:21-22 Advanced 4.4BSD IPC Tutorial
main()
{
...
sp = getservbyname("who", "udp");
net = getnetbyname("localnet");
sin.sin_addr = inet_makeaddr(INADDR_ANY, net);
sin.sin_port = sp->s_port;
...
s = socket(AF_INET, SOCK_DGRAM, 0);
...
on = 1;
if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) {
syslog(LOG_ERR, "setsockopt SO_BROADCAST: %m");
exit(1);
}
bind(s, (struct sockaddr *) &sin, sizeof (sin));
...
signal(SIGALRM, onalrm);
onalrm();
for (;;) {
struct whod wd;
int cc, whod, len = sizeof (from);
viding system calls which return the necessary information*. A mechanism exists, in the form of an ioctl
* An example of such a system call is the gethostname(2) call which returns the host’s ‘‘official’’ name.
Advanced 4.4BSD IPC Tutorial PSD:21-23
call, for finding the collection of networks to which a host is directly connected. Further, a local network
broadcasting mechanism has been implemented at the socket level. Combining these two features allows a
process to broadcast on any directly connected local network which supports the notion of broadcasting in a
site independent manner. This allows 4.4BSD to solve the problem of deciding how to propagate status
information in the case of rwho, or more generally in broadcasting: Such status information is broadcast to
connected networks at the socket level, where the connected networks have been obtained via the appropri-
ate ioctl calls. The specifics of such broadcastings are complex, however, and will be covered in section 5.
PSD:21-24 Advanced 4.4BSD IPC Tutorial
5. ADVANCED TOPICS
A number of facilities have yet to be discussed. For most users of the IPC the mechanisms already
described will suffice in constructing distributed applications. However, others will find the need to utilize
some of the features which we consider in this section.
#include <sys/ioctl.h>
#include <sys/file.h>
...
oob()
{
int out = FWRITE, mark;
char waste[BUFSIZ];
When performing non-blocking I/O on sockets, one must be careful to check for the error EWOULD-
BLOCK (stored in the global variable errno), which occurs when an operation would normally block, but
the socket it was performed on is marked as non-blocking. In particular, accept, connect, send, recv, read,
and write can all return EWOULDBLOCK, and processes should be prepared to deal with such return
codes. If an operation such as a send cannot be done in its entirety, but partial writes are sensible (for
example, when using a stream socket), the data that can be sent immediately will be processed, and the
return value will indicate the amount actually sent.
PSD:21-26 Advanced 4.4BSD IPC Tutorial
int reaper();
...
signal(SIGCHLD, reaper);
listen(f, 5);
for (;;) {
int g, len = sizeof (from);
and slave, which allow a process to serve as an active agent in communication between processes and users.
Data written on the slave side of a pseudo-terminal is supplied as input to a process reading from the master
side, while data written on the master side are processed as terminal input for the slave. In this way, the
process manipulating the master side of the pseudo-terminal has control over the information read and writ-
ten on the slave side as if it were manipulating the keyboard and reading the screen on a real terminal. The
purpose of this abstraction is to preserve terminal semantics over a network connection— that is, the slave
side appears as a normal terminal to any process reading from or writing to it.
For example, the remote login server uses pseudo-terminals for remote login sessions. A user log-
ging in to a machine across the network is provided a shell with a slave pseudo-terminal as standard input,
output, and error. The server process then handles the communication between the programs invoked by
the remote shell and the user’s local client process. When a user sends a character that generates an inter-
rupt on the remote machine that flushes terminal output, the pseudo-terminal generates a control message
for the server process. The server then sends an out of band message to the client process to signal a flush
of data at the real terminal and on the intervening data buffered in the network.
Under 4.4BSD, the name of the slave side of a pseudo-terminal is of the form /dev/ttyxy, where x is a
single letter starting at ‘p’ and continuing to ‘t’. y is a hexadecimal digit (i.e., a single character in the
range 0 through 9 or ‘a’ through ‘f’). The master side of a pseudo-terminal is /dev/ptyxy, where x and y
correspond to the slave side of the pseudo-terminal.
In general, the method of obtaining a pair of master and slave pseudo-terminals is to find a pseudo-
terminal which is not currently in use. The master half of a pseudo-terminal is a single-open device; thus,
each master may be opened in turn until an open succeeds. The slave side of the pseudo-terminal is then
opened, and is set to the proper terminal modes if necessary. The process then forks; the child closes the
master side of the pseudo-terminal, and execs the appropriate program. Meanwhile, the parent closes the
slave side of the pseudo-terminal and begins reading and writing from the master side. Sample code mak-
ing use of pseudo-terminals is given in Figure 8; this code assumes that a connection on a socket s exists,
connected to a peer who wants a service of some kind, and that the process has disassociated itself from any
PSD:21-28 Advanced 4.4BSD IPC Tutorial
line[sizeof("/dev/")-1] = ’t’;
slave = open(line, O_RDWR); /* slave is now slave side */
if (slave < 0) {
syslog(LOG_ERR, "Cannot open slave pty %s", line);
exit(1);
}
i = fork();
if (i < 0) {
syslog(LOG_ERR, "fork: %m");
exit(1);
} else if (i) { /* Parent */
close(slave);
...
} else { /* Child */
(void) close(s);
(void) close(master);
dup2(slave, 0);
dup2(slave, 1);
dup2(slave, 2);
if (slave > 2)
(void) close(slave);
...
}
Figure 8. Creation and use of a pseudo terminal
Advanced 4.4BSD IPC Tutorial PSD:21-29
#include <sys/types.h>
#include <netinet/in.h>
...
struct sockaddr_in sin;
...
s = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(MYPORT);
bind(s, (struct sockaddr *) &sin, sizeof (sin));
Sockets with wildcarded local addresses may receive messages directed to the specified port number, and
sent to any of the possible addresses assigned to a host. For example, if a host has addresses 128.32.0.4 and
10.0.0.78, and a socket is bound as above, the process will be able to accept connection requests which are
addressed to 128.32.0.4 or 10.0.0.78. If a server process wished to only allow hosts on a given network
connect to it, it would bind the address of the host on the appropriate network.
In a similar fashion, a local port may be left unspecified (specified as zero), in which case the system
will select an appropriate port number for it. This shortcut will work both in the Internet and NS domains.
For example, to bind a specific local address to a socket, but to leave the local port number unspecified:
hp = gethostbyname(hostname);
if (hp == NULL) {
...
}
bcopy(hp->h_addr, (char *) sin.sin_addr, hp->h_length);
sin.sin_port = htons(0);
bind(s, (struct sockaddr *) &sin, sizeof (sin));
The system selects the local port number based on two criteria. The first is that on 4BSD systems, Internet
ports below IPPORT_RESERVED (1024) (for the Xerox domain, 0 through 3000) are reserved for privi-
leged users (i.e., the super user); Internet ports above IPPORT_USERRESERVED (50000) are reserved for
non-privileged servers. The second is that the port number is not currently bound to some other socket. In
order to find a free Internet port number in the privileged range the rresvport library routine may be used as
follows to return a stream socket in with a privileged port number:
int lport = IPPORT_RESERVED − 1;
int s;
...
s = rresvport(&lport);
if (s < 0) {
if (errno == EAGAIN)
fprintf(stderr, "socket: all ports in use\n");
else
perror("rresvport: socket");
...
}
The restriction on allocating ports was done to allow processes executing in a ‘‘secure’’ environment to per-
form authentication based on the originating address and port number. For example, the rlogin(1) com-
mand allows users to log in across a network without being asked for a password, if two conditions hold:
First, the name of the system the user is logging in from is in the file /etc/hosts.equiv on the system he is
logging in to (or the system name and the user name are in the user’s .rhosts file in the user’s home direc-
tory), and second, that the user’s rlogin process is coming from a privileged port on the machine from
which he is logging. The port number and network address of the machine from which the user is logging
in can be determined either by the from result of the accept call, or from the getpeername call.
Advanced 4.4BSD IPC Tutorial PSD:21-31
In certain cases the algorithm used by the system in selecting port numbers is unsuitable for an appli-
cation. This is because associations are created in a two step process. For example, the Internet file trans-
fer protocol, FTP, specifies that data connections must always originate from the same local port. However,
duplicate associations are avoided by connecting to different foreign ports. In this situation the system
would disallow binding the same local address and port number to a socket if a previous data connection’s
socket still existed. To override the default port selection algorithm, an option call must be performed prior
to address binding:
...
int on = 1;
...
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
bind(s, (struct sockaddr *) &sin, sizeof (sin));
With the above call, local addresses may be bound which are already in use. This does not violate the
uniqueness requirement as the system still checks at connect time to be sure any other sockets with the
same local address and port do not have the same foreign address and port. If the association already exists,
the error EADDRINUSE is returned. A related socket option, SO_REUSEPORT, which allows completely
duplicate bindings, is described in the IP multicasting section.
The parameters to the calls are as follows: s is the socket on which the option is to be applied. Level
specifies the protocol layer on which the option is to be applied; in most cases this is the ‘‘socket level’’,
indicated by the symbolic constant SOL_SOCKET, defined in <sys/socket.h>. The actual option is speci-
fied in optname, and is a symbolic constant also defined in <sys/socket.h>. Optval and Optlen point to the
value of the option (in most cases, whether the option is to be turned on or off), and the length of the value
of the option, respectively. For getsockopt, optlen is a value-result parameter, initially set to the size of the
storage area pointed to by optval, and modified upon return to indicate the actual amount of storage used.
An example should help clarify things. It is sometimes useful to determine the type (e.g., stream,
datagram, etc.) of an existing socket; programs under inetd (described below) may need to perform this
task. This can be accomplished as follows via the SO_TYPE socket option and the getsockopt call:
#include <sys/types.h>
#include <sys/socket.h>
SOCK_DGRAM.
struct ifconf {
int ifc_len; /* size of associated buffer */
union {
caddr_t ifcu_buf;
struct ifreq *ifcu_req;
} ifc_ifcu;
};
#define IFNAMSIZ 16
struct ifreq {
char ifr_name[IFNAMSIZ]; /* if name, e.g. "en0" */
union {
struct sockaddr ifru_addr;
struct sockaddr ifru_dstaddr;
struct sockaddr ifru_broadaddr;
short ifru_flags;
caddr_t ifru_data;
} ifr_ifru;
};
ifr = ifc.ifc_req;
Once the flags have been obtained, the broadcast address must be obtained. In the case of broadcast
networks this is done via the SIOCGIFBRDADDR ioctl, while for point-to-point networks the address of
the destination host is obtained with SIOCGIFDSTADDR.
struct sockaddr dst;
After the appropriate ioctl’s have obtained the broadcast or destination address (now in dst), the
sendto call may be used:
sendto(s, buf, buflen, 0, (struct sockaddr *)&dst, sizeof (dst));
}
In the above loop one sendto occurs for every interface to which the host is connected that supports the
notion of broadcast or point-to-point addressing. If a process only wished to send broadcast messages on a
given network, code similar to that outlined above would be used, but the loop would need to find the cor-
rect destination address.
Received broadcast messages contain the senders address and port, as datagram sockets are bound
before a message is allowed to go out.
Advanced 4.4BSD IPC Tutorial PSD:21-35
5.10. IP Multicasting
IP multicasting is the transmission of an IP datagram to a "host group", a set of zero or more hosts
identified by a single IP destination address. A multicast datagram is delivered to all members of its desti-
nation host group with the same "best-efforts" reliability as regular unicast IP datagrams, i.e., the datagram
is not guaranteed to arrive intact at all members of the destination group or in the same order relative to
other datagrams.
The membership of a host group is dynamic; that is, hosts may join and leave groups at any time.
There is no restriction on the location or number of members in a host group. A host may be a member of
more than one group at a time. A host need not be a member of a group to send datagrams to it.
A host group may be permanent or transient. A permanent group has a well-known, administratively
assigned IP address. It is the address, not the membership of the group, that is permanent; at any time a
permanent group may have any number of members, even zero. Those IP multicast addresses that are not
reserved for permanent groups are available for dynamic assignment to transient groups which exist only as
long as they have members.
In general, a host cannot assume that datagrams sent to any host group address will reach only the
intended hosts, or that datagrams received as a member of a transient host group are intended for the recipi-
ent. Misdelivery must be detected at a level above IP, using higher-level identifiers or authentication
tokens. Information transmitted to a host group address should be encrypted or governed by administrative
routing controls if the sender is concerned about unwanted listeners.
IP multicasting is currently supported only on AF_INET sockets of type SOCK_DGRAM and
SOCK_RAW, and only on subnetworks for which the interface driver has been modified to support multi-
casting.
The next subsections describe how to send and receive multicast datagrams.
"Sites" and "regions" are not strictly defined, and sites may be further subdivided into smaller
PSD:21-36 Advanced 4.4BSD IPC Tutorial
struct ip_mreq {
struct in_addr imr_multiaddr; /* multicast group to join */
struct in_addr imr_interface; /* interface to join on */
}
Every membership is associated with a single interface, and it is possible to join the same group on more
than one interface. "imr_interface" should be INADDR_ANY to choose the default multicast interface, or
one of the host’s local addresses to choose a particular (multicast-capable) interface. Up to
IP_MAX_MEMBERSHIPS (currently 20) memberships may be added on a single socket.
To drop a membership, use:
struct ip_mreq mreq;
setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
where "mreq" contains the same values as used to add the membership. The memberships associated with
a socket are also dropped when the socket is closed or the process holding the socket is killed. However,
more than one socket may claim a membership in a particular group, and the host will remain a member of
that group until the last claim is dropped.
The memberships associated with a socket do not necessarily determine which datagrams are
received on that socket. Incoming multicast packets are accepted by the kernel IP layer if any socket has
claimed a membership in the destination group of the datagram; however, delivery of a multicast datagram
to a particular socket is based on the destination port (or protocol type, for raw sockets), just as with unicast
datagrams. To receive multicast datagrams sent to a particular port, it is necessary to bind to that local port,
leaving the local address unspecified (i.e., INADDR_ANY). To receive multicast datagrams sent to a par-
ticular group and port, bind to the local port, with the local address set to the multicast group address. Once
bound to a multicast address, the socket cannot be used for sending data.
More than one process may bind to the same SOCK_DGRAM UDP port or the same multicast group
and port if the bind call is preceded by:
int on = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));
All processes sharing the port must enable this option. Every incoming multicast or broadcast UDP data-
gram destined to the shared port is delivered to all sockets bound to the port. For backwards compatibility
reasons, this does not apply to incoming unicast datagrams. Unicast datagrams are never delivered to more
than one socket, regardless of how many sockets are bound to the datagram’s destination port.
A final multicast-related extension is independent of IP: two new ioctls, SIOCADDMULTI and
SIOCDELMULTI, are available to add or delete link-level (e.g., Ethernet) multicast addresses accepted by
a particular interface. The address to be added or deleted is passed as a sockaddr structure of family
AF_UNSPEC, within the standard ifreq structure.
These ioctls are for the use of protocols other than IP, and require superuser privileges. A link-level
multicast address added via SIOCADDMULTI is not automatically deleted when the socket used to add it
goes away; it must be explicitly deleted. It is inadvisable to delete a link-level address that may be in use
by IP.
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <stdio.h>
main(argc)
int argc;
{
struct sockaddr_in addr;
int addrlen, fd, cnt;
struct ip_mreq mreq;
char message[50];
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(EXAMPLE_PORT);
addrlen = sizeof(addr);
mreq.imr_multiaddr.s_addr = inet_addr(EXAMPLE_GROUP);
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
&mreq, sizeof(mreq)) < 0) {
perror("setsockopt mreq");
Advanced 4.4BSD IPC Tutorial PSD:21-39
exit(1);
}
while (1) {
cnt = recvfrom(fd, message, sizeof(message), 0,
(struct sockaddr *)&addr, &addrlen);
if (cnt <= 0) {
if (cnt == 0) {
break;
}
perror("recvfrom");
exit(1);
}
printf("%s: message = \"%s\"\n",
inet_ntoa(addr.sin_addr), message);
}
}
}
#include <sys/types.h>
#include <sys/socket.h>
#include <netns/ns.h>
#include <netns/sp.h>
...
struct sockaddr_ns sns, to;
int s, on = 1;
struct databuf {
struct sphdr proto_spp; /* prototype header */
char buf[534]; /* max. possible data by Xerox std. */
} buf;
...
s = socket(AF_NS, SOCK_SEQPACKET, 0);
...
bind(s, (struct sockaddr *) &sns, sizeof (sns));
setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_OUTPUT, &on, sizeof(on));
...
buf.proto_spp.sp_dt = 1; /* bulk data */
buf.proto_spp.sp_cc = SP_EM; /* end-of-message */
strcpy(buf.buf, "hello world\n");
sendto(s, (char *) &buf, sizeof(struct sphdr) + strlen("hello world\n"),
(struct sockaddr *) &to, sizeof(to));
...
Note that one must be careful when writing headers; if the prototype header is not written with the data
with which it is to be associated, the kernel will treat the first few bytes of the data as the header, with
unpredictable results. To turn off the above association, and to indicate that packet headers received by the
system should be passed up to the user, one might use:
#include <sys/types.h>
#include <sys/socket.h>
#include <netns/ns.h>
#include <netns/sp.h>
...
struct sockaddr sns;
int s, on = 1, off = 0;
...
s = socket(AF_NS, SOCK_SEQPACKET, 0);
...
bind(s, (struct sockaddr *) &sns, sizeof (sns));
setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_OUTPUT, &off, sizeof(off));
setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_INPUT, &on, sizeof(on));
...
Output is handled somewhat differently in the IDP world. The header of an IDP-level packet looks
like:
struct idp {
u_short idp_sum; /* Checksum */
u_short idp_len; /* Length, in bytes, including header */
u_char idp_tc; /* Transport Control (i.e., hop count) */
u_char idp_pt; /* Packet Type (i.e., level 2 protocol) */
struct ns_addr idp_dna; /* Destination Network Address */
struct ns_addr idp_sna; /* Source Network Address */
};
The primary field of interest in an IDP header is the packet type field. The standard values for this field are
Advanced 4.4BSD IPC Tutorial PSD:21-41
#include <sys/types.h>
#include <sys/socket.h>
#include <netns/ns.h>
#include <netns/sp.h>
...
#ifndef SPPSST_END
#define SPPSST_END 254
#define SPPSST_ENDREPLY 255
#endif
struct sphdr proto_sp;
int s;
...
read(s, buf, BUFSIZE);
if (((struct sphdr *)buf)->sp_dt == SPPSST_END) {
/*
* SPPSST_END indicates that the other side wants to
* close.
*/
proto_sp.sp_dt = SPPSST_ENDREPLY;
proto_sp.sp_cc = SP_EM;
setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp,
sizeof(proto_sp));
write(s, buf, 0);
/*
* Write a zero-length packet with datastream type = SPPSST_ENDREPLY
* to indicate that the close is OK with us. The packet that we
* don’t see (because we don’t look for it) is another packet
* from the other side of the connection, with SPPSST_ENDREPLY
* on it it, too. Once that packet is sent, the connection is
* considered closed; note that we really ought to retransmit
* the close for some time if we do not get a reply.
*/
close(s);
}
...
To indicate to another process that we would like to close the connection, the following code would suffice:
Advanced 4.4BSD IPC Tutorial PSD:21-43
#include <sys/types.h>
#include <sys/socket.h>
#include <netns/ns.h>
#include <netns/sp.h>
...
#ifndef SPPSST_END
#define SPPSST_END 254
#define SPPSST_ENDREPLY 255
#endif
struct sphdr proto_sp;
int s;
...
proto_sp.sp_dt = SPPSST_END;
proto_sp.sp_cc = SP_EM;
setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp,
sizeof(proto_sp));
write(s, buf, 0); /* send the end request */
proto_sp.sp_dt = SPPSST_ENDREPLY;
setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp,
sizeof(proto_sp));
/*
* We assume (perhaps unwisely)
* that the other side will send the
* ENDREPLY, so we’ll just send our final ENDREPLY
* as if we’d seen theirs already.
*/
write(s, buf, 0);
close(s);
...
received. To simulate PEX, one must be able to generate unique ids -- something that is hard to do at the
user level with any real guarantee that the id is really unique. Therefore, a means (via getsockopt) has been
provided for getting unique ids from the kernel. The following code fragment indicates how to get a unique
id:
long uniqueid;
int s, idsize = sizeof(uniqueid);
...
s = socket(AF_NS, SOCK_DGRAM, 0);
...
/* get id from the kernel -- only on IDP sockets */
getsockopt(s, NSPROTO_PE, SO_SEQNO, (char *)&uniqueid, &idsize);
...
The retransmission and duplicate suppression code required to simulate PEX fully is left as an exercise for
the reader.
5.14. Inetd
One of the daemons provided with 4.4BSD is inetd, the so called ‘‘internet super-server.’’ Having
one daemon listen for requests for many daemons instead of having each daemon listen for its own requests
reduces the number of idle daemons and simplies their implementation. Inetd handles two types of ser-
vices: standard and TCPMUX. A standard service has a well-known port assigned to it and is listed in
/etc/services (see services(5)); it may be a service that implements an official Internet standard or is a BSD-
specific service. TCPMUX services are nonstandard and do not have a well-known port assigned to them.
They are invoked from inetd when a program connects to the "tcpmux" well-known port and specifies the
service name. This is useful for adding locally-developed servers.
Inetd is invoked at boot time, and determines from the file /etc/inetd.conf the servers for which it is to
listen. Once this information has been read and a pristine environment created, inetd proceeds to create one
socket for each service it is to listen for, binding the appropriate port number to each socket.
Inetd then performs a select on all these sockets for read availability, waiting for somebody wishing a
connection to the service corresponding to that socket. Inetd then performs an accept on the socket in ques-
tion, forks, dups the new socket to file descriptors 0 and 1 (stdin and stdout), closes other open file descrip-
tors, and execs the appropriate server.
Servers making use of inetd are considerably simplified, as inetd takes care of the majority of the IPC
work required in establishing a connection. The server invoked by inetd expects the socket connected to its
client on file descriptors 0 and 1, and may immediately perform any operations such as read, write, send, or
recv. Indeed, servers may use buffered I/O as provided by the ‘‘stdio’’ conventions, as long as they remem-
ber to use fflush when appropriate.
One call which may be of interest to individuals writing servers under inetd is the getpeername call,
which returns the address of the peer (process) connected on the other end of the socket. For example, to
log the Internet address in ‘‘dot notation’’ (e.g., ‘‘128.32.0.4’’) of a client connected to a server under inetd,
the following code might be used:
struct sockaddr_in name;
int namelen = sizeof (name);
...
if (getpeername(0, (struct sockaddr *)&name, &namelen) < 0) {
syslog(LOG_ERR, "getpeername: %m");
exit(1);
} else
syslog(LOG_INFO, "Connection from %s", inet_ntoa(name.sin_addr));
...
While the getpeername call is especially useful when writing programs to run with inetd, it can be used
under other circumstances. Be warned, however, that getpeername will fail on UNIX domain sockets.
Advanced 4.4BSD IPC Tutorial PSD:21-45
Standard TCP services are assigned unique well-known port numbers in the range of 0 to 1023 by the
Internet Assigned Numbers Authority ([email protected]). The limited number of ports in this range are
assigned to official Internet protocols. The TCPMUX service allows you to add locally-developed proto-
cols without needing an official TCP port assignment. The TCPMUX protocol described in RFC-1078 is
simple:
‘‘A TCP client connects to a foreign host on TCP port 1. It sends the service name followed by
a carriage-return line-feed <CRLF>. The service name is never case sensitive. The server
replies with a single character indicating positive ("+") or negative ("−") acknowledgment,
immediately followed by an optional message of explanation, terminated with a <CRLF>. If
the reply was positive, the selected protocol begins; otherwise the connection is closed.’’
In 4.4BSD, the TCPMUX service is built into inetd, that is, inetd listens on TCP port 1 for requests for
TCPMUX services listed in inetd.conf. inetd(8) describes the format of TCPMUX entries for inetd.conf.
The following is an example TCPMUX server and its inetd.conf entry. More sophisticated servers
may want to do additional processing before returning the positive or negative acknowledgement.
#include <sys/types.h>
#include <stdio.h>
main()
{
time_t t;
printf("+Go\r\n");
fflush(stdout);
time(&t);
printf("%d = %s", t, ctime(&t));
fflush(stdout);
}
The inetd.conf entry is:
tcpmux/current_time stream tcp nowait nobody /d/curtime curtime
Here’s the portion of the client code that handles the TCPMUX handshake:
PSD:21-46 Advanced 4.4BSD IPC Tutorial
char line[BUFSIZ];
FILE *fp;
...
switch (line[0]) {
case ’+’:
printf("Got ACK: %s\n", &line[1]);
break;
case ’-’:
printf("Got NAK: %s\n", &line[1]);
exit(0);
default:
printf("Got unknown response: %s\n", line);
exit(1);
}