Initial import from FreeBSD RELENG_4:
[dragonfly.git] / share / doc / psd / 21.ipc / 5.t
1 .\" Copyright (c) 1986, 1993
2 .\"     The Regents of the University of California.  All rights reserved.
3 .\"
4 .\" Redistribution and use in source and binary forms, with or without
5 .\" modification, are permitted provided that the following conditions
6 .\" are met:
7 .\" 1. Redistributions of source code must retain the above copyright
8 .\"    notice, this list of conditions and the following disclaimer.
9 .\" 2. Redistributions in binary form must reproduce the above copyright
10 .\"    notice, this list of conditions and the following disclaimer in the
11 .\"    documentation and/or other materials provided with the distribution.
12 .\" 3. All advertising materials mentioning features or use of this software
13 .\"    must display the following acknowledgement:
14 .\"     This product includes software developed by the University of
15 .\"     California, Berkeley and its contributors.
16 .\" 4. Neither the name of the University nor the names of its contributors
17 .\"    may be used to endorse or promote products derived from this software
18 .\"    without specific prior written permission.
19 .\"
20 .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 .\" SUCH DAMAGE.
31 .\"
32 .\"     @(#)5.t 8.1 (Berkeley) 8/14/93
33 .\" $FreeBSD: src/share/doc/psd/21.ipc/5.t,v 1.5 1999/08/28 00:18:26 peter Exp $
34 .\"
35 .\".ds RH "Advanced Topics
36 .bp
37 .nr H1 5
38 .nr H2 0
39 .LG
40 .B
41 .ce
42 5. ADVANCED TOPICS
43 .sp 2
44 .R
45 .NL
46 .PP
47 A number of facilities have yet to be discussed.  For most users
48 of the IPC the mechanisms already
49 described will suffice in constructing distributed
50 applications.  However, others will find the need to utilize some
51 of the features which we consider in this section.
52 .NH 2
53 Out of band data
54 .PP
55 The stream socket abstraction includes the notion of \*(lqout
56 of band\*(rq data.  Out of band data is a logically independent 
57 transmission channel associated with each pair of connected
58 stream sockets.  Out of band data is delivered to the user
59 independently of normal data.
60 The abstraction defines that the out of band data facilities
61 must support the reliable delivery of at least one
62 out of band message at a time.  This message may contain at least one
63 byte of data, and at least one message may be pending delivery
64 to the user at any one time.  For communications protocols which
65 support only in-band signaling (i.e. the urgent data is
66 delivered in sequence with the normal data), the system normally extracts
67 the data from the normal data stream and stores it separately.
68 This allows users to choose between receiving the urgent data
69 in order and receiving it out of sequence without having to
70 buffer all the intervening data.  It is possible
71 to ``peek'' (via MSG_PEEK) at out of band data.
72 If the socket has a process group, a SIGURG signal is generated
73 when the protocol is notified of its existence.
74 A process can set the process group
75 or process id to be informed by the SIGURG signal via the
76 appropriate \fIfcntl\fP call, as described below for
77 SIGIO.
78 If multiple sockets may have out of band data awaiting
79 delivery, a \fIselect\fP call for exceptional conditions
80 may be used to determine those sockets with such data pending.
81 Neither the signal nor the select indicate the actual arrival
82 of the out-of-band data, but only notification that it is pending.
83 .PP
84 In addition to the information passed, a logical mark is placed in
85 the data stream to indicate the point at which the out
86 of band data was sent.  The remote login and remote shell
87 applications use this facility to propagate signals between
88 client and server processes.  When a signal
89 flushs any pending output from the remote process(es), all
90 data up to the mark in the data stream is discarded.
91 .PP
92 To send an out of band message the MSG_OOB flag is supplied to
93 a \fIsend\fP or \fIsendto\fP calls,
94 while to receive out of band data MSG_OOB should be indicated
95 when performing a \fIrecvfrom\fP or \fIrecv\fP call.
96 To find out if the read pointer is currently pointing at
97 the mark in the data stream, the SIOCATMARK ioctl is provided:
98 .DS
99 ioctl(s, SIOCATMARK, &yes);
100 .DE
101 If \fIyes\fP is a 1 on return, the next read will return data
102 after the mark.  Otherwise (assuming out of band data has arrived), 
103 the next read will provide data sent by the client prior
104 to transmission of the out of band signal.  The routine used
105 in the remote login process to flush output on receipt of an
106 interrupt or quit signal is shown in Figure 5.
107 It reads the normal data up to the mark (to discard it),
108 then reads the out-of-band byte.
109 .KF
110 .DS
111 #include <sys/ioctl.h>
112 #include <sys/file.h>
113  ...
114 oob()
115 {
116         int out = FWRITE, mark;
117         char waste[BUFSIZ];
118
119         /* flush local terminal output */
120         ioctl(1, TIOCFLUSH, (char *)&out);
121         for (;;) {
122                 if (ioctl(rem, SIOCATMARK, &mark) < 0) {
123                         perror("ioctl");
124                         break;
125                 }
126                 if (mark)
127                         break;
128                 (void) read(rem, waste, sizeof (waste));
129         }
130         if (recv(rem, &mark, 1, MSG_OOB) < 0) {
131                 perror("recv");
132                 ...
133         }
134         ...
135 }
136 .DE
137 .ce
138 Figure 5.  Flushing terminal I/O on receipt of out of band data.
139 .sp
140 .KE
141 .PP
142 A process may also read or peek at the out-of-band data
143 without first reading up to the mark.
144 This is more difficult when the underlying protocol delivers
145 the urgent data in-band with the normal data, and only sends
146 notification of its presence ahead of time (e.g., the TCP protocol
147 used to implement streams in the Internet domain).
148 With such protocols, the out-of-band byte may not yet have arrived
149 when a \fIrecv\fP is done with the MSG_OOB flag.
150 In that case, the call will return an error of EWOULDBLOCK.
151 Worse, there may be enough in-band data in the input buffer
152 that normal flow control prevents the peer from sending the urgent data
153 until the buffer is cleared.
154 The process must then read enough of the queued data
155 that the urgent data may be delivered.
156 .PP
157 Certain programs that use multiple bytes of urgent data and must
158 handle multiple urgent signals (e.g., \fItelnet\fP\|(1C))
159 need to retain the position of urgent data within the stream.
160 This treatment is available as a socket-level option, SO_OOBINLINE;
161 see \fIsetsockopt\fP\|(2) for usage.
162 With this option, the position of urgent data (the \*(lqmark\*(rq)
163 is retained, but the urgent data immediately follows the mark
164 within the normal data stream returned without the MSG_OOB flag.
165 Reception of multiple urgent indications causes the mark to move,
166 but no out-of-band data are lost.
167 .NH 2
168 Non-Blocking Sockets
169 .PP
170 It is occasionally convenient to make use of sockets
171 which do not block; that is, I/O requests which
172 cannot complete immediately and
173 would therefore cause the process to be suspended awaiting completion are
174 not executed, and an error code is returned.
175 Once a socket has been created via
176 the \fIsocket\fP call, it may be marked as non-blocking
177 by \fIfcntl\fP as follows:
178 .DS
179 #include <fcntl.h>
180  ...
181 int     s;
182  ...
183 s = socket(AF_INET, SOCK_STREAM, 0);
184  ...
185 if (fcntl(s, F_SETFL, FNDELAY) < 0)
186         perror("fcntl F_SETFL, FNDELAY");
187         exit(1);
188 }
189  ...
190 .DE
191 .PP
192 When performing non-blocking I/O on sockets, one must be
193 careful to check for the error EWOULDBLOCK (stored in the
194 global variable \fIerrno\fP), which occurs when
195 an operation would normally block, but the socket it
196 was performed on is marked as non-blocking.
197 In particular, \fIaccept\fP, \fIconnect\fP, \fIsend\fP, \fIrecv\fP,
198 \fIread\fP, and \fIwrite\fP can
199 all return EWOULDBLOCK, and processes should be prepared
200 to deal with such return codes.
201 If an operation such as a \fIsend\fP cannot be done in its entirety,
202 but partial writes are sensible (for example, when using a stream socket),
203 the data that can be sent immediately will be processed,
204 and the return value will indicate the amount actually sent.
205 .NH 2
206 Interrupt driven socket I/O
207 .PP
208 The SIGIO signal allows a process to be notified
209 via a signal when a socket (or more generally, a file
210 descriptor) has data waiting to be read.  Use of
211 the SIGIO facility requires three steps:  First,
212 the process must set up a SIGIO signal handler
213 by use of the \fIsignal\fP or \fIsigvec\fP calls.  Second,
214 it must set the process id or process group id which is to receive
215 notification of pending input to its own process id,
216 or the process group id of its process group (note that
217 the default process group of a socket is group zero).
218 This is accomplished by use of an \fIfcntl\fP call.
219 Third, it must enable asynchronous notification of pending I/O requests
220 with another \fIfcntl\fP call.  Sample code to
221 allow a given process to receive information on
222 pending I/O requests as they occur for a socket \fIs\fP
223 is given in Figure 6.  With the addition of a handler for SIGURG,
224 this code can also be used to prepare for receipt of SIGURG signals.
225 .KF
226 .DS
227 #include <fcntl.h>
228  ...
229 int     io_handler();
230  ...
231 signal(SIGIO, io_handler);
232
233 /* Set the process receiving SIGIO/SIGURG signals to us */
234
235 if (fcntl(s, F_SETOWN, getpid()) < 0) {
236         perror("fcntl F_SETOWN");
237         exit(1);
238 }
239
240 /* Allow receipt of asynchronous I/O signals */
241
242 if (fcntl(s, F_SETFL, FASYNC) < 0) {
243         perror("fcntl F_SETFL, FASYNC");
244         exit(1);
245 }
246 .DE
247 .ce
248 Figure 6.  Use of asynchronous notification of I/O requests.
249 .sp
250 .KE
251 .NH 2
252 Signals and process groups
253 .PP
254 Due to the existence of the SIGURG and SIGIO signals each socket has an
255 associated process number, just as is done for terminals.
256 This value is initialized to zero,
257 but may be redefined at a later time with the F_SETOWN
258 \fIfcntl\fP, such as was done in the code above for SIGIO.
259 To set the socket's process id for signals, positive arguments
260 should be given to the \fIfcntl\fP call.  To set the socket's
261 process group for signals, negative arguments should be 
262 passed to \fIfcntl\fP.  Note that the process number indicates
263 either the associated process id or the associated process
264 group; it is impossible to specify both at the same time.
265 A similar \fIfcntl\fP, F_GETOWN, is available for determining the
266 current process number of a socket.
267 .PP
268 Another signal which is useful when constructing server processes
269 is SIGCHLD.  This signal is delivered to a process when any
270 child processes have changed state.  Normally servers use
271 the signal to \*(lqreap\*(rq child processes that have exited
272 without explicitly awaiting their termination
273 or periodic polling for exit status.
274 For example, the remote login server loop shown in Figure 2
275 may be augmented as shown in Figure 7.
276 .KF
277 .DS
278 int reaper();
279  ...
280 signal(SIGCHLD, reaper);
281 listen(f, 5);
282 for (;;) {
283         int g, len = sizeof (from);
284
285         g = accept(f, (struct sockaddr *)&from, &len,);
286         if (g < 0) {
287                 if (errno != EINTR)
288                         syslog(LOG_ERR, "rlogind: accept: %m");
289                 continue;
290         }
291         ...
292 }
293  ...
294 #include <wait.h>
295 reaper()
296 {
297         union wait status;
298
299         while (wait3(&status, WNOHANG, 0) > 0)
300                 ;
301 }
302 .DE
303 .sp
304 .ce
305 Figure 7.  Use of the SIGCHLD signal.
306 .sp
307 .KE
308 .PP
309 If the parent server process fails to reap its children,
310 a large number of \*(lqzombie\*(rq processes may be created.
311 .NH 2
312 Pseudo terminals
313 .PP
314 Many programs will not function properly without a terminal
315 for standard input and output.  Since sockets do not provide
316 the semantics of terminals,
317 it is often necessary to have a process communicating over
318 the network do so through a \fIpseudo-terminal\fP.  A pseudo-
319 terminal is actually a pair of devices, master and slave,
320 which allow a process to serve as an active agent in communication
321 between processes and users.  Data written on the slave side
322 of a pseudo-terminal is supplied as input to a process reading
323 from the master side, while data written on the master side are
324 processed as terminal input for the slave.
325 In this way, the process manipulating
326 the master side of the pseudo-terminal has control over the
327 information read and written on the slave side
328 as if it were manipulating the keyboard and reading the screen
329 on a real terminal.
330 The purpose of this abstraction is to
331 preserve terminal semantics over a network connection\(em
332 that is, the slave side appears as a normal terminal to
333 any process reading from or writing to it.
334 .PP
335 For example, the remote
336 login server uses pseudo-terminals for remote login sessions.
337 A user logging in to a machine across the network is provided
338 a shell with a slave pseudo-terminal as standard input, output,
339 and error.  The server process then handles the communication
340 between the programs invoked by the remote shell and the user's
341 local client process.
342 When a user sends a character that generates an interrupt
343 on the remote machine that flushes terminal output,
344 the pseudo-terminal generates a control message for the server process.
345 The server then sends an out of band message
346 to the client process to signal a flush of data at the real terminal
347 and on the intervening data buffered in the network.
348 .PP
349 Under 4.4BSD, the name of the slave side of a pseudo-terminal is of the form
350 \fI/dev/ttyxy\fP, where \fIx\fP is a single letter
351 starting at `p' and continuing to `t'.
352 \fIy\fP is a hexadecimal digit (i.e., a single
353 character in the range 0 through 9 or `a' through `f').
354 The master side of a pseudo-terminal is \fI/dev/ptyxy\fP,
355 where \fIx\fP and \fIy\fP correspond to the
356 slave side of the pseudo-terminal.
357 .PP
358 In general, the method of obtaining a pair of master and
359 slave pseudo-terminals is to
360 find a pseudo-terminal which
361 is not currently in use.
362 The master half of a pseudo-terminal is a single-open device;
363 thus, each master may be opened in turn until an open succeeds.
364 The slave side of the pseudo-terminal is then opened,
365 and is set to the proper terminal modes if necessary.
366 The process then \fIfork\fPs; the child closes
367 the master side of the pseudo-terminal, and \fIexec\fPs the
368 appropriate program.  Meanwhile, the parent closes the
369 slave side of the pseudo-terminal and begins reading and
370 writing from the master side.  Sample code making use of
371 pseudo-terminals is given in Figure 8; this code assumes
372 that a connection on a socket \fIs\fP exists, connected
373 to a peer who wants a service of some kind, and that the
374 process has disassociated itself from any previous controlling terminal.
375 .KF
376 .DS
377 gotpty = 0;
378 for (c = 'p'; !gotpty && c <= 's'; c++) {
379         line = "/dev/ptyXX";
380         line[sizeof("/dev/pty")-1] = c;
381         line[sizeof("/dev/ptyp")-1] = '0';
382         if (stat(line, &statbuf) < 0)
383                 break;
384         for (i = 0; i < 16; i++) {
385                 line[sizeof("/dev/ptyp")-1] = "0123456789abcdef"[i];
386                 master = open(line, O_RDWR);
387                 if (master > 0) {
388                         gotpty = 1;
389                         break;
390                 }
391         }
392 }
393 if (!gotpty) {
394         syslog(LOG_ERR, "All network ports in use");
395         exit(1);
396 }
397
398 line[sizeof("/dev/")-1] = 't';
399 slave = open(line, O_RDWR);     /* \fIslave\fP is now slave side */
400 if (slave < 0) {
401         syslog(LOG_ERR, "Cannot open slave pty %s", line);
402         exit(1);
403 }
404
405 ioctl(slave, TIOCGETP, &b);     /* Set slave tty modes */
406 b.sg_flags = CRMOD|XTABS|ANYP;
407 ioctl(slave, TIOCSETP, &b);
408
409 i = fork();
410 if (i < 0) {
411         syslog(LOG_ERR, "fork: %m");
412         exit(1);
413 } else if (i) {         /* Parent */
414         close(slave);
415         ...
416 } else {                 /* Child */
417         (void) close(s);
418         (void) close(master);
419         dup2(slave, 0);
420         dup2(slave, 1);
421         dup2(slave, 2);
422         if (slave > 2)
423                 (void) close(slave);
424         ...
425 }
426 .DE
427 .ce
428 Figure 8.  Creation and use of a pseudo terminal
429 .sp
430 .KE
431 .NH 2
432 Selecting specific protocols
433 .PP
434 If the third argument to the \fIsocket\fP call is 0,
435 \fIsocket\fP will select a default protocol to use with
436 the returned socket of the type requested.
437 The default protocol is usually correct, and alternate choices are not
438 usually available.
439 However, when using ``raw'' sockets to communicate directly with
440 lower-level protocols or hardware interfaces,
441 the protocol argument may be important for setting up demultiplexing.
442 For example, raw sockets in the Internet family may be used to implement
443 a new protocol above IP, and the socket will receive packets
444 only for the protocol specified.
445 To obtain a particular protocol one determines the protocol number
446 as defined within the communication domain.  For the Internet
447 domain one may use one of the library routines
448 discussed in section 3, such as \fIgetprotobyname\fP:
449 .DS
450 #include <sys/types.h>
451 #include <sys/socket.h>
452 #include <netinet/in.h>
453 #include <netdb.h>
454  ...
455 pp = getprotobyname("newtcp");
456 s = socket(AF_INET, SOCK_STREAM, pp->p_proto);
457 .DE
458 This would result in a socket \fIs\fP using a stream
459 based connection, but with protocol type of ``newtcp''
460 instead of the default ``tcp.''
461 .PP
462 In the NS domain, the available socket protocols are defined in
463 <\fInetns/ns.h\fP>.  To create a raw socket for Xerox Error Protocol
464 messages, one might use:
465 .DS
466 #include <sys/types.h>
467 #include <sys/socket.h>
468 #include <netns/ns.h>
469  ...
470 s = socket(AF_NS, SOCK_RAW, NSPROTO_ERROR);
471 .DE
472 .NH 2
473 Address binding
474 .PP
475 As was mentioned in section 2, 
476 binding addresses to sockets in the Internet and NS domains can be
477 fairly complex.  As a brief reminder, these associations
478 are composed of local and foreign
479 addresses, and local and foreign ports.  Port numbers are
480 allocated out of separate spaces, one for each system and one
481 for each domain on that system.
482 Through the \fIbind\fP system call, a
483 process may specify half of an association, the
484 <local address, local port> part, while the
485 \fIconnect\fP
486 and \fIaccept\fP
487 primitives are used to complete a socket's association by
488 specifying the <foreign address, foreign port> part.
489 Since the association is created in two steps the association
490 uniqueness requirement indicated previously could be violated unless
491 care is taken.  Further, it is unrealistic to expect user
492 programs to always know proper values to use for the local address
493 and local port since a host may reside on multiple networks and
494 the set of allocated port numbers is not directly accessible
495 to a user.
496 .PP
497 To simplify local address binding in the Internet domain the notion of a
498 \*(lqwildcard\*(rq address has been provided.  When an address
499 is specified as INADDR_ANY (a manifest constant defined in
500 <netinet/in.h>), the system interprets the address as 
501 \*(lqany valid address\*(rq.  For example, to bind a specific
502 port number to a socket, but leave the local address unspecified,
503 the following code might be used:
504 .DS
505 #include <sys/types.h>
506 #include <netinet/in.h>
507  ...
508 struct sockaddr_in sin;
509  ...
510 s = socket(AF_INET, SOCK_STREAM, 0);
511 sin.sin_family = AF_INET;
512 sin.sin_addr.s_addr = htonl(INADDR_ANY);
513 sin.sin_port = htons(MYPORT);
514 bind(s, (struct sockaddr *) &sin, sizeof (sin));
515 .DE
516 Sockets with wildcarded local addresses may receive messages
517 directed to the specified port number, and sent to any
518 of the possible addresses assigned to a host.  For example,
519 if a host has addresses 128.32.0.4 and 10.0.0.78, and a socket is bound as
520 above, the process will be
521 able to accept connection requests which are addressed to
522 128.32.0.4 or 10.0.0.78.
523 If a server process wished to only allow hosts on a
524 given network connect to it, it would bind
525 the address of the host on the appropriate network.
526 .PP
527 In a similar fashion, a local port may be left unspecified
528 (specified as zero), in which case the system will select an
529 appropriate port number for it.  This shortcut will work
530 both in the Internet and NS domains.  For example, to
531 bind a specific local address to a socket, but to leave the
532 local port number unspecified:
533 .DS
534 hp = gethostbyname(hostname);
535 if (hp == NULL) {
536         ...
537 }
538 bcopy(hp->h_addr, (char *) sin.sin_addr, hp->h_length);
539 sin.sin_port = htons(0);
540 bind(s, (struct sockaddr *) &sin, sizeof (sin));
541 .DE
542 The system selects the local port number based on two criteria.
543 The first is that on 4BSD systems,
544 Internet ports below IPPORT_RESERVED (1024) (for the Xerox domain,
545 0 through 3000) are reserved
546 for privileged users (i.e., the super user);
547 Internet ports above IPPORT_USERRESERVED (50000) are reserved
548 for non-privileged servers.  The second is
549 that the port number is not currently bound to some other
550 socket.  In order to find a free Internet port number in the privileged
551 range the \fIrresvport\fP library routine may be used as follows
552 to return a stream socket in with a privileged port number:
553 .DS
554 int lport = IPPORT_RESERVED \- 1;
555 int s;
556 \&...
557 s = rresvport(&lport);
558 if (s < 0) {
559         if (errno == EAGAIN)
560                 fprintf(stderr, "socket: all ports in use\en");
561         else
562                 perror("rresvport: socket");
563         ...
564 }
565 .DE
566 The restriction on allocating ports was done to allow processes
567 executing in a \*(lqsecure\*(rq environment to perform authentication
568 based on the originating address and port number.  For example,
569 the \fIrlogin\fP(1) command allows users to log in across a network
570 without being asked for a password, if two conditions hold:
571 First, the name of the system the user
572 is logging in from is in the file
573 \fI/etc/hosts.equiv\fP on the system he is logging
574 in to (or the system name and the user name are in
575 the user's \fI.rhosts\fP file in the user's home
576 directory), and second, that the user's rlogin
577 process is coming from a privileged port on the machine from which he is
578 logging.  The port number and network address of the
579 machine from which the user is logging in can be determined either
580 by the \fIfrom\fP result of the \fIaccept\fP call, or
581 from the \fIgetpeername\fP call.
582 .PP
583 In certain cases the algorithm used by the system in selecting
584 port numbers is unsuitable for an application.  This is because
585 associations are created in a two step process.  For example,
586 the Internet file transfer protocol, FTP, specifies that data
587 connections must always originate from the same local port.  However,
588 duplicate associations are avoided by connecting to different foreign
589 ports.  In this situation the system would disallow binding the
590 same local address and port number to a socket if a previous data
591 connection's socket still existed.  To override the default port
592 selection algorithm, an option call must be performed prior
593 to address binding:
594 .DS
595  ...
596 int     on = 1;
597  ...
598 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
599 bind(s, (struct sockaddr *) &sin, sizeof (sin));
600 .DE
601 With the above call, local addresses may be bound which
602 are already in use.  This does not violate the uniqueness
603 requirement as the system still checks at connect time to
604 be sure any other sockets with the same local address and
605 port do not have the same foreign address and port.
606 If the association already exists, the error EADDRINUSE is returned.
607 A related socket option, SO_REUSEPORT, which allows completely 
608 duplicate bindings, is described in the IP multicasting section.
609 .NH 2
610 Socket Options
611 .PP
612 It is possible to set and get a number of options on sockets
613 via the \fIsetsockopt\fP and \fIgetsockopt\fP system calls.
614 These options include such things as marking a socket for
615 broadcasting, not to route, to linger on close, etc.
616 In addition, there are protocol-specific options for IP and TCP,
617 as described in
618 .IR ip (4),
619 .IR tcp (4),
620 and in the section on multicasting below.
621 .PP
622 The general forms of the calls are:
623 .DS
624 setsockopt(s, level, optname, optval, optlen);
625 .DE
626 and
627 .DS
628 getsockopt(s, level, optname, optval, optlen);
629 .DE
630 .PP
631 The parameters to the calls are as follows: \fIs\fP
632 is the socket on which the option is to be applied.
633 \fILevel\fP specifies the protocol layer on which the
634 option is to be applied; in most cases this is
635 the ``socket level'', indicated by the symbolic constant
636 SOL_SOCKET, defined in \fI<sys/socket.h>.\fP
637 The actual option is specified in \fIoptname\fP, and is
638 a symbolic constant also defined in \fI<sys/socket.h>\fP.
639 \fIOptval\fP and \fIOptlen\fP point to the value of the
640 option (in most cases, whether the option is to be turned
641 on or off), and the length of the value of the option,
642 respectively.
643 For \fIgetsockopt\fP, \fIoptlen\fP is
644 a value-result parameter, initially set to the size of
645 the storage area pointed to by \fIoptval\fP, and modified
646 upon return to indicate the actual amount of storage used.
647 .PP
648 An example should help clarify things.  It is sometimes
649 useful to determine the type (e.g., stream, datagram, etc.)
650 of an existing socket; programs
651 under \fIinetd\fP (described below) may need to perform this
652 task.  This can be accomplished as follows via the
653 SO_TYPE socket option and the \fIgetsockopt\fP call:
654 .DS
655 #include <sys/types.h>
656 #include <sys/socket.h>
657
658 int type, size;
659
660 size = sizeof (int);
661
662 if (getsockopt(s, SOL_SOCKET, SO_TYPE, (char *) &type, &size) < 0) {
663         ...
664 }
665 .DE
666 After the \fIgetsockopt\fP call, \fItype\fP will be set
667 to the value of the socket type, as defined in
668 \fI<sys/socket.h>\fP.  If, for example, the socket were
669 a datagram socket, \fItype\fP would have the value
670 corresponding to SOCK_DGRAM.
671 .NH 2
672 Broadcasting and determining network configuration
673 .PP
674 By using a datagram socket, it is possible to send broadcast
675 packets on many networks supported by the system.
676 The network itself must support broadcast; the system
677 provides no simulation of broadcast in software.
678 Broadcast messages can place a high load on a network since they force
679 every host on the network to service them.  Consequently,
680 the ability to send broadcast packets has been limited
681 to sockets which are explicitly marked as allowing broadcasting.
682 Broadcast is typically used for one of two reasons:
683 it is desired to find a resource on a local network without prior
684 knowledge of its address,
685 or important functions such as routing require that information
686 be sent to all accessible neighbors.
687 .PP
688 Multicasting is an alternative to broadcasting.
689 Setting up IP multicast sockets is described in the next section.
690 .PP
691 To send a broadcast message, a datagram socket 
692 should be created:
693 .DS
694 s = socket(AF_INET, SOCK_DGRAM, 0);
695 .DE
696 or
697 .DS
698 s = socket(AF_NS, SOCK_DGRAM, 0);
699 .DE
700 The socket is marked as allowing broadcasting,
701 .DS
702 int     on = 1;
703
704 setsockopt(s, SOL_SOCKET, SO_BROADCAST, &on, sizeof (on));
705 .DE
706 and at least a port number should be bound to the socket:
707 .DS
708 sin.sin_family = AF_INET;
709 sin.sin_addr.s_addr = htonl(INADDR_ANY);
710 sin.sin_port = htons(MYPORT);
711 bind(s, (struct sockaddr *) &sin, sizeof (sin));
712 .DE
713 or, for the NS domain,
714 .DS
715 sns.sns_family = AF_NS;
716 netnum = htonl(net);
717 sns.sns_addr.x_net = *(union ns_net *) &netnum; /* insert net number */
718 sns.sns_addr.x_port = htons(MYPORT);
719 bind(s, (struct sockaddr *) &sns, sizeof (sns));
720 .DE
721 The destination address of the message to be broadcast
722 depends on the network(s) on which the message is to be broadcast.
723 The Internet domain supports a shorthand notation for broadcast
724 on the local network, the address INADDR_BROADCAST (defined in
725 <\fInetinet/in.h\fP>.
726 To determine the list of addresses for all reachable neighbors
727 requires knowledge of the networks to which the host is connected.
728 Since this information should
729 be obtained in a host-independent fashion and may be impossible
730 to derive, 4.4BSD provides a method of
731 retrieving this information from the system data structures.
732 The SIOCGIFCONF \fIioctl\fP call returns the interface
733 configuration of a host in the form of a
734 single \fIifconf\fP structure; this structure contains
735 a ``data area'' which is made up of an array of
736 of \fIifreq\fP structures, one for each network interface
737 to which the host is connected.
738 These structures are defined in
739 \fI<net/if.h>\fP as follows:
740 .DS
741 .if t .ta .5i 1.0i 1.5i 3.5i
742 .if n .ta .7i 1.4i 2.1i 3.4i
743 struct ifconf {
744         int     ifc_len;                /* size of associated buffer */
745         union {
746                 caddr_t ifcu_buf;
747                 struct  ifreq *ifcu_req;
748         } ifc_ifcu;
749 };
750
751 #define ifc_buf ifc_ifcu.ifcu_buf               /* buffer address */
752 #define ifc_req ifc_ifcu.ifcu_req               /* array of structures returned */
753
754 #define IFNAMSIZ        16
755
756 struct ifreq {
757         char    ifr_name[IFNAMSIZ];             /* if name, e.g. "en0" */
758         union {
759                 struct  sockaddr ifru_addr;
760                 struct  sockaddr ifru_dstaddr;
761                 struct  sockaddr ifru_broadaddr;
762                 short   ifru_flags;
763                 caddr_t ifru_data;
764         } ifr_ifru;
765 };
766
767 .if t .ta \w'  #define'u +\w'  ifr_broadaddr'u +\w'  ifr_ifru.ifru_broadaddr'u
768 #define ifr_addr        ifr_ifru.ifru_addr      /* address */
769 #define ifr_dstaddr     ifr_ifru.ifru_dstaddr   /* other end of p-to-p link */
770 #define ifr_broadaddr   ifr_ifru.ifru_broadaddr /* broadcast address */
771 #define ifr_flags       ifr_ifru.ifru_flags     /* flags */
772 #define ifr_data        ifr_ifru.ifru_data      /* for use by interface */
773 .DE
774 The actual call which obtains the
775 interface configuration is
776 .DS
777 struct ifconf ifc;
778 char buf[BUFSIZ];
779
780 ifc.ifc_len = sizeof (buf);
781 ifc.ifc_buf = buf;
782 if (ioctl(s, SIOCGIFCONF, (char *) &ifc) < 0) {
783         ...
784 }
785 .DE
786 After this call \fIbuf\fP will contain one \fIifreq\fP structure for
787 each network to which the host is connected, and
788 \fIifc.ifc_len\fP will have been modified to reflect the number
789 of bytes used by the \fIifreq\fP structures.
790 .PP
791 For each structure
792 there exists a set of ``interface flags'' which tell
793 whether the network corresponding to that interface is
794 up or down, point to point or broadcast, etc.  The
795 SIOCGIFFLAGS \fIioctl\fP retrieves these
796 flags for an interface specified by an \fIifreq\fP
797 structure as follows:
798 .DS
799 struct ifreq *ifr;
800
801 ifr = ifc.ifc_req;
802
803 for (n = ifc.ifc_len / sizeof (struct ifreq); --n >= 0; ifr++) {
804         /*
805          * We must be careful that we don't use an interface
806          * devoted to an address family other than those intended;
807          * if we were interested in NS interfaces, the
808          * AF_INET would be AF_NS.
809          */
810         if (ifr->ifr_addr.sa_family != AF_INET)
811                 continue;
812         if (ioctl(s, SIOCGIFFLAGS, (char *) ifr) < 0) {
813                 ...
814         }
815         /*
816          * Skip boring cases.
817          */
818         if ((ifr->ifr_flags & IFF_UP) == 0 ||
819             (ifr->ifr_flags & IFF_LOOPBACK) ||
820             (ifr->ifr_flags & (IFF_BROADCAST | IFF_POINTTOPOINT)) == 0)
821                 continue;
822 .DE
823 .PP
824 Once the flags have been obtained, the broadcast address 
825 must be obtained.  In the case of broadcast networks this is
826 done via the SIOCGIFBRDADDR \fIioctl\fP, while for point-to-point networks
827 the address of the destination host is obtained with SIOCGIFDSTADDR.
828 .DS
829 struct sockaddr dst;
830
831 if (ifr->ifr_flags & IFF_POINTTOPOINT) {
832         if (ioctl(s, SIOCGIFDSTADDR, (char *) ifr) < 0) {
833                 ...
834         }
835         bcopy((char *) ifr->ifr_dstaddr, (char *) &dst, sizeof (ifr->ifr_dstaddr));
836 } else if (ifr->ifr_flags & IFF_BROADCAST) {
837         if (ioctl(s, SIOCGIFBRDADDR, (char *) ifr) < 0) {
838                 ...
839         }
840         bcopy((char *) ifr->ifr_broadaddr, (char *) &dst, sizeof (ifr->ifr_broadaddr));
841 }
842 .DE
843 .PP
844 After the appropriate \fIioctl\fP's have obtained the broadcast
845 or destination address (now in \fIdst\fP), the \fIsendto\fP call may be
846 used:
847 .DS
848         sendto(s, buf, buflen, 0, (struct sockaddr *)&dst, sizeof (dst));
849 }
850 .DE
851 In the above loop one \fIsendto\fP occurs for every
852 interface to which the host is connected that supports the notion of
853 broadcast or point-to-point addressing.
854 If a process only wished to send broadcast
855 messages on a given network, code similar to that outlined above
856 would be used, but the loop would need to find the
857 correct destination address.
858 .PP
859 Received broadcast messages contain the senders address
860 and port, as datagram sockets are bound before
861 a message is allowed to go out.
862 .NH 2
863 IP Multicasting
864 .PP
865 IP multicasting is the transmission of an IP datagram to a "host
866 group", a set of zero or more hosts identified by a single IP
867 destination address.  A multicast datagram is delivered to all
868 members of its destination host group with the same "best-efforts"
869 reliability as regular unicast IP datagrams, i.e., the datagram is
870 not guaranteed to arrive intact at all members of the destination
871 group or in the same order relative to other datagrams.
872 .PP
873 The membership of a host group is dynamic; that is, hosts may join
874 and leave groups at any time.  There is no restriction on the
875 location or number of members in a host group.  A host may be a
876 member of more than one group at a time.  A host need not be a member
877 of a group to send datagrams to it.
878 .PP
879 A host group may be permanent or transient.  A permanent group has a
880 well-known, administratively assigned IP address.  It is the address,
881 not the membership of the group, that is permanent; at any time a
882 permanent group may have any number of members, even zero.  Those IP
883 multicast addresses that are not reserved for permanent groups are
884 available for dynamic assignment to transient groups which exist only
885 as long as they have members.
886 .PP
887 In general, a host cannot assume that datagrams sent to any host
888 group address will reach only the intended hosts, or that datagrams
889 received as a member of a transient host group are intended for the
890 recipient.  Misdelivery must be detected at a level above IP, using
891 higher-level identifiers or authentication tokens.  Information
892 transmitted to a host group address should be encrypted or governed
893 by administrative routing controls if the sender is concerned about
894 unwanted listeners.
895 .PP
896 IP multicasting is currently supported only on AF_INET sockets of type
897 SOCK_DGRAM and SOCK_RAW, and only on subnetworks for which the interface
898 driver has been modified to support multicasting.
899 .PP
900 The next subsections describe how to send and receive multicast datagrams.
901 .NH 3 
902 Sending IP Multicast Datagrams
903 .PP
904 To send a multicast datagram, specify an IP multicast address in the range
905 224.0.0.0 to 239.255.255.255 as the destination address
906 in a
907 .IR sendto (2)
908 call.
909 .PP
910 The definitions required for the multicast-related socket options are
911 found in \fI<netinet/in.h>\fP.
912 All IP addresses are passed in network byte-order.
913 .PP
914 By default, IP multicast datagrams are sent with a time-to-live (TTL) of 1,
915 which prevents them from being forwarded beyond a single subnetwork.  A new
916 socket option allows the TTL for subsequent multicast datagrams to be set to
917 any value from 0 to 255, in order to control the scope of the multicasts:
918 .DS
919 u_char ttl;
920 setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
921 .DE
922 Multicast datagrams with a TTL of 0 will not be transmitted on any subnet,
923 but may be delivered locally if the sending host belongs to the destination
924 group and if multicast loopback has not been disabled on the sending socket
925 (see below).  Multicast datagrams with TTL greater than one may be delivered
926 to more than one subnet if there are one or more multicast routers attached
927 to the first-hop subnet.  To provide meaningful scope control, the multicast
928 routers support the notion of TTL "thresholds", which prevent datagrams with
929 less than a certain TTL from traversing certain subnets.  The thresholds
930 enforce the following convention:
931 .TS
932 center;
933 l | l
934 l | n.
935 _
936 Scope   Initial TTL
937 =
938 restricted to the same host     0
939 restricted to the same subnet   1
940 restricted to the same site     32
941 restricted to the same region   64
942 restricted to the same continent        128
943 unrestricted    255
944 _
945 .TE
946 "Sites" and "regions" are not strictly defined, and sites may be further
947 subdivided into smaller administrative units, as a local matter.
948 .PP
949 An application may choose an initial TTL other than the ones listed above.
950 For example, an application might perform an "expanding-ring search" for a
951 network resource by sending a multicast query, first with a TTL of 0, and
952 then with larger and larger TTLs, until a reply is received, perhaps using
953 the TTL sequence 0, 1, 2, 4, 8, 16, 32.
954 .PP
955 The multicast router
956 .IR mrouted (8),
957 refuses to forward any
958 multicast datagram with a destination address between 224.0.0.0 and
959 224.0.0.255, inclusive, regardless of its TTL.  This range of addresses is
960 reserved for the use of routing protocols and other low-level topology
961 discovery or maintenance protocols, such as gateway discovery and group
962 membership reporting.
963 .PP
964 The address 224.0.0.0 is
965 guaranteed not to be assigned to any group, and 224.0.0.1 is assigned
966 to the permanent group of all IP hosts (including gateways).  This is
967 used to address all multicast hosts on the directly connected
968 network.  There is no multicast address (or any other IP address) for
969 all hosts on the total Internet.  The addresses of other well-known,
970 permanent groups are published in the "Assigned Numbers" RFC,
971 which is available from the InterNIC.
972 .PP
973 Each multicast transmission is sent from a single network interface, even if
974 the host has more than one multicast-capable interface.  (If the host is
975 also serving as a multicast router,
976 a multicast may be \fIforwarded\fP to interfaces
977 other than originating interface, provided that the TTL is greater than 1.)
978 The default interface to be used for multicasting is the primary network
979 interface on the system.
980 A socket option
981 is available to override the default for subsequent transmissions from a
982 given socket:
983 .DS
984 struct in_addr addr;
985 setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr));
986 .DE
987 where "addr" is the local IP address of the desired outgoing interface.
988 An address of INADDR_ANY may be used to revert to the default interface.
989 The local IP address of an interface can be obtained via the SIOCGIFCONF
990 ioctl.  To determine if an interface supports multicasting, fetch the
991 interface flags via the SIOCGIFFLAGS ioctl and see if the IFF_MULTICAST
992 flag is set.  (Normal applications should not need to use this option; it
993 is intended primarily for multicast routers and other system services
994 specifically concerned with internet topology.)
995 The SIOCGIFCONF and SIOCGIFFLAGS ioctls are described in the previous section.
996 .PP
997 If a multicast datagram is sent to a group to which the sending host itself
998 belongs (on the outgoing interface), a copy of the datagram is, by default,
999 looped back by the IP layer for local delivery.  Another socket option gives
1000 the sender explicit control over whether or not subsequent datagrams are
1001 looped back:
1002 .DS
1003 u_char loop;
1004 setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
1005 .DE
1006 where \f2loop\f1 is set to 0 to disable loopback,
1007 and set to 1 to enable loopback.
1008 This option
1009 improves performance for applications that may have no more than one
1010 instance on a single host (such as a router demon), by eliminating
1011 the overhead of receiving their own transmissions.  It should generally not
1012 be used by applications for which there may be more than one instance on a
1013 single host (such as a conferencing program) or for which the sender does
1014 not belong to the destination group (such as a time querying program).
1015 .PP
1016 A multicast datagram sent with an initial TTL greater than 1 may be delivered
1017 to the sending host on a different interface from that on which it was sent,
1018 if the host belongs to the destination group on that other interface.  The
1019 loopback control option has no effect on such delivery.
1020 .NH 3 
1021 Receiving IP Multicast Datagrams
1022 .PP
1023 Before a host can receive IP multicast datagrams, it must become a member
1024 of one or more IP multicast groups.  A process can ask the host to join
1025 a multicast group by using the following socket option:
1026 .DS
1027 struct ip_mreq mreq;
1028 setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))
1029 .DE
1030 where "mreq" is the following structure:
1031 .DS
1032 struct ip_mreq {
1033     struct in_addr imr_multiaddr; /* \fImulticast group to join\fP */
1034     struct in_addr imr_interface; /* \fIinterface to join on\fP */
1035 }
1036 .DE
1037 Every membership is associated with a single interface, and it is possible
1038 to join the same group on more than one interface.  "imr_interface" should
1039 be INADDR_ANY to choose the default multicast interface, or one of the
1040 host's local addresses to choose a particular (multicast-capable) interface.
1041 Up to IP_MAX_MEMBERSHIPS (currently 20) memberships may be added on a
1042 single socket.
1043 .PP
1044 To drop a membership, use:
1045 .DS
1046 struct ip_mreq mreq;
1047 setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
1048 .DE
1049 where "mreq" contains the same values as used to add the membership.  The
1050 memberships associated with a socket are also dropped when the socket is
1051 closed or the process holding the socket is killed.  However, more than
1052 one socket may claim a membership in a particular group, and the host
1053 will remain a member of that group until the last claim is dropped.
1054 .PP
1055 The memberships associated with a socket do not necessarily determine which
1056 datagrams are received on that socket.  Incoming multicast packets are
1057 accepted by the kernel IP layer if any socket has claimed a membership in the
1058 destination group of the datagram; however, delivery of a multicast datagram
1059 to a particular socket is based on the destination port (or protocol type, for
1060 raw sockets), just as with unicast datagrams.  
1061 To receive multicast datagrams
1062 sent to a particular port, it is necessary to bind to that local port,
1063 leaving the local address unspecified (i.e., INADDR_ANY).
1064 To receive multicast datagrams
1065 sent to a particular group and port, bind to the local port, with
1066 the local address set to the multicast group address.  
1067 Once bound to a multicast address, the socket cannot be used for sending data.
1068 .PP
1069 More than one process may bind to the same SOCK_DGRAM UDP port 
1070 or the same multicast group and port if the
1071 .I bind
1072 call is preceded by:
1073 .DS
1074 int on = 1;
1075 setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));
1076 .DE
1077 All processes sharing the port must enable this option.
1078 Every incoming multicast or broadcast UDP datagram destined to
1079 the shared port is delivered to all sockets bound to the port.  
1080 For backwards compatibility reasons, this does not apply to incoming
1081 unicast datagrams.  Unicast
1082 datagrams are never delivered to more than one socket, regardless of
1083 how many sockets are bound to the datagram's destination port.
1084 .PP
1085 A final multicast-related extension is independent of IP:  two new ioctls,
1086 SIOCADDMULTI and SIOCDELMULTI, are available to add or delete link-level
1087 (e.g., Ethernet) multicast addresses accepted by a particular interface.
1088 The address to be added or deleted is passed as a sockaddr structure of
1089 family AF_UNSPEC, within the standard ifreq structure.
1090 .PP
1091 These ioctls are
1092 for the use of protocols other than IP, and require superuser privileges.
1093 A link-level multicast address added via SIOCADDMULTI is not automatically
1094 deleted when the socket used to add it goes away; it must be explicitly
1095 deleted.  It is inadvisable to delete a link-level address that may be
1096 in use by IP.
1097 .NH 3
1098 Sample Multicast Program
1099 .PP
1100 The following program sends or receives multicast packets.
1101 If invoked with one argument, it sends a packet containing the current
1102 time to an arbitrarily-chosen multicast group and UDP port.
1103 If invoked with no arguments, it receives and prints these packets.
1104 Start it as a sender on just one host and as a receiver on all the other hosts.
1105 .DS
1106 #include <sys/types.h>
1107 #include <sys/socket.h>
1108 #include <netinet/in.h>
1109 #include <arpa/inet.h>
1110 #include <time.h>
1111 #include <stdio.h>
1112
1113 #define EXAMPLE_PORT    60123
1114 #define EXAMPLE_GROUP   "224.0.0.250"
1115
1116 main(argc)
1117     int argc;
1118 {
1119     struct sockaddr_in addr;
1120     int addrlen, fd, cnt;
1121     struct ip_mreq mreq;
1122     char message[50];
1123
1124     fd = socket(AF_INET, SOCK_DGRAM, 0);
1125     if (fd < 0) {
1126         perror("socket");
1127         exit(1);
1128     }
1129
1130     bzero(&addr, sizeof(addr));
1131     addr.sin_family = AF_INET;
1132     addr.sin_addr.s_addr = htonl(INADDR_ANY);
1133     addr.sin_port = htons(EXAMPLE_PORT);
1134     addrlen = sizeof(addr);
1135
1136     if (argc > 1) {     /* Send */
1137         addr.sin_addr.s_addr = inet_addr(EXAMPLE_GROUP);
1138         while (1) {
1139             time_t t = time(0);
1140             sprintf(message, "time is %-24.24s", ctime(&t));
1141             cnt = sendto(fd, message, sizeof(message), 0,
1142                     (struct sockaddr *)&addr, addrlen);
1143             if (cnt < 0) {
1144                 perror("sendto");
1145                 exit(1);
1146             }
1147             sleep(5);
1148         }
1149     } else {            /* Receive */
1150         if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
1151             perror("bind");
1152             exit(1);
1153         }
1154
1155         mreq.imr_multiaddr.s_addr = inet_addr(EXAMPLE_GROUP);
1156         mreq.imr_interface.s_addr = htonl(INADDR_ANY);
1157         if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1158                     &mreq, sizeof(mreq)) < 0) {
1159             perror("setsockopt mreq");
1160             exit(1);
1161         }
1162
1163         while (1) {
1164             cnt = recvfrom(fd, message, sizeof(message), 0,
1165                             (struct sockaddr *)&addr, &addrlen);
1166             if (cnt <= 0) {
1167                     if (cnt == 0) {
1168                         break;
1169                     }
1170                     perror("recvfrom");
1171                     exit(1);
1172             } 
1173             printf("%s: message = \e"%s\e"\en",
1174                     inet_ntoa(addr.sin_addr), message);
1175         }
1176     }
1177 }
1178 .DE
1179 .\"----------------------------------------------------------------------
1180 .NH 2
1181 NS Packet Sequences
1182 .PP
1183 The semantics of NS connections demand that
1184 the user both be able to look inside the network header associated
1185 with any incoming packet and be able to specify what should go
1186 in certain fields of an outgoing packet.
1187 Using different calls to \fIsetsockopt\fP, it is possible
1188 to indicate whether prototype headers will be associated by
1189 the user with each outgoing packet (SO_HEADERS_ON_OUTPUT),
1190 to indicate whether the headers received by the system should be
1191 delivered to the user (SO_HEADERS_ON_INPUT), or to indicate
1192 default information that should be associated with all
1193 outgoing packets on a given socket (SO_DEFAULT_HEADERS).
1194 .PP
1195 The contents of a SPP header (minus the IDP header) are:
1196 .DS
1197 .if t .ta \w"  #define"u +\w"  u_short"u +2.0i
1198 struct sphdr {
1199         u_char  sp_cc;          /* connection control */
1200 #define SP_SP   0x80            /* system packet */
1201 #define SP_SA   0x40            /* send acknowledgement */
1202 #define SP_OB   0x20            /* attention (out of band data) */
1203 #define SP_EM   0x10            /* end of message */
1204         u_char  sp_dt;          /* datastream type */
1205         u_short sp_sid;         /* source connection identifier */
1206         u_short sp_did;         /* destination connection identifier */
1207         u_short sp_seq;         /* sequence number */
1208         u_short sp_ack;         /* acknowledge number */
1209         u_short sp_alo;         /* allocation number */
1210 };
1211 .DE
1212 Here, the items of interest are the \fIdatastream type\fP and
1213 the \fIconnection control\fP fields.  The semantics of the
1214 datastream type are defined by the application(s) in question;
1215 the value of this field is, by default, zero, but it can be
1216 used to indicate things such as Xerox's Bulk Data Transfer
1217 Protocol (in which case it is set to one).  The connection control
1218 field is a mask of the flags defined just below it.  The user may
1219 set or clear the end-of-message bit to indicate
1220 that a given message is the last of a given substream type,
1221 or may set/clear the attention bit as an alternate way to
1222 indicate that a packet should be sent out-of-band.
1223 As an example, to associate prototype headers with outgoing
1224 SPP packets, consider:
1225 .DS
1226 #include <sys/types.h>
1227 #include <sys/socket.h>
1228 #include <netns/ns.h>
1229 #include <netns/sp.h>
1230  ...
1231 struct sockaddr_ns sns, to;
1232 int s, on = 1;
1233 struct databuf {
1234         struct sphdr proto_spp; /* prototype header */
1235         char buf[534];          /* max. possible data by Xerox std. */
1236 } buf;
1237  ...
1238 s = socket(AF_NS, SOCK_SEQPACKET, 0);
1239  ...
1240 bind(s, (struct sockaddr *) &sns, sizeof (sns));
1241 setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_OUTPUT, &on, sizeof(on));
1242  ...
1243 buf.proto_spp.sp_dt = 1;        /* bulk data */
1244 buf.proto_spp.sp_cc = SP_EM;    /* end-of-message */
1245 strcpy(buf.buf, "hello world\en");
1246 sendto(s, (char *) &buf, sizeof(struct sphdr) + strlen("hello world\en"),
1247     (struct sockaddr *) &to, sizeof(to));
1248  ...
1249 .DE
1250 Note that one must be careful when writing headers; if the prototype
1251 header is not written with the data with which it is to be associated,
1252 the kernel will treat the first few bytes of the data as the
1253 header, with unpredictable results.
1254 To turn off the above association, and to indicate that packet
1255 headers received by the system should be passed up to the user,
1256 one might use:
1257 .DS
1258 #include <sys/types.h>
1259 #include <sys/socket.h>
1260 #include <netns/ns.h>
1261 #include <netns/sp.h>
1262  ...
1263 struct sockaddr sns;
1264 int s, on = 1, off = 0;
1265  ...
1266 s = socket(AF_NS, SOCK_SEQPACKET, 0);
1267  ...
1268 bind(s, (struct sockaddr *) &sns, sizeof (sns));
1269 setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_OUTPUT, &off, sizeof(off));
1270 setsockopt(s, NSPROTO_SPP, SO_HEADERS_ON_INPUT, &on, sizeof(on));
1271  ...
1272 .DE
1273 .PP
1274 Output is handled somewhat differently in the IDP world.
1275 The header of an IDP-level packet looks like:
1276 .DS
1277 .if t .ta \w'struct  'u +\w"  struct ns_addr"u +2.0i
1278 struct idp {
1279         u_short idp_sum;        /* Checksum */
1280         u_short idp_len;        /* Length, in bytes, including header */
1281         u_char  idp_tc;         /* Transport Control (i.e., hop count) */
1282         u_char  idp_pt;         /* Packet Type (i.e., level 2 protocol) */
1283         struct ns_addr  idp_dna;        /* Destination Network Address */
1284         struct ns_addr  idp_sna;        /* Source Network Address */
1285 };
1286 .DE
1287 The primary field of interest in an IDP header is the \fIpacket type\fP
1288 field.  The standard values for this field are (as defined
1289 in <\fInetns/ns.h\fP>):
1290 .DS
1291 .if t .ta \w"  #define"u +\w"  NSPROTO_ERROR"u +1.0i
1292 #define NSPROTO_RI      1               /* Routing Information */
1293 #define NSPROTO_ECHO    2               /* Echo Protocol */
1294 #define NSPROTO_ERROR   3               /* Error Protocol */
1295 #define NSPROTO_PE      4               /* Packet Exchange */
1296 #define NSPROTO_SPP     5               /* Sequenced Packet */
1297 .DE
1298 For SPP connections, the contents of this field are
1299 automatically set to NSPROTO_SPP; for IDP packets,
1300 this value defaults to zero, which means ``unknown''.
1301 .PP
1302 Setting the value of that field with SO_DEFAULT_HEADERS is
1303 easy:
1304 .DS
1305 #include <sys/types.h>
1306 #include <sys/socket.h>
1307 #include <netns/ns.h>
1308 #include <netns/idp.h>
1309  ...
1310 struct sockaddr sns;
1311 struct idp proto_idp;           /* prototype header */
1312 int s, on = 1;
1313  ...
1314 s = socket(AF_NS, SOCK_DGRAM, 0);
1315  ...
1316 bind(s, (struct sockaddr *) &sns, sizeof (sns));
1317 proto_idp.idp_pt = NSPROTO_PE;  /* packet exchange */
1318 setsockopt(s, NSPROTO_IDP, SO_DEFAULT_HEADERS, (char *) &proto_idp,
1319     sizeof(proto_idp));
1320  ...
1321 .DE
1322 .PP
1323 Using SO_HEADERS_ON_OUTPUT is somewhat more difficult.  When
1324 SO_HEADERS_ON_OUTPUT is turned on for an IDP socket, the socket
1325 becomes (for all intents and purposes) a raw socket.  In this
1326 case, all the fields of the prototype header (except the 
1327 length and checksum fields, which are computed by the kernel)
1328 must be filled in correctly in order for the socket to send and
1329 receive data in a sensible manner.  To be more specific, the
1330 source address must be set to that of the host sending the
1331 data; the destination address must be set to that of the
1332 host for whom the data is intended; the packet type must be
1333 set to whatever value is desired; and the hopcount must be
1334 set to some reasonable value (almost always zero).  It should
1335 also be noted that simply sending data using \fIwrite\fP
1336 will not work unless a \fIconnect\fP or \fIsendto\fP call
1337 is used, in spite of the fact that it is the destination
1338 address in the prototype header that is used, not the one
1339 given in either of those calls.  For almost
1340 all IDP applications , using SO_DEFAULT_HEADERS is easier and
1341 more desirable than writing headers.
1342 .NH 2
1343 Three-way Handshake
1344 .PP
1345 The semantics of SPP connections indicates that a three-way
1346 handshake, involving changes in the datastream type, should \(em
1347 but is not absolutely required to \(em take place before a SPP
1348 connection is closed.  Almost all SPP connections are
1349 ``well-behaved'' in this manner; when communicating with
1350 any process, it is best to assume that the three-way handshake
1351 is required unless it is known for certain that it is not
1352 required.  In a three-way close, the closing process
1353 indicates that it wishes to close the connection by sending
1354 a zero-length packet with end-of-message set and with
1355 datastream type 254.  The other side of the connection
1356 indicates that it is OK to close by sending a zero-length
1357 packet with end-of-message set and datastream type 255.  Finally,
1358 the closing process replies with a zero-length packet with 
1359 substream type 255; at this point, the connection is considered
1360 closed.  The following code fragments are simplified examples
1361 of how one might handle this three-way handshake at the user
1362 level; in the future, support for this type of close will
1363 probably be provided as part of the C library or as part of
1364 the kernel.  The first code fragment below illustrates how a process
1365 might handle three-way handshake if it sees that the process it
1366 is communicating with wants to close the connection:
1367 .DS
1368 #include <sys/types.h>
1369 #include <sys/socket.h>
1370 #include <netns/ns.h>
1371 #include <netns/sp.h>
1372  ...
1373 #ifndef SPPSST_END
1374 #define SPPSST_END 254
1375 #define SPPSST_ENDREPLY 255
1376 #endif
1377 struct sphdr proto_sp;
1378 int s;
1379  ...
1380 read(s, buf, BUFSIZE);
1381 if (((struct sphdr *)buf)->sp_dt == SPPSST_END) {
1382         /*
1383          * SPPSST_END indicates that the other side wants to
1384          * close.
1385          */
1386         proto_sp.sp_dt = SPPSST_ENDREPLY;
1387         proto_sp.sp_cc = SP_EM;
1388         setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp,
1389             sizeof(proto_sp));
1390         write(s, buf, 0);
1391         /*
1392          * Write a zero-length packet with datastream type = SPPSST_ENDREPLY
1393          * to indicate that the close is OK with us.  The packet that we
1394          * don't see (because we don't look for it) is another packet
1395          * from the other side of the connection, with SPPSST_ENDREPLY
1396          * on it it, too.  Once that packet is sent, the connection is
1397          * considered closed; note that we really ought to retransmit
1398          * the close for some time if we do not get a reply.
1399          */
1400         close(s);
1401 }
1402  ...
1403 .DE
1404 To indicate to another process that we would like to close the
1405 connection, the following code would suffice:
1406 .DS
1407 #include <sys/types.h>
1408 #include <sys/socket.h>
1409 #include <netns/ns.h>
1410 #include <netns/sp.h>
1411  ...
1412 #ifndef SPPSST_END
1413 #define SPPSST_END 254
1414 #define SPPSST_ENDREPLY 255
1415 #endif
1416 struct sphdr proto_sp;
1417 int s;
1418  ...
1419 proto_sp.sp_dt = SPPSST_END;
1420 proto_sp.sp_cc = SP_EM;
1421 setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp,
1422     sizeof(proto_sp));
1423 write(s, buf, 0);       /* send the end request */
1424 proto_sp.sp_dt = SPPSST_ENDREPLY;
1425 setsockopt(s, NSPROTO_SPP, SO_DEFAULT_HEADERS, (char *)&proto_sp,
1426     sizeof(proto_sp));
1427 /*
1428  * We assume (perhaps unwisely)
1429  * that the other side will send the
1430  * ENDREPLY, so we'll just send our final ENDREPLY
1431  * as if we'd seen theirs already.
1432  */
1433 write(s, buf, 0);
1434 close(s);
1435  ...
1436 .DE
1437 .NH 2
1438 Packet Exchange
1439 .PP
1440 The Xerox standard protocols include a protocol that is both
1441 reliable and datagram-oriented.  This protocol is known as
1442 Packet Exchange (PEX or PE) and, like SPP, is layered on top
1443 of IDP.  PEX is important for a number of things: Courier
1444 remote procedure calls may be expedited through the use
1445 of PEX, and many Xerox servers are located by doing a PEX
1446 ``BroadcastForServers'' operation.  Although there is no
1447 implementation of PEX in the kernel,
1448 it may be simulated at the user level with some clever coding
1449 and the use of one peculiar \fIgetsockopt\fP.  A PEX packet
1450 looks like:
1451 .DS
1452 .if t .ta \w'struct  'u +\w"  struct idp"u +2.0i
1453 /*
1454  * The packet-exchange header shown here is not defined
1455  * as part of any of the system include files.
1456  */
1457 struct pex {
1458         struct idp      p_idp;  /* idp header */
1459         u_short ph_id[2];       /* unique transaction ID for pex */
1460         u_short ph_client;      /* client type field for pex */
1461 };
1462 .DE
1463 The \fIph_id\fP field is used to hold a ``unique id'' that
1464 is used in duplicate suppression; the \fIph_client\fP
1465 field indicates the PEX client type (similar to the packet
1466 type field in the IDP header).  PEX reliability stems from the
1467 fact that it is an idempotent (``I send a packet to you, you
1468 send a packet to me'') protocol.  Processes on each side of
1469 the connection may use the unique id to determine if they have
1470 seen a given packet before (the unique id field differs on each
1471 packet sent) so that duplicates may be detected, and to indicate
1472 which message a given packet is in response to.  If a packet with
1473 a given unique id is sent and no response is received in a given
1474 amount of time, the packet is retransmitted until it is decided
1475 that no response will ever be received.  To simulate PEX, one
1476 must be able to generate unique ids -- something that is hard to
1477 do at the user level with any real guarantee that the id is really
1478 unique.  Therefore, a means (via \fIgetsockopt\fP) has been provided
1479 for getting unique ids from the kernel.  The following code fragment
1480 indicates how to get a unique id:
1481 .DS
1482 long uniqueid;
1483 int s, idsize = sizeof(uniqueid);
1484  ...
1485 s = socket(AF_NS, SOCK_DGRAM, 0);
1486  ...
1487 /* get id from the kernel -- only on IDP sockets */
1488 getsockopt(s, NSPROTO_PE, SO_SEQNO, (char *)&uniqueid, &idsize);
1489  ...
1490 .DE
1491 The retransmission and duplicate suppression code required to
1492 simulate PEX fully is left as an exercise for the reader.
1493 .NH 2
1494 Inetd
1495 .PP
1496 One of the daemons provided with 4.4BSD is \fIinetd\fP, the
1497 so called ``internet super-server.''  
1498 Having one daemon listen for requests for many daemons
1499 instead of having each daemon listen for its own requests
1500 reduces the number of idle daemons and simplies their implementation.
1501 .I Inetd
1502 handles
1503 two types of services: standard and TCPMUX.
1504 A standard service has a well-known port assigned to it and
1505 is listed in
1506 .I /etc/services
1507 (see \f2services\f1(5));
1508 it may be a service that implements an official Internet standard or is a
1509 BSD-specific service.
1510 TCPMUX services are nonstandard and do not have a
1511 well-known port assigned to them.
1512 They are invoked from
1513 .I inetd
1514 when a program connects to the "tcpmux" well-known port and specifies
1515 the service name.
1516 This is useful for adding locally-developed servers.
1517 .PP
1518 \fIInetd\fP is invoked at boot
1519 time, and determines from the file \fI/etc/inetd.conf\fP the
1520 servers for which it is to listen.  Once this information has been
1521 read and a pristine environment created, \fIinetd\fP proceeds
1522 to create one socket for each service it is to listen for,
1523 binding the appropriate port number to each socket.
1524 .PP
1525 \fIInetd\fP then performs a \fIselect\fP on all these
1526 sockets for read availability, waiting for somebody wishing
1527 a connection to the service corresponding to
1528 that socket.  \fIInetd\fP then performs an \fIaccept\fP on
1529 the socket in question, \fIfork\fPs, \fIdup\fPs the new
1530 socket to file descriptors 0 and 1 (stdin and
1531 stdout), closes other open file
1532 descriptors, and \fIexec\fPs the appropriate server.
1533 .PP
1534 Servers making use of \fIinetd\fP are considerably simplified,
1535 as \fIinetd\fP takes care of the majority of the IPC work
1536 required in establishing a connection.  The server invoked
1537 by \fIinetd\fP expects the socket connected to its client
1538 on file descriptors 0 and 1, and may immediately perform
1539 any operations such as \fIread\fP, \fIwrite\fP, \fIsend\fP,
1540 or \fIrecv\fP.  Indeed, servers may use
1541 buffered I/O as provided by the ``stdio'' conventions, as
1542 long as they remember to use \fIfflush\fP when appropriate.
1543 .PP
1544 One call which may be of interest to individuals writing
1545 servers under \fIinetd\fP is the \fIgetpeername\fP call,
1546 which returns the address of the peer (process) connected
1547 on the other end of the socket.  For example, to log the
1548 Internet address in ``dot notation'' (e.g., ``128.32.0.4'')
1549 of a client connected to a server under
1550 \fIinetd\fP, the following code might be used:
1551 .DS
1552 struct sockaddr_in name;
1553 int namelen = sizeof (name);
1554  ...
1555 if (getpeername(0, (struct sockaddr *)&name, &namelen) < 0) {
1556         syslog(LOG_ERR, "getpeername: %m");
1557         exit(1);
1558 } else
1559         syslog(LOG_INFO, "Connection from %s", inet_ntoa(name.sin_addr));
1560  ...
1561 .DE
1562 While the \fIgetpeername\fP call is especially useful when
1563 writing programs to run with \fIinetd\fP, it can be used
1564 under other circumstances.  Be warned, however, that \fIgetpeername\fP will
1565 fail on UNIX domain sockets.
1566 .PP
1567 Standard TCP
1568 services are assigned unique well-known port numbers in the range of
1569 0 to 1023 by the
1570 Internet Assigned Numbers Authority (IANA@ISI.EDU).
1571 The limited number of ports in this range are
1572 assigned to official Internet protocols.
1573 The TCPMUX service allows you to add
1574 locally-developed protocols without needing an official TCP port assignment.
1575 The TCPMUX protocol described in RFC-1078 is simple:
1576 .QP
1577 ``A TCP client connects to a foreign host on TCP port 1.  It sends the
1578 service name followed by a carriage-return line-feed <CRLF>.
1579 The service name is never case sensitive. 
1580 The server replies with a
1581 single character indicating positive ("+") or negative ("\-")
1582 acknowledgment, immediately followed by an optional message of
1583 explanation, terminated with a <CRLF>.  If the reply was positive,
1584 the selected protocol begins; otherwise the connection is closed.''
1585 .LP
1586 In 4.4BSD, the TCPMUX service is built into
1587 .IR inetd ,
1588 that is,
1589 .IR inetd
1590 listens on TCP port 1 for requests for TCPMUX services listed
1591 in \f2inetd.conf\f1.
1592 .IR inetd (8)
1593 describes the format of TCPMUX entries for \f2inetd.conf\f1.
1594 .PP
1595 The following is an example TCPMUX server and its \f2inetd.conf\f1 entry.
1596 More sophisticated servers may want to do additional processing
1597 before returning the positive or negative acknowledgement.
1598 .DS
1599 #include <sys/types.h>
1600 #include <stdio.h>
1601
1602 main()
1603 {
1604         time_t t;
1605
1606         printf("+Go\er\en");
1607         fflush(stdout);
1608         time(&t);
1609         printf("%d = %s", t, ctime(&t));
1610         fflush(stdout);
1611 }
1612 .DE
1613 The \f2inetd.conf\f1 entry is:
1614 .DS
1615 tcpmux/current_time stream tcp nowait nobody /d/curtime curtime
1616 .DE
1617 Here's the portion of the client code that handles the TCPMUX handshake:
1618 .DS
1619 char line[BUFSIZ];
1620 FILE *fp;
1621  ...
1622
1623 /* Use stdio for reading data from the server */
1624 fp = fdopen(sock, "r");
1625 if (fp == NULL) {
1626     fprintf(stderr, "Can't create file pointer\en");
1627     exit(1);
1628 }
1629
1630 /* Send service request */
1631 sprintf(line, "%s\er\en", "current_time");
1632 if (write(sock, line, strlen(line)) < 0) {
1633     perror("write");
1634     exit(1);
1635 }
1636
1637 /* Get ACK/NAK response from the server */
1638 if (fgets(line, sizeof(line), fp) == NULL) {
1639     if (feof(fp)) {
1640         die();
1641     } else {
1642         fprintf(stderr, "Error reading response\en");
1643         exit(1);
1644     }
1645 }
1646
1647 /* Delete <CR> */
1648 if ((lp = index(line, '\r')) != NULL) {
1649     *lp = '\0';
1650 }
1651
1652 switch (line[0]) {
1653     case '+':
1654             printf("Got ACK: %s\en", &line[1]);
1655             break;
1656     case '-':
1657             printf("Got NAK: %s\en", &line[1]);
1658             exit(0);
1659     default:
1660             printf("Got unknown response: %s\en", line);
1661             exit(1);
1662 }
1663
1664 /* Get rest of data from the server */
1665 while ((fgets(line, sizeof(line), fp)) != NULL) {
1666     fputs(line, stdout);
1667 }
1668 .DE