Debian Codegraph @

src/ws/cockpitsocket.c

raw
1 /*
2 * Copyright (C) 2021 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 #include "config.h"
7
8 /* This gets logged as part of the (more verbose) protocol logging */
9 #ifdef G_LOG_DOMAIN
10 #undef G_LOG_DOMAIN
11 #endif
12 #define G_LOG_DOMAIN "cockpit-protocol"
13
14 #include "cockpitsocket.h"
15
16 #include <sys/socket.h>
17 #include <gio/gio.h>
18
19 /* _always_ takes ownership of fd, even in error case */
20 static gpointer
21 cockpit_socket_new_take_fd (int fd,
22 GError **error)
23 {
24 GSocket *socket = g_socket_new_from_fd (fd, error);
25 if (socket == NULL)
26 close (fd);
27
28 return socket;
29 }
30
31 static gpointer
32 cockpit_socket_connection_new_take_fd (GType expected_type,
33 int fd,
34 GError **error)
35 {
36 g_autoptr(GSocket) socket = cockpit_socket_new_take_fd (fd, error);
37 if (socket == NULL)
38 return NULL;
39
40 g_autoptr(GSocketConnection) connection = g_socket_connection_factory_create_connection (socket);
41 if (!G_TYPE_CHECK_INSTANCE_TYPE (connection, expected_type))
42 {
43 g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_INVAL,
44 "connection has type %s, not %s as expected",
45 G_OBJECT_TYPE_NAME (connection), g_type_name (expected_type));
46 return NULL;
47 }
48
49 return g_steal_pointer (&connection);
50 }
51
52 void
53 cockpit_socket_socketpair (GSocket **one,
54 GSocket **two)
55 {
56 int sv[2];
57 if (socketpair (AF_LOCAL, SOCK_STREAM, 0, sv))
58 g_error ("socketpair(AF_LOCAL, SOCK_STREAM) failed: %m");
59
60 g_autoptr(GError) error = NULL;
61 *one = g_socket_new_from_fd (sv[0], &error);
62 g_assert_no_error (error);
63
64 *two = g_socket_new_from_fd (sv[1], &error);
65 g_assert_no_error (error);
66 }
67
68 void
69 cockpit_socket_streampair (GIOStream **one,
70 GIOStream **two)
71 {
72 int sv[2];
73 if (socketpair (AF_LOCAL, SOCK_STREAM, 0, sv))
74 g_error ("socketpair(AF_LOCAL, SOCK_STREAM) failed: %m");
75
76 g_autoptr(GError) error = NULL;
77 *one = cockpit_socket_connection_new_take_fd (G_TYPE_IO_STREAM, sv[0], &error);
78 g_assert_no_error (error);
79
80 *two = cockpit_socket_connection_new_take_fd (G_TYPE_IO_STREAM, sv[1], &error);
81 g_assert_no_error (error);
82 }