aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/java/io/grpc/internal/TransportFrameUtil.java
blob: 879a6c54cee09ea8fc1564f3220cd8e60294f61a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/*
 * Copyright 2014, gRPC Authors All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.grpc.internal;

import static com.google.common.base.Charsets.US_ASCII;

import com.google.common.io.BaseEncoding;
import io.grpc.InternalMetadata;
import io.grpc.Metadata;
import java.util.Arrays;
import java.util.logging.Logger;

/**
 * Utility functions for transport layer framing.
 *
 * <p>Within a given transport frame we reserve the first byte to indicate the type of compression
 * used for the contents of the transport frame.
 */
public final class TransportFrameUtil {

  private static final Logger logger = Logger.getLogger(TransportFrameUtil.class.getName());

  private static final byte[] binaryHeaderSuffixBytes =
      Metadata.BINARY_HEADER_SUFFIX.getBytes(US_ASCII);

  /**
   * Transform the given headers to a format where only spec-compliant ASCII characters are allowed.
   * Binary header values are encoded by Base64 in the result.  It is safe to modify the returned
   * array, but not to modify any of the underlying byte arrays.
   *
   * @return the interleaved keys and values.
   */
  public static byte[][] toHttp2Headers(Metadata headers) {
    byte[][] serializedHeaders = InternalMetadata.serialize(headers);
    // TODO(carl-mastrangelo): eventually remove this once all callers are updated.
    if (serializedHeaders == null) {
      return new byte[][]{};
    }
    int k = 0;
    for (int i = 0; i < serializedHeaders.length; i += 2) {
      byte[] key = serializedHeaders[i];
      byte[] value = serializedHeaders[i + 1];
      if (endsWith(key, binaryHeaderSuffixBytes)) {
        // Binary header.
        serializedHeaders[k] = key;
        serializedHeaders[k + 1] = BaseEncoding.base64().encode(value).getBytes(US_ASCII);
        k += 2;
      } else {
        // Non-binary header.
        // Filter out headers that contain non-spec-compliant ASCII characters.
        // TODO(zhangkun83): only do such check in development mode since it's expensive
        if (isSpecCompliantAscii(value)) {
          serializedHeaders[k] = key;
          serializedHeaders[k + 1] = value;
          k += 2;
        } else {
          String keyString = new String(key, US_ASCII);
          logger.warning("Metadata key=" + keyString + ", value=" + Arrays.toString(value)
              + " contains invalid ASCII characters");
        }
      }
    }
    // Fast path, everything worked out fine.
    if (k == serializedHeaders.length) {
      return serializedHeaders;
    }
    return Arrays.copyOfRange(serializedHeaders, 0, k);
  }

  /**
   * Transform HTTP/2-compliant headers to the raw serialized format which can be deserialized by
   * metadata marshallers. It decodes the Base64-encoded binary headers.  This function modifies
   * the headers in place.  By modifying the input array.
   *
   * @param http2Headers the interleaved keys and values of HTTP/2-compliant headers
   * @return the interleaved keys and values in the raw serialized format
   */
  public static byte[][] toRawSerializedHeaders(byte[][] http2Headers) {
    for (int i = 0; i < http2Headers.length; i += 2) {
      byte[] key = http2Headers[i];
      byte[] value = http2Headers[i + 1];
      http2Headers[i] = key;
      if (endsWith(key, binaryHeaderSuffixBytes)) {
        // Binary header
        http2Headers[i + 1] = BaseEncoding.base64().decode(new String(value, US_ASCII));
      } else {
        // Non-binary header
        // Nothing to do, the value is already in the right place.
      }
    }
    return http2Headers;
  }

  /**
   * Returns {@code true} if {@code subject} ends with {@code suffix}.
   */
  private static boolean endsWith(byte[] subject, byte[] suffix) {
    int start = subject.length - suffix.length;
    if (start < 0) {
      return false;
    }
    for (int i = start; i < subject.length; i++) {
      if (subject[i] != suffix[i - start]) {
        return false;
      }
    }
    return true;
  }

  /**
   * Returns {@code true} if {@code subject} contains only bytes that are spec-compliant ASCII
   * characters and space.
   */
  private static boolean isSpecCompliantAscii(byte[] subject) {
    for (byte b : subject) {
      if (b < 32 || b > 126) {
        return false;
      }
    }
    return true;
  }

  private TransportFrameUtil() {}
}