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
29 /** Information about one encrypted connection. */
31 /** Function used to decrypt received data. */
33 /** Function used to encrypt data to be sent. */
36 * Context-dependent data (crypt keys), passed verbatim to the above
41 /** Array holding per fd crypt data. */
42 static struct crypt_data
*crypt_data_array
;
43 /** Current size of the crypt data array. */
44 static unsigned cda_size
= 0;
47 * Activate encryption for one file descriptor.
49 * \param fd The file descriptor.
50 * \param recv_f The function used for decrypting received data.
51 * \param send_f The function used for encrypting before sending.
52 * \param private_data User data supplied by the caller.
54 void enable_crypt(int fd
, crypt_function
*recv_f
, crypt_function
*send_f
,
57 if (fd
+ 1 > cda_size
) {
58 crypt_data_array
= para_realloc(crypt_data_array
,
59 (fd
+ 1) * sizeof(struct crypt_data
));
60 memset(crypt_data_array
+ cda_size
, 0,
61 (fd
+ 1 - cda_size
) * sizeof(struct crypt_data
));
64 crypt_data_array
[fd
].recv
= recv_f
;
65 crypt_data_array
[fd
].send
= send_f
;
66 crypt_data_array
[fd
].private_data
= private_data
;
67 PARA_INFO_LOG("rc4 encryption activated for fd %d\n", fd
);
71 * Deactivate encryption for a given fd.
73 * \param fd The file descriptor.
75 * This must be called if and only if \p fd was activated via enable_crypt().
77 void disable_crypt(int fd
)
79 if (cda_size
< fd
+ 1)
81 crypt_data_array
[fd
].recv
= NULL
;
82 crypt_data_array
[fd
].send
= NULL
;
83 crypt_data_array
[fd
].private_data
= NULL
;
88 * Determine the socket type for a given layer-4 protocol.
90 * \param l4type The symbolic name of the transport-layer protocol.
92 * \sa ip(7), socket(2)
94 static inline int sock_type(const unsigned l4type
)
97 case IPPROTO_UDP
: return SOCK_DGRAM
;
98 case IPPROTO_TCP
: return SOCK_STREAM
;
99 case IPPROTO_DCCP
: return SOCK_DCCP
;
101 return -1; /* not supported here */
105 * Pretty-print transport-layer name.
107 static const char *layer4_name(const unsigned l4type
)
110 case IPPROTO_UDP
: return "UDP";
111 case IPPROTO_TCP
: return "TCP";
112 case IPPROTO_DCCP
: return "DCCP";
114 return "UNKNOWN PROTOCOL";
118 * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
120 * \param l3type The layer-3 type (\p AF_INET, \p AF_INET6, \p AF_UNSPEC).
121 * \param l4type The layer-4 type (\p IPPROTO_xxx).
122 * \param passive Whether this is a passive (1) or active (0) socket.
123 * \param host Remote or local hostname or IPv/6 address string.
124 * \param port_number Decimal port number.
126 * This creates a ready-made IPv4/v6 socket structure after looking up the
127 * necessary parameters. The interpretation of \a host depends on the value of
129 * - on a passive socket host is interpreted as an interface IPv4/6 address
130 * (can be left NULL);
131 * - on an active socket, \a host is the peer DNS name or IPv4/6 address
133 * - \a port_number is in either case the numeric port number (not service
136 * Furthermore, bind(2) is called on passive sockets, and connect(2) on active
137 * sockets. The algorithm tries all possible address combinations until it
140 * \return This function returns 1 on success and \a -E_ADDRESS_LOOKUP when no
141 * matching connection could be set up (with details in the error log).
143 * \sa ipv6(7), getaddrinfo(3), bind(2), connect(2).
145 int makesock(unsigned l3type
, unsigned l4type
, int passive
,
146 const char *host
, unsigned short port_number
)
148 struct addrinfo
*local
= NULL
, *src
,
149 *remote
= NULL
, *dst
, hints
;
150 int rc
, on
= 1, sockfd
= -1,
151 socktype
= sock_type(l4type
);
152 char port
[6]; /* port number has at most 5 digits */
154 sprintf(port
, "%u", port_number
);
155 /* Set up address hint structure */
156 memset(&hints
, 0, sizeof(hints
));
157 hints
.ai_family
= l3type
;
158 /* getaddrinfo does not really work well with SOCK_DCCP */
159 if (socktype
== SOCK_DGRAM
|| socktype
== SOCK_STREAM
)
160 hints
.ai_socktype
= socktype
;
162 /* only use addresses available on the host */
163 hints
.ai_flags
= AI_ADDRCONFIG
;
164 if (l3type
== AF_INET6
)
165 /* use v4-mapped-v6 if no v6 addresses found */
166 hints
.ai_flags
|= AI_V4MAPPED
| AI_ALL
;
168 if (passive
&& host
== NULL
)
169 hints
.ai_flags
|= AI_PASSIVE
;
171 /* Obtain local/remote address information */
172 if ((rc
= getaddrinfo(host
, port
, &hints
, passive
? &local
: &remote
))) {
173 PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
175 host
? host
: (passive
? "[loopback]" : "[localhost]"),
176 port
, gai_strerror(rc
));
177 return -E_ADDRESS_LOOKUP
;
180 /* Iterate over all src/dst combination, exhausting dst first */
181 for (src
= local
, dst
= remote
; src
!= NULL
|| dst
!= NULL
; /* no op */ ) {
182 if (src
&& dst
&& src
->ai_family
== AF_INET
183 && dst
->ai_family
== AF_INET6
)
184 goto get_next_dst
; /* v4 -> v6 is not possible */
186 sockfd
= socket(src
? src
->ai_family
: dst
->ai_family
,
192 * Set those options that need to be set before establishing
193 * the connection. Reuse the address on passive (listening)
194 * sockets to avoid failure on restart.
196 if (passive
&& setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
197 &on
, sizeof(on
)) == -1) {
198 PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n",
200 return -ERRNO_TO_PARA_ERROR(errno
);
204 if (bind(sockfd
, src
->ai_addr
, src
->ai_addrlen
) < 0) {
208 if (!dst
) /* bind-only completed successfully */
212 if (dst
&& connect(sockfd
, dst
->ai_addr
, dst
->ai_addrlen
) == 0)
213 break; /* connection completed successfully */
216 if (dst
&& (dst
= dst
->ai_next
))
219 if (src
&& (src
= src
->ai_next
)) /* restart inner loop */
225 freeaddrinfo(remote
);
227 if (src
== NULL
&& dst
== NULL
) {
228 PARA_ERROR_LOG("can not create %s socket %s#%s.\n",
229 layer4_name(l4type
), host
? host
: (passive
?
230 "[loopback]" : "[localhost]"), port
);
231 return -ERRNO_TO_PARA_ERROR(errno
);
237 * Create a passive / listening socket.
239 * \param l3type The network-layer type (\p AF_xxx).
240 * \param l4type The transport-layer type (\p IPPROTO_xxx).
241 * \param port The decimal port number to listen on.
243 * \return Positive integer (socket descriptor) on success, negative value
246 * \sa makesock(), ip(7), ipv6(7), bind(2), listen(2).
248 int para_listen(unsigned l3type
, unsigned l4type
, unsigned short port
)
250 int ret
, fd
= makesock(l3type
, l4type
, 1, NULL
, port
);
253 ret
= listen(fd
, BACKLOG
);
256 return -ERRNO_TO_PARA_ERROR(errno
);
258 PARA_INFO_LOG("listening on %s port %u, fd %d\n",
259 layer4_name(l4type
), port
, fd
);
265 * Print numeric host and port number (beware - uses static char).
267 * \param sa The IPv4/IPv6 socket address to use.
268 * \param len The length of \p sa.
270 * \sa getnameinfo(3).
272 static char *host_and_port(struct sockaddr
*sa
, socklen_t len
)
274 static char output
[NI_MAXHOST
+ NI_MAXSERV
+ 2];
275 char hbuf
[NI_MAXHOST
], sbuf
[NI_MAXSERV
];
278 ret
= getnameinfo(sa
, len
, hbuf
, sizeof(hbuf
), sbuf
, sizeof(sbuf
),
279 NI_NUMERICHOST
| NI_NUMERICSERV
);
281 PARA_WARNING_LOG("hostname lookup error (%s).\n",
283 sprintf(output
, "(unknown)");
285 sprintf(output
, "%s#%s", hbuf
, sbuf
);
290 * Look up the local or remote side of a connected socket structure.
292 * \param fd The socket descriptor of the connected socket.
293 * \param getname Either \p getsockname() for local, or \p getpeername() for
296 * \return A static character string identifying hostname and port of the
299 * \sa getsockname(2), getpeername(2).
301 static char *__get_sock_name(int fd
, int (*getname
)(int, struct sockaddr
*,
304 struct sockaddr_storage ss
;
305 socklen_t sslen
= sizeof(ss
);
307 if (getname(fd
, (struct sockaddr
*)&ss
, &sslen
) < 0) {
308 static char *dont_know
= "(don't know)";
309 PARA_ERROR_LOG("can not determine address from fd %d: %s\n",
310 fd
, strerror(errno
));
313 return host_and_port((struct sockaddr
*)&ss
, sslen
);
316 char *local_name(int sockfd
)
318 return __get_sock_name(sockfd
, getsockname
);
321 char *remote_name(int sockfd
)
323 return __get_sock_name(sockfd
, getpeername
);
327 * Extract IPv4 or IPv6-mapped-IPv4 address from sockaddr_storage.
328 * \param ss Container of IPv4/6 address
329 * \return Extracted IPv4 address (different from 0) or 0 if unsuccessful.
333 struct in_addr
extract_v4_addr(const struct sockaddr_storage
*ss
)
335 struct in_addr ia
= {.s_addr
= 0};
337 if (ss
->ss_family
== AF_INET
)
338 ia
.s_addr
= ((struct sockaddr_in
*)ss
)->sin_addr
.s_addr
;
339 if (ss
->ss_family
== AF_INET6
) {
340 const struct in6_addr v6_addr
= ((struct sockaddr_in6
*)ss
)->sin6_addr
;
342 if (IN6_IS_ADDR_V4MAPPED(&v6_addr
))
343 memcpy(&ia
.s_addr
, &(v6_addr
.s6_addr
[12]), 4);
349 * Write a buffer to a file descriptor, re-write on short writes.
351 * \param fd The file descriptor.
352 * \param buf The buffer to be sent.
353 * \param len The length of \a buf.
355 * \return Standard. In any case, the number of bytes that have been written is
358 static int write_all(int fd
, const char *buf
, size_t *len
)
364 while (*len
< total
) {
365 int ret
= write(fd
, buf
+ *len
, total
- *len
);
367 return -ERRNO_TO_PARA_ERROR(errno
);
374 * Encrypt and send a binary buffer.
376 * \param fd The file descriptor.
377 * \param buf The buffer to be encrypted and sent.
378 * \param len The length of \a buf.
380 * Check if encryption is available. If yes, encrypt the given buffer. Send
381 * out the buffer, encrypted or not, and try to resend the remaing part in case
386 int send_bin_buffer(int fd
, const char *buf
, size_t len
)
389 crypt_function
*cf
= NULL
;
392 PARA_CRIT_LOG("len == 0\n");
393 if (fd
+ 1 <= cda_size
)
394 cf
= crypt_data_array
[fd
].send
;
396 void *private = crypt_data_array
[fd
].private_data
;
397 /* RC4 may write more than len to the output buffer */
398 unsigned char *outbuf
= para_malloc(ROUND_UP(len
, 8));
399 (*cf
)(len
, (unsigned char *)buf
, outbuf
, private);
400 ret
= write_all(fd
, (char *)outbuf
, &len
);
403 ret
= write_all(fd
, buf
, &len
);
408 * Encrypt and send null terminated buffer.
410 * \param fd The file descriptor.
411 * \param buf The null-terminated buffer to be send.
413 * This is equivalent to send_bin_buffer(fd, buf, strlen(buf)).
417 int send_buffer(int fd
, const char *buf
)
419 return send_bin_buffer(fd
, buf
, strlen(buf
));
424 * Send and encrypt a buffer given by a format string.
426 * \param fd The file descriptor.
427 * \param fmt A format string.
431 __printf_2_3
int send_va_buffer(int fd
, const char *fmt
, ...)
436 PARA_VSPRINTF(fmt
, msg
);
437 ret
= send_buffer(fd
, msg
);
443 * Receive and decrypt.
445 * \param fd The file descriptor.
446 * \param buf The buffer to write the decrypted data to.
447 * \param size The size of \a buf.
449 * Receive at most \a size bytes from file descriptor \a fd. If encryption is
450 * available, decrypt the received buffer.
452 * \return The number of bytes received on success, negative on errors.
456 __must_check
int recv_bin_buffer(int fd
, char *buf
, size_t size
)
459 crypt_function
*cf
= NULL
;
461 if (fd
+ 1 <= cda_size
)
462 cf
= crypt_data_array
[fd
].recv
;
464 unsigned char *tmp
= para_malloc(size
);
465 void *private = crypt_data_array
[fd
].private_data
;
466 n
= recv(fd
, tmp
, size
, 0);
469 unsigned char *b
= (unsigned char *)buf
;
470 (*cf
)(numbytes
, tmp
, b
, private);
474 n
= recv(fd
, buf
, size
, 0);
476 return -ERRNO_TO_PARA_ERROR(errno
);
481 * Receive, decrypt and write terminating NULL byte.
483 * \param fd The file descriptor.
484 * \param buf The buffer to write the decrypted data to.
485 * \param size The size of \a buf.
487 * Read and decrypt at most \a size - 1 bytes from file descriptor \a fd and
488 * write a NULL byte at the end of the received data.
490 * \return The return value of the underlying call to \a recv_bin_buffer().
492 * \sa recv_bin_buffer()
494 int recv_buffer(int fd
, char *buf
, size_t size
)
499 n
= recv_bin_buffer(fd
, buf
, size
- 1);
508 * Wrapper around the accept system call.
510 * \param fd The listening socket.
511 * \param addr Structure which is filled in with the address of the peer socket.
512 * \param size Should contain the size of the structure pointed to by \a addr.
514 * Accept incoming connections on \a addr. Retry if interrupted.
516 * \return The new file descriptor on success, negative on errors.
520 int para_accept(int fd
, void *addr
, socklen_t size
)
525 new_fd
= accept(fd
, (struct sockaddr
*) addr
, &size
);
526 while (new_fd
< 0 && errno
== EINTR
);
527 return new_fd
< 0? -ERRNO_TO_PARA_ERROR(errno
) : new_fd
;
531 * Prepare a structure for \p AF_UNIX socket addresses.
533 * \param u Pointer to the struct to be prepared.
534 * \param name The socket pathname.
536 * This just copies \a name to the sun_path component of \a u.
538 * \return Positive on success, \p -E_NAME_TOO_LONG if \a name is longer
539 * than \p UNIX_PATH_MAX.
541 static int init_unix_addr(struct sockaddr_un
*u
, const char *name
)
543 if (strlen(name
) >= UNIX_PATH_MAX
)
544 return -E_NAME_TOO_LONG
;
545 memset(u
->sun_path
, 0, UNIX_PATH_MAX
);
546 u
->sun_family
= PF_UNIX
;
547 strcpy(u
->sun_path
, name
);
552 * Prepare, create, and bind a socket for local communication.
554 * \param name The socket pathname.
555 * \param unix_addr Pointer to the \p AF_UNIX socket structure.
556 * \param mode The desired mode of the socket.
558 * This function creates a local socket for sequenced, reliable,
559 * two-way, connection-based byte streams.
561 * \return The file descriptor, on success, negative on errors.
567 int create_local_socket(const char *name
, struct sockaddr_un
*unix_addr
,
572 ret
= init_unix_addr(unix_addr
, name
);
575 ret
= socket(PF_UNIX
, SOCK_STREAM
, 0);
577 return -ERRNO_TO_PARA_ERROR(errno
);
579 ret
= bind(fd
, (struct sockaddr
*) unix_addr
, UNIX_PATH_MAX
);
581 ret
= -ERRNO_TO_PARA_ERROR(errno
);
585 if (chmod(name
, mode
) < 0)
594 * Prepare, create, and connect to a Unix domain socket for local communication.
596 * \param name The socket pathname.
598 * This function creates a local socket for sequenced, reliable, two-way,
599 * connection-based byte streams.
601 * \return The file descriptor, on success, negative on errors.
603 * \sa create_local_socket(), unix(7), connect(2).
605 int create_remote_socket(const char *name
)
607 struct sockaddr_un unix_addr
;
610 ret
= init_unix_addr(&unix_addr
, name
);
613 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
615 return -ERRNO_TO_PARA_ERROR(errno
);
616 if (connect(fd
, (struct sockaddr
*)&unix_addr
, sizeof(unix_addr
)) == -1) {
617 ret
= -ERRNO_TO_PARA_ERROR(errno
);
627 ssize_t
send_cred_buffer(int sock
, char *buf
)
629 return send_buffer(sock
, buf
);
631 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
633 return recv_buffer(fd
, buf
, size
) > 0? 1 : -E_RECVMSG
;
635 #else /* HAVE_UCRED */
637 * Send \p NULL-terminated buffer and Unix credentials of the current process.
639 * \param sock The socket file descriptor.
640 * \param buf The buffer to be sent.
642 * \return On success, this call returns the number of characters sent. On
643 * error, \p -E_SENDMSG is returned.
645 * \sa sendmsg(2), okir's Black Hats Manual.
647 ssize_t
send_cred_buffer(int sock
, char *buf
)
649 char control
[sizeof(struct cmsghdr
) + 10];
651 struct cmsghdr
*cmsg
;
652 static struct iovec iov
;
658 iov
.iov_len
= strlen(buf
);
662 /* compose the message */
663 memset(&msg
, 0, sizeof(msg
));
666 msg
.msg_control
= control
;
667 msg
.msg_controllen
= sizeof(control
);
668 /* attach the ucred struct */
669 cmsg
= CMSG_FIRSTHDR(&msg
);
670 cmsg
->cmsg_level
= SOL_SOCKET
;
671 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
672 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
673 *(struct ucred
*)CMSG_DATA(cmsg
) = c
;
674 msg
.msg_controllen
= cmsg
->cmsg_len
;
675 ret
= sendmsg(sock
, &msg
, 0);
681 static void dispose_fds(int *fds
, unsigned num
)
685 for (i
= 0; i
< num
; i
++)
690 * Receive a buffer and the Unix credentials of the sending process.
692 * \param fd the socket file descriptor.
693 * \param buf the buffer to store the message.
694 * \param size the size of \a buffer.
696 * \return negative on errors, the user id on success.
698 * \sa recvmsg(2), okir's Black Hats Manual.
700 int recv_cred_buffer(int fd
, char *buf
, size_t size
)
704 struct cmsghdr
*cmsg
;
710 setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &yes
, sizeof(int));
711 memset(&msg
, 0, sizeof(msg
));
712 memset(buf
, 0, size
);
717 msg
.msg_control
= control
;
718 msg
.msg_controllen
= sizeof(control
);
719 if (recvmsg(fd
, &msg
, 0) < 0)
721 result
= -E_SCM_CREDENTIALS
;
722 cmsg
= CMSG_FIRSTHDR(&msg
);
724 if (cmsg
->cmsg_level
== SOL_SOCKET
&& cmsg
->cmsg_type
725 == SCM_CREDENTIALS
) {
726 memcpy(&cred
, CMSG_DATA(cmsg
), sizeof(struct ucred
));
729 if (cmsg
->cmsg_level
== SOL_SOCKET
730 && cmsg
->cmsg_type
== SCM_RIGHTS
) {
731 dispose_fds((int *) CMSG_DATA(cmsg
),
732 (cmsg
->cmsg_len
- CMSG_LEN(0))
735 cmsg
= CMSG_NXTHDR(&msg
, cmsg
);
739 #endif /* HAVE_UCRED */
742 * Receive a buffer and check for a pattern.
744 * \param fd The file descriptor to receive from.
745 * \param pattern The expected pattern.
746 * \param bufsize The size of the internal buffer.
748 * \return Positive if \a pattern was received, negative otherwise.
750 * This function creates a buffer of size \a bufsize and tries
751 * to receive at most \a bufsize bytes from file descriptor \a fd.
752 * If at least \p strlen(\a pattern) bytes were received, the beginning of
753 * the received buffer is compared with \a pattern, ignoring case.
755 * \sa recv_buffer(), \sa strncasecmp(3).
757 int recv_pattern(int fd
, const char *pattern
, size_t bufsize
)
759 size_t len
= strlen(pattern
);
760 char *buf
= para_malloc(bufsize
+ 1);
761 int ret
= -E_RECV_PATTERN
, n
= recv_buffer(fd
, buf
, bufsize
);
765 if (strncasecmp(buf
, pattern
, len
))
770 PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n
,
773 PARA_NOTICE_LOG("recvd: %s\n", buf
);