blob: 56a4a5cf2e13edbf2f2bc40e4e16e273bfe6481e [file] [log] [blame]
Willy Tarreau18b7df72020-08-28 12:07:22 +02001/*
2 * Generic code for native (BSD-compatible) sockets
3 *
4 * Copyright 2000-2020 Willy Tarreau <w@1wt.eu>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13#include <ctype.h>
14#include <errno.h>
15#include <fcntl.h>
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19#include <time.h>
20
21#include <sys/param.h>
22#include <sys/socket.h>
23#include <sys/types.h>
24
25#include <haproxy/api.h>
26#include <haproxy/connection.h>
Willy Tarreau063d47d2020-08-28 16:29:53 +020027#include <haproxy/listener-t.h>
Willy Tarreau18b7df72020-08-28 12:07:22 +020028#include <haproxy/namespace.h>
29#include <haproxy/sock.h>
30#include <haproxy/tools.h>
31
Willy Tarreau063d47d2020-08-28 16:29:53 +020032/* the list of remaining sockets transferred from an older process */
33struct xfer_sock_list *xfer_sock_list = NULL;
Willy Tarreau18b7df72020-08-28 12:07:22 +020034
35/* Create a socket to connect to the server in conn->dst (which MUST be valid),
36 * using the configured namespace if needed, or the one passed by the proxy
37 * protocol if required to do so. It ultimately calls socket() or socketat()
38 * and returns the FD or error code.
39 */
40int sock_create_server_socket(struct connection *conn)
41{
42 const struct netns_entry *ns = NULL;
43
44#ifdef USE_NS
45 if (objt_server(conn->target)) {
46 if (__objt_server(conn->target)->flags & SRV_F_USE_NS_FROM_PP)
47 ns = conn->proxy_netns;
48 else
49 ns = __objt_server(conn->target)->netns;
50 }
51#endif
52 return my_socketat(ns, conn->dst->ss_family, SOCK_STREAM, 0);
53}
54
55/*
56 * Retrieves the source address for the socket <fd>, with <dir> indicating
57 * if we're a listener (=0) or an initiator (!=0). It returns 0 in case of
58 * success, -1 in case of error. The socket's source address is stored in
59 * <sa> for <salen> bytes.
60 */
61int sock_get_src(int fd, struct sockaddr *sa, socklen_t salen, int dir)
62{
63 if (dir)
64 return getsockname(fd, sa, &salen);
65 else
66 return getpeername(fd, sa, &salen);
67}
68
69/*
70 * Retrieves the original destination address for the socket <fd>, with <dir>
71 * indicating if we're a listener (=0) or an initiator (!=0). It returns 0 in
72 * case of success, -1 in case of error. The socket's source address is stored
73 * in <sa> for <salen> bytes.
74 */
75int sock_get_dst(int fd, struct sockaddr *sa, socklen_t salen, int dir)
76{
77 if (dir)
78 return getpeername(fd, sa, &salen);
79 else
80 return getsockname(fd, sa, &salen);
81}
82
83/*
84 * Local variables:
85 * c-indent-level: 8
86 * c-basic-offset: 8
87 * End:
88 */