1 /* $NetBSD: unix_dgram_connect.c,v 1.4 2025/02/25 19:15:52 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 62 int unix_dgram_connect(const char *path, int block_mode) 63 { 64 const char myname[] = "unix_dgram_connect"; 65 66 #undef sun 67 struct sockaddr_un sun; 68 ssize_t path_len; 69 int sock; 70 71 /* 72 * Translate address information to internal form. 73 */ 74 if ((path_len = strlen(path)) >= sizeof(sun.sun_path)) 75 msg_fatal("%s: unix-domain name too long: %s", myname, path); 76 memset((void *) &sun, 0, sizeof(sun)); 77 sun.sun_family = AF_UNIX; 78 #ifdef HAS_SUN_LEN 79 sun.sun_len = path_len + 1; 80 #endif 81 memcpy(sun.sun_path, path, path_len + 1); 82 83 /* 84 * Create a client socket. 85 */ 86 if ((sock = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) 87 msg_fatal("%s: socket: %m", myname); 88 if (connect(sock, (struct sockaddr *) &sun, sizeof(sun)) < 0) { 89 close(sock); 90 return (-1); 91 } 92 non_blocking(sock, block_mode); 93 return (sock); 94 } 95