View Javadoc
1   /*
2    * Copyright 2020 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.haproxy;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.channel.ChannelHandler.Sharable;
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.handler.codec.EncoderException;
22  import io.netty.handler.codec.MessageToByteEncoder;
23  import io.netty.util.CharsetUtil;
24  import io.netty.util.NetUtil;
25  
26  import java.util.List;
27  
28  import static io.netty.handler.codec.haproxy.HAProxyConstants.*;
29  
30  /**
31   * Encodes an HAProxy proxy protocol message
32   *
33   * @see <a href="https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt">Proxy Protocol Specification</a>
34   */
35  @Sharable
36  public final class HAProxyMessageEncoder extends MessageToByteEncoder<HAProxyMessage> {
37  
38      private static final int V2_VERSION_BITMASK = 0x02 << 4;
39  
40      // Length for source/destination addresses for the UNIX family must be 108 bytes each.
41      static final int UNIX_ADDRESS_BYTES_LENGTH = 108;
42      static final int TOTAL_UNIX_ADDRESS_BYTES_LENGTH = UNIX_ADDRESS_BYTES_LENGTH * 2;
43  
44      // The v2 header carries the length of the address and TLV section in 16 bits.
45      private static final int V2_MAX_ADDRESS_AND_TLV_BYTES_LENGTH = 65535;
46  
47      public static final HAProxyMessageEncoder INSTANCE = new HAProxyMessageEncoder();
48  
49      private HAProxyMessageEncoder() {
50          super(HAProxyMessage.class);
51      }
52  
53      @Override
54      protected void encode(ChannelHandlerContext ctx, HAProxyMessage msg, ByteBuf out) throws Exception {
55          switch (msg.protocolVersion()) {
56              case V1:
57                  encodeV1(msg, out);
58                  break;
59              case V2:
60                  encodeV2(msg, out);
61                  break;
62              default:
63                  throw new HAProxyProtocolException("Unsupported version: " + msg.protocolVersion());
64          }
65      }
66  
67      private static void encodeV1(HAProxyMessage msg, ByteBuf out) {
68          out.writeBytes(TEXT_PREFIX);
69          out.writeByte((byte) ' ');
70          out.writeCharSequence(msg.proxiedProtocol().name(), CharsetUtil.US_ASCII);
71          // "PROXY UNKNOWN" has no addresses and ports
72          if (msg.proxiedProtocol() != HAProxyProxiedProtocol.UNKNOWN) {
73              out.writeByte((byte) ' ');
74              out.writeCharSequence(msg.sourceAddress(), CharsetUtil.US_ASCII);
75              out.writeByte((byte) ' ');
76              out.writeCharSequence(msg.destinationAddress(), CharsetUtil.US_ASCII);
77              out.writeByte((byte) ' ');
78              out.writeCharSequence(String.valueOf(msg.sourcePort()), CharsetUtil.US_ASCII);
79              out.writeByte((byte) ' ');
80              out.writeCharSequence(String.valueOf(msg.destinationPort()), CharsetUtil.US_ASCII);
81          }
82          out.writeByte((byte) '\r');
83          out.writeByte((byte) '\n');
84      }
85  
86      private static void encodeV2(HAProxyMessage msg, ByteBuf out) {
87          out.writeBytes(BINARY_PREFIX);
88          out.writeByte(V2_VERSION_BITMASK | msg.command().byteValue());
89          out.writeByte(msg.proxiedProtocol().byteValue());
90  
91          switch (msg.proxiedProtocol().addressFamily()) {
92              case AF_IPv4:
93              case AF_IPv6:
94                  byte[] srcAddrBytes = NetUtil.createByteArrayFromIpAddressString(msg.sourceAddress());
95                  byte[] dstAddrBytes = NetUtil.createByteArrayFromIpAddressString(msg.destinationAddress());
96                  // srcAddrLen + dstAddrLen + 4 (srcPort + dstPort) + numTlvBytes
97                  out.writeShort(checkV2Length(srcAddrBytes.length + dstAddrBytes.length + 4 + msg.tlvNumBytes()));
98                  out.writeBytes(srcAddrBytes);
99                  out.writeBytes(dstAddrBytes);
100                 out.writeShort(msg.sourcePort());
101                 out.writeShort(msg.destinationPort());
102                 encodeTlvs(msg.tlvs(), out);
103                 break;
104             case AF_UNIX:
105                 out.writeShort(checkV2Length(TOTAL_UNIX_ADDRESS_BYTES_LENGTH + msg.tlvNumBytes()));
106                 int srcAddrBytesWritten = out.writeCharSequence(msg.sourceAddress(), CharsetUtil.US_ASCII);
107                 out.writeZero(UNIX_ADDRESS_BYTES_LENGTH - srcAddrBytesWritten);
108                 int dstAddrBytesWritten = out.writeCharSequence(msg.destinationAddress(), CharsetUtil.US_ASCII);
109                 out.writeZero(UNIX_ADDRESS_BYTES_LENGTH - dstAddrBytesWritten);
110                 encodeTlvs(msg.tlvs(), out);
111                 break;
112             case AF_UNSPEC:
113                 out.writeShort(0);
114                 break;
115             default:
116                 throw new HAProxyProtocolException("unexpected addrFamily");
117         }
118     }
119 
120     /**
121      * Every TLV is part of the address and TLV section, so bounding the section length also bounds the
122      * 16-bit length of each (nested) TLV.
123      */
124     private static int checkV2Length(int length) {
125         if (length > V2_MAX_ADDRESS_AND_TLV_BYTES_LENGTH) {
126             throw new EncoderException("address and TLV section too long: " + length +
127                     " (expected: <= " + V2_MAX_ADDRESS_AND_TLV_BYTES_LENGTH + ')');
128         }
129         return length;
130     }
131 
132     private static void encodeTlv(HAProxyTLV haProxyTLV, ByteBuf out) {
133         if (haProxyTLV instanceof HAProxySSLTLV) {
134             HAProxySSLTLV ssltlv = (HAProxySSLTLV) haProxyTLV;
135             out.writeByte(haProxyTLV.typeByteValue());
136             out.writeShort(ssltlv.contentNumBytes());
137             out.writeByte(ssltlv.client());
138             out.writeInt(ssltlv.verify());
139             encodeChildTlvs(ssltlv.encapsulatedTLVs(), out);
140         } else {
141             out.writeByte(haProxyTLV.typeByteValue());
142             ByteBuf value = haProxyTLV.content();
143             int readableBytes = value.readableBytes();
144             out.writeShort(readableBytes);
145             // Do not use readSlice(...) (or similar) here as it would mutate the reader index of the
146             // content, which is observable by the caller (e.g. HAProxyMessage.tlvs() exposes the same
147             // TLV instance both as a top-level entry and, if it is a direct child of a PP2_TYPE_SSL TLV,
148             // flattened into the top-level list) and could result in the same TLV being encoded
149             // correctly the first time and as empty content thereafter.
150             out.writeBytes(value, value.readerIndex(), readableBytes);
151         }
152     }
153 
154     /**
155      * Encodes a genuine tree of encapsulated TLVs, e.g. the direct children of a {@link HAProxySSLTLV}.
156      * Unlike {@link HAProxyMessage#tlvs()}, this list is not a flattened view, so every element must be
157      * encoded.
158      */
159     private static void encodeChildTlvs(List<HAProxyTLV> haProxyTLVs, ByteBuf out) {
160         for (int i = 0; i < haProxyTLVs.size(); i++) {
161             encodeTlv(haProxyTLVs.get(i), out);
162         }
163     }
164 
165     /**
166      * Encodes the top-level TLV list as returned by {@link HAProxyMessage#tlvs()}. That list flattens the
167      * direct children of any {@link HAProxySSLTLV} into it for convenience, so those flattened entries must
168      * be skipped here: they are already encoded (recursively) as part of their parent
169      * {@link HAProxySSLTLV}. Encoding them again would both duplicate their bytes on the wire and make the
170      * declared TLV length (see {@link HAProxyMessage#tlvNumBytes()}) not match the number of bytes actually
171      * written.
172      */
173     private static void encodeTlvs(List<HAProxyTLV> haProxyTLVs, ByteBuf out) {
174         for (int i = 0; i < haProxyTLVs.size(); i += 1 + HAProxyMessage.flattenedChildren(haProxyTLVs, i)) {
175             encodeTlv(haProxyTLVs.get(i), out);
176         }
177     }
178 }