Debian Codegraph @

upstream/debian-unstable/man7/unix.7

raw
1 .\" Copyright 1999, Andi Kleen <[email protected]>
2 .\" Copyright 2008-2014, Michael Kerrisk <[email protected]>
3 .\" Copyright, the authors of the Linux man-pages project
4 .\"
5 .\" SPDX-License-Identifier: Linux-man-pages-1-para
6 .\"
7 .TH UNIX 7 2026-02-08 "Linux man-pages 6.18"
8 .SH NAME
9 unix \- sockets for local interprocess communication
10 .SH SYNOPSIS
11 .nf
12 .B #include <sys/socket.h>
13 .B #include <sys/un.h>
14 .P
15 .IB unix_socket " = socket(AF_UNIX, type, 0);"
16 .IB error " = socketpair(AF_UNIX, type, 0, int *" sv ");"
17 .fi
18 .SH DESCRIPTION
19 The
20 .B AF_UNIX
21 (also known as
22 .BR AF_LOCAL )
23 socket family is used to communicate between processes on the same machine
24 efficiently.
25 Traditionally, UNIX domain sockets can be either unnamed,
26 or bound to a filesystem pathname (marked as being of type socket).
27 Linux also supports an abstract namespace which is independent of the
28 filesystem.
29 .P
30 Valid socket types in the UNIX domain are:
31 .BR SOCK_STREAM ,
32 for a stream-oriented socket;
33 .BR SOCK_DGRAM ,
34 for a datagram-oriented socket that preserves message boundaries
35 (as on most UNIX implementations, UNIX domain datagram
36 sockets are always reliable and don't reorder datagrams);
37 and (since Linux 2.6.4)
38 .BR SOCK_SEQPACKET ,
39 for a sequenced-packet socket that is connection-oriented,
40 preserves message boundaries,
41 and delivers messages in the order that they were sent.
42 .P
43 UNIX domain sockets support passing file descriptors or process credentials
44 to other processes using ancillary data.
45 .SS Address format
46 A UNIX domain socket address is represented in the following structure:
47 .P
48 .in +4n
49 .EX
50 .\" #define UNIX_PATH_MAX 108
51 .\"
52 struct sockaddr_un {
53 sa_family_t sun_family; /* AF_UNIX */
54 char sun_path[108]; /* Pathname */
55 };
56 .EE
57 .in
58 .P
59 The
60 .I sun_family
61 field always contains
62 .BR AF_UNIX .
63 On Linux,
64 .I sun_path
65 is 108 bytes in size;
66 see also BUGS, below.
67 .P
68 Various system calls (for example,
69 .BR bind (2),
70 .BR connect (2),
71 and
72 .BR sendto (2))
73 take a
74 .I sockaddr_un
75 argument as input.
76 Some other system calls (for example,
77 .BR getsockname (2),
78 .BR getpeername (2),
79 .BR recvfrom (2),
80 and
81 .BR accept (2))
82 return an argument of this type.
83 .P
84 Three types of address are distinguished in the
85 .I sockaddr_un
86 structure:
87 .TP
88 pathname
89 a UNIX domain socket can be bound to a null-terminated
90 filesystem pathname using
91 .BR bind (2).
92 When the address of a pathname socket is returned
93 (by one of the system calls noted above),
94 its length is
95 .IP
96 .in +4n
97 .EX
98 offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1
99 .EE
100 .in
101 .IP
102 and
103 .I sun_path
104 contains the null-terminated pathname.
105 (On Linux, the above
106 .BR offsetof ()
107 expression equates to the same value as
108 .IR sizeof(sa_family_t) ,
109 but some other implementations include other fields before
110 .IR sun_path ,
111 so the
112 .BR offsetof ()
113 expression more portably describes the size of the address structure.)
114 .IP
115 For further details of pathname sockets, see below.
116 .TP
117 unnamed
118 A stream socket that has not been bound to a pathname using
119 .BR bind (2)
120 has no name.
121 Likewise, the two sockets created by
122 .BR socketpair (2)
123 are unnamed.
124 When the address of an unnamed socket is returned,
125 its length is
126 .IR "sizeof(sa_family_t)" ,
127 and
128 .I sun_path
129 should not be inspected.
130 .\" There is quite some variation across implementations: FreeBSD
131 .\" says the length is 16 bytes, HP-UX 11 says it's zero bytes.
132 .TP
133 abstract
134 an abstract socket address is distinguished (from a pathname socket)
135 by the fact that
136 .I sun_path[0]
137 is a null byte (\[aq]\[rs]0\[aq]).
138 The socket's address in this namespace is given by the additional
139 bytes in
140 .I sun_path
141 that are covered by the specified length of the address structure.
142 (Null bytes in the name have no special significance.)
143 The name has no connection with filesystem pathnames.
144 When the address of an abstract socket is returned,
145 the returned
146 .I addrlen
147 is greater than
148 .I sizeof(sa_family_t)
149 (i.e., greater than 2), and the name of the socket is contained in
150 the first
151 .I (addrlen \- sizeof(sa_family_t))
152 bytes of
153 .IR sun_path .
154 .SS Pathname sockets
155 When binding a socket to a pathname, a few rules should be observed
156 for maximum portability and ease of coding:
157 .IP \[bu] 3
158 The pathname in
159 .I sun_path
160 should be null-terminated.
161 .IP \[bu]
162 The length of the pathname, including the terminating null byte,
163 should not exceed the size of
164 .IR sun_path .
165 .IP \[bu]
166 The
167 .I addrlen
168 argument that describes the enclosing
169 .I sockaddr_un
170 structure should have a value of at least:
171 .IP
172 .in +4n
173 .EX
174 offsetof(struct sockaddr_un, sun_path)+strlen(addr.sun_path)+1
175 .EE
176 .in
177 .IP
178 or, more simply,
179 .I addrlen
180 can be specified as
181 .IR "sizeof(struct sockaddr_un)" .
182 .P
183 There is some variation in how implementations handle UNIX domain
184 socket addresses that do not follow the above rules.
185 For example, some (but not all) implementations
186 .\" Linux does this, including for the case where the supplied path
187 .\" is 108 bytes
188 append a null terminator if none is present in the supplied
189 .IR sun_path .
190 .P
191 When coding portable applications,
192 keep in mind that some implementations
193 .\" HP-UX
194 have
195 .I sun_path
196 as short as 92 bytes.
197 .\" Modern BSDs generally have 104, Tru64 and AIX have 104,
198 .\" Solaris and Irix have 108
199 .P
200 Various system calls
201 .RB ( accept (2),
202 .BR recvfrom (2),
203 .BR getsockname (2),
204 .BR getpeername (2))
205 return socket address structures.
206 When applied to UNIX domain sockets, the value-result
207 .I addrlen
208 argument supplied to the call should be initialized as above.
209 Upon return, the argument is set to indicate the
210 .I actual
211 size of the address structure.
212 The caller should check the value returned in this argument:
213 if the output value exceeds the input value,
214 then there is no guarantee that a null terminator is present in
215 .IR sun_path .
216 (See BUGS.)
217 .\"
218 .SS Pathname socket ownership and permissions
219 In the Linux implementation,
220 pathname sockets honor the permissions of the directory they are in.
221 Creation of a new socket fails if the process does not have write and
222 search (execute) permission on the directory in which the socket is created.
223 .P
224 On Linux,
225 connecting to a stream socket object requires write permission on that socket;
226 sending a datagram to a datagram socket likewise
227 requires write permission on that socket.
228 POSIX does not make any statement about the effect of the permissions
229 on a socket file, and on some systems (e.g., older BSDs),
230 the socket permissions are ignored.
231 Portable programs should not rely on
232 this feature for security.
233 .P
234 When creating a new socket, the owner and group of the socket file
235 are set according to the usual rules.
236 The socket file has all permissions enabled,
237 other than those that are turned off by the process
238 .BR umask (2).
239 .P
240 The owner, group, and permissions of a pathname socket can be changed (using
241 .BR chown (2)
242 and
243 .BR chmod (2)).
244 .\" However, fchown() and fchmod() do not seem to have an effect
245 .\"
246 .SS Abstract sockets
247 Socket permissions have no meaning for abstract sockets:
248 the process
249 .BR umask (2)
250 has no effect when binding an abstract socket,
251 and changing the ownership and permissions of the object (via
252 .BR fchown (2)
253 and
254 .BR fchmod (2))
255 has no effect on the accessibility of the socket.
256 .P
257 Abstract sockets automatically disappear when all open references
258 to the socket are closed.
259 .P
260 The abstract socket namespace is a nonportable Linux extension.
261 .\"
262 .SS Socket options
263 For historical reasons, these socket options are specified with a
264 .B SOL_SOCKET
265 type even though they are
266 .B AF_UNIX
267 specific.
268 They can be set with
269 .BR setsockopt (2)
270 and read with
271 .BR getsockopt (2)
272 by specifying
273 .B SOL_SOCKET
274 as the socket family.
275 .TP
276 .B SO_PASSCRED
277 Enabling this socket option causes receipt of the credentials of
278 the sending process in an
279 .B SCM_CREDENTIALS ancillary
280 message in each subsequently received message.
281 The returned credentials are those specified by the sender using
282 .BR SCM_CREDENTIALS ,
283 or a default that includes the sender's PID, real user ID, and real group ID,
284 if the sender did not specify
285 .B SCM_CREDENTIALS
286 ancillary data.
287 .IP
288 When this option is set and the socket is not yet connected,
289 a unique name in the abstract namespace will be generated automatically.
290 .IP
291 The value given as an argument to
292 .BR setsockopt (2)
293 and returned as the result of
294 .BR getsockopt (2)
295 is an integer boolean flag.
296 .TP
297 .B SO_PASSSEC
298 Enables receiving of the SELinux security label of the peer socket
299 in an ancillary message of type
300 .B SCM_SECURITY
301 (see below).
302 .IP
303 The value given as an argument to
304 .BR setsockopt (2)
305 and returned as the result of
306 .BR getsockopt (2)
307 is an integer boolean flag.
308 .IP
309 The
310 .B SO_PASSSEC
311 option is supported for UNIX domain datagram sockets
312 .\" commit 877ce7c1b3afd69a9b1caeb1b9964c992641f52a
313 since Linux 2.6.18;
314 support for UNIX domain stream sockets was added
315 .\" commit 37a9a8df8ce9de6ea73349c9ac8bdf6ba4ec4f70
316 in Linux 4.2.
317 .TP
318 .B SO_PEEK_OFF
319 See
320 .BR socket (7).
321 .TP
322 .B SO_PEERCRED
323 This read-only socket option returns the
324 credentials of the peer process connected to this socket.
325 The returned credentials are those that were in effect at the time
326 of the call to
327 .BR connect (2),
328 .BR listen (2),
329 or
330 .BR socketpair (2).
331 .IP
332 The argument to
333 .BR getsockopt (2)
334 is a pointer to a
335 .I ucred
336 structure;
337 define the
338 .B _GNU_SOURCE
339 feature test macro to obtain the definition of that structure from
340 .IR <sys/socket.h> .
341 .IP
342 The use of this option is possible only for connected
343 .B AF_UNIX
344 stream sockets and for
345 .B AF_UNIX
346 stream and datagram socket pairs created using
347 .BR socketpair (2).
348 .\"
349 .SS Autobind feature
350 If a
351 .BR bind (2)
352 call specifies
353 .I addrlen
354 as
355 .IR sizeof(sa_family_t) ,
356 .\" i.e., sizeof(short)
357 or the
358 .B SO_PASSCRED
359 socket option was specified for a socket that was
360 not explicitly bound to an address,
361 then the socket is autobound to an abstract address.
362 The address consists of a null byte
363 followed by 5 bytes in the character set
364 .IR [0\-9a\-f] .
365 Thus, there is a limit of 2\[ha]20 autobind addresses.
366 (From Linux 2.1.15, when the autobind feature was added,
367 8 bytes were used, and the limit was thus 2\[ha]32 autobind addresses.
368 The change to 5 bytes came in Linux 2.3.15.)
369 .SS Sockets API
370 The following paragraphs describe domain-specific details and
371 unsupported features of the sockets API for UNIX domain sockets on Linux.
372 .P
373 UNIX domain sockets do not support the transmission of
374 out-of-band data (the
375 .B MSG_OOB
376 flag for
377 .BR send (2)
378 and
379 .BR recv (2)).
380 .P
381 The
382 .BR send (2)
383 .B MSG_MORE
384 flag is not supported by UNIX domain sockets.
385 .P
386 Before Linux 3.4,
387 .\" commit 9f6f9af7694ede6314bed281eec74d588ba9474f
388 the use of
389 .B MSG_TRUNC
390 in the
391 .I flags
392 argument of
393 .BR recv (2)
394 was not supported by UNIX domain sockets.
395 .P
396 The
397 .B SO_SNDBUF
398 socket option does have an effect for UNIX domain sockets, but the
399 .B SO_RCVBUF
400 option does not.
401 For datagram sockets, the
402 .B SO_SNDBUF
403 value imposes an upper limit on the size of outgoing datagrams.
404 This limit is calculated as the doubled (see
405 .BR socket (7))
406 option value less 32 bytes used for overhead.
407 .SS Ancillary messages
408 Ancillary data is sent and received using
409 .BR sendmsg (2)
410 and
411 .BR recvmsg (2).
412 For historical reasons, the ancillary message types listed below
413 are specified with a
414 .B SOL_SOCKET
415 type even though they are
416 .B AF_UNIX
417 specific.
418 To send them, set the
419 .I cmsg_level
420 field of the struct
421 .I cmsghdr
422 to
423 .B SOL_SOCKET
424 and the
425 .I cmsg_type
426 field to the type.
427 For more information, see
428 .BR cmsg (3).
429 .TP
430 .B SCM_RIGHTS
431 Send or receive a set of open file descriptors from another process.
432 The data portion contains an integer array of the file descriptors.
433 .IP
434 Commonly, this operation is referred to as "passing a file descriptor"
435 to another process.
436 However, more accurately,
437 what is being passed is a reference to an open file description (see
438 .BR open (2)),
439 and in the receiving process it is likely that a different
440 file descriptor number will be used.
441 Semantically, this operation is equivalent to duplicating
442 .RB ( dup (2))
443 a file descriptor into the file descriptor table of another process.
444 .IP
445 If the buffer used to receive the ancillary data containing
446 file descriptors is too small (or is absent),
447 then the ancillary data is truncated (or discarded)
448 and the excess file descriptors are automatically closed
449 in the receiving process.
450 .IP
451 If the number of file descriptors received in the ancillary data would
452 cause the process to exceed its
453 .B RLIMIT_NOFILE
454 resource limit (see
455 .BR getrlimit (2)),
456 the excess file descriptors are automatically closed
457 in the receiving process.
458 .IP
459 The kernel constant
460 .B SCM_MAX_FD
461 defines a limit on the number of file descriptors in the array.
462 Attempting to send an array larger than this limit causes
463 .BR sendmsg (2)
464 to fail with the error
465 .BR EINVAL .
466 .B SCM_MAX_FD
467 has the value 253
468 .\" commit bba14de98753cb6599a2dae0e520714b2153522d
469 (or 255 before Linux 2.6.38).
470 .TP
471 .B SCM_CREDENTIALS
472 Send or receive UNIX credentials.
473 This can be used for authentication.
474 The credentials are passed as a
475 .I struct ucred
476 ancillary message.
477 This structure is defined in
478 .I <sys/socket.h>
479 as follows:
480 .IP
481 .in +4n
482 .EX
483 struct ucred {
484 pid_t pid; /* Process ID of the sending process */
485 uid_t uid; /* User ID of the sending process */
486 gid_t gid; /* Group ID of the sending process */
487 };
488 .EE
489 .in
490 .IP
491 Since glibc 2.8, the
492 .B _GNU_SOURCE
493 feature test macro must be defined (before including
494 .I any
495 header files) in order to obtain the definition
496 of this structure.
497 .IP
498 The credentials which the sender specifies are checked by the kernel.
499 A privileged process is allowed to specify values that do not match its own.
500 The sender must specify its own process ID (unless it has the capability
501 .BR CAP_SYS_ADMIN ,
502 in which case the PID of any existing process may be specified),
503 its real user ID, effective user ID, or saved set-user-ID (unless it has
504 .BR CAP_SETUID ),
505 and its real group ID, effective group ID, or saved set-group-ID
506 (unless it has
507 .BR CAP_SETGID ).
508 .IP
509 To receive a
510 .I struct ucred
511 message, the
512 .B SO_PASSCRED
513 option must be enabled on the socket.
514 .TP
515 .B SCM_SECURITY
516 Receive the SELinux security context (the security label)
517 of the peer socket.
518 The received ancillary data is a null-terminated string containing
519 the security context.
520 The receiver should allocate at least
521 .B NAME_MAX
522 bytes in the data portion of the ancillary message for this data.
523 .IP
524 To receive the security context, the
525 .B SO_PASSSEC
526 option must be enabled on the socket (see above).
527 .P
528 When sending ancillary data with
529 .BR sendmsg (2),
530 only one item of each of the above types may be included in the sent message.
531 .P
532 At least one byte of real data should be sent when sending ancillary data.
533 On Linux, this is required to successfully send ancillary data over
534 a UNIX domain stream socket.
535 When sending ancillary data over a UNIX domain datagram socket,
536 it is not necessary on Linux to send any accompanying real data.
537 However, portable applications should also include at least one byte
538 of real data when sending ancillary data over a datagram socket.
539 .P
540 When receiving from a stream socket,
541 ancillary data forms a kind of barrier for the received data.
542 For example, suppose that the sender transmits as follows:
543 .P
544 .RS
545 .PD 0
546 .IP (1) 5
547 .BR sendmsg (2)
548 of four bytes, with no ancillary data.
549 .IP (2)
550 .BR sendmsg (2)
551 of one byte, with ancillary data.
552 .IP (3)
553 .BR sendmsg (2)
554 of four bytes, with no ancillary data.
555 .PD
556 .RE
557 .P
558 Suppose that the receiver now performs
559 .BR recvmsg (2)
560 calls each with a buffer size of 20 bytes.
561 The first call will receive five bytes of data,
562 along with the ancillary data sent by the second
563 .BR sendmsg (2)
564 call.
565 The next call will receive the remaining four bytes of data.
566 .P
567 If the space allocated for receiving incoming ancillary data is too small
568 then the ancillary data is truncated to the number of headers
569 that will fit in the supplied buffer (or, in the case of an
570 .B SCM_RIGHTS
571 file descriptor list, the list of file descriptors may be truncated).
572 If no buffer is provided for incoming ancillary data (i.e., the
573 .I msg_control
574 field of the
575 .I msghdr
576 structure supplied to
577 .BR recvmsg (2)
578 is NULL),
579 then the incoming ancillary data is discarded.
580 In both of these cases, the
581 .B MSG_CTRUNC
582 flag will be set in the
583 .I msg.msg_flags
584 value returned by
585 .BR recvmsg (2).
586 .\"
587 .SS Ioctls
588 The following
589 .BR ioctl (2)
590 calls return information in
591 .IR value .
592 The correct syntax is:
593 .P
594 .RS
595 .nf
596 .BI int " value";
597 .IB error " = ioctl(" unix_socket ", " ioctl_type ", &" value ");"
598 .fi
599 .RE
600 .P
601 .I ioctl_type
602 can be:
603 .TP
604 .B SIOCINQ
605 For
606 .B SOCK_STREAM
607 sockets, this call returns the number of unread bytes in the receive buffer.
608 The socket must not be in LISTEN state, otherwise an error
609 .RB ( EINVAL )
610 is returned.
611 .B SIOCINQ
612 is defined in
613 .IR <linux/sockios.h> .
614 .\" FIXME . https://www.sourceware.org/bugzilla/show_bug.cgi?id=12002,
615 .\" filed 2010-09-10, may cause SIOCINQ to be defined in glibc headers
616 Alternatively,
617 you can use the synonymous
618 .BR FIONREAD ,
619 defined in
620 .IR <sys/ioctl.h> .
621 .\" SIOCOUTQ also has an effect for UNIX domain sockets, but not
622 .\" quite what userland might expect. It seems to return the number
623 .\" of bytes allocated for buffers containing pending output.
624 .\" That number is normally larger than the number of bytes of pending
625 .\" output. Since this info is, from userland's point of view, imprecise,
626 .\" and it may well change, probably best not to document this now.
627 For
628 .B SOCK_DGRAM
629 sockets,
630 the returned value is the same as
631 for Internet domain datagram sockets;
632 see
633 .BR udp (7).
634 .SH ERRORS
635 .TP
636 .B EADDRINUSE
637 The specified local address is already in use or the filesystem socket
638 object already exists.
639 .TP
640 .B EBADF
641 This error can occur for
642 .BR sendmsg (2)
643 when sending a file descriptor as ancillary data over
644 a UNIX domain socket (see the description of
645 .BR SCM_RIGHTS ,
646 above), and indicates that the file descriptor number that
647 is being sent is not valid (e.g., it is not an open file descriptor).
648 .TP
649 .B ECONNREFUSED
650 The remote address specified by
651 .BR connect (2)
652 was not a listening socket.
653 This error can also occur if the target pathname is not a socket.
654 .TP
655 .B ECONNRESET
656 Remote socket was unexpectedly closed.
657 .TP
658 .B EFAULT
659 User memory address was not valid.
660 .TP
661 .B EINVAL
662 Invalid argument passed.
663 A common cause is that the value
664 .B AF_UNIX
665 was not specified in the
666 .I sun_type
667 field of passed addresses, or the socket was in an
668 invalid state for the applied operation.
669 .TP
670 .B EISCONN
671 .BR connect (2)
672 called on an already connected socket or a target address was
673 specified on a connected socket.
674 .TP
675 .B ENFILE
676 The system-wide limit on the total number of open files has been reached.
677 .TP
678 .B ENOENT
679 The pathname in the remote address specified to
680 .BR connect (2)
681 did not exist.
682 .TP
683 .B ENOMEM
684 Out of memory.
685 .TP
686 .B ENOTCONN
687 Socket operation needs a target address, but the socket is not connected.
688 .TP
689 .B EOPNOTSUPP
690 Stream operation called on non-stream oriented socket or tried to
691 use the out-of-band data option.
692 .TP
693 .B EPERM
694 The sender passed invalid credentials in the
695 .IR "struct ucred" .
696 .TP
697 .B EPIPE
698 Remote socket was closed on a stream socket.
699 If enabled, a
700 .B SIGPIPE
701 is sent as well.
702 This can be avoided by passing the
703 .B MSG_NOSIGNAL
704 flag to
705 .BR send (2)
706 or
707 .BR sendmsg (2).
708 .TP
709 .B EPROTONOSUPPORT
710 Passed protocol is not
711 .BR AF_UNIX .
712 .TP
713 .B EPROTOTYPE
714 Remote socket does not match the local socket type
715 .RB ( SOCK_DGRAM
716 versus
717 .BR SOCK_STREAM ).
718 .TP
719 .B ESOCKTNOSUPPORT
720 Unknown socket type.
721 .TP
722 .B ESRCH
723 While sending an ancillary message containing credentials
724 .RB ( SCM_CREDENTIALS ),
725 the caller specified a PID that does not match any existing process.
726 .TP
727 .B ETOOMANYREFS
728 This error can occur for
729 .BR sendmsg (2)
730 when sending a file descriptor as ancillary data over
731 a UNIX domain socket (see the description of
732 .BR SCM_RIGHTS ,
733 above).
734 It occurs if the number of "in-flight" file descriptors exceeds the
735 .B RLIMIT_NOFILE
736 resource limit and the caller does not have the
737 .B CAP_SYS_RESOURCE
738 capability.
739 An in-flight file descriptor is one that has been sent using
740 .BR sendmsg (2)
741 but has not yet been accepted in the recipient process using
742 .BR recvmsg (2).
743 .IP
744 This error is diagnosed since mainline Linux 4.5
745 (and in some earlier kernel versions where the fix has been backported).
746 .\" commit 712f4aad406bb1ed67f3f98d04c044191f0ff593
747 In earlier kernel versions,
748 it was possible to place an unlimited number of file descriptors in flight,
749 by sending each file descriptor with
750 .BR sendmsg (2)
751 and then closing the file descriptor so that it was not accounted against the
752 .B RLIMIT_NOFILE
753 resource limit.
754 .P
755 Other errors can be generated by the generic socket layer or
756 by the filesystem while generating a filesystem socket object.
757 See the appropriate manual pages for more information.
758 .SH VERSIONS
759 .B SCM_CREDENTIALS
760 and the abstract namespace were introduced with Linux 2.2 and should not
761 be used in portable programs.
762 (Some BSD-derived systems also support credential passing,
763 but the implementation details differ.)
764 .SH NOTES
765 Binding to a socket with a filename creates a socket
766 in the filesystem that must be deleted by the caller when it is no
767 longer needed (using
768 .BR unlink (2)).
769 The usual UNIX close-behind semantics apply;
770 the socket can be unlinked at any time
771 and will be finally removed from the filesystem
772 when the last reference to it is closed.
773 .P
774 To pass file descriptors or credentials over a
775 .B SOCK_STREAM
776 socket,
777 you must send or receive
778 at least one byte of nonancillary data in the same
779 .BR sendmsg (2)
780 or
781 .BR recvmsg (2)
782 call.
783 .P
784 UNIX domain stream sockets do not support the notion of out-of-band data.
785 .\"
786 .SH BUGS
787 When binding a socket to an address,
788 Linux is one of the implementations that append a null terminator
789 if none is supplied in
790 .IR sun_path .
791 In most cases this is unproblematic:
792 when the socket address is retrieved,
793 it will be one byte longer than that supplied when the socket was bound.
794 However, there is one case where confusing behavior can result:
795 if 108 non-null bytes are supplied when a socket is bound,
796 then the addition of the null terminator takes the length of
797 the pathname beyond
798 .IR sizeof(sun_path) .
799 Consequently, when retrieving the socket address
800 (for example, via
801 .BR accept (2)),
802 .\" The behavior on Solaris is quite similar.
803 if the input
804 .I addrlen
805 argument for the retrieving call is specified as
806 .IR "sizeof(struct sockaddr_un)" ,
807 then the returned address structure
808 .I won't
809 have a null terminator in
810 .IR sun_path .
811 .P
812 In addition, some implementations
813 .\" i.e., traditional BSD
814 don't require a null terminator when binding a socket (the
815 .I addrlen
816 argument is used to determine the length of
817 .IR sun_path )
818 and when the socket address is retrieved on these implementations,
819 there is no null terminator in
820 .IR sun_path .
821 .P
822 Applications that retrieve socket addresses can (portably) code
823 to handle the possibility that there is no null terminator in
824 .I sun_path
825 by respecting the fact that the number of valid bytes in the pathname is:
826 .P
827 .in +4n
828 .EX
829 strnlen(addr.sun_path, addrlen \- offsetof(sockaddr_un, sun_path))
830 .EE
831 .in
832 .\" The following patch to amend kernel behavior was rejected:
833 .\" http://thread.gmane.org/gmane.linux.kernel.api/2437
834 .\" Subject: [patch] Fix handling of overlength pathname in AF_UNIX sun_path
835 .\" 2012-04-17
836 .\" And there was a related discussion in the Austin list:
837 .\" http://thread.gmane.org/gmane.comp.standards.posix.austin.general/5735
838 .\" Subject: Having a sun_path with no null terminator
839 .\" 2012-04-18
840 .\"
841 .\" FIXME . Track http://austingroupbugs.net/view.php?id=561
842 .P
843 Alternatively, an application can retrieve
844 the socket address by allocating a buffer of size
845 .I "sizeof(struct sockaddr_un)+1"
846 that is zeroed out before the retrieval.
847 The retrieving call can specify
848 .I addrlen
849 as
850 .IR "sizeof(struct sockaddr_un)" ,
851 and the extra zero byte ensures that there will be
852 a null terminator for the string returned in
853 .IR sun_path :
854 .P
855 .in +4n
856 .EX
857 void *addrp;
858 \&
859 addrlen = sizeof(struct sockaddr_un);
860 addrp = malloc(addrlen + 1);
861 if (addrp == NULL)
862 /* Handle error */ ;
863 memset(addrp, 0, addrlen + 1);
864 \&
865 if (getsockname(sfd, (struct sockaddr *) addrp, &addrlen)) == \-1)
866 /* handle error */ ;
867 \&
868 printf("sun_path = %s\[rs]n", ((struct sockaddr_un *) addrp)\->sun_path);
869 .EE
870 .in
871 .P
872 This sort of messiness can be avoided if it is guaranteed
873 that the applications that
874 .I create
875 pathname sockets follow the rules outlined above under
876 .IR "Pathname sockets" .
877 .SH EXAMPLES
878 The following code demonstrates the use of sequenced-packet
879 sockets for local interprocess communication.
880 It consists of two programs.
881 The server program waits for a connection from the client program.
882 The client sends each of its command-line arguments in separate messages.
883 The server treats the incoming messages as integers and adds them up.
884 The client sends the command string "END".
885 The server sends back a message containing the sum of the client's integers.
886 The client prints the sum and exits.
887 The server waits for the next client to connect.
888 To stop the server, the client is called with the command-line argument "DOWN".
889 .P
890 The following output was recorded while running the server in the background
891 and repeatedly executing the client.
892 Execution of the server program ends when it receives the "DOWN" command.
893 .SS Example output
894 .in +4n
895 .EX
896 .RB $ " ./server &"
897 [1] 25887
898 .RB $ " ./client 3 4" ;
899 Result = 7
900 .RB $ " ./client 11 \-5" ;
901 Result = 6
902 .RB $ " ./client DOWN" ;
903 Result = 0
904 [1]+ Done ./server
905 $
906 .EE
907 .in
908 .SS Program source
909 \&
910 .\" SRC BEGIN (connection.h)
911 .EX
912 /*
913 * File connection.h
914 */
915 #ifndef CONNECTION_H
916 #define CONNECTION_H
917 \&
918 #define SOCKET_NAME "/tmp/9Lq7BNBnBycd6nxy.socket"
919 #define BUFFER_SIZE 12
920 \&
921 #endif // include guard
922 .EE
923 .\" SRC END
924 .P
925 .\" SRC BEGIN (server.c)
926 .EX
927 /*
928 * File server.c
929 */
930 \&
931 #include <stdio.h>
932 #include <stdlib.h>
933 #include <string.h>
934 #include <sys/socket.h>
935 #include <sys/types.h>
936 #include <sys/un.h>
937 #include <unistd.h>
938 \&
939 #include "connection.h"
940 \&
941 int
942 main(void)
943 {
944 int down_flag = 0;
945 int ret;
946 int connection_socket;
947 int data_socket;
948 int result;
949 ssize_t r, w;
950 struct sockaddr_un name;
951 char buffer[BUFFER_SIZE];
952 \&
953 /* Create local socket. */
954 \&
955 connection_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
956 if (connection_socket == \-1) {
957 perror("socket");
958 exit(EXIT_FAILURE);
959 }
960 \&
961 /*
962 * For portability clear the whole structure, since some
963 * implementations have additional (nonstandard) fields in
964 * the structure.
965 */
966 \&
967 memset(&name, 0, sizeof(name));
968 \&
969 /* Bind socket to socket name. */
970 \&
971 name.sun_family = AF_UNIX;
972 strncpy(name.sun_path, SOCKET_NAME, sizeof(name.sun_path) \- 1);
973 \&
974 ret = bind(connection_socket, (const struct sockaddr *) &name,
975 sizeof(name));
976 if (ret == \-1) {
977 perror("bind");
978 exit(EXIT_FAILURE);
979 }
980 \&
981 /*
982 * Prepare for accepting connections. The backlog size is set
983 * to 20. So while one request is being processed other requests
984 * can be waiting.
985 */
986 \&
987 ret = listen(connection_socket, 20);
988 if (ret == \-1) {
989 perror("listen");
990 exit(EXIT_FAILURE);
991 }
992 \&
993 /* This is the main loop for handling connections. */
994 \&
995 for (;;) {
996 \&
997 /* Wait for incoming connection. */
998 \&
999 data_socket = accept(connection_socket, NULL, NULL);
1000 if (data_socket == \-1) {
1001 perror("accept");
1002 exit(EXIT_FAILURE);
1003 }
1004 \&
1005 result = 0;
1006 for (;;) {
1007 \&
1008 /* Wait for next data packet. */
1009 \&
1010 r = read(data_socket, buffer, sizeof(buffer));
1011 if (r == \-1) {
1012 perror("read");
1013 exit(EXIT_FAILURE);
1014 }
1015 \&
1016 /* Ensure buffer is 0\-terminated. */
1017 \&
1018 buffer[sizeof(buffer) \- 1] = 0;
1019 \&
1020 /* Handle commands. */
1021 \&
1022 if (!strncmp(buffer, "DOWN", sizeof(buffer))) {
1023 down_flag = 1;
1024 continue;
1025 }
1026 \&
1027 if (!strncmp(buffer, "END", sizeof(buffer))) {
1028 break;
1029 }
1030 \&
1031 if (down_flag) {
1032 continue;
1033 }
1034 \&
1035 /* Add received summand. */
1036 \&
1037 result += atoi(buffer);
1038 }
1039 \&
1040 /* Send result. */
1041 \&
1042 sprintf(buffer, "%d", result);
1043 w = write(data_socket, buffer, sizeof(buffer));
1044 if (w == \-1) {
1045 perror("write");
1046 exit(EXIT_FAILURE);
1047 }
1048 \&
1049 /* Close socket. */
1050 \&
1051 close(data_socket);
1052 \&
1053 /* Quit on DOWN command. */
1054 \&
1055 if (down_flag) {
1056 break;
1057 }
1058 }
1059 \&
1060 close(connection_socket);
1061 \&
1062 /* Unlink the socket. */
1063 \&
1064 unlink(SOCKET_NAME);
1065 \&
1066 exit(EXIT_SUCCESS);
1067 }
1068 .EE
1069 .\" SRC END
1070 .P
1071 .\" SRC BEGIN (client.c)
1072 .EX
1073 /*
1074 * File client.c
1075 */
1076 \&
1077 #include <stdio.h>
1078 #include <stdlib.h>
1079 #include <string.h>
1080 #include <sys/socket.h>
1081 #include <sys/types.h>
1082 #include <sys/un.h>
1083 #include <unistd.h>
1084 \&
1085 #include "connection.h"
1086 \&
1087 int
1088 main(int argc, char *argv[])
1089 {
1090 int ret;
1091 int data_socket;
1092 ssize_t r, w;
1093 struct sockaddr_un addr;
1094 char buffer[BUFFER_SIZE];
1095 \&
1096 /* Create local socket. */
1097 \&
1098 data_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
1099 if (data_socket == \-1) {
1100 perror("socket");
1101 exit(EXIT_FAILURE);
1102 }
1103 \&
1104 /*
1105 * For portability clear the whole structure, since some
1106 * implementations have additional (nonstandard) fields in
1107 * the structure.
1108 */
1109 \&
1110 memset(&addr, 0, sizeof(addr));
1111 \&
1112 /* Connect socket to socket address. */
1113 \&
1114 addr.sun_family = AF_UNIX;
1115 strncpy(addr.sun_path, SOCKET_NAME, sizeof(addr.sun_path) \- 1);
1116 \&
1117 ret = connect(data_socket, (const struct sockaddr *) &addr,
1118 sizeof(addr));
1119 if (ret == \-1) {
1120 fprintf(stderr, "The server is down.\[rs]n");
1121 exit(EXIT_FAILURE);
1122 }
1123 \&
1124 /* Send arguments. */
1125 \&
1126 for (int i = 1; i < argc; ++i) {
1127 w = write(data_socket, argv[i], strlen(argv[i]) + 1);
1128 if (w == \-1) {
1129 perror("write");
1130 break;
1131 }
1132 }
1133 \&
1134 /* Request result. */
1135 \&
1136 strcpy(buffer, "END");
1137 w = write(data_socket, buffer, strlen(buffer) + 1);
1138 if (w == \-1) {
1139 perror("write");
1140 exit(EXIT_FAILURE);
1141 }
1142 \&
1143 /* Receive result. */
1144 \&
1145 r = read(data_socket, buffer, sizeof(buffer));
1146 if (r == \-1) {
1147 perror("read");
1148 exit(EXIT_FAILURE);
1149 }
1150 \&
1151 /* Ensure buffer is 0\-terminated. */
1152 \&
1153 buffer[sizeof(buffer) \- 1] = 0;
1154 \&
1155 printf("Result = %s\[rs]n", buffer);
1156 \&
1157 /* Close socket. */
1158 \&
1159 close(data_socket);
1160 \&
1161 exit(EXIT_SUCCESS);
1162 }
1163 .EE
1164 .\" SRC END
1165 .P
1166 For examples of the use of
1167 .BR SCM_RIGHTS ,
1168 see
1169 .BR cmsg (3)
1170 and
1171 .BR seccomp_unotify (2).
1172 .SH SEE ALSO
1173 .BR recvmsg (2),
1174 .BR sendmsg (2),
1175 .BR socket (2),
1176 .BR socketpair (2),
1177 .BR cmsg (3),
1178 .BR capabilities (7),
1179 .BR credentials (7),
1180 .BR socket (7),
1181 .BR udp (7)