ipc_address.cpp
Go to the documentation of this file.
1 /* SPDX-License-Identifier: MPL-2.0 */
2 
3 #include "precompiled.hpp"
4 #include "compat.hpp"
5 #include "ipc_address.hpp"
6 
7 #if defined ZMQ_HAVE_IPC
8 
9 #include "err.hpp"
10 
11 #include <string>
12 
13 zmq::ipc_address_t::ipc_address_t ()
14 {
15  memset (&_address, 0, sizeof _address);
16 }
17 
18 zmq::ipc_address_t::ipc_address_t (const sockaddr *sa_, socklen_t sa_len_) :
19  _addrlen (sa_len_)
20 {
21  zmq_assert (sa_ && sa_len_ > 0);
22 
23  memset (&_address, 0, sizeof _address);
24  if (sa_->sa_family == AF_UNIX)
25  memcpy (&_address, sa_, sa_len_);
26 }
27 
28 zmq::ipc_address_t::~ipc_address_t ()
29 {
30 }
31 
32 int zmq::ipc_address_t::resolve (const char *path_)
33 {
34  const size_t path_len = strlen (path_);
35  if (path_len >= sizeof _address.sun_path) {
36  errno = ENAMETOOLONG;
37  return -1;
38  }
39  if (path_[0] == '@' && !path_[1]) {
40  errno = EINVAL;
41  return -1;
42  }
43 
44  _address.sun_family = AF_UNIX;
45  memcpy (_address.sun_path, path_, path_len + 1);
46  /* Abstract sockets start with '\0' */
47  if (path_[0] == '@')
48  *_address.sun_path = '\0';
49 
50  _addrlen =
51  static_cast<socklen_t> (offsetof (sockaddr_un, sun_path) + path_len);
52  return 0;
53 }
54 
55 int zmq::ipc_address_t::to_string (std::string &addr_) const
56 {
57  if (_address.sun_family != AF_UNIX) {
58  addr_.clear ();
59  return -1;
60  }
61 
62  const char prefix[] = "ipc://";
63  char buf[sizeof prefix + sizeof _address.sun_path];
64  char *pos = buf;
65  memcpy (pos, prefix, sizeof prefix - 1);
66  pos += sizeof prefix - 1;
67  const char *src_pos = _address.sun_path;
68  if (!_address.sun_path[0] && _address.sun_path[1]) {
69  *pos++ = '@';
70  src_pos++;
71  }
72  // according to http://man7.org/linux/man-pages/man7/unix.7.html, NOTES
73  // section, address.sun_path might not always be null-terminated; therefore,
74  // we calculate the length based of addrlen
75  const size_t src_len =
76  strnlen (src_pos, _addrlen - offsetof (sockaddr_un, sun_path)
77  - (src_pos - _address.sun_path));
78  memcpy (pos, src_pos, src_len);
79  addr_.assign (buf, pos - buf + src_len);
80  return 0;
81 }
82 
83 const sockaddr *zmq::ipc_address_t::addr () const
84 {
85  return reinterpret_cast<const sockaddr *> (&_address);
86 }
87 
88 socklen_t zmq::ipc_address_t::addrlen () const
89 {
90  return _addrlen;
91 }
92 
93 #endif
EINVAL
#define EINVAL
Definition: errno.hpp:25
ipc_address.hpp
strnlen
static size_t strnlen(const char *s, size_t len)
Definition: compat.hpp:37
precompiled.hpp
zmq_assert
#define zmq_assert(x)
Definition: err.hpp:102
string
GLsizei const GLchar *const * string
Definition: glcorearb.h:3083
errno
int errno
compat.hpp
prefix
static const char prefix[]
Definition: test_pair_ipc.cpp:26
buf
GLenum GLuint GLenum GLsizei const GLchar * buf
Definition: glcorearb.h:4175
err.hpp


libaditof
Author(s):
autogenerated on Wed May 21 2025 02:06:54