xref: /netbsd-src/external/ibm-public/postfix/dist/src/util/unix_dgram_connect.c (revision 67b9b338a7386232ac596b5fd0cd5a9cc8a03c71)
1 /*	$NetBSD: unix_dgram_connect.c,v 1.3 2022/10/08 16:12:50 christos Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	unix_dgram_connect 3
6 /* SUMMARY
7 /*	connect to UNIX-domain datagram server
8 /* SYNOPSIS
9 /*	#include <connect.h>
10 /*
11 /*	int	unix_dgram_connect(
12 /*	const char *path,
13 /*	int	block_mode)
14 /* DESCRIPTION
15 /*	unix_dgram_connect() connects to the specified UNIX-domain
16 /*	datagram server, and returns the resulting file descriptor.
17 /*
18 /*	Arguments:
19 /* .IP path
20 /*	Null-terminated string with connection destination.`
21 /* .IP block_mode
22 /*	Either NON_BLOCKING for a non-blocking socket, or BLOCKING for
23 /*	blocking mode.
24 /* DIAGNOSTICS
25 /*	Fatal errors: path too large, can't create socket.
26 /*
27 /*	Other errors result in a -1 result value, with errno indicating
28 /*	why the service is unavailable.
29 /* .sp
30 /*	ENOENT: the named socket does not exist.
31 /* .sp
32 /*	ECONNREFUSED: the named socket is not open.
33 /* LICENSE
34 /* .ad
35 /* .fi
36 /*	The Secure Mailer license must be distributed with this software.
37 /* AUTHOR(S)
38 /*	Wietse Venema
39 /*	Google, Inc.
40 /*	111 8th Avenue
41 /*	New York, NY 10011, USA
42 /*--*/
43 
44  /*
45   * System library.
46   */
47 #include <sys_defs.h>
48 #include <sys/socket.h>
49 #include <sys/un.h>
50 #include <unistd.h>
51 #include <string.h>
52 
53  /*
54   * Utility library.
55   */
56 #include <msg.h>
57 #include <connect.h>
58 #include <iostuff.h>
59 
60 /* unix_dgram_connect - connect to UNIX-domain datagram service */
61 
unix_dgram_connect(const char * path,int block_mode)62 int     unix_dgram_connect(const char *path, int block_mode)
63 {
64     const char myname[] = "unix_dgram_connect";
65 #undef sun
66     struct sockaddr_un sun;
67     ssize_t path_len;
68     int     sock;
69 
70     /*
71      * Translate address information to internal form.
72      */
73     if ((path_len = strlen(path)) >= sizeof(sun.sun_path))
74 	msg_fatal("%s: unix-domain name too long: %s", myname, path);
75     memset((void *) &sun, 0, sizeof(sun));
76     sun.sun_family = AF_UNIX;
77 #ifdef HAS_SUN_LEN
78     sun.sun_len = path_len + 1;
79 #endif
80     memcpy(sun.sun_path, path, path_len + 1);
81 
82     /*
83      * Create a client socket.
84      */
85     if ((sock = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0)
86 	msg_fatal("%s: socket: %m", myname);
87     if (connect(sock, (struct sockaddr *) &sun, sizeof(sun)) < 0) {
88 	close(sock);
89 	return (-1);
90     }
91     non_blocking(sock, block_mode);
92     return (sock);
93 }
94