1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9
10 #include "net/base/sockaddr_util_posix.h"
11
12 #include <stddef.h>
13 #include <string.h>
14 #include <stddef.h>
15
16 #include <sys/socket.h>
17 #include <sys/un.h>
18
19 #include "build/build_config.h"
20 #include "net/base/sockaddr_storage.h"
21
22 namespace net {
23
FillUnixAddress(const std::string & socket_path,bool use_abstract_namespace,SockaddrStorage * address)24 bool FillUnixAddress(const std::string& socket_path,
25 bool use_abstract_namespace,
26 SockaddrStorage* address) {
27 // Caller should provide a non-empty path for the socket address.
28 if (socket_path.empty())
29 return false;
30
31 size_t path_max = address->addr_len - offsetof(struct sockaddr_un, sun_path);
32 // Non abstract namespace pathname should be null-terminated. Abstract
33 // namespace pathname must start with '\0'. So, the size is always greater
34 // than socket_path size by 1.
35 size_t path_size = socket_path.size() + 1;
36 if (path_size > path_max)
37 return false;
38
39 struct sockaddr_un* socket_addr =
40 reinterpret_cast<struct sockaddr_un*>(address->addr);
41 memset(socket_addr, 0, address->addr_len);
42 socket_addr->sun_family = AF_UNIX;
43 address->addr_len = path_size + offsetof(struct sockaddr_un, sun_path);
44 if (!use_abstract_namespace) {
45 memcpy(socket_addr->sun_path, socket_path.c_str(), socket_path.size());
46 return true;
47 }
48
49 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
50 // Convert the path given into abstract socket name. It must start with
51 // the '\0' character, so we are adding it. |addr_len| must specify the
52 // length of the structure exactly, as potentially the socket name may
53 // have '\0' characters embedded (although we don't support this).
54 // Note that addr.sun_path is already zero initialized.
55 memcpy(socket_addr->sun_path + 1, socket_path.c_str(), socket_path.size());
56 return true;
57 #else
58 return false;
59 #endif
60 }
61
62 } // namespace net
63