sockaddr_util_posix.cc 1.9 KB

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