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