2 * Copyright (C) 2005-2008 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file net.c Networking-related helper functions. */
11 /* At least NetBSD needs these. */
19 #define AI_ADDRCONFIG 0
31 /** Information about one encrypted connection. */
33 /** Function used to decrypt received data. */
35 /** Function used to encrypt data to be sent. */
38 * Context-dependent data (crypt keys), passed verbatim to the above
43 /** Array holding per fd crypt data. */
44 static struct crypt_data
*crypt_data_array
;
45 /** Current size of the crypt data array. */
46 static unsigned cda_size
= 0;
49 * Activate encryption for one file descriptor.
51 * \param fd The file descriptor.
52 * \param recv_f The function used for decrypting received data.
53 * \param send_f The function used for encrypting before sending.
54 * \param private_data User data supplied by the caller.
56 void enable_crypt(int fd
, crypt_function
*recv_f
, crypt_function
*send_f
,
59 if (fd
+ 1 > cda_size
) {
60 crypt_data_array
= para_realloc(crypt_data_array
,
61 (fd
+ 1) * sizeof(struct crypt_data
));
62 memset(crypt_data_array
+ cda_size
, 0,
63 (fd
+ 1 - cda_size
) * sizeof(struct crypt_data
));
66 crypt_data_array
[fd
].recv
= recv_f
;
67 crypt_data_array
[fd
].send
= send_f
;
68 crypt_data_array
[fd
].private_data
= private_data
;
69 PARA_INFO_LOG("rc4 encryption activated for fd %d\n", fd
);
73 * Deactivate encryption for a given fd.
75 * \param fd The file descriptor.
77 * This must be called if and only if \p fd was activated via enable_crypt().
79 void disable_crypt(int fd
)
81 if (cda_size
< fd
+ 1)
83 crypt_data_array
[fd
].recv
= NULL
;
84 crypt_data_array
[fd
].send
= NULL
;
85 crypt_data_array
[fd
].private_data
= NULL
;
90 * Determine the socket type for a given layer-4 protocol.
92 * \param l4type The symbolic name of the transport-layer protocol.
94 * \sa ip(7), socket(2)
96 static inline int sock_type(const unsigned l4type
)
99 case IPPROTO_UDP
: return SOCK_DGRAM
;
100 case IPPROTO_TCP
: return SOCK_STREAM
;
101 case IPPROTO_DCCP
: return SOCK_DCCP
;
103 return -1; /* not supported here */
107 * Pretty-print transport-layer name.
109 static const char *layer4_name(const unsigned l4type
)
112 case IPPROTO_UDP
: return "UDP";
113 case IPPROTO_TCP
: return "TCP";
114 case IPPROTO_DCCP
: return "DCCP";
116 return "UNKNOWN PROTOCOL";
120 * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
122 * \param l3type The layer-3 type (\p AF_INET, \p AF_INET6, \p AF_UNSPEC).
123 * \param l4type The layer-4 type (\p IPPROTO_xxx).
124 * \param passive Whether this is a passive (1) or active (0) socket.
125 * \param host Remote or local hostname or IPv/6 address string.
126 * \param port_number Decimal port number.
128 * This creates a ready-made IPv4/v6 socket structure after looking up the
129 * necessary parameters. The interpretation of \a host depends on the value of
131 * - on a passive socket host is interpreted as an interface IPv4/6 address
132 * (can be left NULL);
133 * - on an active socket, \a host is the peer DNS name or IPv4/6 address
135 * - \a port_number is in either case the numeric port number (not service
138 * Furthermore, bind(2) is called on passive sockets, and connect(2) on active
139 * sockets. The algorithm tries all possible address combinations until it
142 * \return This function returns 1 on success and \a -E_ADDRESS_LOOKUP when no
143 * matching connection could be set up (with details in the error log).
145 * \sa ipv6(7), getaddrinfo(3), bind(2), connect(2).
147 int makesock(unsigned l3type
, unsigned l4type
, int passive
,
148 const char *host
, unsigned short port_number
)
150 struct addrinfo
*local
= NULL
, *src
,
151 *remote
= NULL
, *dst
, hints
;
152 int rc
, on
= 1, sockfd
= -1,
153 socktype
= sock_type(l4type
);
154 char port
[6]; /* port number has at most 5 digits */
156 sprintf(port
, "%u", port_number
);
157 /* Set up address hint structure */
158 memset(&hints
, 0, sizeof(hints
));
159 hints
.ai_family
= l3type
;
160 hints
.ai_socktype
= socktype
;
162 * getaddrinfo does not support SOCK_DCCP, so for the sake of lookup
163 * (and only then) pretend to be UDP.
165 if (l4type
== IPPROTO_DCCP
)
166 hints
.ai_socktype
= SOCK_DGRAM
;
168 /* only use addresses available on the host */
169 hints
.ai_flags
= AI_ADDRCONFIG
;
170 if (l3type
== AF_INET6
)
171 /* use v4-mapped-v6 if no v6 addresses found */
172 hints
.ai_flags
|= AI_V4MAPPED
| AI_ALL
;
174 if (passive
&& host
== NULL
)
175 hints
.ai_flags
|= AI_PASSIVE
;
177 /* Obtain local/remote address information */
178 if ((rc
= getaddrinfo(host
, port
, &hints
, passive
? &local
: &remote
))) {
179 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
181 host
? host
: (passive
? "[loopback]" : "[localhost]"),
182 port
, gai_strerror(rc
));
183 return -E_ADDRESS_LOOKUP
;
186 /* Iterate over all src/dst combination, exhausting dst first */
187 for (src
= local
, dst
= remote
; src
!= NULL
|| dst
!= NULL
; /* no op */ ) {
188 if (src
&& dst
&& src
->ai_family
== AF_INET
189 && dst
->ai_family
== AF_INET6
)
190 goto get_next_dst
; /* v4 -> v6 is not possible */
192 sockfd
= socket(src
? src
->ai_family
: dst
->ai_family
,
198 * Set those options that need to be set before establishing
199 * the connection. Reuse the address on passive (listening)
200 * sockets to avoid failure on restart.
202 if (passive
&& setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
203 &on
, sizeof(on
)) == -1) {
204 PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n",
206 return -ERRNO_TO_PARA_ERROR(errno
);
210 if (bind(sockfd
, src
->ai_addr
, src
->ai_addrlen
) < 0) {
214 if (!dst
) /* bind-only completed successfully */
218 if (dst
&& connect(sockfd
, dst
->ai_addr
, dst
->ai_addrlen
) == 0)
219 break; /* connection completed successfully */
222 if (dst
&& (dst
= dst
->ai_next
))
225 if (src
&& (src
= src
->ai_next
)) /* restart inner loop */
231 freeaddrinfo(remote
);
233 if (src
== NULL
&& dst
== NULL
) {
234 PARA_ERROR_LOG("can not create %s socket %s#%s.\n",
235 layer4_name(l4type
), host
? host
: (passive
?
236 "[loopback]" : "[localhost]"), port
);
237 return -ERRNO_TO_PARA_ERROR(errno
);
243 * Create a passive / listening socket.
245 * \param l3type The network-layer type (\p AF_xxx).
246 * \param l4type The transport-layer type (\p IPPROTO_xxx).
247 * \param port The decimal port number to listen on.
249 * \return Positive integer (socket descriptor) on success, negative value
252 * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
254 int para_listen(unsigned l3type
, unsigned l4type
, unsigned short port
)
256 int ret
, fd
= makesock(l3type
, l4type
, 1, NULL
, port
);
259 ret
= listen(fd
, BACKLOG
);
262 return -ERRNO_TO_PARA_ERROR(errno
);
264 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
265 layer4_name(l4type
), port
, fd
);
271 * Print numeric host and port number (beware - uses static char).
273 * \param sa The IPv4/IPv6 socket address to use.
274 * \param len The length of \p sa.
276 * \sa getnameinfo(3).
278 static char *host_and_port(struct sockaddr
*sa
, socklen_t len
)
280 static char output
[NI_MAXHOST
+ NI_MAXSERV
+ 2];
281 char hbuf
[NI_MAXHOST
], sbuf
[NI_MAXSERV
];
284 ret
= getnameinfo(sa
, len
, hbuf
, sizeof(hbuf
), sbuf
, sizeof(sbuf
),
285 NI_NUMERICHOST
| NI_NUMERICSERV
);
287 PARA_WARNING_LOG("hostname lookup error (%s).\n",
289 sprintf(output
, "(unknown)");
291 sprintf(output
, "%s#%s", hbuf
, sbuf
);
296 * Look up the local or remote side of a connected socket structure.
298 * \param fd The socket descriptor of the connected socket.
299 * \param getname Either \p getsockname() for local, or \p getpeername() for
302 * \return A static character string identifying hostname and port of the
305 * \sa getsockname(2), getpeername(2).
307 static char *__get_sock_name(int fd
, int (*getname
)(int, struct sockaddr
*,
310 struct sockaddr_storage ss
;
311 socklen_t sslen
= sizeof(ss
);
313 if (getname(fd
, (struct sockaddr
*)&ss
, &sslen
) < 0) {
314 static char *dont_know
= "(don't know)";
315 PARA_ERROR_LOG("can not determine address from fd %d: %s\n",
316 fd
, strerror(errno
));
319 return host_and_port((struct sockaddr
*)&ss
, sslen
);
322 char *local_name(int sockfd
)
324 return __get_sock_name(sockfd
, getsockname
);
327 char *remote_name(int sockfd
)
329 return __get_sock_name(sockfd
, getpeername
);
333 * Extract IPv4 or IPv6-mapped-IPv4 address from sockaddr_storage.
334 * \param ss Container of IPv4/6 address
335 * \return Extracted IPv4 address (different from 0) or 0 if unsuccessful.
339 struct in_addr
extract_v4_addr(const struct sockaddr_storage
*ss
)
341 struct in_addr ia
= {.s_addr
= 0};
343 if (ss
->ss_family
== AF_INET
)
344 ia
.s_addr
= ((struct sockaddr_in
*)ss
)->sin_addr
.s_addr
;
345 if (ss
->ss_family
== AF_INET6
) {
346 const struct in6_addr v6_addr
= ((struct sockaddr_in6
*)ss
)->sin6_addr
;
348 if (IN6_IS_ADDR_V4MAPPED(&v6_addr
))
349 memcpy(&ia
.s_addr
, &(v6_addr
.s6_addr
[12]), 4);
355 * Encrypt and send a binary buffer.
357 * \param fd The file descriptor.
358 * \param buf The buffer to be encrypted and sent.
359 * \param len The length of \a buf.
361 * Check if encryption is available. If yes, encrypt the given buffer. Send
362 * out the buffer, encrypted or not, and try to resend the remaing part in case
367 int send_bin_buffer(int fd
, const char *buf
, size_t len
)
370 crypt_function
*cf
= NULL
;
373 PARA_CRIT_LOG("len == 0\n");
374 if (fd
+ 1 <= cda_size
)
375 cf
= crypt_data_array
[fd
].send
;
377 void *private = crypt_data_array
[fd
].private_data
;
378 /* RC4 may write more than len to the output buffer */
379 unsigned char *outbuf
= para_malloc(ROUND_UP(len
, 8));
380 (*cf
)(len
, (unsigned char *)buf
, outbuf
, private);
381 ret
= write_all(fd
, (char *)outbuf
, &len
);
384 ret
= write_all(fd
, buf
, &len
);
389 * Encrypt and send null terminated buffer.
391 * \param fd The file descriptor.
392 * \param buf The null-terminated buffer to be send.
394 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
398 int send_buffer(int fd
, const char *buf
)
400 return send_bin_buffer(fd
, buf
, strlen(buf
));
405 * Send and encrypt a buffer given by a format string.
407 * \param fd The file descriptor.
408 * \param fmt A format string.
412 __printf_2_3
int send_va_buffer(int fd
, const char *fmt
, ...)
417 PARA_VSPRINTF(fmt
, msg
);
418 ret
= send_buffer(fd
, msg
);
424 * Receive and decrypt.
426 * \param fd The file descriptor.
427 * \param buf The buffer to write the decrypted data to.
428 * \param size The size of \a buf.
430 * Receive at most \a size bytes from file descriptor \a fd. If encryption is
431 * available, decrypt the received buffer.
433 * \return The number of bytes received on success, negative on errors.
437 __must_check
int recv_bin_buffer(int fd
, char *buf
, size_t size
)
440 crypt_function
*cf
= NULL
;
442 if (fd
+ 1 <= cda_size
)
443 cf
= crypt_data_array
[fd
].recv
;
445 unsigned char *tmp
= para_malloc(size
);
446 void *private = crypt_data_array
[fd
].private_data
;
447 n
= recv(fd
, tmp
, size
, 0);
450 unsigned char *b
= (unsigned char *)buf
;
451 (*cf
)(numbytes
, tmp
, b
, private);
455 n
= recv(fd
, buf
, size
, 0);
457 return -ERRNO_TO_PARA_ERROR(errno
);
462 * Receive, decrypt and write terminating NULL byte.
464 * \param fd The file descriptor.
465 * \param buf The buffer to write the decrypted data to.
466 * \param size The size of \a buf.
468 * Read and decrypt at most \a size - 1 bytes from file descriptor \a fd and
469 * write a NULL byte at the end of the received data.
471 * \return The return value of the underlying call to \a recv_bin_buffer().
473 * \sa recv_bin_buffer()
475 int recv_buffer(int fd
, char *buf
, size_t size
)
480 n
= recv_bin_buffer(fd
, buf
, size
- 1);
489 * Wrapper around the accept system call.
491 * \param fd The listening socket.
492 * \param addr Structure which is filled in with the address of the peer socket.
493 * \param size Should contain the size of the structure pointed to by \a addr.
495 * Accept incoming connections on \a addr. Retry if interrupted.
497 * \return The new file descriptor on success, negative on errors.
501 int para_accept(int fd
, void *addr
, socklen_t size
)
506 new_fd
= accept(fd
, (struct sockaddr
*) addr
, &size
);
507 while (new_fd
< 0 && errno
== EINTR
);
508 return new_fd
< 0? -ERRNO_TO_PARA_ERROR(errno
) : new_fd
;
512 * Prepare a structure for \p AF_UNIX socket addresses.
514 * \param u Pointer to the struct to be prepared.
515 * \param name The socket pathname.
517 * This just copies \a name to the sun_path component of \a u.
519 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
520 * than \p UNIX_PATH_MAX.
522 static int init_unix_addr(struct sockaddr_un
*u
, const char *name
)
524 if (strlen(name
) >= UNIX_PATH_MAX
)
525 return -E_NAME_TOO_LONG
;
526 memset(u
->sun_path
, 0, UNIX_PATH_MAX
);
527 u
->sun_family
= PF_UNIX
;
528 strcpy(u
->sun_path
, name
);
533 * Prepare, create, and bind a socket for local communication.
535 * \param name The socket pathname.
536 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
537 * \param mode The desired mode of the socket.
539 * This function creates a local socket for sequenced, reliable,
540 * two-way, connection-based byte streams.
542 * \return The file descriptor, on success, negative on errors.
548 int create_local_socket(const char *name
, struct sockaddr_un
*unix_addr
,
553 ret
= init_unix_addr(unix_addr
, name
);
556 ret
= socket(PF_UNIX
, SOCK_STREAM
, 0);
558 return -ERRNO_TO_PARA_ERROR(errno
);
560 ret
= bind(fd
, (struct sockaddr
*) unix_addr
, UNIX_PATH_MAX
);
562 ret
= -ERRNO_TO_PARA_ERROR(errno
);
566 if (chmod(name
, mode
) < 0)
575 * Prepare, create, and connect to a Unix domain socket for local communication.
577 * \param name The socket pathname.
579 * This function creates a local socket for sequenced, reliable, two-way,
580 * connection-based byte streams.
582 * \return The file descriptor, on success, negative on errors.
584 * \sa create_local_socket(), unix(7), connect(2).
586 int create_remote_socket(const char *name
)
588 struct sockaddr_un unix_addr
;
591 ret
= init_unix_addr(&unix_addr
, name
);
594 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
596 return -ERRNO_TO_PARA_ERROR(errno
);
597 if (connect(fd
, (struct sockaddr
*)&unix_addr
, sizeof(unix_addr
)) == -1) {
598 ret
= -ERRNO_TO_PARA_ERROR(errno
);
608 ssize_t
send_cred_buffer(int sock
, char *buf
)
610 return send_buffer(sock
, buf
);
612 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
614 return recv_buffer(fd
, buf
, size
) > 0? 1 : -E_RECVMSG
;
616 #else /* HAVE_UCRED */
618 * Send \p NULL-terminated buffer and Unix credentials of the current process.
620 * \param sock The socket file descriptor.
621 * \param buf The buffer to be sent.
623 * \return On success, this call returns the number of characters sent. On
624 * error, \p -E_SENDMSG is returned.
626 * \sa sendmsg(2), okir's Black Hats Manual.
628 ssize_t
send_cred_buffer(int sock
, char *buf
)
630 char control
[sizeof(struct cmsghdr
) + 10];
632 struct cmsghdr
*cmsg
;
633 static struct iovec iov
;
639 iov
.iov_len
= strlen(buf
);
643 /* compose the message */
644 memset(&msg
, 0, sizeof(msg
));
647 msg
.msg_control
= control
;
648 msg
.msg_controllen
= sizeof(control
);
649 /* attach the ucred struct */
650 cmsg
= CMSG_FIRSTHDR(&msg
);
651 cmsg
->cmsg_level
= SOL_SOCKET
;
652 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
653 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
654 *(struct ucred
*)CMSG_DATA(cmsg
) = c
;
655 msg
.msg_controllen
= cmsg
->cmsg_len
;
656 ret
= sendmsg(sock
, &msg
, 0);
662 static void dispose_fds(int *fds
, unsigned num
)
666 for (i
= 0; i
< num
; i
++)
671 * Receive a buffer and the Unix credentials of the sending process.
673 * \param fd the socket file descriptor.
674 * \param buf the buffer to store the message.
675 * \param size the size of \a buffer.
677 * \return negative on errors, the user id on success.
679 * \sa recvmsg(2), okir's Black Hats Manual.
681 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
685 struct cmsghdr
*cmsg
;
691 setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &yes
, sizeof(int));
692 memset(&msg
, 0, sizeof(msg
));
693 memset(buf
, 0, size
);
698 msg
.msg_control
= control
;
699 msg
.msg_controllen
= sizeof(control
);
700 if (recvmsg(fd
, &msg
, 0) < 0)
702 result
= -E_SCM_CREDENTIALS
;
703 cmsg
= CMSG_FIRSTHDR(&msg
);
705 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
706 == SCM_CREDENTIALS
) {
707 memcpy(&cred
, CMSG_DATA(cmsg
), sizeof(struct ucred
));
710 if (cmsg
->cmsg_level
== SOL_SOCKET
711 && cmsg
->cmsg_type
== SCM_RIGHTS
) {
712 dispose_fds((int *) CMSG_DATA(cmsg
),
713 (cmsg
->cmsg_len
- CMSG_LEN(0))
716 cmsg
= CMSG_NXTHDR(&msg
, cmsg
);
720 #endif /* HAVE_UCRED */
723 * Receive a buffer and check for a pattern.
725 * \param fd The file descriptor to receive from.
726 * \param pattern The expected pattern.
727 * \param bufsize The size of the internal buffer.
729 * \return Positive if \a pattern was received, negative otherwise.
731 * This function creates a buffer of size \a bufsize and tries
732 * to receive at most \a bufsize bytes from file descriptor \a fd.
733 * If at least \p strlen(\a pattern) bytes were received, the beginning of
734 * the received buffer is compared with \a pattern, ignoring case.
736 * \sa recv_buffer(), \sa strncasecmp(3).
738 int recv_pattern(int fd
, const char *pattern
, size_t bufsize
)
740 size_t len
= strlen(pattern
);
741 char *buf
= para_malloc(bufsize
+ 1);
742 int ret
= -E_RECV_PATTERN
, n
= recv_buffer(fd
, buf
, bufsize
);
746 if (strncasecmp(buf
, pattern
, len
))
751 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n
,
754 PARA_NOTICE_LOG("recvd: %s\n", buf
);