updates for 4.3 from lapsley
[unix-history] / usr / src / share / doc / psd / 21.ipc / 5.t
CommitLineData
d60e8dff
MK
1.\" Copyright (c) 1986 Regents of the University of California.
2.\" All rights reserved. The Berkeley software License Agreement
3.\" specifies the terms and conditions for redistribution.
4.\"
5.\" @(#)5.t 1.2 (Berkeley) %G%
6.\"
200989e9
MK
7.ds RH "Advanced Topics
8.bp
9.nr H1 5
10.nr H2 0
11.bp
12.LG
13.B
14.ce
155. ADVANCED TOPICS
16.sp 2
17.R
18.NL
19.PP
20A number of facilities have yet to be discussed. For most users
d60e8dff 21of the IPC the mechanisms already
200989e9 22described will suffice in constructing distributed
d60e8dff 23applications. However, others will find the need to utilize some
200989e9
MK
24of the features which we consider in this section.
25.NH 2
26Out of band data
27.PP
28The stream socket abstraction includes the notion of \*(lqout
29of band\*(rq data. Out of band data is a logically independent
30transmission channel associated with each pair of connected
31stream sockets. Out of band data is delivered to the user
d60e8dff
MK
32independently of normal data along with the SIGURG signal
33(if multiple sockets may have out of band data awaiting
34delivery, a \fIselect\fP call may be used to determine those
35sockets with such data). A process can set the process group
36or process id to be informed by the SIGURG signal via the
37appropriate \fIfcntl\fP call, as described below for
38SIGIO.
39.PP
200989e9
MK
40In addition to the information passed, a logical mark is placed in
41the data stream to indicate the point at which the out
42of band data was sent. The remote login and remote shell
d60e8dff 43applications use this facility to propagate signals between
200989e9
MK
44client and server processes. When a signal is expected to
45flush any pending output from the remote process(es), all
46data up to the mark in the data stream is discarded.
47.PP
48The
49stream abstraction defines that the out of band data facilities
50must support the reliable delivery of at least one
51out of band message at a time. This message may contain at least one
52byte of data, and at least one message may be pending delivery
53to the user at any one time. For communications protocols which
54support only in-band signaling (i.e. the urgent data is
d60e8dff 55delivered in sequence with the normal data), the system extracts
200989e9
MK
56the data from the normal data stream and stores it separately.
57This allows users to choose between receiving the urgent data
58in order and receiving it out of sequence without having to
d60e8dff
MK
59buffer all the intervening data. It is not possible
60to ``peek'' (via MSG_PEEK) at out of band data.
200989e9 61.PP
d60e8dff 62To send an out of band message the MSG_OOB flag is supplied to
200989e9 63a \fIsend\fP or \fIsendto\fP calls,
d60e8dff 64while to receive out of band data MSG_OOB should be indicated
200989e9
MK
65when performing a \fIrecvfrom\fP or \fIrecv\fP call.
66To find out if the read pointer is currently pointing at
67the mark in the data stream, the SIOCATMARK ioctl is provided:
68.DS
69ioctl(s, SIOCATMARK, &yes);
70.DE
71If \fIyes\fP is a 1 on return, the next read will return data
72after the mark. Otherwise (assuming out of band data has arrived),
73the next read will provide data sent by the client prior
74to transmission of the out of band signal. The routine used
75in the remote login process to flush output on receipt of an
76interrupt or quit signal is shown in Figure 5.
77.KF
78.DS
d60e8dff
MK
79#include <sys/ioctl.h>
80#include <sys/file.h>
81 ...
200989e9
MK
82oob()
83{
d60e8dff 84 int out = FWRITE;
200989e9
MK
85 char waste[BUFSIZ], mark;
86
d60e8dff 87 /* flush local terminal output */
200989e9
MK
88 ioctl(1, TIOCFLUSH, (char *)&out);
89 for (;;) {
90 if (ioctl(rem, SIOCATMARK, &mark) < 0) {
91 perror("ioctl");
92 break;
93 }
94 if (mark)
95 break;
96 (void) read(rem, waste, sizeof (waste));
97 }
d60e8dff
MK
98 if (recv(rem, &mark, 1, MSG_OOB) < 0) {
99 perror("recv");
100 ...
101 }
200989e9
MK
102 ...
103}
104.DE
105.ce
106Figure 5. Flushing terminal i/o on receipt of out of band data.
107.sp
108.KE
109.NH 2
d60e8dff
MK
110Interrupt driven socket i/o
111.PP
112The SIGIO signal allows a process to be notified
113via a signal when a socket (or more generally, a file
114descriptor) has data waiting to be read. Use of
115the SIGIO facility requires three steps: First,
116the process must set up a SIGIO signal handler
117by use of the \fIsignal\fP call. Second,
118it must set the process id or process group id which is to receive
119notification of pending input to its own process id,
120or the process group id of its process group (note that
121the default process group of a socket is group zero).
122This is accomplished by use of a \fIfcntl\fP call.
123Third, it must turn on notification of pending i/o requests
124with another \fIfcntl\fP call. Sample code to
125allow a given process to receive information on
126pending i/o requests as they occur for a socket \fIs\fP
127is given in Figure 6. With slight change, this code can also
128be used to prepare for receipt of SIGURG signals.
129.KF
130.DS
131#include <fcntl.h>
132 ...
133int io_handler();
134 ...
135signal(SIGIO, io_handler);
136
137/* Set the process receiving SIGIO/SIGURG signals to us */
138
139if (fcntl(s, F_SETOWN, getpid()) < 0) {
140 perror("fcntl F_SETOWN");
141 exit(1);
142}
143
144/* Allow receipt of asynchronous i/o signals */
145
146if (fcntl(s, F_SETFL, FASYNC) < 0) {
147 perror("fcntl F_SETFL, FASYNC");
148 exit(1);
149}
150.DE
151.ce
152Figure 6. Use of asynchronous notification of i/o requests.
153.sp
154.KE
155.NH 2
200989e9
MK
156Signals and process groups
157.PP
158Due to the existence of the SIGURG and SIGIO signals each socket has an
d60e8dff
MK
159associated process number, just as is done for terminals.
160This value is initialized to zero,
161but may be redefined at a later time with the F_SETOWN
162\fIfcntl\fP, such as was done in the code above for SIGIO.
163To set the socket's process id for signals, positive arguments
164should be given to the \fIfcntl\fP call. To set the socket's
165process group for signals, negative arguments should be
166passed to \fIfcntl\fP. Note that the process number indicates
167either the associated process id or the associated process
168group; it is impossible to specify both at the same time.
169A similar \fIfcntl\fP, F_GETOWN, is available for determining the
170current process number of a socket.
171.PP
172An old signal which is useful when constructing server processes
173is SIGCHLD. This signal is delivered to a process when any
174children processes have changed state. Normally servers use
175the signal to \*(lqreap\*(rq child processes after exiting.
176For example, the remote login server loop shown in Figure 2
177may be augmented as shown in Figure 7.
178.KF
200989e9 179.DS
d60e8dff
MK
180int reaper();
181 ...
182signal(SIGCHLD, reaper);
183listen(f, 5);
184for (;;) {
185 int g, len = sizeof (from);
186
187 g = accept(f, (struct sockaddr *)&from, &len,);
188 if (g < 0) {
189 if (errno != EINTR)
190 syslog(LOG_ERR, "rlogind: accept: %m");
191 continue;
192 }
193 ...
194}
195 ...
196#include <wait.h>
197reaper()
198{
199 union wait status;
200
201 while (wait3(&status, WNOHANG, 0) > 0)
202 ;
203}
200989e9 204.DE
d60e8dff
MK
205.sp
206.ce
207Figure 7. Use of the SIGCHLD signal.
208.sp
209.KE
210.PP
211If the parent server process fails to reap its children,
212a large number of \*(lqzombie\*(rq processes may be created.
200989e9
MK
213.NH 2
214Pseudo terminals
215.PP
216Many programs will not function properly without a terminal
217for standard input and output. Since a socket is not a terminal,
218it is often necessary to have a process communicating over
219the network do so through a \fIpseudo terminal\fP. A pseudo
220terminal is actually a pair of devices, master and slave,
221which allow a process to serve as an active agent in communication
222between processes and users. Data written on the slave side
223of a pseudo terminal is supplied as input to a process reading
d60e8dff
MK
224from the master side, while data written on the master side is
225given to the slave as input. In this way, the process manipulating
200989e9 226the master side of the pseudo terminal has control over the
d60e8dff
MK
227information read and written on the slave side.
228The purpose of this abstraction is to
229preserve terminal semantics over a network connection \(em
230that is, the slave side looks like a normal terminal to
231any process reading from or writing to it.
232.PP
233For example, the remote
200989e9
MK
234login server uses pseudo terminals for remote login sessions.
235A user logging in to a machine across the network is provided
236a shell with a slave pseudo terminal as standard input, output,
237and error. The server process then handles the communication
238between the programs invoked by the remote shell and the user's
239local client process. When a user sends an interrupt or quit
240signal to a process executing on a remote machine, the client
241login program traps the signal, sends an out of band message
242to the server process who then uses the signal number, sent
243as the data value in the out of band message, to perform a
244\fIkillpg\fP(2) on the appropriate process group.
d60e8dff
MK
245.PP
246Under 4.3BSD, the slave side of a pseudo terminal is
247\fI/dev/ttyxy\fP, where \fIx\fP is a single letter
248starting at `p' and perhaps continuing as far down
249as `t'. \fIy\fP is a hexidecimal ``digit'' (i.e., a single
250character in the range 0 through 9 or `a' through `f').
251The master side of a pseudo terminal is \fI/dev/ptyxy\fP,
252where \fIx\fP and \fIy\fP correspond to the same letters
253in the slave side of the pseudo terminal.
254.PP
255In general, the method of obtaining a pair of master and
256slave pseudo terminals is made up of three components.
257First, the process must find a pseudo terminal which
258is not currently in use. Having done so,
259it then opens both the master and the slave side of
260the device, taking care to open the master side of the device first.
261The process then \fIfork\fPs; the child closes
262the master side of the pseudo terminal, and \fIexec\fPs the
263appropriate program. Meanwhile, the parent closes the
264slave side of the pseudo terminal and begins reading and
265writing from the master side. Sample code making use of
266pseudo terminals is given in Figure 8; this code assumes
267that a connection on a socket \fIs\fP exists, connected
268to a peer who wants a service of some kind, and that the
269process has disassociated itself from a controlling terminal.
270.KF
271.DS
272gotpty = 0;
273for (c = 'p'; !gotpty && c <= 's'; c++) {
274 line = "/dev/ptyXX";
275 line[sizeof("/dev/pty")-1] = c;
276 line[sizeof("/dev/ptyp")-1] = '0';
277 if (stat(line, &statbuf) < 0)
278 break;
279 for (i = 0; i < 16; i++) {
280 line[sizeof("/dev/ptyp")-1] = "0123456789abcdef"[i];
281 master = open(line, O_RDWR);
282 if (master > 0) {
283 gotpty = 1;
284 break;
285 }
286 }
287}
288if (!gotpty) {
289 syslog(LOG_ERR, "All network ports in use");
290 exit(1);
291}
292
293line[sizeof("/dev/")-1] = 't';
294slave = open(line, O_RDWR); /* \fIslave\fP is now slave side */
295if (slave < 0) {
296 syslog(LOG_ERR, "Cannot open slave pty %s", line);
297 exit(1);
298}
299
300ioctl(slave, TIOCGETP, &b); /* Set slave tty modes */
301b.sg_flags = CRMOD|XTABS|ANYP;
302ioctl(slave, TIOCSETP, &b);
303
304i = fork();
305if (i < 0) {
306 syslog(LOG_ERR, "fork: %m");
307 exit(1);
308} else if (i) { /* Parent */
309 close(slave);
310 ...
311} else { /* Child */
312 (void) close(s);
313 (void) close(master);
314 dup2(slave, 0);
315 dup2(slave, 1);
316 dup2(slave, 2);
317 if (slave > 2)
318 (void) close(slave);
319 ...
320}
321.DE
322.ce
323Figure 8. Creation and use of a pseudo terminal
324.sp
325.KE
200989e9 326.NH 2
d60e8dff 327Selecting specific protocols
200989e9 328.PP
d60e8dff
MK
329If the third argument to the \fIsocket\fP call is 0,
330\fIsocket\fP will select a default protocol to use with
331the returned socket of the type requested. This
332protocol should be correct for almost every situation.
333Still, it is conceivable that the user may wish to specify
334a particular protocol for use with a given socket.
335.PP
336To obtain a particular protocol one selects the protocol number,
337as defined within the communication domain. For the Internet
338domain the available protocols are defined in <\fInetinet/in.h\fP>
339or, better yet, one may use one of the library routines
340discussed in section 3, such as \fIgetprotobyname\fP:
341.DS
342#include <sys/types.h>
343#include <sys/socket.h>
344#include <netinet/in.h>
345#include <netdb.h>
346 ...
347pp = getprotobyname("newtcp");
348s = socket(AF_INET, SOCK_STREAM, pp->p_proto);
349.DE
350This would result in a socket \fIs\fP using a stream
351based connection, but with protocol type of ``newtcp''
352instead of the default ``tcp.''
353.PP
354In the NS domain, the available socket protocols are defined in
355<\fInetns/ns.h\fP>. To create a raw socket for Xerox Error Protocol
356messages, one might use:
357.DS
358#include <sys/types.h>
359#include <sys/socket.h>
360#include <netns/ns.h>
361 ...
362s = socket(AF_NS, SOCK_RAW, NSPROTO_ERROR);
363.DE
364.NH 2
365Address binding
366.PP
367As was mentioned in section 2,
368binding addresses to sockets in the Internet and NS domains can be
369fairly complex. As a brief reminder, these associations
370are composed of local and foreign
200989e9 371addresses, and local and foreign ports. Port numbers are
d60e8dff
MK
372allocated out of separate spaces, one for each system and one
373for each domain on that system.
374Through the \fIbind\fP system call, a
375process may specify half of an association, the
376<local address, local port> part, while the
377\fIconnect\fP
378and \fIaccept\fP
379primitives are used to complete a socket's association by
380specifying the <foreign address, foreign port> part.
200989e9 381Since the association is created in two steps the association
d60e8dff 382uniqueness requirement indicated previously could be violated unless
200989e9
MK
383care is taken. Further, it is unrealistic to expect user
384programs to always know proper values to use for the local address
385and local port since a host may reside on multiple networks and
386the set of allocated port numbers is not directly accessible
387to a user.
388.PP
d60e8dff 389To simplify local address binding in the Internet domain the notion of a
200989e9
MK
390\*(lqwildcard\*(rq address has been provided. When an address
391is specified as INADDR_ANY (a manifest constant defined in
392<netinet/in.h>), the system interprets the address as
393\*(lqany valid address\*(rq. For example, to bind a specific
394port number to a socket, but leave the local address unspecified,
395the following code might be used:
396.DS
397#include <sys/types.h>
398#include <netinet/in.h>
399 ...
400struct sockaddr_in sin;
401 ...
402s = socket(AF_INET, SOCK_STREAM, 0);
403sin.sin_family = AF_INET;
d60e8dff
MK
404sin.sin_addr.s_addr = htonl(INADDR_ANY);
405sin.sin_port = htons(MYPORT);
406bind(s, (struct sockaddr *) &sin, sizeof (sin));
200989e9
MK
407.DE
408Sockets with wildcarded local addresses may receive messages
409directed to the specified port number, and addressed to any
d60e8dff
MK
410of the possible addresses assigned to a host. For example,
411if a host is on a networks 128.32 and 10 and a socket is bound as
200989e9
MK
412above, then an accept call is performed, the process will be
413able to accept connection requests which arrive either from
d60e8dff
MK
414network 128.32 or network 10.
415If a server process wished to only allow hosts on a
416given network connect to it, it would bind
417the address of the host on the appropriate network. Such
418an address could perhaps be determined by a routine
419such as \fIgethostbynameandnet\fP, as mentioned in section 3.
200989e9
MK
420.PP
421In a similar fashion, a local port may be left unspecified
422(specified as zero), in which case the system will select an
d60e8dff
MK
423appropriate port number for it. This shortcut will work
424both in the Internet and NS domains. For example, to
425bind a specific local address to a socket, but to leave the
426local port number unspecified:
200989e9 427.DS
d60e8dff
MK
428hp = gethostbyname(hostname);
429if (hp == NULL) {
430 ...
431}
432bcopy(hp->h_addr, (char *) sin.sin_addr, hp->h_length);
433sin.sin_port = htons(0);
434bind(s, (struct sockaddr *) &sin, sizeof (sin));
200989e9 435.DE
d60e8dff
MK
436The system selects the local port number based on two criteria.
437The first is that on 4BSD systems,
438local ports numbered 0 through 1023 (for the Xerox domain,
4390 through 3000) are reserved
440for privileged users (i.e., the super user). The second is
200989e9 441that the port number is not currently bound to some other
d60e8dff
MK
442socket. In order to find a free Internet port number in the privileged
443range the \fIrresvport\fP library routine may be used as follows
444to return a stream socket in with a privileged port number:
200989e9 445.DS
d60e8dff
MK
446int lport = IPPORT_RESERVED \- 1;
447int s;
448...
449s = rresvport(&lport);
450if (s < 0) {
451 if (errno == EAGAIN)
452 fprintf(stderr, "socket: all ports in use\en");
453 else
454 perror("rresvport: socket");
455 ...
200989e9
MK
456}
457.DE
458The restriction on allocating ports was done to allow processes
459executing in a \*(lqsecure\*(rq environment to perform authentication
d60e8dff
MK
460based on the originating address and port number. For example,
461the \fIrlogin\fP(1) command allows users to log in across a network
462without being asked for a password, if two conditions hold:
463First, the name of the system the user
464is logging in from is in the file
465\fI/etc/hosts.equiv\fP on the system he is logging
466in to (or the system name and the user name are in
467the user's \fI.rhosts\fP file in the user's home
468directory), and second, that the user's rlogin
469process is coming from a privileged port on the machine he is
470logging in from. The port number and network address of the
471machine the user is logging in from can be determined either
472by the \fIfrom\fP value-result parameter to the \fIaccept\fP call, or
473from the \fIgetpeername\fP call.
200989e9
MK
474.PP
475In certain cases the algorithm used by the system in selecting
476port numbers is unsuitable for an application. This is due to
477associations being created in a two step process. For example,
478the Internet file transfer protocol, FTP, specifies that data
479connections must always originate from the same local port. However,
480duplicate associations are avoided by connecting to different foreign
481ports. In this situation the system would disallow binding the
482same local address and port number to a socket if a previous data
483connection's socket were around. To override the default port
484selection algorithm then an option call must be performed prior
485to address binding:
486.DS
d60e8dff
MK
487 ...
488int on = 1;
489 ...
490setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
491bind(s, (struct sockaddr *) &sin, sizeof (sin));
200989e9
MK
492.DE
493With the above call, local addresses may be bound which
494are already in use. This does not violate the uniqueness
495requirement as the system still checks at connect time to
496be sure any other sockets with the same local address and
497port do not have the same foreign address and port (if an
498association already exists, the error EADDRINUSE is returned).
200989e9
MK
499.NH 2
500Broadcasting and datagram sockets
501.PP
502By using a datagram socket it is possible to send broadcast
503packets on many networks supported by the system (the network
504itself must support the notion of broadcasting; the system
505provides no broadcast simulation in software). Broadcast
506messages can place a high load on a network since they force
507every host on the network to service them. Consequently,
d60e8dff
MK
508the ability to send broadcast packets has been limited
509to sockets which are explicitly marked as allowing broadcasting.
200989e9 510.PP
d60e8dff 511To send a broadcast message, a datagram socket
200989e9
MK
512should be created:
513.DS
514s = socket(AF_INET, SOCK_DGRAM, 0);
515.DE
d60e8dff
MK
516or
517.DS
518s = socket(AF_NS, SOCK_DGRAM, 0);
519.DE
520The socket is marked as allowing broadcasting,
521.DS
522int on = 1;
523
524setsockopt(s, SOL_SOCKET, SO_BROADCAST, &on, sizeof (on));
525.DE
200989e9
MK
526and at least a port number should be bound to the socket:
527.DS
528sin.sin_family = AF_INET;
d60e8dff
MK
529sin.sin_addr.s_addr = htonl(INADDR_ANY);
530sin.sin_port = htons(MYPORT);
531bind(s, (struct sockaddr *) &sin, sizeof (sin));
532.DE
533or, for the NS domain,
534.DS
535sns.sns_family = AF_NS;
536netnum = htonl(net);
537sns.sns_addr.x_net = *(union ns_net *) &netnum; /* insert net number */
538sns.sns_addr.x_port = htons(MYPORT);
539bind(s, (struct sockaddr *) &sns, sizeof (sns));
540.DE
541The destination address of the message to be broadcast
542depends on the network the message is to be broadcast
543on, and therefore requires some knowledge of the networks
544to which the host is connected. Since this information should
545be obtained in a host-independent fashion, 4.3BSD provides a method of
546retrieving this information from the system data structures.
547The SIOCGIFCONF \fIioctl\fP call returns the interface
548configuration of a host in the form of a
549single \fIifconf\fP structure; this structure contains
550a ``data area'' which is made up of an array of
551of \fIifreq\fP structures, one for each network interface
552to which the host is connected.
553These structures are defined in
554\fI<net/if.h>\fP as follows:
555.DS
556.if t .ta .5i 1.0i 1.5i 3.5i
557.if n .ta .7i 1.4i 2.1i 3.4i
558struct ifconf {
559 int ifc_len; /* size of associated buffer */
560 union {
561 caddr_t ifcu_buf;
562 struct ifreq *ifcu_req;
563 } ifc_ifcu;
564};
565
566#define ifc_buf ifc_ifcu.ifcu_buf /* buffer address */
567#define ifc_req ifc_ifcu.ifcu_req /* array of structures returned */
568
569#define IFNAMSIZ 16
570
571struct ifreq {
572 char ifr_name[IFNAMSIZ]; /* if name, e.g. "en0" */
573 union {
574 struct sockaddr ifru_addr;
575 struct sockaddr ifru_dstaddr;
576 struct sockaddr ifru_broadaddr;
577 short ifru_flags;
578 caddr_t ifru_data;
579 } ifr_ifru;
580};
581
582.if t .ta \w' #define'u +\w' ifr_broadaddr'u +\w' ifr_ifru.ifru_broadaddr'u
583#define ifr_addr ifr_ifru.ifru_addr /* address */
584#define ifr_dstaddr ifr_ifru.ifru_dstaddr /* other end of p-to-p link */
585#define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */
586#define ifr_flags ifr_ifru.ifru_flags /* flags */
587#define ifr_data ifr_ifru.ifru_data /* for use by interface */
588.DE
589The actual call which obtains the
590interface configuration is
591.DS
592struct ifconf ifc;
593char buf[BUFSIZ];
594
595ifc.ifc_len = sizeof (buf);
596ifc.ifc_buf = buf;
597if (ioctl(s, SIOCGIFCONF, (char *) &ifc) < 0) {
598 ...
599}
200989e9 600.DE
d60e8dff
MK
601After this call \fIbuf\fP will contain one \fIifreq\fP structure for
602each network to which the host is connected, and
603\fIifc.ifc_len\fP will have been modified to reflect the number
604of bytes used by the \fIifreq\fP structures.
605.PP
606For each structure
607there exists a set of ``interface flags'' which tell
608whether the network corresponding to that interface is
609up or down, point to point or broadcast, etc. The
610SIOCGIFFLAGS \fIioctl\fP retrieves these
611flags for an interface specified by an \fIifreq\fP
612structure as follows:
200989e9 613.DS
d60e8dff
MK
614struct ifreq *ifr;
615
616ifr = ifc.ifc_req;
617
618for (n = ifc.ifc_len / sizeof (struct ifreq); --n >= 0; ifr++) {
619 /*
620 * We must be careful that we don't use an interface
621 * devoted to an address family other than our own;
622 * if we were interested in NS interfaces, the
623 * AF_INET would be AF_NS.
624 */
625 if (ifr->ifr_addr.sa_family != AF_INET)
626 continue;
627 if (ioctl(s, SIOCGIFFLAGS, (char *) ifr) < 0) {
628 ...
629 }
630 if ((ifr->ifr_flags & IFF_UP) == 0 || /* Skip boring cases */
631 (ifr->ifr_flags & (IFF_BROADCAST | IFF_POINTTOPOINT)) == 0)
632 continue;
200989e9 633.DE
d60e8dff
MK
634.PP
635Once the flags have been obtained, the broadcast address
636must be obtained. In the case of broadcast networks this is
637done via the SIOCGIFBRDADDR \fIioctl\fP, while for point-to-point networks
638the address of the destination host is obtained with SIOCGIFDSTADDR.
639.DS
640struct sockaddr dst;
641
642if (ifr->ifr_flags & IFF_POINTTOPOINT) {
643 if (ioctl(s, SIOCGIFDSTADDR, (char *) ifr) < 0) {
644 ...
645 }
646 bcopy((char *) ifr->ifr_dstaddr, (char *) &dst, sizeof (ifr->ifr_dstaddr));
647} else if (ifr->ifr_flags & IFF_BROADCAST) {
648 if (ioctl(s, SIOCGIFBRDADDR, (char *) ifr) < 0) {
649 ...
650 }
651 bcopy((char *) ifr->ifr_broadaddr, (char *) &dst, sizeof (ifr->ifr_broadaddr));
652}
653.DE
654.PP
655After the appropriate \fIioctl\fP's have obtained the broadcast
656or destination address (now in \fIdst\fP), the \fIsendto\fP call may be
657used:
200989e9 658.DS
d60e8dff
MK
659 sendto(s, buf, buflen, 0, (struct sockaddr *)&dst, sizeof (dst));
660}
200989e9 661.DE
d60e8dff
MK
662In the above loop one \fIsendto\fP occurs for every
663interface the host is connected to which supports the notion of
664broadcast or point-to-point addressing.
665If a process only wished to send broadcast
666messages on a given network, code similar to that outlined above
667would be used, but the loop would need to find the
668correct destination address.
200989e9
MK
669.PP
670Received broadcast messages contain the senders address
d60e8dff
MK
671and port, as datagram sockets are bound before
672a message is allowed to go out.
200989e9 673.NH 2
d60e8dff 674Socket Options
200989e9 675.PP
d60e8dff
MK
676It is possible to set and get a number of options on sockets
677via the \fIsetsockopt\fP and \fIgetsockopt\fP system calls.
678These options include such things as marking a socket for
679broadcasting, not to route, to linger on close, etc.
680The general forms of the calls are:
200989e9 681.DS
d60e8dff
MK
682setsockopt(s, level, optname, optval, optlen);
683.DE
684and
685.DS
686getsockopt(s, level, optname, optval, optlen);
687.DE
688.PP
689The parameters to the calls are as follows: \fIs\fP
690is the socket on which the option is to be applied.
691\fILevel\fP specifies the protocol layer on which the
692option is to be applied; in most cases this is
693the ``socket level'', indicated by the symbolic constant
694SOL_SOCKET, defined in \fI<sys/socket.h>.\fP
695The actual option is specified in \fIoptname\fP, and is
696a symbolic constant also defined in \fI<sys/socket.h>\fP.
697\fIOptval\fP and \fIOptlen\fP point to the value of the
698option (in most cases, whether the option is to be turned
699on or off), and the length of the value of the option,
700respectively.
701For \fIgetsockopt\fP, \fIoptlen\fP is
702a value-result parameter, initially set to the size of
703the storage area pointed to by \fIoptval\fP, and modified
704upon return to indicate the actual amount of storage used.
705.PP
706An example should help clarify things. It is sometimes
707useful to determine the type (e.g., stream, datagram, etc.)
708of an existing socket; programs
709under \fIinetd\fP (described below) may need to perform this
710task. This can be accomplished as follows via the
711SO_TYPE socket option and the \fIgetsockopt\fP call:
712.DS
713#include <sys/types.h>
714#include <sys/socket.h>
200989e9 715
d60e8dff
MK
716int type, size;
717
718size = sizeof (int);
719
720if (getsockopt(s, SOL_SOCKET, SO_TYPE, (char *) &type, &size) < 0) {
200989e9
MK
721 ...
722}
d60e8dff
MK
723.DE
724After the \fIgetsockopt\fP call, \fItype\fP will be set
725to the value of the socket type, as defined in
726\fI<sys/socket.h>\fP. If, for example, the socket were
727a datagram socket, \fItype\fP would have the value
728corresponding to SOCK_DGRAM.
729.NH 2
730NS Packet Sequences
731.PP
732The semantics of NS connections demand that
733the user both be able to look inside the network header associated
734with any incoming packet and be able to specify what should go
735in certain fields of an outgoing packet. The header of an
736IDP-level packet looks like:
737.DS
738.if t .ta \w'struct 'u +\w" struct ns_addr"u +2.0i
739struct idp {
740 u_short idp_sum; /* Checksum */
741 u_short idp_len; /* Length, in bytes, including header */
742 u_char idp_tc; /* Transport Control (i.e., hop count) */
743 u_char idp_pt; /* Packet Type (i.e., level 2 protocol) */
744 struct ns_addr idp_dna; /* Destination Network Address */
745 struct ns_addr idp_sna; /* Source Network Address */
746};
747.DE
748Most of the fields are filled in automatically; the only
749field that the user should be concerned with is the
750\fIpacket type\fP field. The standard values for this
751field are (as defined in <\fInetns/ns.h\fP>):
752.DS
753.if t .ta \w" #define"u +\w" NSPROTO_ERROR"u +1.0i
754#define NSPROTO_RI 1 /* Routing Information */
755#define NSPROTO_ECHO 2 /* Echo Protocol */
756#define NSPROTO_ERROR 3 /* Error Protocol */
757#define NSPROTO_PE 4 /* Packet Exchange */
758#define NSPROTO_SPP 5 /* Sequenced Packet */
759.DE
760For SPP connections, the contents of this field are
761automatically set to NSPROTO_SPP; for IDP packets,
762this value defaults to zero, which means ``unknown''.
763.PP
764The contents of a SPP header (minus the IDP header) are:
765.DS
766.if t .ta \w" #define"u +\w" u_short"u +2.0i
767struct sphdr {
768 u_char sp_cc; /* connection control */
769#define SP_SP 0x80 /* system packet */
770#define SP_SA 0x40 /* send acknowledgement */
771#define SP_OB 0x20 /* attention (out of band data) */
772#define SP_EM 0x10 /* end of message */
773 u_char sp_dt; /* datastream type */
774 u_short sp_sid; /* source connection identifier */
775 u_short sp_did; /* destination connection identifier */
776 u_short sp_seq; /* sequence number */
777 u_short sp_ack; /* acknowledge number */
778 u_short sp_alo; /* allocation number */
779};
780.DE
781Here, the items of interest are the \fIdatastream type\fP and
782the \fIconnection control\fP fields. The semantics of the
783datastream type are defined by the application(s) in question;
784the value of this field is, by default, zero, but it can be
785used to indicate things such as Xerox's Bulk Data Transfer
786Protocol (in which case it is set to one). The connection control
787field is a mask of the flags defined above. The user may
788set or clear the end-of-message bit to indicate
789that a given message is the last of a given substream type,
790or may set/clear the attention bit as an alternate way to
791indicate that a packet should be sent out-of-band.
792.PP
793Using different calls to \fIsetsockopt\fP, is it possible
794to indicate whether prototype headers will be associated by
795the user with each outgoing packet (SO_HEADERS_ON_OUTPUT),
796to indicate whether the headers received by the system should be
797delivered to the user (SO_HEADERS_ON_INPUT), or to indicate
798default information that should be associated with all
799outgoing packets on a given socket (SO_DEFAULT_HEADERS).
800For example, to associate prototype headers with outgoing
801SPP packets, one might use:
802.DS
803#include <sys/types.h>
804#include <sys/socket.h>
805#include <netns/ns.h>
806#include <netns/sp.h>
200989e9 807 ...
d60e8dff
MK
808struct sockaddr_ns sns, to;
809int s, on = 1;
810struct databuf {
811 struct sphdr proto_spp; /* prototype header */
812 char buf[534]; /* max. possible data by Xerox std. */
813} buf;
814 ...
815s = socket(AF_NS, SOCK_SEQPACKET, 0);
816 ...
817bind(s, (struct sockaddr *) &sns, sizeof (sns));
818setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_OUTPUT, &on, sizeof(on));
819 ...
820buf.proto_spp.sp_dt = 1; /* bulk data */
821buf.proto_spp.sp_cc = SP_EM; /* end-of-message */
822strcpy(buf.buf, "hello world\en");
823sendto(s, (char *) &buf, sizeof(struct sphdr) + strlen("hello world\en"),
824 (struct sockaddr *) &to, sizeof(to));
825 ...
826.DE
827Note that one must be careful when writing headers; if the prototype
828header is not written with the data with which it is to be associated,
829the kernel will treat the first few bytes of the data as the
830header, with unpredictable results.
831To turn off the above association, and to indicate that packet
832headers received by the system should be passed up to the user,
833one might use:
834.DS
835#include <sys/types.h>
836#include <sys/socket.h>
837#include <netns/ns.h>
838#include <netns/sp.h>
839 ...
840struct sockaddr sns;
841int s, on = 1, off = 0;
842 ...
843s = socket(AF_NS, SOCK_SEQPACKET, 0);
844 ...
845bind(s, (struct sockaddr *) &sns, sizeof (sns));
846setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_OUTPUT, &off, sizeof(off));
847setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_INPUT, &on, sizeof(on));
848 ...
849.DE
850To indicate a default prototype header to be associated with
851the outgoing packets on an IDP datagram socket, one would use:
852.DS
853#include <sys/types.h>
854#include <sys/socket.h>
855#include <netns/ns.h>
856#include <netns/idp.h>
857 ...
858struct sockaddr sns;
859struct idp proto_idp; /* prototype header */
860int s, on = 1;
861 ...
862s = socket(AF_NS, SOCK_DGRAM, 0);
863 ...
864bind(s, (struct sockaddr *) &sns, sizeof (sns));
865proto_idp.idp_pt = NSPROTO_PE; /* packet exchange */
866setsockopt(s, NSPROTO_IDP, SO_DEFAULT_HEADERS, (char *) &proto_idp,
867 sizeof(proto_idp));
868 ...
869.DE
870.NH 2
871Three-way Handshake
872.PP
873The semantics of SPP connections indicates that a three-way
874handshake, involving changes in the datastream type, should \(em
875but is not absolutely required to \(em take place before a SPP
876connection is closed. Almost all SPP connections are
877``well-behaved'' in this manner; when communicating with
878any process, it is best to assume that the three-way handshake
879is required unless it is known for certain that it is not
880required. In a three-way close, the closing process
881indicates that it wishes to close the connection by sending
882a zero-length packet with end-of-message set and with
883datastream type 254. The other side of the connection
884indicates that it is OK to close by sending a zero-length
885packet with end-of-message set and datastream type 255. Finally,
886the closing process replies with a zero-length packet with
887substream type 255; at this point, the connection is considered
888closed. The following code fragments are simplified examples
889of how one might handle this three-way handshake at the user
890level; in the future, support for this type of close will
891probably be provided as part of the C library or as part of
892the kernel. The first code fragment below illustrates how a process
893might handle three-way handshake if it sees that the process it
894is communicating with wants to close the connection:
895.DS
896#include <sys/types.h>
897#include <sys/socket.h>
898#include <netns/ns.h>
899#include <netns/sp.h>
900 ...
901#ifndef SPPSST_END
902#define SPPSST_END 254
903#define SPPSST_ENDREPLY 255
904#endif
905struct sphdr proto_sp;
906int s;
907 ...
908read(s, buf, BUFSIZE);
909if (((struct sphdr *)buf)->sp_dt == SPPSST_END) {
910 /*
911 * SPPSST_END indicates that the other side wants to
912 * close.
913 */
914 proto_sp.sp_dt = SPPSST_ENDREPLY;
915 proto_sp.sp_cc = SP_EM;
916 setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp,
917 sizeof(proto_sp));
918 write(s, buf, 0);
919 /*
920 * Write a zero-length packet with datastream type = SPPSST_ENDREPLY
921 * to indicate that the close is OK with us. The packet that we
922 * don't see (because we don't look for it) is another packet
923 * from the other side of the connection, with SPPSST_ENDREPLY
924 * on it it, too. Once that packet is sent, the connection is
925 * considered closed; note that we really ought to retransmit
926 * the close for some time if we do not get a reply.
927 */
928 close(s);
929}
930 ...
931.DE
932To indicate to another process that we would like to close the
933connection, the following code would suffice:
934.DS
935#include <sys/types.h>
936#include <sys/socket.h>
937#include <netns/ns.h>
938#include <netns/sp.h>
939 ...
940#ifndef SPPSST_END
941#define SPPSST_END 254
942#define SPPSST_ENDREPLY 255
943#endif
944struct sphdr proto_sp;
945int s;
946 ...
947proto_sp.sp_dt = SPPSST_END;
948proto_sp.sp_cc = SP_EM;
949setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp,
950 sizeof(proto_sp));
951write(s, buf, 0); /* send the end request */
952proto_sp.sp_dt = SPPSST_ENDREPLY;
953setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp,
954 sizeof(proto_sp));
955/*
956 * We assume (perhaps unwisely)
957 * that the other side will send the
958 * ENDREPLY, so we'll just send our final ENDREPLY
959 * as if we'd seen theirs already.
960 */
961write(s, buf, 0);
962close(s);
963 ...
964.DE
965.NH 2
966Packet Exchange
967.PP
968The Xerox standard protocols include a protocol that is both
969reliable and datagram-oriented. This protocol is known as
970Packet Exchange (PEX or PE) and, like SPP, is layered on top
971of IDP. PEX is important for a number of things: Courier
972remote procedure calls may be expedited through the use
973of PEX, and many Xerox servers are located by doing a PEX
974``BroadcastForServers'' operation. Although there is no
975implementation of PEX in the kernel,
976it may be simulated at the user level with some clever coding
977and the use of one peculiar \fIgetsockopt\fP. A PEX packet
978looks like:
979.DS
980.if t .ta \w'struct 'u +\w" struct idp"u +2.0i
981/*
982 * The packet-exchange header shown here is not defined
983 * as part of any of the system include files.
984 */
985struct pex {
986 struct idp p_idp; /* idp header */
987 u_short ph_id[2]; /* unique transaction ID for pex */
988 u_short ph_client; /* client type field for pex */
989};
990.DE
991The \fIph_id\fP field is used to hold a ``unique id'' that
992is used in duplicate suppression; the \fIph_client\fP
993field indicates the PEX client type (similar to the packet
994type field in the IDP header). PEX reliability stems from the
995fact that it is an idempotent (``I send a packet to you, you
996send a packet to me'') protocol. Processes on each side of
997the connection may use the unique id to determine if they have
998seen a given packet before (the unique id field differs on each
999packet sent) so that duplicates may be detected, and to indicate
1000which message a given packet is in response to. If a packet with
1001a given unique id is sent and no response is received in a given
1002amount of time, the packet is retransmitted until it is decided
1003that no response will ever be received. To simulate PEX, one
1004must be able to generate unique ids -- something that is hard to
1005do at the user level with any real guarantee that the id is really
1006unique. Therefore, a means (via \fIgetsockopt\fP) has been provided
1007for getting unique ids from the kernel. The following code fragment
1008indicates how to get a unique id:
1009.DS
1010long uniqueid;
1011int s, idsize = sizeof(uniqueid);
1012 ...
1013s = socket(AF_NS, SOCK_DGRAM, 0);
1014 ...
1015/* get id from the kernel -- only on IDP sockets */
1016getsockopt(s, NSPROTO_PE, SO_SEQNO, (char *)&uniqueid, &idsize);
1017 ...
1018.DE
1019The retransmission and duplicate suppression code required to
1020simulate PEX fully is left as an exercise for the reader.
1021.NH 2
1022Non-Blocking Sockets
1023.PP
1024It is occasionally convenient to make use of sockets
1025which do not block; that is, i/o requests which
1026would take time and
1027would cause the process to wait for their completion are
1028not executed, and an error code is returned.
1029Once a socket has been created via
1030the \fIsocket\fP call, it may be marked as non-blocking
1031by \fIfcntl\fP as follows:
1032.DS
1033#include <fcntl.h>
1034 ...
1035int s;
1036 ...
1037s = socket(AF_INET, SOCK_STREAM, 0);
1038 ...
1039if (fcntl(s, F_SETFL, FNDELAY) < 0)
1040 perror("fcntl F_SETFL, FNDELAY");
1041 exit(1);
200989e9 1042}
d60e8dff 1043 ...
200989e9
MK
1044.DE
1045.PP
d60e8dff
MK
1046When performing non-blocking i/o on sockets, one must be
1047careful to check for the error EWOULDBLOCK (stored in the
1048global variable \fIerrno\fP), which occurs when
1049an operation would normally block, but the socket it
1050was performed on is marked as non-blocking.
1051In particular, \fIaccept\fP, \fIconnect\fP, \fIsend\fP, \fIrecv\fP,
1052\fIread\fP, and \fIwrite\fP can
1053all return EWOULDBLOCK, and processes should be prepared
1054to deal with such return codes.
1055.NH 2
1056Inetd
1057.PP
1058One of the daemons provided with 4.3BSD is \fIinetd\fP, the
1059so called ``internet super-server.'' \fIInetd\fP is invoked at boot
1060time, and determines from the file \fI/etc/inetd.conf\fP the
1061servers for which it is to listen. Once this information has been
1062read and a pristine environment created, \fIinetd\fP proceeds
1063to create one socket for each service it is to listen for,
1064binding the appropriate port number to each socket.
1065.PP
1066\fIInetd\fP then performs a \fIselect\fP on all these
1067sockets for read availability, waiting for somebody wishing
1068a connection to the service corresponding to
1069that socket. \fIInetd\fP then performs an \fIaccept\fP on
1070the socket in question, \fIfork\fPs, \fIdup\fPs the new
1071socket to file descriptors 0 and 1 (stdin and
1072stdout), closes other open file
1073descriptors, and \fIexec\fPs the appropriate server.
1074.PP
1075Servers making use of \fIinetd\fP are considerably simplified,
1076as \fIinetd\fP takes care of the majority of the IPC work
1077required in establishing a connection. The server invoked
1078by \fIinetd\fP expects the socket connected to its client
1079on file descriptors 0 and 1, and may immediately perform
1080any operations such as \fIread\fP, \fIwrite\fP, \fIsend\fP,
1081or \fIrecv\fP. Indeed, servers may use
1082buffered i/o as provided by the ``stdio'' conventions, as
1083long as as they remember to use \fIfflush\fP when appropriate.
1084.PP
1085One call which may be of interest to individuals writing
1086servers under \fIinetd\fP is the \fIgetpeername\fP call,
1087which returns the address of the peer (process) connected
1088on the other end of the socket. For example, to log the
1089Internet address in ``dot notation'' (e.g., ``128.32.0.4'')
1090of a client connected to a server under
1091\fIinetd\fP, the following code might be used:
1092.DS
1093struct sockaddr_in name;
1094int namelen = sizeof (name);
1095 ...
1096if (getpeername(0, (struct sockaddr *)&name, &namelen) < 0) {
1097 syslog(LOG_ERR, "getpeername: %m");
1098 exit(1);
1099} else
1100 syslog(LOG_INFO, "Connection from %s", inet_ntoa(name.sin_addr));
1101 ...
1102.DE
1103While the \fIgetpeername\fP call is especially useful when
1104writing programs to run with \fIinetd\fP, it can be used
1105at any time. Be warned, however, that \fIgetpeername\fP will
1106fail on UNIX domain sockets, as their addresses (i.e., pathnames)
1107are inaccessible.