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