Line data Source code
1 : /* SPDX-License-Identifier: GPL-2.0-only */
2 : /*
3 : * Copyright (c) 2023 Meta Platforms, Inc. and affiliates.
4 : */
5 :
6 : #include "libbpfilter/generic.h"
7 :
8 : #include <errno.h>
9 : #include <string.h>
10 : #include <sys/socket.h>
11 : #include <sys/un.h>
12 :
13 : #include "core/helper.h"
14 : #include "core/io.h"
15 : #include "core/logger.h"
16 :
17 0 : int bf_send(const struct bf_request *request, struct bf_response **response)
18 : {
19 0 : _cleanup_close_ int fd = -1;
20 0 : struct sockaddr_un addr = {};
21 : int r;
22 :
23 0 : bf_assert(request);
24 0 : bf_assert(response);
25 :
26 0 : fd = socket(AF_UNIX, SOCK_STREAM, 0);
27 0 : if (fd < 0)
28 0 : return bf_err_r(errno, "bpfilter: can't create socket");
29 :
30 0 : addr.sun_family = AF_UNIX;
31 0 : strncpy(addr.sun_path, BF_SOCKET_PATH, sizeof(addr.sun_path) - 1);
32 :
33 0 : r = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
34 0 : if (r < 0)
35 0 : return bf_err_r(errno, "bpfilter: failed to connect to socket");
36 :
37 0 : r = bf_send_request(fd, request);
38 0 : if (r < 0)
39 0 : return bf_err_r(r, "bpfilter: failed to send request to the daemon");
40 :
41 0 : r = bf_recv_response(fd, response);
42 0 : if (r < 0) {
43 0 : return bf_err_r(r,
44 : "bpfilter: failed to receive response from the daemon");
45 : }
46 :
47 : return 0;
48 : }
49 :
50 0 : int bf_send_with_fd(const struct bf_request *request,
51 : struct bf_response **response)
52 : {
53 0 : bf_assert(request && response);
54 :
55 0 : _cleanup_close_ int sock_fd = -1;
56 0 : _cleanup_close_ int fd = -1;
57 0 : struct sockaddr_un addr = {};
58 : int r;
59 :
60 0 : sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
61 0 : if (sock_fd < 0)
62 0 : return bf_err_r(errno, "failed to create socket");
63 :
64 0 : addr.sun_family = AF_UNIX;
65 0 : strncpy(addr.sun_path, BF_SOCKET_PATH, sizeof(addr.sun_path) - 1);
66 :
67 0 : r = connect(sock_fd, (struct sockaddr *)&addr, sizeof(addr));
68 0 : if (r < 0)
69 0 : return bf_err_r(errno, "failed to connect to socket");
70 :
71 0 : r = bf_send_request(sock_fd, request);
72 0 : if (r < 0)
73 0 : return bf_err_r(r, "failed to send request to the daemon");
74 :
75 0 : fd = bf_recv_fd(sock_fd);
76 0 : if (fd < 0)
77 0 : return bf_err_r(fd, "failed to receive file descriptor");
78 :
79 0 : r = bf_recv_response(sock_fd, response);
80 0 : if (r < 0)
81 0 : return bf_err_r(r, "failed to receive response from the daemon");
82 :
83 0 : return TAKE_FD(fd);
84 : }
|