blob: 829ae6798dd598f12594be79de2582d65330037c [file] [log] [blame]
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001#include "aos/network/sctp_lib.h"
2
3#include <arpa/inet.h>
Adam Snaiderbe263512023-05-18 20:40:23 -07004#include <linux/sctp.h>
Austin Schuhe84c3ed2019-12-14 15:29:48 -08005#include <net/if.h>
6#include <netdb.h>
Adam Snaiderbe263512023-05-18 20:40:23 -07007#include <sys/socket.h>
Austin Schuh2fe4b712020-03-15 14:21:45 -07008#include <sys/stat.h>
9#include <sys/types.h>
10#include <unistd.h>
Austin Schuhe84c3ed2019-12-14 15:29:48 -080011
Austin Schuha705d782021-07-31 20:40:00 -070012#include <algorithm>
Adam Snaider9bb33442023-06-26 16:31:37 -070013#include <cerrno>
14#include <fstream>
Austin Schuhe84c3ed2019-12-14 15:29:48 -080015#include <string_view>
Adam Snaider9bb33442023-06-26 16:31:37 -070016#include <vector>
Austin Schuhe84c3ed2019-12-14 15:29:48 -080017
Austin Schuh2fe4b712020-03-15 14:21:45 -070018#include "aos/util/file.h"
19
Adam Snaider13d48d92023-08-03 12:20:15 -070020// The casts required to read datastructures from sockets trip - Wcast - align.
21#ifdef __clang
22#pragma clang diagnostic ignored "-Wcast-align"
23#endif
24
Austin Schuh0a0a8272021-12-08 13:19:32 -080025DEFINE_string(interface, "", "network interface");
Brian Silverman0c6d44e2021-11-10 12:27:49 -080026DEFINE_bool(disable_ipv6, false, "disable ipv6");
Austin Schuh9dd8f592021-12-25 14:32:43 -080027DEFINE_int32(rmem, 0, "If nonzero, set rmem to this size.");
Austin Schuhe84c3ed2019-12-14 15:29:48 -080028
Stephan Pleinesf63bde82024-01-13 15:59:33 -080029namespace aos::message_bridge {
Austin Schuhe84c3ed2019-12-14 15:29:48 -080030
31namespace {
32const char *sac_state_tbl[] = {"COMMUNICATION_UP", "COMMUNICATION_LOST",
33 "RESTART", "SHUTDOWN_COMPLETE",
Sarah Newman4aeb2372022-04-06 13:07:11 -070034 "CANT_START_ASSOCIATION"};
Austin Schuhe84c3ed2019-12-14 15:29:48 -080035
36typedef union {
37 struct sctp_initmsg init;
38 struct sctp_sndrcvinfo sndrcvinfo;
39} _sctp_cmsg_data_t;
40
Adam Snaider9bb33442023-06-26 16:31:37 -070041#if HAS_SCTP_AUTH
Adam Snaider96a0f4b2023-05-18 20:41:19 -070042// Returns true if SCTP authentication is available and enabled.
43bool SctpAuthIsEnabled() {
Adam Snaider96a0f4b2023-05-18 20:41:19 -070044 struct stat current_stat;
45 if (stat("/proc/sys/net/sctp/auth_enable", &current_stat) != -1) {
46 int value = std::stoi(
47 util::ReadFileToStringOrDie("/proc/sys/net/sctp/auth_enable"));
48 CHECK(value == 0 || value == 1)
49 << "Unknown auth enable sysctl value: " << value;
50 return value == 1;
51 } else {
52 LOG(WARNING) << "/proc/sys/net/sctp/auth_enable doesn't exist.";
53 return false;
54 }
Adam Snaider96a0f4b2023-05-18 20:41:19 -070055}
56
Adam Snaider9bb33442023-06-26 16:31:37 -070057std::vector<uint8_t> GenerateSecureRandomSequence(size_t count) {
58 std::ifstream rng("/dev/random", std::ios::in | std::ios::binary);
59 CHECK(rng) << "Unable to open /dev/random";
60 std::vector<uint8_t> out(count, 0);
61 rng.read(reinterpret_cast<char *>(out.data()), count);
62 CHECK(rng) << "Couldn't read from random device";
63 rng.close();
64 return out;
65}
66#endif
67
Austin Schuhe84c3ed2019-12-14 15:29:48 -080068} // namespace
69
Austin Schuh0a0a8272021-12-08 13:19:32 -080070bool Ipv6Enabled() {
71 if (FLAGS_disable_ipv6) {
72 return false;
73 }
74 int fd = socket(AF_INET6, SOCK_SEQPACKET, IPPROTO_SCTP);
75 if (fd != -1) {
76 close(fd);
77 return true;
78 }
79 switch (errno) {
80 case EAFNOSUPPORT:
81 case EINVAL:
82 case EPROTONOSUPPORT:
83 PLOG(INFO) << "no ipv6";
84 return false;
85 default:
86 PLOG(FATAL) << "Open socket failed";
87 return false;
88 };
89}
90
91struct sockaddr_storage ResolveSocket(std::string_view host, int port,
92 bool use_ipv6) {
Austin Schuhe84c3ed2019-12-14 15:29:48 -080093 struct sockaddr_storage result;
James Kuszmaul784deb72023-02-17 14:42:51 -080094 memset(&result, 0, sizeof(result));
Austin Schuhe84c3ed2019-12-14 15:29:48 -080095 struct addrinfo *addrinfo_result;
96 struct sockaddr_in *t_addr = (struct sockaddr_in *)&result;
97 struct sockaddr_in6 *t_addr6 = (struct sockaddr_in6 *)&result;
Brian Silverman0c6d44e2021-11-10 12:27:49 -080098 struct addrinfo hints;
99 memset(&hints, 0, sizeof(hints));
Austin Schuh0a0a8272021-12-08 13:19:32 -0800100 if (!use_ipv6) {
Brian Silverman0c6d44e2021-11-10 12:27:49 -0800101 hints.ai_family = AF_INET;
102 } else {
Austin Schuh0a0a8272021-12-08 13:19:32 -0800103 // Default to IPv6 as the clearly superior protocol, since it also handles
104 // IPv4.
Brian Silverman0c6d44e2021-11-10 12:27:49 -0800105 hints.ai_family = AF_INET6;
106 }
107 hints.ai_socktype = SOCK_SEQPACKET;
108 hints.ai_protocol = IPPROTO_SCTP;
109 // We deliberately avoid AI_ADDRCONFIG here because it breaks running things
110 // inside Bazel's test sandbox, which has no non-localhost IPv4 or IPv6
111 // addresses. Also, it's not really helpful, because most systems will have
112 // link-local addresses of both types with any interface that's up.
113 hints.ai_flags = AI_PASSIVE | AI_V4MAPPED | AI_NUMERICSERV;
114 int ret = getaddrinfo(host.empty() ? nullptr : std::string(host).c_str(),
115 std::to_string(port).c_str(), &hints, &addrinfo_result);
Brian Silverman0c6d44e2021-11-10 12:27:49 -0800116 if (ret == EAI_SYSTEM) {
117 PLOG(FATAL) << "getaddrinfo failed to look up '" << host << "'";
118 } else if (ret != 0) {
119 LOG(FATAL) << "getaddrinfo failed to look up '" << host
120 << "': " << gai_strerror(ret);
121 }
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800122 switch (addrinfo_result->ai_family) {
123 case AF_INET:
124 memcpy(t_addr, addrinfo_result->ai_addr, addrinfo_result->ai_addrlen);
125 t_addr->sin_family = addrinfo_result->ai_family;
126 t_addr->sin_port = htons(port);
127
128 break;
129 case AF_INET6:
130 memcpy(t_addr6, addrinfo_result->ai_addr, addrinfo_result->ai_addrlen);
131 t_addr6->sin6_family = addrinfo_result->ai_family;
132 t_addr6->sin6_port = htons(port);
133
134 if (FLAGS_interface.size() > 0) {
135 t_addr6->sin6_scope_id = if_nametoindex(FLAGS_interface.c_str());
136 }
137
138 break;
139 }
140
141 // Now print it back out nicely.
142 char host_string[NI_MAXHOST];
143 char service_string[NI_MAXSERV];
144
145 int error = getnameinfo((struct sockaddr *)&result,
146 addrinfo_result->ai_addrlen, host_string, NI_MAXHOST,
147 service_string, NI_MAXSERV, NI_NUMERICHOST);
148
149 if (error) {
150 LOG(ERROR) << "Reverse lookup failed ... " << gai_strerror(error);
151 }
152
153 LOG(INFO) << "remote:addr=" << host_string << ", port=" << service_string
154 << ", family=" << addrinfo_result->ai_family;
155
156 freeaddrinfo(addrinfo_result);
157
158 return result;
159}
160
161std::string_view Family(const struct sockaddr_storage &sockaddr) {
162 if (sockaddr.ss_family == AF_INET) {
163 return "AF_INET";
164 } else if (sockaddr.ss_family == AF_INET6) {
165 return "AF_INET6";
166 } else {
167 return "unknown";
168 }
169}
170std::string Address(const struct sockaddr_storage &sockaddr) {
171 char addrbuf[INET6_ADDRSTRLEN];
172 if (sockaddr.ss_family == AF_INET) {
173 const struct sockaddr_in *sin = (const struct sockaddr_in *)&sockaddr;
174 return std::string(
175 inet_ntop(AF_INET, &sin->sin_addr, addrbuf, INET6_ADDRSTRLEN));
176 } else {
177 const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)&sockaddr;
178 return std::string(
179 inet_ntop(AF_INET6, &sin6->sin6_addr, addrbuf, INET6_ADDRSTRLEN));
180 }
181}
182
183void PrintNotification(const Message *msg) {
184 const union sctp_notification *snp =
185 (const union sctp_notification *)msg->data();
186
187 LOG(INFO) << "Notification:";
188
189 switch (snp->sn_header.sn_type) {
190 case SCTP_ASSOC_CHANGE: {
191 const struct sctp_assoc_change *sac = &snp->sn_assoc_change;
192 LOG(INFO) << "SCTP_ASSOC_CHANGE(" << sac_state_tbl[sac->sac_state] << ")";
193 VLOG(1) << " (assoc_change: state=" << sac->sac_state
194 << ", error=" << sac->sac_error
195 << ", instr=" << sac->sac_inbound_streams
196 << " outstr=" << sac->sac_outbound_streams
197 << ", assoc=" << sac->sac_assoc_id << ")";
198 } break;
199 case SCTP_PEER_ADDR_CHANGE: {
200 const struct sctp_paddr_change *spc = &snp->sn_paddr_change;
201 LOG(INFO) << " SlCTP_PEER_ADDR_CHANGE";
202 VLOG(1) << "\t\t(peer_addr_change: " << Address(spc->spc_aaddr)
203 << " state=" << spc->spc_state << ", error=" << spc->spc_error
204 << ")";
205 } break;
206 case SCTP_SEND_FAILED: {
207 const struct sctp_send_failed *ssf = &snp->sn_send_failed;
208 LOG(INFO) << " SCTP_SEND_FAILED";
209 VLOG(1) << "\t\t(sendfailed: len=" << ssf->ssf_length
210 << " err=" << ssf->ssf_error << ")";
211 } break;
212 case SCTP_REMOTE_ERROR: {
213 const struct sctp_remote_error *sre = &snp->sn_remote_error;
214 LOG(INFO) << " SCTP_REMOTE_ERROR";
215 VLOG(1) << "\t\t(remote_error: err=" << ntohs(sre->sre_error) << ")";
216 } break;
Austin Schuhf7777002020-09-01 18:41:28 -0700217 case SCTP_STREAM_CHANGE_EVENT: {
Austin Schuh62a0c272021-03-31 21:04:53 -0700218 const struct sctp_stream_change_event *sce = &snp->sn_strchange_event;
Austin Schuhf7777002020-09-01 18:41:28 -0700219 LOG(INFO) << " SCTP_STREAM_CHANGE_EVENT";
220 VLOG(1) << "\t\t(stream_change_event: flags=" << sce->strchange_flags
221 << ", assoc_id=" << sce->strchange_assoc_id
222 << ", instrms=" << sce->strchange_instrms
223 << ", outstrms=" << sce->strchange_outstrms << " )";
224 } break;
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800225 case SCTP_SHUTDOWN_EVENT: {
226 LOG(INFO) << " SCTP_SHUTDOWN_EVENT";
227 } break;
228 default:
229 LOG(INFO) << " Unknown type: " << snp->sn_header.sn_type;
230 break;
231 }
232}
233
234std::string GetHostname() {
235 char buf[256];
236 buf[sizeof(buf) - 1] = '\0';
237 PCHECK(gethostname(buf, sizeof(buf) - 1) == 0);
238 return buf;
239}
240
241std::string Message::PeerAddress() const { return Address(sin); }
242
243void LogSctpStatus(int fd, sctp_assoc_t assoc_id) {
244 struct sctp_status status;
245 memset(&status, 0, sizeof(status));
246 status.sstat_assoc_id = assoc_id;
247
248 socklen_t size = sizeof(status);
Adam Snaiderbe263512023-05-18 20:40:23 -0700249 const int result = getsockopt(fd, IPPROTO_SCTP, SCTP_STATUS,
Austin Schuha5f545b2021-07-31 20:39:42 -0700250 reinterpret_cast<void *>(&status), &size);
251 if (result == -1 && errno == EINVAL) {
252 LOG(INFO) << "sctp_status) not associated";
253 return;
254 }
255 PCHECK(result == 0);
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800256
257 LOG(INFO) << "sctp_status) sstat_assoc_id:" << status.sstat_assoc_id
258 << " sstat_state:" << status.sstat_state
259 << " sstat_rwnd:" << status.sstat_rwnd
260 << " sstat_unackdata:" << status.sstat_unackdata
261 << " sstat_penddata:" << status.sstat_penddata
262 << " sstat_instrms:" << status.sstat_instrms
263 << " sstat_outstrms:" << status.sstat_outstrms
264 << " sstat_fragmentation_point:" << status.sstat_fragmentation_point
265 << " sstat_primary.spinfo_srtt:" << status.sstat_primary.spinfo_srtt
266 << " sstat_primary.spinfo_rto:" << status.sstat_primary.spinfo_rto;
267}
268
Austin Schuh507f7582021-07-31 20:39:55 -0700269void SctpReadWrite::OpenSocket(const struct sockaddr_storage &sockaddr_local) {
270 fd_ = socket(sockaddr_local.ss_family, SOCK_SEQPACKET, IPPROTO_SCTP);
271 PCHECK(fd_ != -1);
272 LOG(INFO) << "socket(" << Family(sockaddr_local)
273 << ", SOCK_SEQPACKET, IPPROTOSCTP) = " << fd_;
274 {
275 // Per https://tools.ietf.org/html/rfc6458
276 // Setting this to !0 allows event notifications to be interleaved
Austin Schuha705d782021-07-31 20:40:00 -0700277 // with data if enabled. This typically only matters during congestion.
278 // However, Linux seems to interleave under memory pressure regardless of
279 // this being enabled, so we have to handle it in the code anyways, so might
280 // as well turn it on all the time.
281 // TODO(Brian): Change this to 2 once we have kernels that support it, and
282 // also address the TODO in ProcessNotification to match on all the
283 // necessary fields.
284 int interleaving = 1;
Austin Schuh507f7582021-07-31 20:39:55 -0700285 PCHECK(setsockopt(fd_, IPPROTO_SCTP, SCTP_FRAGMENT_INTERLEAVE,
286 &interleaving, sizeof(interleaving)) == 0);
287 }
288 {
289 // Enable recvinfo when a packet arrives.
290 int on = 1;
291 PCHECK(setsockopt(fd_, IPPROTO_SCTP, SCTP_RECVRCVINFO, &on, sizeof(int)) ==
292 0);
293 }
294
Austin Schuha705d782021-07-31 20:40:00 -0700295 {
296 // TODO(austin): This is the old style registration... But, the sctp
297 // stack out in the wild for linux is old and primitive.
298 struct sctp_event_subscribe subscribe;
299 memset(&subscribe, 0, sizeof(subscribe));
300 subscribe.sctp_association_event = 1;
301 subscribe.sctp_stream_change_event = 1;
302 subscribe.sctp_partial_delivery_event = 1;
Adam Snaiderbe263512023-05-18 20:40:23 -0700303 PCHECK(setsockopt(fd(), IPPROTO_SCTP, SCTP_EVENTS, (char *)&subscribe,
Austin Schuha705d782021-07-31 20:40:00 -0700304 sizeof(subscribe)) == 0);
305 }
306
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700307#if HAS_SCTP_AUTH
Adam Snaider9bb33442023-06-26 16:31:37 -0700308 if (sctp_authentication_) {
309 CHECK(SctpAuthIsEnabled())
310 << "SCTP Authentication key requested, but authentication isn't "
311 "enabled... Use `sysctl -w net.sctp.auth_enable=1` to enable";
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700312
Adam Snaider9bb33442023-06-26 16:31:37 -0700313 // Unfortunately there's no way to delete the null key if we don't have
314 // another key active so this is the only way to prevent unauthenticated
315 // traffic until the real shared key is established.
316 SetAuthKey(GenerateSecureRandomSequence(16));
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700317
Adam Snaider9bb33442023-06-26 16:31:37 -0700318 // Disallow the null key.
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700319 struct sctp_authkeyid authkeyid;
Adam Snaider9bb33442023-06-26 16:31:37 -0700320 authkeyid.scact_keynumber = 0;
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700321 authkeyid.scact_assoc_id = SCTP_ALL_ASSOC;
Adam Snaider9bb33442023-06-26 16:31:37 -0700322 PCHECK(setsockopt(fd(), IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY, &authkeyid,
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700323 sizeof(authkeyid)) == 0);
324
325 // Set up authentication for data chunks.
326 struct sctp_authchunk authchunk;
327 authchunk.sauth_chunk = 0;
328
329 PCHECK(setsockopt(fd(), IPPROTO_SCTP, SCTP_AUTH_CHUNK, &authchunk,
330 sizeof(authchunk)) == 0);
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700331 }
Adam Snaider9bb33442023-06-26 16:31:37 -0700332#endif
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700333
Austin Schuh507f7582021-07-31 20:39:55 -0700334 DoSetMaxSize();
335}
336
337bool SctpReadWrite::SendMessage(
338 int stream, std::string_view data, int time_to_live,
339 std::optional<struct sockaddr_storage> sockaddr_remote,
340 sctp_assoc_t snd_assoc_id) {
341 CHECK(fd_ != -1);
Adam Snaider9bb33442023-06-26 16:31:37 -0700342 LOG_IF(FATAL, sctp_authentication_ && current_key_.empty())
343 << "Expected SCTP authentication but no key active";
Austin Schuh507f7582021-07-31 20:39:55 -0700344 struct iovec iov;
345 iov.iov_base = const_cast<char *>(data.data());
346 iov.iov_len = data.size();
347
348 // Use the assoc_id for the destination instead of the msg_name.
349 struct msghdr outmsg;
James Kuszmaul784deb72023-02-17 14:42:51 -0800350 memset(&outmsg, 0, sizeof(outmsg));
Austin Schuh507f7582021-07-31 20:39:55 -0700351 if (sockaddr_remote) {
352 outmsg.msg_name = &*sockaddr_remote;
353 outmsg.msg_namelen = sizeof(*sockaddr_remote);
Sarah Newman4aeb2372022-04-06 13:07:11 -0700354 VLOG(2) << "Sending to " << Address(*sockaddr_remote);
Austin Schuh507f7582021-07-31 20:39:55 -0700355 } else {
356 outmsg.msg_namelen = 0;
357 }
358
359 // Data to send.
360 outmsg.msg_iov = &iov;
361 outmsg.msg_iovlen = 1;
362
363 // Build up the sndinfo message.
364 char outcmsg[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
365 outmsg.msg_control = outcmsg;
366 outmsg.msg_controllen = sizeof(outcmsg);
367 outmsg.msg_flags = 0;
368
369 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&outmsg);
370 cmsg->cmsg_level = IPPROTO_SCTP;
371 cmsg->cmsg_type = SCTP_SNDRCV;
372 cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
373
374 struct sctp_sndrcvinfo *sinfo =
375 reinterpret_cast<struct sctp_sndrcvinfo *>(CMSG_DATA(cmsg));
376 memset(sinfo, 0, sizeof(struct sctp_sndrcvinfo));
377 sinfo->sinfo_ppid = ++send_ppid_;
378 sinfo->sinfo_stream = stream;
379 sinfo->sinfo_flags = 0;
380 sinfo->sinfo_assoc_id = snd_assoc_id;
381 sinfo->sinfo_timetolive = time_to_live;
382
383 // And send.
384 const ssize_t size = sendmsg(fd_, &outmsg, MSG_NOSIGNAL | MSG_DONTWAIT);
385 if (size == -1) {
386 if (errno == EPIPE || errno == EAGAIN || errno == ESHUTDOWN ||
387 errno == EINTR) {
Austin Schuh581fab92022-02-07 19:50:54 -0800388 if (VLOG_IS_ON(1)) {
389 PLOG(WARNING) << "sendmsg on sctp socket failed";
390 }
Austin Schuh507f7582021-07-31 20:39:55 -0700391 return false;
392 }
393 PLOG(FATAL) << "sendmsg on sctp socket failed";
394 return false;
395 }
396 CHECK_EQ(static_cast<ssize_t>(data.size()), size);
Sarah Newman4aeb2372022-04-06 13:07:11 -0700397 VLOG(2) << "Sent " << data.size();
Austin Schuh507f7582021-07-31 20:39:55 -0700398 return true;
399}
400
Austin Schuhf95a6ab2023-05-15 14:34:57 -0700401void SctpReadWrite::FreeMessage(aos::unique_c_ptr<Message> &&message) {
402 if (use_pool_) {
403 free_messages_.emplace_back(std::move(message));
404 }
405}
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800406
Austin Schuhf95a6ab2023-05-15 14:34:57 -0700407void SctpReadWrite::SetPoolSize(size_t pool_size) {
408 CHECK(!use_pool_);
409 free_messages_.reserve(pool_size);
410 for (size_t i = 0; i < pool_size; ++i) {
411 free_messages_.emplace_back(AcquireMessage());
412 }
413 use_pool_ = true;
414}
415
416aos::unique_c_ptr<Message> SctpReadWrite::AcquireMessage() {
417 if (!use_pool_) {
James Kuszmaul6e622382023-02-17 14:56:38 -0800418 constexpr size_t kMessageAlign = alignof(Message);
419 const size_t max_message_size =
Austin Schuh89e1e9c2023-05-15 14:38:44 -0700420 ((sizeof(Message) + max_read_size_ + 1 + (kMessageAlign - 1)) /
James Kuszmaul6e622382023-02-17 14:56:38 -0800421 kMessageAlign) *
422 kMessageAlign;
423 aos::unique_c_ptr<Message> result(reinterpret_cast<Message *>(
424 aligned_alloc(kMessageAlign, max_message_size)));
Austin Schuhf95a6ab2023-05-15 14:34:57 -0700425 return result;
426 } else {
427 CHECK_GT(free_messages_.size(), 0u);
428 aos::unique_c_ptr<Message> result = std::move(free_messages_.back());
429 free_messages_.pop_back();
430 return result;
431 }
432}
433
434// We read each fragment into a fresh Message, because most of them won't be
435// fragmented. If we do end up with a fragment, then we copy the data out of it.
436aos::unique_c_ptr<Message> SctpReadWrite::ReadMessage() {
437 CHECK(fd_ != -1);
Adam Snaider9bb33442023-06-26 16:31:37 -0700438 LOG_IF(FATAL, sctp_authentication_ && current_key_.empty())
439 << "Expected SCTP authentication but no key active";
Austin Schuhf95a6ab2023-05-15 14:34:57 -0700440
441 while (true) {
442 aos::unique_c_ptr<Message> result = AcquireMessage();
Austin Schuha705d782021-07-31 20:40:00 -0700443
Austin Schuh05c18122021-07-31 20:39:47 -0700444 struct msghdr inmessage;
Austin Schuhc4202572021-03-31 21:06:55 -0700445 memset(&inmessage, 0, sizeof(struct msghdr));
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800446
Austin Schuh05c18122021-07-31 20:39:47 -0700447 struct iovec iov;
Austin Schuh89e1e9c2023-05-15 14:38:44 -0700448 iov.iov_len = max_read_size_ + 1;
Austin Schuha705d782021-07-31 20:40:00 -0700449 iov.iov_base = result->mutable_data();
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800450
Austin Schuhc4202572021-03-31 21:06:55 -0700451 inmessage.msg_iov = &iov;
452 inmessage.msg_iovlen = 1;
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800453
Austin Schuh05c18122021-07-31 20:39:47 -0700454 char incmsg[CMSG_SPACE(sizeof(_sctp_cmsg_data_t))];
Austin Schuhc4202572021-03-31 21:06:55 -0700455 inmessage.msg_control = incmsg;
456 inmessage.msg_controllen = sizeof(incmsg);
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800457
Austin Schuhc4202572021-03-31 21:06:55 -0700458 inmessage.msg_namelen = sizeof(struct sockaddr_storage);
459 inmessage.msg_name = &result->sin;
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800460
Austin Schuha705d782021-07-31 20:40:00 -0700461 const ssize_t size = recvmsg(fd_, &inmessage, MSG_DONTWAIT);
462 if (size == -1) {
463 if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
464 // These are all non-fatal failures indicating we should retry later.
465 return nullptr;
Austin Schuhc4202572021-03-31 21:06:55 -0700466 }
Austin Schuha705d782021-07-31 20:40:00 -0700467 PLOG(FATAL) << "recvmsg on sctp socket " << fd_ << " failed";
Austin Schuhc4202572021-03-31 21:06:55 -0700468 }
469
Austin Schuha705d782021-07-31 20:40:00 -0700470 CHECK(!(inmessage.msg_flags & MSG_CTRUNC))
Austin Schuhc4202572021-03-31 21:06:55 -0700471 << ": Control message truncated.";
472
Austin Schuha705d782021-07-31 20:40:00 -0700473 if (MSG_NOTIFICATION & inmessage.msg_flags) {
474 result->message_type = Message::kNotification;
475 } else {
476 result->message_type = Message::kMessage;
477 }
478 result->partial_deliveries = 0;
Austin Schuhc4202572021-03-31 21:06:55 -0700479
Austin Schuha705d782021-07-31 20:40:00 -0700480 {
481 bool found_rcvinfo = false;
482 for (struct cmsghdr *scmsg = CMSG_FIRSTHDR(&inmessage); scmsg != NULL;
483 scmsg = CMSG_NXTHDR(&inmessage, scmsg)) {
484 switch (scmsg->cmsg_type) {
485 case SCTP_RCVINFO: {
486 CHECK(!found_rcvinfo);
487 found_rcvinfo = true;
488 result->header.rcvinfo =
489 *reinterpret_cast<struct sctp_rcvinfo *>(CMSG_DATA(scmsg));
490 } break;
491 default:
492 LOG(INFO) << "\tUnknown type: " << scmsg->cmsg_type;
493 break;
494 }
495 }
496 CHECK_EQ(found_rcvinfo, result->message_type == Message::kMessage)
497 << ": Failed to find a SCTP_RCVINFO cmsghdr. flags: "
498 << inmessage.msg_flags;
499 }
Austin Schuh89f23e32023-05-15 17:06:43 -0700500
501 // Client just sent too big a block of data. Eat it and signal up the
502 // chain.
503 result->size = size;
504 if (size > static_cast<ssize_t>(max_read_size_)) {
505 Abort(result->header.rcvinfo.rcv_assoc_id);
506 result->message_type = Message::kOverflow;
507
508 VLOG(1) << "Message overflowed buffer on stream "
509 << result->header.rcvinfo.rcv_sid << ", disconnecting."
510 << " Check for config mismatch or rogue device.";
511 return result;
512 }
513
Austin Schuha705d782021-07-31 20:40:00 -0700514 if (result->message_type == Message::kNotification) {
515 // Notifications are never fragmented, just return it now.
516 CHECK(inmessage.msg_flags & MSG_EOR)
517 << ": Notifications should never be big enough to fragment";
518 if (ProcessNotification(result.get())) {
519 // We handled this notification internally, so don't pass it on.
520 return nullptr;
521 }
522 return result;
523 }
524
525 auto partial_message_iterator =
526 std::find_if(partial_messages_.begin(), partial_messages_.end(),
527 [&result](const aos::unique_c_ptr<Message> &candidate) {
528 return result->header.rcvinfo.rcv_sid ==
529 candidate->header.rcvinfo.rcv_sid &&
530 result->header.rcvinfo.rcv_ssn ==
531 candidate->header.rcvinfo.rcv_ssn &&
532 result->header.rcvinfo.rcv_assoc_id ==
533 candidate->header.rcvinfo.rcv_assoc_id;
534 });
535 if (partial_message_iterator != partial_messages_.end()) {
536 const aos::unique_c_ptr<Message> &partial_message =
537 *partial_message_iterator;
538 // Verify it's really part of the same message.
539 CHECK_EQ(partial_message->message_type, result->message_type)
540 << ": for " << result->header.rcvinfo.rcv_sid << ","
541 << result->header.rcvinfo.rcv_ssn << ","
542 << result->header.rcvinfo.rcv_assoc_id;
543 CHECK_EQ(partial_message->header.rcvinfo.rcv_ppid,
544 result->header.rcvinfo.rcv_ppid)
545 << ": for " << result->header.rcvinfo.rcv_sid << ","
546 << result->header.rcvinfo.rcv_ssn << ","
547 << result->header.rcvinfo.rcv_assoc_id;
548
549 // Now copy the data over and update the size.
Austin Schuh89e1e9c2023-05-15 14:38:44 -0700550 CHECK_LE(partial_message->size + result->size, max_read_size_)
Austin Schuha705d782021-07-31 20:40:00 -0700551 << ": Assembled fragments overflowed buffer on stream "
552 << result->header.rcvinfo.rcv_sid << ".";
553 memcpy(partial_message->mutable_data() + partial_message->size,
554 result->data(), result->size);
555 ++partial_message->partial_deliveries;
Sarah Newman4aeb2372022-04-06 13:07:11 -0700556 VLOG(2) << "Merged fragment of " << result->size << " after "
Austin Schuha705d782021-07-31 20:40:00 -0700557 << partial_message->size << ", had "
558 << partial_message->partial_deliveries
559 << ", for: " << result->header.rcvinfo.rcv_sid << ","
560 << result->header.rcvinfo.rcv_ssn << ","
561 << result->header.rcvinfo.rcv_assoc_id;
562 partial_message->size += result->size;
563 result.reset();
564 }
565
566 if (inmessage.msg_flags & MSG_EOR) {
567 // This is the last fragment, so we have something to return.
568 if (partial_message_iterator != partial_messages_.end()) {
569 // It was already merged into the message in the list, so now we pull
570 // that out of the list and return it.
571 CHECK(!result);
572 result = std::move(*partial_message_iterator);
573 partial_messages_.erase(partial_message_iterator);
574 VLOG(1) << "Final count: " << (result->partial_deliveries + 1)
575 << ", size: " << result->size
576 << ", for: " << result->header.rcvinfo.rcv_sid << ","
577 << result->header.rcvinfo.rcv_ssn << ","
578 << result->header.rcvinfo.rcv_assoc_id;
579 }
580 CHECK(result);
581 return result;
582 }
583 if (partial_message_iterator == partial_messages_.end()) {
Sarah Newman4aeb2372022-04-06 13:07:11 -0700584 VLOG(2) << "Starting fragment for: " << result->header.rcvinfo.rcv_sid
Austin Schuha705d782021-07-31 20:40:00 -0700585 << "," << result->header.rcvinfo.rcv_ssn << ","
586 << result->header.rcvinfo.rcv_assoc_id;
587 // Need to record this as the first fragment.
588 partial_messages_.emplace_back(std::move(result));
589 }
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800590 }
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800591}
592
Sarah Newman80e955e2022-04-13 11:19:36 -0700593bool SctpReadWrite::Abort(sctp_assoc_t snd_assoc_id) {
594 if (fd_ == -1) {
595 return true;
596 }
597 VLOG(1) << "Sending abort to assoc " << snd_assoc_id;
598
599 // Use the assoc_id for the destination instead of the msg_name.
600 struct msghdr outmsg;
James Kuszmaul784deb72023-02-17 14:42:51 -0800601 memset(&outmsg, 0, sizeof(outmsg));
Sarah Newman80e955e2022-04-13 11:19:36 -0700602 outmsg.msg_namelen = 0;
603
604 outmsg.msg_iovlen = 0;
605
606 // Build up the sndinfo message.
607 char outcmsg[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
608 outmsg.msg_control = outcmsg;
609 outmsg.msg_controllen = CMSG_SPACE(sizeof(struct sctp_sndrcvinfo));
610 outmsg.msg_flags = 0;
611
612 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&outmsg);
613 cmsg->cmsg_level = IPPROTO_SCTP;
614 cmsg->cmsg_type = SCTP_SNDRCV;
615 cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
616
617 struct sctp_sndrcvinfo *sinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
618 memset(sinfo, 0, sizeof(struct sctp_sndrcvinfo));
619 sinfo->sinfo_stream = 0;
620 sinfo->sinfo_flags = SCTP_ABORT;
621 sinfo->sinfo_assoc_id = snd_assoc_id;
622
623 // And send.
624 const ssize_t size = sendmsg(fd_, &outmsg, MSG_NOSIGNAL | MSG_DONTWAIT);
625 if (size == -1) {
626 if (errno == EPIPE || errno == EAGAIN || errno == ESHUTDOWN) {
627 return false;
628 }
629 return false;
630 } else {
631 CHECK_EQ(0, size);
632 return true;
633 }
634}
635
Austin Schuh507f7582021-07-31 20:39:55 -0700636void SctpReadWrite::CloseSocket() {
637 if (fd_ == -1) {
638 return;
639 }
640 LOG(INFO) << "close(" << fd_ << ")";
641 PCHECK(close(fd_) == 0);
642 fd_ = -1;
643}
644
645void SctpReadWrite::DoSetMaxSize() {
Austin Schuh89e1e9c2023-05-15 14:38:44 -0700646 size_t max_size = max_write_size_;
Austin Schuh507f7582021-07-31 20:39:55 -0700647
Austin Schuh61224882021-10-11 18:21:11 -0700648 // This sets the max packet size that we can send.
Austin Schuh89e1e9c2023-05-15 14:38:44 -0700649 CHECK_GE(ReadWMemMax(), max_write_size_)
Austin Schuh507f7582021-07-31 20:39:55 -0700650 << "wmem_max is too low. To increase wmem_max temporarily, do sysctl "
651 "-w net.core.wmem_max="
652 << max_size;
Austin Schuh507f7582021-07-31 20:39:55 -0700653 PCHECK(setsockopt(fd(), SOL_SOCKET, SO_SNDBUF, &max_size, sizeof(max_size)) ==
654 0);
Austin Schuh61224882021-10-11 18:21:11 -0700655
656 // The SO_RCVBUF option (also controlled by net.core.rmem_default) needs to be
657 // decently large but the actual size can be measured by tuning. The defaults
658 // should be fine. If it isn't big enough, transmission will fail.
Austin Schuh9dd8f592021-12-25 14:32:43 -0800659 if (FLAGS_rmem > 0) {
660 size_t rmem = FLAGS_rmem;
661 PCHECK(setsockopt(fd(), SOL_SOCKET, SO_RCVBUF, &rmem, sizeof(rmem)) == 0);
662 }
Austin Schuh507f7582021-07-31 20:39:55 -0700663}
664
Austin Schuha705d782021-07-31 20:40:00 -0700665bool SctpReadWrite::ProcessNotification(const Message *message) {
666 const union sctp_notification *const snp =
667 reinterpret_cast<const union sctp_notification *>(message->data());
668 switch (snp->sn_header.sn_type) {
669 case SCTP_PARTIAL_DELIVERY_EVENT: {
670 const struct sctp_pdapi_event *const partial_delivery =
671 &snp->sn_pdapi_event;
672 CHECK_EQ(partial_delivery->pdapi_length, sizeof(*partial_delivery))
673 << ": Kernel's SCTP code is not a version we support";
674 switch (partial_delivery->pdapi_indication) {
675 case SCTP_PARTIAL_DELIVERY_ABORTED: {
676 const auto iterator = std::find_if(
677 partial_messages_.begin(), partial_messages_.end(),
678 [partial_delivery](const aos::unique_c_ptr<Message> &candidate) {
679 // TODO(Brian): Once we have new enough userpace headers, for
680 // kernels that support level-2 interleaving, we'll need to add
681 // this:
682 // candidate->header.rcvinfo.rcv_sid ==
683 // partial_delivery->pdapi_stream &&
684 // candidate->header.rcvinfo.rcv_ssn ==
685 // partial_delivery->pdapi_seq &&
686 return candidate->header.rcvinfo.rcv_assoc_id ==
687 partial_delivery->pdapi_assoc_id;
688 });
689 CHECK(iterator != partial_messages_.end())
690 << ": Got out of sync with the kernel for "
691 << partial_delivery->pdapi_assoc_id;
692 VLOG(1) << "Pruning partial delivery for "
693 << iterator->get()->header.rcvinfo.rcv_sid << ","
694 << iterator->get()->header.rcvinfo.rcv_ssn << ","
695 << iterator->get()->header.rcvinfo.rcv_assoc_id;
696 partial_messages_.erase(iterator);
697 }
698 return true;
699 }
700 } break;
701 }
702 return false;
703}
704
Adam Snaider9bb33442023-06-26 16:31:37 -0700705void SctpReadWrite::SetAuthKey(absl::Span<const uint8_t> auth_key) {
706 PCHECK(fd_ != -1);
707 if (auth_key.empty()) {
708 return;
709 }
710 // We are already using the key, nothing to do.
711 if (auth_key == current_key_) {
712 return;
713 }
714#if !(HAS_SCTP_AUTH)
715 LOG(FATAL) << "SCTP Authentication key requested, but authentication isn't "
716 "available... You may need a newer kernel";
717#else
718 LOG_IF(FATAL, !SctpAuthIsEnabled())
719 << "SCTP Authentication key requested, but authentication isn't "
720 "enabled... Use `sysctl -w net.sctp.auth_enable=1` to enable";
721 // Set up the key with id `1`.
Adam Snaider82d1dc72023-09-26 09:13:55 -0700722 // NOTE: `sctp_authkey` is a variable-sized struct which is why it needs
723 // to be heap allocated. Regardless, this object doesn't have to persist past
724 // the `setsockopt` call below.
725 std::unique_ptr<sctp_authkey> authkey(static_cast<sctp_authkey *>(
726 ::operator new(sizeof(sctp_authkey) + auth_key.size())));
Adam Snaider9bb33442023-06-26 16:31:37 -0700727
728 authkey->sca_keynumber = 1;
729 authkey->sca_keylength = auth_key.size();
730 authkey->sca_assoc_id = SCTP_ALL_ASSOC;
731 memcpy(&authkey->sca_key, auth_key.data(), auth_key.size());
732
733 if (setsockopt(fd(), IPPROTO_SCTP, SCTP_AUTH_KEY, authkey.get(),
734 sizeof(sctp_authkey) + auth_key.size()) != 0) {
735 if (errno == EACCES) {
736 // TODO(adam.snaider): Figure out why this fails when expected nodes are
737 // not connected.
738 PLOG_EVERY_N(ERROR, 100) << "Setting authentication key failed";
739 return;
740 } else {
741 PLOG(FATAL) << "Setting authentication key failed";
742 }
743 }
744
745 // Set key `1` as active.
746 struct sctp_authkeyid authkeyid;
747 authkeyid.scact_keynumber = 1;
748 authkeyid.scact_assoc_id = SCTP_ALL_ASSOC;
749 if (setsockopt(fd(), IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid,
750 sizeof(authkeyid)) != 0) {
751 PLOG(FATAL) << "Setting key id `1` as active failed";
752 }
753 current_key_.assign(auth_key.begin(), auth_key.end());
754#endif
755} // namespace message_bridge
756
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800757void Message::LogRcvInfo() const {
758 LOG(INFO) << "\tSNDRCV (stream=" << header.rcvinfo.rcv_sid
759 << " ssn=" << header.rcvinfo.rcv_ssn
760 << " tsn=" << header.rcvinfo.rcv_tsn << " flags=0x" << std::hex
761 << header.rcvinfo.rcv_flags << std::dec
762 << " ppid=" << header.rcvinfo.rcv_ppid
763 << " cumtsn=" << header.rcvinfo.rcv_cumtsn << ")";
764}
765
Austin Schuh2fe4b712020-03-15 14:21:45 -0700766size_t ReadRMemMax() {
767 struct stat current_stat;
768 if (stat("/proc/sys/net/core/rmem_max", &current_stat) != -1) {
769 return static_cast<size_t>(
770 std::stoi(util::ReadFileToStringOrDie("/proc/sys/net/core/rmem_max")));
771 } else {
772 LOG(WARNING) << "/proc/sys/net/core/rmem_max doesn't exist. Are you in a "
773 "container?";
774 return 212992;
775 }
776}
777
778size_t ReadWMemMax() {
779 struct stat current_stat;
780 if (stat("/proc/sys/net/core/wmem_max", &current_stat) != -1) {
781 return static_cast<size_t>(
782 std::stoi(util::ReadFileToStringOrDie("/proc/sys/net/core/wmem_max")));
783 } else {
784 LOG(WARNING) << "/proc/sys/net/core/wmem_max doesn't exist. Are you in a "
785 "container?";
786 return 212992;
787 }
788}
789
Stephan Pleinesf63bde82024-01-13 15:59:33 -0800790} // namespace aos::message_bridge