1 /*
2 * Copyright 2021 The Netty Project
3 *
4 * The Netty Project licenses this file to you under the Apache License,
5 * version 2.0 (the "License"); you may not use this file except in compliance
6 * with the License. You may obtain a copy of the License at:
7 *
8 * https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16 package io.netty.handler.codec.quic;
17
18 import java.net.InetSocketAddress;
19 import java.nio.ByteBuffer;
20
21
22 /**
23 * Utility class to handle access to {@code quiche_recv_info}.
24 */
25 final class QuicheRecvInfo {
26
27 private QuicheRecvInfo() { }
28
29 /**
30 * Set the {@link InetSocketAddress} into the {@code quiche_recv_info} struct.
31 *
32 * <pre>
33 * typedef struct {
34 * struct sockaddr *from;
35 * socklen_t from_len;
36 * struct sockaddr *to;
37 * socklen_t to_len;
38 * } quiche_recv_info;
39 * </pre>
40 *
41 * @param memory the memory of {@code quiche_recv_info}.
42 * @param from the {@link InetSocketAddress} to write into {@code quiche_recv_info}.
43 * @param to the {@link InetSocketAddress} to write into {@code quiche_recv_info}.
44 */
45 static void setRecvInfo(ByteBuffer memory, InetSocketAddress from, InetSocketAddress to) {
46 int position = memory.position();
47 try {
48 setAddress(memory, Quiche.SIZEOF_QUICHE_RECV_INFO, Quiche.QUICHE_RECV_INFO_OFFSETOF_FROM,
49 Quiche.QUICHE_RECV_INFO_OFFSETOF_FROM_LEN, from);
50 setAddress(memory, Quiche.SIZEOF_QUICHE_RECV_INFO + Quiche.SIZEOF_SOCKADDR_STORAGE,
51 Quiche.QUICHE_RECV_INFO_OFFSETOF_TO, Quiche.QUICHE_RECV_INFO_OFFSETOF_TO_LEN, to);
52 } finally {
53 memory.position(position);
54 }
55 }
56
57 private static void setAddress(ByteBuffer memory, int socketAddressOffset, int addrOffset, int lenOffset,
58 InetSocketAddress address) {
59 int position = memory.position();
60 try {
61 int sockaddrPosition = position + socketAddressOffset;
62 memory.position(sockaddrPosition);
63 long sockaddrMemoryAddress = Quiche.memoryAddressWithPosition(memory);
64 int len = SockaddrIn.setAddress(memory, address);
65 if (Quiche.SIZEOF_SIZE_T == 4) {
66 memory.putInt(position + addrOffset, (int) sockaddrMemoryAddress);
67 } else {
68 memory.putLong(position + addrOffset, sockaddrMemoryAddress);
69 }
70 Quiche.setPrimitiveValue(memory, position + lenOffset, Quiche.SIZEOF_SOCKLEN_T, len);
71 } finally {
72 memory.position(position);
73 }
74 }
75 }