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