blob: c3c6e234dc1eb986268f11871cf12e676daa41f1 [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
Austin Schuh0a0a8272021-12-08 13:19:32 -080020DEFINE_string(interface, "", "network interface");
Brian Silverman0c6d44e2021-11-10 12:27:49 -080021DEFINE_bool(disable_ipv6, false, "disable ipv6");
Austin Schuh9dd8f592021-12-25 14:32:43 -080022DEFINE_int32(rmem, 0, "If nonzero, set rmem to this size.");
Austin Schuhe84c3ed2019-12-14 15:29:48 -080023
24namespace aos {
25namespace message_bridge {
26
27namespace {
28const char *sac_state_tbl[] = {"COMMUNICATION_UP", "COMMUNICATION_LOST",
29 "RESTART", "SHUTDOWN_COMPLETE",
Sarah Newman4aeb2372022-04-06 13:07:11 -070030 "CANT_START_ASSOCIATION"};
Austin Schuhe84c3ed2019-12-14 15:29:48 -080031
32typedef union {
33 struct sctp_initmsg init;
34 struct sctp_sndrcvinfo sndrcvinfo;
35} _sctp_cmsg_data_t;
36
Adam Snaider9bb33442023-06-26 16:31:37 -070037#if HAS_SCTP_AUTH
Adam Snaider96a0f4b2023-05-18 20:41:19 -070038// Returns true if SCTP authentication is available and enabled.
39bool SctpAuthIsEnabled() {
Adam Snaider96a0f4b2023-05-18 20:41:19 -070040 struct stat current_stat;
41 if (stat("/proc/sys/net/sctp/auth_enable", &current_stat) != -1) {
42 int value = std::stoi(
43 util::ReadFileToStringOrDie("/proc/sys/net/sctp/auth_enable"));
44 CHECK(value == 0 || value == 1)
45 << "Unknown auth enable sysctl value: " << value;
46 return value == 1;
47 } else {
48 LOG(WARNING) << "/proc/sys/net/sctp/auth_enable doesn't exist.";
49 return false;
50 }
Adam Snaider96a0f4b2023-05-18 20:41:19 -070051}
52
Adam Snaider9bb33442023-06-26 16:31:37 -070053std::vector<uint8_t> GenerateSecureRandomSequence(size_t count) {
54 std::ifstream rng("/dev/random", std::ios::in | std::ios::binary);
55 CHECK(rng) << "Unable to open /dev/random";
56 std::vector<uint8_t> out(count, 0);
57 rng.read(reinterpret_cast<char *>(out.data()), count);
58 CHECK(rng) << "Couldn't read from random device";
59 rng.close();
60 return out;
61}
62#endif
63
Austin Schuhe84c3ed2019-12-14 15:29:48 -080064} // namespace
65
Austin Schuh0a0a8272021-12-08 13:19:32 -080066bool Ipv6Enabled() {
67 if (FLAGS_disable_ipv6) {
68 return false;
69 }
70 int fd = socket(AF_INET6, SOCK_SEQPACKET, IPPROTO_SCTP);
71 if (fd != -1) {
72 close(fd);
73 return true;
74 }
75 switch (errno) {
76 case EAFNOSUPPORT:
77 case EINVAL:
78 case EPROTONOSUPPORT:
79 PLOG(INFO) << "no ipv6";
80 return false;
81 default:
82 PLOG(FATAL) << "Open socket failed";
83 return false;
84 };
85}
86
87struct sockaddr_storage ResolveSocket(std::string_view host, int port,
88 bool use_ipv6) {
Austin Schuhe84c3ed2019-12-14 15:29:48 -080089 struct sockaddr_storage result;
James Kuszmaul784deb72023-02-17 14:42:51 -080090 memset(&result, 0, sizeof(result));
Austin Schuhe84c3ed2019-12-14 15:29:48 -080091 struct addrinfo *addrinfo_result;
92 struct sockaddr_in *t_addr = (struct sockaddr_in *)&result;
93 struct sockaddr_in6 *t_addr6 = (struct sockaddr_in6 *)&result;
Brian Silverman0c6d44e2021-11-10 12:27:49 -080094 struct addrinfo hints;
95 memset(&hints, 0, sizeof(hints));
Austin Schuh0a0a8272021-12-08 13:19:32 -080096 if (!use_ipv6) {
Brian Silverman0c6d44e2021-11-10 12:27:49 -080097 hints.ai_family = AF_INET;
98 } else {
Austin Schuh0a0a8272021-12-08 13:19:32 -080099 // Default to IPv6 as the clearly superior protocol, since it also handles
100 // IPv4.
Brian Silverman0c6d44e2021-11-10 12:27:49 -0800101 hints.ai_family = AF_INET6;
102 }
103 hints.ai_socktype = SOCK_SEQPACKET;
104 hints.ai_protocol = IPPROTO_SCTP;
105 // We deliberately avoid AI_ADDRCONFIG here because it breaks running things
106 // inside Bazel's test sandbox, which has no non-localhost IPv4 or IPv6
107 // addresses. Also, it's not really helpful, because most systems will have
108 // link-local addresses of both types with any interface that's up.
109 hints.ai_flags = AI_PASSIVE | AI_V4MAPPED | AI_NUMERICSERV;
110 int ret = getaddrinfo(host.empty() ? nullptr : std::string(host).c_str(),
111 std::to_string(port).c_str(), &hints, &addrinfo_result);
Brian Silverman0c6d44e2021-11-10 12:27:49 -0800112 if (ret == EAI_SYSTEM) {
113 PLOG(FATAL) << "getaddrinfo failed to look up '" << host << "'";
114 } else if (ret != 0) {
115 LOG(FATAL) << "getaddrinfo failed to look up '" << host
116 << "': " << gai_strerror(ret);
117 }
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800118 switch (addrinfo_result->ai_family) {
119 case AF_INET:
120 memcpy(t_addr, addrinfo_result->ai_addr, addrinfo_result->ai_addrlen);
121 t_addr->sin_family = addrinfo_result->ai_family;
122 t_addr->sin_port = htons(port);
123
124 break;
125 case AF_INET6:
126 memcpy(t_addr6, addrinfo_result->ai_addr, addrinfo_result->ai_addrlen);
127 t_addr6->sin6_family = addrinfo_result->ai_family;
128 t_addr6->sin6_port = htons(port);
129
130 if (FLAGS_interface.size() > 0) {
131 t_addr6->sin6_scope_id = if_nametoindex(FLAGS_interface.c_str());
132 }
133
134 break;
135 }
136
137 // Now print it back out nicely.
138 char host_string[NI_MAXHOST];
139 char service_string[NI_MAXSERV];
140
141 int error = getnameinfo((struct sockaddr *)&result,
142 addrinfo_result->ai_addrlen, host_string, NI_MAXHOST,
143 service_string, NI_MAXSERV, NI_NUMERICHOST);
144
145 if (error) {
146 LOG(ERROR) << "Reverse lookup failed ... " << gai_strerror(error);
147 }
148
149 LOG(INFO) << "remote:addr=" << host_string << ", port=" << service_string
150 << ", family=" << addrinfo_result->ai_family;
151
152 freeaddrinfo(addrinfo_result);
153
154 return result;
155}
156
157std::string_view Family(const struct sockaddr_storage &sockaddr) {
158 if (sockaddr.ss_family == AF_INET) {
159 return "AF_INET";
160 } else if (sockaddr.ss_family == AF_INET6) {
161 return "AF_INET6";
162 } else {
163 return "unknown";
164 }
165}
166std::string Address(const struct sockaddr_storage &sockaddr) {
167 char addrbuf[INET6_ADDRSTRLEN];
168 if (sockaddr.ss_family == AF_INET) {
169 const struct sockaddr_in *sin = (const struct sockaddr_in *)&sockaddr;
170 return std::string(
171 inet_ntop(AF_INET, &sin->sin_addr, addrbuf, INET6_ADDRSTRLEN));
172 } else {
173 const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)&sockaddr;
174 return std::string(
175 inet_ntop(AF_INET6, &sin6->sin6_addr, addrbuf, INET6_ADDRSTRLEN));
176 }
177}
178
179void PrintNotification(const Message *msg) {
180 const union sctp_notification *snp =
181 (const union sctp_notification *)msg->data();
182
183 LOG(INFO) << "Notification:";
184
185 switch (snp->sn_header.sn_type) {
186 case SCTP_ASSOC_CHANGE: {
187 const struct sctp_assoc_change *sac = &snp->sn_assoc_change;
188 LOG(INFO) << "SCTP_ASSOC_CHANGE(" << sac_state_tbl[sac->sac_state] << ")";
189 VLOG(1) << " (assoc_change: state=" << sac->sac_state
190 << ", error=" << sac->sac_error
191 << ", instr=" << sac->sac_inbound_streams
192 << " outstr=" << sac->sac_outbound_streams
193 << ", assoc=" << sac->sac_assoc_id << ")";
194 } break;
195 case SCTP_PEER_ADDR_CHANGE: {
196 const struct sctp_paddr_change *spc = &snp->sn_paddr_change;
197 LOG(INFO) << " SlCTP_PEER_ADDR_CHANGE";
198 VLOG(1) << "\t\t(peer_addr_change: " << Address(spc->spc_aaddr)
199 << " state=" << spc->spc_state << ", error=" << spc->spc_error
200 << ")";
201 } break;
202 case SCTP_SEND_FAILED: {
203 const struct sctp_send_failed *ssf = &snp->sn_send_failed;
204 LOG(INFO) << " SCTP_SEND_FAILED";
205 VLOG(1) << "\t\t(sendfailed: len=" << ssf->ssf_length
206 << " err=" << ssf->ssf_error << ")";
207 } break;
208 case SCTP_REMOTE_ERROR: {
209 const struct sctp_remote_error *sre = &snp->sn_remote_error;
210 LOG(INFO) << " SCTP_REMOTE_ERROR";
211 VLOG(1) << "\t\t(remote_error: err=" << ntohs(sre->sre_error) << ")";
212 } break;
Austin Schuhf7777002020-09-01 18:41:28 -0700213 case SCTP_STREAM_CHANGE_EVENT: {
Austin Schuh62a0c272021-03-31 21:04:53 -0700214 const struct sctp_stream_change_event *sce = &snp->sn_strchange_event;
Austin Schuhf7777002020-09-01 18:41:28 -0700215 LOG(INFO) << " SCTP_STREAM_CHANGE_EVENT";
216 VLOG(1) << "\t\t(stream_change_event: flags=" << sce->strchange_flags
217 << ", assoc_id=" << sce->strchange_assoc_id
218 << ", instrms=" << sce->strchange_instrms
219 << ", outstrms=" << sce->strchange_outstrms << " )";
220 } break;
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800221 case SCTP_SHUTDOWN_EVENT: {
222 LOG(INFO) << " SCTP_SHUTDOWN_EVENT";
223 } break;
224 default:
225 LOG(INFO) << " Unknown type: " << snp->sn_header.sn_type;
226 break;
227 }
228}
229
230std::string GetHostname() {
231 char buf[256];
232 buf[sizeof(buf) - 1] = '\0';
233 PCHECK(gethostname(buf, sizeof(buf) - 1) == 0);
234 return buf;
235}
236
237std::string Message::PeerAddress() const { return Address(sin); }
238
239void LogSctpStatus(int fd, sctp_assoc_t assoc_id) {
240 struct sctp_status status;
241 memset(&status, 0, sizeof(status));
242 status.sstat_assoc_id = assoc_id;
243
244 socklen_t size = sizeof(status);
Adam Snaiderbe263512023-05-18 20:40:23 -0700245 const int result = getsockopt(fd, IPPROTO_SCTP, SCTP_STATUS,
Austin Schuha5f545b2021-07-31 20:39:42 -0700246 reinterpret_cast<void *>(&status), &size);
247 if (result == -1 && errno == EINVAL) {
248 LOG(INFO) << "sctp_status) not associated";
249 return;
250 }
251 PCHECK(result == 0);
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800252
253 LOG(INFO) << "sctp_status) sstat_assoc_id:" << status.sstat_assoc_id
254 << " sstat_state:" << status.sstat_state
255 << " sstat_rwnd:" << status.sstat_rwnd
256 << " sstat_unackdata:" << status.sstat_unackdata
257 << " sstat_penddata:" << status.sstat_penddata
258 << " sstat_instrms:" << status.sstat_instrms
259 << " sstat_outstrms:" << status.sstat_outstrms
260 << " sstat_fragmentation_point:" << status.sstat_fragmentation_point
261 << " sstat_primary.spinfo_srtt:" << status.sstat_primary.spinfo_srtt
262 << " sstat_primary.spinfo_rto:" << status.sstat_primary.spinfo_rto;
263}
264
Austin Schuh507f7582021-07-31 20:39:55 -0700265void SctpReadWrite::OpenSocket(const struct sockaddr_storage &sockaddr_local) {
266 fd_ = socket(sockaddr_local.ss_family, SOCK_SEQPACKET, IPPROTO_SCTP);
267 PCHECK(fd_ != -1);
268 LOG(INFO) << "socket(" << Family(sockaddr_local)
269 << ", SOCK_SEQPACKET, IPPROTOSCTP) = " << fd_;
270 {
271 // Per https://tools.ietf.org/html/rfc6458
272 // Setting this to !0 allows event notifications to be interleaved
Austin Schuha705d782021-07-31 20:40:00 -0700273 // with data if enabled. This typically only matters during congestion.
274 // However, Linux seems to interleave under memory pressure regardless of
275 // this being enabled, so we have to handle it in the code anyways, so might
276 // as well turn it on all the time.
277 // TODO(Brian): Change this to 2 once we have kernels that support it, and
278 // also address the TODO in ProcessNotification to match on all the
279 // necessary fields.
280 int interleaving = 1;
Austin Schuh507f7582021-07-31 20:39:55 -0700281 PCHECK(setsockopt(fd_, IPPROTO_SCTP, SCTP_FRAGMENT_INTERLEAVE,
282 &interleaving, sizeof(interleaving)) == 0);
283 }
284 {
285 // Enable recvinfo when a packet arrives.
286 int on = 1;
287 PCHECK(setsockopt(fd_, IPPROTO_SCTP, SCTP_RECVRCVINFO, &on, sizeof(int)) ==
288 0);
289 }
290
Austin Schuha705d782021-07-31 20:40:00 -0700291 {
292 // TODO(austin): This is the old style registration... But, the sctp
293 // stack out in the wild for linux is old and primitive.
294 struct sctp_event_subscribe subscribe;
295 memset(&subscribe, 0, sizeof(subscribe));
296 subscribe.sctp_association_event = 1;
297 subscribe.sctp_stream_change_event = 1;
298 subscribe.sctp_partial_delivery_event = 1;
Adam Snaiderbe263512023-05-18 20:40:23 -0700299 PCHECK(setsockopt(fd(), IPPROTO_SCTP, SCTP_EVENTS, (char *)&subscribe,
Austin Schuha705d782021-07-31 20:40:00 -0700300 sizeof(subscribe)) == 0);
301 }
302
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700303#if HAS_SCTP_AUTH
Adam Snaider9bb33442023-06-26 16:31:37 -0700304 if (sctp_authentication_) {
305 CHECK(SctpAuthIsEnabled())
306 << "SCTP Authentication key requested, but authentication isn't "
307 "enabled... Use `sysctl -w net.sctp.auth_enable=1` to enable";
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700308
Adam Snaider9bb33442023-06-26 16:31:37 -0700309 // Unfortunately there's no way to delete the null key if we don't have
310 // another key active so this is the only way to prevent unauthenticated
311 // traffic until the real shared key is established.
312 SetAuthKey(GenerateSecureRandomSequence(16));
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700313
Adam Snaider9bb33442023-06-26 16:31:37 -0700314 // Disallow the null key.
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700315 struct sctp_authkeyid authkeyid;
Adam Snaider9bb33442023-06-26 16:31:37 -0700316 authkeyid.scact_keynumber = 0;
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700317 authkeyid.scact_assoc_id = SCTP_ALL_ASSOC;
Adam Snaider9bb33442023-06-26 16:31:37 -0700318 PCHECK(setsockopt(fd(), IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY, &authkeyid,
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700319 sizeof(authkeyid)) == 0);
320
321 // Set up authentication for data chunks.
322 struct sctp_authchunk authchunk;
323 authchunk.sauth_chunk = 0;
324
325 PCHECK(setsockopt(fd(), IPPROTO_SCTP, SCTP_AUTH_CHUNK, &authchunk,
326 sizeof(authchunk)) == 0);
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700327 }
Adam Snaider9bb33442023-06-26 16:31:37 -0700328#endif
Adam Snaider96a0f4b2023-05-18 20:41:19 -0700329
Austin Schuh507f7582021-07-31 20:39:55 -0700330 DoSetMaxSize();
331}
332
333bool SctpReadWrite::SendMessage(
334 int stream, std::string_view data, int time_to_live,
335 std::optional<struct sockaddr_storage> sockaddr_remote,
336 sctp_assoc_t snd_assoc_id) {
337 CHECK(fd_ != -1);
Adam Snaider9bb33442023-06-26 16:31:37 -0700338 LOG_IF(FATAL, sctp_authentication_ && current_key_.empty())
339 << "Expected SCTP authentication but no key active";
Austin Schuh507f7582021-07-31 20:39:55 -0700340 struct iovec iov;
341 iov.iov_base = const_cast<char *>(data.data());
342 iov.iov_len = data.size();
343
344 // Use the assoc_id for the destination instead of the msg_name.
345 struct msghdr outmsg;
James Kuszmaul784deb72023-02-17 14:42:51 -0800346 memset(&outmsg, 0, sizeof(outmsg));
Austin Schuh507f7582021-07-31 20:39:55 -0700347 if (sockaddr_remote) {
348 outmsg.msg_name = &*sockaddr_remote;
349 outmsg.msg_namelen = sizeof(*sockaddr_remote);
Sarah Newman4aeb2372022-04-06 13:07:11 -0700350 VLOG(2) << "Sending to " << Address(*sockaddr_remote);
Austin Schuh507f7582021-07-31 20:39:55 -0700351 } else {
352 outmsg.msg_namelen = 0;
353 }
354
355 // Data to send.
356 outmsg.msg_iov = &iov;
357 outmsg.msg_iovlen = 1;
358
359 // Build up the sndinfo message.
360 char outcmsg[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
361 outmsg.msg_control = outcmsg;
362 outmsg.msg_controllen = sizeof(outcmsg);
363 outmsg.msg_flags = 0;
364
365 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&outmsg);
366 cmsg->cmsg_level = IPPROTO_SCTP;
367 cmsg->cmsg_type = SCTP_SNDRCV;
368 cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
369
370 struct sctp_sndrcvinfo *sinfo =
371 reinterpret_cast<struct sctp_sndrcvinfo *>(CMSG_DATA(cmsg));
372 memset(sinfo, 0, sizeof(struct sctp_sndrcvinfo));
373 sinfo->sinfo_ppid = ++send_ppid_;
374 sinfo->sinfo_stream = stream;
375 sinfo->sinfo_flags = 0;
376 sinfo->sinfo_assoc_id = snd_assoc_id;
377 sinfo->sinfo_timetolive = time_to_live;
378
379 // And send.
380 const ssize_t size = sendmsg(fd_, &outmsg, MSG_NOSIGNAL | MSG_DONTWAIT);
381 if (size == -1) {
382 if (errno == EPIPE || errno == EAGAIN || errno == ESHUTDOWN ||
383 errno == EINTR) {
Austin Schuh581fab92022-02-07 19:50:54 -0800384 if (VLOG_IS_ON(1)) {
385 PLOG(WARNING) << "sendmsg on sctp socket failed";
386 }
Austin Schuh507f7582021-07-31 20:39:55 -0700387 return false;
388 }
389 PLOG(FATAL) << "sendmsg on sctp socket failed";
390 return false;
391 }
392 CHECK_EQ(static_cast<ssize_t>(data.size()), size);
Sarah Newman4aeb2372022-04-06 13:07:11 -0700393 VLOG(2) << "Sent " << data.size();
Austin Schuh507f7582021-07-31 20:39:55 -0700394 return true;
395}
396
Austin Schuhf95a6ab2023-05-15 14:34:57 -0700397void SctpReadWrite::FreeMessage(aos::unique_c_ptr<Message> &&message) {
398 if (use_pool_) {
399 free_messages_.emplace_back(std::move(message));
400 }
401}
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800402
Austin Schuhf95a6ab2023-05-15 14:34:57 -0700403void SctpReadWrite::SetPoolSize(size_t pool_size) {
404 CHECK(!use_pool_);
405 free_messages_.reserve(pool_size);
406 for (size_t i = 0; i < pool_size; ++i) {
407 free_messages_.emplace_back(AcquireMessage());
408 }
409 use_pool_ = true;
410}
411
412aos::unique_c_ptr<Message> SctpReadWrite::AcquireMessage() {
413 if (!use_pool_) {
James Kuszmaul6e622382023-02-17 14:56:38 -0800414 constexpr size_t kMessageAlign = alignof(Message);
415 const size_t max_message_size =
Austin Schuh89e1e9c2023-05-15 14:38:44 -0700416 ((sizeof(Message) + max_read_size_ + 1 + (kMessageAlign - 1)) /
James Kuszmaul6e622382023-02-17 14:56:38 -0800417 kMessageAlign) *
418 kMessageAlign;
419 aos::unique_c_ptr<Message> result(reinterpret_cast<Message *>(
420 aligned_alloc(kMessageAlign, max_message_size)));
Austin Schuhf95a6ab2023-05-15 14:34:57 -0700421 return result;
422 } else {
423 CHECK_GT(free_messages_.size(), 0u);
424 aos::unique_c_ptr<Message> result = std::move(free_messages_.back());
425 free_messages_.pop_back();
426 return result;
427 }
428}
429
430// We read each fragment into a fresh Message, because most of them won't be
431// fragmented. If we do end up with a fragment, then we copy the data out of it.
432aos::unique_c_ptr<Message> SctpReadWrite::ReadMessage() {
433 CHECK(fd_ != -1);
Adam Snaider9bb33442023-06-26 16:31:37 -0700434 LOG_IF(FATAL, sctp_authentication_ && current_key_.empty())
435 << "Expected SCTP authentication but no key active";
Austin Schuhf95a6ab2023-05-15 14:34:57 -0700436
437 while (true) {
438 aos::unique_c_ptr<Message> result = AcquireMessage();
Austin Schuha705d782021-07-31 20:40:00 -0700439
Austin Schuh05c18122021-07-31 20:39:47 -0700440 struct msghdr inmessage;
Austin Schuhc4202572021-03-31 21:06:55 -0700441 memset(&inmessage, 0, sizeof(struct msghdr));
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800442
Austin Schuh05c18122021-07-31 20:39:47 -0700443 struct iovec iov;
Austin Schuh89e1e9c2023-05-15 14:38:44 -0700444 iov.iov_len = max_read_size_ + 1;
Austin Schuha705d782021-07-31 20:40:00 -0700445 iov.iov_base = result->mutable_data();
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800446
Austin Schuhc4202572021-03-31 21:06:55 -0700447 inmessage.msg_iov = &iov;
448 inmessage.msg_iovlen = 1;
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800449
Austin Schuh05c18122021-07-31 20:39:47 -0700450 char incmsg[CMSG_SPACE(sizeof(_sctp_cmsg_data_t))];
Austin Schuhc4202572021-03-31 21:06:55 -0700451 inmessage.msg_control = incmsg;
452 inmessage.msg_controllen = sizeof(incmsg);
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800453
Austin Schuhc4202572021-03-31 21:06:55 -0700454 inmessage.msg_namelen = sizeof(struct sockaddr_storage);
455 inmessage.msg_name = &result->sin;
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800456
Austin Schuha705d782021-07-31 20:40:00 -0700457 const ssize_t size = recvmsg(fd_, &inmessage, MSG_DONTWAIT);
458 if (size == -1) {
459 if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
460 // These are all non-fatal failures indicating we should retry later.
461 return nullptr;
Austin Schuhc4202572021-03-31 21:06:55 -0700462 }
Austin Schuha705d782021-07-31 20:40:00 -0700463 PLOG(FATAL) << "recvmsg on sctp socket " << fd_ << " failed";
Austin Schuhc4202572021-03-31 21:06:55 -0700464 }
465
Austin Schuha705d782021-07-31 20:40:00 -0700466 CHECK(!(inmessage.msg_flags & MSG_CTRUNC))
Austin Schuhc4202572021-03-31 21:06:55 -0700467 << ": Control message truncated.";
468
Austin Schuha705d782021-07-31 20:40:00 -0700469 if (MSG_NOTIFICATION & inmessage.msg_flags) {
470 result->message_type = Message::kNotification;
471 } else {
472 result->message_type = Message::kMessage;
473 }
474 result->partial_deliveries = 0;
Austin Schuhc4202572021-03-31 21:06:55 -0700475
Austin Schuha705d782021-07-31 20:40:00 -0700476 {
477 bool found_rcvinfo = false;
478 for (struct cmsghdr *scmsg = CMSG_FIRSTHDR(&inmessage); scmsg != NULL;
479 scmsg = CMSG_NXTHDR(&inmessage, scmsg)) {
480 switch (scmsg->cmsg_type) {
481 case SCTP_RCVINFO: {
482 CHECK(!found_rcvinfo);
483 found_rcvinfo = true;
484 result->header.rcvinfo =
485 *reinterpret_cast<struct sctp_rcvinfo *>(CMSG_DATA(scmsg));
486 } break;
487 default:
488 LOG(INFO) << "\tUnknown type: " << scmsg->cmsg_type;
489 break;
490 }
491 }
492 CHECK_EQ(found_rcvinfo, result->message_type == Message::kMessage)
493 << ": Failed to find a SCTP_RCVINFO cmsghdr. flags: "
494 << inmessage.msg_flags;
495 }
Austin Schuh89f23e32023-05-15 17:06:43 -0700496
497 // Client just sent too big a block of data. Eat it and signal up the
498 // chain.
499 result->size = size;
500 if (size > static_cast<ssize_t>(max_read_size_)) {
501 Abort(result->header.rcvinfo.rcv_assoc_id);
502 result->message_type = Message::kOverflow;
503
504 VLOG(1) << "Message overflowed buffer on stream "
505 << result->header.rcvinfo.rcv_sid << ", disconnecting."
506 << " Check for config mismatch or rogue device.";
507 return result;
508 }
509
Austin Schuha705d782021-07-31 20:40:00 -0700510 if (result->message_type == Message::kNotification) {
511 // Notifications are never fragmented, just return it now.
512 CHECK(inmessage.msg_flags & MSG_EOR)
513 << ": Notifications should never be big enough to fragment";
514 if (ProcessNotification(result.get())) {
515 // We handled this notification internally, so don't pass it on.
516 return nullptr;
517 }
518 return result;
519 }
520
521 auto partial_message_iterator =
522 std::find_if(partial_messages_.begin(), partial_messages_.end(),
523 [&result](const aos::unique_c_ptr<Message> &candidate) {
524 return result->header.rcvinfo.rcv_sid ==
525 candidate->header.rcvinfo.rcv_sid &&
526 result->header.rcvinfo.rcv_ssn ==
527 candidate->header.rcvinfo.rcv_ssn &&
528 result->header.rcvinfo.rcv_assoc_id ==
529 candidate->header.rcvinfo.rcv_assoc_id;
530 });
531 if (partial_message_iterator != partial_messages_.end()) {
532 const aos::unique_c_ptr<Message> &partial_message =
533 *partial_message_iterator;
534 // Verify it's really part of the same message.
535 CHECK_EQ(partial_message->message_type, result->message_type)
536 << ": for " << result->header.rcvinfo.rcv_sid << ","
537 << result->header.rcvinfo.rcv_ssn << ","
538 << result->header.rcvinfo.rcv_assoc_id;
539 CHECK_EQ(partial_message->header.rcvinfo.rcv_ppid,
540 result->header.rcvinfo.rcv_ppid)
541 << ": for " << result->header.rcvinfo.rcv_sid << ","
542 << result->header.rcvinfo.rcv_ssn << ","
543 << result->header.rcvinfo.rcv_assoc_id;
544
545 // Now copy the data over and update the size.
Austin Schuh89e1e9c2023-05-15 14:38:44 -0700546 CHECK_LE(partial_message->size + result->size, max_read_size_)
Austin Schuha705d782021-07-31 20:40:00 -0700547 << ": Assembled fragments overflowed buffer on stream "
548 << result->header.rcvinfo.rcv_sid << ".";
549 memcpy(partial_message->mutable_data() + partial_message->size,
550 result->data(), result->size);
551 ++partial_message->partial_deliveries;
Sarah Newman4aeb2372022-04-06 13:07:11 -0700552 VLOG(2) << "Merged fragment of " << result->size << " after "
Austin Schuha705d782021-07-31 20:40:00 -0700553 << partial_message->size << ", had "
554 << partial_message->partial_deliveries
555 << ", for: " << result->header.rcvinfo.rcv_sid << ","
556 << result->header.rcvinfo.rcv_ssn << ","
557 << result->header.rcvinfo.rcv_assoc_id;
558 partial_message->size += result->size;
559 result.reset();
560 }
561
562 if (inmessage.msg_flags & MSG_EOR) {
563 // This is the last fragment, so we have something to return.
564 if (partial_message_iterator != partial_messages_.end()) {
565 // It was already merged into the message in the list, so now we pull
566 // that out of the list and return it.
567 CHECK(!result);
568 result = std::move(*partial_message_iterator);
569 partial_messages_.erase(partial_message_iterator);
570 VLOG(1) << "Final count: " << (result->partial_deliveries + 1)
571 << ", size: " << result->size
572 << ", for: " << result->header.rcvinfo.rcv_sid << ","
573 << result->header.rcvinfo.rcv_ssn << ","
574 << result->header.rcvinfo.rcv_assoc_id;
575 }
576 CHECK(result);
577 return result;
578 }
579 if (partial_message_iterator == partial_messages_.end()) {
Sarah Newman4aeb2372022-04-06 13:07:11 -0700580 VLOG(2) << "Starting fragment for: " << result->header.rcvinfo.rcv_sid
Austin Schuha705d782021-07-31 20:40:00 -0700581 << "," << result->header.rcvinfo.rcv_ssn << ","
582 << result->header.rcvinfo.rcv_assoc_id;
583 // Need to record this as the first fragment.
584 partial_messages_.emplace_back(std::move(result));
585 }
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800586 }
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800587}
588
Sarah Newman80e955e2022-04-13 11:19:36 -0700589bool SctpReadWrite::Abort(sctp_assoc_t snd_assoc_id) {
590 if (fd_ == -1) {
591 return true;
592 }
593 VLOG(1) << "Sending abort to assoc " << snd_assoc_id;
594
595 // Use the assoc_id for the destination instead of the msg_name.
596 struct msghdr outmsg;
James Kuszmaul784deb72023-02-17 14:42:51 -0800597 memset(&outmsg, 0, sizeof(outmsg));
Sarah Newman80e955e2022-04-13 11:19:36 -0700598 outmsg.msg_namelen = 0;
599
600 outmsg.msg_iovlen = 0;
601
602 // Build up the sndinfo message.
603 char outcmsg[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
604 outmsg.msg_control = outcmsg;
605 outmsg.msg_controllen = CMSG_SPACE(sizeof(struct sctp_sndrcvinfo));
606 outmsg.msg_flags = 0;
607
608 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&outmsg);
609 cmsg->cmsg_level = IPPROTO_SCTP;
610 cmsg->cmsg_type = SCTP_SNDRCV;
611 cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
612
613 struct sctp_sndrcvinfo *sinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
614 memset(sinfo, 0, sizeof(struct sctp_sndrcvinfo));
615 sinfo->sinfo_stream = 0;
616 sinfo->sinfo_flags = SCTP_ABORT;
617 sinfo->sinfo_assoc_id = snd_assoc_id;
618
619 // And send.
620 const ssize_t size = sendmsg(fd_, &outmsg, MSG_NOSIGNAL | MSG_DONTWAIT);
621 if (size == -1) {
622 if (errno == EPIPE || errno == EAGAIN || errno == ESHUTDOWN) {
623 return false;
624 }
625 return false;
626 } else {
627 CHECK_EQ(0, size);
628 return true;
629 }
630}
631
Austin Schuh507f7582021-07-31 20:39:55 -0700632void SctpReadWrite::CloseSocket() {
633 if (fd_ == -1) {
634 return;
635 }
636 LOG(INFO) << "close(" << fd_ << ")";
637 PCHECK(close(fd_) == 0);
638 fd_ = -1;
639}
640
641void SctpReadWrite::DoSetMaxSize() {
Austin Schuh89e1e9c2023-05-15 14:38:44 -0700642 size_t max_size = max_write_size_;
Austin Schuh507f7582021-07-31 20:39:55 -0700643
Austin Schuh61224882021-10-11 18:21:11 -0700644 // This sets the max packet size that we can send.
Austin Schuh89e1e9c2023-05-15 14:38:44 -0700645 CHECK_GE(ReadWMemMax(), max_write_size_)
Austin Schuh507f7582021-07-31 20:39:55 -0700646 << "wmem_max is too low. To increase wmem_max temporarily, do sysctl "
647 "-w net.core.wmem_max="
648 << max_size;
Austin Schuh507f7582021-07-31 20:39:55 -0700649 PCHECK(setsockopt(fd(), SOL_SOCKET, SO_SNDBUF, &max_size, sizeof(max_size)) ==
650 0);
Austin Schuh61224882021-10-11 18:21:11 -0700651
652 // The SO_RCVBUF option (also controlled by net.core.rmem_default) needs to be
653 // decently large but the actual size can be measured by tuning. The defaults
654 // should be fine. If it isn't big enough, transmission will fail.
Austin Schuh9dd8f592021-12-25 14:32:43 -0800655 if (FLAGS_rmem > 0) {
656 size_t rmem = FLAGS_rmem;
657 PCHECK(setsockopt(fd(), SOL_SOCKET, SO_RCVBUF, &rmem, sizeof(rmem)) == 0);
658 }
Austin Schuh507f7582021-07-31 20:39:55 -0700659}
660
Austin Schuha705d782021-07-31 20:40:00 -0700661bool SctpReadWrite::ProcessNotification(const Message *message) {
662 const union sctp_notification *const snp =
663 reinterpret_cast<const union sctp_notification *>(message->data());
664 switch (snp->sn_header.sn_type) {
665 case SCTP_PARTIAL_DELIVERY_EVENT: {
666 const struct sctp_pdapi_event *const partial_delivery =
667 &snp->sn_pdapi_event;
668 CHECK_EQ(partial_delivery->pdapi_length, sizeof(*partial_delivery))
669 << ": Kernel's SCTP code is not a version we support";
670 switch (partial_delivery->pdapi_indication) {
671 case SCTP_PARTIAL_DELIVERY_ABORTED: {
672 const auto iterator = std::find_if(
673 partial_messages_.begin(), partial_messages_.end(),
674 [partial_delivery](const aos::unique_c_ptr<Message> &candidate) {
675 // TODO(Brian): Once we have new enough userpace headers, for
676 // kernels that support level-2 interleaving, we'll need to add
677 // this:
678 // candidate->header.rcvinfo.rcv_sid ==
679 // partial_delivery->pdapi_stream &&
680 // candidate->header.rcvinfo.rcv_ssn ==
681 // partial_delivery->pdapi_seq &&
682 return candidate->header.rcvinfo.rcv_assoc_id ==
683 partial_delivery->pdapi_assoc_id;
684 });
685 CHECK(iterator != partial_messages_.end())
686 << ": Got out of sync with the kernel for "
687 << partial_delivery->pdapi_assoc_id;
688 VLOG(1) << "Pruning partial delivery for "
689 << iterator->get()->header.rcvinfo.rcv_sid << ","
690 << iterator->get()->header.rcvinfo.rcv_ssn << ","
691 << iterator->get()->header.rcvinfo.rcv_assoc_id;
692 partial_messages_.erase(iterator);
693 }
694 return true;
695 }
696 } break;
697 }
698 return false;
699}
700
Adam Snaider9bb33442023-06-26 16:31:37 -0700701void SctpReadWrite::SetAuthKey(absl::Span<const uint8_t> auth_key) {
702 PCHECK(fd_ != -1);
703 if (auth_key.empty()) {
704 return;
705 }
706 // We are already using the key, nothing to do.
707 if (auth_key == current_key_) {
708 return;
709 }
710#if !(HAS_SCTP_AUTH)
711 LOG(FATAL) << "SCTP Authentication key requested, but authentication isn't "
712 "available... You may need a newer kernel";
713#else
714 LOG_IF(FATAL, !SctpAuthIsEnabled())
715 << "SCTP Authentication key requested, but authentication isn't "
716 "enabled... Use `sysctl -w net.sctp.auth_enable=1` to enable";
717 // Set up the key with id `1`.
718 std::unique_ptr<sctp_authkey> authkey(
719 (sctp_authkey *)malloc(sizeof(sctp_authkey) + auth_key.size()));
720
721 authkey->sca_keynumber = 1;
722 authkey->sca_keylength = auth_key.size();
723 authkey->sca_assoc_id = SCTP_ALL_ASSOC;
724 memcpy(&authkey->sca_key, auth_key.data(), auth_key.size());
725
726 if (setsockopt(fd(), IPPROTO_SCTP, SCTP_AUTH_KEY, authkey.get(),
727 sizeof(sctp_authkey) + auth_key.size()) != 0) {
728 if (errno == EACCES) {
729 // TODO(adam.snaider): Figure out why this fails when expected nodes are
730 // not connected.
731 PLOG_EVERY_N(ERROR, 100) << "Setting authentication key failed";
732 return;
733 } else {
734 PLOG(FATAL) << "Setting authentication key failed";
735 }
736 }
737
738 // Set key `1` as active.
739 struct sctp_authkeyid authkeyid;
740 authkeyid.scact_keynumber = 1;
741 authkeyid.scact_assoc_id = SCTP_ALL_ASSOC;
742 if (setsockopt(fd(), IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid,
743 sizeof(authkeyid)) != 0) {
744 PLOG(FATAL) << "Setting key id `1` as active failed";
745 }
746 current_key_.assign(auth_key.begin(), auth_key.end());
747#endif
748} // namespace message_bridge
749
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800750void Message::LogRcvInfo() const {
751 LOG(INFO) << "\tSNDRCV (stream=" << header.rcvinfo.rcv_sid
752 << " ssn=" << header.rcvinfo.rcv_ssn
753 << " tsn=" << header.rcvinfo.rcv_tsn << " flags=0x" << std::hex
754 << header.rcvinfo.rcv_flags << std::dec
755 << " ppid=" << header.rcvinfo.rcv_ppid
756 << " cumtsn=" << header.rcvinfo.rcv_cumtsn << ")";
757}
758
Austin Schuh2fe4b712020-03-15 14:21:45 -0700759size_t ReadRMemMax() {
760 struct stat current_stat;
761 if (stat("/proc/sys/net/core/rmem_max", &current_stat) != -1) {
762 return static_cast<size_t>(
763 std::stoi(util::ReadFileToStringOrDie("/proc/sys/net/core/rmem_max")));
764 } else {
765 LOG(WARNING) << "/proc/sys/net/core/rmem_max doesn't exist. Are you in a "
766 "container?";
767 return 212992;
768 }
769}
770
771size_t ReadWMemMax() {
772 struct stat current_stat;
773 if (stat("/proc/sys/net/core/wmem_max", &current_stat) != -1) {
774 return static_cast<size_t>(
775 std::stoi(util::ReadFileToStringOrDie("/proc/sys/net/core/wmem_max")));
776 } else {
777 LOG(WARNING) << "/proc/sys/net/core/wmem_max doesn't exist. Are you in a "
778 "container?";
779 return 212992;
780 }
781}
782
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800783} // namespace message_bridge
784} // namespace aos