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